@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,139 @@
1
+ /**
2
+ * Example 04: Tick-Only HQE Gating
3
+ *
4
+ * Demonstrates the tick-based discrete gating from discrete.pdf
5
+ * where quantum gates activate only on specific tick boundaries.
6
+ */
7
+
8
+ const { TickGate } = require('../../apps/sentient/lib/hqe');
9
+
10
+ console.log('═══════════════════════════════════════════════════════════════');
11
+ console.log(' Tick-Only HQE Gating');
12
+ console.log('═══════════════════════════════════════════════════════════════\n');
13
+
14
+ // The tick gate concept
15
+ console.log('1. Tick-Based Discrete Gating\n');
16
+ console.log(' From discrete.pdf: Gates activate on discrete tick');
17
+ console.log(' boundaries rather than continuous time.\n');
18
+ console.log(' Benefits:');
19
+ console.log(' • Deterministic gate timing');
20
+ console.log(' • Reduced noise sensitivity');
21
+ console.log(' • Synchronized multi-gate operations');
22
+ console.log(' • Hardware-friendly implementation\n');
23
+
24
+ // Create tick gates
25
+ console.log('2. Creating Tick Gates\n');
26
+
27
+ const gates = [
28
+ new TickGate({ period: 4, phase: 0, name: 'G0' }),
29
+ new TickGate({ period: 4, phase: 1, name: 'G1' }),
30
+ new TickGate({ period: 4, phase: 2, name: 'G2' }),
31
+ new TickGate({ period: 4, phase: 3, name: 'G3' }),
32
+ ];
33
+
34
+ console.log(' Created 4 gates with period=4, different phases:\n');
35
+ for (const gate of gates) {
36
+ console.log(` • ${gate.name}: period=${gate.period}, phase=${gate.phase}`);
37
+ }
38
+
39
+ // Tick simulation
40
+ console.log('\n3. Tick Simulation\n');
41
+ console.log(' Simulating 12 ticks, showing which gates are open:\n');
42
+
43
+ console.log(' ┌──────┬──────┬──────┬──────┬──────┐');
44
+ console.log(' │ Tick │ G0 │ G1 │ G2 │ G3 │');
45
+ console.log(' ├──────┼──────┼──────┼──────┼──────┤');
46
+
47
+ for (let tick = 0; tick < 12; tick++) {
48
+ const states = gates.map(g => g.isOpen(tick) ? ' ● ' : ' ○ ');
49
+ console.log(` │ ${tick.toString().padStart(4)} │${states.join('│')}│`);
50
+ }
51
+ console.log(' └──────┴──────┴──────┴──────┴──────┘');
52
+
53
+ // Gate application
54
+ console.log('\n4. Gate Application\n');
55
+
56
+ const inputState = { amplitude: 1.0, phase: 0 };
57
+ const operation = (state) => ({
58
+ amplitude: state.amplitude * 0.9,
59
+ phase: state.phase + Math.PI / 4
60
+ });
61
+
62
+ console.log(' Applying gate operation through tick sequence:\n');
63
+ console.log(` Input state: amplitude=${inputState.amplitude}, phase=${inputState.phase.toFixed(3)}`);
64
+
65
+ let currentState = { ...inputState };
66
+ const gate = gates[0];
67
+
68
+ console.log('\n ┌──────┬─────────────┬───────────────┬───────────────┐');
69
+ console.log(' │ Tick │ Gate Open? │ Amplitude │ Phase │');
70
+ console.log(' ├──────┼─────────────┼───────────────┼───────────────┤');
71
+
72
+ for (let tick = 0; tick < 8; tick++) {
73
+ const open = gate.isOpen(tick);
74
+ if (open) {
75
+ currentState = gate.apply(currentState, operation, tick);
76
+ }
77
+ const status = open ? 'Yes ●' : 'No ○';
78
+ console.log(` │ ${tick.toString().padStart(4)} │ ${status.padEnd(11)} │ ${currentState.amplitude.toFixed(6).padStart(13)} │ ${currentState.phase.toFixed(6).padStart(13)} │`);
79
+ }
80
+ console.log(' └──────┴─────────────┴───────────────┴───────────────┘');
81
+
82
+ // Multiple coordinated gates
83
+ console.log('\n5. Coordinated Multi-Gate Operations\n');
84
+
85
+ console.log(' Multiple gates can be coordinated for complex operations:');
86
+ console.log(' • Sequential: G0 → G1 → G2 → G3');
87
+ console.log(' • Parallel: All gates at same phase');
88
+ console.log(' • Interleaved: Even/odd tick separation\n');
89
+
90
+ const seqGate = new TickGate({ period: 8, phase: 0, name: 'Prepare' });
91
+ const midGate = new TickGate({ period: 8, phase: 2, name: 'Process' });
92
+ const endGate = new TickGate({ period: 8, phase: 4, name: 'Measure' });
93
+
94
+ console.log(' Sequential pipeline (period=8):');
95
+ console.log(' ┌──────┬──────────┬──────────┬──────────┐');
96
+ console.log(' │ Tick │ Prepare │ Process │ Measure │');
97
+ console.log(' ├──────┼──────────┼──────────┼──────────┤');
98
+
99
+ for (let tick = 0; tick < 8; tick++) {
100
+ const prep = seqGate.isOpen(tick) ? ' ● ' : ' ○ ';
101
+ const proc = midGate.isOpen(tick) ? ' ● ' : ' ○ ';
102
+ const meas = endGate.isOpen(tick) ? ' ● ' : ' ○ ';
103
+ console.log(` │ ${tick.toString().padStart(4)} │${prep}│${proc}│${meas}│`);
104
+ }
105
+ console.log(' └──────┴──────────┴──────────┴──────────┘');
106
+
107
+ // Prime-period gates
108
+ console.log('\n6. Prime-Period Gates\n');
109
+
110
+ console.log(' Using prime periods avoids synchronization artifacts:');
111
+
112
+ const primeGates = [
113
+ new TickGate({ period: 3, phase: 0, name: 'P3' }),
114
+ new TickGate({ period: 5, phase: 0, name: 'P5' }),
115
+ new TickGate({ period: 7, phase: 0, name: 'P7' }),
116
+ ];
117
+
118
+ console.log('\n Prime periods (3, 5, 7):');
119
+ console.log(' ┌──────┬──────┬──────┬──────┬─────────────┐');
120
+ console.log(' │ Tick │ P3 │ P5 │ P7 │ All Open │');
121
+ console.log(' ├──────┼──────┼──────┼──────┼─────────────┤');
122
+
123
+ for (let tick = 0; tick < 15; tick++) {
124
+ const p3 = primeGates[0].isOpen(tick);
125
+ const p5 = primeGates[1].isOpen(tick);
126
+ const p7 = primeGates[2].isOpen(tick);
127
+ const allOpen = p3 && p5 && p7 ? 'Yes (LCM=105)' : '';
128
+
129
+ const s3 = p3 ? ' ● ' : ' ○ ';
130
+ const s5 = p5 ? ' ● ' : ' ○ ';
131
+ const s7 = p7 ? ' ● ' : ' ○ ';
132
+ console.log(` │ ${tick.toString().padStart(4)} │${s3}│${s5}│${s7}│ ${allOpen.padEnd(11)} │`);
133
+ }
134
+ console.log(' └──────┴──────┴──────┴──────┴─────────────┘');
135
+
136
+ console.log('\n Prime periods ensure gates rarely align simultaneously,');
137
+ console.log(' reducing interference and providing temporal isolation.');
138
+
139
+ console.log('\n═══════════════════════════════════════════════════════════════\n');
@@ -0,0 +1,142 @@
1
+ # Discrete Dynamics Examples
2
+
3
+ These examples demonstrate the discrete-time dynamics from the discrete.pdf paper for deterministic semantic computation.
4
+
5
+ ## Examples
6
+
7
+ ### [01-integer-sine-table.js](./01-integer-sine-table.js)
8
+
9
+ Integer sine tables for discrete phase dynamics:
10
+
11
+ - Pre-computed M=256 sine table
12
+ - Phase accumulator simulation
13
+ - Histogram coherence measurement
14
+ - Phase distribution visualization
15
+
16
+ ```bash
17
+ node examples/discrete/01-integer-sine-table.js
18
+ ```
19
+
20
+ ### [02-codebook-tunneling.js](./02-codebook-tunneling.js)
21
+
22
+ 64-attractor codebook and controlled tunneling:
23
+
24
+ - SMF_CODEBOOK structure (64 attractors)
25
+ - Finding nearest attractor
26
+ - Controlled state transitions
27
+ - Tunneling parameters
28
+
29
+ ```bash
30
+ node examples/discrete/02-codebook-tunneling.js
31
+ ```
32
+
33
+ ### [03-canonical-fusion.js](./03-canonical-fusion.js)
34
+
35
+ Deterministic FUSE(p,q,r) selection:
36
+
37
+ - Canonical triad ordering
38
+ - Finding triads for target primes
39
+ - Uniqueness guarantee
40
+ - Verification utilities
41
+
42
+ ```bash
43
+ node examples/discrete/03-canonical-fusion.js
44
+ ```
45
+
46
+ ### [04-tick-gate.js](./04-tick-gate.js)
47
+
48
+ Tick-based discrete HQE gating:
49
+
50
+ - TickGate class usage
51
+ - Coordinated multi-gate operations
52
+ - Sequential pipelines
53
+ - Prime-period isolation
54
+
55
+ ```bash
56
+ node examples/discrete/04-tick-gate.js
57
+ ```
58
+
59
+ ## Key Concepts
60
+
61
+ ### Integer Sine Tables
62
+
63
+ Pre-computed lookup tables for deterministic phase dynamics:
64
+
65
+ ```javascript
66
+ const { INT_SINE_TABLE, computeHistogramCoherence } = require('@aleph-ai/tinyaleph/apps/sentient/lib/prsc');
67
+
68
+ // Lookup sine value (range -127 to 127)
69
+ const idx = 64; // 90 degrees
70
+ console.log(INT_SINE_TABLE[idx]); // 127 (max)
71
+
72
+ // Compute histogram coherence
73
+ const phases = [0.1, 0.12, 0.11, 0.09, 0.15];
74
+ const coherence = computeHistogramCoherence(phases);
75
+ console.log(coherence.coherence); // High (phases clustered)
76
+ ```
77
+
78
+ ### Codebook Tunneling
79
+
80
+ 64-attractor codebook for controlled state transitions:
81
+
82
+ ```javascript
83
+ const { SMF_CODEBOOK, nearestCodebookAttractor, codebookTunnel } = require('@aleph-ai/tinyaleph/apps/sentient/lib/smf');
84
+
85
+ // Find nearest attractor
86
+ const state = { s: [1, 0, 0, 0, ...] };
87
+ const nearest = nearestCodebookAttractor(state);
88
+
89
+ // Controlled tunneling
90
+ const result = codebookTunnel(state, 0.5, 0.3);
91
+ if (result.tunneled) {
92
+ console.log(`Tunneled to attractor ${result.targetId}`);
93
+ }
94
+ ```
95
+
96
+ ### Canonical Fusion
97
+
98
+ Deterministic triad selection:
99
+
100
+ ```javascript
101
+ const { canonicalFusion, canonicalTriadForTarget } = require('@aleph-ai/tinyaleph/apps/sentient/lib/prime-calculus');
102
+
103
+ // Get canonical triad for target prime
104
+ const triad = canonicalTriadForTarget(19);
105
+ console.log(triad); // [3, 5, 11]
106
+
107
+ // Fuse with automatic canonicalization
108
+ const result = canonicalFusion(11, 3, 5); // Reordered to (3, 5, 11)
109
+ console.log(result.result); // 19
110
+ ```
111
+
112
+ ### Tick Gates
113
+
114
+ Discrete-time gate activation:
115
+
116
+ ```javascript
117
+ const { TickGate } = require('@aleph-ai/tinyaleph/apps/sentient/lib/hqe');
118
+
119
+ const gate = new TickGate({ period: 4, phase: 0 });
120
+
121
+ for (let tick = 0; tick < 8; tick++) {
122
+ if (gate.isOpen(tick)) {
123
+ console.log(`Gate open at tick ${tick}`);
124
+ }
125
+ }
126
+ ```
127
+
128
+ ## Running All Examples
129
+
130
+ ```bash
131
+ # Run all discrete examples
132
+ for f in examples/discrete/*.js; do node "$f"; done
133
+ ```
134
+
135
+ ## References
136
+
137
+ - discrete.pdf: "Discrete Dynamics for Semantic Computation"
138
+ - Section 2: Integer Sine Tables
139
+ - Section 3: Histogram Coherence
140
+ - Section 4: Codebook Tunneling
141
+ - Section 5: Canonical Fusion
142
+ - Section 6: Tick-Only Gating
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Example: Typed Terms in Prime-Indexed Semantic Calculi
3
+ *
4
+ * Demonstrates the formal type system:
5
+ * - N(p): Noun terms indexed by prime
6
+ * - A(p): Adjective/operator terms
7
+ * - Operator application with p < q constraint
8
+ * - Triadic fusion FUSE(p,q,r)
9
+ */
10
+
11
+ const {
12
+ N, A, FUSE, CHAIN, SENTENCE, SEQ, IMPL,
13
+ NounTerm, AdjTerm, ChainTerm, FusionTerm,
14
+ TypeChecker
15
+ } = require('../../core');
16
+
17
+ console.log('=== Typed Terms in Prime-Indexed Semantic Calculi ===\n');
18
+
19
+ // ============================================================================
20
+ // 1. Basic Term Construction
21
+ // ============================================================================
22
+
23
+ console.log('1. BASIC TERM CONSTRUCTION\n');
24
+
25
+ // Noun terms - N(p)
26
+ const truth = N(7); // N(7) - "truth" (semantic meaning)
27
+ const light = N(11); // N(11) - "light/illumination"
28
+ const wisdom = N(17); // N(17) - "wisdom"
29
+
30
+ console.log(`Noun terms:`);
31
+ console.log(` N(7) = ${truth.signature()}`);
32
+ console.log(` N(11) = ${light.signature()}`);
33
+ console.log(` N(17) = ${wisdom.signature()}`);
34
+ console.log(` All well-formed: ${truth.isWellFormed() && light.isWellFormed() && wisdom.isWellFormed()}`);
35
+
36
+ // Adjective terms - A(p)
37
+ const dual = A(2); // A(2) - "dual" modifier
38
+ const triple = A(3); // A(3) - "triple" modifier
39
+ const vital = A(5); // A(5) - "vital" modifier
40
+
41
+ console.log(`\nAdjective terms:`);
42
+ console.log(` A(2) = ${dual.signature()}`);
43
+ console.log(` A(3) = ${triple.signature()}`);
44
+ console.log(` A(5) = ${vital.signature()}`);
45
+
46
+ // ============================================================================
47
+ // 2. Operator Application with Ordering Constraint
48
+ // ============================================================================
49
+
50
+ console.log('\n2. OPERATOR APPLICATION (p < q constraint)\n');
51
+
52
+ // A(p) can apply to N(q) only if p < q
53
+ console.log(`Can A(3) apply to N(7)? ${triple.canApplyTo(truth)}`); // true: 3 < 7
54
+ console.log(`Can A(5) apply to N(7)? ${vital.canApplyTo(truth)}`); // true: 5 < 7
55
+ console.log(`Can A(11) apply to N(7)? ${A(11).canApplyTo(truth)}`); // false: 11 > 7
56
+
57
+ // Building operator chains
58
+ const modified = CHAIN([2, 3, 5], N(7)); // A(2)A(3)A(5)N(7)
59
+ console.log(`\nChain: ${modified.toString()}`);
60
+ console.log(`Signature: ${modified.signature()}`);
61
+ console.log(`Well-formed: ${modified.isWellFormed()}`); // true: all primes < 7
62
+
63
+ // Ill-formed chain (violates constraint)
64
+ const illFormed = CHAIN([2, 11], N(7)); // A(2)A(11)N(7) - 11 > 7
65
+ console.log(`\nIll-formed chain: ${illFormed.toString()}`);
66
+ console.log(`Well-formed: ${illFormed.isWellFormed()}`); // false
67
+
68
+ // ============================================================================
69
+ // 3. Triadic Fusion
70
+ // ============================================================================
71
+
72
+ console.log('\n3. TRIADIC FUSION - FUSE(p, q, r)\n');
73
+
74
+ // FUSE(p,q,r) is well-formed when:
75
+ // 1. p, q, r are distinct odd primes
76
+ // 2. p + q + r is prime
77
+
78
+ const fusion1 = FUSE(3, 5, 11); // 3 + 5 + 11 = 19 (prime)
79
+ console.log(`FUSE(3, 5, 11):`);
80
+ console.log(` Signature: ${fusion1.signature()}`);
81
+ console.log(` Well-formed: ${fusion1.isWellFormed()}`);
82
+ console.log(` Fused prime: ${fusion1.getFusedPrime()}`);
83
+
84
+ const fusion2 = FUSE(5, 7, 11); // 5 + 7 + 11 = 23 (prime)
85
+ console.log(`\nFUSE(5, 7, 11):`);
86
+ console.log(` Signature: ${fusion2.signature()}`);
87
+ console.log(` Well-formed: ${fusion2.isWellFormed()}`);
88
+ console.log(` Fused prime: ${fusion2.getFusedPrime()}`);
89
+
90
+ // Invalid fusion (sum not prime)
91
+ const invalidFusion = FUSE(2, 3, 5); // 2 + 3 + 5 = 10 (not prime)
92
+ console.log(`\nFUSE(2, 3, 5):`);
93
+ console.log(` Well-formed: ${invalidFusion.isWellFormed()}`); // false
94
+
95
+ // Find all valid triads for a target prime
96
+ console.log(`\nValid triads for prime 29:`);
97
+ const triads = FusionTerm.findTriads(29);
98
+ triads.slice(0, 5).forEach(t => {
99
+ console.log(` ${t.signature()} → ${t.p + t.q + t.r}`);
100
+ });
101
+
102
+ // ============================================================================
103
+ // 4. Sentence Composition
104
+ // ============================================================================
105
+
106
+ console.log('\n4. SENTENCE COMPOSITION\n');
107
+
108
+ // NounSentence - lift noun expression to sentence level
109
+ const s1 = SENTENCE(N(7)); // [N(7)]
110
+ const s2 = SENTENCE(N(11)); // [N(11)]
111
+
112
+ console.log(`Noun sentences:`);
113
+ console.log(` S₁ = ${s1.signature()}`);
114
+ console.log(` S₂ = ${s2.signature()}`);
115
+
116
+ // Sequential composition: S₁ ◦ S₂
117
+ const seq = SEQ(s1, s2);
118
+ console.log(`\nSequential composition (◦):`);
119
+ console.log(` S₁ ◦ S₂ = ${seq.signature()}`);
120
+ console.log(` Discourse state: [${seq.getDiscourseState().join(', ')}]`);
121
+
122
+ // Implication: S₁ ⇒ S₂
123
+ const impl = IMPL(s1, s2);
124
+ console.log(`\nImplication (⇒):`);
125
+ console.log(` S₁ ⇒ S₂ = ${impl.signature()}`);
126
+
127
+ // ============================================================================
128
+ // 5. Type Checking
129
+ // ============================================================================
130
+
131
+ console.log('\n5. TYPE CHECKING\n');
132
+
133
+ const checker = new TypeChecker();
134
+
135
+ // Check various terms
136
+ const terms = [
137
+ N(7),
138
+ A(3),
139
+ CHAIN([2, 3], N(7)),
140
+ FUSE(3, 5, 11),
141
+ SENTENCE(N(7))
142
+ ];
143
+
144
+ console.log(`Type inference:`);
145
+ for (const term of terms) {
146
+ const type = checker.inferType(term);
147
+ console.log(` ${term.signature()} : ${type}`);
148
+ }
149
+
150
+ // Typing judgment derivation
151
+ const judgment = checker.derive(CHAIN([2, 3], N(7)));
152
+ console.log(`\nTyping judgment:`);
153
+ console.log(` ${judgment.toString()}`);
154
+ console.log(` Valid: ${judgment.isValid()}`);
155
+
156
+ console.log('\n=== Done ===');
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Example: Reduction Semantics and Strong Normalization
3
+ *
4
+ * Demonstrates the operational semantics:
5
+ * - Small-step reduction (→)
6
+ * - Prime-preserving operators (⊕)
7
+ * - Strong normalization proof
8
+ * - Confluence via Newman's Lemma
9
+ * - Fusion canonicalization
10
+ */
11
+
12
+ const {
13
+ N, A, FUSE, CHAIN,
14
+ ReductionSystem, ResonancePrimeOperator, NextPrimeOperator,
15
+ isNormalForm, isReducible, termSize,
16
+ FusionCanonicalizer, NormalFormVerifier,
17
+ demonstrateStrongNormalization, testLocalConfluence
18
+ } = require('../../core');
19
+
20
+ console.log('=== Reduction Semantics and Strong Normalization ===\n');
21
+
22
+ // ============================================================================
23
+ // 1. Prime-Preserving Operators
24
+ // ============================================================================
25
+
26
+ console.log('1. PRIME-PRESERVING OPERATORS (⊕)\n');
27
+
28
+ const resonanceOp = new ResonancePrimeOperator();
29
+ const nextPrimeOp = new NextPrimeOperator();
30
+
31
+ console.log('Operator applicability (p < q required):');
32
+ console.log(` 3 ⊕ 7 applicable: ${resonanceOp.canApply(3, 7)}`); // true
33
+ console.log(` 7 ⊕ 3 applicable: ${resonanceOp.canApply(7, 3)}`); // false
34
+ console.log(` 4 ⊕ 7 applicable: ${resonanceOp.canApply(4, 7)}`); // false (4 not prime)
35
+
36
+ console.log('\nResonance operator results:');
37
+ console.log(` 3 ⊕ 7 = ${resonanceOp.apply(3, 7)} (via resonance)`);
38
+ console.log(` 5 ⊕ 11 = ${resonanceOp.apply(5, 11)} (via resonance)`);
39
+ console.log(` 7 ⊕ 13 = ${resonanceOp.apply(7, 13)} (via resonance)`);
40
+
41
+ console.log('\nNext-prime operator results:');
42
+ console.log(` 3 ⊕ 7 = ${nextPrimeOp.apply(3, 7)} (next prime after 7+3)`);
43
+ console.log(` 5 ⊕ 11 = ${nextPrimeOp.apply(5, 11)} (next prime after 11+5)`);
44
+
45
+ // ============================================================================
46
+ // 2. Normal Form Detection
47
+ // ============================================================================
48
+
49
+ console.log('\n2. NORMAL FORM DETECTION\n');
50
+
51
+ const noun = N(7);
52
+ const chain = CHAIN([2, 3], N(7));
53
+ const fusion = FUSE(3, 5, 11);
54
+
55
+ console.log('Term analysis:');
56
+ console.log(` N(7) - normal form: ${isNormalForm(noun)}, reducible: ${isReducible(noun)}`);
57
+ console.log(` A(2)A(3)N(7) - normal form: ${isNormalForm(chain)}, reducible: ${isReducible(chain)}`);
58
+ console.log(` FUSE(3,5,11) - normal form: ${isNormalForm(fusion)}, reducible: ${isReducible(fusion)}`);
59
+
60
+ console.log('\nTerm sizes (for termination measure):');
61
+ console.log(` |N(7)| = ${termSize(noun)}`);
62
+ console.log(` |A(3)| = ${termSize(A(3))}`);
63
+ console.log(` |A(2)A(3)N(7)| = ${termSize(chain)}`);
64
+ console.log(` |FUSE(3,5,11)| = ${termSize(fusion)}`);
65
+
66
+ // ============================================================================
67
+ // 3. Step-by-Step Reduction
68
+ // ============================================================================
69
+
70
+ console.log('\n3. STEP-BY-STEP REDUCTION\n');
71
+
72
+ const reducer = new ReductionSystem();
73
+
74
+ // Reduce a fusion term
75
+ console.log('Reducing FUSE(3, 5, 11):');
76
+ const fusionStep = reducer.step(fusion);
77
+ console.log(` ${fusionStep.before} →[${fusionStep.rule}] ${fusionStep.after}`);
78
+ console.log(` Result: N(${fusionStep.details.sum})`);
79
+
80
+ // Reduce an operator chain step by step
81
+ console.log('\nReducing A(2)A(3)N(7) step by step:');
82
+ const chainTerm = CHAIN([2, 3], N(7));
83
+ const trace = reducer.normalize(chainTerm);
84
+
85
+ console.log(` Initial: ${trace.initial.signature()}`);
86
+ for (let i = 0; i < trace.steps.length; i++) {
87
+ const step = trace.steps[i];
88
+ console.log(` Step ${i+1}: ${step.before.signature()} →[${step.rule}] ${step.after.signature()}`);
89
+ if (step.details.operator) {
90
+ console.log(` (${step.details.operator} ⊕ ${step.details.operand} = ${step.details.result})`);
91
+ }
92
+ }
93
+ console.log(` Final: ${trace.final.signature()}`);
94
+
95
+ // ============================================================================
96
+ // 4. Full Evaluation
97
+ // ============================================================================
98
+
99
+ console.log('\n4. FULL EVALUATION\n');
100
+
101
+ const terms = [
102
+ FUSE(3, 5, 11),
103
+ CHAIN([2], N(7)),
104
+ CHAIN([2, 3, 5], N(11)),
105
+ FUSE(5, 7, 11)
106
+ ];
107
+
108
+ console.log('Evaluating terms to normal form:');
109
+ for (const term of terms) {
110
+ const result = reducer.evaluate(term);
111
+ console.log(` ${term.signature()} →* N(${result.prime})`);
112
+ }
113
+
114
+ // ============================================================================
115
+ // 5. Strong Normalization Proof
116
+ // ============================================================================
117
+
118
+ console.log('\n5. STRONG NORMALIZATION (Theorem 1)\n');
119
+
120
+ console.log('Lemma: If e → e\', then |e\'| < |e|');
121
+ console.log('This ensures termination - no infinite reduction sequences.\n');
122
+
123
+ const proofTerm = CHAIN([2, 3], N(7));
124
+ const proof = demonstrateStrongNormalization(proofTerm);
125
+
126
+ console.log(`Term: ${proof.term}`);
127
+ console.log(`Size sequence: [${proof.sizes.join(' > ')}]`);
128
+ console.log(`Strictly decreasing: ${proof.strictlyDecreasing}`);
129
+ console.log(`Normal form: ${proof.normalForm}`);
130
+ console.log(`Verified: ${proof.verified}`);
131
+
132
+ // ============================================================================
133
+ // 6. Confluence
134
+ // ============================================================================
135
+
136
+ console.log('\n6. CONFLUENCE (Theorem 2)\n');
137
+
138
+ console.log('By Newman\'s Lemma: SN + local confluence → confluence');
139
+ console.log('Different reduction orders always reach the same normal form.\n');
140
+
141
+ const confluenceTest = testLocalConfluence();
142
+ console.log(`All test cases confluent: ${confluenceTest.allConfluent}`);
143
+ for (const tc of confluenceTest.testCases) {
144
+ console.log(` ${tc.term} →* ${tc.normalForm}`);
145
+ }
146
+
147
+ // ============================================================================
148
+ // 7. Fusion Canonicalization
149
+ // ============================================================================
150
+
151
+ console.log('\n7. FUSION CANONICALIZATION\n');
152
+
153
+ const canonicalizer = new FusionCanonicalizer();
154
+
155
+ console.log('Finding canonical triads (d*(P)):');
156
+ const targetPrimes = [19, 23, 29, 31];
157
+
158
+ for (const P of targetPrimes) {
159
+ const allTriads = canonicalizer.getTriads(P);
160
+ const canonical = canonicalizer.selectCanonical(P);
161
+
162
+ if (canonical) {
163
+ console.log(` P = ${P}: ${allTriads.length} triads, canonical = FUSE(${canonical.p}, ${canonical.q}, ${canonical.r})`);
164
+ } else {
165
+ console.log(` P = ${P}: no valid triads`);
166
+ }
167
+ }
168
+
169
+ // Show scoring
170
+ console.log('\nTriad scoring for P = 23:');
171
+ const triads23 = canonicalizer.getTriads(23);
172
+ for (const t of triads23.slice(0, 3)) {
173
+ const score = canonicalizer.resonanceScore(t);
174
+ console.log(` FUSE(${t.p}, ${t.q}, ${t.r}) - score: ${score.toFixed(4)}`);
175
+ }
176
+
177
+ // ============================================================================
178
+ // 8. Normal Form Verification
179
+ // ============================================================================
180
+
181
+ console.log('\n8. NORMAL FORM VERIFICATION (NF_ok)\n');
182
+
183
+ const verifier = new NormalFormVerifier();
184
+
185
+ // Correct claims
186
+ console.log('Verifying normal form claims:');
187
+ console.log(` NF_ok(FUSE(3,5,11), 19): ${verifier.verify(FUSE(3, 5, 11), 19)}`);
188
+ console.log(` NF_ok(FUSE(5,7,11), 23): ${verifier.verify(FUSE(5, 7, 11), 23)}`);
189
+
190
+ // Incorrect claims
191
+ console.log(` NF_ok(FUSE(3,5,11), 17): ${verifier.verify(FUSE(3, 5, 11), 17)}`); // wrong
192
+
193
+ // Generate certificate
194
+ console.log('\nVerification certificate:');
195
+ const cert = verifier.certificate(CHAIN([2, 3], N(7)), N(7));
196
+ console.log(` Term: ${cert.term}`);
197
+ console.log(` Claimed: ${cert.claimed}`);
198
+ console.log(` Actual: ${cert.actual}`);
199
+ console.log(` Verified: ${cert.verified}`);
200
+ console.log(` Steps: ${cert.steps}`);
201
+
202
+ console.log('\n=== Done ===');