tracelattice 1.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +24 -0
- package/README.md +112 -0
- package/dist/ServerConfig.d.ts +229 -0
- package/dist/ServerConfig.d.ts.map +1 -0
- package/dist/ServerConfig.js +121 -0
- package/dist/ServerConfig.js.map +1 -0
- package/dist/__tests__/base-registry.test.d.ts +2 -0
- package/dist/__tests__/base-registry.test.d.ts.map +1 -0
- package/dist/__tests__/base-transport-cov.test.d.ts +2 -0
- package/dist/__tests__/base-transport-cov.test.d.ts.map +1 -0
- package/dist/__tests__/base-transport.test.d.ts +2 -0
- package/dist/__tests__/base-transport.test.d.ts.map +1 -0
- package/dist/__tests__/config-loader.test.d.ts +2 -0
- package/dist/__tests__/config-loader.test.d.ts.map +1 -0
- package/dist/__tests__/connection-pool-cov.test.d.ts +2 -0
- package/dist/__tests__/connection-pool-cov.test.d.ts.map +1 -0
- package/dist/__tests__/connection-pool.test.d.ts +2 -0
- package/dist/__tests__/connection-pool.test.d.ts.map +1 -0
- package/dist/__tests__/container.test.d.ts +2 -0
- package/dist/__tests__/container.test.d.ts.map +1 -0
- package/dist/__tests__/crud.test.d.ts +2 -0
- package/dist/__tests__/crud.test.d.ts.map +1 -0
- package/dist/__tests__/discovery-cache.test.d.ts +2 -0
- package/dist/__tests__/discovery-cache.test.d.ts.map +1 -0
- package/dist/__tests__/errors.test.d.ts +2 -0
- package/dist/__tests__/errors.test.d.ts.map +1 -0
- package/dist/__tests__/factories.test.d.ts +2 -0
- package/dist/__tests__/factories.test.d.ts.map +1 -0
- package/dist/__tests__/health-checker-cov.test.d.ts +2 -0
- package/dist/__tests__/health-checker-cov.test.d.ts.map +1 -0
- package/dist/__tests__/health-checker.test.d.ts +2 -0
- package/dist/__tests__/health-checker.test.d.ts.map +1 -0
- package/dist/__tests__/helpers/factories.d.ts +36 -0
- package/dist/__tests__/helpers/factories.d.ts.map +1 -0
- package/dist/__tests__/helpers/index.d.ts +3 -0
- package/dist/__tests__/helpers/index.d.ts.map +1 -0
- package/dist/__tests__/helpers/timers.d.ts +4 -0
- package/dist/__tests__/helpers/timers.d.ts.map +1 -0
- package/dist/__tests__/history-manager.test.d.ts +2 -0
- package/dist/__tests__/history-manager.test.d.ts.map +1 -0
- package/dist/__tests__/http-helpers-cov.test.d.ts +2 -0
- package/dist/__tests__/http-helpers-cov.test.d.ts.map +1 -0
- package/dist/__tests__/http-transport-cov.test.d.ts +2 -0
- package/dist/__tests__/http-transport-cov.test.d.ts.map +1 -0
- package/dist/__tests__/http-transport.test.d.ts +2 -0
- package/dist/__tests__/http-transport.test.d.ts.map +1 -0
- package/dist/__tests__/input-normalizer.test.d.ts +8 -0
- package/dist/__tests__/input-normalizer.test.d.ts.map +1 -0
- package/dist/__tests__/integration.test.d.ts +2 -0
- package/dist/__tests__/integration.test.d.ts.map +1 -0
- package/dist/__tests__/lib-server.test.d.ts +2 -0
- package/dist/__tests__/lib-server.test.d.ts.map +1 -0
- package/dist/__tests__/memory-persistence.test.d.ts +2 -0
- package/dist/__tests__/memory-persistence.test.d.ts.map +1 -0
- package/dist/__tests__/metrics-integration.test.d.ts +2 -0
- package/dist/__tests__/metrics-integration.test.d.ts.map +1 -0
- package/dist/__tests__/persistence.test.d.ts +2 -0
- package/dist/__tests__/persistence.test.d.ts.map +1 -0
- package/dist/__tests__/reasoning-integration.test.d.ts +11 -0
- package/dist/__tests__/reasoning-integration.test.d.ts.map +1 -0
- package/dist/__tests__/reasoning-types.test.d.ts +2 -0
- package/dist/__tests__/reasoning-types.test.d.ts.map +1 -0
- package/dist/__tests__/request-context.test.d.ts +2 -0
- package/dist/__tests__/request-context.test.d.ts.map +1 -0
- package/dist/__tests__/sanitize.test.d.ts +2 -0
- package/dist/__tests__/sanitize.test.d.ts.map +1 -0
- package/dist/__tests__/schema.test.d.ts +2 -0
- package/dist/__tests__/schema.test.d.ts.map +1 -0
- package/dist/__tests__/sequentialthinking-tools.test.d.ts +2 -0
- package/dist/__tests__/sequentialthinking-tools.test.d.ts.map +1 -0
- package/dist/__tests__/server-config.test.d.ts +2 -0
- package/dist/__tests__/server-config.test.d.ts.map +1 -0
- package/dist/__tests__/skill-discovery.test.d.ts +2 -0
- package/dist/__tests__/skill-discovery.test.d.ts.map +1 -0
- package/dist/__tests__/skill-registry.test.d.ts +2 -0
- package/dist/__tests__/skill-registry.test.d.ts.map +1 -0
- package/dist/__tests__/skill-watcher.test.d.ts +2 -0
- package/dist/__tests__/skill-watcher.test.d.ts.map +1 -0
- package/dist/__tests__/sqlite-persistence.test.d.ts +2 -0
- package/dist/__tests__/sqlite-persistence.test.d.ts.map +1 -0
- package/dist/__tests__/sse-transport-cov.test.d.ts +2 -0
- package/dist/__tests__/sse-transport-cov.test.d.ts.map +1 -0
- package/dist/__tests__/sse-transport.test.d.ts +2 -0
- package/dist/__tests__/sse-transport.test.d.ts.map +1 -0
- package/dist/__tests__/streamable-http-cov.test.d.ts +2 -0
- package/dist/__tests__/streamable-http-cov.test.d.ts.map +1 -0
- package/dist/__tests__/streamable-http-transport.test.d.ts +2 -0
- package/dist/__tests__/streamable-http-transport.test.d.ts.map +1 -0
- package/dist/__tests__/structured-logger.test.d.ts +2 -0
- package/dist/__tests__/structured-logger.test.d.ts.map +1 -0
- package/dist/__tests__/thought-evaluator.test.d.ts +2 -0
- package/dist/__tests__/thought-evaluator.test.d.ts.map +1 -0
- package/dist/__tests__/thought-formatter.test.d.ts +2 -0
- package/dist/__tests__/thought-formatter.test.d.ts.map +1 -0
- package/dist/__tests__/thought-processor.test.d.ts +8 -0
- package/dist/__tests__/thought-processor.test.d.ts.map +1 -0
- package/dist/__tests__/tool-registry-cov.test.d.ts +2 -0
- package/dist/__tests__/tool-registry-cov.test.d.ts.map +1 -0
- package/dist/__tests__/tool-registry.test.d.ts +2 -0
- package/dist/__tests__/tool-registry.test.d.ts.map +1 -0
- package/dist/__tests__/tool-watcher.test.d.ts +2 -0
- package/dist/__tests__/tool-watcher.test.d.ts.map +1 -0
- package/dist/__tests__/worker-manager-cov.test.d.ts +2 -0
- package/dist/__tests__/worker-manager-cov.test.d.ts.map +1 -0
- package/dist/__tests__/worker-manager.test.d.ts +2 -0
- package/dist/__tests__/worker-manager.test.d.ts.map +1 -0
- package/dist/cache/DiscoveryCache.d.ts +269 -0
- package/dist/cache/DiscoveryCache.d.ts.map +1 -0
- package/dist/cache/DiscoveryCache.js +100 -0
- package/dist/cache/DiscoveryCache.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +114 -0
- package/dist/cli.js.map +1 -0
- package/dist/cluster/WorkerManager.d.ts +166 -0
- package/dist/cluster/WorkerManager.d.ts.map +1 -0
- package/dist/cluster/WorkerManager.js +202 -0
- package/dist/cluster/WorkerManager.js.map +1 -0
- package/dist/cluster/worker.d.ts +11 -0
- package/dist/cluster/worker.d.ts.map +1 -0
- package/dist/cluster/worker.js +36 -0
- package/dist/cluster/worker.js.map +1 -0
- package/dist/config/ConfigLoader.d.ts +224 -0
- package/dist/config/ConfigLoader.d.ts.map +1 -0
- package/dist/config/ConfigLoader.js +85 -0
- package/dist/config/ConfigLoader.js.map +1 -0
- package/dist/context/RequestContext.d.ts +61 -0
- package/dist/context/RequestContext.d.ts.map +1 -0
- package/dist/context/RequestContext.js +17 -0
- package/dist/context/RequestContext.js.map +1 -0
- package/dist/contracts/index.d.ts +10 -0
- package/dist/contracts/index.d.ts.map +1 -0
- package/dist/contracts/index.js +1 -0
- package/dist/contracts/interfaces.d.ts +107 -0
- package/dist/contracts/interfaces.d.ts.map +1 -0
- package/dist/contracts/interfaces.js +1 -0
- package/dist/core/HistoryManager.d.ts +514 -0
- package/dist/core/HistoryManager.d.ts.map +1 -0
- package/dist/core/HistoryManager.js +331 -0
- package/dist/core/HistoryManager.js.map +1 -0
- package/dist/core/IHistoryManager.d.ts +100 -0
- package/dist/core/IHistoryManager.d.ts.map +1 -0
- package/dist/core/IHistoryManager.js +1 -0
- package/dist/core/InputNormalizer.d.ts +139 -0
- package/dist/core/InputNormalizer.d.ts.map +1 -0
- package/dist/core/InputNormalizer.js +101 -0
- package/dist/core/InputNormalizer.js.map +1 -0
- package/dist/core/ThoughtEvaluator.d.ts +127 -0
- package/dist/core/ThoughtEvaluator.d.ts.map +1 -0
- package/dist/core/ThoughtEvaluator.js +346 -0
- package/dist/core/ThoughtEvaluator.js.map +1 -0
- package/dist/core/ThoughtFormatter.d.ts +133 -0
- package/dist/core/ThoughtFormatter.d.ts.map +1 -0
- package/dist/core/ThoughtFormatter.js +70 -0
- package/dist/core/ThoughtFormatter.js.map +1 -0
- package/dist/core/ThoughtProcessor.d.ts +218 -0
- package/dist/core/ThoughtProcessor.d.ts.map +1 -0
- package/dist/core/ThoughtProcessor.js +205 -0
- package/dist/core/ThoughtProcessor.js.map +1 -0
- package/dist/core/reasoning.d.ts +169 -0
- package/dist/core/reasoning.d.ts.map +1 -0
- package/dist/core/reasoning.js +1 -0
- package/dist/core/step.d.ts +45 -0
- package/dist/core/step.d.ts.map +1 -0
- package/dist/core/step.js +1 -0
- package/dist/core/thought.d.ts +190 -0
- package/dist/core/thought.d.ts.map +1 -0
- package/dist/core/thought.js +1 -0
- package/dist/di/Container.d.ts +226 -0
- package/dist/di/Container.d.ts.map +1 -0
- package/dist/di/Container.js +96 -0
- package/dist/di/Container.js.map +1 -0
- package/dist/di/ServiceRegistry.d.ts +32 -0
- package/dist/di/ServiceRegistry.d.ts.map +1 -0
- package/dist/di/ServiceRegistry.js +1 -0
- package/dist/errors.d.ts +482 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +108 -0
- package/dist/errors.js.map +1 -0
- package/dist/health/HealthChecker.d.ts +73 -0
- package/dist/health/HealthChecker.d.ts.map +1 -0
- package/dist/health/HealthChecker.js +69 -0
- package/dist/health/HealthChecker.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1 -0
- package/dist/lib.d.ts +205 -0
- package/dist/lib.d.ts.map +1 -0
- package/dist/lib.js +219 -0
- package/dist/lib.js.map +1 -0
- package/dist/logger/NullLogger.d.ts +154 -0
- package/dist/logger/NullLogger.d.ts.map +1 -0
- package/dist/logger/NullLogger.js +24 -0
- package/dist/logger/NullLogger.js.map +1 -0
- package/dist/logger/StructuredLogger.d.ts +327 -0
- package/dist/logger/StructuredLogger.d.ts.map +1 -0
- package/dist/logger/StructuredLogger.js +72 -0
- package/dist/logger/StructuredLogger.js.map +1 -0
- package/dist/metrics/__tests__/metrics.test.d.ts +2 -0
- package/dist/metrics/__tests__/metrics.test.d.ts.map +1 -0
- package/dist/metrics/metrics.impl.d.ts +252 -0
- package/dist/metrics/metrics.impl.d.ts.map +1 -0
- package/dist/metrics/metrics.impl.js +197 -0
- package/dist/metrics/metrics.impl.js.map +1 -0
- package/dist/persistence/FilePersistence.d.ts +66 -0
- package/dist/persistence/FilePersistence.d.ts.map +1 -0
- package/dist/persistence/FilePersistence.js +132 -0
- package/dist/persistence/FilePersistence.js.map +1 -0
- package/dist/persistence/MemoryPersistence.d.ts +68 -0
- package/dist/persistence/MemoryPersistence.d.ts.map +1 -0
- package/dist/persistence/MemoryPersistence.js +51 -0
- package/dist/persistence/MemoryPersistence.js.map +1 -0
- package/dist/persistence/PersistenceBackend.d.ts +69 -0
- package/dist/persistence/PersistenceBackend.d.ts.map +1 -0
- package/dist/persistence/PersistenceBackend.js +1 -0
- package/dist/persistence/PersistenceFactory.d.ts +21 -0
- package/dist/persistence/PersistenceFactory.d.ts.map +1 -0
- package/dist/persistence/PersistenceFactory.js +25 -0
- package/dist/persistence/PersistenceFactory.js.map +1 -0
- package/dist/persistence/SqlitePersistence.d.ts +60 -0
- package/dist/persistence/SqlitePersistence.d.ts.map +1 -0
- package/dist/persistence/SqlitePersistence.js +136 -0
- package/dist/persistence/SqlitePersistence.js.map +1 -0
- package/dist/pool/ConnectionPool.d.ts +215 -0
- package/dist/pool/ConnectionPool.d.ts.map +1 -0
- package/dist/pool/ConnectionPool.js +187 -0
- package/dist/pool/ConnectionPool.js.map +1 -0
- package/dist/registry/BaseRegistry.d.ts +203 -0
- package/dist/registry/BaseRegistry.d.ts.map +1 -0
- package/dist/registry/BaseRegistry.js +165 -0
- package/dist/registry/BaseRegistry.js.map +1 -0
- package/dist/registry/SkillRegistry.d.ts +69 -0
- package/dist/registry/SkillRegistry.d.ts.map +1 -0
- package/dist/registry/SkillRegistry.js +88 -0
- package/dist/registry/SkillRegistry.js.map +1 -0
- package/dist/registry/ToolRegistry.d.ts +69 -0
- package/dist/registry/ToolRegistry.d.ts.map +1 -0
- package/dist/registry/ToolRegistry.js +93 -0
- package/dist/registry/ToolRegistry.js.map +1 -0
- package/dist/sanitize.d.ts +63 -0
- package/dist/sanitize.d.ts.map +1 -0
- package/dist/sanitize.js +14 -0
- package/dist/sanitize.js.map +1 -0
- package/dist/schema.d.ts +531 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +204 -0
- package/dist/schema.js.map +1 -0
- package/dist/telemetry/Telemetry.d.ts +36 -0
- package/dist/telemetry/Telemetry.d.ts.map +1 -0
- package/dist/telemetry/Telemetry.js +68 -0
- package/dist/telemetry/Telemetry.js.map +1 -0
- package/dist/telemetry/__tests__/Telemetry.test.d.ts +2 -0
- package/dist/telemetry/__tests__/Telemetry.test.d.ts.map +1 -0
- package/dist/transport/BaseTransport.d.ts +184 -0
- package/dist/transport/BaseTransport.d.ts.map +1 -0
- package/dist/transport/BaseTransport.js +200 -0
- package/dist/transport/BaseTransport.js.map +1 -0
- package/dist/transport/HttpHelpers.d.ts +60 -0
- package/dist/transport/HttpHelpers.d.ts.map +1 -0
- package/dist/transport/HttpHelpers.js +50 -0
- package/dist/transport/HttpHelpers.js.map +1 -0
- package/dist/transport/HttpTransport.d.ts +134 -0
- package/dist/transport/HttpTransport.d.ts.map +1 -0
- package/dist/transport/HttpTransport.js +175 -0
- package/dist/transport/HttpTransport.js.map +1 -0
- package/dist/transport/SseTransport.d.ts +133 -0
- package/dist/transport/SseTransport.d.ts.map +1 -0
- package/dist/transport/SseTransport.js +318 -0
- package/dist/transport/SseTransport.js.map +1 -0
- package/dist/transport/StreamableHttpTransport.d.ts +224 -0
- package/dist/transport/StreamableHttpTransport.d.ts.map +1 -0
- package/dist/transport/StreamableHttpTransport.js +407 -0
- package/dist/transport/StreamableHttpTransport.js.map +1 -0
- package/dist/types/disposable.d.ts +22 -0
- package/dist/types/disposable.d.ts.map +1 -0
- package/dist/types/disposable.js +1 -0
- package/dist/types/server-config.d.ts +32 -0
- package/dist/types/server-config.d.ts.map +1 -0
- package/dist/types/server-config.js +1 -0
- package/dist/types/skill.d.ts +69 -0
- package/dist/types/skill.d.ts.map +1 -0
- package/dist/types/skill.js +1 -0
- package/dist/types/tool.d.ts +68 -0
- package/dist/types/tool.d.ts.map +1 -0
- package/dist/types/tool.js +1 -0
- package/dist/watchers/SkillWatcher.d.ts +132 -0
- package/dist/watchers/SkillWatcher.d.ts.map +1 -0
- package/dist/watchers/SkillWatcher.js +73 -0
- package/dist/watchers/SkillWatcher.js.map +1 -0
- package/dist/watchers/ToolWatcher.d.ts +109 -0
- package/dist/watchers/ToolWatcher.d.ts.map +1 -0
- package/dist/watchers/ToolWatcher.js +71 -0
- package/dist/watchers/ToolWatcher.js.map +1 -0
- package/package.json +95 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core thought processing logic and validation.
|
|
3
|
+
*
|
|
4
|
+
* This module provides the `ThoughtProcessor` class which handles the main
|
|
5
|
+
* sequential thinking request processing pipeline, including input validation,
|
|
6
|
+
* history management, and response formatting.
|
|
7
|
+
*
|
|
8
|
+
* @module processor
|
|
9
|
+
*/
|
|
10
|
+
import type { Logger } from '../logger/StructuredLogger.js';
|
|
11
|
+
import type { IHistoryManager } from './IHistoryManager.js';
|
|
12
|
+
import type { ThoughtData } from './thought.js';
|
|
13
|
+
import type { ThoughtEvaluator } from './ThoughtEvaluator.js';
|
|
14
|
+
import { ThoughtFormatter } from './ThoughtFormatter.js';
|
|
15
|
+
/**
|
|
16
|
+
* The return type expected by MCP tool invocations.
|
|
17
|
+
*
|
|
18
|
+
* This structure matches the MCP protocol for tool results,
|
|
19
|
+
* supporting both success and error responses.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```typescript
|
|
23
|
+
* const successResult: CallToolResult = {
|
|
24
|
+
* content: [{ type: 'text', text: '{"status":"success"}' }]
|
|
25
|
+
* };
|
|
26
|
+
*
|
|
27
|
+
* const errorResult: CallToolResult = {
|
|
28
|
+
* content: [{ type: 'text', text: '{"error":"Something went wrong"}' }],
|
|
29
|
+
* isError: true
|
|
30
|
+
* };
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export interface CallToolResult {
|
|
34
|
+
/** Array of content blocks (typically text) to return to the client. */
|
|
35
|
+
content: Array<{
|
|
36
|
+
type: 'text';
|
|
37
|
+
text: string;
|
|
38
|
+
}>;
|
|
39
|
+
/** Whether this result represents an error condition. */
|
|
40
|
+
isError?: boolean;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Core processor for sequential thinking requests.
|
|
44
|
+
*
|
|
45
|
+
* This class handles the main processing pipeline for thought requests,
|
|
46
|
+
* coordinating between history management, validation, and response formatting.
|
|
47
|
+
* It serves as the central entry point for the sequential thinking tool.
|
|
48
|
+
*
|
|
49
|
+
* @remarks
|
|
50
|
+
* **Processing Pipeline:**
|
|
51
|
+
* 1. Validate and normalize the input thought
|
|
52
|
+
* 2. Add the thought to history (triggers auto-trimming if needed)
|
|
53
|
+
* 3. Format the thought for logging/display
|
|
54
|
+
* 4. Compute quality signals via ThoughtEvaluator
|
|
55
|
+
* 5. Return structured response with metadata and reasoning enrichment
|
|
56
|
+
*
|
|
57
|
+
* **Validation Rules:**
|
|
58
|
+
* - `thought_number` must be >= 1
|
|
59
|
+
* - `total_thoughts` must be >= 1
|
|
60
|
+
* - If `thought_number > total_thoughts`, `total_thoughts` is auto-adjusted
|
|
61
|
+
*
|
|
62
|
+
* **Error Handling:**
|
|
63
|
+
* All errors are caught and returned as formatted error responses
|
|
64
|
+
* with `isError: true` set, preventing crashes from malformed input.
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```typescript
|
|
68
|
+
* const processor = new ThoughtProcessor(historyManager, formatter, new ThoughtEvaluator());
|
|
69
|
+
*
|
|
70
|
+
* const result = await processor.process({
|
|
71
|
+
* thought: 'I need to analyze the codebase structure',
|
|
72
|
+
* thought_number: 1,
|
|
73
|
+
* total_thoughts: 5,
|
|
74
|
+
* next_thought_needed: true,
|
|
75
|
+
* available_mcp_tools: ['Read', 'Grep', 'Glob'],
|
|
76
|
+
* current_step: {
|
|
77
|
+
* step_description: 'Analyze codebase structure',
|
|
78
|
+
* recommended_tools: [{
|
|
79
|
+
* tool_name: 'Glob',
|
|
80
|
+
* confidence: 0.9,
|
|
81
|
+
* rationale: 'Best for finding files by pattern',
|
|
82
|
+
* priority: 1
|
|
83
|
+
* }],
|
|
84
|
+
* expected_outcome: 'List of all TypeScript files'
|
|
85
|
+
* }
|
|
86
|
+
* });
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
export declare class ThoughtProcessor {
|
|
90
|
+
private historyManager;
|
|
91
|
+
private thoughtFormatter;
|
|
92
|
+
/** Logger for debugging and monitoring. */
|
|
93
|
+
private _logger;
|
|
94
|
+
/** Evaluator for quality signal computation. */
|
|
95
|
+
private readonly _thoughtEvaluator;
|
|
96
|
+
/**
|
|
97
|
+
* Per-session cooldown tracker: session_id → pattern → last_fired_thought_number.
|
|
98
|
+
* Prevents re-firing the same pattern hint within 3 thoughts.
|
|
99
|
+
*/
|
|
100
|
+
private _hintCooldowns;
|
|
101
|
+
/**
|
|
102
|
+
* Creates a new ThoughtProcessor instance.
|
|
103
|
+
*
|
|
104
|
+
* @param historyManager - The history manager for storing thoughts
|
|
105
|
+
* @param thoughtFormatter - The formatter for output formatting
|
|
106
|
+
* @param thoughtEvaluator - Evaluator for quality signal computation
|
|
107
|
+
* @param logger - Optional logger for diagnostics (defaults to NullLogger)
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```typescript
|
|
111
|
+
* const processor = new ThoughtProcessor(
|
|
112
|
+
* historyManager,
|
|
113
|
+
* new ThoughtFormatter(),
|
|
114
|
+
* new ThoughtEvaluator(),
|
|
115
|
+
* logger,
|
|
116
|
+
* );
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
constructor(historyManager: IHistoryManager, thoughtFormatter: ThoughtFormatter, thoughtEvaluator: ThoughtEvaluator, logger?: Logger);
|
|
120
|
+
/**
|
|
121
|
+
* Internal logging method.
|
|
122
|
+
* @param message - The message to log
|
|
123
|
+
* @param meta - Optional metadata
|
|
124
|
+
* @private
|
|
125
|
+
*/
|
|
126
|
+
private log;
|
|
127
|
+
/**
|
|
128
|
+
* Generate actionable hints from pattern signals.
|
|
129
|
+
* Rules: max 3 hints, warning-severity only, cooldown of 3 thoughts per pattern per session.
|
|
130
|
+
*
|
|
131
|
+
* @param patterns - Detected pattern signals
|
|
132
|
+
* @param currentThoughtNumber - The current thought number being processed
|
|
133
|
+
* @param sessionId - Session identifier for cooldown scoping
|
|
134
|
+
* @returns Array of hint strings (max 3), empty if no warnings
|
|
135
|
+
*/
|
|
136
|
+
private _generateHints;
|
|
137
|
+
/**
|
|
138
|
+
* Processes a thought through the sequential thinking pipeline.
|
|
139
|
+
*
|
|
140
|
+
* This method validates the input, adds it to history, formats the output,
|
|
141
|
+
* computes quality signals via the ThoughtEvaluator, and returns
|
|
142
|
+
* a structured response with metadata about the current state.
|
|
143
|
+
*
|
|
144
|
+
* @param input - The thought data to process
|
|
145
|
+
* @returns A Promise resolving to the formatted tool result containing:
|
|
146
|
+
* - `thought_number` — Current thought index
|
|
147
|
+
* - `total_thoughts` — Estimated total thoughts
|
|
148
|
+
* - `next_thought_needed` — Whether to continue
|
|
149
|
+
* - `branches` — Active branch IDs
|
|
150
|
+
* - `thought_history_length` — Number of thoughts in history
|
|
151
|
+
* - `available_mcp_tools` — MCP tools available for recommendation
|
|
152
|
+
* - `available_skills` — Skills available for recommendation
|
|
153
|
+
* - `current_step` — Current step recommendation
|
|
154
|
+
* - `previous_steps` — Previously recommended steps
|
|
155
|
+
* - `remaining_steps` — Upcoming step descriptions
|
|
156
|
+
* - `thought_type` — Classification of thought purpose (optional)
|
|
157
|
+
* - `quality_score` — Self-assessed quality score 0-1 (optional)
|
|
158
|
+
* - `confidence` — Self-assessed confidence 0-1 (optional)
|
|
159
|
+
* - `hypothesis_id` — Hypothesis link for verification chains (optional)
|
|
160
|
+
* - `confidence_signals` — Computed reasoning quality signals (includes structural_quality and quality_components)
|
|
161
|
+
* - `reasoning_stats` — Aggregated reasoning analytics
|
|
162
|
+
* - `reasoning_hints` — (Conditional) Actionable hints from pattern analysis, max 3, warning-severity only (optional)
|
|
163
|
+
*
|
|
164
|
+
* @example
|
|
165
|
+
* ```typescript
|
|
166
|
+
* const result = await processor.process({
|
|
167
|
+
* thought: 'I should read the README file',
|
|
168
|
+
* thought_number: 1,
|
|
169
|
+
* total_thoughts: 3,
|
|
170
|
+
* next_thought_needed: true
|
|
171
|
+
* });
|
|
172
|
+
*
|
|
173
|
+
* console.log(result.content[0].text);
|
|
174
|
+
* // Output includes: thought_number, total_thoughts, next_thought_needed,
|
|
175
|
+
* // branches, thought_history_length, and any recommendations
|
|
176
|
+
* ```
|
|
177
|
+
*/
|
|
178
|
+
process(input: ThoughtData): Promise<CallToolResult>;
|
|
179
|
+
/**
|
|
180
|
+
* Validates and normalizes thought input.
|
|
181
|
+
*
|
|
182
|
+
* Ensures that thought numbers are consistent and within valid ranges.
|
|
183
|
+
* If `thought_number` exceeds `total_thoughts`, `total_thoughts` is
|
|
184
|
+
* automatically adjusted to match and a warning is emitted.
|
|
185
|
+
*
|
|
186
|
+
* @param input - The input to validate
|
|
187
|
+
* @returns Object with validated input and any warnings generated
|
|
188
|
+
* @private
|
|
189
|
+
*
|
|
190
|
+
* @example
|
|
191
|
+
* ```typescript
|
|
192
|
+
* // Auto-adjusts total_thoughts when thought_number exceeds it
|
|
193
|
+
* const { result, warnings } = this.validateInput(input);
|
|
194
|
+
* // result.total_thoughts === 10 (auto-adjusted from 5)
|
|
195
|
+
* // warnings === ['Auto-adjusted total_thoughts from 5 to 10 to match thought_number']
|
|
196
|
+
* ```
|
|
197
|
+
*/
|
|
198
|
+
private validateInput;
|
|
199
|
+
/**
|
|
200
|
+
* Validates cross-field references against actual thought history.
|
|
201
|
+
* Drops invalid references with a warning log — never rejects.
|
|
202
|
+
* LLMs frequently send optimistic references to thoughts that don't exist yet.
|
|
203
|
+
*
|
|
204
|
+
* @param input - The thought data to validate
|
|
205
|
+
* @returns Object with cleaned input and any warnings generated
|
|
206
|
+
* @private
|
|
207
|
+
*
|
|
208
|
+
* @example
|
|
209
|
+
* ```typescript
|
|
210
|
+
* // verification_target=999 with only 3 thoughts in history
|
|
211
|
+
* const { result, warnings } = this._validateCrossReferences(input);
|
|
212
|
+
* // result.verification_target === undefined
|
|
213
|
+
* // warnings === ['Dropped dangling verification_target: 999 (history has 3 thoughts)']
|
|
214
|
+
* ```
|
|
215
|
+
*/
|
|
216
|
+
private _validateCrossReferences;
|
|
217
|
+
}
|
|
218
|
+
//# sourceMappingURL=ThoughtProcessor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ThoughtProcessor.d.ts","sourceRoot":"","sources":["../../src/core/ThoughtProcessor.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,+BAA+B,CAAC;AAC5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAGzD;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,WAAW,cAAc;IAC9B,wEAAwE;IACxE,OAAO,EAAE,KAAK,CAAC;QACd,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;KACb,CAAC,CAAC;IAEH,yDAAyD;IACzD,OAAO,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,qBAAa,gBAAgB;IAgC3B,OAAO,CAAC,cAAc;IACtB,OAAO,CAAC,gBAAgB;IAhCzB,2CAA2C;IAC3C,OAAO,CAAC,OAAO,CAAS;IAExB,gDAAgD;IAChD,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAmB;IAErD;;;OAGG;IACH,OAAO,CAAC,cAAc,CAA0C;IAEhE;;;;;;;;;;;;;;;;;OAiBG;gBAEM,cAAc,EAAE,eAAe,EAC/B,gBAAgB,EAAE,gBAAgB,EAC1C,gBAAgB,EAAE,gBAAgB,EAClC,MAAM,CAAC,EAAE,MAAM;IAMhB;;;;;OAKG;IACH,OAAO,CAAC,GAAG;IAIX;;;;;;;;OAQG;IACH,OAAO,CAAC,cAAc;IA8BtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAwCG;IACU,OAAO,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,cAAc,CAAC;IA6GjE;;;;;;;;;;;;;;;;;;OAkBG;IACH,OAAO,CAAC,aAAa;IAoBrB;;;;;;;;;;;;;;;;OAgBG;IACH,OAAO,CAAC,wBAAwB;CAmGhC"}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { NullLogger } from "../logger/NullLogger.js";
|
|
2
|
+
import { normalizeInput } from "./InputNormalizer.js";
|
|
3
|
+
class ThoughtProcessor {
|
|
4
|
+
historyManager;
|
|
5
|
+
thoughtFormatter;
|
|
6
|
+
_logger;
|
|
7
|
+
_thoughtEvaluator;
|
|
8
|
+
_hintCooldowns = new Map();
|
|
9
|
+
constructor(historyManager, thoughtFormatter, thoughtEvaluator, logger){
|
|
10
|
+
this.historyManager = historyManager;
|
|
11
|
+
this.thoughtFormatter = thoughtFormatter;
|
|
12
|
+
this._thoughtEvaluator = thoughtEvaluator;
|
|
13
|
+
this._logger = logger ?? new NullLogger();
|
|
14
|
+
}
|
|
15
|
+
log(message, meta) {
|
|
16
|
+
this._logger.info(message, meta);
|
|
17
|
+
}
|
|
18
|
+
_generateHints(patterns, currentThoughtNumber, sessionId) {
|
|
19
|
+
const warnings = patterns.filter((p)=>'warning' === p.severity);
|
|
20
|
+
if (0 === warnings.length) return [];
|
|
21
|
+
const sessionKey = sessionId ?? '__global__';
|
|
22
|
+
if (!this._hintCooldowns.has(sessionKey)) this._hintCooldowns.set(sessionKey, new Map());
|
|
23
|
+
const cooldowns = this._hintCooldowns.get(sessionKey);
|
|
24
|
+
const hints = [];
|
|
25
|
+
for (const warning of warnings){
|
|
26
|
+
if (hints.length >= 3) break;
|
|
27
|
+
const lastFired = cooldowns.get(warning.pattern);
|
|
28
|
+
if (void 0 === lastFired || !(currentThoughtNumber - lastFired < 3)) {
|
|
29
|
+
hints.push(warning.message);
|
|
30
|
+
cooldowns.set(warning.pattern, currentThoughtNumber);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return hints;
|
|
34
|
+
}
|
|
35
|
+
async process(input) {
|
|
36
|
+
try {
|
|
37
|
+
const normalizedInput = normalizeInput(input);
|
|
38
|
+
const sessionId = normalizedInput.session_id;
|
|
39
|
+
if (normalizedInput.reset_state) {
|
|
40
|
+
this.historyManager.clear(sessionId);
|
|
41
|
+
this.log('State reset for session', {
|
|
42
|
+
sessionId: sessionId ?? '__global__'
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
if (!normalizedInput.available_mcp_tools) normalizedInput.available_mcp_tools = this.historyManager.getAvailableMcpTools(sessionId);
|
|
46
|
+
if (!normalizedInput.available_skills) normalizedInput.available_skills = this.historyManager.getAvailableSkills(sessionId);
|
|
47
|
+
const { result: validatedInput, warnings: validateWarnings } = this.validateInput(normalizedInput);
|
|
48
|
+
const { result: checkedInput, warnings: refWarnings } = this._validateCrossReferences(validatedInput, sessionId);
|
|
49
|
+
const allWarnings = [
|
|
50
|
+
...validateWarnings,
|
|
51
|
+
...refWarnings
|
|
52
|
+
];
|
|
53
|
+
this.historyManager.addThought(checkedInput);
|
|
54
|
+
const formattedThought = this.thoughtFormatter.formatThought(checkedInput);
|
|
55
|
+
this.log(formattedThought, {
|
|
56
|
+
sessionId: sessionId ?? '__global__'
|
|
57
|
+
});
|
|
58
|
+
const history = this.historyManager.getHistory(sessionId);
|
|
59
|
+
const branches = this.historyManager.getBranches(sessionId);
|
|
60
|
+
const confidenceSignals = this._thoughtEvaluator.computeConfidenceSignals(history, branches);
|
|
61
|
+
const reasoningStats = this._thoughtEvaluator.computeReasoningStats(history, branches);
|
|
62
|
+
const patternSignals = this._thoughtEvaluator.computePatternSignals(history, branches);
|
|
63
|
+
const reasoningHints = this._generateHints(patternSignals, checkedInput.thought_number, sessionId);
|
|
64
|
+
return {
|
|
65
|
+
content: [
|
|
66
|
+
{
|
|
67
|
+
type: 'text',
|
|
68
|
+
text: JSON.stringify({
|
|
69
|
+
thought_number: checkedInput.thought_number,
|
|
70
|
+
total_thoughts: checkedInput.total_thoughts,
|
|
71
|
+
next_thought_needed: checkedInput.next_thought_needed ?? true,
|
|
72
|
+
branches: this.historyManager.getBranchIds(sessionId),
|
|
73
|
+
thought_history_length: this.historyManager.getHistoryLength(sessionId),
|
|
74
|
+
available_mcp_tools: checkedInput.available_mcp_tools,
|
|
75
|
+
available_skills: checkedInput.available_skills,
|
|
76
|
+
current_step: checkedInput.current_step,
|
|
77
|
+
previous_steps: checkedInput.previous_steps,
|
|
78
|
+
remaining_steps: checkedInput.remaining_steps,
|
|
79
|
+
thought_type: checkedInput.thought_type,
|
|
80
|
+
quality_score: checkedInput.quality_score,
|
|
81
|
+
confidence: checkedInput.confidence,
|
|
82
|
+
hypothesis_id: checkedInput.hypothesis_id,
|
|
83
|
+
confidence_signals: confidenceSignals,
|
|
84
|
+
reasoning_stats: reasoningStats,
|
|
85
|
+
...reasoningHints.length > 0 && {
|
|
86
|
+
reasoning_hints: reasoningHints
|
|
87
|
+
},
|
|
88
|
+
...allWarnings.length > 0 && {
|
|
89
|
+
warnings: allWarnings
|
|
90
|
+
},
|
|
91
|
+
...sessionId ? {
|
|
92
|
+
session_id: sessionId
|
|
93
|
+
} : {}
|
|
94
|
+
}, null, 2)
|
|
95
|
+
}
|
|
96
|
+
]
|
|
97
|
+
};
|
|
98
|
+
} catch (error) {
|
|
99
|
+
return {
|
|
100
|
+
content: [
|
|
101
|
+
{
|
|
102
|
+
type: 'text',
|
|
103
|
+
text: JSON.stringify({
|
|
104
|
+
error: error instanceof Error ? error.message : String(error),
|
|
105
|
+
status: 'failed'
|
|
106
|
+
}, null, 2)
|
|
107
|
+
}
|
|
108
|
+
],
|
|
109
|
+
isError: true
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
validateInput(input) {
|
|
114
|
+
const warnings = [];
|
|
115
|
+
if (input.thought_number > input.total_thoughts) {
|
|
116
|
+
const originalTotal = input.total_thoughts;
|
|
117
|
+
warnings.push(`Auto-adjusted total_thoughts from ${originalTotal} to ${input.thought_number} to match thought_number`);
|
|
118
|
+
this._logger.warn('Auto-adjusted total_thoughts to match thought_number', {
|
|
119
|
+
thought_number: input.thought_number,
|
|
120
|
+
original_total_thoughts: originalTotal,
|
|
121
|
+
adjusted_total_thoughts: input.thought_number
|
|
122
|
+
});
|
|
123
|
+
input.total_thoughts = input.thought_number;
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
result: input,
|
|
127
|
+
warnings
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
_validateCrossReferences(input, sessionId) {
|
|
131
|
+
const warnings = [];
|
|
132
|
+
const historyLength = this.historyManager.getHistoryLength(sessionId);
|
|
133
|
+
const branchIds = new Set(this.historyManager.getBranchIds(sessionId));
|
|
134
|
+
if (void 0 !== input.verification_target && input.verification_target > historyLength) {
|
|
135
|
+
warnings.push(`Dropped dangling verification_target: ${input.verification_target} (history has ${historyLength} thoughts)`);
|
|
136
|
+
this._logger.warn('Dropped dangling verification_target', {
|
|
137
|
+
verification_target: input.verification_target,
|
|
138
|
+
historyLength
|
|
139
|
+
});
|
|
140
|
+
input.verification_target = void 0;
|
|
141
|
+
}
|
|
142
|
+
if (void 0 !== input.revises_thought && input.revises_thought > historyLength) {
|
|
143
|
+
warnings.push(`Dropped dangling revises_thought: ${input.revises_thought} (history has ${historyLength} thoughts)`);
|
|
144
|
+
this._logger.warn('Dropped dangling revises_thought', {
|
|
145
|
+
revises_thought: input.revises_thought,
|
|
146
|
+
historyLength
|
|
147
|
+
});
|
|
148
|
+
input.revises_thought = void 0;
|
|
149
|
+
}
|
|
150
|
+
if (void 0 !== input.branch_from_thought && input.branch_from_thought > historyLength) {
|
|
151
|
+
warnings.push(`Dropped dangling branch_from_thought: ${input.branch_from_thought} (history has ${historyLength} thoughts)`);
|
|
152
|
+
this._logger.warn('Dropped dangling branch_from_thought', {
|
|
153
|
+
branch_from_thought: input.branch_from_thought,
|
|
154
|
+
historyLength
|
|
155
|
+
});
|
|
156
|
+
input.branch_from_thought = void 0;
|
|
157
|
+
}
|
|
158
|
+
if (input.synthesis_sources?.length) {
|
|
159
|
+
const valid = input.synthesis_sources.filter((n)=>n <= historyLength);
|
|
160
|
+
if (valid.length < input.synthesis_sources.length) {
|
|
161
|
+
const dropped = input.synthesis_sources.filter((n)=>n > historyLength);
|
|
162
|
+
warnings.push(`Filtered dangling synthesis_sources: [${dropped.join(', ')}] (history has ${historyLength} thoughts)`);
|
|
163
|
+
this._logger.warn('Filtered dangling synthesis_sources', {
|
|
164
|
+
original: input.synthesis_sources,
|
|
165
|
+
filtered: valid,
|
|
166
|
+
historyLength
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
input.synthesis_sources = valid.length > 0 ? valid : void 0;
|
|
170
|
+
}
|
|
171
|
+
if (input.merge_from_thoughts?.length) {
|
|
172
|
+
const valid = input.merge_from_thoughts.filter((n)=>n <= historyLength);
|
|
173
|
+
if (valid.length < input.merge_from_thoughts.length) {
|
|
174
|
+
const dropped = input.merge_from_thoughts.filter((n)=>n > historyLength);
|
|
175
|
+
warnings.push(`Filtered dangling merge_from_thoughts: [${dropped.join(', ')}] (history has ${historyLength} thoughts)`);
|
|
176
|
+
this._logger.warn('Filtered dangling merge_from_thoughts', {
|
|
177
|
+
original: input.merge_from_thoughts,
|
|
178
|
+
filtered: valid,
|
|
179
|
+
historyLength
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
input.merge_from_thoughts = valid.length > 0 ? valid : void 0;
|
|
183
|
+
}
|
|
184
|
+
if (input.merge_branch_ids?.length) {
|
|
185
|
+
const valid = input.merge_branch_ids.filter((id)=>branchIds.has(id));
|
|
186
|
+
if (valid.length < input.merge_branch_ids.length) {
|
|
187
|
+
const dropped = input.merge_branch_ids.filter((id)=>!branchIds.has(id));
|
|
188
|
+
warnings.push(`Filtered dangling merge_branch_ids: [${dropped.join(', ')}]`);
|
|
189
|
+
this._logger.warn('Filtered dangling merge_branch_ids', {
|
|
190
|
+
original: input.merge_branch_ids,
|
|
191
|
+
filtered: valid,
|
|
192
|
+
existingBranches: Array.from(branchIds)
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
input.merge_branch_ids = valid.length > 0 ? valid : void 0;
|
|
196
|
+
}
|
|
197
|
+
return {
|
|
198
|
+
result: input,
|
|
199
|
+
warnings
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
export { ThoughtProcessor };
|
|
204
|
+
|
|
205
|
+
//# sourceMappingURL=ThoughtProcessor.js.map
|
|
@@ -0,0 +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 { NullLogger } from '../logger/NullLogger.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport type { IHistoryManager } from './IHistoryManager.js';\nimport { normalizeInput } from './InputNormalizer.js';\nimport type { ThoughtData } from './thought.js';\nimport type { ThoughtEvaluator } from './ThoughtEvaluator.js';\nimport { ThoughtFormatter } from './ThoughtFormatter.js';\nimport type { PatternSignal } from './reasoning.js';\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 {\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 * This class handles the main processing pipeline for thought requests,\n * coordinating between history management, validation, and response formatting.\n * It serves as the central entry point for the sequential thinking tool.\n *\n * @remarks\n * **Processing Pipeline:**\n * 1. Validate and normalize the input thought\n * 2. Add the thought to history (triggers auto-trimming if needed)\n * 3. Format the thought for logging/display\n * 4. Compute quality signals via ThoughtEvaluator\n * 5. Return structured response with metadata and reasoning enrichment\n *\n * **Validation Rules:**\n * - `thought_number` must be >= 1\n * - `total_thoughts` must be >= 1\n * - If `thought_number > total_thoughts`, `total_thoughts` is auto-adjusted\n *\n * **Error Handling:**\n * All errors are caught and returned as formatted error responses\n * with `isError: true` set, preventing crashes from malformed input.\n *\n * @example\n * ```typescript\n * const processor = new ThoughtProcessor(historyManager, formatter, new ThoughtEvaluator());\n *\n * const result = await processor.process({\n * thought: 'I need to analyze the codebase structure',\n * thought_number: 1,\n * total_thoughts: 5,\n * next_thought_needed: true,\n * available_mcp_tools: ['Read', 'Grep', 'Glob'],\n * current_step: {\n * step_description: 'Analyze codebase structure',\n * recommended_tools: [{\n * tool_name: 'Glob',\n * confidence: 0.9,\n * rationale: 'Best for finding files by pattern',\n * priority: 1\n * }],\n * expected_outcome: 'List of all TypeScript files'\n * }\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<string, Map<string, number>>();\n\n\t/**\n\t * Creates a new ThoughtProcessor instance.\n\t *\n\t * @param historyManager - The history manager for storing thoughts\n\t * @param thoughtFormatter - The 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 *\n\t * @example\n\t * ```typescript\n\t * const processor = new ThoughtProcessor(\n\t * historyManager,\n\t * new ThoughtFormatter(),\n\t * new ThoughtEvaluator(),\n\t * logger,\n\t * );\n\t * ```\n\t */\n\tconstructor(\n\t\tprivate historyManager: IHistoryManager,\n\t\tprivate thoughtFormatter: ThoughtFormatter,\n\t\tthoughtEvaluator: ThoughtEvaluator,\n\t\tlogger?: Logger\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 * 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 * @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?: string\n\t): string[] {\n\t\tconst warnings = patterns.filter((p) => p.severity === 'warning');\n\t\tif (warnings.length === 0) return [];\n\n\t\tconst sessionKey = sessionId ?? '__global__';\n\t\tif (!this._hintCooldowns.has(sessionKey)) {\n\t\t\tthis._hintCooldowns.set(sessionKey, new Map());\n\t\t}\n\t\tconst cooldowns = this._hintCooldowns.get(sessionKey)!;\n\n\t\tconst hints: string[] = [];\n\t\tfor (const warning of warnings) {\n\t\t\tif (hints.length >= 3) break;\n\n\t\t\tconst lastFired = cooldowns.get(warning.pattern);\n\t\t\tif (lastFired !== undefined && currentThoughtNumber - lastFired < 3) {\n\t\t\t\tcontinue; // Still in cooldown\n\t\t\t}\n\n\t\t\thints.push(warning.message);\n\t\t\tcooldowns.set(warning.pattern, currentThoughtNumber);\n\t\t}\n\n\t\treturn hints;\n\t}\n\n\t/**\n\t * Processes a thought through the sequential thinking pipeline.\n\t *\n\t * This method validates the input, adds it to history, formats the output,\n\t * computes quality signals via the ThoughtEvaluator, and returns\n\t * a structured response with metadata about the current state.\n\t *\n\t * @param input - The thought data to process\n\t * @returns A Promise resolving to the formatted tool result containing:\n\t * - `thought_number` — Current thought index\n\t * - `total_thoughts` — Estimated total thoughts\n\t * - `next_thought_needed` — Whether to continue\n\t * - `branches` — Active branch IDs\n\t * - `thought_history_length` — Number of thoughts in history\n\t * - `available_mcp_tools` — MCP tools available for recommendation\n\t * - `available_skills` — Skills available for recommendation\n\t * - `current_step` — Current step recommendation\n\t * - `previous_steps` — Previously recommended steps\n\t * - `remaining_steps` — Upcoming step descriptions\n\t * - `thought_type` — Classification of thought purpose (optional)\n\t * - `quality_score` — Self-assessed quality score 0-1 (optional)\n\t * - `confidence` — Self-assessed confidence 0-1 (optional)\n\t * - `hypothesis_id` — Hypothesis link for verification chains (optional)\n * - `confidence_signals` — Computed reasoning quality signals (includes structural_quality and quality_components)\n * - `reasoning_stats` — Aggregated reasoning analytics\n * - `reasoning_hints` — (Conditional) Actionable hints from pattern analysis, max 3, warning-severity only (optional)\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await processor.process({\n\t * thought: 'I should read the README file',\n\t * thought_number: 1,\n\t * total_thoughts: 3,\n\t * next_thought_needed: true\n\t * });\n\t *\n\t * console.log(result.content[0].text);\n\t * // Output includes: thought_number, total_thoughts, next_thought_needed,\n\t * // branches, thought_history_length, and any recommendations\n\t * ```\n\t */\n\tpublic async process(input: ThoughtData): Promise<CallToolResult> {\n\t\ttry {\n\t\t\t// Normalize input to handle common LLM field name mistakes\n\t\t\tconst normalizedInput = normalizeInput(input);\n\t\t\tconst sessionId = normalizedInput.session_id;\n\n\t\t\t// Handle reset_state: clear session before processing\n\t\t\tif (normalizedInput.reset_state) {\n\t\t\t\tthis.historyManager.clear(sessionId);\n\t\t\t\tthis.log('State reset for session', { sessionId: sessionId ?? '__global__' });\n\t\t\t}\n\n\t\t\t// Persist available_mcp_tools/available_skills across calls within a session.\n\t\t\t// If the caller omits these, reuse the last-seen values from the session.\n\t\t\tif (!normalizedInput.available_mcp_tools) {\n\t\t\t\tnormalizedInput.available_mcp_tools = this.historyManager.getAvailableMcpTools(sessionId);\n\t\t\t}\n\t\t\tif (!normalizedInput.available_skills) {\n\t\t\t\tnormalizedInput.available_skills = this.historyManager.getAvailableSkills(sessionId);\n\t\t\t}\n\n\t\t\tconst { result: validatedInput, warnings: validateWarnings } =\n\t\t\t\tthis.validateInput(normalizedInput);\n\t\t\tconst { result: checkedInput, warnings: refWarnings } =\n\t\t\t\tthis._validateCrossReferences(validatedInput, sessionId);\n\t\t\tconst allWarnings = [...validateWarnings, ...refWarnings];\n\n\t\t\tthis.historyManager.addThought(checkedInput);\n\n\t\t\tconst formattedThought = this.thoughtFormatter.formatThought(checkedInput);\n\t\t\tthis.log(formattedThought, { sessionId: sessionId ?? '__global__' });\n\n\t\t\t// Compute quality signals — fetch history/branches once\n\t\t\tconst history = this.historyManager.getHistory(sessionId);\n\t\t\tconst branches = this.historyManager.getBranches(sessionId);\n\n\t\t\tconst confidenceSignals = this._thoughtEvaluator.computeConfidenceSignals(\n\t\t\t\thistory,\n\t\t\t\tbranches\n\t\t\t);\n\t\t\tconst reasoningStats = this._thoughtEvaluator.computeReasoningStats(\n\t\t\t\thistory,\n\t\t\t\tbranches\n\t\t\t);\n\n\t\t\t// Detect reasoning patterns and generate hints\n\t\t\tconst patternSignals = this._thoughtEvaluator.computePatternSignals(\n\t\t\t\thistory,\n\t\t\t\tbranches\n\t\t\t);\n\t\t\tconst reasoningHints = this._generateHints(\n\t\t\t\tpatternSignals,\n\t\t\t\tcheckedInput.thought_number,\n\t\t\t\tsessionId\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthought_number: checkedInput.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: checkedInput.total_thoughts,\n\t\t\t\t\t\t\tnext_thought_needed: checkedInput.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: checkedInput.available_mcp_tools,\n\t\t\t\t\t\t\tavailable_skills: checkedInput.available_skills,\n\t\t\t\t\t\t\tcurrent_step: checkedInput.current_step,\n\t\t\t\t\t\t\tprevious_steps: checkedInput.previous_steps,\n\t\t\t\t\t\t\tremaining_steps: checkedInput.remaining_steps,\n\t\t\t\t\t\t\t// Reasoning enrichment fields\n\t\t\t\t\t\t\tthought_type: checkedInput.thought_type,\n\t\t\t\t\t\t\tquality_score: checkedInput.quality_score,\n\t\t\t\t\t\t\tconfidence: checkedInput.confidence,\n\t\t\t\t\t\t\thypothesis_id: checkedInput.hypothesis_id,\n\t\t\t\t\t\t\tconfidence_signals: confidenceSignals,\n\t\t\t\t\t\t\treasoning_stats: reasoningStats,\n\t\t\t\t\t\t\t...(reasoningHints.length > 0 && { reasoning_hints: reasoningHints }),\n\t\t\t\t\t\t\t...(allWarnings.length > 0 && { warnings: allWarnings }),\n\t\t\t\t\t\t\t...(sessionId ? { session_id: sessionId } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t2\n\t\t\t\t\t\t),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t};\n\t\t}\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`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 * Validates cross-field references against actual thought history.\n\t * Drops invalid references with a warning log — never rejects.\n\t * LLMs frequently send optimistic references to thoughts that don't exist yet.\n\t *\n\t * @param input - The thought data to validate\n\t * @returns Object with cleaned input and any warnings generated\n\t * @private\n\t *\n\t * @example\n\t * ```typescript\n\t * // verification_target=999 with only 3 thoughts in history\n\t * const { result, warnings } = this._validateCrossReferences(input);\n\t * // result.verification_target === undefined\n\t * // warnings === ['Dropped dangling verification_target: 999 (history has 3 thoughts)']\n\t * ```\n\t */\n\tprivate _validateCrossReferences(input: ThoughtData, sessionId?: string): {\n\t\tresult: ThoughtData;\n\t\twarnings: string[];\n\t} {\n\t\tconst warnings: string[] = [];\n\t\tconst historyLength = this.historyManager.getHistoryLength(sessionId);\n\t\tconst branchIds = new Set(this.historyManager.getBranchIds(sessionId));\n\n\t\t// verification_target: must reference existing thought\n\t\tif (input.verification_target !== undefined && input.verification_target > historyLength) {\n\t\t\twarnings.push(\n\t\t\t\t`Dropped dangling verification_target: ${input.verification_target} (history has ${historyLength} thoughts)`\n\t\t\t);\n\t\t\tthis._logger.warn('Dropped dangling verification_target', {\n\t\t\t\tverification_target: input.verification_target,\n\t\t\t\thistoryLength,\n\t\t\t});\n\t\t\tinput.verification_target = undefined;\n\t\t}\n\n\t\t// revises_thought: must reference existing thought\n\t\tif (input.revises_thought !== undefined && input.revises_thought > historyLength) {\n\t\t\twarnings.push(\n\t\t\t\t`Dropped dangling revises_thought: ${input.revises_thought} (history has ${historyLength} thoughts)`\n\t\t\t);\n\t\t\tthis._logger.warn('Dropped dangling revises_thought', {\n\t\t\t\trevises_thought: input.revises_thought,\n\t\t\t\thistoryLength,\n\t\t\t});\n\t\t\tinput.revises_thought = undefined;\n\t\t}\n\n\t\t// branch_from_thought: must reference existing thought\n\t\tif (input.branch_from_thought !== undefined && input.branch_from_thought > historyLength) {\n\t\t\twarnings.push(\n\t\t\t\t`Dropped dangling branch_from_thought: ${input.branch_from_thought} (history has ${historyLength} thoughts)`\n\t\t\t);\n\t\t\tthis._logger.warn('Dropped dangling branch_from_thought', {\n\t\t\t\tbranch_from_thought: input.branch_from_thought,\n\t\t\t\thistoryLength,\n\t\t\t});\n\t\t\tinput.branch_from_thought = undefined;\n\t\t}\n\n\t\t// synthesis_sources: filter to existing thoughts only\n\t\tif (input.synthesis_sources?.length) {\n\t\t\tconst valid = input.synthesis_sources.filter((n: number) => n <= historyLength);\n\t\t\tif (valid.length < input.synthesis_sources.length) {\n\t\t\t\tconst dropped = input.synthesis_sources.filter((n: number) => n > historyLength);\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Filtered dangling synthesis_sources: [${dropped.join(', ')}] (history has ${historyLength} thoughts)`\n\t\t\t\t);\n\t\t\t\tthis._logger.warn('Filtered dangling synthesis_sources', {\n\t\t\t\t\toriginal: input.synthesis_sources,\n\t\t\t\t\tfiltered: valid,\n\t\t\t\t\thistoryLength,\n\t\t\t\t});\n\t\t\t}\n\t\t\tinput.synthesis_sources = valid.length > 0 ? valid : undefined;\n\t\t}\n\n\t\t// merge_from_thoughts: filter to existing thoughts only\n\t\tif (input.merge_from_thoughts?.length) {\n\t\t\tconst valid = input.merge_from_thoughts.filter((n: number) => n <= historyLength);\n\t\t\tif (valid.length < input.merge_from_thoughts.length) {\n\t\t\t\tconst dropped = input.merge_from_thoughts.filter(\n\t\t\t\t\t(n: number) => n > historyLength\n\t\t\t\t);\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Filtered dangling merge_from_thoughts: [${dropped.join(', ')}] (history has ${historyLength} thoughts)`\n\t\t\t\t);\n\t\t\t\tthis._logger.warn('Filtered dangling merge_from_thoughts', {\n\t\t\t\t\toriginal: input.merge_from_thoughts,\n\t\t\t\t\tfiltered: valid,\n\t\t\t\t\thistoryLength,\n\t\t\t\t});\n\t\t\t}\n\t\t\tinput.merge_from_thoughts = valid.length > 0 ? valid : undefined;\n\t\t}\n\n\t\t// merge_branch_ids: filter to existing branches only\n\t\tif (input.merge_branch_ids?.length) {\n\t\t\tconst valid = input.merge_branch_ids.filter((id: string) => branchIds.has(id));\n\t\t\tif (valid.length < input.merge_branch_ids.length) {\n\t\t\t\tconst dropped = input.merge_branch_ids.filter(\n\t\t\t\t\t(id: string) => !branchIds.has(id)\n\t\t\t\t);\n\t\t\t\twarnings.push(`Filtered dangling merge_branch_ids: [${dropped.join(', ')}]`);\n\t\t\t\tthis._logger.warn('Filtered dangling merge_branch_ids', {\n\t\t\t\t\toriginal: input.merge_branch_ids,\n\t\t\t\t\tfiltered: valid,\n\t\t\t\t\texistingBranches: Array.from(branchIds),\n\t\t\t\t});\n\t\t\t}\n\t\t\tinput.merge_branch_ids = valid.length > 0 ? valid : undefined;\n\t\t}\n\n\t\treturn { result: input, warnings };\n\t}\n}\n"],"names":["ThoughtProcessor","Map","historyManager","thoughtFormatter","thoughtEvaluator","logger","NullLogger","message","meta","patterns","currentThoughtNumber","sessionId","warnings","p","sessionKey","cooldowns","hints","warning","lastFired","undefined","input","normalizedInput","normalizeInput","validatedInput","validateWarnings","checkedInput","refWarnings","allWarnings","formattedThought","history","branches","confidenceSignals","reasoningStats","patternSignals","reasoningHints","JSON","error","Error","String","originalTotal","historyLength","branchIds","Set","valid","n","dropped","id","Array"],"mappings":";;AA+FO,MAAMA;;;IAEJ,QAAgB;IAGP,kBAAoC;IAM7C,iBAAiB,IAAIC,MAAmC;IAoBhE,YACSC,cAA+B,EAC/BC,gBAAkC,EAC1CC,gBAAkC,EAClCC,MAAe,CACd;aAJOH,cAAc,GAAdA;aACAC,gBAAgB,GAAhBA;QAIR,IAAI,CAAC,iBAAiB,GAAGC;QACzB,IAAI,CAAC,OAAO,GAAGC,UAAU,IAAIC;IAC9B;IAQQ,IAAIC,OAAe,EAAEC,IAA8B,EAAQ;QAClE,IAAI,CAAC,OAAO,CAAC,IAAI,CAACD,SAASC;IAC5B;IAWQ,eACPC,QAAyB,EACzBC,oBAA4B,EAC5BC,SAAkB,EACP;QACX,MAAMC,WAAWH,SAAS,MAAM,CAAC,CAACI,IAAMA,AAAe,cAAfA,EAAE,QAAQ;QAClD,IAAID,AAAoB,MAApBA,SAAS,MAAM,EAAQ,OAAO,EAAE;QAEpC,MAAME,aAAaH,aAAa;QAChC,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,CAACG,aAC5B,IAAI,CAAC,cAAc,CAAC,GAAG,CAACA,YAAY,IAAIb;QAEzC,MAAMc,YAAY,IAAI,CAAC,cAAc,CAAC,GAAG,CAACD;QAE1C,MAAME,QAAkB,EAAE;QAC1B,KAAK,MAAMC,WAAWL,SAAU;YAC/B,IAAII,MAAM,MAAM,IAAI,GAAG;YAEvB,MAAME,YAAYH,UAAU,GAAG,CAACE,QAAQ,OAAO;YAC/C,IAAIC,AAAcC,WAAdD,cAA2BR,CAAAA,uBAAuBQ,YAAY;gBAIlEF,MAAM,IAAI,CAACC,QAAQ,OAAO;gBAC1BF,UAAU,GAAG,CAACE,QAAQ,OAAO,EAAEP;;QAChC;QAEA,OAAOM;IAC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UpB,MAAM,mBAAmB;oBACnC,UAAUuB;oBACVH;gBACD;YACD;YACApB,MAAM,mBAAmB,GAAGuB,MAAM,MAAM,GAAG,IAAIA,QAAQxB;QACxD;QAGA,IAAIC,MAAM,gBAAgB,EAAE,QAAQ;YACnC,MAAMuB,QAAQvB,MAAM,gBAAgB,CAAC,MAAM,CAAC,CAAC0B,KAAeL,UAAU,GAAG,CAACK;YAC1E,IAAIH,MAAM,MAAM,GAAGvB,MAAM,gBAAgB,CAAC,MAAM,EAAE;gBACjD,MAAMyB,UAAUzB,MAAM,gBAAgB,CAAC,MAAM,CAC5C,CAAC0B,KAAe,CAACL,UAAU,GAAG,CAACK;gBAEhClC,SAAS,IAAI,CAAC,CAAC,qCAAqC,EAAEiC,QAAQ,IAAI,CAAC,MAAM,CAAC,CAAC;gBAC3E,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,sCAAsC;oBACvD,UAAUzB,MAAM,gBAAgB;oBAChC,UAAUuB;oBACV,kBAAkBI,MAAM,IAAI,CAACN;gBAC9B;YACD;YACArB,MAAM,gBAAgB,GAAGuB,MAAM,MAAM,GAAG,IAAIA,QAAQxB;QACrD;QAEA,OAAO;YAAE,QAAQC;YAAOR;QAAS;IAClC;AACD"}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reasoning type definitions for advanced sequential thinking.
|
|
3
|
+
*
|
|
4
|
+
* Provides type-level constructs for classifying thoughts, computing confidence
|
|
5
|
+
* signals from reasoning history, and aggregating session analytics.
|
|
6
|
+
*
|
|
7
|
+
* @module core/reasoning
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Classification of thought purpose — enables type-specific formatting, evaluation, and analytics.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* const thoughtType: ThoughtType = 'hypothesis';
|
|
15
|
+
*
|
|
16
|
+
* // Use in conditional formatting
|
|
17
|
+
* if (thoughtType === 'verification') {
|
|
18
|
+
* console.log('Verifying a hypothesis...');
|
|
19
|
+
* }
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export type ThoughtType = 'regular' | 'hypothesis' | 'verification' | 'critique' | 'synthesis' | 'meta';
|
|
23
|
+
/**
|
|
24
|
+
* A detected reasoning pattern — surfaced as metadata or a warning.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```typescript
|
|
28
|
+
* const signal: PatternSignal = {
|
|
29
|
+
* pattern: 'hypothesis-without-verification',
|
|
30
|
+
* severity: 'warning',
|
|
31
|
+
* message: 'Hypothesis H1 has no matching verification thought.',
|
|
32
|
+
* thought_range: [3, 7],
|
|
33
|
+
* };
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
export interface PatternSignal {
|
|
37
|
+
/** Machine-readable pattern identifier. */
|
|
38
|
+
pattern: string;
|
|
39
|
+
/** Severity: 'warning' surfaces as a hint, 'info' is metadata only. */
|
|
40
|
+
severity: 'info' | 'warning';
|
|
41
|
+
/** Human-readable description of the detected pattern. */
|
|
42
|
+
message: string;
|
|
43
|
+
/** Thought number range [start, end] where the pattern was detected. */
|
|
44
|
+
thought_range: [number, number];
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Signals about reasoning quality computed from history.
|
|
48
|
+
*
|
|
49
|
+
* These metrics are derived from the thought chain and provide insight into
|
|
50
|
+
* the depth, breadth, and completeness of the reasoning process.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```typescript
|
|
54
|
+
* const signals: ConfidenceSignals = {
|
|
55
|
+
* reasoning_depth: 5,
|
|
56
|
+
* revision_count: 1,
|
|
57
|
+
* branch_count: 2,
|
|
58
|
+
* thought_type_distribution: {
|
|
59
|
+
* regular: 3,
|
|
60
|
+
* hypothesis: 1,
|
|
61
|
+
* verification: 1,
|
|
62
|
+
* critique: 0,
|
|
63
|
+
* synthesis: 0,
|
|
64
|
+
* meta: 0,
|
|
65
|
+
* },
|
|
66
|
+
* has_hypothesis: true,
|
|
67
|
+
* has_verification: true,
|
|
68
|
+
* average_confidence: 0.85,
|
|
69
|
+
* structural_quality: 0.72,
|
|
70
|
+
* quality_components: {
|
|
71
|
+
* type_diversity: 0.65,
|
|
72
|
+
* verification_coverage: 1.0,
|
|
73
|
+
* depth_efficiency: 0.6,
|
|
74
|
+
* confidence_stability: 0.85,
|
|
75
|
+
* },
|
|
76
|
+
* };
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
export interface ConfidenceSignals {
|
|
80
|
+
/** Length of thought chain to this point. */
|
|
81
|
+
reasoning_depth: number;
|
|
82
|
+
/** How many revisions in this chain. */
|
|
83
|
+
revision_count: number;
|
|
84
|
+
/** Active branches. */
|
|
85
|
+
branch_count: number;
|
|
86
|
+
/** Distribution of thought types used. */
|
|
87
|
+
thought_type_distribution: Record<ThoughtType, number>;
|
|
88
|
+
/** Whether any hypothesis exists in chain. */
|
|
89
|
+
has_hypothesis: boolean;
|
|
90
|
+
/** Whether any verification exists. */
|
|
91
|
+
has_verification: boolean;
|
|
92
|
+
/** Mean of explicit confidence values, null if none. */
|
|
93
|
+
average_confidence: number | null;
|
|
94
|
+
/**
|
|
95
|
+
* Composite structural quality score (0-1).
|
|
96
|
+
* Geometric mean of quality_components with floor of 0.01 per component.
|
|
97
|
+
* Only present when history has ≥1 thought.
|
|
98
|
+
*/
|
|
99
|
+
structural_quality?: number;
|
|
100
|
+
/**
|
|
101
|
+
* Individual quality components that feed into structural_quality.
|
|
102
|
+
* Only present when structural_quality is present.
|
|
103
|
+
*/
|
|
104
|
+
quality_components?: {
|
|
105
|
+
/** Shannon entropy of thought_type distribution / log2(6), normalized 0-1. */
|
|
106
|
+
type_diversity: number;
|
|
107
|
+
/** verified_hypotheses / total_hypotheses. 1.0 if no hypotheses exist. */
|
|
108
|
+
verification_coverage: number;
|
|
109
|
+
/** max(chain_depth, branch_count + 1) / total_thoughts, clamped to [0, 1]. Branching is desirable. */
|
|
110
|
+
depth_efficiency: number;
|
|
111
|
+
/** 1 - stddev(confidence values). Defaults to 0.5 if no confidence values. */
|
|
112
|
+
confidence_stability: number;
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Aggregated analytics about the reasoning session.
|
|
117
|
+
*
|
|
118
|
+
* Provides a comprehensive summary of the reasoning process including
|
|
119
|
+
* thought counts, branch metrics, hypothesis tracking, and quality scores.
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```typescript
|
|
123
|
+
* const stats: ReasoningStats = {
|
|
124
|
+
* total_thoughts: 12,
|
|
125
|
+
* total_branches: 3,
|
|
126
|
+
* total_revisions: 2,
|
|
127
|
+
* total_merges: 1,
|
|
128
|
+
* chain_depth: 8,
|
|
129
|
+
* thought_type_counts: {
|
|
130
|
+
* regular: 6,
|
|
131
|
+
* hypothesis: 2,
|
|
132
|
+
* verification: 2,
|
|
133
|
+
* critique: 1,
|
|
134
|
+
* synthesis: 1,
|
|
135
|
+
* meta: 0,
|
|
136
|
+
* },
|
|
137
|
+
* hypothesis_count: 2,
|
|
138
|
+
* verified_hypothesis_count: 1,
|
|
139
|
+
* unresolved_hypothesis_count: 1,
|
|
140
|
+
* average_quality_score: 0.78,
|
|
141
|
+
* average_confidence: 0.82,
|
|
142
|
+
* };
|
|
143
|
+
* ```
|
|
144
|
+
*/
|
|
145
|
+
export interface ReasoningStats {
|
|
146
|
+
/** Total thoughts in session. */
|
|
147
|
+
total_thoughts: number;
|
|
148
|
+
/** Total branches created. */
|
|
149
|
+
total_branches: number;
|
|
150
|
+
/** Total revision operations. */
|
|
151
|
+
total_revisions: number;
|
|
152
|
+
/** Total merge operations (DAG topology). */
|
|
153
|
+
total_merges: number;
|
|
154
|
+
/** Longest sequential chain depth. */
|
|
155
|
+
chain_depth: number;
|
|
156
|
+
/** Count of each thought type. */
|
|
157
|
+
thought_type_counts: Record<ThoughtType, number>;
|
|
158
|
+
/** Hypotheses created. */
|
|
159
|
+
hypothesis_count: number;
|
|
160
|
+
/** Hypotheses that have been verified. */
|
|
161
|
+
verified_hypothesis_count: number;
|
|
162
|
+
/** Hypotheses without verification. */
|
|
163
|
+
unresolved_hypothesis_count: number;
|
|
164
|
+
/** Average quality score across thoughts with scores, null if none. */
|
|
165
|
+
average_quality_score: number | null;
|
|
166
|
+
/** Average confidence across thoughts with confidence, null if none. */
|
|
167
|
+
average_confidence: number | null;
|
|
168
|
+
}
|
|
169
|
+
//# sourceMappingURL=reasoning.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reasoning.d.ts","sourceRoot":"","sources":["../../src/core/reasoning.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,WAAW,GACpB,SAAS,GACT,YAAY,GACZ,cAAc,GACd,UAAU,GACV,WAAW,GACX,MAAM,CAAC;AAEV;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,aAAa;IAC7B,2CAA2C;IAC3C,OAAO,EAAE,MAAM,CAAC;IAEhB,uEAAuE;IACvE,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAE7B,0DAA0D;IAC1D,OAAO,EAAE,MAAM,CAAC;IAEhB,wEAAwE;IACxE,aAAa,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAChC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAM,WAAW,iBAAiB;IACjC,6CAA6C;IAC7C,eAAe,EAAE,MAAM,CAAC;IAExB,wCAAwC;IACxC,cAAc,EAAE,MAAM,CAAC;IAEvB,uBAAuB;IACvB,YAAY,EAAE,MAAM,CAAC;IAErB,0CAA0C;IAC1C,yBAAyB,EAAE,MAAM,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IAEvD,8CAA8C;IAC9C,cAAc,EAAE,OAAO,CAAC;IAExB,uCAAuC;IACvC,gBAAgB,EAAE,OAAO,CAAC;IAE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