deepthinking-mcp 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
- # DeepThinking MCP v2.5
1
+ # DeepThinking MCP v3.1.0
2
2
 
3
- A comprehensive Model Context Protocol (MCP) server featuring **13 advanced reasoning modes** with intelligent mode recommendation and visual export capabilities for complex problem-solving, analysis, and decision-making.
3
+ A comprehensive Model Context Protocol (MCP) server featuring **14 advanced reasoning modes** with intelligent mode recommendation, visual export capabilities, high-performance validation caching, comprehensive testing, and automated CI/CD for complex problem-solving, analysis, and decision-making.
4
4
 
5
5
  ## Overview
6
6
 
7
- DeepThinking MCP v2.5 provides a complete toolkit for structured reasoning with 13 specialized modes, an intelligent recommendation system, and powerful visual export capabilities:
7
+ DeepThinking MCP v3.1 provides a complete toolkit for structured reasoning with 14 specialized modes, an intelligent recommendation system, powerful visual export capabilities, and optimized performance through validation caching:
8
8
 
9
9
  ### Core Modes
10
10
  - **Sequential**: Iterative refinement with revision capabilities
@@ -23,6 +23,7 @@ n### Phase 3 Modes (v2.3+)
23
23
  - **Temporal**: Event timelines, temporal constraints, Allen's interval algebra, causal relations over time
24
24
  - **Game Theory**: Nash equilibria, strategic analysis, payoff matrices, dominant strategies, game trees
25
25
  - **Evidential**: Dempster-Shafer theory, belief functions, evidence combination, uncertainty intervals
26
+ - **First-Principles**: Deductive reasoning from foundational axioms and principles
26
27
 
27
28
  ## Features
28
29
 
@@ -45,6 +46,7 @@ n#### Phase 3 Reasoning Modes (v2.3+)
45
46
  - **Temporal**: Model events, intervals, and temporal relationships using Allen's interval algebra. Track causality over time with timestamps, durations, and temporal constraints. Perfect for timeline analysis, scheduling problems, and understanding event sequences.
46
47
  - **Game Theory**: Analyze strategic interactions between rational agents. Define games, players, and strategies. Compute Nash equilibria (pure and mixed), identify dominant strategies, construct payoff matrices, and build extensive-form game trees. Ideal for competitive analysis, mechanism design, and strategic decision-making.
47
48
  - **Evidential**: Apply Dempster-Shafer theory for reasoning with uncertain and incomplete evidence. Define hypotheses, collect evidence with reliability scores, assign belief functions with mass assignments, combine evidence using Dempster's rule, compute belief and plausibility intervals, and make decisions under uncertainty. Ideal for sensor fusion, diagnostic reasoning, intelligence analysis, and situations with incomplete information.
49
+ - **First-Principles**: Derive conclusions from foundational axioms and principles using deductive reasoning. Define principles (axioms, definitions, observations), build derivation chains with logical inferences, track confidence levels, and reach conclusions with certainty analysis. Ideal for fundamental analysis, conceptual understanding, and reasoning from basic truths.
48
50
 
49
51
  ### Mathematical Enhancements
50
52
  - **Symbolic computation** support with LaTeX and symbolic formats
@@ -73,6 +75,23 @@ n#### Phase 3 Reasoning Modes (v2.3+)
73
75
  - **Problem Characteristics Analysis**: Analyzes domain, complexity, uncertainty, time-dependence, and more
74
76
  - **Ranked Recommendations**: Returns modes sorted by suitability score with detailed reasoning
75
77
 
78
+ ### Performance & Optimization (v3.0)
79
+ - **Validation Caching**: LRU cache with content-based hashing for validation results
80
+ - **1.4-17x speedup** for repeated validations (typically 4-5x in realistic workloads)
81
+ - **O(1) lookup complexity** regardless of cache size
82
+ - **95%+ hit rates** in typical usage patterns
83
+ - Configurable cache size (default: 1000 entries)
84
+ - Automatic cache statistics tracking in session metrics
85
+ - **Modular Validator Architecture**: Clean separation of concerns with mode-specific validators
86
+ - **Session Metrics**: Comprehensive performance tracking including cache statistics
87
+
88
+ ### Configuration Options
89
+ ```javascript
90
+ // Environment variables for performance tuning
91
+ MCP_ENABLE_VALIDATION_CACHE=true // Enable/disable caching (default: true)
92
+ MCP_VALIDATION_CACHE_SIZE=1000 // Max cache entries (default: 1000)
93
+ ```
94
+
76
95
  ## Installation
77
96
 
78
97
  ```bash
@@ -175,11 +194,7 @@ Export your reasoning sessions as visual diagrams in multiple formats for presen
175
194
  - **DOT**: Graphviz format for professional graph visualization and publication-quality diagrams
176
195
  - **ASCII**: Plain text diagrams for terminal output, logs, and text-based documentation
177
196
 
178
- #### Supported Modes
179
- - **Causal Mode**: Export causal graphs showing cause-effect relationships with node types (causes, effects, mediators, confounders) and edge strengths
180
- - **Temporal Mode**: Export timelines as Gantt charts showing events, intervals, and temporal relationships
181
- - **Game Theory Mode**: Export game trees with strategies, decision nodes, and payoffs
182
- - **Bayesian Mode**: Export Bayesian networks showing prior/posterior relationships and evidence flow
197
+ #### Supported Modes**All 14 modes now support visual export (100% coverage):**- **Causal Mode**: Export causal graphs showing cause-effect relationships with node types (causes, effects, mediators, confounders) and edge strengths- **Temporal Mode**: Export timelines as Gantt charts showing events, intervals, and temporal relationships- **Game Theory Mode**: Export game trees with strategies, decision nodes, and payoffs- **Bayesian Mode**: Export Bayesian networks showing prior/posterior relationships and evidence flow- **First-Principles Mode**: Export derivation chains showing question → principles → derivation steps → conclusion flow- **All Other Modes**: Generic thought sequence visualization showing reasoning progression for Sequential, Shannon, Mathematics, Physics, Hybrid, Abductive, Counterfactual, Analogical, and Evidential modes
183
198
 
184
199
  #### Visual Export Examples
185
200
 
@@ -262,7 +277,7 @@ Visual exports work seamlessly with:
262
277
  - `thoughtNumber` (number, required): Position in sequence
263
278
  - `totalThoughts` (number, required): Estimated total thoughts needed
264
279
  - `nextThoughtNeeded` (boolean, required): Whether to continue thinking
265
- - `mode` (string, optional): `sequential`, `shannon`, `mathematics`, `physics`, `hybrid`, `abductive`, `causal`, `bayesian`, `counterfactual`, `analogical`, or `temporal` (default: `hybrid`)
280
+ - `mode` (string, optional): `sequential`, `shannon`, `mathematics`, `physics`, `hybrid`, `abductive`, `causal`, `bayesian`, `counterfactual`, `analogical`, or `temporal`, `gametheory`, `evidential`, `firstprinciple` (default: `hybrid`)
266
281
 
267
282
  ### Mode-Specific Parameters
268
283
 
@@ -349,6 +364,26 @@ n#### Temporal Mode
349
364
  - `combinedBelief`: Belief function resulting from Dempster-Shafer combination (includes conflictMass)
350
365
  - `plausibility`: Plausibility function with belief/plausibility values and uncertainty intervals
351
366
  - `decisions`: Decision analysis (selectedHypothesis, confidence, reasoning, alternatives)
367
+ n#### First-Principles Mode
368
+ - `question`: The question being answered from first principles
369
+ - `principles`: Array of foundational principles with:
370
+ - `id`: Unique identifier
371
+ - `type`: Principle type (axiom, definition, observation, logical_inference, assumption)
372
+ - `statement`: The principle statement
373
+ - `justification`: Why this principle is valid
374
+ - `dependsOn`: Optional array of principle IDs this depends on
375
+ - `derivationSteps`: Chain of reasoning steps with:
376
+ - `stepNumber`: Step position in derivation
377
+ - `principle`: The principle being applied
378
+ - `inference`: What is inferred from this principle
379
+ - `logicalForm`: Optional formal logic representation
380
+ - `confidence`: Confidence in this step (0-1)
381
+ - `conclusion`: Final conclusion with:
382
+ - `statement`: The conclusion statement
383
+ - `derivationChain`: Array of step numbers leading to conclusion
384
+ - `certainty`: Overall certainty level (0-1)
385
+ - `limitations`: Optional array of known limitations or assumptions
386
+ - `alternativeInterpretations`: Optional array of other possible interpretations
352
387
 
353
388
  ### Actions
354
389
  - `add_thought` (default): Add a new thought to session
@@ -618,6 +653,87 @@ npm test
618
653
  npm run typecheck
619
654
  ```
620
655
 
656
+ ### Testing & CI/CD
657
+
658
+ #### Comprehensive Test Suite (v3.0.2)
659
+
660
+ DeepThinking MCP includes **397 tests** across **24 test files** with **100% pass rate**:
661
+
662
+ - **Unit Tests**: Core functionality, validators, session management
663
+ - **Integration Tests (94 tests)**: MCP protocol compliance, multi-session scenarios, error handling
664
+ - **Benchmark Tests**: Performance validation (15x speedup with caching)
665
+ - **Mode-Specific Tests**: All 13 reasoning modes thoroughly tested
666
+
667
+ **Test Coverage:**
668
+ ```bash
669
+ # Run full test suite
670
+ npm test
671
+
672
+ # Run with coverage report
673
+ npm run test:coverage
674
+
675
+ # Run specific test file
676
+ npm test -- tests/integration/mcp-protocol.test.ts
677
+ ```
678
+
679
+ **Test Results:**
680
+ - Test Files: 24 passed
681
+ - Tests: 397 passed
682
+ - Duration: ~7-8 seconds
683
+ - Pass Rate: 100%
684
+
685
+ #### CI/CD Pipeline
686
+
687
+ Automated workflows using GitHub Actions ensure code quality and reliability:
688
+
689
+ **Test Workflow** (`.github/workflows/test.yml`):
690
+ - Multi-OS testing: Ubuntu, Windows, macOS
691
+ - Multi-Node version: 18.x, 20.x, 22.x
692
+ - Runs: TypeScript checks, linter, formatter, full test suite
693
+ - Test result artifacts with 30-day retention
694
+
695
+ **Coverage Workflow** (`.github/workflows/coverage.yml`):
696
+ - Generates detailed coverage reports
697
+ - Codecov integration for coverage tracking
698
+ - PR comments with coverage summary
699
+ - Coverage badge generation
700
+ - Threshold warnings (<60% triggers warning)
701
+
702
+ **Release Workflow** (`.github/workflows/release.yml`):
703
+ - Automated releases on version tags (v*.*.*)
704
+ - Pre-release testing (type check + full test suite)
705
+ - GitHub release creation with changelog
706
+ - npm publishing (requires NPM_TOKEN)
707
+ - Workflow dispatch for manual releases
708
+
709
+ **Branch Protection:**
710
+ See `.github/BRANCH_PROTECTION.md` for recommended settings:
711
+ - Required status checks before merging
712
+ - PR review requirements
713
+ - Linear history enforcement
714
+ - Force push protection
715
+
716
+ #### Integration Tests
717
+
718
+ **MCP Protocol Compliance** (43 tests):
719
+ - Tool schema validation for all 13 modes
720
+ - Required/optional field validation
721
+ - MCP response format compliance
722
+ - Error handling for invalid inputs
723
+
724
+ **Multi-Session Scenarios** (18 tests):
725
+ - Session isolation and concurrent operations
726
+ - Resource management (50+ sessions)
727
+ - State consistency verification
728
+ - Concurrent error handling
729
+
730
+ **Error Handling & Edge Cases** (36 tests):
731
+ - Invalid session operations
732
+ - Boundary conditions (0, 1, MAX_SAFE_INTEGER)
733
+ - Large data handling (100 thoughts, 50 dependencies)
734
+ - Unicode and special character support
735
+ - Mode-specific edge cases
736
+
621
737
  ## Architecture
622
738
 
623
739
  ```
@@ -650,21 +766,40 @@ deepthinking-mcp/
650
766
  - ✅ Comprehensive test suite (77 tests)
651
767
  - ✅ Enhanced type safety
652
768
 
653
- ### Phase 3 (In Progress)
769
+ ### Phase 3 (Completed - v3.1.0)
654
770
  - ✅ Temporal reasoning mode (v2.1)
655
771
  - ✅ Game theory mode (v2.2)
656
772
  - ✅ Evidential reasoning mode (v2.3)
657
773
  - ✅ Mode recommendation system (v2.4)
658
774
  - ✅ Visual exports - Mermaid, DOT, ASCII (v2.5)
659
775
  - ✅ Export to LaTeX/Jupyter/HTML (v2.5)
776
+ - ✅ Performance optimization with validation caching (v3.0)
777
+ - ✅ Integration tests & MCP compliance (v3.0.2)
778
+ - ✅ CI/CD pipeline with GitHub Actions (v3.0.2)
779
+ - ✅ First-Principles reasoning mode (v3.1.0)
780
+ - ✅ Universal visual export support for all 14 modes (v3.1.0)
781
+
782
+ ### Phase 4 (Planned)
660
783
  - [ ] Math-MCP integration
661
784
  - [ ] Persistence layer
662
785
  - [ ] Collaborative thinking sessions
663
786
  - [ ] Pattern learning from successful reasoning chains
787
+ - [ ] Advanced visualization dashboard
788
+ - [ ] Real-time reasoning collaboration
664
789
 
665
790
  ## Contributing
666
791
 
667
- Contributions welcome! Please read our contributing guidelines and submit PRs.
792
+ Contributions welcome! Please ensure:
793
+
794
+ 1. **All tests pass**: Run `npm test` before submitting PRs
795
+ 2. **Type checking passes**: Run `npm run typecheck`
796
+ 3. **Code formatting**: Run `npm run format:check` or `npm run format`
797
+ 4. **Linting passes**: Run `npm run lint`
798
+ 5. **CI/CD workflows pass**: All GitHub Actions checks must pass
799
+ 6. **Test coverage**: Maintain or improve test coverage
800
+ 7. **Documentation**: Update README.md and CHANGELOG.md for new features
801
+
802
+ See `.github/BRANCH_PROTECTION.md` for branch protection requirements and `.github/workflows/` for CI/CD pipeline details.
668
803
 
669
804
  ## License
670
805
 
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ import { z } from 'zod';
10
10
 
11
11
  var ThinkingToolSchema = z.object({
12
12
  sessionId: z.string().optional(),
13
- mode: z.enum(["sequential", "shannon", "mathematics", "physics", "hybrid", "abductive", "causal", "bayesian", "counterfactual", "analogical", "temporal", "gametheory", "evidential"]).default("hybrid"),
13
+ mode: z.enum(["sequential", "shannon", "mathematics", "physics", "hybrid", "abductive", "causal", "bayesian", "counterfactual", "analogical", "temporal", "gametheory", "evidential", "firstprinciple"]).default("hybrid"),
14
14
  thought: z.string(),
15
15
  thoughtNumber: z.number().int().positive(),
16
16
  totalThoughts: z.number().int().positive(),
@@ -397,9 +397,38 @@ var ThinkingToolSchema = z.object({
397
397
  risk: z.number()
398
398
  }))
399
399
  })).optional(),
400
+ // First-principles reasoning properties (v3.1.0)
401
+ question: z.string().optional(),
402
+ principles: z.array(z.object({
403
+ id: z.string(),
404
+ type: z.enum(["axiom", "definition", "observation", "logical_inference", "assumption"]),
405
+ statement: z.string(),
406
+ justification: z.string(),
407
+ dependsOn: z.array(z.string()).optional()
408
+ })).optional(),
409
+ derivationSteps: z.array(z.object({
410
+ stepNumber: z.number(),
411
+ principle: z.object({
412
+ id: z.string(),
413
+ type: z.enum(["axiom", "definition", "observation", "logical_inference", "assumption"]),
414
+ statement: z.string(),
415
+ justification: z.string(),
416
+ dependsOn: z.array(z.string()).optional()
417
+ }),
418
+ inference: z.string(),
419
+ logicalForm: z.string().optional(),
420
+ confidence: z.number().min(0).max(1)
421
+ })).optional(),
422
+ conclusion: z.object({
423
+ statement: z.string(),
424
+ derivationChain: z.array(z.number()),
425
+ certainty: z.number().min(0).max(1),
426
+ limitations: z.array(z.string()).optional()
427
+ }).optional(),
428
+ alternativeInterpretations: z.array(z.string()).optional(),
400
429
  action: z.enum(["add_thought", "summarize", "export", "switch_mode", "get_session", "recommend_mode"]).default("add_thought"),
401
430
  exportFormat: z.enum(["markdown", "latex", "json", "html", "jupyter", "mermaid", "dot", "ascii"]).optional(),
402
- newMode: z.enum(["sequential", "shannon", "mathematics", "physics", "hybrid", "abductive", "causal", "bayesian", "counterfactual", "analogical", "temporal", "gametheory", "evidential"]).optional(),
431
+ newMode: z.enum(["sequential", "shannon", "mathematics", "physics", "hybrid", "abductive", "causal", "bayesian", "counterfactual", "analogical", "temporal", "gametheory", "evidential", "firstprinciple"]).optional(),
403
432
  // Mode recommendation parameters (v2.4)
404
433
  problemType: z.string().optional(),
405
434
  problemCharacteristics: z.object({
@@ -847,19 +876,15 @@ Choose the mode that best fits your problem type, or use recommend_mode to get i
847
876
  }
848
877
  };
849
878
 
850
- // src/types/modes/temporal.ts
879
+ // src/types/core.ts
851
880
  function isTemporalThought(thought) {
852
- return thought.mode === "temporal";
881
+ return thought.mode === "temporal" /* TEMPORAL */;
853
882
  }
854
-
855
- // src/types/modes/gametheory.ts
856
883
  function isGameTheoryThought(thought) {
857
- return thought.mode === "gametheory";
884
+ return thought.mode === "gametheory" /* GAMETHEORY */;
858
885
  }
859
-
860
- // src/types/modes/evidential.ts
861
886
  function isEvidentialThought(thought) {
862
- return thought.mode === "evidential";
887
+ return thought.mode === "evidential" /* EVIDENTIAL */;
863
888
  }
864
889
 
865
890
  // src/types/modes/recommendations.ts
@@ -1113,15 +1138,9 @@ var DeepThinkingError = class extends Error {
1113
1138
  };
1114
1139
  }
1115
1140
  };
1116
- var SessionError = class extends DeepThinkingError {
1117
- constructor(message, context) {
1118
- super(message, "SESSION_ERROR", context);
1119
- }
1120
- };
1121
- var SessionNotFoundError = class extends SessionError {
1141
+ var SessionNotFoundError = class extends DeepThinkingError {
1122
1142
  constructor(sessionId) {
1123
- super(`Session not found: ${sessionId}`, { sessionId });
1124
- this.code = "SESSION_NOT_FOUND";
1143
+ super(`Session not found: ${sessionId}`, "SESSION_NOT_FOUND", { sessionId });
1125
1144
  }
1126
1145
  };
1127
1146
 
@@ -1613,7 +1632,7 @@ var SessionManager = class {
1613
1632
  let session = this.activeSessions.get(sessionId);
1614
1633
  if (!session && this.storage) {
1615
1634
  try {
1616
- session = await this.storage.loadSession(sessionId);
1635
+ session = await this.storage.loadSession(sessionId) ?? void 0;
1617
1636
  if (session) {
1618
1637
  this.activeSessions.set(sessionId, session);
1619
1638
  this.logger.debug("Session loaded from storage", { sessionId });
@@ -1911,7 +1930,7 @@ var SessionManager = class {
1911
1930
  updateMetrics(session, thought) {
1912
1931
  const metrics = session.metrics;
1913
1932
  metrics.totalThoughts = session.thoughts.length;
1914
- const thoughtType = thought.type || "unknown";
1933
+ const thoughtType = thought.mode || "unknown";
1915
1934
  metrics.thoughtsByType[thoughtType] = (metrics.thoughtsByType[thoughtType] || 0) + 1;
1916
1935
  if (thought.isRevision) {
1917
1936
  metrics.revisionCount++;
@@ -1921,9 +1940,11 @@ var SessionManager = class {
1921
1940
  const uncertaintyValue = thought.uncertainty;
1922
1941
  const currentSum = metrics._uncertaintySum || 0;
1923
1942
  const currentCount = metrics._uncertaintyCount || 0;
1924
- metrics._uncertaintySum = currentSum + uncertaintyValue;
1925
- metrics._uncertaintyCount = currentCount + 1;
1926
- metrics.averageUncertainty = metrics._uncertaintySum / metrics._uncertaintyCount;
1943
+ const newSum = currentSum + uncertaintyValue;
1944
+ const newCount = currentCount + 1;
1945
+ metrics._uncertaintySum = newSum;
1946
+ metrics._uncertaintyCount = newCount;
1947
+ metrics.averageUncertainty = newSum / newCount;
1927
1948
  }
1928
1949
  if ("dependencies" in thought && thought.dependencies) {
1929
1950
  const deps = thought.dependencies;
@@ -2269,7 +2290,7 @@ var VisualExporter = class {
2269
2290
  return ascii;
2270
2291
  }
2271
2292
  // ===== Game Theory Exporters =====
2272
- gameTreeToMermaid(thought, colorScheme, includeLabels, includeMetrics) {
2293
+ gameTreeToMermaid(thought, _colorScheme, includeLabels, includeMetrics) {
2273
2294
  let mermaid = "graph TD\n";
2274
2295
  if (!thought.game) {
2275
2296
  return mermaid + " root[No game defined]\n";
@@ -2277,8 +2298,8 @@ var VisualExporter = class {
2277
2298
  if (thought.gameTree && thought.gameTree.nodes) {
2278
2299
  for (const node of thought.gameTree.nodes) {
2279
2300
  const nodeId = this.sanitizeId(node.id);
2280
- const label = includeLabels ? node.name : nodeId;
2281
- const shape = node.isTerminal ? ["[[", "]]"] : ["[", "]"];
2301
+ const label = includeLabels ? node.action || node.id : nodeId;
2302
+ const shape = node.type === "terminal" ? ["[[", "]]"] : ["[", "]"];
2282
2303
  mermaid += ` ${nodeId}${shape[0]}${label}${shape[1]}
2283
2304
  `;
2284
2305
  }
@@ -2322,8 +2343,8 @@ var VisualExporter = class {
2322
2343
  if (thought.gameTree && thought.gameTree.nodes) {
2323
2344
  for (const node of thought.gameTree.nodes) {
2324
2345
  const nodeId = this.sanitizeId(node.id);
2325
- const label = includeLabels ? node.name : nodeId;
2326
- const shape = node.isTerminal ? "doublecircle" : "circle";
2346
+ const label = includeLabels ? node.action || node.id : nodeId;
2347
+ const shape = node.type === "terminal" ? "doublecircle" : "circle";
2327
2348
  dot += ` ${nodeId} [label="${label}", shape=${shape}];
2328
2349
  `;
2329
2350
  }
@@ -2355,13 +2376,14 @@ var VisualExporter = class {
2355
2376
  if (thought.strategies && thought.strategies.length > 0) {
2356
2377
  ascii += "Strategies:\n";
2357
2378
  for (const strategy of thought.strategies) {
2358
- ascii += ` \u2022 ${strategy.name} (${strategy.type})
2379
+ const strategyType = strategy.isPure ? "Pure" : "Mixed";
2380
+ ascii += ` \u2022 ${strategy.name} (${strategyType})
2359
2381
  `;
2360
2382
  }
2361
2383
  }
2362
- if (thought.equilibria && thought.equilibria.length > 0) {
2384
+ if (thought.nashEquilibria && thought.nashEquilibria.length > 0) {
2363
2385
  ascii += "\nEquilibria:\n";
2364
- for (const eq of thought.equilibria) {
2386
+ for (const eq of thought.nashEquilibria) {
2365
2387
  ascii += ` \u2696 ${eq.type}: ${eq.strategyProfile.join(", ")}
2366
2388
  `;
2367
2389
  ascii += ` Payoffs: [${eq.payoffs.join(", ")}]
@@ -2371,7 +2393,7 @@ var VisualExporter = class {
2371
2393
  return ascii;
2372
2394
  }
2373
2395
  // ===== Bayesian Network Exporters =====
2374
- bayesianToMermaid(thought, colorScheme, includeLabels, includeMetrics) {
2396
+ bayesianToMermaid(thought, colorScheme, _includeLabels, includeMetrics) {
2375
2397
  let mermaid = "graph LR\n";
2376
2398
  mermaid += ` H([Hypothesis])
2377
2399
  `;
@@ -2396,7 +2418,7 @@ var VisualExporter = class {
2396
2418
  }
2397
2419
  return mermaid;
2398
2420
  }
2399
- bayesianToDOT(thought, includeLabels, includeMetrics) {
2421
+ bayesianToDOT(thought, _includeLabels, includeMetrics) {
2400
2422
  let dot = "digraph BayesianNetwork {\n";
2401
2423
  dot += " rankdir=LR;\n";
2402
2424
  dot += " node [shape=ellipse];\n\n";
@@ -2431,14 +2453,14 @@ var VisualExporter = class {
2431
2453
  if (thought.evidence && thought.evidence.length > 0) {
2432
2454
  ascii += "Evidence:\n";
2433
2455
  for (const ev of thought.evidence) {
2434
- ascii += ` \u2022 ${ev.observation}
2456
+ ascii += ` \u2022 ${ev.description}
2435
2457
  `;
2436
2458
  }
2437
2459
  ascii += "\n";
2438
2460
  }
2439
2461
  ascii += `Posterior Probability: ${thought.posterior.probability.toFixed(3)}
2440
2462
  `;
2441
- ascii += ` Justification: ${thought.posterior.justification}
2463
+ ascii += ` Calculation: ${thought.posterior.calculation}
2442
2464
  `;
2443
2465
  if (thought.bayesFactor !== void 0) {
2444
2466
  ascii += `
@@ -2454,6 +2476,215 @@ Bayes Factor: ${thought.bayesFactor.toFixed(2)}
2454
2476
  sanitizeId(id) {
2455
2477
  return id.replace(/[^a-zA-Z0-9_]/g, "_");
2456
2478
  }
2479
+ // ===== Generic Thought Sequence Export =====
2480
+ /**
2481
+ * Export any thought sequence as a flow diagram
2482
+ * Works for sequential, shannon, mathematics, physics, hybrid, abductive,
2483
+ * counterfactual, analogical, and evidential modes
2484
+ */
2485
+ exportThoughtSequence(thoughts, options) {
2486
+ const { format, colorScheme = "default" } = options;
2487
+ switch (format) {
2488
+ case "mermaid":
2489
+ return this.thoughtSequenceToMermaid(thoughts, colorScheme);
2490
+ case "dot":
2491
+ return this.thoughtSequenceToDOT(thoughts);
2492
+ case "ascii":
2493
+ return this.thoughtSequenceToASCII(thoughts);
2494
+ default:
2495
+ throw new Error(`Unsupported format: ${format}`);
2496
+ }
2497
+ }
2498
+ thoughtSequenceToMermaid(thoughts, colorScheme) {
2499
+ let mermaid = "graph TD\n";
2500
+ for (let i = 0; i < thoughts.length; i++) {
2501
+ const thought = thoughts[i];
2502
+ const nodeId = `T${i + 1}`;
2503
+ const content = thought.content.substring(0, 60).replace(/\n/g, " ");
2504
+ const label = `${i + 1}. ${content}${thought.content.length > 60 ? "..." : ""}`;
2505
+ mermaid += ` ${nodeId}["${label}"]
2506
+ `;
2507
+ if (i > 0) {
2508
+ mermaid += ` T${i} --> ${nodeId}
2509
+ `;
2510
+ }
2511
+ }
2512
+ if (colorScheme !== "monochrome" && thoughts.length > 0) {
2513
+ mermaid += "\n";
2514
+ const color = colorScheme === "pastel" ? "#e1f5ff" : "#a8d5ff";
2515
+ mermaid += ` style T1 fill:${color}
2516
+ `;
2517
+ if (thoughts.length > 1) {
2518
+ const endColor = colorScheme === "pastel" ? "#e8f5e9" : "#c8e6c9";
2519
+ mermaid += ` style T${thoughts.length} fill:${endColor}
2520
+ `;
2521
+ }
2522
+ }
2523
+ return mermaid;
2524
+ }
2525
+ thoughtSequenceToDOT(thoughts) {
2526
+ let dot = "digraph ThoughtSequence {\n";
2527
+ dot += " rankdir=TD;\n";
2528
+ dot += " node [shape=box, style=rounded];\n\n";
2529
+ for (let i = 0; i < thoughts.length; i++) {
2530
+ const thought = thoughts[i];
2531
+ const nodeId = `T${i + 1}`;
2532
+ const content = thought.content.substring(0, 60).replace(/"/g, '\\"').replace(/\n/g, " ");
2533
+ const label = `${i + 1}. ${content}${thought.content.length > 60 ? "..." : ""}`;
2534
+ dot += ` ${nodeId} [label="${label}"];
2535
+ `;
2536
+ if (i > 0) {
2537
+ dot += ` T${i} -> ${nodeId};
2538
+ `;
2539
+ }
2540
+ }
2541
+ dot += "}\n";
2542
+ return dot;
2543
+ }
2544
+ thoughtSequenceToASCII(thoughts) {
2545
+ let ascii = "Thought Sequence:\n";
2546
+ ascii += "=================\n\n";
2547
+ for (let i = 0; i < thoughts.length; i++) {
2548
+ const thought = thoughts[i];
2549
+ ascii += `${i + 1}. ${thought.content}
2550
+ `;
2551
+ if (i < thoughts.length - 1) {
2552
+ ascii += " \u2193\n";
2553
+ }
2554
+ ascii += "\n";
2555
+ }
2556
+ return ascii;
2557
+ }
2558
+ // ===== First-Principles Export =====
2559
+ /**
2560
+ * Export first-principles reasoning to visual format
2561
+ */
2562
+ exportFirstPrinciples(thought, options) {
2563
+ const { format, colorScheme = "default" } = options;
2564
+ switch (format) {
2565
+ case "mermaid":
2566
+ return this.firstPrinciplesToMermaid(thought, colorScheme);
2567
+ case "dot":
2568
+ return this.firstPrinciplesToDOT(thought);
2569
+ case "ascii":
2570
+ return this.firstPrinciplesToASCII(thought);
2571
+ default:
2572
+ throw new Error(`Unsupported format: ${format}`);
2573
+ }
2574
+ }
2575
+ firstPrinciplesToMermaid(thought, colorScheme) {
2576
+ let mermaid = "graph TD\n";
2577
+ mermaid += ` Q["Question: ${thought.question}"]
2578
+ `;
2579
+ for (const principle of thought.principles) {
2580
+ const pid = this.sanitizeId(principle.id);
2581
+ mermaid += ` ${pid}["${principle.type}: ${principle.statement}"]
2582
+ `;
2583
+ }
2584
+ for (const step of thought.derivationSteps) {
2585
+ const sid = `S${step.stepNumber}`;
2586
+ const pid = this.sanitizeId(step.principle.id);
2587
+ mermaid += ` ${sid}["Step ${step.stepNumber}: ${step.inference}"]
2588
+ `;
2589
+ mermaid += ` ${pid} --> ${sid}
2590
+ `;
2591
+ if (step.stepNumber > 1) {
2592
+ mermaid += ` S${step.stepNumber - 1} --> ${sid}
2593
+ `;
2594
+ } else {
2595
+ mermaid += ` Q --> ${pid}
2596
+ `;
2597
+ }
2598
+ }
2599
+ mermaid += ` C[["Conclusion: ${thought.conclusion.statement}"]]:
2600
+ `;
2601
+ if (thought.derivationSteps.length > 0) {
2602
+ mermaid += ` S${thought.derivationSteps.length} --> C
2603
+ `;
2604
+ }
2605
+ if (colorScheme !== "monochrome") {
2606
+ mermaid += "\n";
2607
+ const qColor = colorScheme === "pastel" ? "#fff3e0" : "#ffeb3b";
2608
+ const cColor = colorScheme === "pastel" ? "#e8f5e9" : "#4caf50";
2609
+ mermaid += ` style Q fill:${qColor}
2610
+ `;
2611
+ mermaid += ` style C fill:${cColor}
2612
+ `;
2613
+ }
2614
+ return mermaid;
2615
+ }
2616
+ firstPrinciplesToDOT(thought) {
2617
+ let dot = "digraph FirstPrinciples {\n";
2618
+ dot += " rankdir=TD;\n";
2619
+ dot += " node [shape=box, style=rounded];\n\n";
2620
+ dot += ` Q [label="Question:\\n${thought.question}", shape=ellipse];
2621
+ `;
2622
+ for (const principle of thought.principles) {
2623
+ const pid = this.sanitizeId(principle.id);
2624
+ dot += ` ${pid} [label="${principle.type}:\\n${principle.statement}"];
2625
+ `;
2626
+ }
2627
+ for (const step of thought.derivationSteps) {
2628
+ const sid = `S${step.stepNumber}`;
2629
+ const pid = this.sanitizeId(step.principle.id);
2630
+ dot += ` ${sid} [label="Step ${step.stepNumber}:\\n${step.inference}"];
2631
+ `;
2632
+ dot += ` ${pid} -> ${sid};
2633
+ `;
2634
+ if (step.stepNumber > 1) {
2635
+ dot += ` S${step.stepNumber - 1} -> ${sid};
2636
+ `;
2637
+ } else {
2638
+ dot += ` Q -> ${pid};
2639
+ `;
2640
+ }
2641
+ }
2642
+ dot += ` C [label="Conclusion:\\n${thought.conclusion.statement}", shape=doubleoctagon];
2643
+ `;
2644
+ if (thought.derivationSteps.length > 0) {
2645
+ dot += ` S${thought.derivationSteps.length} -> C;
2646
+ `;
2647
+ }
2648
+ dot += "}\n";
2649
+ return dot;
2650
+ }
2651
+ firstPrinciplesToASCII(thought) {
2652
+ let ascii = "First-Principles Reasoning:\n";
2653
+ ascii += "===========================\n\n";
2654
+ ascii += `Question: ${thought.question}
2655
+
2656
+ `;
2657
+ ascii += "Foundational Principles:\n";
2658
+ for (const principle of thought.principles) {
2659
+ ascii += ` \u2022 [${principle.type}] ${principle.statement}
2660
+ `;
2661
+ ascii += ` Justification: ${principle.justification}
2662
+ `;
2663
+ }
2664
+ ascii += "\n";
2665
+ ascii += "Derivation Chain:\n";
2666
+ for (const step of thought.derivationSteps) {
2667
+ ascii += ` ${step.stepNumber}. ${step.inference}
2668
+ `;
2669
+ ascii += ` (From: ${step.principle.statement})
2670
+ `;
2671
+ ascii += ` Confidence: ${(step.confidence * 100).toFixed(0)}%
2672
+ `;
2673
+ }
2674
+ ascii += "\n";
2675
+ ascii += `Conclusion: ${thought.conclusion.statement}
2676
+ `;
2677
+ ascii += `Certainty: ${(thought.conclusion.certainty * 100).toFixed(0)}%
2678
+ `;
2679
+ if (thought.conclusion.limitations && thought.conclusion.limitations.length > 0) {
2680
+ ascii += "\nLimitations:\n";
2681
+ for (const limitation of thought.conclusion.limitations) {
2682
+ ascii += ` \u2022 ${limitation}
2683
+ `;
2684
+ }
2685
+ }
2686
+ return ascii;
2687
+ }
2457
2688
  };
2458
2689
 
2459
2690
  // src/utils/type-guards.ts
@@ -2644,8 +2875,16 @@ async function handleExport(input) {
2644
2875
  includeLabels: true,
2645
2876
  includeMetrics: true
2646
2877
  });
2878
+ } else if (lastThought.mode === "firstprinciple" && "question" in lastThought) {
2879
+ exported2 = visualExporter.exportFirstPrinciples(lastThought, {
2880
+ format,
2881
+ colorScheme: "default"
2882
+ });
2647
2883
  } else {
2648
- throw new Error(`Visual export not supported for mode: ${lastThought.mode}`);
2884
+ exported2 = visualExporter.exportThoughtSequence(session.thoughts, {
2885
+ format,
2886
+ colorScheme: "default"
2887
+ });
2649
2888
  }
2650
2889
  return {
2651
2890
  content: [{
@@ -2880,6 +3119,8 @@ function createThought(input, sessionId) {
2880
3119
  plausibility: input.plausibility,
2881
3120
  decisions: input.decisions || []
2882
3121
  };
3122
+ case "firstprinciple":
3123
+ return { ...baseThought, mode: "firstprinciple" /* FIRSTPRINCIPLE */, question: input.question || "", principles: input.principles || [], derivationSteps: input.derivationSteps || [], conclusion: input.conclusion || { statement: "", derivationChain: [], certainty: 0 }, alternativeInterpretations: input.alternativeInterpretations || [] };
2883
3124
  case "hybrid":
2884
3125
  default:
2885
3126
  return {