@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,263 @@
1
+ /**
2
+ * @example Content-Addressable Storage
3
+ * @description Use content hashes as addresses for deduplication
4
+ *
5
+ * Content-addressable storage uses the hash of content as its address:
6
+ * - Identical content always has the same address
7
+ * - Enables automatic deduplication
8
+ * - Used in Git, IPFS, and other systems
9
+ */
10
+
11
+ const { CryptographicBackend } = require('../../modular');
12
+
13
+ // ===========================================
14
+ // SETUP
15
+ // ===========================================
16
+
17
+ const backend = new CryptographicBackend({ dimension: 32 });
18
+
19
+ console.log('TinyAleph Content-Addressable Storage Example');
20
+ console.log('=============================================\n');
21
+
22
+ // ===========================================
23
+ // CONTENT-ADDRESSABLE STORE
24
+ // ===========================================
25
+
26
+ function ContentStore() {
27
+ this.objects = {};
28
+ this.refs = {};
29
+ }
30
+
31
+ ContentStore.prototype.hash = function(content) {
32
+ return backend.hash(content, 32).toString('hex');
33
+ };
34
+
35
+ ContentStore.prototype.put = function(content) {
36
+ var hash = this.hash(content);
37
+ if (!this.objects[hash]) {
38
+ this.objects[hash] = content;
39
+ return { hash: hash, new: true };
40
+ }
41
+ return { hash: hash, new: false, deduplicated: true };
42
+ };
43
+
44
+ ContentStore.prototype.get = function(hash) {
45
+ return this.objects[hash];
46
+ };
47
+
48
+ ContentStore.prototype.has = function(hash) {
49
+ return !!this.objects[hash];
50
+ };
51
+
52
+ ContentStore.prototype.setRef = function(name, hash) {
53
+ this.refs[name] = hash;
54
+ };
55
+
56
+ ContentStore.prototype.getRef = function(name) {
57
+ return this.refs[name];
58
+ };
59
+
60
+ ContentStore.prototype.stats = function() {
61
+ return {
62
+ objectCount: Object.keys(this.objects).length,
63
+ refCount: Object.keys(this.refs).length,
64
+ totalSize: Object.values(this.objects).reduce(function(sum, obj) {
65
+ return sum + obj.length;
66
+ }, 0)
67
+ };
68
+ };
69
+
70
+ // ===========================================
71
+ // BASIC USAGE
72
+ // ===========================================
73
+
74
+ console.log('Basic Content-Addressable Storage:');
75
+ console.log('-'.repeat(50) + '\n');
76
+
77
+ var store = new ContentStore();
78
+
79
+ var content1 = 'Hello, World!';
80
+ var content2 = 'Goodbye, World!';
81
+ var content3 = 'Hello, World!'; // Duplicate
82
+
83
+ var result1 = store.put(content1);
84
+ var result2 = store.put(content2);
85
+ var result3 = store.put(content3);
86
+
87
+ console.log('Storing content:');
88
+ console.log(' "' + content1 + '" -> ' + result1.hash.substring(0, 16) + '... (new: ' + result1.new + ')');
89
+ console.log(' "' + content2 + '" -> ' + result2.hash.substring(0, 16) + '... (new: ' + result2.new + ')');
90
+ console.log(' "' + content3 + '" -> ' + result3.hash.substring(0, 16) + '... (new: ' + result3.new + ', dedup: ' + result3.deduplicated + ')');
91
+
92
+ console.log('\nRetrieving by hash:');
93
+ console.log(' ' + result1.hash.substring(0, 16) + '... -> "' + store.get(result1.hash) + '"');
94
+
95
+ // ===========================================
96
+ // DEDUPLICATION
97
+ // ===========================================
98
+
99
+ console.log('\n' + '='.repeat(50));
100
+ console.log('Automatic Deduplication:');
101
+ console.log('='.repeat(50) + '\n');
102
+
103
+ var dedupStore = new ContentStore();
104
+
105
+ // Simulate storing files with duplicates
106
+ var files = [
107
+ { name: 'doc1.txt', content: 'This is document content.' },
108
+ { name: 'doc2.txt', content: 'Different document content.' },
109
+ { name: 'doc3.txt', content: 'This is document content.' }, // Duplicate of doc1
110
+ { name: 'doc4.txt', content: 'Another unique document.' },
111
+ { name: 'doc5.txt', content: 'This is document content.' } // Duplicate of doc1
112
+ ];
113
+
114
+ var fileRefs = {};
115
+ var stats = { stored: 0, deduplicated: 0 };
116
+
117
+ console.log('Storing files:\n');
118
+
119
+ for (var i = 0; i < files.length; i++) {
120
+ var file = files[i];
121
+ var result = dedupStore.put(file.content);
122
+ fileRefs[file.name] = result.hash;
123
+
124
+ if (result.new) {
125
+ stats.stored++;
126
+ console.log(' ' + file.name + ': STORED (new content)');
127
+ } else {
128
+ stats.deduplicated++;
129
+ console.log(' ' + file.name + ': DEDUPLICATED (content exists)');
130
+ }
131
+ }
132
+
133
+ console.log('\nDeduplication stats:');
134
+ console.log(' Total files: ' + files.length);
135
+ console.log(' Unique stored: ' + stats.stored);
136
+ console.log(' Deduplicated: ' + stats.deduplicated);
137
+ console.log(' Space saved: ' + (stats.deduplicated / files.length * 100).toFixed(0) + '%');
138
+
139
+ // ===========================================
140
+ // VERSIONED STORAGE
141
+ // ===========================================
142
+
143
+ console.log('\n' + '='.repeat(50));
144
+ console.log('Version Control with Content Addressing:');
145
+ console.log('='.repeat(50) + '\n');
146
+
147
+ function VersionedDocument(store, name) {
148
+ this.store = store;
149
+ this.name = name;
150
+ this.versions = [];
151
+ }
152
+
153
+ VersionedDocument.prototype.update = function(content) {
154
+ var result = this.store.put(content);
155
+ this.versions.push({
156
+ hash: result.hash,
157
+ timestamp: new Date().toISOString(),
158
+ version: this.versions.length + 1
159
+ });
160
+ return result;
161
+ };
162
+
163
+ VersionedDocument.prototype.getVersion = function(version) {
164
+ var versionInfo = this.versions[version - 1];
165
+ if (!versionInfo) return null;
166
+ return {
167
+ content: this.store.get(versionInfo.hash),
168
+ ...versionInfo
169
+ };
170
+ };
171
+
172
+ VersionedDocument.prototype.latest = function() {
173
+ return this.getVersion(this.versions.length);
174
+ };
175
+
176
+ VersionedDocument.prototype.history = function() {
177
+ return this.versions;
178
+ };
179
+
180
+ var vStore = new ContentStore();
181
+ var doc = new VersionedDocument(vStore, 'readme.md');
182
+
183
+ console.log('Creating document versions:\n');
184
+
185
+ doc.update('# Version 1\n\nInitial content.');
186
+ doc.update('# Version 2\n\nAdded more details.');
187
+ doc.update('# Version 3\n\nFinal version with all content.');
188
+
189
+ console.log('Version history:');
190
+ var history = doc.history();
191
+ for (var i = 0; i < history.length; i++) {
192
+ var v = history[i];
193
+ console.log(' v' + v.version + ': ' + v.hash.substring(0, 16) + '...');
194
+ }
195
+
196
+ console.log('\nRetrieving specific versions:');
197
+ var v1 = doc.getVersion(1);
198
+ var v3 = doc.latest();
199
+ console.log(' v1: "' + v1.content.substring(0, 25) + '..."');
200
+ console.log(' v3: "' + v3.content.substring(0, 25) + '..."');
201
+
202
+ // ===========================================
203
+ // MERKLE TREE
204
+ // ===========================================
205
+
206
+ console.log('\n' + '='.repeat(50));
207
+ console.log('Merkle Tree (Hash Tree):');
208
+ console.log('='.repeat(50) + '\n');
209
+
210
+ function buildMerkleTree(items) {
211
+ if (items.length === 0) return null;
212
+
213
+ // Hash all leaves
214
+ var leaves = items.map(function(item) {
215
+ return backend.hash(item, 32).toString('hex');
216
+ });
217
+
218
+ var tree = [leaves];
219
+
220
+ // Build tree bottom-up
221
+ while (leaves.length > 1) {
222
+ var level = [];
223
+ for (var i = 0; i < leaves.length; i += 2) {
224
+ var left = leaves[i];
225
+ var right = leaves[i + 1] || left; // Duplicate last if odd
226
+ var combined = backend.hash(left + right, 32).toString('hex');
227
+ level.push(combined);
228
+ }
229
+ tree.push(level);
230
+ leaves = level;
231
+ }
232
+
233
+ return {
234
+ root: leaves[0],
235
+ tree: tree
236
+ };
237
+ }
238
+
239
+ var dataBlocks = ['Block A', 'Block B', 'Block C', 'Block D'];
240
+ var merkle = buildMerkleTree(dataBlocks);
241
+
242
+ console.log('Data blocks: ' + dataBlocks.join(', '));
243
+ console.log('\nMerkle Tree:');
244
+ console.log(' Root: ' + merkle.root.substring(0, 32) + '...');
245
+ console.log(' Levels: ' + merkle.tree.length);
246
+
247
+ for (var level = merkle.tree.length - 1; level >= 0; level--) {
248
+ var indent = ' '.repeat(merkle.tree.length - level);
249
+ console.log(indent + 'Level ' + level + ': ' + merkle.tree[level].length + ' nodes');
250
+ }
251
+
252
+ // ===========================================
253
+ // KEY TAKEAWAYS
254
+ // ===========================================
255
+
256
+ console.log('\n' + '='.repeat(50));
257
+ console.log('KEY TAKEAWAYS:');
258
+ console.log('1. Hash of content becomes its address');
259
+ console.log('2. Identical content always has same address');
260
+ console.log('3. Automatic deduplication saves storage');
261
+ console.log('4. Versions can coexist with shared content');
262
+ console.log('5. Merkle trees enable efficient verification');
263
+ console.log('6. Used in Git, IPFS, blockchains, and more');
@@ -0,0 +1,99 @@
1
+ # Cryptographic Examples
2
+
3
+ This directory contains examples demonstrating TinyAleph's cryptographic capabilities.
4
+
5
+ ## Examples
6
+
7
+ ### 01-password-hash.js
8
+ **Password Hashing** - Securely hash passwords with salt support and timing attack resistance.
9
+
10
+ ```bash
11
+ node examples/crypto/01-password-hash.js
12
+ ```
13
+
14
+ ### 02-key-derivation.js
15
+ **Key Derivation** - Derive strong cryptographic keys from passwords using configurable work factor.
16
+
17
+ ```bash
18
+ node examples/crypto/02-key-derivation.js
19
+ ```
20
+
21
+ ### 03-hmac.js
22
+ **HMAC (Message Authentication)** - Create and verify message authentication codes for API signing and webhooks.
23
+
24
+ ```bash
25
+ node examples/crypto/03-hmac.js
26
+ ```
27
+
28
+ ### 04-file-integrity.js
29
+ **File Integrity** - Verify file integrity using cryptographic hashes and manifest files.
30
+
31
+ ```bash
32
+ node examples/crypto/04-file-integrity.js
33
+ ```
34
+
35
+ ### 05-content-hash.js
36
+ **Content-Addressable Storage** - Use content hashes as addresses for automatic deduplication.
37
+
38
+ ```bash
39
+ node examples/crypto/05-content-hash.js
40
+ ```
41
+
42
+ ## Key Concepts
43
+
44
+ ### Cryptographic Hashing
45
+ One-way functions that produce fixed-size output from any input:
46
+ - Deterministic: same input always produces same output
47
+ - One-way: cannot reverse to get original input
48
+ - Collision-resistant: hard to find two inputs with same output
49
+ - Avalanche effect: small input changes cause large output changes
50
+
51
+ ### Key Derivation
52
+ Creating strong cryptographic keys from potentially weak passwords:
53
+ - Uses salt to prevent rainbow table attacks
54
+ - Configurable iterations (work factor) for security/performance tradeoff
55
+ - Produces keys of specified length for various algorithms
56
+
57
+ ### HMAC
58
+ Combining a secret key with a message for authentication:
59
+ - Verifies message integrity (not tampered)
60
+ - Verifies message authenticity (from expected sender)
61
+ - Uses a shared secret key known only to trusted parties
62
+
63
+ ### Content Addressing
64
+ Using the hash of content as its address:
65
+ - Identical content always has the same address
66
+ - Enables automatic deduplication
67
+ - Used in Git, IPFS, blockchains, and more
68
+
69
+ ## Usage Pattern
70
+
71
+ ```javascript
72
+ const { CryptographicBackend } = require('../../modular');
73
+
74
+ // Create backend
75
+ const backend = new CryptographicBackend({ dimension: 32 });
76
+
77
+ // Hash data
78
+ const hash = backend.hash('input data', 32);
79
+ console.log(hash.toString('hex'));
80
+
81
+ // Derive key
82
+ const key = backend.deriveKey('password', 'salt', 32, 10000);
83
+ console.log(key.toString('hex'));
84
+ ```
85
+
86
+ ## Security Considerations
87
+
88
+ 1. **Salt passwords** - Always use unique salts per user/purpose
89
+ 2. **Constant-time comparison** - Prevent timing attacks when verifying
90
+ 3. **Increase iterations** - Higher work factor = harder to brute force
91
+ 4. **Keep keys secret** - Never expose secret keys in logs or responses
92
+ 5. **Use appropriate key lengths** - 256 bits (32 bytes) for modern security
93
+
94
+ ## Next Steps
95
+
96
+ After understanding cryptographic operations, explore:
97
+ - `../semantic/` - Semantic text processing
98
+ - `../scientific/` - Quantum computing simulation
99
+ - `../apps/` - Full application examples
@@ -0,0 +1,223 @@
1
+ /**
2
+ * TinyAleph Modular Demo
3
+ *
4
+ * Demonstrates the three backend types:
5
+ * 1. Semantic - Natural language processing
6
+ * 2. Cryptographic - Hashing and key derivation
7
+ * 3. Scientific - Quantum simulation
8
+ */
9
+
10
+ const {
11
+ createEngine,
12
+ SemanticBackend,
13
+ CryptographicBackend,
14
+ ScientificBackend,
15
+ AlephEngine,
16
+ hash,
17
+ deriveKey
18
+ } = require('../modular');
19
+
20
+ console.log('╔═══════════════════════════════════════════════════════════════╗');
21
+ console.log('║ TinyAleph Modular Architecture Demo ║');
22
+ console.log('╚═══════════════════════════════════════════════════════════════╝\n');
23
+
24
+ // ============================================
25
+ // 1. SEMANTIC COMPUTING
26
+ // ============================================
27
+ console.log('┌───────────────────────────────────────────────────────────────┐');
28
+ console.log('│ SEMANTIC BACKEND - Natural Language Understanding │');
29
+ console.log('└───────────────────────────────────────────────────────────────┘\n');
30
+
31
+ const semanticConfig = {
32
+ dimension: 16,
33
+ vocabulary: {
34
+ 'love': [2, 3, 5],
35
+ 'truth': [7, 11, 13],
36
+ 'wisdom': [2, 7, 11],
37
+ 'knowledge': [3, 5, 7],
38
+ 'beauty': [2, 5, 11],
39
+ 'justice': [3, 7, 13],
40
+ 'freedom': [5, 11, 17],
41
+ 'peace': [2, 3, 7]
42
+ },
43
+ ontology: {
44
+ 2: 'existence',
45
+ 3: 'unity',
46
+ 5: 'form',
47
+ 7: 'logos',
48
+ 11: 'psyche',
49
+ 13: 'telos',
50
+ 17: 'dynamis'
51
+ },
52
+ transforms: [
53
+ { n: 'synthesis', q: [2, 3], r: [5] },
54
+ { n: 'analysis', q: [5], r: [2, 3] },
55
+ { n: 'transcend', q: [2, 3, 5], r: [7, 11] }
56
+ ]
57
+ };
58
+
59
+ const semanticEngine = createEngine('semantic', semanticConfig);
60
+
61
+ console.log('Processing: "love and truth lead to wisdom"\n');
62
+ const semanticResult = semanticEngine.run('love and truth lead to wisdom');
63
+
64
+ console.log(` Input primes: [${semanticResult.inputPrimes.slice(0, 8).join(', ')}...]`);
65
+ console.log(` Output: "${semanticResult.output}"`);
66
+ console.log(` Entropy: ${semanticResult.entropy.toFixed(3)}`);
67
+ console.log(` Coherence: ${semanticResult.coherence.toFixed(3)}`);
68
+ console.log(` Stability: ${semanticResult.stability}`);
69
+
70
+ if (semanticResult.steps.length > 0) {
71
+ console.log('\n Reasoning steps:');
72
+ for (const step of semanticResult.steps) {
73
+ console.log(` ${step.step}. ${step.transform} (ΔH = -${step.entropyDrop.toFixed(3)})`);
74
+ }
75
+ }
76
+
77
+ // ============================================
78
+ // 2. CRYPTOGRAPHIC APPLICATIONS
79
+ // ============================================
80
+ console.log('\n┌───────────────────────────────────────────────────────────────┐');
81
+ console.log('│ CRYPTOGRAPHIC BACKEND - Hashing & Key Derivation │');
82
+ console.log('└───────────────────────────────────────────────────────────────┘\n');
83
+
84
+ const cryptoBackend = new CryptographicBackend({ dimension: 32 });
85
+
86
+ // Hashing demonstration
87
+ console.log('Hashing demonstration:');
88
+ const message1 = 'Hello, World!';
89
+ const message2 = 'Hello, World?';
90
+
91
+ const hash1 = cryptoBackend.hash(message1);
92
+ const hash2 = cryptoBackend.hash(message2);
93
+
94
+ console.log(` Input 1: "${message1}"`);
95
+ console.log(` Hash 1: ${hash1.toString('hex').slice(0, 32)}...`);
96
+ console.log(` Input 2: "${message2}"`);
97
+ console.log(` Hash 2: ${hash2.toString('hex').slice(0, 32)}...`);
98
+ console.log(` Different: ${!hash1.equals(hash2)}`);
99
+
100
+ // Key derivation
101
+ console.log('\nKey derivation (PBKDF-like):');
102
+ const password = 'my-secret-password';
103
+ const salt = 'random-salt-value';
104
+ const key = cryptoBackend.deriveKey(password, salt, 32, 1000);
105
+ console.log(` Password: "${password}"`);
106
+ console.log(` Salt: "${salt}"`);
107
+ console.log(` Key: ${key.toString('hex').slice(0, 32)}...`);
108
+
109
+ // HMAC
110
+ console.log('\nHMAC computation:');
111
+ const hmacKey = 'secret-key';
112
+ const hmacMsg = 'authenticate this message';
113
+ const hmac = cryptoBackend.hmac(hmacKey, hmacMsg);
114
+ console.log(` Key: "${hmacKey}"`);
115
+ console.log(` Message: "${hmacMsg}"`);
116
+ console.log(` HMAC: ${hmac.toString('hex').slice(0, 32)}...`);
117
+
118
+ // ============================================
119
+ // 3. SCIENTIFIC COMPUTING
120
+ // ============================================
121
+ console.log('\n┌───────────────────────────────────────────────────────────────┐');
122
+ console.log('│ SCIENTIFIC BACKEND - Quantum Simulation │');
123
+ console.log('└───────────────────────────────────────────────────────────────┘\n');
124
+
125
+ const scientificBackend = new ScientificBackend({ dimension: 16 });
126
+
127
+ // Quantum state manipulation
128
+ console.log('Quantum state encoding:');
129
+ console.log(` |0⟩ encodes to: [${scientificBackend.encode('|0⟩').join(', ')}]`);
130
+ console.log(` |1⟩ encodes to: [${scientificBackend.encode('|1⟩').join(', ')}]`);
131
+ console.log(` |+⟩ encodes to: [${scientificBackend.encode('|+⟩').join(', ')}]`);
132
+ console.log(` |Φ+⟩ (Bell) encodes to: [${scientificBackend.createEntangledPair('Φ+').join(', ')}]`);
133
+
134
+ // Quantum gates
135
+ console.log('\nQuantum gate application:');
136
+ const qubit0 = [2]; // |0⟩
137
+ console.log(` Initial: |0⟩ = [${qubit0.join(', ')}]`);
138
+
139
+ const afterX = scientificBackend.applyGate(qubit0, 'X');
140
+ console.log(` After X gate: [${afterX.join(', ')}] → ${scientificBackend.decode(afterX)}`);
141
+
142
+ const afterH = scientificBackend.applyGate(qubit0, 'H');
143
+ console.log(` After H gate: [${afterH.join(', ')}] → ${scientificBackend.decode(afterH)}`);
144
+
145
+ // Measurement
146
+ console.log('\nQuantum measurement (10 samples from |+⟩ state):');
147
+ const plusState = scientificBackend.primesToState([2, 3]);
148
+ const outcomes = { '|0⟩': 0, '|1⟩': 0 };
149
+ for (let i = 0; i < 10; i++) {
150
+ const result = scientificBackend.measure(plusState);
151
+ outcomes[result.state]++;
152
+ }
153
+ console.log(` |0⟩ outcomes: ${outcomes['|0⟩']}`);
154
+ console.log(` |1⟩ outcomes: ${outcomes['|1⟩']}`);
155
+
156
+ // Particle interaction
157
+ console.log('\nParticle interaction simulation:');
158
+ const electron = [11]; // electron prime
159
+ const positron = [13]; // positron prime
160
+ const interaction = scientificBackend.interact(electron, positron, 'electromagnetic');
161
+ console.log(` Particles: electron [${electron}] + positron [${positron}]`);
162
+ console.log(` Interaction: ${interaction.interaction}`);
163
+ console.log(` Conserved quantity: ${interaction.conserved}`);
164
+
165
+ // ============================================
166
+ // 4. BACKEND SWITCHING AT RUNTIME
167
+ // ============================================
168
+ console.log('\n┌───────────────────────────────────────────────────────────────┐');
169
+ console.log('│ RUNTIME BACKEND SWITCHING │');
170
+ console.log('└───────────────────────────────────────────────────────────────┘\n');
171
+
172
+ const engine = createEngine('semantic', semanticConfig);
173
+ console.log(`Starting backend: ${engine.getBackendInfo().name}`);
174
+
175
+ engine.setBackend(new CryptographicBackend({ dimension: 32 }));
176
+ console.log(`Switched to: ${engine.getBackendInfo().name}`);
177
+
178
+ engine.setBackend(new ScientificBackend({ dimension: 16 }));
179
+ console.log(`Switched to: ${engine.getBackendInfo().name}`);
180
+
181
+ // ============================================
182
+ // 5. PHYSICS ENGINE DEMONSTRATION
183
+ // ============================================
184
+ console.log('\n┌───────────────────────────────────────────────────────────────┐');
185
+ console.log('│ PHYSICS ENGINE - Oscillator Dynamics │');
186
+ console.log('└───────────────────────────────────────────────────────────────┘\n');
187
+
188
+ const physicsEngine = createEngine('semantic', semanticConfig);
189
+ physicsEngine.run('test input to excite oscillators');
190
+
191
+ console.log('Evolving system for 20 time steps:');
192
+ const evolution = physicsEngine.evolve(20);
193
+
194
+ console.log('\n Step | Entropy | Order | Stability');
195
+ console.log(' -----+---------+-------+----------');
196
+ for (let i = 0; i < evolution.length; i += 4) {
197
+ const e = evolution[i];
198
+ console.log(` ${String(e.step).padStart(2)} | ${e.entropy.toFixed(3)} | ${e.orderParameter.toFixed(3)} | ${e.stability}`);
199
+ }
200
+
201
+ const finalState = physicsEngine.getPhysicsState();
202
+ console.log(`\n Final Lyapunov exponent: ${finalState.lyapunov.toFixed(4)}`);
203
+ console.log(` Final coupling strength: ${finalState.coupling.toFixed(3)}`);
204
+ console.log(` Collapse probability: ${finalState.collapseProbability.toFixed(3)}`);
205
+
206
+ // ============================================
207
+ // SUMMARY
208
+ // ============================================
209
+ console.log('\n╔═══════════════════════════════════════════════════════════════╗');
210
+ console.log('║ Demo Complete ║');
211
+ console.log('╠═══════════════════════════════════════════════════════════════╣');
212
+ console.log('║ Backends demonstrated: ║');
213
+ console.log('║ ✓ SemanticBackend - NLP, concept mapping ║');
214
+ console.log('║ ✓ CryptographicBackend - hash, PBKDF, HMAC ║');
215
+ console.log('║ ✓ ScientificBackend - quantum gates, measurement ║');
216
+ console.log('║ ║');
217
+ console.log('║ Features shown: ║');
218
+ console.log('║ ✓ Unified AlephEngine with backend-agnostic API ║');
219
+ console.log('║ ✓ Runtime backend switching ║');
220
+ console.log('║ ✓ Kuramoto oscillator physics simulation ║');
221
+ console.log('║ ✓ Lyapunov stability analysis ║');
222
+ console.log('║ ✓ Entropy-minimizing reasoning ║');
223
+ console.log('╚═══════════════════════════════════════════════════════════════╝\n');