@aleph-ai/tinyaleph 1.5.6 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/core/alexander-module.js +1469 -0
  2. package/core/arithmetic-link-kernel.js +1338 -0
  3. package/core/index.js +95 -2
  4. package/examples/01-hello-world.js +69 -0
  5. package/examples/02-basic-hash.js +90 -0
  6. package/examples/02-observer-stack.js +385 -0
  7. package/examples/03-quantum-coin.js +136 -0
  8. package/examples/05-symbolic-resonance.js +146 -0
  9. package/examples/06-symbol-database.js +150 -0
  10. package/examples/07-semantic-inference.js +223 -0
  11. package/examples/08-compound-symbols.js +219 -0
  12. package/examples/README.md +170 -0
  13. package/examples/ai/01-embeddings.js +155 -0
  14. package/examples/ai/02-semantic-memory.js +243 -0
  15. package/examples/ai/03-reasoning.js +243 -0
  16. package/examples/ai/04-knowledge-graph.js +279 -0
  17. package/examples/ai/05-llm-integration.js +333 -0
  18. package/examples/ai/06-agent.js +294 -0
  19. package/examples/ai/07-hybrid-ai.js +223 -0
  20. package/examples/ai/08-entropy-reasoning.js +259 -0
  21. package/examples/ai/09-concept-learning.js +271 -0
  22. package/examples/ai/10-prompt-primes.js +312 -0
  23. package/examples/ai/11-rag.js +332 -0
  24. package/examples/ai/12-neuro-symbolic.js +321 -0
  25. package/examples/ai/README.md +80 -0
  26. package/examples/arithmetic-topology/01-legendre-symbol.js +78 -0
  27. package/examples/arithmetic-topology/02-redei-symbol.js +126 -0
  28. package/examples/arithmetic-topology/03-alk-kuramoto.js +138 -0
  29. package/examples/arithmetic-topology/04-alexander-module.js +117 -0
  30. package/examples/arithmetic-topology/05-signature-memory.js +118 -0
  31. package/examples/arithmetic-topology/README.md +291 -0
  32. package/examples/bioinformatics/01-dna-encoding.js +108 -0
  33. package/examples/bioinformatics/02-central-dogma.js +162 -0
  34. package/examples/bioinformatics/03-protein-folding.js +206 -0
  35. package/examples/bioinformatics/04-dna-computing.js +192 -0
  36. package/examples/bioinformatics/05-molecular-binding.js +209 -0
  37. package/examples/chat.js +105 -0
  38. package/examples/crt-homology/01-residue-encoding.js +87 -0
  39. package/examples/crt-homology/02-birkhoff-attention.js +100 -0
  40. package/examples/crt-homology/03-homology-loss.js +132 -0
  41. package/examples/crt-homology/04-crt-resoformer.js +132 -0
  42. package/examples/crt-homology/README.md +67 -0
  43. package/examples/crypto/01-password-hash.js +210 -0
  44. package/examples/crypto/02-key-derivation.js +210 -0
  45. package/examples/crypto/03-hmac.js +229 -0
  46. package/examples/crypto/04-file-integrity.js +263 -0
  47. package/examples/crypto/05-content-hash.js +263 -0
  48. package/examples/crypto/README.md +99 -0
  49. package/examples/demo-modular.js +223 -0
  50. package/examples/demo-two-layer.js +196 -0
  51. package/examples/discrete/01-integer-sine-table.js +120 -0
  52. package/examples/discrete/02-codebook-tunneling.js +118 -0
  53. package/examples/discrete/03-canonical-fusion.js +135 -0
  54. package/examples/discrete/04-tick-gate.js +139 -0
  55. package/examples/discrete/README.md +142 -0
  56. package/examples/formal-semantics/01-typed-terms.js +156 -0
  57. package/examples/formal-semantics/02-reduction.js +202 -0
  58. package/examples/formal-semantics/03-lambda-translation.js +206 -0
  59. package/examples/formal-semantics/04-enochian-language.js +257 -0
  60. package/examples/formal-semantics/README.md +98 -0
  61. package/examples/math/01-quaternions.js +237 -0
  62. package/examples/math/02-octonions.js +192 -0
  63. package/examples/math/03-prime-factorization.js +215 -0
  64. package/examples/math/04-vector-spaces.js +210 -0
  65. package/examples/math/05-gaussian-primes.js +234 -0
  66. package/examples/math/README.md +93 -0
  67. package/examples/physics/01-oscillator.js +177 -0
  68. package/examples/physics/02-lyapunov.js +201 -0
  69. package/examples/physics/03-collapse.js +183 -0
  70. package/examples/physics/04-kuramoto.js +212 -0
  71. package/examples/physics/05-entropy.js +226 -0
  72. package/examples/physics/05-sync-models.js +298 -0
  73. package/examples/physics/06-primeon-ladder.js +233 -0
  74. package/examples/physics/07-kuramoto-coupled-ladder.js +298 -0
  75. package/examples/physics/README.md +126 -0
  76. package/examples/resonance/01-prime-hilbert-space.js +140 -0
  77. package/examples/resonance/02-prime-resonance-network.js +221 -0
  78. package/examples/resonance/03-resoformer.js +349 -0
  79. package/examples/resonance/04-resoformer-training.js +329 -0
  80. package/examples/resonance/05-language-model.js +484 -0
  81. package/examples/resonance/README.md +238 -0
  82. package/examples/run-examples.js +417 -0
  83. package/examples/scientific/01-single-qubit.js +185 -0
  84. package/examples/scientific/02-two-qubit.js +209 -0
  85. package/examples/scientific/03-quantum-circuits.js +270 -0
  86. package/examples/scientific/04-measurement.js +229 -0
  87. package/examples/scientific/05-algorithms.js +245 -0
  88. package/examples/scientific/06-random.js +225 -0
  89. package/examples/scientific/07-wavefunction.js +192 -0
  90. package/examples/scientific/README.md +118 -0
  91. package/examples/semantic/01-vocabulary.js +186 -0
  92. package/examples/semantic/02-similarity.js +263 -0
  93. package/examples/semantic/03-word-algebra.js +295 -0
  94. package/examples/semantic/04-clustering.js +348 -0
  95. package/examples/semantic/05-classification.js +386 -0
  96. package/examples/semantic/06-dna-encoding.js +228 -0
  97. package/examples/semantic/07-search.js +304 -0
  98. package/examples/semantic/08-qa-system.js +278 -0
  99. package/examples/semantic/README.md +116 -0
  100. package/examples/topology/01-108-invariant.js +81 -0
  101. package/examples/topology/02-trefoil-constants.js +112 -0
  102. package/examples/topology/03-gauge-symmetry.js +112 -0
  103. package/examples/topology/04-free-energy-dynamics.js +124 -0
  104. package/examples/topology/README.md +129 -0
  105. package/index.js +32 -0
  106. package/modular.js +63 -2
  107. package/observer/agency.js +885 -0
  108. package/observer/assays.js +973 -0
  109. package/observer/boundary.js +1155 -0
  110. package/observer/entanglement.js +673 -0
  111. package/observer/hqe.js +1465 -0
  112. package/observer/index.js +158 -0
  113. package/observer/prsc.js +1289 -0
  114. package/observer/safety.js +815 -0
  115. package/observer/smf.js +1015 -0
  116. package/observer/symbolic-smf.js +726 -0
  117. package/observer/symbolic-temporal.js +790 -0
  118. package/observer/temporal.js +669 -0
  119. package/package.json +9 -3
  120. package/physics/alk-kuramoto.js +817 -0
  121. package/physics/index.js +23 -2
@@ -0,0 +1,238 @@
1
+ # Prime Resonance Examples
2
+
3
+ This directory contains examples demonstrating the Prime Resonance framework
4
+ from the TinyAleph library. These examples implement concepts from the
5
+ "Programming Reality" paper and the ResoFormer architecture specification.
6
+
7
+ ## Examples
8
+
9
+ ### 01-prime-hilbert-space.js
10
+ Demonstrates the mathematical foundation:
11
+ - Complex amplitudes in Prime Hilbert Space (HP)
12
+ - Resonance Operators: P̂ (projection), F̂ (Fourier), R̂ (rotation), Ĉ (collapse)
13
+ - Entropy-driven Hamiltonian evolution
14
+ - Memory encoding via prime factorization
15
+
16
+ Run: `node examples/resonance/01-prime-hilbert-space.js`
17
+
18
+ ### 02-prime-resonance-network.js
19
+ Demonstrates resonance network structures:
20
+ - Prime Resonance Identity (PRI)
21
+ - Phase-locked prime rings
22
+ - Holographic field encoding
23
+ - ResoLang-style fragments and entangled nodes
24
+
25
+ Run: `node examples/resonance/02-prime-resonance-network.js`
26
+
27
+ ### 03-resoformer.js
28
+ Demonstrates ResoFormer ML primitives (pure JavaScript):
29
+ - Quaternion-valued states: H_Q = H_P ⊗ ℍ
30
+ - Sparse prime state representations
31
+ - Resonance score: α·Jaccard + β·QuaternionAlign + γ·PhaseCoherence
32
+ - Resonant attention with top-k selection
33
+ - Hamilton product composition (non-commutative!)
34
+ - Coherence-gated adaptive computation (ACT-style)
35
+ - Entropy collapse to 64 attractors
36
+ - PR-Graph memory (put/get operations)
37
+
38
+ Run: `node examples/resonance/03-resoformer.js`
39
+
40
+ ### 04-resoformer-training.js
41
+ Demonstrates TensorFlow.js trainable ResoFormer:
42
+ - Custom TensorFlow.js layers for all ResoFormer components
43
+ - QuaternionDense, ResonantAttention, CoherenceGating layers
44
+ - EntropyCollapse layer with 64-attractor codebook
45
+ - ResoFormerBlock (complete transformer block)
46
+ - Model builders: createResoFormerClassifier, createResoFormerEmbedder
47
+ - Training on synthetic prime pattern classification task
48
+
49
+ **Requires:** `npm install @tensorflow/tfjs-node`
50
+
51
+ Run: `node examples/resonance/04-resoformer-training.js`
52
+
53
+ ## Key Concepts
54
+
55
+ ### State Space: H_Q = H_P ⊗ ℍ
56
+
57
+ The fundamental state space combines:
58
+ - **H_P**: Prime Hilbert Space with complex amplitudes on prime basis states
59
+ - **ℍ**: Quaternions for order-sensitive, non-commutative composition
60
+
61
+ ### Resonance Score
62
+
63
+ Attention weights computed from three components:
64
+ ```
65
+ score(q,k) = α·Jaccard(π_q, π_k) + β·QuatAlign(ĥ_q, ĥ_k) + γ·PhaseCoherence(φ_q, φ_k)
66
+ ```
67
+
68
+ Where:
69
+ - Jaccard: Prime overlap (shared structure)
70
+ - QuatAlign: Quaternion alignment via q^(-1)·k (orientation compatibility)
71
+ - PhaseCoherence: cos(φ_q - φ_k) (temporal alignment)
72
+
73
+ ### Entropy Collapse
74
+
75
+ VQ-style collapse to 64 attractors with target entropy ~5.99 bits (log₂64).
76
+ This acts as an information bottleneck enforcing discrete structure.
77
+
78
+ ### Coherence-Gated Computation
79
+
80
+ ACT-style adaptive depth where layers halt when coherence exceeds threshold:
81
+ ```
82
+ if C(t) ≥ τ: halt
83
+ else: continue
84
+ ```
85
+
86
+ ## Architecture Diagram
87
+
88
+ ```
89
+ Input Tokens
90
+
91
+
92
+ ┌─────────────────┐
93
+ │ Token Embedding │ → Standard embedding
94
+ └────────┬────────┘
95
+
96
+
97
+ ┌─────────────────────────────────────────┐
98
+ │ ResoFormer Block ×N │
99
+ │ ┌─────────────────────────────────┐ │
100
+ │ │ LayerNorm → ResonantAttention │ │
101
+ │ │ │ │ │
102
+ │ │ ▼ │ │
103
+ │ │ ResonanceOperator (R̂) │ │
104
+ │ │ │ │ │
105
+ │ │ ▼ │ │
106
+ │ │ LayerNorm → FFN (GELU) │ │
107
+ │ │ │ │ │
108
+ │ │ ▼ │ │
109
+ │ │ CoherenceGating (halt if C≥τ) │ │
110
+ │ │ │ │ │
111
+ │ │ ▼ │ │
112
+ │ │ EntropyCollapse (last layer) │ │
113
+ │ └─────────────────────────────────┘ │
114
+ └────────────────────┬────────────────────┘
115
+
116
+
117
+ Task Head (LM/Classifier/Embedder)
118
+ ```
119
+
120
+ ## Performance
121
+
122
+ On synthetic prime pattern classification (5 classes, 1000 samples):
123
+ - **Train accuracy**: 100% after 3 epochs
124
+ - **Test accuracy**: 100%
125
+ - **Training time**: ~11 seconds (TensorFlow.js on Node.js)
126
+
127
+ The model learns to distinguish sequences based on their prime structure
128
+ (multiples of 2, 3, 5, prime indices, alternating patterns).
129
+
130
+ This folder contains examples demonstrating the concepts from the paper:
131
+
132
+ **"Programming Reality: Prime Resonance Systems for Memory, Computation, and Probability Control"**
133
+
134
+ ## Examples
135
+
136
+ ### 01-prime-hilbert-space.js
137
+
138
+ Demonstrates the formal Prime Hilbert Space (HP):
139
+
140
+ - **Prime Basis States** `|p⟩` - Orthonormal basis indexed by primes
141
+ - **Complex Amplitudes** `αp ∈ ℂ` - Full quantum-like representation
142
+ - **Superposition** - Uniform and weighted superpositions
143
+ - **Composite States** - Factorization into prime components
144
+ - **Resonance Operators**:
145
+ - `P̂`: Eigenvalue operator (`P̂|p⟩ = p|p⟩`)
146
+ - `R̂(n)`: Phase rotation (`e^(2πi log_p(n))`)
147
+ - `Ĉ(n)`: Coupling operator
148
+ - `Ĥ`: Hadamard-like superposition
149
+ - **Born Measurement** - Probabilistic collapse
150
+ - **Entropy-Driven Evolution** - Equation (7) dynamics
151
+
152
+ ### 02-prime-resonance-network.js
153
+
154
+ Demonstrates the Prime Resonance Network (PRN) specification:
155
+
156
+ - **Prime Resonance Identity (PRI)** - Triadic identity `(P_G, P_E, P_Q)`:
157
+ - Gaussian primes
158
+ - Eisenstein primes
159
+ - Quaternionic primes
160
+ - **Phase-Locked Rings** - Irrational phase locks (φ, √2)
161
+ - **Holographic Memory** - 2D spatial encoding `I(x,y) = Σ A_p e^(-S) e^(ipθ)`
162
+ - **Entangled Nodes** - Network nodes with coherence and memory
163
+ - **Resonant Fragments** - Portable memory patterns
164
+ - **Memory Teleportation** - Conceptual demonstration
165
+
166
+ ## Running the Examples
167
+
168
+ ```bash
169
+ node examples/resonance/01-prime-hilbert-space.js
170
+ node examples/resonance/02-prime-resonance-network.js
171
+ ```
172
+
173
+ ## Key Concepts from the Paper
174
+
175
+ ### Prime Hilbert Space (Equation 1)
176
+ ```
177
+ HP = {|ψ⟩ = Σ αp|p⟩ : Σ|αp|² = 1, αp ∈ ℂ}
178
+ ```
179
+
180
+ ### Entropy-Driven Evolution (Equation 7)
181
+ ```
182
+ d|Ψ(t)⟩/dt = iĤ|Ψ(t)⟩ - λ(R̂ - r_stable)|Ψ(t)⟩
183
+ ```
184
+
185
+ ### Collapse Probability (Equation 8)
186
+ ```
187
+ P_collapse = 1 - e^(-∫S(t)dt)
188
+ ```
189
+
190
+ ### Holographic Encoding (Equation 11)
191
+ ```
192
+ I(x,y) = Σ A_p e^(-S(x,y)) e^(ipθ)
193
+ ```
194
+
195
+ ## API Reference
196
+
197
+ ### Core Hilbert Space
198
+
199
+ ```javascript
200
+ const { Complex, PrimeState, ResonanceOperators, EntropyDrivenEvolution } = require('tinyaleph');
201
+
202
+ // Create basis state
203
+ const state = PrimeState.basis(7);
204
+
205
+ // Create superposition
206
+ const uniform = PrimeState.uniform();
207
+
208
+ // Apply operators
209
+ const R5 = ResonanceOperators.R(5);
210
+ const rotated = R5(state);
211
+
212
+ // Evolve with entropy dynamics
213
+ const evolution = new EntropyDrivenEvolution(state, { lambda: 0.1 });
214
+ evolution.evolveUntilCollapse(1000);
215
+ ```
216
+
217
+ ### Resonance Network
218
+
219
+ ```javascript
220
+ const {
221
+ PrimeResonanceIdentity,
222
+ PhaseLockedRing,
223
+ EntangledNode,
224
+ ResonantFragment
225
+ } = require('tinyaleph');
226
+
227
+ // Create node with PRI
228
+ const node = new EntangledNode('observer');
229
+
230
+ // Establish entanglement
231
+ const strength = nodeA.entangleWith(nodeB);
232
+
233
+ // Store memory fragment
234
+ const fragment = ResonantFragment.fromText('important concept');
235
+ node.storeMemory(fragment.state, 16, 16);
236
+
237
+ // Create phase-locked ring
238
+ const ring = new PhaseLockedRing([2, 3, 5, 7, 11], 'phi');
@@ -0,0 +1,417 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * TinyAleph Examples Runner
4
+ * Interactive menu-driven CLI to browse and run examples
5
+ */
6
+
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const readline = require('readline');
10
+ const { spawn } = require('child_process');
11
+
12
+ // ANSI color codes
13
+ const colors = {
14
+ reset: '\x1b[0m',
15
+ bold: '\x1b[1m',
16
+ dim: '\x1b[2m',
17
+ red: '\x1b[31m',
18
+ green: '\x1b[32m',
19
+ yellow: '\x1b[33m',
20
+ blue: '\x1b[34m',
21
+ magenta: '\x1b[35m',
22
+ cyan: '\x1b[36m',
23
+ white: '\x1b[37m',
24
+ bgBlue: '\x1b[44m',
25
+ bgGreen: '\x1b[42m'
26
+ };
27
+
28
+ // Example categories with metadata
29
+ const categories = {
30
+ quickstart: {
31
+ name: '🚀 Quickstart',
32
+ description: 'Basic examples to get started',
33
+ path: '.',
34
+ examples: [
35
+ { file: '01-hello-world.js', name: 'Hello World', desc: 'Your first TinyAleph embedding' },
36
+ { file: '02-basic-hash.js', name: 'Basic Hash', desc: 'Cryptographic hashing basics' },
37
+ { file: '03-quantum-coin.js', name: 'Quantum Coin', desc: 'Quantum coin flip simulation' }
38
+ ]
39
+ },
40
+ ai: {
41
+ name: '🤖 AI & Machine Learning',
42
+ description: 'AI applications using semantic embeddings',
43
+ path: 'ai',
44
+ examples: [
45
+ { file: '01-embeddings.js', name: 'Embeddings', desc: 'Text embeddings for ML' },
46
+ { file: '02-semantic-memory.js', name: 'Semantic Memory', desc: 'Memory systems with recall' },
47
+ { file: '03-reasoning.js', name: 'Reasoning', desc: 'Symbolic reasoning chains' },
48
+ { file: '04-knowledge-graph.js', name: 'Knowledge Graph', desc: 'Graph construction & traversal' },
49
+ { file: '05-llm-integration.js', name: 'LLM Integration', desc: 'Integrate with language models' },
50
+ { file: '06-agent.js', name: 'AI Agent', desc: 'Agent implementation patterns' },
51
+ { file: '07-hybrid-ai.js', name: 'Hybrid AI', desc: 'Neural-symbolic hybrid systems' },
52
+ { file: '08-entropy-reasoning.js', name: 'Entropy Reasoning', desc: 'Entropy-guided inference' },
53
+ { file: '09-concept-learning.js', name: 'Concept Learning', desc: 'Learning new concepts' },
54
+ { file: '10-prompt-primes.js', name: 'Prompt Primes', desc: 'Prime-based prompting' },
55
+ { file: '11-rag.js', name: 'RAG', desc: 'Retrieval-augmented generation' },
56
+ { file: '12-neuro-symbolic.js', name: 'Neuro-Symbolic', desc: 'Neural-symbolic bridge' }
57
+ ]
58
+ },
59
+ semantic: {
60
+ name: '📝 Semantic Processing',
61
+ description: 'Text analysis and NLP applications',
62
+ path: 'semantic',
63
+ examples: [
64
+ { file: '01-vocabulary.js', name: 'Vocabulary', desc: 'Word-to-prime mapping' },
65
+ { file: '02-similarity.js', name: 'Similarity', desc: 'Semantic similarity metrics' },
66
+ { file: '03-word-algebra.js', name: 'Word Algebra', desc: 'Vector arithmetic on words' },
67
+ { file: '04-clustering.js', name: 'Clustering', desc: 'Text clustering algorithms' },
68
+ { file: '05-classification.js', name: 'Classification', desc: 'Text classification' },
69
+ { file: '06-dna-encoding.js', name: 'DNA Encoding', desc: 'Bio-inspired encoding' },
70
+ { file: '07-search.js', name: 'Search', desc: 'Semantic search engine' },
71
+ { file: '08-qa-system.js', name: 'QA System', desc: 'Question answering' }
72
+ ]
73
+ },
74
+ crypto: {
75
+ name: '🔐 Cryptography',
76
+ description: 'Cryptographic operations and security',
77
+ path: 'crypto',
78
+ examples: [
79
+ { file: '01-password-hash.js', name: 'Password Hash', desc: 'Secure password hashing' },
80
+ { file: '02-key-derivation.js', name: 'Key Derivation', desc: 'PBKDF key derivation' },
81
+ { file: '03-hmac.js', name: 'HMAC', desc: 'Message authentication' },
82
+ { file: '04-file-integrity.js', name: 'File Integrity', desc: 'File verification' },
83
+ { file: '05-content-hash.js', name: 'Content Hash', desc: 'Content-addressable storage' }
84
+ ]
85
+ },
86
+ scientific: {
87
+ name: '⚛️ Scientific Computing',
88
+ description: 'Quantum computing simulation',
89
+ path: 'scientific',
90
+ examples: [
91
+ { file: '01-single-qubit.js', name: 'Single Qubit', desc: 'Qubit gates and operations' },
92
+ { file: '02-two-qubit.js', name: 'Two Qubit', desc: 'Entanglement and CNOT' },
93
+ { file: '03-quantum-circuits.js', name: 'Circuits', desc: 'Quantum circuit builder' },
94
+ { file: '04-measurement.js', name: 'Measurement', desc: 'Quantum measurement' },
95
+ { file: '05-algorithms.js', name: 'Algorithms', desc: 'Quantum algorithms' },
96
+ { file: '06-random.js', name: 'Random', desc: 'Quantum random numbers' },
97
+ { file: '07-wavefunction.js', name: 'Wavefunction', desc: 'Wavefunction simulation' }
98
+ ]
99
+ },
100
+ bioinformatics: {
101
+ name: '🧬 Bioinformatics',
102
+ description: 'DNA computing and molecular biology',
103
+ path: 'bioinformatics',
104
+ examples: [
105
+ { file: '01-dna-encoding.js', name: 'DNA Encoding', desc: 'Prime-encoded sequences' },
106
+ { file: '02-central-dogma.js', name: 'Central Dogma', desc: 'DNA→RNA→Protein' },
107
+ { file: '03-protein-folding.js', name: 'Protein Folding', desc: 'Kuramoto dynamics' },
108
+ { file: '04-dna-computing.js', name: 'DNA Computing', desc: 'Logic gates with DNA' },
109
+ { file: '05-molecular-binding.js', name: 'Molecular Binding', desc: 'Binding affinity' }
110
+ ]
111
+ },
112
+ math: {
113
+ name: '➗ Mathematics',
114
+ description: 'Mathematical foundations',
115
+ path: 'math',
116
+ examples: [
117
+ { file: '01-quaternions.js', name: 'Quaternions', desc: '4D rotation algebra' },
118
+ { file: '02-octonions.js', name: 'Octonions', desc: '8D hypercomplex numbers' },
119
+ { file: '03-prime-factorization.js', name: 'Primes', desc: 'Prime factorization' },
120
+ { file: '04-vector-spaces.js', name: 'Vector Spaces', desc: 'Linear algebra' },
121
+ { file: '05-gaussian-primes.js', name: 'Gaussian Primes', desc: 'Complex plane primes' }
122
+ ]
123
+ },
124
+ physics: {
125
+ name: '🌊 Physics Simulation',
126
+ description: 'Physics and dynamics',
127
+ path: 'physics',
128
+ examples: [
129
+ { file: '01-oscillator.js', name: 'Oscillator', desc: 'Coupled oscillators' },
130
+ { file: '02-lyapunov.js', name: 'Lyapunov', desc: 'Chaos and stability' },
131
+ { file: '03-collapse.js', name: 'Collapse', desc: 'State collapse dynamics' },
132
+ { file: '04-kuramoto.js', name: 'Kuramoto', desc: 'Synchronization model' },
133
+ { file: '05-entropy.js', name: 'Entropy', desc: 'Information entropy' }
134
+ ]
135
+ }
136
+ };
137
+
138
+ class ExampleRunner {
139
+ constructor() {
140
+ this.rl = readline.createInterface({
141
+ input: process.stdin,
142
+ output: process.stdout
143
+ });
144
+ this.currentCategory = null;
145
+ this.examplesDir = __dirname;
146
+ }
147
+
148
+ clear() {
149
+ console.clear();
150
+ }
151
+
152
+ print(text) {
153
+ console.log(text);
154
+ }
155
+
156
+ printHeader() {
157
+ this.print('');
158
+ this.print(colors.bgBlue + colors.white + colors.bold + ' ' + colors.reset);
159
+ this.print(colors.bgBlue + colors.white + colors.bold + ' ✨ TinyAleph Examples Runner ✨ ' + colors.reset);
160
+ this.print(colors.bgBlue + colors.white + colors.bold + ' ' + colors.reset);
161
+ this.print('');
162
+ }
163
+
164
+ printCategoryMenu() {
165
+ this.print(colors.bold + 'Select a category:' + colors.reset);
166
+ this.print('');
167
+
168
+ const catKeys = Object.keys(categories);
169
+ for (let i = 0; i < catKeys.length; i++) {
170
+ const key = catKeys[i];
171
+ const cat = categories[key];
172
+ const num = String(i + 1).padStart(2, ' ');
173
+ this.print(` ${colors.cyan}[${num}]${colors.reset} ${cat.name}`);
174
+ this.print(` ${colors.dim}${cat.description}${colors.reset}`);
175
+ }
176
+
177
+ this.print('');
178
+ this.print(` ${colors.yellow}[a]${colors.reset} Run all examples`);
179
+ this.print(` ${colors.red}[q]${colors.reset} Quit`);
180
+ this.print('');
181
+ }
182
+
183
+ printExampleMenu(categoryKey) {
184
+ const cat = categories[categoryKey];
185
+ this.print(colors.bold + `${cat.name}` + colors.reset);
186
+ this.print(colors.dim + cat.description + colors.reset);
187
+ this.print('');
188
+
189
+ for (let i = 0; i < cat.examples.length; i++) {
190
+ const ex = cat.examples[i];
191
+ const num = String(i + 1).padStart(2, ' ');
192
+ this.print(` ${colors.cyan}[${num}]${colors.reset} ${ex.name}`);
193
+ this.print(` ${colors.dim}${ex.desc}${colors.reset}`);
194
+ }
195
+
196
+ this.print('');
197
+ this.print(` ${colors.green}[a]${colors.reset} Run all in category`);
198
+ this.print(` ${colors.yellow}[b]${colors.reset} Back to categories`);
199
+ this.print(` ${colors.red}[q]${colors.reset} Quit`);
200
+ this.print('');
201
+ }
202
+
203
+ prompt(question) {
204
+ return new Promise((resolve) => {
205
+ this.rl.question(colors.bold + question + colors.reset, (answer) => {
206
+ resolve(answer.trim().toLowerCase());
207
+ });
208
+ });
209
+ }
210
+
211
+ async runExample(categoryKey, exampleIndex) {
212
+ const cat = categories[categoryKey];
213
+ const example = cat.examples[exampleIndex];
214
+ const filePath = path.join(this.examplesDir, cat.path, example.file);
215
+
216
+ this.print('');
217
+ this.print(colors.bgGreen + colors.white + colors.bold + ` Running: ${example.name} ` + colors.reset);
218
+ this.print(colors.dim + filePath + colors.reset);
219
+ this.print('─'.repeat(60));
220
+ this.print('');
221
+
222
+ return new Promise((resolve) => {
223
+ const child = spawn('node', [filePath], {
224
+ stdio: 'inherit',
225
+ cwd: path.join(this.examplesDir, '..')
226
+ });
227
+
228
+ child.on('close', (code) => {
229
+ this.print('');
230
+ this.print('─'.repeat(60));
231
+ if (code === 0) {
232
+ this.print(colors.green + '✓ Example completed successfully' + colors.reset);
233
+ } else {
234
+ this.print(colors.red + `✗ Example exited with code ${code}` + colors.reset);
235
+ }
236
+ resolve();
237
+ });
238
+
239
+ child.on('error', (err) => {
240
+ this.print(colors.red + `Error: ${err.message}` + colors.reset);
241
+ resolve();
242
+ });
243
+ });
244
+ }
245
+
246
+ async runAllInCategory(categoryKey) {
247
+ const cat = categories[categoryKey];
248
+ this.print('');
249
+ this.print(colors.bold + `Running all examples in ${cat.name}...` + colors.reset);
250
+
251
+ for (let i = 0; i < cat.examples.length; i++) {
252
+ await this.runExample(categoryKey, i);
253
+ if (i < cat.examples.length - 1) {
254
+ const cont = await this.prompt('\nPress Enter for next, or q to stop: ');
255
+ if (cont === 'q') break;
256
+ }
257
+ }
258
+ }
259
+
260
+ async runAllExamples() {
261
+ this.print('');
262
+ this.print(colors.bold + 'Running ALL examples...' + colors.reset);
263
+
264
+ const catKeys = Object.keys(categories);
265
+ for (const catKey of catKeys) {
266
+ await this.runAllInCategory(catKey);
267
+ const cont = await this.prompt('\nPress Enter for next category, or q to stop: ');
268
+ if (cont === 'q') break;
269
+ }
270
+ }
271
+
272
+ async showCategoryMenu() {
273
+ while (true) {
274
+ this.clear();
275
+ this.printHeader();
276
+ this.printCategoryMenu();
277
+
278
+ const choice = await this.prompt('Enter choice: ');
279
+
280
+ if (choice === 'q') {
281
+ this.print('\nGoodbye! 👋\n');
282
+ this.rl.close();
283
+ return;
284
+ }
285
+
286
+ if (choice === 'a') {
287
+ await this.runAllExamples();
288
+ await this.prompt('\nPress Enter to continue...');
289
+ continue;
290
+ }
291
+
292
+ const num = parseInt(choice);
293
+ const catKeys = Object.keys(categories);
294
+
295
+ if (num >= 1 && num <= catKeys.length) {
296
+ await this.showExampleMenu(catKeys[num - 1]);
297
+ }
298
+ }
299
+ }
300
+
301
+ async showExampleMenu(categoryKey) {
302
+ const cat = categories[categoryKey];
303
+
304
+ while (true) {
305
+ this.clear();
306
+ this.printHeader();
307
+ this.printExampleMenu(categoryKey);
308
+
309
+ const choice = await this.prompt('Enter choice: ');
310
+
311
+ if (choice === 'q') {
312
+ this.print('\nGoodbye! 👋\n');
313
+ this.rl.close();
314
+ process.exit(0);
315
+ }
316
+
317
+ if (choice === 'b') {
318
+ return; // Back to category menu
319
+ }
320
+
321
+ if (choice === 'a') {
322
+ await this.runAllInCategory(categoryKey);
323
+ await this.prompt('\nPress Enter to continue...');
324
+ continue;
325
+ }
326
+
327
+ const num = parseInt(choice);
328
+ if (num >= 1 && num <= cat.examples.length) {
329
+ await this.runExample(categoryKey, num - 1);
330
+ await this.prompt('\nPress Enter to continue...');
331
+ }
332
+ }
333
+ }
334
+
335
+ async start() {
336
+ // Handle Ctrl+C gracefully
337
+ process.on('SIGINT', () => {
338
+ this.print('\n\nGoodbye! 👋\n');
339
+ this.rl.close();
340
+ process.exit(0);
341
+ });
342
+
343
+ await this.showCategoryMenu();
344
+ }
345
+ }
346
+
347
+ // Quick run mode for direct execution
348
+ async function quickRun(args) {
349
+ if (args.length < 1) {
350
+ console.log('Usage: node run-examples.js [category] [example]');
351
+ console.log(' node run-examples.js --list');
352
+ console.log(' node run-examples.js (interactive mode)');
353
+ return;
354
+ }
355
+
356
+ if (args[0] === '--list' || args[0] === '-l') {
357
+ console.log('\nAvailable examples:\n');
358
+ for (const [key, cat] of Object.entries(categories)) {
359
+ console.log(`${cat.name}:`);
360
+ for (const ex of cat.examples) {
361
+ console.log(` ${key}/${ex.file.replace('.js', '')}`);
362
+ }
363
+ console.log('');
364
+ }
365
+ return;
366
+ }
367
+
368
+ // Parse category/example format
369
+ const parts = args[0].split('/');
370
+ const categoryKey = parts[0];
371
+ const exampleName = parts[1];
372
+
373
+ if (!categories[categoryKey]) {
374
+ console.log(`Unknown category: ${categoryKey}`);
375
+ console.log('Available: ' + Object.keys(categories).join(', '));
376
+ return;
377
+ }
378
+
379
+ const cat = categories[categoryKey];
380
+
381
+ if (!exampleName) {
382
+ // Run all in category
383
+ const runner = new ExampleRunner();
384
+ await runner.runAllInCategory(categoryKey);
385
+ process.exit(0);
386
+ }
387
+
388
+ // Find example
389
+ const exIndex = cat.examples.findIndex(e =>
390
+ e.file.replace('.js', '') === exampleName ||
391
+ e.file === exampleName ||
392
+ e.name.toLowerCase() === exampleName.toLowerCase()
393
+ );
394
+
395
+ if (exIndex === -1) {
396
+ console.log(`Unknown example: ${exampleName}`);
397
+ console.log('Available in ' + categoryKey + ':');
398
+ for (const ex of cat.examples) {
399
+ console.log(' ' + ex.file.replace('.js', ''));
400
+ }
401
+ return;
402
+ }
403
+
404
+ const runner = new ExampleRunner();
405
+ await runner.runExample(categoryKey, exIndex);
406
+ process.exit(0);
407
+ }
408
+
409
+ // Main entry point
410
+ const args = process.argv.slice(2);
411
+
412
+ if (args.length > 0) {
413
+ quickRun(args);
414
+ } else {
415
+ const runner = new ExampleRunner();
416
+ runner.start();
417
+ }