@iworkforces/tracelattice 2.1.1 → 2.2.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.
Files changed (129) hide show
  1. package/README.md +20 -3
  2. package/dist/contracts/PersistenceBackend.d.ts +10 -1
  3. package/dist/contracts/PersistenceBackend.d.ts.map +1 -1
  4. package/dist/contracts/calibrator.d.ts +9 -6
  5. package/dist/contracts/calibrator.d.ts.map +1 -1
  6. package/dist/contracts/interfaces.d.ts +6 -0
  7. package/dist/contracts/interfaces.d.ts.map +1 -1
  8. package/dist/contracts/persistence-work.d.ts +13 -1
  9. package/dist/contracts/persistence-work.d.ts.map +1 -1
  10. package/dist/contracts/strategy.d.ts +14 -9
  11. package/dist/contracts/strategy.d.ts.map +1 -1
  12. package/dist/core/DurableThoughtIdentityIndex.d.ts +35 -0
  13. package/dist/core/DurableThoughtIdentityIndex.d.ts.map +1 -0
  14. package/dist/core/DurableThoughtIdentityIndex.js +94 -0
  15. package/dist/core/DurableThoughtIdentityIndex.js.map +1 -0
  16. package/dist/core/HistoryManager.d.ts +5 -0
  17. package/dist/core/HistoryManager.d.ts.map +1 -1
  18. package/dist/core/HistoryManager.js +37 -4
  19. package/dist/core/HistoryManager.js.map +1 -1
  20. package/dist/core/IHistoryManager.d.ts +2 -0
  21. package/dist/core/IHistoryManager.d.ts.map +1 -1
  22. package/dist/core/PersistenceBuffer.d.ts +7 -1
  23. package/dist/core/PersistenceBuffer.d.ts.map +1 -1
  24. package/dist/core/PersistenceBuffer.js +13 -1
  25. package/dist/core/PersistenceBuffer.js.map +1 -1
  26. package/dist/core/PersistenceRestore.d.ts.map +1 -1
  27. package/dist/core/PersistenceRestore.js +11 -3
  28. package/dist/core/PersistenceRestore.js.map +1 -1
  29. package/dist/core/PersistenceWorkQueue.d.ts +13 -1
  30. package/dist/core/PersistenceWorkQueue.d.ts.map +1 -1
  31. package/dist/core/PersistenceWorkQueue.js +86 -11
  32. package/dist/core/PersistenceWorkQueue.js.map +1 -1
  33. package/dist/core/PersistenceWriter.d.ts.map +1 -1
  34. package/dist/core/PersistenceWriter.js +3 -0
  35. package/dist/core/PersistenceWriter.js.map +1 -1
  36. package/dist/core/ThoughtEvaluator.d.ts +7 -4
  37. package/dist/core/ThoughtEvaluator.d.ts.map +1 -1
  38. package/dist/core/ThoughtEvaluator.js +15 -7
  39. package/dist/core/ThoughtEvaluator.js.map +1 -1
  40. package/dist/core/ThoughtProcessor.d.ts.map +1 -1
  41. package/dist/core/ThoughtProcessor.js +19 -7
  42. package/dist/core/ThoughtProcessor.js.map +1 -1
  43. package/dist/core/ThoughtReferenceIndex.d.ts +4 -0
  44. package/dist/core/ThoughtReferenceIndex.d.ts.map +1 -1
  45. package/dist/core/ThoughtReferenceIndex.js +28 -1
  46. package/dist/core/ThoughtReferenceIndex.js.map +1 -1
  47. package/dist/core/VerificationOutcomeAdmission.d.ts +8 -1
  48. package/dist/core/VerificationOutcomeAdmission.d.ts.map +1 -1
  49. package/dist/core/VerificationOutcomeAdmission.js.map +1 -1
  50. package/dist/core/VerificationTargetRestore.d.ts +5 -0
  51. package/dist/core/VerificationTargetRestore.d.ts.map +1 -0
  52. package/dist/core/VerificationTargetRestore.js +61 -0
  53. package/dist/core/VerificationTargetRestore.js.map +1 -0
  54. package/dist/core/evaluator/Aggregator.d.ts +2 -1
  55. package/dist/core/evaluator/Aggregator.d.ts.map +1 -1
  56. package/dist/core/evaluator/Aggregator.js +4 -12
  57. package/dist/core/evaluator/Aggregator.js.map +1 -1
  58. package/dist/core/evaluator/Calibrator.d.ts +13 -9
  59. package/dist/core/evaluator/Calibrator.d.ts.map +1 -1
  60. package/dist/core/evaluator/Calibrator.js +25 -11
  61. package/dist/core/evaluator/Calibrator.js.map +1 -1
  62. package/dist/core/evaluator/PatternDetector.d.ts +2 -1
  63. package/dist/core/evaluator/PatternDetector.d.ts.map +1 -1
  64. package/dist/core/evaluator/PatternDetector.js +13 -12
  65. package/dist/core/evaluator/PatternDetector.js.map +1 -1
  66. package/dist/core/evaluator/SignalComputer.d.ts +3 -2
  67. package/dist/core/evaluator/SignalComputer.d.ts.map +1 -1
  68. package/dist/core/evaluator/SignalComputer.js +4 -9
  69. package/dist/core/evaluator/SignalComputer.js.map +1 -1
  70. package/dist/core/evaluator/VerificationLinks.d.ts +19 -0
  71. package/dist/core/evaluator/VerificationLinks.d.ts.map +1 -0
  72. package/dist/core/evaluator/VerificationLinks.js +113 -0
  73. package/dist/core/evaluator/VerificationLinks.js.map +1 -0
  74. package/dist/core/evaluator/calibration-math.d.ts +12 -2
  75. package/dist/core/evaluator/calibration-math.d.ts.map +1 -1
  76. package/dist/core/evaluator/calibration-math.js +11 -2
  77. package/dist/core/evaluator/calibration-math.js.map +1 -1
  78. package/dist/core/graph/EdgeEmitter.d.ts.map +1 -1
  79. package/dist/core/graph/EdgeEmitter.js +2 -1
  80. package/dist/core/graph/EdgeEmitter.js.map +1 -1
  81. package/dist/core/graph/GraphView.d.ts +5 -5
  82. package/dist/core/graph/GraphView.d.ts.map +1 -1
  83. package/dist/core/graph/GraphView.js +11 -11
  84. package/dist/core/graph/GraphView.js.map +1 -1
  85. package/dist/core/reasoning/ActiveEvidenceProjection.d.ts +20 -0
  86. package/dist/core/reasoning/ActiveEvidenceProjection.d.ts.map +1 -0
  87. package/dist/core/reasoning/ActiveEvidenceProjection.js +100 -0
  88. package/dist/core/reasoning/ActiveEvidenceProjection.js.map +1 -0
  89. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts +5 -4
  90. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts.map +1 -1
  91. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js +24 -14
  92. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js.map +1 -1
  93. package/dist/lib.d.ts.map +1 -1
  94. package/dist/lib.js +3 -1
  95. package/dist/lib.js.map +1 -1
  96. package/dist/persistence/BacktrackPersistence.d.ts +13 -0
  97. package/dist/persistence/BacktrackPersistence.d.ts.map +1 -0
  98. package/dist/persistence/BacktrackPersistence.js +90 -0
  99. package/dist/persistence/BacktrackPersistence.js.map +1 -0
  100. package/dist/persistence/FilePersistence.d.ts +2 -1
  101. package/dist/persistence/FilePersistence.d.ts.map +1 -1
  102. package/dist/persistence/FilePersistence.js +28 -0
  103. package/dist/persistence/FilePersistence.js.map +1 -1
  104. package/dist/persistence/FileSnapshotV2.d.ts +2 -0
  105. package/dist/persistence/FileSnapshotV2.d.ts.map +1 -1
  106. package/dist/persistence/FileSnapshotV2.js +6 -2
  107. package/dist/persistence/FileSnapshotV2.js.map +1 -1
  108. package/dist/persistence/MemoryPersistence.d.ts +2 -1
  109. package/dist/persistence/MemoryPersistence.d.ts.map +1 -1
  110. package/dist/persistence/MemoryPersistence.js +21 -1
  111. package/dist/persistence/MemoryPersistence.js.map +1 -1
  112. package/dist/persistence/PersistenceCodec.d.ts.map +1 -1
  113. package/dist/persistence/PersistenceCodec.js +5 -0
  114. package/dist/persistence/PersistenceCodec.js.map +1 -1
  115. package/dist/persistence/PersistenceErrors.d.ts +1 -1
  116. package/dist/persistence/PersistenceErrors.d.ts.map +1 -1
  117. package/dist/persistence/PersistenceErrors.js.map +1 -1
  118. package/dist/persistence/PersistenceScope.d.ts +1 -1
  119. package/dist/persistence/PersistenceScope.d.ts.map +1 -1
  120. package/dist/persistence/PersistenceScope.js.map +1 -1
  121. package/dist/persistence/SqlitePersistence.d.ts +2 -1
  122. package/dist/persistence/SqlitePersistence.d.ts.map +1 -1
  123. package/dist/persistence/SqlitePersistence.js +18 -0
  124. package/dist/persistence/SqlitePersistence.js.map +1 -1
  125. package/dist/registry/BaseRegistry.d.ts +10 -2
  126. package/dist/registry/BaseRegistry.d.ts.map +1 -1
  127. package/dist/registry/BaseRegistry.js +128 -81
  128. package/dist/registry/BaseRegistry.js.map +1 -1
  129. package/package.json +4 -3
@@ -1 +1 @@
1
- {"version":3,"file":"core/ThoughtProcessor.js","sources":["../../src/core/ThoughtProcessor.ts"],"sourcesContent":["/**\n * Core thought processing logic and validation.\n *\n * This module provides the `ThoughtProcessor` class which handles the main\n * sequential thinking request processing pipeline, including input validation,\n * history management, and response formatting.\n *\n * @module processor\n */\n\nimport * as v from 'valibot';\n\nimport { NullLogger } from '../logger/NullLogger.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport {\n\tasBranchId,\n\tasSessionId,\n\ttype BranchId,\n\ttype SessionId,\n\ttype ThoughtId,\n} from '../contracts/ids.js';\nimport type { IEdgeStore, IOutcomeRecorder } from '../contracts/interfaces.js';\nimport type { ICalibrator } from '../contracts/calibrator.js';\nimport type { ISuspensionStore, SuspensionRecord } from '../contracts/suspension.js';\nimport type { IReasoningStrategy, StrategyDecision } from '../contracts/strategy.js';\nimport { DEFAULT_FLAGS, type FeatureFlags } from '../contracts/features.js';\nimport type { ISessionLock, IToolRegistry } from '../contracts/interfaces.js';\nimport {\n\tInvalidBacktrackError,\n\tInvalidToolCallError,\n\tSequentialThinkingError,\n\tUnknownToolError,\n\tValidationError,\n} from '../errors.js';\nimport { getErrorMessage, WARNING_CODES } from '../errors.js';\nimport { enforceJsonShape, JsonShapeError } from '../sanitize.js';\nimport { SequentialThinkingSchema } from '../schema.js';\nimport { GraphView } from './graph/GraphView.js';\nimport { assertNever } from '../utils.js';\nimport type {\n\tHistorySessionSnapshot,\n\tIHistoryManager,\n\tThoughtAdmissionContext,\n} from './IHistoryManager.js';\nimport { normalizeInput } from './InputNormalizer.js';\nimport type {\n\tThoughtData,\n\tToolCallThought,\n\tToolObservationThought,\n\tValidatedThought,\n} from './thought.js';\nimport type { ThoughtEvaluator } from './ThoughtEvaluator.js';\nimport type { ThoughtFormatter } from './ThoughtFormatter.js';\nimport type { PatternName } from '../contracts/reasoning-types.js';\nimport type { PatternSignal } from './reasoning.js';\nimport { SequentialStrategy } from './reasoning/strategies/SequentialStrategy.js';\nimport type { CompressionService } from './compression/CompressionService.js';\nimport { validateThoughtCrossReferences } from './CrossReferenceValidator.js';\nimport { SessionLifecycleCoordinator } from './SessionLifecycleCoordinator.js';\nimport { prepareVerificationOutcome } from './VerificationOutcomeAdmission.js';\n\ntype ConfidenceSignalsResult = ReturnType<ThoughtEvaluator['computeConfidenceSignals']>;\ntype ReasoningStatsResult = ReturnType<ThoughtEvaluator['computeReasoningStats']>;\n\ntype ReasoningSignalBundle = {\n\treadonly history: ThoughtData[];\n\treadonly confidenceSignals: ConfidenceSignalsResult;\n\treadonly reasoningStats: ReasoningStatsResult;\n\treadonly reasoningHints: readonly string[];\n};\n\ntype ProcessedThoughtResponseState = {\n\treadonly thought: ThoughtData;\n\treadonly reasoning: {\n\t\treadonly confidenceSignals: ConfidenceSignalsResult;\n\t\treadonly reasoningStats: ReasoningStatsResult;\n\t\treadonly reasoningHints: readonly string[];\n\t};\n\treadonly decision: StrategyDecision | undefined;\n\treadonly warnings: readonly string[];\n};\n\ntype ThoughtProcessInput = ThoughtData & { readonly register_branch_id?: string };\n\ntype PreparedThought = {\n\treadonly thought: ThoughtData;\n\treadonly resetState: boolean;\n\treadonly registerBranchId: BranchId | undefined;\n\treadonly validationWarnings: readonly string[];\n};\n\n/**\n * The return type expected by MCP tool invocations.\n *\n * This structure matches the MCP protocol for tool results,\n * supporting both success and error responses.\n *\n * @example\n * ```typescript\n * const successResult: CallToolResult = {\n * content: [{ type: 'text', text: '{\"status\":\"success\"}' }]\n * };\n *\n * const errorResult: CallToolResult = {\n * content: [{ type: 'text', text: '{\"error\":\"Something went wrong\"}' }],\n * isError: true\n * };\n * ```\n */\nexport interface CallToolResult extends Record<string, unknown> {\n\t/** Array of content blocks (typically text) to return to the client. */\n\tcontent: Array<{\n\t\ttype: 'text';\n\t\ttext: string;\n\t}>;\n\n\t/** Whether this result represents an error condition. */\n\tisError?: boolean;\n}\n\n/**\n * Core processor for sequential thinking requests.\n *\n * Pipeline: validate → normalize → add to history → format → evaluate signals\n * → run reasoning strategy → return structured response.\n *\n * Auto-adjusts `total_thoughts` if `thought_number` exceeds it. All errors are\n * caught and returned as formatted error responses with `isError: true`.\n *\n * @example\n * ```typescript\n * const processor = new ThoughtProcessor(historyManager, formatter, new ThoughtEvaluator());\n * const result = await processor.process({\n * thought: '...',\n * thought_number: 1,\n * total_thoughts: 5,\n * next_thought_needed: true,\n * session_id: asSessionId('analysis')\n * });\n * ```\n */\nexport class ThoughtProcessor {\n\t/** Logger for debugging and monitoring. */\n\tprivate _logger: Logger;\n\n\t/** Evaluator for quality signal computation. */\n\tprivate readonly _thoughtEvaluator: ThoughtEvaluator;\n\n\t/**\n\t * Per-session cooldown tracker: session_id → pattern → last_fired_thought_number.\n\t * Prevents re-firing the same pattern hint within 3 thoughts.\n\t */\n\tprivate _hintCooldowns = new Map<SessionId, Map<PatternName, number>>();\n\n\t/**\n\t * Creates a new ThoughtProcessor instance.\n\t *\n\t * @param historyManager - History manager for storing thoughts\n\t * @param thoughtFormatter - Formatter for output formatting\n\t * @param thoughtEvaluator - Evaluator for quality signal computation\n\t * @param logger - Optional logger for diagnostics (defaults to NullLogger)\n\t * @param strategy - Reasoning strategy controlling next-action decisions (defaults to SequentialStrategy)\n\t * @param compressionService - Optional compression service for auto-compression on terminate\n\t * @param suspensionStore - Optional suspension store enabling tool interleave\n\t * @param toolRegistry - Optional tool registry for tool_name allowlist validation (required when toolInterleave is enabled)\n\t * @param features - Optional feature flags (defaults to DEFAULT_FLAGS — all opt-in flags off)\n\t * @param sessionLock - Optional per-session async lock; when provided, `process()` runs under it\n\t * @param outcomeRecorder - Optional per-session calibration outcome store\n\t */\n\tconstructor(\n\t\tprivate historyManager: IHistoryManager,\n\t\tprivate thoughtFormatter: ThoughtFormatter,\n\t\tthoughtEvaluator: ThoughtEvaluator,\n\t\tlogger?: Logger,\n\t\tprivate readonly strategy: IReasoningStrategy = new SequentialStrategy(),\n\t\tprivate readonly _compressionService?: CompressionService,\n\t\tprivate readonly _suspensionStore?: ISuspensionStore,\n\t\tprivate readonly _toolRegistry?: IToolRegistry,\n\t\tprivate readonly _features: FeatureFlags = DEFAULT_FLAGS,\n\t\tprivate readonly _sessionLock?: ISessionLock,\n\t\tprivate readonly _outcomeRecorder?: IOutcomeRecorder,\n\t\tprivate readonly _lifecycle: SessionLifecycleCoordinator = new SessionLifecycleCoordinator(),\n\t\tprivate readonly _calibrator?: ICalibrator\n\t) {\n\t\tthis._thoughtEvaluator = thoughtEvaluator;\n\t\tthis._logger = logger ?? new NullLogger();\n\t}\n\n\t/**\n\t * Internal logging method.\n\t * @param message - The message to log\n\t * @param meta - Optional metadata\n\t * @private\n\t */\n\tprivate log(message: string, meta?: Record<string, unknown>): void {\n\t\tthis._logger.info(message, meta);\n\t}\n\n\t/**\n\t * Priority ordering for warning patterns (lower = higher priority).\n\t * Ensures the most actionable patterns fill the hint cap first.\n\t */\n\tprivate static readonly _HINT_PRIORITY: Readonly<Partial<Record<PatternName, number>>> = {\n\t\tconfidence_drift: 1, // Most actionable — degrading confidence\n\t\tunverified_hypothesis: 2, // Important for quality\n\t\tno_alternatives_explored: 3, // Breadth gap\n\t\tconsecutive_without_verification: 4, // Routine pattern\n\t};\n\n\t/**\n\t * Generate actionable hints from pattern signals.\n\t * Rules: max 3 hints, warning-severity only, cooldown of 3 thoughts per pattern per session.\n\t *\n\t * Warning patterns are sorted by priority before selection (see _HINT_PRIORITY).\n\t * Higher-priority patterns (lower number) fill the hint cap first.\n\t *\n\t * @param patterns - Detected pattern signals\n\t * @param currentThoughtNumber - The current thought number being processed\n\t * @param sessionId - Session identifier for cooldown scoping\n\t * @returns Array of hint strings (max 3), empty if no warnings\n\t */\n\tprivate _generateHints(\n\t\tpatterns: PatternSignal[],\n\t\tcurrentThoughtNumber: number,\n\t\tsessionId: SessionId\n\t): string[] {\n\t\tconst warnings = patterns.filter((p) => p.severity === 'warning');\n\t\tif (warnings.length === 0) return [];\n\n\t\t// Sort by priority (lower number = higher priority)\n\t\twarnings.sort((a, b) => {\n\t\t\tconst pa = ThoughtProcessor._HINT_PRIORITY[a.pattern] ?? 99;\n\t\t\tconst pb = ThoughtProcessor._HINT_PRIORITY[b.pattern] ?? 99;\n\t\t\treturn pa - pb;\n\t\t});\n\n\t\tlet cooldowns = this._hintCooldowns.get(sessionId);\n\t\tif (cooldowns === undefined) {\n\t\t\tcooldowns = new Map();\n\t\t\tthis._hintCooldowns.set(sessionId, cooldowns);\n\t\t}\n\n\t\tconst hints: string[] = [];\n\t\tfor (const warning of warnings) {\n\t\t\tif (hints.length >= 3) break;\n\n\t\t\tconst lastFired = cooldowns.get(warning.pattern);\n\t\t\tif (lastFired !== undefined && currentThoughtNumber - lastFired < 3) {\n\t\t\t\tcontinue; // Still in cooldown\n\t\t\t}\n\n\t\t\thints.push(warning.message);\n\t\t\tcooldowns.set(warning.pattern, currentThoughtNumber);\n\t\t}\n\n\t\treturn hints;\n\t}\n\n\t/**\n\t * Processes a thought through the sequential thinking pipeline.\n\t *\n\t * This method validates the input, adds it to history, formats the output,\n\t * computes quality signals via the ThoughtEvaluator, and returns\n\t * a structured response with metadata about the current state.\n\t *\n\t * @param input - The thought data to process\n\t * @returns A Promise resolving to the formatted tool result containing:\n\t * - `thought_number` — Current thought index\n\t * - `total_thoughts` — Estimated total thoughts\n\t * - `next_thought_needed` — Whether to continue\n\t * - `branches` — Active branch IDs\n\t * - `thought_history_length` — Number of thoughts in history\n\t * - `available_mcp_tools` — MCP tools available for recommendation\n\t * - `available_skills` — Skills available for recommendation\n\t * - `current_step` — Current step recommendation\n\t * - `previous_steps` — Previously recommended steps\n\t * - `remaining_steps` — Upcoming step descriptions\n\t * - `thought_type` — Classification of thought purpose (optional)\n\t * - `quality_score` — Self-assessed quality score 0-1 (optional)\n\t * - `confidence` — Self-assessed confidence 0-1 (optional)\n\t * - `hypothesis_id` — Hypothesis link for verification chains (optional)\n\t * - `confidence_signals` — Computed reasoning quality signals (includes structural_quality and quality_components)\n\t * - `reasoning_stats` — Aggregated reasoning analytics\n\t * - `reasoning_hints` — (Conditional) Actionable hints from pattern analysis, max 3, warning-severity only (optional)\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await processor.process({\n\t * thought: 'I should read the README file',\n\t * thought_number: 1,\n\t * total_thoughts: 3,\n\t * next_thought_needed: true,\n\t * session_id: asSessionId('analysis')\n\t * });\n\t *\n\t * console.log(result.content[0].text);\n\t * // Output includes: thought_number, total_thoughts, next_thought_needed,\n\t * // branches, thought_history_length, and any recommendations\n\t * ```\n\t */\n\tpublic async process(input: ThoughtProcessInput): Promise<CallToolResult> {\n\t\ttry {\n\t\t\tconst prepared = this._prepareInput(input);\n\t\t\tconst sessionId = prepared.thought.session_id;\n\t\t\tconst operation = async (): Promise<CallToolResult> => {\n\t\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\t\treturn await this._sessionLock.withLock(sessionId, () => this._processInner(prepared));\n\t\t\t\t}\n\t\t\t\treturn await this._processInner(prepared);\n\t\t\t};\n\t\t\tif (prepared.resetState) {\n\t\t\t\tthis.historyManager.inspectSession(sessionId);\n\t\t\t\treturn await this._lifecycle.withSessionReset(sessionId, operation);\n\t\t\t}\n\t\t\treturn await this._lifecycle.runOperation(sessionId, operation);\n\t\t} catch (error) {\n\t\t\treturn this._buildErrorResponse(error);\n\t\t}\n\t}\n\n\t/** Resets one canonical session and its processor-owned auxiliary state. */\n\tpublic async resetSession(sessionId: string): Promise<void> {\n\t\tconst canonicalSessionId = asSessionId(sessionId);\n\t\tthis.historyManager.inspectSession(canonicalSessionId);\n\t\tconst operation = async (): Promise<void> => {\n\t\t\tawait this.historyManager.resetSessionWithinExclusive(canonicalSessionId, () =>\n\t\t\t\tthis.clearSessionAuxiliaryState(canonicalSessionId)\n\t\t\t);\n\t\t};\n\t\tawait this._lifecycle.withSessionReset(canonicalSessionId, async () => {\n\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\tawait this._sessionLock.withLock(canonicalSessionId, operation);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait operation();\n\t\t});\n\t}\n\n\t/** Resets all history and processor-owned auxiliary state from a trusted context. */\n\tpublic async resetAll(): Promise<void> {\n\t\tawait this._lifecycle.withGlobalReset(\n\t\t\tasync () =>\n\t\t\t\tawait this.historyManager.resetAllWithinExclusive(() => this.clearAllAuxiliaryState())\n\t\t);\n\t}\n\n\tprivate _prepareInput(input: ThoughtProcessInput): PreparedThought {\n\t\tconst normalized = normalizeInput(input);\n\t\tif (typeof normalized === 'object' && normalized !== null) {\n\t\t\tthis._validateToolArgumentsShape(normalized.tool_arguments);\n\t\t}\n\t\tconst parsed = v.safeParse(SequentialThinkingSchema, normalized);\n\t\tif (!parsed.success) {\n\t\t\tconst firstIssue = parsed.issues[0];\n\t\t\tconst field = firstIssue?.path?.map((item) => String(item.key)).join('.') || 'input';\n\t\t\tthrow new ValidationError(field, firstIssue?.message ?? 'Invalid input');\n\t\t}\n\n\t\tconst internal = normalizeInput(parsed.output) as ThoughtData & {\n\t\t\tregister_branch_id?: string;\n\t\t};\n\t\tconst registerBranchId =\n\t\t\tinternal.register_branch_id === undefined\n\t\t\t\t? undefined\n\t\t\t\t: asBranchId(internal.register_branch_id);\n\t\tconst thought = { ...internal };\n\t\tdelete thought.register_branch_id;\n\t\tconst { result, warnings } = this.validateInput(thought);\n\t\tthis._validateStatelessNewTypes(result);\n\t\treturn {\n\t\t\tthought: result,\n\t\t\tresetState: result.reset_state === true,\n\t\t\tregisterBranchId,\n\t\t\tvalidationWarnings: warnings,\n\t\t};\n\t}\n\n\tprivate _buildErrorResponse(error: unknown): CallToolResult {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...(error instanceof SequentialThinkingError && { code: error.code }),\n\t\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t\t\tmessage: getErrorMessage(error),\n\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\tprivate static _emptySessionSnapshot(): HistorySessionSnapshot {\n\t\treturn {\n\t\t\thistory: [],\n\t\t\tbranches: {},\n\t\t\tbranchIds: [],\n\t\t\tavailableMcpTools: undefined,\n\t\t\tavailableSkills: undefined,\n\t\t};\n\t}\n\n\t/** Clears all processor-owned state for one removed session. */\n\tpublic clearSessionAuxiliaryState(sessionId: SessionId): void {\n\t\tthis._hintCooldowns.delete(sessionId);\n\t\tthis._suspensionStore?.clearSession(sessionId);\n\t\tthis._outcomeRecorder?.clearOutcomes(sessionId);\n\t\tthis._calibrator?.clearSession(sessionId);\n\t}\n\n\t/** Clears all processor-owned state after global reset or successful shutdown. */\n\tpublic clearAllAuxiliaryState(): void {\n\t\tthis._suspensionStore?.clearAll();\n\t\tthis._outcomeRecorder?.clearAllOutcomes();\n\t\tthis._calibrator?.clearAll();\n\t\tthis._hintCooldowns.clear();\n\t}\n\n\tprivate _validateToolArgumentsShape(toolArguments: unknown): void {\n\t\ttry {\n\t\t\tenforceJsonShape(toolArguments ?? {});\n\t\t} catch (error) {\n\t\t\tif (error instanceof JsonShapeError) {\n\t\t\t\tthrow new ValidationError('tool_arguments', error.reason);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate async _processInner(prepared: PreparedThought): Promise<CallToolResult> {\n\t\tconst { thought, resetState, registerBranchId } = prepared;\n\t\tconst sessionId = thought.session_id;\n\t\tconst existingSnapshot = this.historyManager.inspectSession(sessionId);\n\t\tconst validationSnapshot = resetState\n\t\t\t? ThoughtProcessor._emptySessionSnapshot()\n\t\t\t: existingSnapshot;\n\t\tif (!resetState) {\n\t\t\tif (!thought.available_mcp_tools && validationSnapshot.availableMcpTools) {\n\t\t\t\tthought.available_mcp_tools = [...validationSnapshot.availableMcpTools];\n\t\t\t}\n\t\t\tif (!thought.available_skills && validationSnapshot.availableSkills) {\n\t\t\t\tthought.available_skills = [...validationSnapshot.availableSkills];\n\t\t\t}\n\t\t}\n\t\tconst resolveThoughtReference = resetState\n\t\t\t? () => ({ kind: 'missing' as const })\n\t\t\t: (thoughtNumber: number) =>\n\t\t\t\t\tthis.historyManager.resolveThoughtReference(sessionId, thoughtNumber);\n\t\tconst {\n\t\t\tresult: checkedInput,\n\t\t\twarnings: refWarnings,\n\t\t\tresolvedReferences,\n\t\t} = validateThoughtCrossReferences(thought, {\n\t\t\tsnapshot: validationSnapshot,\n\t\t\tresolveThoughtReference,\n\t\t\tstrictBranchReferences: resetState || registerBranchId !== undefined,\n\t\t\tlogger: this._logger,\n\t\t});\n\t\tconst verificationOutcome = prepareVerificationOutcome({\n\t\t\tinput: checkedInput,\n\t\t\tsnapshot: validationSnapshot,\n\t\t\tresolvedReferences,\n\t\t\tsessionId,\n\t\t\trecorder: this._outcomeRecorder,\n\t\t});\n\t\tconst allWarnings = [...prepared.validationWarnings, ...refWarnings];\n\t\tconst validated = this._validateNewTypes(checkedInput);\n\t\tconst admissionContext: ThoughtAdmissionContext = { resolvedReferences };\n\t\tif (resetState && validated.thought_type === 'tool_observation') {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t'tool_observation cannot resume a suspension in reset replacement state'\n\t\t\t);\n\t\t}\n\n\t\tif (resetState) {\n\t\t\tawait this.historyManager.resetSessionWithinExclusive(sessionId, () =>\n\t\t\t\tthis.clearSessionAuxiliaryState(sessionId)\n\t\t\t);\n\t\t\tthis.log('State reset for session', { sessionId });\n\t\t}\n\t\tif (registerBranchId !== undefined) {\n\t\t\tthis.historyManager.registerBranch(sessionId, registerBranchId);\n\t\t}\n\n\t\t// Tool-interleave suspend path: persist the tool_call thought, then return\n\t\t// a `suspended` envelope without running strategy/evaluator.\n\t\tif (validated.thought_type === 'tool_call' && this._suspensionStore) {\n\t\t\treturn this._handleToolCall(validated, admissionContext);\n\t\t}\n\n\t\t// Tool-interleave resume path: consume the suspension and continue the\n\t\t// normal pipeline (addThought → format → evaluate → strategy).\n\t\tif (validated.thought_type === 'tool_observation' && this._suspensionStore) {\n\t\t\tawait this._handleToolObservation(validated, admissionContext);\n\t\t} else {\n\t\t\tthis.historyManager.addThought(checkedInput, admissionContext);\n\t\t}\n\t\tthis._recordVerificationOutcome(verificationOutcome, sessionId);\n\n\t\tconst formattedThought = this.thoughtFormatter.formatThought(checkedInput);\n\t\tthis.log(formattedThought, { sessionId });\n\n\t\tconst signals = this._collectReasoningSignals(checkedInput);\n\n\t\t// Strategy decision — pluggable reasoning policy hook.\n\t\t// Built after history/stats so strategies see the latest state.\n\t\tconst decision = this._runStrategy(checkedInput, signals.history, signals.reasoningStats);\n\n\t\treturn this._buildSuccessResponse({\n\t\t\tthought: checkedInput,\n\t\t\treasoning: {\n\t\t\t\tconfidenceSignals: signals.confidenceSignals,\n\t\t\t\treasoningStats: signals.reasoningStats,\n\t\t\t\treasoningHints: signals.reasoningHints,\n\t\t\t},\n\t\t\tdecision,\n\t\t\twarnings: allWarnings,\n\t\t});\n\t}\n\n\tprivate _recordVerificationOutcome(\n\t\toutcome: ReturnType<typeof prepareVerificationOutcome>,\n\t\tsessionId: SessionId\n\t): void {\n\t\tif (outcome === undefined) return;\n\t\tif (this._outcomeRecorder?.enabled === true) {\n\t\t\tthis._outcomeRecorder.recordVerification(outcome);\n\t\t}\n\t\tif (this._calibrator?.enabled === true) this._calibrator.refit(sessionId);\n\t}\n\n\tprivate _collectReasoningSignals(input: ThoughtData): ReasoningSignalBundle {\n\t\tconst sessionId = input.session_id;\n\t\tconst history = this.historyManager.getHistory(sessionId);\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst confidenceSignals = this._thoughtEvaluator.computeConfidenceSignals(history, branches, {\n\t\t\tcurrentThought: input,\n\t\t\tsessionId,\n\t\t});\n\t\tconst reasoningStats = this._thoughtEvaluator.computeReasoningStats(history, branches);\n\t\tconst patternSignals = this._thoughtEvaluator.computePatternSignals(history, branches);\n\t\tconst reasoningHints = this._generateHints(patternSignals, input.thought_number, sessionId);\n\n\t\treturn {\n\t\t\thistory,\n\t\t\tconfidenceSignals,\n\t\t\treasoningStats,\n\t\t\treasoningHints,\n\t\t};\n\t}\n\n\tprivate _buildSuccessResponse(state: ProcessedThoughtResponseState): CallToolResult {\n\t\tconst sessionId = state.thought.session_id;\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthought_number: state.thought.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: state.thought.total_thoughts,\n\t\t\t\t\t\t\tnext_thought_needed: state.thought.next_thought_needed ?? true,\n\t\t\t\t\t\t\tbranches: this.historyManager.getBranchIds(sessionId),\n\t\t\t\t\t\t\tthought_history_length: this.historyManager.getHistoryLength(sessionId),\n\t\t\t\t\t\t\tavailable_mcp_tools: state.thought.available_mcp_tools,\n\t\t\t\t\t\t\tavailable_skills: state.thought.available_skills,\n\t\t\t\t\t\t\tcurrent_step: state.thought.current_step,\n\t\t\t\t\t\t\tprevious_steps: state.thought.previous_steps,\n\t\t\t\t\t\t\tremaining_steps: state.thought.remaining_steps,\n\t\t\t\t\t\t\tthought_type: state.thought.thought_type,\n\t\t\t\t\t\t\tquality_score: state.thought.quality_score,\n\t\t\t\t\t\t\tconfidence: state.thought.confidence,\n\t\t\t\t\t\t\thypothesis_id: state.thought.hypothesis_id,\n\t\t\t\t\t\t\tconfidence_signals: state.reasoning.confidenceSignals,\n\t\t\t\t\t\t\treasoning_stats: state.reasoning.reasoningStats,\n\t\t\t\t\t\t\t...(state.reasoning.reasoningHints.length > 0 && {\n\t\t\t\t\t\t\t\treasoning_hints: state.reasoning.reasoningHints,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(state.decision !== undefined && { strategy_hint: state.decision }),\n\t\t\t\t\t\t\t...(state.warnings.length > 0 && { warnings: state.warnings.slice(0, 3) }),\n\t\t\t\t\t\t\tsession_id: sessionId,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Run the configured reasoning strategy and return its decision.\n\t * Strategy errors omit the decision from the public response.\n\t * @private\n\t */\n\tprivate _runStrategy(\n\t\tcurrentThought: ThoughtData,\n\t\thistory: ThoughtData[],\n\t\tstats: ReturnType<ThoughtEvaluator['computeReasoningStats']>\n\t): StrategyDecision | undefined {\n\t\tconst sessionId = currentThought.session_id;\n\t\tlet decision: StrategyDecision | undefined;\n\t\ttry {\n\t\t\tconst edgeStore = this._getEdgeStore();\n\t\t\tconst graph = edgeStore ? new GraphView(edgeStore) : undefined;\n\t\t\tdecision = this.strategy.decide({\n\t\t\t\tsessionId,\n\t\t\t\thistory,\n\t\t\t\tgraph,\n\t\t\t\tstats,\n\t\t\t\tcurrentThought,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis._logger.warn('Reasoning strategy threw — omitting strategy hint', {\n\t\t\t\tstrategy: this.strategy.name,\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t}\n\n\t\t// Auto-compression trigger: when strategy terminates a branch and\n\t\t// compression is enabled, summarize the branch subtree. Compression\n\t\t// failures must NEVER break the thought pipeline.\n\t\tif (decision?.action === 'terminate' && this._compressionService && currentThought.branch_id) {\n\t\t\ttry {\n\t\t\t\tconst branchRoot = this._findBranchRoot(sessionId, currentThought.branch_id);\n\t\t\t\tif (branchRoot) {\n\t\t\t\t\tthis._compressionService.compressBranch(\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tcurrentThought.branch_id,\n\t\t\t\t\t\tbranchRoot as ThoughtId\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthis._logger.debug('Compression auto-trigger failed', {\n\t\t\t\t\terror: getErrorMessage(err),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn decision;\n\t}\n\n\t/**\n\t * Locate the root thought id for a branch.\n\t * Prefers GraphView.branchThoughts() when an EdgeStore is available;\n\t * falls back to historyManager.getBranches(sessionId)[branchId][0].id.\n\t * @private\n\t */\n\tprivate _findBranchRoot(sessionId: SessionId, branchId: BranchId): string | undefined {\n\t\tconst edgeStore = this._getEdgeStore();\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst branchList = branches[branchId];\n\t\tconst firstId = branchList?.[0]?.id;\n\t\tif (edgeStore && firstId) {\n\t\t\tconst graph = new GraphView(edgeStore);\n\t\t\tconst ids = graph.branchThoughts(sessionId, firstId);\n\t\t\tif (ids.length > 0) return ids[0];\n\t\t}\n\t\treturn firstId;\n\t}\n\n\t/** Access the EdgeStore via IHistoryManager. @private */\n\tprivate _getEdgeStore(): IEdgeStore | undefined {\n\t\treturn this.historyManager.getEdgeStore();\n\t}\n\n\t/**\n\t * Validates and normalizes thought input.\n\t *\n\t * Ensures that thought numbers are consistent and within valid ranges.\n\t * If `thought_number` exceeds `total_thoughts`, `total_thoughts` is\n\t * automatically adjusted to match and a warning is emitted.\n\t *\n\t * @param input - The input to validate\n\t * @returns Object with validated input and any warnings generated\n\t * @private\n\t *\n\t * @example\n\t * ```typescript\n\t * // Auto-adjusts total_thoughts when thought_number exceeds it\n\t * const { result, warnings } = this.validateInput(input);\n\t * // result.total_thoughts === 10 (auto-adjusted from 5)\n\t * // warnings === ['Auto-adjusted total_thoughts from 5 to 10 to match thought_number']\n\t * ```\n\t */\n\tprivate validateInput(input: ThoughtData): {\n\t\tresult: ThoughtData;\n\t\twarnings: string[];\n\t} {\n\t\tconst warnings: string[] = [];\n\t\tif (input.thought_number > input.total_thoughts) {\n\t\t\tconst originalTotal = input.total_thoughts;\n\t\t\twarnings.push(\n\t\t\t\t`[${WARNING_CODES.TOTAL_THOUGHTS_ADJUSTED}] Auto-adjusted total_thoughts from ${originalTotal} to ${input.thought_number} to match thought_number`\n\t\t\t);\n\t\t\tthis._logger.warn('Auto-adjusted total_thoughts to match thought_number', {\n\t\t\t\tthought_number: input.thought_number,\n\t\t\t\toriginal_total_thoughts: originalTotal,\n\t\t\t\tadjusted_total_thoughts: input.thought_number,\n\t\t\t});\n\t\t\tinput.total_thoughts = input.thought_number;\n\t\t}\n\t\treturn { result: input, warnings };\n\t}\n\n\t/**\n\t * Validate new thought-type invariants behind feature flags.\n\t * @private\n\t */\n\tprivate _validateStatelessNewTypes(input: ThoughtData): void {\n\t\tconst t = input.thought_type;\n\t\tif ((t === 'tool_call' || t === 'tool_observation') && !this._features.toolInterleave) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t`Type '${t}' requires the toolInterleave feature flag. Set TRACELATTICE_FEATURES_TOOL_INTERLEAVE=true to enable it.`\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\t(t === 'assumption' || t === 'decomposition' || t === 'backtrack') &&\n\t\t\t!this._features.newThoughtTypes\n\t\t) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t`Type '${t}' requires the newThoughtTypes feature flag. Set TRACELATTICE_FEATURES_NEW_THOUGHT_TYPES=true to enable it, or use '${ThoughtProcessor._getWorkaroundType(t)}' type as a workaround.`\n\t\t\t);\n\t\t}\n\t\tif (t === 'tool_call') {\n\t\t\tif (!input.tool_name) {\n\t\t\t\tthrow new InvalidToolCallError(\n\t\t\t\t\t'tool_call thought ' + input.thought_number + ' missing required tool_name'\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis._validateToolName(input.tool_name);\n\t\t}\n\t\tif (t === 'tool_observation' && !input.continuation_token) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'continuation_token',\n\t\t\t\t'tool_observation thought ' + input.thought_number + ' missing continuation_token'\n\t\t\t);\n\t\t}\n\t\tif (t === 'backtrack') {\n\t\t\tif (input.backtrack_target === undefined) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t'backtrack_target',\n\t\t\t\t\t'backtrack thought ' + input.thought_number + ' requires backtrack_target'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (input.backtrack_target > input.thought_number) {\n\t\t\t\tthrow new InvalidBacktrackError(\n\t\t\t\t\t'backtrack_target ' +\n\t\t\t\t\t\tinput.backtrack_target +\n\t\t\t\t\t\t' must be <= thought_number ' +\n\t\t\t\t\t\tinput.thought_number\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (t === 'tool_call') {\n\t\t\tthis._validateToolArgumentsShape(input.tool_arguments);\n\t\t}\n\t}\n\n\tprivate _validateNewTypes(input: ThoughtData): ValidatedThought {\n\t\treturn input as ValidatedThought;\n\t}\n\n\t/**\n\t * Validate a tool_call's tool_name against the configured allowlist.\n\t *\n\t * Fails closed: if no tool registry was wired, all tool_call invocations are\n\t * rejected. This prevents arbitrary tool name injection through the protocol.\n\t *\n\t * @param toolName - The tool name from the tool_call thought\n\t * @throws {UnknownToolError} When no registry is wired or the tool is not registered\n\t * @private\n\t */\n\tprivate _validateToolName(toolName: string): void {\n\t\tif (!this._toolRegistry) {\n\t\t\tthrow new UnknownToolError(\n\t\t\t\ttoolName,\n\t\t\t\t`Tool '${toolName}' rejected: no tool registry configured. Tool interleave requires a registered allowlist.`\n\t\t\t);\n\t\t}\n\t\tif (!this._toolRegistry.has(toolName)) {\n\t\t\tthrow new UnknownToolError(toolName);\n\t\t}\n\t}\n\n\t/**\n\t * Returns a workaround thought type for a feature-flagged type.\n\t * @private\n\t */\n\tprivate static _getWorkaroundType(t: 'assumption' | 'decomposition' | 'backtrack'): string {\n\t\tswitch (t) {\n\t\t\tcase 'assumption':\n\t\t\t\treturn 'regular';\n\t\t\tcase 'decomposition':\n\t\t\t\treturn 'hypothesis';\n\t\t\tcase 'backtrack':\n\t\t\t\treturn 'regular';\n\t\t\tdefault:\n\t\t\t\tassertNever(t);\n\t\t}\n\t}\n\n\t/**\n\t * Persist a tool_call thought and return a `suspended` envelope.\n\t * Strategy/evaluator are intentionally skipped.\n\t * @private\n\t */\n\tprivate _handleToolCall(\n\t\tinput: ToolCallThought,\n\t\tadmissionContext: ThoughtAdmissionContext\n\t): CallToolResult {\n\t\tif (input.id === undefined) {\n\t\t\tthrow new ValidationError('id', 'tool_call requires an admitted thought id');\n\t\t}\n\t\tthis.historyManager.addThought(input, admissionContext);\n\t\tif (!this._suspensionStore) {\n\t\t\tthrow new ValidationError('thought_type', 'tool_call requires suspensionStore');\n\t\t}\n\t\tconst record: SuspensionRecord = this._suspensionStore.suspend({\n\t\t\tsessionId: input.session_id,\n\t\t\ttoolCallThoughtNumber: input.thought_number,\n\t\t\ttoolCallThoughtId: input.id,\n\t\t\ttoolName: input.tool_name,\n\t\t\ttoolArguments: input.tool_arguments ?? {},\n\t\t\texpiresAt: 0,\n\t\t});\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstatus: 'suspended',\n\t\t\t\t\t\t\tcontinuation_token: record.token,\n\t\t\t\t\t\t\ttool_name: record.toolName,\n\t\t\t\t\t\t\ttool_arguments: record.toolArguments,\n\t\t\t\t\t\t\texpires_at: record.expiresAt,\n\t\t\t\t\t\t\tthought_number: input.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: input.total_thoughts,\n\t\t\t\t\t\t\tsession_id: input.session_id,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Resume from a tool_observation and atomically admit it before consuming the record.\n\t * @private\n\t */\n\tprivate async _handleToolObservation(\n\t\tinput: ToolObservationThought,\n\t\tadmissionContext: ThoughtAdmissionContext\n\t): Promise<void> {\n\t\tif (!this._suspensionStore) {\n\t\t\tthrow new ValidationError('thought_type', 'tool_observation requires suspensionStore');\n\t\t}\n\t\tawait this._suspensionStore.compareAndAdmit(\n\t\t\tinput.continuation_token,\n\t\t\tinput.session_id,\n\t\t\t(record) => {\n\t\t\t\tthis.historyManager.addThought(input, {\n\t\t\t\t\t...admissionContext,\n\t\t\t\t\ttoolInvocationSourceThoughtId: record.toolCallThoughtId,\n\t\t\t\t});\n\t\t\t}\n\t\t);\n\t}\n}\n"],"names":["ThoughtProcessor","Map","historyManager","thoughtFormatter","thoughtEvaluator","logger","strategy","SequentialStrategy","_compressionService","_suspensionStore","_toolRegistry","_features","DEFAULT_FLAGS","_sessionLock","_outcomeRecorder","_lifecycle","SessionLifecycleCoordinator","_calibrator","NullLogger","message","meta","patterns","currentThoughtNumber","sessionId","warnings","p","a","b","pa","pb","cooldowns","undefined","hints","warning","lastFired","input","prepared","operation","error","canonicalSessionId","asSessionId","normalized","normalizeInput","parsed","v","SequentialThinkingSchema","firstIssue","field","item","String","ValidationError","internal","registerBranchId","asBranchId","thought","result","JSON","SequentialThinkingError","getErrorMessage","toolArguments","enforceJsonShape","JsonShapeError","resetState","existingSnapshot","validationSnapshot","resolveThoughtReference","thoughtNumber","checkedInput","refWarnings","resolvedReferences","validateThoughtCrossReferences","verificationOutcome","prepareVerificationOutcome","allWarnings","validated","admissionContext","formattedThought","signals","decision","outcome","history","branches","confidenceSignals","reasoningStats","patternSignals","reasoningHints","state","currentThought","stats","edgeStore","graph","GraphView","branchRoot","err","branchId","branchList","firstId","ids","originalTotal","WARNING_CODES","t","InvalidToolCallError","InvalidBacktrackError","toolName","UnknownToolError","assertNever","record"],"mappings":";;;;;;;;;;;;;;AA6IO,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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B,MAAM,IAAIzB,gBAAgB,gBAAgB;QAE3C,MAAMwD,SAA2B,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC;YAC9D,WAAWvE,MAAM,UAAU;YAC3B,uBAAuBA,MAAM,cAAc;YAC3C,mBAAmBA,MAAM,EAAE;YAC3B,UAAUA,MAAM,SAAS;YACzB,eAAeA,MAAM,cAAc,IAAI,CAAC;YACxC,WAAW;QACZ;QACA,OAAO;YACN,SAAS;gBACR;oBACC,MAAM;oBACN,MAAMqB,KAAK,SAAS,CACnB;wBACC,QAAQ;wBACR,oBAAoBkD,OAAO,KAAK;wBAChC,WAAWA,OAAO,QAAQ;wBAC1B,gBAAgBA,OAAO,aAAa;wBACpC,YAAYA,OAAO,SAAS;wBAC5B,gBAAgBvE,MAAM,cAAc;wBACpC,gBAAgBA,MAAM,cAAc;wBACpC,YAAYA,MAAM,UAAU;oBAC7B,GACA,MACA;gBAEF;aACA;QACF;IACD;IAMA,MAAc,uBACbA,KAA6B,EAC7BwC,gBAAyC,EACzB;QAChB,IAAI,CAAC,IAAI,CAAC,gBAAgB,EACzB,MAAM,IAAIzB,gBAAgB,gBAAgB;QAE3C,MAAM,IAAI,CAAC,gBAAgB,CAAC,eAAe,CAC1Cf,MAAM,kBAAkB,EACxBA,MAAM,UAAU,EAChB,CAACuE;YACA,IAAI,CAAC,cAAc,CAAC,UAAU,CAACvE,OAAO;gBACrC,GAAGwC,gBAAgB;gBACnB,+BAA+B+B,OAAO,iBAAiB;YACxD;QACD;IAEF;AACD"}
1
+ {"version":3,"file":"core/ThoughtProcessor.js","sources":["../../src/core/ThoughtProcessor.ts"],"sourcesContent":["/**\n * Core thought processing logic and validation.\n *\n * This module provides the `ThoughtProcessor` class which handles the main\n * sequential thinking request processing pipeline, including input validation,\n * history management, and response formatting.\n *\n * @module processor\n */\n\nimport * as v from 'valibot';\n\nimport { NullLogger } from '../logger/NullLogger.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport {\n\tasBranchId,\n\tasSessionId,\n\ttype BranchId,\n\ttype SessionId,\n\ttype ThoughtId,\n} from '../contracts/ids.js';\nimport type { IEdgeStore, IOutcomeRecorder } from '../contracts/interfaces.js';\nimport type { ICalibrator } from '../contracts/calibrator.js';\nimport type { ISuspensionStore, SuspensionRecord } from '../contracts/suspension.js';\nimport type { IReasoningStrategy, StrategyDecision } from '../contracts/strategy.js';\nimport { DEFAULT_FLAGS, type FeatureFlags } from '../contracts/features.js';\nimport type { ISessionLock, IToolRegistry } from '../contracts/interfaces.js';\nimport {\n\tInvalidBacktrackError,\n\tInvalidToolCallError,\n\tSequentialThinkingError,\n\tUnknownToolError,\n\tValidationError,\n} from '../errors.js';\nimport { getErrorMessage, WARNING_CODES } from '../errors.js';\nimport { enforceJsonShape, JsonShapeError } from '../sanitize.js';\nimport { SequentialThinkingSchema } from '../schema.js';\nimport { GraphView } from './graph/GraphView.js';\nimport { buildActiveEvidenceProjection } from './reasoning/ActiveEvidenceProjection.js';\nimport { assertNever } from '../utils.js';\nimport type {\n\tHistorySessionSnapshot,\n\tIHistoryManager,\n\tThoughtAdmissionContext,\n} from './IHistoryManager.js';\nimport { normalizeInput } from './InputNormalizer.js';\nimport type {\n\tThoughtData,\n\tToolCallThought,\n\tToolObservationThought,\n\tValidatedThought,\n} from './thought.js';\nimport type { ThoughtEvaluator } from './ThoughtEvaluator.js';\nimport type { ThoughtFormatter } from './ThoughtFormatter.js';\nimport type { PatternName } from '../contracts/reasoning-types.js';\nimport type { PatternSignal } from './reasoning.js';\nimport { SequentialStrategy } from './reasoning/strategies/SequentialStrategy.js';\nimport type { CompressionService } from './compression/CompressionService.js';\nimport { validateThoughtCrossReferences } from './CrossReferenceValidator.js';\nimport { SessionLifecycleCoordinator } from './SessionLifecycleCoordinator.js';\nimport { prepareVerificationOutcome } from './VerificationOutcomeAdmission.js';\n\ntype ConfidenceSignalsResult = ReturnType<ThoughtEvaluator['computeConfidenceSignals']>;\ntype ReasoningStatsResult = ReturnType<ThoughtEvaluator['computeReasoningStats']>;\n\ntype ReasoningSignalBundle = {\n\treadonly history: ThoughtData[];\n\treadonly confidenceSignals: ConfidenceSignalsResult;\n\treadonly reasoningStats: ReasoningStatsResult;\n\treadonly reasoningHints: readonly string[];\n};\n\ntype ProcessedThoughtResponseState = {\n\treadonly thought: ThoughtData;\n\treadonly reasoning: {\n\t\treadonly confidenceSignals: ConfidenceSignalsResult;\n\t\treadonly reasoningStats: ReasoningStatsResult;\n\t\treadonly reasoningHints: readonly string[];\n\t};\n\treadonly decision: StrategyDecision | undefined;\n\treadonly warnings: readonly string[];\n};\n\ntype ThoughtProcessInput = ThoughtData & { readonly register_branch_id?: string };\n\ntype PreparedThought = {\n\treadonly thought: ThoughtData;\n\treadonly resetState: boolean;\n\treadonly registerBranchId: BranchId | undefined;\n\treadonly validationWarnings: readonly string[];\n};\n\n/**\n * The return type expected by MCP tool invocations.\n *\n * This structure matches the MCP protocol for tool results,\n * supporting both success and error responses.\n *\n * @example\n * ```typescript\n * const successResult: CallToolResult = {\n * content: [{ type: 'text', text: '{\"status\":\"success\"}' }]\n * };\n *\n * const errorResult: CallToolResult = {\n * content: [{ type: 'text', text: '{\"error\":\"Something went wrong\"}' }],\n * isError: true\n * };\n * ```\n */\nexport interface CallToolResult extends Record<string, unknown> {\n\t/** Array of content blocks (typically text) to return to the client. */\n\tcontent: Array<{\n\t\ttype: 'text';\n\t\ttext: string;\n\t}>;\n\n\t/** Whether this result represents an error condition. */\n\tisError?: boolean;\n}\n\n/**\n * Core processor for sequential thinking requests.\n *\n * Pipeline: validate → normalize → add to history → format → evaluate signals\n * → run reasoning strategy → return structured response.\n *\n * Auto-adjusts `total_thoughts` if `thought_number` exceeds it. All errors are\n * caught and returned as formatted error responses with `isError: true`.\n *\n * @example\n * ```typescript\n * const processor = new ThoughtProcessor(historyManager, formatter, new ThoughtEvaluator());\n * const result = await processor.process({\n * thought: '...',\n * thought_number: 1,\n * total_thoughts: 5,\n * next_thought_needed: true,\n * session_id: asSessionId('analysis')\n * });\n * ```\n */\nexport class ThoughtProcessor {\n\t/** Logger for debugging and monitoring. */\n\tprivate _logger: Logger;\n\n\t/** Evaluator for quality signal computation. */\n\tprivate readonly _thoughtEvaluator: ThoughtEvaluator;\n\n\t/**\n\t * Per-session cooldown tracker: session_id → pattern → last_fired_thought_number.\n\t * Prevents re-firing the same pattern hint within 3 thoughts.\n\t */\n\tprivate _hintCooldowns = new Map<SessionId, Map<PatternName, number>>();\n\n\t/**\n\t * Creates a new ThoughtProcessor instance.\n\t *\n\t * @param historyManager - History manager for storing thoughts\n\t * @param thoughtFormatter - Formatter for output formatting\n\t * @param thoughtEvaluator - Evaluator for quality signal computation\n\t * @param logger - Optional logger for diagnostics (defaults to NullLogger)\n\t * @param strategy - Reasoning strategy controlling next-action decisions (defaults to SequentialStrategy)\n\t * @param compressionService - Optional compression service for auto-compression on terminate\n\t * @param suspensionStore - Optional suspension store enabling tool interleave\n\t * @param toolRegistry - Optional tool registry for tool_name allowlist validation (required when toolInterleave is enabled)\n\t * @param features - Optional feature flags (defaults to DEFAULT_FLAGS — all opt-in flags off)\n\t * @param sessionLock - Optional per-session async lock; when provided, `process()` runs under it\n\t * @param outcomeRecorder - Optional per-session calibration outcome store\n\t */\n\tconstructor(\n\t\tprivate historyManager: IHistoryManager,\n\t\tprivate thoughtFormatter: ThoughtFormatter,\n\t\tthoughtEvaluator: ThoughtEvaluator,\n\t\tlogger?: Logger,\n\t\tprivate readonly strategy: IReasoningStrategy = new SequentialStrategy(),\n\t\tprivate readonly _compressionService?: CompressionService,\n\t\tprivate readonly _suspensionStore?: ISuspensionStore,\n\t\tprivate readonly _toolRegistry?: IToolRegistry,\n\t\tprivate readonly _features: FeatureFlags = DEFAULT_FLAGS,\n\t\tprivate readonly _sessionLock?: ISessionLock,\n\t\tprivate readonly _outcomeRecorder?: IOutcomeRecorder,\n\t\tprivate readonly _lifecycle: SessionLifecycleCoordinator = new SessionLifecycleCoordinator(),\n\t\tprivate readonly _calibrator?: ICalibrator\n\t) {\n\t\tthis._thoughtEvaluator = thoughtEvaluator;\n\t\tthis._logger = logger ?? new NullLogger();\n\t}\n\n\t/**\n\t * Internal logging method.\n\t * @param message - The message to log\n\t * @param meta - Optional metadata\n\t * @private\n\t */\n\tprivate log(message: string, meta?: Record<string, unknown>): void {\n\t\tthis._logger.info(message, meta);\n\t}\n\n\t/**\n\t * Priority ordering for warning patterns (lower = higher priority).\n\t * Ensures the most actionable patterns fill the hint cap first.\n\t */\n\tprivate static readonly _HINT_PRIORITY: Readonly<Partial<Record<PatternName, number>>> = {\n\t\tconfidence_drift: 1, // Most actionable — degrading confidence\n\t\tunverified_hypothesis: 2, // Important for quality\n\t\tno_alternatives_explored: 3, // Breadth gap\n\t\tconsecutive_without_verification: 4, // Routine pattern\n\t};\n\n\t/**\n\t * Generate actionable hints from pattern signals.\n\t * Rules: max 3 hints, warning-severity only, cooldown of 3 thoughts per pattern per session.\n\t *\n\t * Warning patterns are sorted by priority before selection (see _HINT_PRIORITY).\n\t * Higher-priority patterns (lower number) fill the hint cap first.\n\t *\n\t * @param patterns - Detected pattern signals\n\t * @param currentThoughtNumber - The current thought number being processed\n\t * @param sessionId - Session identifier for cooldown scoping\n\t * @returns Array of hint strings (max 3), empty if no warnings\n\t */\n\tprivate _generateHints(\n\t\tpatterns: PatternSignal[],\n\t\tcurrentThoughtNumber: number,\n\t\tsessionId: SessionId\n\t): string[] {\n\t\tconst warnings = patterns.filter((p) => p.severity === 'warning');\n\t\tif (warnings.length === 0) return [];\n\n\t\t// Sort by priority (lower number = higher priority)\n\t\twarnings.sort((a, b) => {\n\t\t\tconst pa = ThoughtProcessor._HINT_PRIORITY[a.pattern] ?? 99;\n\t\t\tconst pb = ThoughtProcessor._HINT_PRIORITY[b.pattern] ?? 99;\n\t\t\treturn pa - pb;\n\t\t});\n\n\t\tlet cooldowns = this._hintCooldowns.get(sessionId);\n\t\tif (cooldowns === undefined) {\n\t\t\tcooldowns = new Map();\n\t\t\tthis._hintCooldowns.set(sessionId, cooldowns);\n\t\t}\n\n\t\tconst hints: string[] = [];\n\t\tfor (const warning of warnings) {\n\t\t\tif (hints.length >= 3) break;\n\n\t\t\tconst lastFired = cooldowns.get(warning.pattern);\n\t\t\tif (lastFired !== undefined && currentThoughtNumber - lastFired < 3) {\n\t\t\t\tcontinue; // Still in cooldown\n\t\t\t}\n\n\t\t\thints.push(warning.message);\n\t\t\tcooldowns.set(warning.pattern, currentThoughtNumber);\n\t\t}\n\n\t\treturn hints;\n\t}\n\n\t/**\n\t * Processes a thought through the sequential thinking pipeline.\n\t *\n\t * This method validates the input, adds it to history, formats the output,\n\t * computes quality signals via the ThoughtEvaluator, and returns\n\t * a structured response with metadata about the current state.\n\t *\n\t * @param input - The thought data to process\n\t * @returns A Promise resolving to the formatted tool result containing:\n\t * - `thought_number` — Current thought index\n\t * - `total_thoughts` — Estimated total thoughts\n\t * - `next_thought_needed` — Whether to continue\n\t * - `branches` — Active branch IDs\n\t * - `thought_history_length` — Number of thoughts in history\n\t * - `available_mcp_tools` — MCP tools available for recommendation\n\t * - `available_skills` — Skills available for recommendation\n\t * - `current_step` — Current step recommendation\n\t * - `previous_steps` — Previously recommended steps\n\t * - `remaining_steps` — Upcoming step descriptions\n\t * - `thought_type` — Classification of thought purpose (optional)\n\t * - `quality_score` — Self-assessed quality score 0-1 (optional)\n\t * - `confidence` — Self-assessed confidence 0-1 (optional)\n\t * - `hypothesis_id` — Hypothesis link for verification chains (optional)\n\t * - `confidence_signals` — Computed reasoning quality signals (includes structural_quality and quality_components)\n\t * - `reasoning_stats` — Aggregated reasoning analytics\n\t * - `reasoning_hints` — (Conditional) Actionable hints from pattern analysis, max 3, warning-severity only (optional)\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await processor.process({\n\t * thought: 'I should read the README file',\n\t * thought_number: 1,\n\t * total_thoughts: 3,\n\t * next_thought_needed: true,\n\t * session_id: asSessionId('analysis')\n\t * });\n\t *\n\t * console.log(result.content[0].text);\n\t * // Output includes: thought_number, total_thoughts, next_thought_needed,\n\t * // branches, thought_history_length, and any recommendations\n\t * ```\n\t */\n\tpublic async process(input: ThoughtProcessInput): Promise<CallToolResult> {\n\t\ttry {\n\t\t\tconst prepared = this._prepareInput(input);\n\t\t\tconst sessionId = prepared.thought.session_id;\n\t\t\tconst operation = async (): Promise<CallToolResult> => {\n\t\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\t\treturn await this._sessionLock.withLock(sessionId, () => this._processInner(prepared));\n\t\t\t\t}\n\t\t\t\treturn await this._processInner(prepared);\n\t\t\t};\n\t\t\tif (prepared.resetState) {\n\t\t\t\tthis.historyManager.inspectSession(sessionId);\n\t\t\t\treturn await this._lifecycle.withSessionReset(sessionId, operation);\n\t\t\t}\n\t\t\treturn await this._lifecycle.runOperation(sessionId, operation);\n\t\t} catch (error) {\n\t\t\treturn this._buildErrorResponse(error);\n\t\t}\n\t}\n\n\t/** Resets one canonical session and its processor-owned auxiliary state. */\n\tpublic async resetSession(sessionId: string): Promise<void> {\n\t\tconst canonicalSessionId = asSessionId(sessionId);\n\t\tthis.historyManager.inspectSession(canonicalSessionId);\n\t\tconst operation = async (): Promise<void> => {\n\t\t\tawait this.historyManager.resetSessionWithinExclusive(canonicalSessionId, () =>\n\t\t\t\tthis.clearSessionAuxiliaryState(canonicalSessionId)\n\t\t\t);\n\t\t};\n\t\tawait this._lifecycle.withSessionReset(canonicalSessionId, async () => {\n\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\tawait this._sessionLock.withLock(canonicalSessionId, operation);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait operation();\n\t\t});\n\t}\n\n\t/** Resets all history and processor-owned auxiliary state from a trusted context. */\n\tpublic async resetAll(): Promise<void> {\n\t\tawait this._lifecycle.withGlobalReset(\n\t\t\tasync () =>\n\t\t\t\tawait this.historyManager.resetAllWithinExclusive(() => this.clearAllAuxiliaryState())\n\t\t);\n\t}\n\n\tprivate _prepareInput(input: ThoughtProcessInput): PreparedThought {\n\t\tconst normalized = normalizeInput(input);\n\t\tif (typeof normalized === 'object' && normalized !== null) {\n\t\t\tthis._validateToolArgumentsShape(normalized.tool_arguments);\n\t\t}\n\t\tconst parsed = v.safeParse(SequentialThinkingSchema, normalized);\n\t\tif (!parsed.success) {\n\t\t\tconst firstIssue = parsed.issues[0];\n\t\t\tconst field = firstIssue?.path?.map((item) => String(item.key)).join('.') || 'input';\n\t\t\tthrow new ValidationError(field, firstIssue?.message ?? 'Invalid input');\n\t\t}\n\n\t\tconst internal = normalizeInput(parsed.output) as ThoughtData & {\n\t\t\tregister_branch_id?: string;\n\t\t};\n\t\tconst registerBranchId =\n\t\t\tinternal.register_branch_id === undefined\n\t\t\t\t? undefined\n\t\t\t\t: asBranchId(internal.register_branch_id);\n\t\tconst thought = { ...internal };\n\t\tdelete thought.register_branch_id;\n\t\tconst { result, warnings } = this.validateInput(thought);\n\t\tthis._validateStatelessNewTypes(result);\n\t\treturn {\n\t\t\tthought: result,\n\t\t\tresetState: result.reset_state === true,\n\t\t\tregisterBranchId,\n\t\t\tvalidationWarnings: warnings,\n\t\t};\n\t}\n\n\tprivate _buildErrorResponse(error: unknown): CallToolResult {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...(error instanceof SequentialThinkingError && { code: error.code }),\n\t\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t\t\tmessage: getErrorMessage(error),\n\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\tprivate static _emptySessionSnapshot(): HistorySessionSnapshot {\n\t\treturn {\n\t\t\thistory: [],\n\t\t\tbranches: {},\n\t\t\tverificationTargets: new Map(),\n\t\t\tbranchIds: [],\n\t\t\tavailableMcpTools: undefined,\n\t\t\tavailableSkills: undefined,\n\t\t};\n\t}\n\n\t/** Clears all processor-owned state for one removed session. */\n\tpublic clearSessionAuxiliaryState(sessionId: SessionId): void {\n\t\tthis._hintCooldowns.delete(sessionId);\n\t\tthis._suspensionStore?.clearSession(sessionId);\n\t\tthis._outcomeRecorder?.clearOutcomes(sessionId);\n\t\tthis._calibrator?.clearSession(sessionId);\n\t}\n\n\t/** Clears all processor-owned state after global reset or successful shutdown. */\n\tpublic clearAllAuxiliaryState(): void {\n\t\tthis._suspensionStore?.clearAll();\n\t\tthis._outcomeRecorder?.clearAllOutcomes();\n\t\tthis._calibrator?.clearAll();\n\t\tthis._hintCooldowns.clear();\n\t}\n\n\tprivate _validateToolArgumentsShape(toolArguments: unknown): void {\n\t\ttry {\n\t\t\tenforceJsonShape(toolArguments ?? {});\n\t\t} catch (error) {\n\t\t\tif (error instanceof JsonShapeError) {\n\t\t\t\tthrow new ValidationError('tool_arguments', error.reason);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate async _processInner(prepared: PreparedThought): Promise<CallToolResult> {\n\t\tconst { thought, resetState, registerBranchId } = prepared;\n\t\tconst sessionId = thought.session_id;\n\t\tconst existingSnapshot = this.historyManager.inspectSession(sessionId);\n\t\tconst validationSnapshot = resetState\n\t\t\t? ThoughtProcessor._emptySessionSnapshot()\n\t\t\t: existingSnapshot;\n\t\tif (!resetState) {\n\t\t\tif (!thought.available_mcp_tools && validationSnapshot.availableMcpTools) {\n\t\t\t\tthought.available_mcp_tools = [...validationSnapshot.availableMcpTools];\n\t\t\t}\n\t\t\tif (!thought.available_skills && validationSnapshot.availableSkills) {\n\t\t\t\tthought.available_skills = [...validationSnapshot.availableSkills];\n\t\t\t}\n\t\t}\n\t\tconst resolveThoughtReference = resetState\n\t\t\t? () => ({ kind: 'missing' as const })\n\t\t\t: (thoughtNumber: number) =>\n\t\t\t\t\tthis.historyManager.resolveThoughtReference(sessionId, thoughtNumber);\n\t\tconst {\n\t\t\tresult: checkedInput,\n\t\t\twarnings: refWarnings,\n\t\t\tresolvedReferences,\n\t\t} = validateThoughtCrossReferences(thought, {\n\t\t\tsnapshot: validationSnapshot,\n\t\t\tresolveThoughtReference,\n\t\t\tstrictBranchReferences: resetState || registerBranchId !== undefined,\n\t\t\tlogger: this._logger,\n\t\t});\n\t\tconst verificationOutcome = prepareVerificationOutcome({\n\t\t\tinput: checkedInput,\n\t\t\tsnapshot: validationSnapshot,\n\t\t\tresolvedReferences,\n\t\t\tsessionId,\n\t\t\trecorder: this._outcomeRecorder,\n\t\t});\n\t\tconst allWarnings = [...prepared.validationWarnings, ...refWarnings];\n\t\tconst validated = this._validateNewTypes(checkedInput);\n\t\tconst admissionContext: ThoughtAdmissionContext = { resolvedReferences };\n\t\tif (resetState && validated.thought_type === 'tool_observation') {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t'tool_observation cannot resume a suspension in reset replacement state'\n\t\t\t);\n\t\t}\n\n\t\tif (resetState) {\n\t\t\tawait this.historyManager.resetSessionWithinExclusive(sessionId, () =>\n\t\t\t\tthis.clearSessionAuxiliaryState(sessionId)\n\t\t\t);\n\t\t\tthis.log('State reset for session', { sessionId });\n\t\t}\n\t\tthis.historyManager.assertThoughtIdentityAvailable(checkedInput);\n\t\tif (registerBranchId !== undefined) {\n\t\t\tthis.historyManager.registerBranch(sessionId, registerBranchId);\n\t\t}\n\n\t\t// Tool-interleave suspend path: persist the tool_call thought, then return\n\t\t// a `suspended` envelope without running strategy/evaluator.\n\t\tif (validated.thought_type === 'tool_call' && this._suspensionStore) {\n\t\t\treturn this._handleToolCall(validated, admissionContext);\n\t\t}\n\n\t\t// Tool-interleave resume path: consume the suspension and continue the\n\t\t// normal pipeline (addThought → format → evaluate → strategy).\n\t\tif (validated.thought_type === 'tool_observation' && this._suspensionStore) {\n\t\t\tawait this._handleToolObservation(validated, admissionContext);\n\t\t} else {\n\t\t\tthis.historyManager.addThought(checkedInput, admissionContext);\n\t\t}\n\t\tthis._recordVerificationOutcome(verificationOutcome, sessionId);\n\n\t\tconst formattedThought = this.thoughtFormatter.formatThought(checkedInput);\n\t\tthis.log(formattedThought, { sessionId });\n\n\t\tconst signals = this._collectReasoningSignals(checkedInput);\n\n\t\t// Strategy decision — pluggable reasoning policy hook.\n\t\t// Built after history/stats so strategies see the latest state.\n\t\tconst decision = this._runStrategy(checkedInput, signals.history, signals.reasoningStats);\n\n\t\treturn this._buildSuccessResponse({\n\t\t\tthought: checkedInput,\n\t\t\treasoning: {\n\t\t\t\tconfidenceSignals: signals.confidenceSignals,\n\t\t\t\treasoningStats: signals.reasoningStats,\n\t\t\t\treasoningHints: signals.reasoningHints,\n\t\t\t},\n\t\t\tdecision,\n\t\t\twarnings: allWarnings,\n\t\t});\n\t}\n\n\tprivate _recordVerificationOutcome(\n\t\toutcome: ReturnType<typeof prepareVerificationOutcome>,\n\t\tsessionId: SessionId\n\t): void {\n\t\tif (outcome === undefined) return;\n\t\tif (this._outcomeRecorder?.enabled === true) {\n\t\t\tthis._outcomeRecorder.recordVerification(outcome);\n\t\t}\n\t\tif (this._calibrator?.enabled === true) this._calibrator.refit(sessionId);\n\t}\n\n\tprivate _collectReasoningSignals(input: ThoughtData): ReasoningSignalBundle {\n\t\tconst sessionId = input.session_id;\n\t\tconst history = this.historyManager.getHistory(sessionId);\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst verificationTargets = this.historyManager.inspectSession(sessionId).verificationTargets;\n\t\tconst confidenceSignals = this._thoughtEvaluator.computeConfidenceSignals(history, branches, {\n\t\t\tcurrentThought: input,\n\t\t\tsessionId,\n\t\t\tverificationTargets,\n\t\t});\n\t\tconst reasoningStats = this._thoughtEvaluator.computeReasoningStats(history, branches, {\n\t\t\tverificationTargets,\n\t\t});\n\t\tconst patternSignals = this._thoughtEvaluator.computePatternSignals(history, branches, {\n\t\t\tverificationTargets,\n\t\t});\n\t\tconst reasoningHints = this._generateHints(patternSignals, input.thought_number, sessionId);\n\n\t\treturn {\n\t\t\thistory,\n\t\t\tconfidenceSignals,\n\t\t\treasoningStats,\n\t\t\treasoningHints,\n\t\t};\n\t}\n\n\tprivate _buildSuccessResponse(state: ProcessedThoughtResponseState): CallToolResult {\n\t\tconst sessionId = state.thought.session_id;\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthought_number: state.thought.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: state.thought.total_thoughts,\n\t\t\t\t\t\t\tnext_thought_needed: state.thought.next_thought_needed ?? true,\n\t\t\t\t\t\t\tbranches: this.historyManager.getBranchIds(sessionId),\n\t\t\t\t\t\t\tthought_history_length: this.historyManager.getHistoryLength(sessionId),\n\t\t\t\t\t\t\tavailable_mcp_tools: state.thought.available_mcp_tools,\n\t\t\t\t\t\t\tavailable_skills: state.thought.available_skills,\n\t\t\t\t\t\t\tcurrent_step: state.thought.current_step,\n\t\t\t\t\t\t\tprevious_steps: state.thought.previous_steps,\n\t\t\t\t\t\t\tremaining_steps: state.thought.remaining_steps,\n\t\t\t\t\t\t\tthought_type: state.thought.thought_type,\n\t\t\t\t\t\t\tquality_score: state.thought.quality_score,\n\t\t\t\t\t\t\tconfidence: state.thought.confidence,\n\t\t\t\t\t\t\thypothesis_id: state.thought.hypothesis_id,\n\t\t\t\t\t\t\tconfidence_signals: state.reasoning.confidenceSignals,\n\t\t\t\t\t\t\treasoning_stats: state.reasoning.reasoningStats,\n\t\t\t\t\t\t\t...(state.reasoning.reasoningHints.length > 0 && {\n\t\t\t\t\t\t\t\treasoning_hints: state.reasoning.reasoningHints,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(state.decision !== undefined && { strategy_hint: state.decision }),\n\t\t\t\t\t\t\t...(state.warnings.length > 0 && { warnings: state.warnings.slice(0, 3) }),\n\t\t\t\t\t\t\tsession_id: sessionId,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Run the configured reasoning strategy and return its decision.\n\t * Strategy errors omit the decision from the public response.\n\t * @private\n\t */\n\tprivate _runStrategy(\n\t\tcurrentThought: ThoughtData,\n\t\thistory: ThoughtData[],\n\t\tstats: ReturnType<ThoughtEvaluator['computeReasoningStats']>\n\t): StrategyDecision | undefined {\n\t\tconst sessionId = currentThought.session_id;\n\t\tlet decision: StrategyDecision | undefined;\n\t\ttry {\n\t\t\tconst evidence = buildActiveEvidenceProjection({\n\t\t\t\tsessionId,\n\t\t\t\thistory,\n\t\t\t\tbranches: this.historyManager.getBranches(sessionId),\n\t\t\t\tedgeStore: this._getEdgeStore(),\n\t\t\t});\n\t\t\tdecision = this.strategy.decide({\n\t\t\t\tsessionId,\n\t\t\t\tevidence,\n\t\t\t\tstats,\n\t\t\t\tcurrentThought,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis._logger.warn('Reasoning strategy threw — omitting strategy hint', {\n\t\t\t\tstrategy: this.strategy.name,\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t}\n\n\t\t// Auto-compression trigger: when strategy terminates a branch and\n\t\t// compression is enabled, summarize the branch subtree. Compression\n\t\t// failures must NEVER break the thought pipeline.\n\t\tif (decision?.action === 'terminate' && this._compressionService && currentThought.branch_id) {\n\t\t\ttry {\n\t\t\t\tconst branchRoot = this._findBranchRoot(sessionId, currentThought.branch_id);\n\t\t\t\tif (branchRoot) {\n\t\t\t\t\tthis._compressionService.compressBranch(\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tcurrentThought.branch_id,\n\t\t\t\t\t\tbranchRoot as ThoughtId\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthis._logger.debug('Compression auto-trigger failed', {\n\t\t\t\t\terror: getErrorMessage(err),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn decision;\n\t}\n\n\t/**\n\t * Locate the root thought id for a branch.\n\t * Prefers GraphView.branchThoughts() when an EdgeStore is available;\n\t * falls back to historyManager.getBranches(sessionId)[branchId][0].id.\n\t * @private\n\t */\n\tprivate _findBranchRoot(sessionId: SessionId, branchId: BranchId): string | undefined {\n\t\tconst edgeStore = this._getEdgeStore();\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst branchList = branches[branchId];\n\t\tconst firstId = branchList?.[0]?.id;\n\t\tif (edgeStore && firstId) {\n\t\t\tconst graph = new GraphView(edgeStore);\n\t\t\tconst ids = graph.branchThoughts(sessionId, firstId);\n\t\t\tif (ids.length > 0) return ids[0];\n\t\t}\n\t\treturn firstId;\n\t}\n\n\t/** Access the EdgeStore via IHistoryManager. @private */\n\tprivate _getEdgeStore(): IEdgeStore | undefined {\n\t\treturn this.historyManager.getEdgeStore();\n\t}\n\n\t/**\n\t * Validates and normalizes thought input.\n\t *\n\t * Ensures that thought numbers are consistent and within valid ranges.\n\t * If `thought_number` exceeds `total_thoughts`, `total_thoughts` is\n\t * automatically adjusted to match and a warning is emitted.\n\t *\n\t * @param input - The input to validate\n\t * @returns Object with validated input and any warnings generated\n\t * @private\n\t *\n\t * @example\n\t * ```typescript\n\t * // Auto-adjusts total_thoughts when thought_number exceeds it\n\t * const { result, warnings } = this.validateInput(input);\n\t * // result.total_thoughts === 10 (auto-adjusted from 5)\n\t * // warnings === ['Auto-adjusted total_thoughts from 5 to 10 to match thought_number']\n\t * ```\n\t */\n\tprivate validateInput(input: ThoughtData): {\n\t\tresult: ThoughtData;\n\t\twarnings: string[];\n\t} {\n\t\tconst warnings: string[] = [];\n\t\tif (input.thought_number > input.total_thoughts) {\n\t\t\tconst originalTotal = input.total_thoughts;\n\t\t\twarnings.push(\n\t\t\t\t`[${WARNING_CODES.TOTAL_THOUGHTS_ADJUSTED}] Auto-adjusted total_thoughts from ${originalTotal} to ${input.thought_number} to match thought_number`\n\t\t\t);\n\t\t\tthis._logger.warn('Auto-adjusted total_thoughts to match thought_number', {\n\t\t\t\tthought_number: input.thought_number,\n\t\t\t\toriginal_total_thoughts: originalTotal,\n\t\t\t\tadjusted_total_thoughts: input.thought_number,\n\t\t\t});\n\t\t\tinput.total_thoughts = input.thought_number;\n\t\t}\n\t\treturn { result: input, warnings };\n\t}\n\n\t/**\n\t * Validate new thought-type invariants behind feature flags.\n\t * @private\n\t */\n\tprivate _validateStatelessNewTypes(input: ThoughtData): void {\n\t\tconst t = input.thought_type;\n\t\tif ((t === 'tool_call' || t === 'tool_observation') && !this._features.toolInterleave) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t`Type '${t}' requires the toolInterleave feature flag. Set TRACELATTICE_FEATURES_TOOL_INTERLEAVE=true to enable it.`\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\t(t === 'assumption' || t === 'decomposition' || t === 'backtrack') &&\n\t\t\t!this._features.newThoughtTypes\n\t\t) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t`Type '${t}' requires the newThoughtTypes feature flag. Set TRACELATTICE_FEATURES_NEW_THOUGHT_TYPES=true to enable it, or use '${ThoughtProcessor._getWorkaroundType(t)}' type as a workaround.`\n\t\t\t);\n\t\t}\n\t\tif (t === 'tool_call') {\n\t\t\tif (!input.tool_name) {\n\t\t\t\tthrow new InvalidToolCallError(\n\t\t\t\t\t'tool_call thought ' + input.thought_number + ' missing required tool_name'\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis._validateToolName(input.tool_name);\n\t\t}\n\t\tif (t === 'tool_observation' && !input.continuation_token) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'continuation_token',\n\t\t\t\t'tool_observation thought ' + input.thought_number + ' missing continuation_token'\n\t\t\t);\n\t\t}\n\t\tif (t === 'backtrack') {\n\t\t\tif (input.backtrack_target === undefined) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t'backtrack_target',\n\t\t\t\t\t'backtrack thought ' + input.thought_number + ' requires backtrack_target'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (input.backtrack_target > input.thought_number) {\n\t\t\t\tthrow new InvalidBacktrackError(\n\t\t\t\t\t'backtrack_target ' +\n\t\t\t\t\t\tinput.backtrack_target +\n\t\t\t\t\t\t' must be <= thought_number ' +\n\t\t\t\t\t\tinput.thought_number\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (t === 'tool_call') {\n\t\t\tthis._validateToolArgumentsShape(input.tool_arguments);\n\t\t}\n\t}\n\n\tprivate _validateNewTypes(input: ThoughtData): ValidatedThought {\n\t\treturn input as ValidatedThought;\n\t}\n\n\t/**\n\t * Validate a tool_call's tool_name against the configured allowlist.\n\t *\n\t * Fails closed: if no tool registry was wired, all tool_call invocations are\n\t * rejected. This prevents arbitrary tool name injection through the protocol.\n\t *\n\t * @param toolName - The tool name from the tool_call thought\n\t * @throws {UnknownToolError} When no registry is wired or the tool is not registered\n\t * @private\n\t */\n\tprivate _validateToolName(toolName: string): void {\n\t\tif (!this._toolRegistry) {\n\t\t\tthrow new UnknownToolError(\n\t\t\t\ttoolName,\n\t\t\t\t`Tool '${toolName}' rejected: no tool registry configured. Tool interleave requires a registered allowlist.`\n\t\t\t);\n\t\t}\n\t\tif (!this._toolRegistry.has(toolName)) {\n\t\t\tthrow new UnknownToolError(toolName);\n\t\t}\n\t}\n\n\t/**\n\t * Returns a workaround thought type for a feature-flagged type.\n\t * @private\n\t */\n\tprivate static _getWorkaroundType(t: 'assumption' | 'decomposition' | 'backtrack'): string {\n\t\tswitch (t) {\n\t\t\tcase 'assumption':\n\t\t\t\treturn 'regular';\n\t\t\tcase 'decomposition':\n\t\t\t\treturn 'hypothesis';\n\t\t\tcase 'backtrack':\n\t\t\t\treturn 'regular';\n\t\t\tdefault:\n\t\t\t\tassertNever(t);\n\t\t}\n\t}\n\n\t/**\n\t * Persist a tool_call thought and return a `suspended` envelope.\n\t * Strategy/evaluator are intentionally skipped.\n\t * @private\n\t */\n\tprivate _handleToolCall(\n\t\tinput: ToolCallThought,\n\t\tadmissionContext: ThoughtAdmissionContext\n\t): CallToolResult {\n\t\tif (input.id === undefined) {\n\t\t\tthrow new ValidationError('id', 'tool_call requires an admitted thought id');\n\t\t}\n\t\tthis.historyManager.addThought(input, admissionContext);\n\t\tif (!this._suspensionStore) {\n\t\t\tthrow new ValidationError('thought_type', 'tool_call requires suspensionStore');\n\t\t}\n\t\tconst record: SuspensionRecord = this._suspensionStore.suspend({\n\t\t\tsessionId: input.session_id,\n\t\t\ttoolCallThoughtNumber: input.thought_number,\n\t\t\ttoolCallThoughtId: input.id,\n\t\t\ttoolName: input.tool_name,\n\t\t\ttoolArguments: input.tool_arguments ?? {},\n\t\t\texpiresAt: 0,\n\t\t});\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstatus: 'suspended',\n\t\t\t\t\t\t\tcontinuation_token: record.token,\n\t\t\t\t\t\t\ttool_name: record.toolName,\n\t\t\t\t\t\t\ttool_arguments: record.toolArguments,\n\t\t\t\t\t\t\texpires_at: record.expiresAt,\n\t\t\t\t\t\t\tthought_number: input.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: input.total_thoughts,\n\t\t\t\t\t\t\tsession_id: input.session_id,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Resume from a tool_observation and atomically admit it before consuming the record.\n\t * @private\n\t */\n\tprivate async _handleToolObservation(\n\t\tinput: ToolObservationThought,\n\t\tadmissionContext: ThoughtAdmissionContext\n\t): Promise<void> {\n\t\tif (!this._suspensionStore) {\n\t\t\tthrow new ValidationError('thought_type', 'tool_observation requires suspensionStore');\n\t\t}\n\t\tawait this._suspensionStore.compareAndAdmit(\n\t\t\tinput.continuation_token,\n\t\t\tinput.session_id,\n\t\t\t(record) => {\n\t\t\t\tthis.historyManager.addThought(input, {\n\t\t\t\t\t...admissionContext,\n\t\t\t\t\ttoolInvocationSourceThoughtId: record.toolCallThoughtId,\n\t\t\t\t});\n\t\t\t}\n\t\t);\n\t}\n}\n"],"names":["ThoughtProcessor","Map","historyManager","thoughtFormatter","thoughtEvaluator","logger","strategy","SequentialStrategy","_compressionService","_suspensionStore","_toolRegistry","_features","DEFAULT_FLAGS","_sessionLock","_outcomeRecorder","_lifecycle","SessionLifecycleCoordinator","_calibrator","NullLogger","message","meta","patterns","currentThoughtNumber","sessionId","warnings","p","a","b","pa","pb","cooldowns","undefined","hints","warning","lastFired","input","prepared","operation","error","canonicalSessionId","asSessionId","normalized","normalizeInput","parsed","v","SequentialThinkingSchema","firstIssue","field","item","String","ValidationError","internal","registerBranchId","asBranchId","thought","result","JSON","SequentialThinkingError","getErrorMessage","toolArguments","enforceJsonShape","JsonShapeError","resetState","existingSnapshot","validationSnapshot","resolveThoughtReference","thoughtNumber","checkedInput","refWarnings","resolvedReferences","validateThoughtCrossReferences","verificationOutcome","prepareVerificationOutcome","allWarnings","validated","admissionContext","formattedThought","signals","decision","outcome","history","branches","verificationTargets","confidenceSignals","reasoningStats","patternSignals","reasoningHints","state","currentThought","stats","evidence","buildActiveEvidenceProjection","branchRoot","err","branchId","edgeStore","branchList","firstId","graph","GraphView","ids","originalTotal","WARNING_CODES","t","InvalidToolCallError","InvalidBacktrackError","toolName","UnknownToolError","assertNever","record"],"mappings":";;;;;;;;;;;;;;;AA8IO,MAAMA;;;;;;;;;;;;IAEJ,QAAgB;IAGP,kBAAoC;IAM7C,iBAAiB,IAAIC,MAA2C;IAiBxE,YACSC,cAA+B,EAC/BC,gBAAkC,EAC1CC,gBAAkC,EAClCC,MAAe,EACEC,WAA+B,IAAIC,oBA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O,iBAAiB;YACxD;QACD;IAEF;AACD"}
@@ -12,12 +12,16 @@ export type ThoughtReferenceResolution = {
12
12
  /** Ref-counted stable-ID lookup for retained thoughts in each session. */
13
13
  export declare class ThoughtReferenceIndex {
14
14
  private readonly _sessions;
15
+ private readonly _identities;
15
16
  add(sessionId: SessionId, thought: ThoughtData): void;
16
17
  remove(sessionId: SessionId, thought: ThoughtData): void;
18
+ has(sessionId: SessionId, thoughtId: ThoughtId): boolean;
17
19
  resolve(sessionId: SessionId, thoughtNumber: number): ThoughtReferenceResolution;
18
20
  replaceSession(sessionId: SessionId, thoughts: Iterable<ThoughtData>): void;
19
21
  clearSession(sessionId: SessionId): void;
20
22
  clearAll(): void;
23
+ private _addIdentity;
24
+ private _removeIdentity;
21
25
  private _addToSession;
22
26
  }
23
27
  //# sourceMappingURL=ThoughtReferenceIndex.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ThoughtReferenceIndex.d.ts","sourceRoot":"","sources":["../../src/core/ThoughtReferenceIndex.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,MAAM,MAAM,0BAA0B,GACnC;IAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAA;CAAE,GAC5B;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAA;CAAE,GAC1D;IAAE,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAAC,QAAQ,CAAC,UAAU,EAAE,SAAS,SAAS,EAAE,CAAA;CAAE,CAAC;AAI7E,0EAA0E;AAC1E,qBAAa,qBAAqB;IACjC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA6D;IAEhF,GAAG,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,WAAW,GAAG,IAAI;IAUr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,SAAS,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,GAAG,0BAA0B;IAWhF,cAAc,CAAC,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,CAAC,WAAW,CAAC,GAAG,IAAI;IAiB3E,YAAY,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI;IAKxC,QAAQ,IAAI,IAAI;IAKvB,OAAO,CAAC,YAAY;IAMpB,OAAO,CAAC,eAAe;IASvB,OAAO,CAAC,aAAa;CASrB"}
@@ -3,6 +3,7 @@ const MISSING = Object.freeze({
3
3
  });
4
4
  class ThoughtReferenceIndex {
5
5
  _sessions = new Map();
6
+ _identities = new Map();
6
7
  add(sessionId, thought) {
7
8
  if (void 0 === thought.id) return;
8
9
  let session = this._sessions.get(sessionId);
@@ -11,6 +12,7 @@ class ThoughtReferenceIndex {
11
12
  this._sessions.set(sessionId, session);
12
13
  }
13
14
  this._addToSession(session, thought);
15
+ this._addIdentity(sessionId, thought.id);
14
16
  }
15
17
  remove(sessionId, thought) {
16
18
  if (void 0 === thought.id) return;
@@ -22,6 +24,10 @@ class ThoughtReferenceIndex {
22
24
  else bucket.delete(thought.id);
23
25
  if (0 === bucket.size) session.delete(thought.thought_number);
24
26
  if (0 === session.size) this._sessions.delete(sessionId);
27
+ this._removeIdentity(sessionId, thought.id);
28
+ }
29
+ has(sessionId, thoughtId) {
30
+ return this._identities.get(sessionId)?.has(thoughtId) === true;
25
31
  }
26
32
  resolve(sessionId, thoughtNumber) {
27
33
  const bucket = this._sessions.get(sessionId)?.get(thoughtNumber);
@@ -41,15 +47,36 @@ class ThoughtReferenceIndex {
41
47
  }
42
48
  replaceSession(sessionId, thoughts) {
43
49
  const replacement = new Map();
44
- for (const thought of thoughts)this._addToSession(replacement, thought);
50
+ const identities = new Map();
51
+ for (const thought of thoughts){
52
+ this._addToSession(replacement, thought);
53
+ if (void 0 !== thought.id) identities.set(thought.id, (identities.get(thought.id) ?? 0) + 1);
54
+ }
45
55
  if (0 === replacement.size) this._sessions.delete(sessionId);
46
56
  else this._sessions.set(sessionId, replacement);
57
+ if (0 === identities.size) this._identities.delete(sessionId);
58
+ else this._identities.set(sessionId, identities);
47
59
  }
48
60
  clearSession(sessionId) {
49
61
  this._sessions.delete(sessionId);
62
+ this._identities.delete(sessionId);
50
63
  }
51
64
  clearAll() {
52
65
  this._sessions.clear();
66
+ this._identities.clear();
67
+ }
68
+ _addIdentity(sessionId, thoughtId) {
69
+ const identities = this._identities.get(sessionId) ?? new Map();
70
+ identities.set(thoughtId, (identities.get(thoughtId) ?? 0) + 1);
71
+ this._identities.set(sessionId, identities);
72
+ }
73
+ _removeIdentity(sessionId, thoughtId) {
74
+ const identities = this._identities.get(sessionId);
75
+ const count = identities?.get(thoughtId);
76
+ if (void 0 === identities || void 0 === count) return;
77
+ if (count > 1) identities.set(thoughtId, count - 1);
78
+ else identities.delete(thoughtId);
79
+ if (0 === identities.size) this._identities.delete(sessionId);
53
80
  }
54
81
  _addToSession(session, thought) {
55
82
  if (void 0 === thought.id) return;
@@ -1 +1 @@
1
- {"version":3,"file":"core/ThoughtReferenceIndex.js","sources":["../../src/core/ThoughtReferenceIndex.ts"],"sourcesContent":["import type { SessionId, ThoughtId } from '../contracts/ids.js';\nimport type { ThoughtData } from './thought.js';\n\nexport type ThoughtReferenceResolution =\n\t| { readonly kind: 'missing' }\n\t| { readonly kind: 'unique'; readonly thoughtId: ThoughtId }\n\t| { readonly kind: 'ambiguous'; readonly thoughtIds: readonly ThoughtId[] };\n\nconst MISSING: ThoughtReferenceResolution = Object.freeze({ kind: 'missing' });\n\n/** Ref-counted stable-ID lookup for retained thoughts in each session. */\nexport class ThoughtReferenceIndex {\n\tprivate readonly _sessions = new Map<SessionId, Map<number, Map<ThoughtId, number>>>();\n\n\tpublic add(sessionId: SessionId, thought: ThoughtData): void {\n\t\tif (thought.id === undefined) return;\n\t\tlet session = this._sessions.get(sessionId);\n\t\tif (session === undefined) {\n\t\t\tsession = new Map();\n\t\t\tthis._sessions.set(sessionId, session);\n\t\t}\n\t\tthis._addToSession(session, thought);\n\t}\n\n\tpublic remove(sessionId: SessionId, thought: ThoughtData): void {\n\t\tif (thought.id === undefined) return;\n\t\tconst session = this._sessions.get(sessionId);\n\t\tconst bucket = session?.get(thought.thought_number);\n\t\tconst count = bucket?.get(thought.id);\n\t\tif (session === undefined || bucket === undefined || count === undefined) return;\n\t\tif (count > 1) {\n\t\t\tbucket.set(thought.id, count - 1);\n\t\t} else {\n\t\t\tbucket.delete(thought.id);\n\t\t}\n\t\tif (bucket.size === 0) session.delete(thought.thought_number);\n\t\tif (session.size === 0) this._sessions.delete(sessionId);\n\t}\n\n\tpublic resolve(sessionId: SessionId, thoughtNumber: number): ThoughtReferenceResolution {\n\t\tconst bucket = this._sessions.get(sessionId)?.get(thoughtNumber);\n\t\tif (bucket === undefined || bucket.size === 0) return MISSING;\n\t\tif (bucket.size === 1) {\n\t\t\tconst thoughtId = bucket.keys().next().value;\n\t\t\treturn thoughtId === undefined ? MISSING : { kind: 'unique', thoughtId };\n\t\t}\n\t\tconst thoughtIds = Object.freeze(Array.from(bucket.keys()).sort());\n\t\treturn Object.freeze({ kind: 'ambiguous', thoughtIds });\n\t}\n\n\tpublic replaceSession(sessionId: SessionId, thoughts: Iterable<ThoughtData>): void {\n\t\tconst replacement = new Map<number, Map<ThoughtId, number>>();\n\t\tfor (const thought of thoughts) this._addToSession(replacement, thought);\n\t\tif (replacement.size === 0) {\n\t\t\tthis._sessions.delete(sessionId);\n\t\t} else {\n\t\t\tthis._sessions.set(sessionId, replacement);\n\t\t}\n\t}\n\n\tpublic clearSession(sessionId: SessionId): void {\n\t\tthis._sessions.delete(sessionId);\n\t}\n\n\tpublic clearAll(): void {\n\t\tthis._sessions.clear();\n\t}\n\n\tprivate _addToSession(session: Map<number, Map<ThoughtId, number>>, thought: ThoughtData): void {\n\t\tif (thought.id === undefined) return;\n\t\tlet bucket = session.get(thought.thought_number);\n\t\tif (bucket === undefined) {\n\t\t\tbucket = new Map();\n\t\t\tsession.set(thought.thought_number, bucket);\n\t\t}\n\t\tbucket.set(thought.id, (bucket.get(thought.id) ?? 0) + 1);\n\t}\n}\n"],"names":["MISSING","Object","ThoughtReferenceIndex","Map","sessionId","thought","undefined","session","bucket","count","thoughtNumber","thoughtId","thoughtIds","Array","thoughts","replacement"],"mappings":"AAQA,MAAMA,UAAsCC,OAAO,MAAM,CAAC;IAAE,MAAM;AAAU;AAGrE,MAAMC;IACK,YAAY,IAAIC,MAAsD;IAEhF,IAAIC,SAAoB,EAAEC,OAAoB,EAAQ;QAC5D,IAAIA,AAAeC,WAAfD,QAAQ,EAAE,EAAgB;QAC9B,IAAIE,UAAU,IAAI,CAAC,SAAS,CAAC,GAAG,CAACH;QACjC,IAAIG,AAAYD,WAAZC,SAAuB;YAC1BA,UAAU,IAAIJ;YACd,IAAI,CAAC,SAAS,CAAC,GAAG,CAACC,WAAWG;QAC/B;QACA,IAAI,CAAC,aAAa,CAACA,SAASF;IAC7B;IAEO,OAAOD,SAAoB,EAAEC,OAAoB,EAAQ;QAC/D,IAAIA,AAAeC,WAAfD,QAAQ,EAAE,EAAgB;QAC9B,MAAME,UAAU,IAAI,CAAC,SAAS,CAAC,GAAG,CAACH;QACnC,MAAMI,SAASD,SAAS,IAAIF,QAAQ,cAAc;QAClD,MAAMI,QAAQD,QAAQ,IAAIH,QAAQ,EAAE;QACpC,IAAIE,AAAYD,WAAZC,WAAyBC,AAAWF,WAAXE,UAAwBC,AAAUH,WAAVG,OAAqB;QAC1E,IAAIA,QAAQ,GACXD,OAAO,GAAG,CAACH,QAAQ,EAAE,EAAEI,QAAQ;aAE/BD,OAAO,MAAM,CAACH,QAAQ,EAAE;QAEzB,IAAIG,AAAgB,MAAhBA,OAAO,IAAI,EAAQD,QAAQ,MAAM,CAACF,QAAQ,cAAc;QAC5D,IAAIE,AAAiB,MAAjBA,QAAQ,IAAI,EAAQ,IAAI,CAAC,SAAS,CAAC,MAAM,CAACH;IAC/C;IAEO,QA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AAG,CAACH,QAAQ,EAAE,KAAK,KAAK;IACxD;AACD"}
1
+ {"version":3,"file":"core/ThoughtReferenceIndex.js","sources":["../../src/core/ThoughtReferenceIndex.ts"],"sourcesContent":["import type { SessionId, ThoughtId } from '../contracts/ids.js';\nimport type { ThoughtData } from './thought.js';\n\nexport type ThoughtReferenceResolution =\n\t| { readonly kind: 'missing' }\n\t| { readonly kind: 'unique'; readonly thoughtId: ThoughtId }\n\t| { readonly kind: 'ambiguous'; readonly thoughtIds: readonly ThoughtId[] };\n\nconst MISSING: ThoughtReferenceResolution = Object.freeze({ kind: 'missing' });\n\n/** Ref-counted stable-ID lookup for retained thoughts in each session. */\nexport class ThoughtReferenceIndex {\n\tprivate readonly _sessions = new Map<SessionId, Map<number, Map<ThoughtId, number>>>();\n\tprivate readonly _identities = new Map<SessionId, Map<ThoughtId, number>>();\n\n\tpublic add(sessionId: SessionId, thought: ThoughtData): void {\n\t\tif (thought.id === undefined) return;\n\t\tlet session = this._sessions.get(sessionId);\n\t\tif (session === undefined) {\n\t\t\tsession = new Map();\n\t\t\tthis._sessions.set(sessionId, session);\n\t\t}\n\t\tthis._addToSession(session, thought);\n\t\tthis._addIdentity(sessionId, thought.id);\n\t}\n\n\tpublic remove(sessionId: SessionId, thought: ThoughtData): void {\n\t\tif (thought.id === undefined) return;\n\t\tconst session = this._sessions.get(sessionId);\n\t\tconst bucket = session?.get(thought.thought_number);\n\t\tconst count = bucket?.get(thought.id);\n\t\tif (session === undefined || bucket === undefined || count === undefined) return;\n\t\tif (count > 1) {\n\t\t\tbucket.set(thought.id, count - 1);\n\t\t} else {\n\t\t\tbucket.delete(thought.id);\n\t\t}\n\t\tif (bucket.size === 0) session.delete(thought.thought_number);\n\t\tif (session.size === 0) this._sessions.delete(sessionId);\n\t\tthis._removeIdentity(sessionId, thought.id);\n\t}\n\n\tpublic has(sessionId: SessionId, thoughtId: ThoughtId): boolean {\n\t\treturn this._identities.get(sessionId)?.has(thoughtId) === true;\n\t}\n\n\tpublic resolve(sessionId: SessionId, thoughtNumber: number): ThoughtReferenceResolution {\n\t\tconst bucket = this._sessions.get(sessionId)?.get(thoughtNumber);\n\t\tif (bucket === undefined || bucket.size === 0) return MISSING;\n\t\tif (bucket.size === 1) {\n\t\t\tconst thoughtId = bucket.keys().next().value;\n\t\t\treturn thoughtId === undefined ? MISSING : { kind: 'unique', thoughtId };\n\t\t}\n\t\tconst thoughtIds = Object.freeze(Array.from(bucket.keys()).sort());\n\t\treturn Object.freeze({ kind: 'ambiguous', thoughtIds });\n\t}\n\n\tpublic replaceSession(sessionId: SessionId, thoughts: Iterable<ThoughtData>): void {\n\t\tconst replacement = new Map<number, Map<ThoughtId, number>>();\n\t\tconst identities = new Map<ThoughtId, number>();\n\t\tfor (const thought of thoughts) {\n\t\t\tthis._addToSession(replacement, thought);\n\t\t\tif (thought.id !== undefined)\n\t\t\t\tidentities.set(thought.id, (identities.get(thought.id) ?? 0) + 1);\n\t\t}\n\t\tif (replacement.size === 0) {\n\t\t\tthis._sessions.delete(sessionId);\n\t\t} else {\n\t\t\tthis._sessions.set(sessionId, replacement);\n\t\t}\n\t\tif (identities.size === 0) this._identities.delete(sessionId);\n\t\telse this._identities.set(sessionId, identities);\n\t}\n\n\tpublic clearSession(sessionId: SessionId): void {\n\t\tthis._sessions.delete(sessionId);\n\t\tthis._identities.delete(sessionId);\n\t}\n\n\tpublic clearAll(): void {\n\t\tthis._sessions.clear();\n\t\tthis._identities.clear();\n\t}\n\n\tprivate _addIdentity(sessionId: SessionId, thoughtId: ThoughtId): void {\n\t\tconst identities = this._identities.get(sessionId) ?? new Map<ThoughtId, number>();\n\t\tidentities.set(thoughtId, (identities.get(thoughtId) ?? 0) + 1);\n\t\tthis._identities.set(sessionId, identities);\n\t}\n\n\tprivate _removeIdentity(sessionId: SessionId, thoughtId: ThoughtId): void {\n\t\tconst identities = this._identities.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._identities.delete(sessionId);\n\t}\n\n\tprivate _addToSession(session: Map<number, Map<ThoughtId, number>>, thought: ThoughtData): void {\n\t\tif (thought.id === undefined) return;\n\t\tlet bucket = session.get(thought.thought_number);\n\t\tif (bucket === undefined) {\n\t\t\tbucket = new Map();\n\t\t\tsession.set(thought.thought_number, bucket);\n\t\t}\n\t\tbucket.set(thought.id, (bucket.get(thought.id) ?? 0) + 1);\n\t}\n}\n"],"names":["MISSING","Object","ThoughtReferenceIndex","Map","sessionId","thought","undefined","session","bucket","count","thoughtId","thoughtNumber","thoughtIds","Array","thoughts","replacement","identities"],"mappings":"AAQA,MAAMA,UAAsCC,OAAO,MAAM,CAAC;IAAE,MAAM;AAAU;AAGrE,MAAMC;IACK,YAAY,IAAIC,MAAsD;IACtE,cAAc,IAAIA,MAAyC;IAErE,IAAIC,SAAoB,EAAEC,OAAoB,EAAQ;QAC5D,IAAIA,AAAeC,WAAfD,QAAQ,EAAE,EAAgB;QAC9B,IAAIE,UAAU,IAAI,CAAC,SAAS,CAAC,GAAG,CAACH;QACjC,IAAIG,AAAYD,WAAZC,SAAuB;YAC1BA,UAAU,IAAIJ;YACd,IAAI,CAAC,SAAS,CAAC,GAAG,CAACC,WAAWG;QAC/B;QACA,IAAI,CAAC,aAAa,CAACA,SAASF;QAC5B,IAAI,CAAC,YAAY,CAACD,WAAWC,QAAQ,EAAE;IACxC;IAEO,OAAOD,SAAoB,EAAEC,OAAoB,EAAQ;QAC/D,IAAIA,AAAeC,WAAfD,QAAQ,EAAE,EAAgB;QAC9B,MAAME,UAAU,IAAI,CAAC,SAAS,CAAC,GAAG,CAACH;QACnC,MAAMI,SAASD,SAAS,IAAIF,QAAQ,cAAc;QAClD,MAAMI,QAAQD,QAAQ,IAAIH,QAAQ,EAAE;QACpC,IAAIE,AAAYD,WAAZC,WAAyBC,AAAWF,WAAXE,UAAwBC,AAAUH,W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AeC,WAAfD,QAAQ,EAAE,EAAgB;QAC9B,IAAIG,SAASD,QAAQ,GAAG,CAACF,QAAQ,cAAc;QAC/C,IAAIG,AAAWF,WAAXE,QAAsB;YACzBA,SAAS,IAAIL;YACbI,QAAQ,GAAG,CAACF,QAAQ,cAAc,EAAEG;QACrC;QACAA,OAAO,GAAG,CAACH,QAAQ,EAAE,EAAGG,AAAAA,CAAAA,OAAO,GAAG,CAACH,QAAQ,EAAE,KAAK,KAAK;IACxD;AACD"}
@@ -9,7 +9,14 @@ interface VerificationOutcomeAdmissionContext {
9
9
  readonly sessionId: SessionId;
10
10
  readonly recorder?: IOutcomeRecorder;
11
11
  }
12
- /** Builds one immutable calibration sample from the retained pre-admission target. */
12
+ /**
13
+ * Builds one immutable calibration sample from the canonical retained pre-admission target.
14
+ *
15
+ * An explicit stable target resolved during admission is authoritative. Missing, ambiguous,
16
+ * id-less, or retracted targets fail closed before recorder side effects. Legacy label fallback
17
+ * is allowed only when it resolves one identity-bearing target. Outcome-key duplicate admission
18
+ * is separate from duplicate thought-ID admission.
19
+ */
13
20
  export declare function prepareVerificationOutcome(context: VerificationOutcomeAdmissionContext): Omit<VerificationOutcome, 'recordedAt'> | undefined;
14
21
  export {};
15
22
  //# sourceMappingURL=VerificationOutcomeAdmission.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"VerificationOutcomeAdmission.d.ts","sourceRoot":"","sources":["../../src/core/VerificationOutcomeAdmission.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAExF,OAAO,KAAK,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,UAAU,mCAAmC;IAC5C,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,sBAAsB,CAAC;IAC1C,QAAQ,CAAC,kBAAkB,EAAE,yBAAyB,CAAC;IACvD,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,QAAQ,CAAC,EAAE,gBAAgB,CAAC;CACrC;AAED,sFAAsF;AACtF,wBAAgB,0BAA0B,CACzC,OAAO,EAAE,mCAAmC,GAC1C,IAAI,CAAC,mBAAmB,EAAE,YAAY,CAAC,GAAG,SAAS,CA2BrD"}
1
+ {"version":3,"file":"VerificationOutcomeAdmission.d.ts","sourceRoot":"","sources":["../../src/core/VerificationOutcomeAdmission.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAExF,OAAO,KAAK,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,UAAU,mCAAmC;IAC5C,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,sBAAsB,CAAC;IAC1C,QAAQ,CAAC,kBAAkB,EAAE,yBAAyB,CAAC;IACvD,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,QAAQ,CAAC,EAAE,gBAAgB,CAAC;CACrC;AAED;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CACzC,OAAO,EAAE,mCAAmC,GAC1C,IAAI,CAAC,mBAAmB,EAAE,YAAY,CAAC,GAAG,SAAS,CA2BrD"}
@@ -1 +1 @@
1
- {"version":3,"file":"core/VerificationOutcomeAdmission.js","sources":["../../src/core/VerificationOutcomeAdmission.ts"],"sourcesContent":["import type { SessionId } from '../contracts/ids.js';\nimport type { IOutcomeRecorder, VerificationOutcome } from '../contracts/interfaces.js';\nimport { ValidationError } from '../errors.js';\nimport type { HistorySessionSnapshot, ResolvedThoughtReferences } from './IHistoryManager.js';\nimport type { ThoughtData } from './thought.js';\n\ninterface VerificationOutcomeAdmissionContext {\n\treadonly input: ThoughtData;\n\treadonly snapshot: HistorySessionSnapshot;\n\treadonly resolvedReferences: ResolvedThoughtReferences;\n\treadonly sessionId: SessionId;\n\treadonly recorder?: IOutcomeRecorder;\n}\n\n/** Builds one immutable calibration sample from the retained pre-admission target. */\nexport function prepareVerificationOutcome(\n\tcontext: VerificationOutcomeAdmissionContext\n): Omit<VerificationOutcome, 'recordedAt'> | undefined {\n\tconst { input, resolvedReferences, sessionId, snapshot, recorder } = context;\n\tif (input.thought_type !== 'verification' || input.verification_result === undefined) {\n\t\treturn undefined;\n\t}\n\tconst thoughtId = resolvedReferences.verificationTargetThoughtId;\n\tif (thoughtId === undefined) {\n\t\tthrow new ValidationError('verification_result', 'requires a retained verification_target');\n\t}\n\tconst target = findTarget(snapshot, thoughtId);\n\tif (target === undefined) {\n\t\tthrow new ValidationError('verification_result', 'verification_target is no longer retained');\n\t}\n\tif (target.retracted === true) {\n\t\tthrow new ValidationError('verification_result', 'verification_target must not be retracted');\n\t}\n\tif (target.confidence === undefined) {\n\t\tthrow new ValidationError('verification_result', 'verification_target must have confidence');\n\t}\n\trecorder?.assertCanRecord(sessionId, thoughtId);\n\treturn Object.freeze({\n\t\tthoughtId,\n\t\tsessionId,\n\t\tpredicted: target.confidence,\n\t\tactual: input.verification_result,\n\t\ttype: target.thought_type ?? 'regular',\n\t});\n}\n\nfunction findTarget(\n\tsnapshot: HistorySessionSnapshot,\n\tthoughtId: VerificationOutcome['thoughtId']\n): ThoughtData | undefined {\n\tfor (const thought of snapshot.history) {\n\t\tif (thought.id === thoughtId) return thought;\n\t}\n\tfor (const branch of Object.values(snapshot.branches)) {\n\t\tfor (const thought of branch) {\n\t\t\tif (thought.id === thoughtId) return thought;\n\t\t}\n\t}\n\treturn undefined;\n}\n"],"names":["prepareVerificationOutcome","context","input","resolvedReferences","sessionId","snapshot","recorder","undefined","thoughtId","ValidationError","target","findTarget","Object","thought","branch"],"mappings":";AAeO,SAASA,2BACfC,OAA4C;IAE5C,MAAM,EAAEC,KAAK,EAAEC,kBAAkB,EAAEC,SAAS,EAAEC,QAAQ,EAAEC,QAAQ,EAAE,GAAGL;IACrE,IAAIC,AAAuB,mBAAvBA,MAAM,YAAY,IAAuBA,AAA8BK,WAA9BL,MAAM,mBAAmB,EACrE;IAED,MAAMM,YAAYL,mBAAmB,2BAA2B;IAChE,IAAIK,AAAcD,WAAdC,WACH,MAAM,IAAIC,gBAAgB,uBAAuB;IAElD,MAAMC,SAASC,WAAWN,UAAUG;IACpC,IAAIE,AAAWH,WAAXG,QACH,MAAM,IAAID,gBAAgB,uBAAuB;IAElD,IAAIC,AAAqB,SAArBA,OAAO,SAAS,EACnB,MAAM,IAAID,gBAAgB,uBAAuB;IAElD,IAAIC,AAAsBH,WAAtBG,OAAO,UAAU,EACpB,MAAM,IAAID,gBAAgB,uBAAuB;IAElDH,UAAU,gBAAgBF,WAAWI;IACrC,OAAOI,OAAO,MAAM,CAAC;QACpBJ;QACAJ;QACA,WAAWM,OAAO,UAAU;QAC5B,QAAQR,MAAM,mBAAmB;QACjC,MAAMQ,OAAO,YAAY,IAAI;IAC9B;AACD;AAEA,SAASC,WACRN,QAAgC,EAChCG,SAA2C;IAE3C,KAAK,MAAMK,WAAWR,SAAS,OAAO,CACrC,IAAIQ,QAAQ,EAAE,KAAKL,WAAW,OAAOK;IAEtC,KAAK,MAAMC,UAAUF,OAAO,MAAM,CAACP,SAAS,QAAQ,EACnD,KAAK,MAAMQ,WAAWC,OACrB,IAAID,QAAQ,EAAE,KAAKL,WAAW,OAAOK;AAIxC"}
1
+ {"version":3,"file":"core/VerificationOutcomeAdmission.js","sources":["../../src/core/VerificationOutcomeAdmission.ts"],"sourcesContent":["import type { SessionId } from '../contracts/ids.js';\nimport type { IOutcomeRecorder, VerificationOutcome } from '../contracts/interfaces.js';\nimport { ValidationError } from '../errors.js';\nimport type { HistorySessionSnapshot, ResolvedThoughtReferences } from './IHistoryManager.js';\nimport type { ThoughtData } from './thought.js';\n\ninterface VerificationOutcomeAdmissionContext {\n\treadonly input: ThoughtData;\n\treadonly snapshot: HistorySessionSnapshot;\n\treadonly resolvedReferences: ResolvedThoughtReferences;\n\treadonly sessionId: SessionId;\n\treadonly recorder?: IOutcomeRecorder;\n}\n\n/**\n * Builds one immutable calibration sample from the canonical retained pre-admission target.\n *\n * An explicit stable target resolved during admission is authoritative. Missing, ambiguous,\n * id-less, or retracted targets fail closed before recorder side effects. Legacy label fallback\n * is allowed only when it resolves one identity-bearing target. Outcome-key duplicate admission\n * is separate from duplicate thought-ID admission.\n */\nexport function prepareVerificationOutcome(\n\tcontext: VerificationOutcomeAdmissionContext\n): Omit<VerificationOutcome, 'recordedAt'> | undefined {\n\tconst { input, resolvedReferences, sessionId, snapshot, recorder } = context;\n\tif (input.thought_type !== 'verification' || input.verification_result === undefined) {\n\t\treturn undefined;\n\t}\n\tconst thoughtId = resolvedReferences.verificationTargetThoughtId;\n\tif (thoughtId === undefined) {\n\t\tthrow new ValidationError('verification_result', 'requires a retained verification_target');\n\t}\n\tconst target = findTarget(snapshot, thoughtId);\n\tif (target === undefined) {\n\t\tthrow new ValidationError('verification_result', 'verification_target is no longer retained');\n\t}\n\tif (target.retracted === true) {\n\t\tthrow new ValidationError('verification_result', 'verification_target must not be retracted');\n\t}\n\tif (target.confidence === undefined) {\n\t\tthrow new ValidationError('verification_result', 'verification_target must have confidence');\n\t}\n\trecorder?.assertCanRecord(sessionId, thoughtId);\n\treturn Object.freeze({\n\t\tthoughtId,\n\t\tsessionId,\n\t\tpredicted: target.confidence,\n\t\tactual: input.verification_result,\n\t\ttype: target.thought_type ?? 'regular',\n\t});\n}\n\nfunction findTarget(\n\tsnapshot: HistorySessionSnapshot,\n\tthoughtId: VerificationOutcome['thoughtId']\n): ThoughtData | undefined {\n\tfor (const thought of snapshot.history) {\n\t\tif (thought.id === thoughtId) return thought;\n\t}\n\tfor (const branch of Object.values(snapshot.branches)) {\n\t\tfor (const thought of branch) {\n\t\t\tif (thought.id === thoughtId) return thought;\n\t\t}\n\t}\n\treturn undefined;\n}\n"],"names":["prepareVerificationOutcome","context","input","resolvedReferences","sessionId","snapshot","recorder","undefined","thoughtId","ValidationError","target","findTarget","Object","thought","branch"],"mappings":";AAsBO,SAASA,2BACfC,OAA4C;IAE5C,MAAM,EAAEC,KAAK,EAAEC,kBAAkB,EAAEC,SAAS,EAAEC,QAAQ,EAAEC,QAAQ,EAAE,GAAGL;IACrE,IAAIC,AAAuB,mBAAvBA,MAAM,YAAY,IAAuBA,AAA8BK,WAA9BL,MAAM,mBAAmB,EACrE;IAED,MAAMM,YAAYL,mBAAmB,2BAA2B;IAChE,IAAIK,AAAcD,WAAdC,WACH,MAAM,IAAIC,gBAAgB,uBAAuB;IAElD,MAAMC,SAASC,WAAWN,UAAUG;IACpC,IAAIE,AAAWH,WAAXG,QACH,MAAM,IAAID,gBAAgB,uBAAuB;IAElD,IAAIC,AAAqB,SAArBA,OAAO,SAAS,EACnB,MAAM,IAAID,gBAAgB,uBAAuB;IAElD,IAAIC,AAAsBH,WAAtBG,OAAO,UAAU,EACpB,MAAM,IAAID,gBAAgB,uBAAuB;IAElDH,UAAU,gBAAgBF,WAAWI;IACrC,OAAOI,OAAO,MAAM,CAAC;QACpBJ;QACAJ;QACA,WAAWM,OAAO,UAAU;QAC5B,QAAQR,MAAM,mBAAmB;QACjC,MAAMQ,OAAO,YAAY,IAAI;IAC9B;AACD;AAEA,SAASC,WACRN,QAAgC,EAChCG,SAA2C;IAE3C,KAAK,MAAMK,WAAWR,SAAS,OAAO,CACrC,IAAIQ,QAAQ,EAAE,KAAKL,WAAW,OAAOK;IAEtC,KAAK,MAAMC,UAAUF,OAAO,MAAM,CAACP,SAAS,QAAQ,EACnD,KAAK,MAAMQ,WAAWC,OACrB,IAAID,QAAQ,EAAE,KAAKL,WAAW,OAAOK;AAIxC"}
@@ -0,0 +1,5 @@
1
+ import type { SessionId, ThoughtId } from '../contracts/ids.js';
2
+ import type { RestoredBranch } from './PersistenceRestore.js';
3
+ import type { ThoughtData } from './thought.js';
4
+ export declare function reconstructVerificationTargets(sessionId: SessionId, history: readonly ThoughtData[], branches: readonly RestoredBranch[]): Map<ThoughtId, ThoughtId>;
5
+ //# sourceMappingURL=VerificationTargetRestore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"VerificationTargetRestore.d.ts","sourceRoot":"","sources":["../../src/core/VerificationTargetRestore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAEhE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAGhD,wBAAgB,8BAA8B,CAC7C,SAAS,EAAE,SAAS,EACpB,OAAO,EAAE,SAAS,WAAW,EAAE,EAC/B,QAAQ,EAAE,SAAS,cAAc,EAAE,GACjC,GAAG,CAAC,SAAS,EAAE,SAAS,CAAC,CAa3B"}
@@ -0,0 +1,61 @@
1
+ import { assertNever } from "../utils.js";
2
+ import { ThoughtReferenceIndex } from "./ThoughtReferenceIndex.js";
3
+ function reconstructVerificationTargets(sessionId, history, branches) {
4
+ const references = new ThoughtReferenceIndex();
5
+ const verificationTargets = new Map();
6
+ for (const thought of admissionOrder(history, branches)){
7
+ const verifierId = thought.id;
8
+ if (void 0 === verifierId) continue;
9
+ const targetId = restoredVerificationTarget(thought, sessionId, references);
10
+ if (void 0 !== targetId) verificationTargets.set(verifierId, targetId);
11
+ references.add(sessionId, thought);
12
+ }
13
+ return verificationTargets;
14
+ }
15
+ function admissionOrder(history, branches) {
16
+ const thoughts = [];
17
+ const identities = new Set();
18
+ for (const candidate of [
19
+ ...history,
20
+ ...branches.flatMap((branch)=>branch.thoughts)
21
+ ])if (!(!candidate.id || identities.has(candidate.id))) {
22
+ identities.add(candidate.id);
23
+ thoughts.push(candidate);
24
+ }
25
+ return thoughts;
26
+ }
27
+ function restoredVerificationTarget(thought, sessionId, references) {
28
+ const thoughtType = thought.thought_type ?? 'regular';
29
+ switch(thoughtType){
30
+ case 'verification':
31
+ {
32
+ if (void 0 === thought.verification_target) return;
33
+ const resolution = references.resolve(sessionId, thought.verification_target);
34
+ switch(resolution.kind){
35
+ case 'unique':
36
+ return resolution.thoughtId;
37
+ case 'missing':
38
+ case 'ambiguous':
39
+ return;
40
+ default:
41
+ return assertNever(resolution);
42
+ }
43
+ }
44
+ case 'regular':
45
+ case 'hypothesis':
46
+ case 'critique':
47
+ case 'synthesis':
48
+ case 'meta':
49
+ case 'tool_call':
50
+ case 'tool_observation':
51
+ case 'assumption':
52
+ case 'decomposition':
53
+ case 'backtrack':
54
+ return;
55
+ default:
56
+ return assertNever(thoughtType);
57
+ }
58
+ }
59
+ export { reconstructVerificationTargets };
60
+
61
+ //# sourceMappingURL=VerificationTargetRestore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core/VerificationTargetRestore.js","sources":["../../src/core/VerificationTargetRestore.ts"],"sourcesContent":["import type { SessionId, ThoughtId } from '../contracts/ids.js';\nimport { assertNever } from '../utils.js';\nimport type { RestoredBranch } from './PersistenceRestore.js';\nimport type { ThoughtData } from './thought.js';\nimport { ThoughtReferenceIndex } from './ThoughtReferenceIndex.js';\n\nexport function reconstructVerificationTargets(\n\tsessionId: SessionId,\n\thistory: readonly ThoughtData[],\n\tbranches: readonly RestoredBranch[]\n): Map<ThoughtId, ThoughtId> {\n\tconst references = new ThoughtReferenceIndex();\n\tconst verificationTargets = new Map<ThoughtId, ThoughtId>();\n\n\tfor (const thought of admissionOrder(history, branches)) {\n\t\tconst verifierId = thought.id;\n\t\tif (verifierId === undefined) continue;\n\t\tconst targetId = restoredVerificationTarget(thought, sessionId, references);\n\t\tif (targetId !== undefined) verificationTargets.set(verifierId, targetId);\n\t\treferences.add(sessionId, thought);\n\t}\n\n\treturn verificationTargets;\n}\n\nfunction admissionOrder(\n\thistory: readonly ThoughtData[],\n\tbranches: readonly RestoredBranch[]\n): readonly ThoughtData[] {\n\tconst thoughts: ThoughtData[] = [];\n\tconst identities = new Set<ThoughtId>();\n\tfor (const candidate of [...history, ...branches.flatMap((branch) => branch.thoughts)]) {\n\t\tif (!candidate.id || identities.has(candidate.id)) continue;\n\t\tidentities.add(candidate.id);\n\t\tthoughts.push(candidate);\n\t}\n\treturn thoughts;\n}\n\nfunction restoredVerificationTarget(\n\tthought: ThoughtData,\n\tsessionId: SessionId,\n\treferences: ThoughtReferenceIndex\n): ThoughtId | undefined {\n\tconst thoughtType = thought.thought_type ?? 'regular';\n\tswitch (thoughtType) {\n\t\tcase 'verification': {\n\t\t\tif (thought.verification_target === undefined) return undefined;\n\t\t\tconst resolution = references.resolve(sessionId, thought.verification_target);\n\t\t\tswitch (resolution.kind) {\n\t\t\t\tcase 'unique':\n\t\t\t\t\treturn resolution.thoughtId;\n\t\t\t\tcase 'missing':\n\t\t\t\tcase 'ambiguous':\n\t\t\t\t\treturn undefined;\n\t\t\t\tdefault:\n\t\t\t\t\treturn assertNever(resolution);\n\t\t\t}\n\t\t}\n\t\tcase 'regular':\n\t\tcase 'hypothesis':\n\t\tcase 'critique':\n\t\tcase 'synthesis':\n\t\tcase 'meta':\n\t\tcase 'tool_call':\n\t\tcase 'tool_observation':\n\t\tcase 'assumption':\n\t\tcase 'decomposition':\n\t\tcase 'backtrack':\n\t\t\treturn undefined;\n\t\tdefault:\n\t\t\treturn assertNever(thoughtType);\n\t}\n}\n"],"names":["reconstructVerificationTargets","sessionId","history","branches","references","ThoughtReferenceIndex","verificationTargets","Map","thought","admissionOrder","verifierId","undefined","targetId","restoredVerificationTarget","thoughts","identities","Set","candidate","branch","thoughtType","resolution","assertNever"],"mappings":";;AAMO,SAASA,+BAC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YAAYF;IACrB;AACD"}
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import type { ReasoningStats } from '../reasoning.js';
12
12
  import type { ThoughtData } from '../thought.js';
13
+ import type { VerificationLinks } from './VerificationLinks.js';
13
14
  /**
14
15
  * Stateless service that aggregates reasoning analytics from thought
15
16
  * history and branch data.
@@ -35,6 +36,6 @@ export declare class Aggregator {
35
36
  * @param branches - Map of branch IDs to their thought arrays
36
37
  * @returns Aggregated reasoning statistics for the session
37
38
  */
38
- computeReasoningStats(history: ThoughtData[], branches: Record<string, ThoughtData[]>): ReasoningStats;
39
+ computeReasoningStats(history: ThoughtData[], branches: Record<string, ThoughtData[]>, links: VerificationLinks): ReasoningStats;
39
40
  }
40
41
  //# sourceMappingURL=Aggregator.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Aggregator.d.ts","sourceRoot":"","sources":["../../../src/core/evaluator/Aggregator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAajD;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,UAAU;IACtB;;;;;;;OAOG;IACI,qBAAqB,CAC3B,OAAO,EAAE,WAAW,EAAE,EACtB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,EAAE,CAAC,GACrC,cAAc;CAwCjB"}
1
+ {"version":3,"file":"Aggregator.d.ts","sourceRoot":"","sources":["../../../src/core/evaluator/Aggregator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAEjD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAYhE;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,UAAU;IACtB;;;;;;;OAOG;IACI,qBAAqB,CAC3B,OAAO,EAAE,WAAW,EAAE,EACtB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,EAAE,CAAC,EACvC,KAAK,EAAE,iBAAiB,GACtB,cAAc;CA+BjB"}
@@ -4,16 +4,10 @@ function roundToPrecision(value, decimals = 10) {
4
4
  return Math.round(value * factor) / factor;
5
5
  }
6
6
  class Aggregator {
7
- computeReasoningStats(history, branches) {
7
+ computeReasoningStats(history, branches, links) {
8
8
  const typeCounts = _countByType(history);
9
9
  const allScores = history.map((t)=>t.quality_score).filter((s)=>void 0 !== s);
10
10
  const allConfidences = history.map((t)=>t.confidence).filter((c)=>void 0 !== c);
11
- const hypotheses = history.filter((t)=>'hypothesis' === t.thought_type);
12
- const hypothesisIds = new Set(hypotheses.map((t)=>t.hypothesis_id).filter(Boolean));
13
- const verifiedIds = new Set(history.filter((t)=>'verification' === t.thought_type && t.hypothesis_id).map((t)=>t.hypothesis_id));
14
- const unresolvedCount = [
15
- ...hypothesisIds
16
- ].filter((id)=>!verifiedIds.has(id)).length;
17
11
  return {
18
12
  total_thoughts: history.length,
19
13
  total_branches: Object.keys(branches).length,
@@ -21,11 +15,9 @@ class Aggregator {
21
15
  total_merges: history.filter((t)=>(t.merge_from_thoughts?.length ?? 0) > 0 || (t.merge_branch_ids?.length ?? 0) > 0).length,
22
16
  chain_depth: _computeChainDepth(history),
23
17
  thought_type_counts: typeCounts,
24
- hypothesis_count: hypothesisIds.size,
25
- verified_hypothesis_count: [
26
- ...hypothesisIds
27
- ].filter((id)=>verifiedIds.has(id)).length,
28
- unresolved_hypothesis_count: unresolvedCount,
18
+ hypothesis_count: links.hypotheses.length,
19
+ verified_hypothesis_count: links.verifiedHypothesisCount,
20
+ unresolved_hypothesis_count: links.hypotheses.length - links.verifiedHypothesisCount,
29
21
  average_quality_score: allScores.length > 0 ? roundToPrecision(allScores.reduce((a, b)=>a + b, 0) / allScores.length) : null,
30
22
  average_confidence: allConfidences.length > 0 ? roundToPrecision(allConfidences.reduce((a, b)=>a + b, 0) / allConfidences.length) : null
31
23
  };
@@ -1 +1 @@
1
- {"version":3,"file":"core/evaluator/Aggregator.js","sources":["../../../src/core/evaluator/Aggregator.ts"],"sourcesContent":["/**\n * Reasoning analytics aggregation.\n *\n * Provides the {@link Aggregator} class — a stateless service that computes\n * aggregated {@link ReasoningStats} from thought history and branch data.\n * Extracted from {@link ThoughtEvaluator} to isolate the stats-aggregation\n * concern.\n *\n * @module core/evaluator/Aggregator\n */\n\nimport type { ReasoningStats } from '../reasoning.js';\nimport type { ThoughtData } from '../thought.js';\nimport { _computeChainDepth, _countByType } from './internals.js';\n\n/**\n * Round a numeric value to a fixed number of decimal places to mitigate\n * IEEE 754 floating-point accumulation errors (e.g. 0.9 + 0.8 averaging to\n * 0.8500000000000001 instead of 0.85).\n */\nfunction roundToPrecision(value: number, decimals: number = 10): number {\n\tconst factor = Math.pow(10, decimals);\n\treturn Math.round(value * factor) / factor;\n}\n\n/**\n * Stateless service that aggregates reasoning analytics from thought\n * history and branch data.\n *\n * @remarks\n * All methods are pure computations — no side effects, no I/O, no\n * internal state. Designed to be registered as transient in the DI\n * container.\n *\n * @example\n * ```typescript\n * const aggregator = new Aggregator();\n * const stats = aggregator.computeReasoningStats(history, branches);\n * console.log(stats.total_thoughts); // 12\n * ```\n */\nexport class Aggregator {\n\t/**\n\t * Compute aggregated reasoning analytics.\n\t * Pure computation from history + branches.\n\t *\n\t * @param history - All thoughts in the current session\n\t * @param branches - Map of branch IDs to their thought arrays\n\t * @returns Aggregated reasoning statistics for the session\n\t */\n\tpublic computeReasoningStats(\n\t\thistory: ThoughtData[],\n\t\tbranches: Record<string, ThoughtData[]>\n\t): ReasoningStats {\n\t\tconst typeCounts = _countByType(history);\n\t\tconst allScores = history\n\t\t\t.map((t) => t.quality_score)\n\t\t\t.filter((s): s is number => s !== undefined);\n\t\tconst allConfidences = history\n\t\t\t.map((t) => t.confidence)\n\t\t\t.filter((c): c is number => c !== undefined);\n\n\t\tconst hypotheses = history.filter((t) => t.thought_type === 'hypothesis');\n\t\tconst hypothesisIds = new Set(hypotheses.map((t) => t.hypothesis_id).filter(Boolean));\n\t\tconst verifiedIds = new Set(\n\t\t\thistory\n\t\t\t\t.filter((t) => t.thought_type === 'verification' && t.hypothesis_id)\n\t\t\t\t.map((t) => t.hypothesis_id)\n\t\t);\n\t\tconst unresolvedCount = [...hypothesisIds].filter((id) => !verifiedIds.has(id)).length;\n\n\t\treturn {\n\t\t\ttotal_thoughts: history.length,\n\t\t\ttotal_branches: Object.keys(branches).length,\n\t\t\ttotal_revisions: history.filter((t) => t.is_revision).length,\n\t\t\ttotal_merges: history.filter(\n\t\t\t\t(t) => (t.merge_from_thoughts?.length ?? 0) > 0 || (t.merge_branch_ids?.length ?? 0) > 0\n\t\t\t).length,\n\t\t\tchain_depth: _computeChainDepth(history),\n\t\t\tthought_type_counts: typeCounts,\n\t\t\thypothesis_count: hypothesisIds.size,\n\t\t\tverified_hypothesis_count: [...hypothesisIds].filter((id) => verifiedIds.has(id)).length,\n\t\t\tunresolved_hypothesis_count: unresolvedCount,\n\t\t\taverage_quality_score:\n\t\t\t\tallScores.length > 0\n\t\t\t\t\t? roundToPrecision(allScores.reduce((a, b) => a + b, 0) / allScores.length)\n\t\t\t\t\t: null,\n\t\t\taverage_confidence:\n\t\t\t\tallConfidences.length > 0\n\t\t\t\t\t? roundToPrecision(allConfidences.reduce((a, b) => a + b, 0) / allConfidences.length)\n\t\t\t\t\t: null,\n\t\t};\n\t}\n}\n"],"names":["roundToPrecision","value","decimals","factor","Math","Aggregator","history","branches","typeCounts","_countByType","allScores","t","s","undefined","allConfidences","c","hypotheses","hypothesisIds","Set","Boolean","verifiedIds","unresolvedCount","id","Object","_computeChainDepth","a","b"],"mappings":";AAoBA,SAASA,iBAAiBC,KAAa,EAAEC,WAAmB,EAAE;IAC7D,MAAMC,SAASC,KAAK,GAAG,CAAC,IAAIF;IAC5B,OAAOE,KAAK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F,YAAY,GAAG,CAACE,KAAK,MAAM;YACxF,6BAA6BD;YAC7B,uBACCX,UAAU,MAAM,GAAG,IAChBV,iBAAiBU,UAAU,MAAM,CAAC,CAACe,GAAGC,IAAMD,IAAIC,GAAG,KAAKhB,UAAU,MAAM,IACxE;YACJ,oBACCI,eAAe,MAAM,GAAG,IACrBd,iBAAiBc,eAAe,MAAM,CAAC,CAACW,GAAGC,IAAMD,IAAIC,GAAG,KAAKZ,eAAe,MAAM,IAClF;QACL;IACD;AACD"}
1
+ {"version":3,"file":"core/evaluator/Aggregator.js","sources":["../../../src/core/evaluator/Aggregator.ts"],"sourcesContent":["/**\n * Reasoning analytics aggregation.\n *\n * Provides the {@link Aggregator} class — a stateless service that computes\n * aggregated {@link ReasoningStats} from thought history and branch data.\n * Extracted from {@link ThoughtEvaluator} to isolate the stats-aggregation\n * concern.\n *\n * @module core/evaluator/Aggregator\n */\n\nimport type { ReasoningStats } from '../reasoning.js';\nimport type { ThoughtData } from '../thought.js';\nimport { _computeChainDepth, _countByType } from './internals.js';\nimport type { VerificationLinks } from './VerificationLinks.js';\n\n/**\n * Round a numeric value to a fixed number of decimal places to mitigate\n * IEEE 754 floating-point accumulation errors (e.g. 0.9 + 0.8 averaging to\n * 0.8500000000000001 instead of 0.85).\n */\nfunction roundToPrecision(value: number, decimals: number = 10): number {\n\tconst factor = Math.pow(10, decimals);\n\treturn Math.round(value * factor) / factor;\n}\n\n/**\n * Stateless service that aggregates reasoning analytics from thought\n * history and branch data.\n *\n * @remarks\n * All methods are pure computations — no side effects, no I/O, no\n * internal state. Designed to be registered as transient in the DI\n * container.\n *\n * @example\n * ```typescript\n * const aggregator = new Aggregator();\n * const stats = aggregator.computeReasoningStats(history, branches);\n * console.log(stats.total_thoughts); // 12\n * ```\n */\nexport class Aggregator {\n\t/**\n\t * Compute aggregated reasoning analytics.\n\t * Pure computation from history + branches.\n\t *\n\t * @param history - All thoughts in the current session\n\t * @param branches - Map of branch IDs to their thought arrays\n\t * @returns Aggregated reasoning statistics for the session\n\t */\n\tpublic computeReasoningStats(\n\t\thistory: ThoughtData[],\n\t\tbranches: Record<string, ThoughtData[]>,\n\t\tlinks: VerificationLinks\n\t): ReasoningStats {\n\t\tconst typeCounts = _countByType(history);\n\t\tconst allScores = history\n\t\t\t.map((t) => t.quality_score)\n\t\t\t.filter((s): s is number => s !== undefined);\n\t\tconst allConfidences = history\n\t\t\t.map((t) => t.confidence)\n\t\t\t.filter((c): c is number => c !== undefined);\n\n\t\treturn {\n\t\t\ttotal_thoughts: history.length,\n\t\t\ttotal_branches: Object.keys(branches).length,\n\t\t\ttotal_revisions: history.filter((t) => t.is_revision).length,\n\t\t\ttotal_merges: history.filter(\n\t\t\t\t(t) => (t.merge_from_thoughts?.length ?? 0) > 0 || (t.merge_branch_ids?.length ?? 0) > 0\n\t\t\t).length,\n\t\t\tchain_depth: _computeChainDepth(history),\n\t\t\tthought_type_counts: typeCounts,\n\t\t\thypothesis_count: links.hypotheses.length,\n\t\t\tverified_hypothesis_count: links.verifiedHypothesisCount,\n\t\t\tunresolved_hypothesis_count: links.hypotheses.length - links.verifiedHypothesisCount,\n\t\t\taverage_quality_score:\n\t\t\t\tallScores.length > 0\n\t\t\t\t\t? roundToPrecision(allScores.reduce((a, b) => a + b, 0) / allScores.length)\n\t\t\t\t\t: null,\n\t\t\taverage_confidence:\n\t\t\t\tallConfidences.length > 0\n\t\t\t\t\t? roundToPrecision(allConfidences.reduce((a, b) => a + b, 0) / allConfidences.length)\n\t\t\t\t\t: null,\n\t\t};\n\t}\n}\n"],"names":["roundToPrecision","value","decimals","factor","Math","Aggregator","history","branches","links","typeCounts","_countByType","allScores","t","s","undefined","allConfidences","c","Object","_computeChainDepth","a","b"],"mappings":";AAqBA,SAASA,iBAAiBC,KAAa,EAAEC,WAAmB,EAAE;IAC7D,MAAMC,SAASC,KAAK,GAAG,CAAC,IAAIF;IAC5B,OAAOE,KAAK,KAAK,CAACH,QAAQE,UAAUA;AACrC;AAkBO,MA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