@aleph-ai/tinyaleph 1.5.7 → 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 (109) 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/package.json +8 -3
  108. package/physics/alk-kuramoto.js +817 -0
  109. package/physics/index.js +23 -2
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Example: Prime Resonance Network (PRN)
3
+ *
4
+ * Demonstrates the network components from the PRNS specification:
5
+ * - Prime Resonance Identity (PRI) = (P_G, P_E, P_Q)
6
+ * - Phase-Locked Prime Rings
7
+ * - Holographic Memory Fields
8
+ * - Entangled Nodes
9
+ * - Resonant Fragments
10
+ */
11
+
12
+ const {
13
+ PrimeResonanceIdentity,
14
+ PhaseLockedRing,
15
+ HolographicField,
16
+ EntangledNode,
17
+ ResonantFragment,
18
+ PrimeState,
19
+ PHI,
20
+ DELTA_S
21
+ } = require('../../modular');
22
+
23
+ console.log('═══════════════════════════════════════════════════════════════');
24
+ console.log(' PRIME RESONANCE NETWORK DEMONSTRATION');
25
+ console.log('═══════════════════════════════════════════════════════════════\n');
26
+
27
+ // 1. Prime Resonance Identity (PRI)
28
+ console.log('1. PRIME RESONANCE IDENTITY (PRI)');
29
+ console.log('─────────────────────────────────────────────────────────────────');
30
+ console.log('PRI = (P_G, P_E, P_Q) - Gaussian, Eisenstein, Quaternionic primes');
31
+
32
+ const priAlpha = PrimeResonanceIdentity.fromSeed(42);
33
+ const priBeta = PrimeResonanceIdentity.random();
34
+
35
+ console.log('\nNode Alpha PRI:');
36
+ console.log(' Gaussian:', priAlpha.gaussian.toString());
37
+ console.log(' Eisenstein:', priAlpha.eisenstein.toString());
38
+ console.log(' Quaternion:', priAlpha.quaternion.toString());
39
+ console.log(' Signature:', priAlpha.signature);
40
+
41
+ console.log('\nNode Beta PRI:');
42
+ console.log(' Signature:', priBeta.signature);
43
+
44
+ const strength = priAlpha.entanglementStrength(priBeta);
45
+ console.log('\nEntanglement strength α↔β:', strength.toFixed(4));
46
+
47
+ // 2. Phase-Locked Prime Rings
48
+ console.log('\n2. PHASE-LOCKED PRIME RINGS');
49
+ console.log('─────────────────────────────────────────────────────────────────');
50
+ console.log('Using irrational phase locks: 2π/φ, 2π/√2');
51
+ console.log('φ (golden ratio):', PHI.toFixed(6));
52
+ console.log('δS (√2):', DELTA_S.toFixed(6));
53
+
54
+ const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29];
55
+ const ring = new PhaseLockedRing(primes, 'phi');
56
+
57
+ console.log('\nInitial phases (scaled by 1/π):');
58
+ for (let i = 0; i < 5; i++) {
59
+ console.log(` Phase[${primes[i]}]: ${(ring.phases[i] / Math.PI).toFixed(4)}π`);
60
+ }
61
+
62
+ console.log('\nInitial order parameter:', ring.orderParameter().toFixed(4));
63
+
64
+ // Evolve the ring
65
+ for (let i = 0; i < 200; i++) {
66
+ ring.tick(0.05);
67
+ }
68
+
69
+ console.log('After 200 ticks:');
70
+ console.log(' Order parameter:', ring.orderParameter().toFixed(4));
71
+ console.log(' Mean phase:', (ring.meanPhase() / Math.PI).toFixed(4) + 'π');
72
+ console.log(' Synchronization:', ring.synchronization().toFixed(4));
73
+
74
+ // 3. Holographic Memory Field
75
+ console.log('\n3. HOLOGRAPHIC MEMORY FIELD');
76
+ console.log('─────────────────────────────────────────────────────────────────');
77
+ console.log('I(x,y) = Σ A_p e^(-S(x,y)) e^(ipθ)');
78
+
79
+ const field = new HolographicField(64, 64);
80
+
81
+ // Encode multiple memory fragments at different locations
82
+ const memories = [
83
+ { state: PrimeState.basis(7), x: 20, y: 20 },
84
+ { state: PrimeState.basis(11), x: 44, y: 20 },
85
+ { state: PrimeState.basis(13), x: 32, y: 44 }
86
+ ];
87
+
88
+ for (const mem of memories) {
89
+ field.encodeState(mem.state, mem.x, mem.y);
90
+ }
91
+
92
+ console.log('\nEncoded 3 memory fragments:');
93
+ console.log(' |7⟩ at (20, 20)');
94
+ console.log(' |11⟩ at (44, 20)');
95
+ console.log(' |13⟩ at (32, 44)');
96
+
97
+ console.log('\nField statistics:');
98
+ console.log(' Max intensity:', field.maxIntensity().toFixed(4));
99
+
100
+ const peaks = field.findPeaks(0.5);
101
+ console.log(' Peaks found:', peaks.length);
102
+
103
+ for (const peak of peaks.slice(0, 3)) {
104
+ console.log(` Peak at (${peak.x}, ${peak.y}): intensity=${peak.intensity.toFixed(4)}`);
105
+ }
106
+
107
+ // Decode from a location
108
+ const decoded = field.decodeAt(20, 20, 5);
109
+ console.log('\nDecoded from (20, 20):');
110
+ for (const { p, amp } of decoded.dominant(3)) {
111
+ console.log(` |${p}⟩: ${amp.toFixed(4)}`);
112
+ }
113
+
114
+ // 4. Entangled Nodes
115
+ console.log('\n4. ENTANGLED NODES');
116
+ console.log('─────────────────────────────────────────────────────────────────');
117
+
118
+ const nodeA = new EntangledNode('observer-1');
119
+ const nodeB = new EntangledNode('observer-2');
120
+ const nodeC = new EntangledNode('observer-3');
121
+
122
+ console.log('Created nodes: observer-1, observer-2, observer-3');
123
+
124
+ // Establish entanglements
125
+ const strengthAB = nodeA.entangleWith(nodeB);
126
+ const strengthBC = nodeB.entangleWith(nodeC);
127
+ const strengthAC = nodeA.entangleWith(nodeC);
128
+
129
+ console.log('\nEntanglement network:');
130
+ console.log(' observer-1 ↔ observer-2:', strengthAB.toFixed(4));
131
+ console.log(' observer-2 ↔ observer-3:', strengthBC.toFixed(4));
132
+ console.log(' observer-1 ↔ observer-3:', strengthAC.toFixed(4));
133
+
134
+ // Store memory in node A
135
+ const thoughtState = PrimeState.uniform().scale({ re: 0.5, im: 0.5 });
136
+ nodeA.storeMemory(thoughtState, 16, 16);
137
+
138
+ console.log('\nStored memory in observer-1');
139
+ console.log(' Holographic field intensity:', nodeA.holographicMemory.maxIntensity().toFixed(4));
140
+
141
+ // Evolve nodes
142
+ for (let i = 0; i < 50; i++) {
143
+ nodeA.tick(0.1);
144
+ nodeB.tick(0.1);
145
+ nodeC.tick(0.1);
146
+ }
147
+
148
+ console.log('\nAfter 50 ticks:');
149
+ console.log(' observer-1 coherence:', nodeA.coherence.toFixed(4));
150
+ console.log(' observer-2 coherence:', nodeB.coherence.toFixed(4));
151
+ console.log(' observer-3 coherence:', nodeC.coherence.toFixed(4));
152
+
153
+ console.log('\nNode stability:');
154
+ console.log(' observer-1 stable:', nodeA.isStable() ? 'YES' : 'NO');
155
+ console.log(' observer-2 stable:', nodeB.isStable() ? 'YES' : 'NO');
156
+
157
+ // 5. Resonant Fragments
158
+ console.log('\n5. RESONANT FRAGMENTS');
159
+ console.log('─────────────────────────────────────────────────────────────────');
160
+
161
+ const fragmentA = ResonantFragment.fromText('truth and wisdom');
162
+ const fragmentB = ResonantFragment.fromText('love and beauty');
163
+
164
+ console.log('Fragment A: "truth and wisdom"');
165
+ console.log(' Entropy:', fragmentA.entropy.toFixed(4));
166
+ console.log(' Dominant primes:', fragmentA.dominant(3).map(d => d.p).join(', '));
167
+
168
+ console.log('\nFragment B: "love and beauty"');
169
+ console.log(' Entropy:', fragmentB.entropy.toFixed(4));
170
+ console.log(' Dominant primes:', fragmentB.dominant(3).map(d => d.p).join(', '));
171
+
172
+ // Tensor product
173
+ const combined = fragmentA.tensorWith(fragmentB);
174
+ console.log('\nTensor product A ⊗ B:');
175
+ console.log(' Combined dominant primes:', combined.dominant(3).map(d => d.p).join(', '));
176
+
177
+ // Coherence
178
+ const coherence = fragmentA.coherenceWith(fragmentB);
179
+ console.log('\nCoherence(A, B):', coherence.toFixed(4));
180
+
181
+ // Phase rotation
182
+ const rotated = fragmentA.rotatePhase(Math.PI / 4);
183
+ console.log('\nAfter π/4 phase rotation:');
184
+ console.log(' Coherence with original:', fragmentA.coherenceWith(rotated).toFixed(4));
185
+
186
+ // 6. Memory Teleportation Scenario
187
+ console.log('\n6. MEMORY TELEPORTATION SCENARIO');
188
+ console.log('─────────────────────────────────────────────────────────────────');
189
+
190
+ const sender = new EntangledNode('sender');
191
+ const receiver = new EntangledNode('receiver');
192
+
193
+ // Establish entanglement
194
+ const entStrength = sender.entangleWith(receiver);
195
+ console.log('Entanglement established:', entStrength.toFixed(4));
196
+
197
+ // Create memory to teleport
198
+ const memoryFragment = ResonantFragment.fromText('the secret of existence');
199
+ console.log('Memory to teleport: "the secret of existence"');
200
+ console.log(' Dominant primes:', memoryFragment.dominant(3).map(d => d.p).join(', '));
201
+
202
+ // Store in sender's holographic field
203
+ sender.storeMemory(memoryFragment.state, 16, 16);
204
+
205
+ // Simulate teleportation (in a real implementation, this would involve
206
+ // the Memory Teleportation Protocol from PRNS)
207
+ console.log('\nSimulating teleportation...');
208
+
209
+ // Transfer the memory pattern to receiver (conceptually)
210
+ receiver.holographicMemory.encodeState(memoryFragment.state, 16, 16);
211
+
212
+ // Verify transfer
213
+ const retrieved = receiver.holographicMemory.decodeAt(16, 16, 5);
214
+ console.log('\nRetrieved from receiver:');
215
+ for (const { p, amp } of retrieved.dominant(3)) {
216
+ console.log(` |${p}⟩: ${amp.toFixed(4)}`);
217
+ }
218
+
219
+ console.log('\n═══════════════════════════════════════════════════════════════');
220
+ console.log(' DEMONSTRATION COMPLETE');
221
+ console.log('═══════════════════════════════════════════════════════════════\n');
@@ -0,0 +1,349 @@
1
+ /**
2
+ * Example: ResoFormer (Resonant Field Transformer)
3
+ *
4
+ * Demonstrates all ResoFormer ML primitives:
5
+ * - Sparse Prime State with Quaternions (H_Q = H_P ⊗ ℍ)
6
+ * - Resonant Attention Score (Jaccard + Quaternion + Phase)
7
+ * - Hamilton Product Composition (Non-commutative)
8
+ * - Coherence-Gated Halting (ACT-style)
9
+ * - Entropy Collapse Head (64-codebook)
10
+ * - PR-Graph Memory (put/get)
11
+ *
12
+ * Based on the ResoFormer specification combining:
13
+ * - PRSC (Prime Resonance Symbolic Computing)
14
+ * - Quantum Semantics
15
+ * - Quaternionic Memory Field (QMF)
16
+ * - Prime Resonant Graph Database
17
+ */
18
+
19
+ const {
20
+ // Quaternion algebra
21
+ Quaternion,
22
+
23
+ // Sparse prime state
24
+ SparsePrimeState,
25
+
26
+ // Attention
27
+ resonanceScore,
28
+ resonantAttention,
29
+
30
+ // Composition
31
+ hamiltonCompose,
32
+ measureNonCommutativity,
33
+
34
+ // Halting
35
+ computeCoherence,
36
+ haltingDecision,
37
+ coherenceGatedCompute,
38
+
39
+ // Collapse
40
+ EntropyCollapseHead,
41
+
42
+ // Memory
43
+ PRGraphMemory,
44
+
45
+ // Operators
46
+ applyResonanceOperator
47
+ } = require('../../modular');
48
+
49
+ console.log('═══════════════════════════════════════════════════════════════');
50
+ console.log(' RESOFORMER DEMONSTRATION');
51
+ console.log(' (Resonant Field Transformer Primitives)');
52
+ console.log('═══════════════════════════════════════════════════════════════\n');
53
+
54
+ // ============================================================================
55
+ // 1. QUATERNION ALGEBRA
56
+ // ============================================================================
57
+ console.log('1. QUATERNION ALGEBRA (ℍ)');
58
+ console.log('─────────────────────────────────────────────────────────────────');
59
+ console.log('Hamilton product: (a₁ + b₁i + c₁j + d₁k) × (a₂ + b₂i + c₂j + d₂k)');
60
+ console.log('Key property: NON-COMMUTATIVE (q₁×q₂ ≠ q₂×q₁)');
61
+
62
+ const q1 = new Quaternion(1, 2, 3, 4);
63
+ const q2 = new Quaternion(5, 6, 7, 8);
64
+
65
+ console.log('\nq₁ =', q1.toString());
66
+ console.log('q₂ =', q2.toString());
67
+ console.log('\nq₁ × q₂ =', q1.mul(q2).toString());
68
+ console.log('q₂ × q₁ =', q2.mul(q1).toString());
69
+
70
+ const commutator = q1.commutator(q2);
71
+ console.log('\nCommutator [q₁, q₂] =', commutator.toString());
72
+ console.log('‖[q₁, q₂]‖ =', q1.commutatorNorm(q2).toFixed(4));
73
+ console.log('→ Non-zero commutator proves order sensitivity!');
74
+
75
+ // ============================================================================
76
+ // 2. SPARSE PRIME STATE (H_Q = H_P ⊗ ℍ)
77
+ // ============================================================================
78
+ console.log('\n\n2. SPARSE PRIME STATE (H_Q = H_P ⊗ ℍ)');
79
+ console.log('─────────────────────────────────────────────────────────────────');
80
+ console.log('|Ψ_t⟩ = Σ_{p ∈ P_t} α_{t,p} · q_{t,p} · |p⟩');
81
+ console.log(' α_{t,p} ∈ ℂ (complex amplitude with phase)');
82
+ console.log(' q_{t,p} ∈ ℍ (quaternion orientation)');
83
+
84
+ const sentence1 = SparsePrimeState.fromHash('The cat sat on the mat');
85
+ const sentence2 = SparsePrimeState.fromHash('The dog ran in the park');
86
+ const sentence3 = SparsePrimeState.fromHash('The cat sat on the mat'); // Same as 1
87
+
88
+ console.log('\nSentence 1: "The cat sat on the mat"');
89
+ console.log(' Active primes (k=32):', sentence1.getActivePrimes().slice(0, 5).join(', '), '...');
90
+ console.log(' Entropy:', sentence1.entropy().toFixed(4));
91
+
92
+ console.log('\nSentence 2: "The dog ran in the park"');
93
+ console.log(' Active primes:', sentence2.getActivePrimes().slice(0, 5).join(', '), '...');
94
+ console.log(' Entropy:', sentence2.entropy().toFixed(4));
95
+
96
+ // ============================================================================
97
+ // 3. RESONANT ATTENTION SCORE
98
+ // ============================================================================
99
+ console.log('\n\n3. RESONANT ATTENTION SCORE');
100
+ console.log('─────────────────────────────────────────────────────────────────');
101
+ console.log('Res(i,j) = α·Jaccard(P_i, P_j) + β·QuaternionAlign + γ·PhaseCoherence');
102
+
103
+ const score12 = resonanceScore(sentence1, sentence2);
104
+ const score13 = resonanceScore(sentence1, sentence3);
105
+ const score23 = resonanceScore(sentence2, sentence3);
106
+
107
+ console.log('\nResonance scores (attention kernel):');
108
+ console.log(' "cat on mat" ↔ "dog in park":', score12.toFixed(4));
109
+ console.log(' "cat on mat" ↔ "cat on mat":', score13.toFixed(4), '(identical)');
110
+ console.log(' "dog in park" ↔ "cat on mat":', score23.toFixed(4));
111
+
112
+ // ============================================================================
113
+ // 4. RESONANT ATTENTION MECHANISM
114
+ // ============================================================================
115
+ console.log('\n\n4. RESONANT ATTENTION MECHANISM');
116
+ console.log('─────────────────────────────────────────────────────────────────');
117
+ console.log('Replaces dot-product attention with resonance-based scoring');
118
+
119
+ const query = SparsePrimeState.fromHash('What animal was sitting?');
120
+ const keys = [
121
+ SparsePrimeState.fromHash('The cat sat quietly'),
122
+ SparsePrimeState.fromHash('The dog was running'),
123
+ SparsePrimeState.fromHash('The bird flew away')
124
+ ];
125
+ const values = keys; // Same as keys for this demo
126
+
127
+ const attention = resonantAttention(query, keys, values, 1.0);
128
+
129
+ console.log('\nQuery: "What animal was sitting?"');
130
+ console.log('Keys:');
131
+ console.log(' [0] "The cat sat quietly"');
132
+ console.log(' [1] "The dog was running"');
133
+ console.log(' [2] "The bird flew away"');
134
+ console.log('\nAttention weights (softmax of resonance scores):');
135
+ for (let i = 0; i < attention.weights.length; i++) {
136
+ const bar = '█'.repeat(Math.round(attention.weights[i] * 20));
137
+ console.log(` [${i}] ${attention.weights[i].toFixed(4)} ${bar}`);
138
+ }
139
+
140
+ // ============================================================================
141
+ // 5. HAMILTON PRODUCT COMPOSITION (ORDER-SENSITIVE)
142
+ // ============================================================================
143
+ console.log('\n\n5. HAMILTON PRODUCT COMPOSITION');
144
+ console.log('─────────────────────────────────────────────────────────────────');
145
+ console.log('Compose(A, B) ≠ Compose(B, A) via Hamilton product');
146
+
147
+ const eventA = SparsePrimeState.fromHash('Alice called Bob');
148
+ const eventB = SparsePrimeState.fromHash('Bob answered');
149
+
150
+ const AB = hamiltonCompose(eventA, eventB);
151
+ const BA = hamiltonCompose(eventB, eventA);
152
+
153
+ console.log('\nEvent A: "Alice called Bob"');
154
+ console.log('Event B: "Bob answered"');
155
+ console.log('\nCompose(A, B) active primes:', AB.getActivePrimes().slice(0, 5).join(', '));
156
+ console.log('Compose(B, A) active primes:', BA.getActivePrimes().slice(0, 5).join(', '));
157
+
158
+ const nonComm = measureNonCommutativity(eventA, eventB);
159
+ console.log('\nNon-commutativity measure:', nonComm.toFixed(4));
160
+ console.log('→ Captures "A then B" ≠ "B then A" in representation');
161
+
162
+ // ============================================================================
163
+ // 6. RESONANCE OPERATOR (PHASE ROTATION)
164
+ // ============================================================================
165
+ console.log('\n\n6. RESONANCE OPERATOR (PHASE ROTATION)');
166
+ console.log('─────────────────────────────────────────────────────────────────');
167
+ console.log('R̂(n)|p⟩ = e^(2πi log_p(n))|p⟩');
168
+
169
+ const original = SparsePrimeState.fromHash('test state');
170
+ const rotated5 = applyResonanceOperator(original, 5);
171
+ const rotated7 = applyResonanceOperator(original, 7);
172
+
173
+ console.log('\nApplying R̂(n) with different n:');
174
+ console.log(' Original entropy:', original.entropy().toFixed(4));
175
+ console.log(' After R̂(5):', rotated5.entropy().toFixed(4));
176
+ console.log(' After R̂(7):', rotated7.entropy().toFixed(4));
177
+
178
+ const scoreOrigRot5 = resonanceScore(original, rotated5);
179
+ const scoreRot5Rot7 = resonanceScore(rotated5, rotated7);
180
+ console.log('\nResonance after rotation:');
181
+ console.log(' Original ↔ R̂(5):', scoreOrigRot5.toFixed(4));
182
+ console.log(' R̂(5) ↔ R̂(7):', scoreRot5Rot7.toFixed(4));
183
+
184
+ // ============================================================================
185
+ // 7. COHERENCE-GATED HALTING (ACT-STYLE)
186
+ // ============================================================================
187
+ console.log('\n\n7. COHERENCE-GATED HALTING (ACT-STYLE)');
188
+ console.log('─────────────────────────────────────────────────────────────────');
189
+ console.log('Time/compute happens when the field coheres: C(t) ≥ C_threshold');
190
+
191
+ const state = SparsePrimeState.fromHash('initial thought');
192
+ const coherence = computeCoherence(state);
193
+ console.log('\nInitial coherence:', coherence.toFixed(4));
194
+
195
+ const halt = haltingDecision(state, 0.6, 0.1);
196
+ console.log('Halting decision (threshold=0.6):');
197
+ console.log(' Coherence:', halt.coherence.toFixed(4));
198
+ console.log(' Halt probability:', halt.probability.toFixed(4));
199
+ console.log(' Should halt:', halt.halt ? 'YES' : 'NO');
200
+
201
+ // Simulate coherence-gated computation
202
+ const stepFn = (s, step) => applyResonanceOperator(s, step + 2);
203
+ const result = coherenceGatedCompute(state, stepFn, 50, 0.7);
204
+
205
+ console.log('\nCoherence-gated evolution:');
206
+ console.log(' Steps taken:', result.steps);
207
+ console.log(' Halted naturally:', result.halted ? 'YES' : 'NO');
208
+ console.log(' Final coherence:', result.haltHistory[result.haltHistory.length - 1].coherence.toFixed(4));
209
+
210
+ // ============================================================================
211
+ // 8. ENTROPY COLLAPSE HEAD (64-CODEBOOK)
212
+ // ============================================================================
213
+ console.log('\n\n8. ENTROPY COLLAPSE HEAD (64-CODEBOOK)');
214
+ console.log('─────────────────────────────────────────────────────────────────');
215
+ console.log('64 attractor states (I-Ching style) with target entropy ~5.99 bits');
216
+
217
+ const collapseHead = new EntropyCollapseHead(5.99);
218
+
219
+ const testState = SparsePrimeState.fromHash('thinking about truth');
220
+
221
+ // Soft assignment (training mode)
222
+ const soft = collapseHead.softAssign(testState);
223
+ console.log('\nSoft assignment (training):');
224
+ console.log(' Entropy over attractors:', soft.entropy.toFixed(4));
225
+ console.log(' Top 3 probabilities:', soft.probs.slice(0, 3).map(p => p.toFixed(4)).join(', '));
226
+
227
+ // Hard assignment (inference mode)
228
+ const hard = collapseHead.hardAssign(testState);
229
+ console.log('\nHard assignment (inference):');
230
+ console.log(' Selected attractor:', hard.index);
231
+ console.log(' Confidence:', hard.confidence.toFixed(4));
232
+
233
+ // Entropy regularization
234
+ const entropyLoss = collapseHead.entropyLoss(testState);
235
+ console.log('\nEntropy regularization:');
236
+ console.log(' Target entropy:', collapseHead.targetEntropy.toFixed(2));
237
+ console.log(' Current loss:', entropyLoss.toFixed(4));
238
+
239
+ // ============================================================================
240
+ // 9. PR-GRAPH MEMORY (PERSISTENT CONTENT-ADDRESSABLE)
241
+ // ============================================================================
242
+ console.log('\n\n9. PR-GRAPH MEMORY (PERSISTENT CONTENT-ADDRESSABLE)');
243
+ console.log('─────────────────────────────────────────────────────────────────');
244
+ console.log('Prime-entropy hash → phase-code → resonance retrieval → CRT decode');
245
+
246
+ const memory = new PRGraphMemory(4096, 0.8);
247
+
248
+ // Store facts
249
+ const facts = [
250
+ { key: 'fact1', text: 'Paris is the capital of France', type: 'geography' },
251
+ { key: 'fact2', text: 'Python is a programming language', type: 'tech' },
252
+ { key: 'fact3', text: 'The Eiffel Tower is in Paris', type: 'geography' },
253
+ { key: 'fact4', text: 'JavaScript runs in browsers', type: 'tech' }
254
+ ];
255
+
256
+ console.log('\nStoring facts:');
257
+ for (const fact of facts) {
258
+ const state = SparsePrimeState.fromHash(fact.text);
259
+ memory.put(fact.key, state, { text: fact.text, type: fact.type });
260
+ console.log(` [${fact.key}] "${fact.text}"`);
261
+ }
262
+
263
+ // Query for related facts
264
+ const query1 = SparsePrimeState.fromHash('capital city of France');
265
+ const results1 = memory.get(query1, 2);
266
+
267
+ console.log('\nQuery: "capital city of France"');
268
+ console.log('Top 2 results:');
269
+ for (const r of results1) {
270
+ console.log(` - [${r.key}] score=${r.score.toFixed(4)} "${r.metadata.text}"`);
271
+ }
272
+
273
+ const query2 = SparsePrimeState.fromHash('coding languages');
274
+ const results2 = memory.get(query2, 2);
275
+
276
+ console.log('\nQuery: "coding languages"');
277
+ console.log('Top 2 results:');
278
+ for (const r of results2) {
279
+ console.log(` - [${r.key}] score=${r.score.toFixed(4)} "${r.metadata.text}"`);
280
+ }
281
+
282
+ // Memory stats
283
+ const stats = memory.stats();
284
+ console.log('\nMemory statistics:');
285
+ console.log(' Total entries:', stats.total);
286
+ console.log(' Locked (stable):', stats.locked);
287
+ console.log(' Average entropy:', stats.avgEntropy.toFixed(4));
288
+
289
+ // ============================================================================
290
+ // 10. FULL RESOFORMER PIPELINE
291
+ // ============================================================================
292
+ console.log('\n\n10. FULL RESOFORMER PIPELINE');
293
+ console.log('─────────────────────────────────────────────────────────────────');
294
+ console.log('Input → Sparse Prime State → Resonant Attention → Hamilton Mix →');
295
+ console.log(' → Coherence-Gated Steps → Collapse → Memory Retrieval');
296
+
297
+ // Simulate a simple ResoFormer forward pass
298
+ const input = 'What is the meaning of existence?';
299
+ console.log('\nInput:', `"${input}"`);
300
+
301
+ // 1. Encode to sparse prime state
302
+ const inputState = SparsePrimeState.fromHash(input);
303
+ console.log('\n[1] Encode to H_Q:');
304
+ console.log(' Active primes:', inputState.getActivePrimes().length);
305
+ console.log(' Entropy:', inputState.entropy().toFixed(4));
306
+
307
+ // 2. Attend to context (simulated)
308
+ const context = [
309
+ SparsePrimeState.fromHash('Life has no inherent meaning'),
310
+ SparsePrimeState.fromHash('Meaning is created through action'),
311
+ SparsePrimeState.fromHash('The universe is vast and mysterious')
312
+ ];
313
+ const attnResult = resonantAttention(inputState, context, context);
314
+ console.log('\n[2] Resonant Attention:');
315
+ console.log(' Weights:', attnResult.weights.map(w => w.toFixed(3)).join(', '));
316
+
317
+ // 3. Hamilton composition
318
+ const composed = hamiltonCompose(inputState, attnResult.result);
319
+ console.log('\n[3] Hamilton Composition:');
320
+ console.log(' Composed entropy:', composed.entropy().toFixed(4));
321
+
322
+ // 4. Coherence-gated steps
323
+ const evolved = coherenceGatedCompute(composed, stepFn, 20, 0.6);
324
+ console.log('\n[4] Coherence-Gated Evolution:');
325
+ console.log(' Steps:', evolved.steps);
326
+ console.log(' Final coherence:', evolved.haltHistory[evolved.haltHistory.length - 1].coherence.toFixed(4));
327
+
328
+ // 5. Collapse to attractor
329
+ const collapsed = collapseHead.hardAssign(evolved.finalState);
330
+ console.log('\n[5] Entropy Collapse:');
331
+ console.log(' Attractor index:', collapsed.index);
332
+ console.log(' Confidence:', collapsed.confidence.toFixed(4));
333
+
334
+ // 6. Memory lookup
335
+ memory.put('input', inputState, { text: input });
336
+ const memResults = memory.get(evolved.finalState, 1);
337
+ console.log('\n[6] Memory Retrieval:');
338
+ if (memResults.length > 0) {
339
+ console.log(' Best match:', memResults[0].key, 'score:', memResults[0].score.toFixed(4));
340
+ }
341
+
342
+ console.log('\n═══════════════════════════════════════════════════════════════');
343
+ console.log(' DEMONSTRATION COMPLETE');
344
+ console.log('═══════════════════════════════════════════════════════════════');
345
+ console.log('\nResoFormer = (Prime Sparse State) + (Quaternionic Attention) +');
346
+ console.log(' (Resonant Phase Rotations) + (Coherence Halting) +');
347
+ console.log(' (Entropy Collapse Head) + (PR-Graph Memory)');
348
+ console.log('\nState space: H_Q = H_P ⊗ ℍ');
349
+ console.log('════════════════════════════════════════════════════════════════\n');