@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,196 @@
1
+ /**
2
+ * Demo: Two-Layer Semantic System
3
+ *
4
+ * Shows how the same MEANING (primes) can be expressed
5
+ * with different WORDS based on register/style biases
6
+ */
7
+
8
+ const { TwoLayerEngine } = require('../backends/semantic/two-layer');
9
+
10
+ console.log('╔═══════════════════════════════════════════════════════════════╗');
11
+ console.log('║ Two-Layer Semantic System Demo ║');
12
+ console.log('║ Layer 1: Prime-Based Meaning (Invariant) ║');
13
+ console.log('║ Layer 2: Word Selection with Bias (Variable) ║');
14
+ console.log('╚═══════════════════════════════════════════════════════════════╝\n');
15
+
16
+ const engine = new TwoLayerEngine({
17
+ core: { dimension: 16 }
18
+ });
19
+
20
+ // ============================================
21
+ // 1. Same Meaning, Different Registers
22
+ // ============================================
23
+ console.log('┌───────────────────────────────────────────────────────────────┐');
24
+ console.log('│ SAME MEANING, DIFFERENT REGISTERS │');
25
+ console.log('└───────────────────────────────────────────────────────────────┘\n');
26
+
27
+ const input1 = 'truth wisdom knowledge';
28
+ console.log(`Input: "${input1}"\n`);
29
+
30
+ // Process in formal register
31
+ engine.useRegister('formal');
32
+ const formal = engine.process(input1);
33
+ console.log(` Formal: "${formal.surface.words.join(' ')}"`);
34
+
35
+ // Transform to casual
36
+ const toCasual = engine.transform(input1, 'casual');
37
+ console.log(` Casual: "${toCasual.transformed}"`);
38
+
39
+ // Transform to technical
40
+ const toTechnical = engine.transform(input1, 'technical');
41
+ console.log(` Technical: "${toTechnical.transformed}"`);
42
+
43
+ // Transform to poetic
44
+ const toPoetic = engine.transform(input1, 'poetic');
45
+ console.log(` Poetic: "${toPoetic.transformed}"`);
46
+
47
+ console.log(`\n Same meaning primes: [${formal.meaning.primes.slice(0,8).join(', ')}...]`);
48
+ console.log(` Meaning entropy: ${formal.meaning.entropy.toFixed(3)}`);
49
+
50
+ // ============================================
51
+ // 2. Cross-Register Translation
52
+ // ============================================
53
+ console.log('\n┌───────────────────────────────────────────────────────────────┐');
54
+ console.log('│ CROSS-REGISTER TRANSLATION │');
55
+ console.log('└───────────────────────────────────────────────────────────────┘\n');
56
+
57
+ // Casual to Formal
58
+ const casualInput = 'love';
59
+ console.log(`Translating casual → formal:`);
60
+ console.log(` "${casualInput}" → `, engine.translate(casualInput, 'casual', 'formal').translated);
61
+
62
+ // Formal to Casual
63
+ const formalInput = 'contemplate';
64
+ console.log(`\nTranslating formal → casual:`);
65
+ console.log(` "${formalInput}" → `, engine.translate(formalInput, 'formal', 'casual').translated);
66
+
67
+ // Technical to Poetic
68
+ const techInput = 'analyze';
69
+ console.log(`\nTranslating technical → poetic:`);
70
+ console.log(` "${techInput}" → `, engine.translate(techInput, 'technical', 'poetic').translated);
71
+
72
+ // ============================================
73
+ // 3. Context-Sensitive Selection
74
+ // ============================================
75
+ console.log('\n┌───────────────────────────────────────────────────────────────┐');
76
+ console.log('│ CONTEXT-SENSITIVE WORD SELECTION │');
77
+ console.log('└───────────────────────────────────────────────────────────────┘\n');
78
+
79
+ // Set context and see how it affects word choice
80
+ engine.useRegister('formal');
81
+
82
+ console.log('Same primes [7, 11, 13] ("truth") in different contexts:\n');
83
+
84
+ engine.surfaces.pushContext('academic');
85
+ const academic = engine.surfaces.decode([7, 11, 13], { deterministic: true });
86
+ engine.surfaces.popContext();
87
+ console.log(` Context: academic → "${academic}"`);
88
+
89
+ engine.surfaces.pushContext('legal');
90
+ const legal = engine.surfaces.decode([7, 11, 13], { deterministic: true });
91
+ engine.surfaces.popContext();
92
+ console.log(` Context: legal → "${legal}"`);
93
+
94
+ engine.surfaces.pushContext('archaic');
95
+ const archaic = engine.surfaces.decode([7, 11, 13], { deterministic: true });
96
+ engine.surfaces.popContext();
97
+ console.log(` Context: archaic → "${archaic}"`);
98
+
99
+ // ============================================
100
+ // 4. The Two-Layer Architecture
101
+ // ============================================
102
+ console.log('\n┌───────────────────────────────────────────────────────────────┐');
103
+ console.log('│ THE TWO-LAYER ARCHITECTURE │');
104
+ console.log('└───────────────────────────────────────────────────────────────┘\n');
105
+
106
+ console.log(`
107
+ INPUT TEXT
108
+
109
+
110
+ ┌─────────────────────┐
111
+ │ LAYER 1: CORE │
112
+ │ ───────────── │
113
+ │ Tokenize → Primes │
114
+ │ Non-commutative │
115
+ │ multiplication │ ← INVARIANT MEANING
116
+ │ ↓ │
117
+ │ Hypercomplex │
118
+ │ State Vector │
119
+ └──────────┬──────────┘
120
+
121
+ │ [primes]
122
+
123
+ ┌─────────────────────┐
124
+ │ LAYER 2: SURFACE │
125
+ │ ─────────────── │
126
+ │ Prime → Word │
127
+ │ candidates │
128
+ │ ↓ │
129
+ │ Apply biases: │ ← VARIABLE EXPRESSION
130
+ │ • Register │
131
+ │ • Context │
132
+ │ • Recency │
133
+ │ • User preference │
134
+ │ ↓ │
135
+ │ Select best word │
136
+ └──────────┬──────────┘
137
+
138
+
139
+ OUTPUT TEXT
140
+ `);
141
+
142
+ // ============================================
143
+ // 5. Probabilistic vs Deterministic Selection
144
+ // ============================================
145
+ console.log('\n┌───────────────────────────────────────────────────────────────┐');
146
+ console.log('│ PROBABILISTIC WORD SELECTION │');
147
+ console.log('└───────────────────────────────────────────────────────────────┘\n');
148
+
149
+ console.log('10 samples of [2, 3, 5] ("love") in casual register:');
150
+ engine.useRegister('casual');
151
+
152
+ const samples = [];
153
+ for (let i = 0; i < 10; i++) {
154
+ samples.push(engine.surfaces.decode([2, 3, 5], { deterministic: false }));
155
+ }
156
+ console.log(` ${samples.join(', ')}\n`);
157
+
158
+ console.log('(Probabilistic selection adds natural variety)');
159
+
160
+ // ============================================
161
+ // 6. Available Registers
162
+ // ============================================
163
+ console.log('\n┌───────────────────────────────────────────────────────────────┐');
164
+ console.log('│ AVAILABLE REGISTERS │');
165
+ console.log('└───────────────────────────────────────────────────────────────┘\n');
166
+
167
+ const registers = engine.getRegisters();
168
+ console.log(` Registers: ${registers.join(', ')}\n`);
169
+
170
+ for (const reg of registers) {
171
+ const example = engine.transform('good think', reg);
172
+ console.log(` ${reg.padEnd(12)} → "${example.transformed}"`);
173
+ }
174
+
175
+ // ============================================
176
+ // Summary
177
+ // ============================================
178
+ console.log('\n╔═══════════════════════════════════════════════════════════════╗');
179
+ console.log('║ KEY INSIGHTS ║');
180
+ console.log('╠═══════════════════════════════════════════════════════════════╣');
181
+ console.log('║ ║');
182
+ console.log('║ 1. MEANING (primes) is universal and invariant ║');
183
+ console.log('║ - Same [7,11,13] = "truth" in all registers ║');
184
+ console.log('║ ║');
185
+ console.log('║ 2. WORDS are local and variable ║');
186
+ console.log('║ - "truth", "verity", "real talk" = same primes ║');
187
+ console.log('║ ║');
188
+ console.log('║ 3. BIAS controls word selection ║');
189
+ console.log('║ - Register (formal/casual/technical/poetic) ║');
190
+ console.log('║ - Context (academic, legal, romantic, etc.) ║');
191
+ console.log('║ - Recency (variety vs. consistency) ║');
192
+ console.log('║ ║');
193
+ console.log('║ 4. This is how TRANSLATION should work: ║');
194
+ console.log('║ Word₁ → Primes → Word₂ (meaning-preserving) ║');
195
+ console.log('║ ║');
196
+ console.log('╚═══════════════════════════════════════════════════════════════╝\n');
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Example 01: Integer Sine Tables
3
+ *
4
+ * Demonstrates the discrete phase dynamics from discrete.pdf using
5
+ * integer sine tables for deterministic phase computation.
6
+ */
7
+
8
+ const { INT_SINE_TABLE, computeHistogramCoherence } = require('../../apps/sentient/lib/prsc');
9
+
10
+ console.log('═══════════════════════════════════════════════════════════════');
11
+ console.log(' Integer Sine Tables for Discrete Phase Dynamics');
12
+ console.log('═══════════════════════════════════════════════════════════════\n');
13
+
14
+ // Basic sine table properties
15
+ console.log('1. Integer Sine Table (M=256)\n');
16
+ console.log(' From discrete.pdf: Pre-computed integer sine values');
17
+ console.log(' for deterministic phase dynamics.\n');
18
+
19
+ console.log(` Table size: ${INT_SINE_TABLE.length} entries`);
20
+ console.log(` Range: [${Math.min(...INT_SINE_TABLE)}, ${Math.max(...INT_SINE_TABLE)}]`);
21
+
22
+ // Sample values
23
+ console.log('\n Sample values (phase → sine):\n');
24
+ console.log(' ┌───────────┬───────────┬──────────────┐');
25
+ console.log(' │ Index │ Phase (°) │ sin(phase) │');
26
+ console.log(' ├───────────┼───────────┼──────────────┤');
27
+
28
+ const sampleIndices = [0, 32, 64, 96, 128, 160, 192, 224, 255];
29
+ for (const i of sampleIndices) {
30
+ const phase = (i / 256 * 360).toFixed(1);
31
+ const value = INT_SINE_TABLE[i];
32
+ const normalized = (value / 127).toFixed(4);
33
+ console.log(` │ ${i.toString().padStart(9)} │ ${phase.padStart(9)} │ ${normalized.padStart(12)} │`);
34
+ }
35
+ console.log(' └───────────┴───────────┴──────────────┘');
36
+
37
+ // Phase accumulator simulation
38
+ console.log('\n2. Phase Accumulator Simulation\n');
39
+
40
+ function simulatePhaseAccumulator(frequency, steps) {
41
+ const history = [];
42
+ let phase = 0;
43
+
44
+ for (let t = 0; t < steps; t++) {
45
+ const idx = Math.floor(phase) & 0xFF; // Mod 256
46
+ const sine = INT_SINE_TABLE[idx];
47
+ history.push({ t, phase: idx, sine, normalized: sine / 127 });
48
+ phase = (phase + frequency) % 256;
49
+ }
50
+
51
+ return history;
52
+ }
53
+
54
+ const freq = 17; // Prime frequency for interesting dynamics
55
+ const simulation = simulatePhaseAccumulator(freq, 16);
56
+
57
+ console.log(` Frequency: ${freq} (phase increment per step)`);
58
+ console.log('\n ┌──────┬───────────┬─────────────┐');
59
+ console.log(' │ Step │ Phase Idx │ Sine Output │');
60
+ console.log(' ├──────┼───────────┼─────────────┤');
61
+
62
+ for (const step of simulation) {
63
+ console.log(` │ ${step.t.toString().padStart(4)} │ ${step.phase.toString().padStart(9)} │ ${step.normalized.toFixed(4).padStart(11)} │`);
64
+ }
65
+ console.log(' └──────┴───────────┴─────────────┘');
66
+
67
+ // Histogram coherence
68
+ console.log('\n3. Histogram Coherence\n');
69
+ console.log(' C_bin(t) = max_k(b_k(t)) / |P|');
70
+ console.log(' Measures how concentrated phases are in a single bin.\n');
71
+
72
+ // Generate random phases and compute coherence
73
+ const randomPhases = Array.from({ length: 32 }, () => Math.random() * 2 * Math.PI);
74
+ const coherentPhases = Array.from({ length: 32 }, (_, i) => Math.PI + 0.1 * (Math.random() - 0.5));
75
+ const bimodalPhases = Array.from({ length: 32 }, (_, i) =>
76
+ i < 16 ? 0.5 + 0.1 * Math.random() : 2.5 + 0.1 * Math.random()
77
+ );
78
+
79
+ const randomCoherence = computeHistogramCoherence(randomPhases);
80
+ const coherentCoherence = computeHistogramCoherence(coherentPhases);
81
+ const bimodalCoherence = computeHistogramCoherence(bimodalPhases);
82
+
83
+ console.log(' ┌───────────────────┬────────────┬──────────────┬─────────────┐');
84
+ console.log(' │ Distribution │ Coherence │ Max Count │ Entropy │');
85
+ console.log(' ├───────────────────┼────────────┼──────────────┼─────────────┤');
86
+ console.log(` │ Random │ ${randomCoherence.coherence.toFixed(4).padStart(10)} │ ${randomCoherence.maxCount.toString().padStart(12)} │ ${randomCoherence.entropy.toFixed(4).padStart(11)} │`);
87
+ console.log(` │ Coherent (peaked) │ ${coherentCoherence.coherence.toFixed(4).padStart(10)} │ ${coherentCoherence.maxCount.toString().padStart(12)} │ ${coherentCoherence.entropy.toFixed(4).padStart(11)} │`);
88
+ console.log(` │ Bimodal │ ${bimodalCoherence.coherence.toFixed(4).padStart(10)} │ ${bimodalCoherence.maxCount.toString().padStart(12)} │ ${bimodalCoherence.entropy.toFixed(4).padStart(11)} │`);
89
+ console.log(' └───────────────────┴────────────┴──────────────┴─────────────┘');
90
+
91
+ // Phase distribution visualization
92
+ console.log('\n4. Phase Distribution (ASCII Histogram)\n');
93
+
94
+ function visualizeHistogram(binCounts, label) {
95
+ const maxCount = Math.max(...binCounts);
96
+ const scale = 40 / maxCount;
97
+
98
+ console.log(` ${label}:`);
99
+ for (let i = 0; i < binCounts.length; i++) {
100
+ const bar = '█'.repeat(Math.round(binCounts[i] * scale));
101
+ console.log(` Bin ${i}: ${bar} (${binCounts[i]})`);
102
+ }
103
+ }
104
+
105
+ console.log(' Random phases:');
106
+ const randomHist = randomCoherence.binCounts;
107
+ visualizeHistogram(randomHist, 'Random');
108
+
109
+ console.log('\n Coherent phases:');
110
+ visualizeHistogram(coherentCoherence.binCounts, 'Coherent');
111
+
112
+ // Application notes
113
+ console.log('\n5. Application in Discrete HQE\n');
114
+ console.log(' Integer sine tables enable:');
115
+ console.log(' • Deterministic phase evolution (no floating-point drift)');
116
+ console.log(' • Efficient hardware implementation (lookup tables)');
117
+ console.log(' • Reproducible dynamics across nodes');
118
+ console.log(' • Histogram coherence for sync detection');
119
+
120
+ console.log('\n═══════════════════════════════════════════════════════════════\n');
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Example 02: Codebook Tunneling
3
+ *
4
+ * Demonstrates the 64-attractor codebook from discrete.pdf for
5
+ * controlled state transitions via tunneling.
6
+ */
7
+
8
+ const { SMF_CODEBOOK, nearestCodebookAttractor, codebookTunnel } = require('../../apps/sentient/lib/smf');
9
+
10
+ console.log('═══════════════════════════════════════════════════════════════');
11
+ console.log(' 64-Attractor Codebook and Tunneling');
12
+ console.log('═══════════════════════════════════════════════════════════════\n');
13
+
14
+ // Codebook structure
15
+ console.log('1. SMF Codebook Structure (64 Attractors)\n');
16
+ console.log(' From discrete.pdf: Pre-defined attractor states for');
17
+ console.log(' controlled tunneling in the Sedenion Memory Field.\n');
18
+
19
+ console.log(` Total attractors: ${SMF_CODEBOOK.length}`);
20
+
21
+ // Group by type
22
+ const byType = {};
23
+ for (const entry of SMF_CODEBOOK) {
24
+ byType[entry.type] = (byType[entry.type] || 0) + 1;
25
+ }
26
+
27
+ console.log('\n Distribution by type:');
28
+ for (const [type, count] of Object.entries(byType)) {
29
+ console.log(` • ${type}: ${count} attractors`);
30
+ }
31
+
32
+ // Sample attractors
33
+ console.log('\n2. Sample Attractors\n');
34
+ console.log(' ┌─────┬────────────────┬────────────────────────┬───────────────┐');
35
+ console.log(' │ ID │ Type │ Active Axes │ State │');
36
+ console.log(' ├─────┼────────────────┼────────────────────────┼───────────────┤');
37
+
38
+ for (const entry of SMF_CODEBOOK.slice(0, 10)) {
39
+ const axes = entry.axes.slice(0, 4).join(', ') + (entry.axes.length > 4 ? '...' : '');
40
+ const state = entry.state.slice(0, 3).join(', ') + '...';
41
+ console.log(` │ ${entry.id.toString().padStart(3)} │ ${entry.type.padEnd(14)} │ ${axes.padEnd(22)} │ ${state.padEnd(13)} │`);
42
+ }
43
+ console.log(' └─────┴────────────────┴────────────────────────┴───────────────┘');
44
+
45
+ // Finding nearest attractor
46
+ console.log('\n3. Finding Nearest Attractor\n');
47
+
48
+ // Create test states
49
+ const testStates = [
50
+ { name: 'Coherent', s: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] },
51
+ { name: 'Random', s: Array.from({ length: 16 }, () => Math.random() * 2 - 1) },
52
+ { name: 'Sparse', s: [0.5, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.3, 0] },
53
+ ];
54
+
55
+ console.log(' Finding nearest codebook attractor for test states:\n');
56
+
57
+ for (const test of testStates) {
58
+ const nearest = nearestCodebookAttractor(test);
59
+ if (nearest) {
60
+ console.log(` ${test.name} state → Attractor ${nearest.entry.id} (${nearest.entry.type})`);
61
+ console.log(` Distance: ${nearest.distance.toFixed(4)}`);
62
+ } else {
63
+ console.log(` ${test.name} state → No attractor found`);
64
+ }
65
+ }
66
+
67
+ // Codebook tunneling
68
+ console.log('\n4. Codebook Tunneling\n');
69
+ console.log(' Controlled state transitions via tunneling:\n');
70
+
71
+ // Create an initial state
72
+ const initialState = { s: [0.8, 0.2, 0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] };
73
+
74
+ // Try tunneling with different parameters
75
+ const tunnelingTests = [
76
+ { rate: 0.1, threshold: 0.3 },
77
+ { rate: 0.5, threshold: 0.5 },
78
+ { rate: 0.9, threshold: 0.7 },
79
+ ];
80
+
81
+ for (const params of tunnelingTests) {
82
+ const result = codebookTunnel(initialState, params.rate, params.threshold);
83
+
84
+ console.log(` Rate=${params.rate}, Threshold=${params.threshold}:`);
85
+ if (result.tunneled) {
86
+ console.log(` ✓ Tunneled to attractor ${result.targetId} (${result.targetType})`);
87
+ console.log(` Blend factor: ${result.blendFactor.toFixed(3)}`);
88
+ } else {
89
+ console.log(` ✗ No tunnel (random check failed or no suitable attractor)`);
90
+ }
91
+ }
92
+
93
+ // Attractor types explained
94
+ console.log('\n5. Attractor Types\n');
95
+
96
+ console.log(' • basis: Single axis activation (pure modes)');
97
+ console.log(' • dual: Two-axis correlation states');
98
+ console.log(' • triad: Three-axis relationships');
99
+ console.log(' • quad: Four-axis complex patterns');
100
+ console.log(' • harmonic: Resonant frequency patterns');
101
+ console.log(' • modular: Modular arithmetic relationships');
102
+
103
+ // Tunneling in practice
104
+ console.log('\n6. Tunneling in Practice\n');
105
+
106
+ console.log(' Codebook tunneling enables:');
107
+ console.log(' • Controlled phase transitions between stable states');
108
+ console.log(' • Escape from local minima during learning');
109
+ console.log(' • Structured exploration of semantic space');
110
+ console.log(' • Deterministic behavior for distributed consensus');
111
+
112
+ console.log('\n Parameters:');
113
+ console.log(' • rate: Probability of attempting a tunnel');
114
+ console.log(' • threshold: Minimum distance to trigger tunneling');
115
+ console.log(' • Higher rate = more frequent transitions');
116
+ console.log(' • Higher threshold = only tunnel from far states');
117
+
118
+ console.log('\n═══════════════════════════════════════════════════════════════\n');
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Example 03: Canonical Fusion Selection
3
+ *
4
+ * Demonstrates deterministic FUSE(p,q,r) selection from discrete.pdf
5
+ * using the canonical triad ordering constraint.
6
+ */
7
+
8
+ const {
9
+ canonicalTriad,
10
+ canonicalFusion,
11
+ canonicalTriadForTarget,
12
+ verifyCanonical
13
+ } = require('../../apps/sentient/lib/prime-calculus');
14
+
15
+ console.log('═══════════════════════════════════════════════════════════════');
16
+ console.log(' Canonical Fusion Selection');
17
+ console.log('═══════════════════════════════════════════════════════════════\n');
18
+
19
+ // The problem with non-canonical fusion
20
+ console.log('1. The Non-Determinism Problem\n');
21
+ console.log(' Given target prime P, many (p, q, r) triads satisfy p + q + r = P:');
22
+ console.log(' • 19 = 3 + 5 + 11 = 3 + 7 + 9 = 5 + 7 + 7 = ...');
23
+ console.log(' • 29 = 3 + 7 + 19 = 5 + 7 + 17 = 5 + 11 + 13 = ...');
24
+ console.log('\n Which one to choose? Canonical ordering provides determinism.\n');
25
+
26
+ // Canonical ordering
27
+ console.log('2. Canonical Ordering\n');
28
+ console.log(' Definition: A triad (p, q, r) is canonical if:');
29
+ console.log(' 1. p ≤ q ≤ r (non-decreasing order)');
30
+ console.log(' 2. All are prime');
31
+ console.log(' 3. p is the smallest possible first element');
32
+ console.log(' 4. Given p, q is the smallest possible second element\n');
33
+
34
+ // Verify triads
35
+ const testTriads = [
36
+ [3, 5, 11], // 19 - canonical
37
+ [5, 3, 11], // 19 - not canonical (order)
38
+ [11, 5, 3], // 19 - not canonical (order)
39
+ [2, 2, 2], // 6 - not prime sum
40
+ [2, 3, 2], // 7 - not ordered
41
+ ];
42
+
43
+ console.log(' Testing triad canonicity:\n');
44
+ console.log(' ┌─────────────────┬───────────┬──────────────────────┐');
45
+ console.log(' │ Triad │ Sum │ Canonical? │');
46
+ console.log(' ├─────────────────┼───────────┼──────────────────────┤');
47
+
48
+ for (const triad of testTriads) {
49
+ const sum = triad.reduce((a, b) => a + b, 0);
50
+ const result = verifyCanonical(triad);
51
+ const status = result.isCanonical ? '✓ Yes' : `✗ No (${result.reason})`;
52
+ console.log(` │ (${triad.join(', ')})`.padEnd(18) + `│ ${sum.toString().padEnd(9)} │ ${status.slice(0, 20).padEnd(20)} │`);
53
+ }
54
+ console.log(' └─────────────────┴───────────┴──────────────────────┘');
55
+
56
+ // Finding canonical triads
57
+ console.log('\n3. Finding Canonical Triads for Target Primes\n');
58
+
59
+ const targetPrimes = [7, 11, 13, 17, 19, 23, 29, 31, 37, 41];
60
+
61
+ console.log(' ┌────────┬─────────────────┬───────────────────────┐');
62
+ console.log(' │ Target │ Canonical Triad │ Verification │');
63
+ console.log(' ├────────┼─────────────────┼───────────────────────┤');
64
+
65
+ for (const target of targetPrimes) {
66
+ const triad = canonicalTriadForTarget(target);
67
+ if (triad) {
68
+ const verification = verifyCanonical(triad);
69
+ const status = verification.isCanonical ? '✓ Verified' : '✗ Failed';
70
+ console.log(` │ ${target.toString().padEnd(6)} │ (${triad.join(', ')})`.padEnd(27) + `│ ${status.padEnd(21)} │`);
71
+ } else {
72
+ console.log(` │ ${target.toString().padEnd(6)} │ (none)`.padEnd(27) + `│ No valid decomposition │`);
73
+ }
74
+ }
75
+ console.log(' └────────┴─────────────────┴───────────────────────┘');
76
+
77
+ // Canonical fusion operation
78
+ console.log('\n4. Canonical Fusion Operation\n');
79
+
80
+ console.log(' FUSE(p, q, r) automatically:');
81
+ console.log(' 1. Reorders arguments to canonical form');
82
+ console.log(' 2. Verifies sum is prime');
83
+ console.log(' 3. Returns fusion result\n');
84
+
85
+ const fusionTests = [
86
+ [5, 3, 11], // Will be reordered to (3, 5, 11)
87
+ [11, 7, 5], // Will be reordered to (5, 7, 11)
88
+ [2, 2, 3], // Sum = 7 (prime)
89
+ ];
90
+
91
+ for (const [p, q, r] of fusionTests) {
92
+ const result = canonicalFusion(p, q, r);
93
+ if (result.success) {
94
+ console.log(` FUSE(${p}, ${q}, ${r}):`);
95
+ console.log(` Canonical form: (${result.canonical.join(', ')})`);
96
+ console.log(` Result: ${result.result}\n`);
97
+ } else {
98
+ console.log(` FUSE(${p}, ${q}, ${r}): Failed - ${result.reason}\n`);
99
+ }
100
+ }
101
+
102
+ // Uniqueness guarantee
103
+ console.log('5. Uniqueness Guarantee\n');
104
+
105
+ console.log(' For any prime P with a valid decomposition,');
106
+ console.log(' canonical selection returns a UNIQUE triad.\n');
107
+
108
+ // Show that different orderings give same canonical result
109
+ const target = 19;
110
+ const orderings = [
111
+ [3, 5, 11],
112
+ [5, 3, 11],
113
+ [11, 3, 5],
114
+ [11, 5, 3],
115
+ [3, 11, 5],
116
+ [5, 11, 3],
117
+ ];
118
+
119
+ console.log(` All orderings of 3+5+11 = ${target}:\n`);
120
+
121
+ for (const ordering of orderings) {
122
+ const canonical = canonicalTriad(ordering);
123
+ console.log(` (${ordering.join(', ')}) → canonical: (${canonical.join(', ')})`);
124
+ }
125
+
126
+ // Applications
127
+ console.log('\n6. Applications\n');
128
+
129
+ console.log(' Canonical fusion enables:');
130
+ console.log(' • Deterministic distributed consensus');
131
+ console.log(' • Reproducible semantic transformations');
132
+ console.log(' • Unique normal forms for proofs');
133
+ console.log(' • Consistent cross-node behavior');
134
+
135
+ console.log('\n═══════════════════════════════════════════════════════════════\n');