@aleph-ai/tinyaleph 1.0.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 (58) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +278 -0
  3. package/backends/cryptographic/index.js +196 -0
  4. package/backends/index.js +15 -0
  5. package/backends/interface.js +89 -0
  6. package/backends/scientific/index.js +272 -0
  7. package/backends/semantic/index.js +527 -0
  8. package/backends/semantic/surface.js +393 -0
  9. package/backends/semantic/two-layer.js +375 -0
  10. package/core/fano.js +127 -0
  11. package/core/hilbert.js +564 -0
  12. package/core/hypercomplex.js +141 -0
  13. package/core/index.js +133 -0
  14. package/core/llm.js +132 -0
  15. package/core/prime.js +184 -0
  16. package/core/resonance.js +695 -0
  17. package/core/rformer-tf.js +1086 -0
  18. package/core/rformer.js +806 -0
  19. package/core/sieve.js +350 -0
  20. package/data.json +8163 -0
  21. package/docs/EXAMPLES_PLAN.md +293 -0
  22. package/docs/README.md +159 -0
  23. package/docs/design/ALEPH_CHAT_ARCHITECTURE.md +499 -0
  24. package/docs/guide/01-quickstart.md +298 -0
  25. package/docs/guide/02-semantic-computing.md +409 -0
  26. package/docs/guide/03-cryptographic.md +420 -0
  27. package/docs/guide/04-scientific.md +494 -0
  28. package/docs/guide/05-llm-integration.md +568 -0
  29. package/docs/guide/06-advanced.md +996 -0
  30. package/docs/guide/README.md +188 -0
  31. package/docs/reference/01-core.md +695 -0
  32. package/docs/reference/02-physics.md +601 -0
  33. package/docs/reference/03-backends.md +892 -0
  34. package/docs/reference/04-engine.md +632 -0
  35. package/docs/reference/README.md +252 -0
  36. package/docs/theory/01-prime-semantics.md +327 -0
  37. package/docs/theory/02-hypercomplex-algebra.md +421 -0
  38. package/docs/theory/03-phase-synchronization.md +364 -0
  39. package/docs/theory/04-entropy-reasoning.md +348 -0
  40. package/docs/theory/05-non-commutativity.md +402 -0
  41. package/docs/theory/06-two-layer-meaning.md +414 -0
  42. package/docs/theory/07-resonant-field-interface.md +419 -0
  43. package/docs/theory/08-semantic-sieve.md +520 -0
  44. package/docs/theory/09-temporal-emergence.md +298 -0
  45. package/docs/theory/10-quaternionic-memory.md +415 -0
  46. package/docs/theory/README.md +162 -0
  47. package/engine/aleph.js +418 -0
  48. package/engine/index.js +7 -0
  49. package/index.js +23 -0
  50. package/modular.js +254 -0
  51. package/package.json +99 -0
  52. package/physics/collapse.js +95 -0
  53. package/physics/entropy.js +88 -0
  54. package/physics/index.js +65 -0
  55. package/physics/kuramoto.js +91 -0
  56. package/physics/lyapunov.js +80 -0
  57. package/physics/oscillator.js +95 -0
  58. package/types/index.d.ts +575 -0
@@ -0,0 +1,996 @@
1
+ # Advanced Topics
2
+
3
+ This guide covers power-user techniques, customization, and deep integration patterns for Aleph.
4
+
5
+ ## Overview
6
+
7
+ This document is for developers who want to:
8
+
9
+ - Extend Aleph with custom backends
10
+ - Fine-tune oscillator dynamics
11
+ - Implement custom transforms
12
+ - Optimize for specific use cases
13
+ - Understand internal mechanics
14
+
15
+ ---
16
+
17
+ ## Custom Backends
18
+
19
+ ### Backend Architecture
20
+
21
+ All backends extend the base interface:
22
+
23
+ ```javascript
24
+ const { BackendInterface } = require('./backends/interface');
25
+
26
+ class CustomBackend extends BackendInterface {
27
+ constructor(config) {
28
+ super(config);
29
+ // Initialize custom state
30
+ }
31
+
32
+ // Required methods
33
+ encode(input) { /* Convert input to primes */ }
34
+ decode(primes) { /* Convert primes back to output */ }
35
+ process(input) { /* Main processing logic */ }
36
+
37
+ // Optional methods
38
+ learn(item, primes) { /* Add to vocabulary */ }
39
+ validate(input) { /* Validate input format */ }
40
+ }
41
+ ```
42
+
43
+ ### Example: Graph Backend
44
+
45
+ ```javascript
46
+ const { BackendInterface } = require('./backends/interface');
47
+ const { SedenionState } = require('./core/hypercomplex');
48
+
49
+ class GraphBackend extends BackendInterface {
50
+ constructor(config) {
51
+ super(config);
52
+ this.nodes = new Map();
53
+ this.edges = [];
54
+ }
55
+
56
+ // Encode graph structure to primes
57
+ encode(graph) {
58
+ const primes = [];
59
+
60
+ // Encode nodes
61
+ for (const node of graph.nodes) {
62
+ const nodePrime = this.nodeToProme(node);
63
+ primes.push(nodePrime);
64
+ this.nodes.set(node.id, nodePrime);
65
+ }
66
+
67
+ // Encode edges as prime products
68
+ for (const edge of graph.edges) {
69
+ const edgePrime = this.nodes.get(edge.source) * this.nodes.get(edge.target);
70
+ primes.push(edgePrime);
71
+ this.edges.push({ edge, prime: edgePrime });
72
+ }
73
+
74
+ return primes;
75
+ }
76
+
77
+ // Decode primes back to graph
78
+ decode(primes) {
79
+ // Reconstruct graph from prime factorization
80
+ const nodes = [];
81
+ const edges = [];
82
+
83
+ for (const prime of primes) {
84
+ if (this.isPureNode(prime)) {
85
+ nodes.push(this.primeToNode(prime));
86
+ } else {
87
+ // Factor composite to find edge endpoints
88
+ const factors = this.factor(prime);
89
+ edges.push({
90
+ source: this.primeToNodeId(factors[0]),
91
+ target: this.primeToNodeId(factors[1])
92
+ });
93
+ }
94
+ }
95
+
96
+ return { nodes, edges };
97
+ }
98
+
99
+ // Process graph queries
100
+ process(query) {
101
+ const primes = this.encode(query.graph);
102
+ const state = this.primesToState(primes);
103
+
104
+ // Apply graph-specific transforms
105
+ const result = this.applyGraphTransforms(state, query.operation);
106
+
107
+ return {
108
+ state: result,
109
+ entropy: result.entropy(),
110
+ graph: this.stateToGraph(result)
111
+ };
112
+ }
113
+
114
+ nodeToProme(node) {
115
+ // Map node properties to prime
116
+ return this.config.nodePrimes[node.type] || 2;
117
+ }
118
+
119
+ isPureNode(prime) {
120
+ return this.primeCheck(prime);
121
+ }
122
+
123
+ primeToNode(prime) {
124
+ // Reverse lookup
125
+ for (const [type, p] of Object.entries(this.config.nodePrimes)) {
126
+ if (p === prime) return { type };
127
+ }
128
+ return null;
129
+ }
130
+ }
131
+
132
+ module.exports = { GraphBackend };
133
+ ```
134
+
135
+ ### Registering Custom Backends
136
+
137
+ ```javascript
138
+ const { registerBackend, createEngine } = require('./modular');
139
+ const { GraphBackend } = require('./my-graph-backend');
140
+
141
+ // Register the backend
142
+ registerBackend('graph', GraphBackend);
143
+
144
+ // Now usable via createEngine
145
+ const engine = createEngine('graph', {
146
+ nodePrimes: {
147
+ person: 2,
148
+ company: 3,
149
+ location: 5
150
+ }
151
+ });
152
+
153
+ const result = engine.run({
154
+ nodes: [
155
+ { id: 1, type: 'person' },
156
+ { id: 2, type: 'company' }
157
+ ],
158
+ edges: [
159
+ { source: 1, target: 2 }
160
+ ]
161
+ });
162
+ ```
163
+
164
+ ---
165
+
166
+ ## Oscillator Customization
167
+
168
+ ### Custom Oscillator Types
169
+
170
+ ```javascript
171
+ const { createOscillator } = require('./physics/oscillator');
172
+
173
+ // Standard oscillator
174
+ const basic = createOscillator({
175
+ frequency: 1.0,
176
+ phase: 0,
177
+ amplitude: 1.0
178
+ });
179
+
180
+ // Damped oscillator
181
+ const damped = createOscillator({
182
+ frequency: 1.0,
183
+ phase: 0,
184
+ amplitude: 1.0,
185
+ damping: 0.1 // Exponential decay
186
+ });
187
+
188
+ // Driven oscillator
189
+ const driven = createOscillator({
190
+ frequency: 1.0,
191
+ phase: 0,
192
+ amplitude: 1.0,
193
+ driving: {
194
+ frequency: 1.2, // External driving frequency
195
+ amplitude: 0.5
196
+ }
197
+ });
198
+ ```
199
+
200
+ ### Custom Coupling Functions
201
+
202
+ ```javascript
203
+ const { setCouplingFunction } = require('./physics/kuramoto');
204
+
205
+ // Default Kuramoto coupling: sin(θⱼ - θᵢ)
206
+ // Custom: weighted by state similarity
207
+
208
+ function semanticCoupling(oscillatorI, oscillatorJ, globalState) {
209
+ // Base Kuramoto term
210
+ const kuramotoTerm = Math.sin(oscillatorJ.phase - oscillatorI.phase);
211
+
212
+ // Weight by semantic similarity
213
+ const similarity = oscillatorI.state.coherence(oscillatorJ.state);
214
+
215
+ return kuramotoTerm * similarity;
216
+ }
217
+
218
+ setCouplingFunction(semanticCoupling);
219
+ ```
220
+
221
+ ### Oscillator Networks
222
+
223
+ ```javascript
224
+ class OscillatorNetwork {
225
+ constructor(size, topology) {
226
+ this.oscillators = [];
227
+ this.connections = [];
228
+
229
+ // Create oscillators
230
+ for (let i = 0; i < size; i++) {
231
+ this.oscillators.push(createOscillator({
232
+ frequency: 1.0 + 0.1 * Math.random(),
233
+ phase: Math.random() * 2 * Math.PI,
234
+ amplitude: 1.0
235
+ }));
236
+ }
237
+
238
+ // Create connection topology
239
+ this.buildTopology(topology);
240
+ }
241
+
242
+ buildTopology(type) {
243
+ switch (type) {
244
+ case 'full':
245
+ // All-to-all connections
246
+ for (let i = 0; i < this.oscillators.length; i++) {
247
+ for (let j = i + 1; j < this.oscillators.length; j++) {
248
+ this.connections.push([i, j, 1.0]);
249
+ }
250
+ }
251
+ break;
252
+
253
+ case 'ring':
254
+ // Nearest-neighbor ring
255
+ for (let i = 0; i < this.oscillators.length; i++) {
256
+ const j = (i + 1) % this.oscillators.length;
257
+ this.connections.push([i, j, 1.0]);
258
+ }
259
+ break;
260
+
261
+ case 'small-world':
262
+ // Ring + random long-range connections
263
+ this.buildTopology('ring');
264
+ const extraConnections = Math.floor(this.oscillators.length * 0.1);
265
+ for (let k = 0; k < extraConnections; k++) {
266
+ const i = Math.floor(Math.random() * this.oscillators.length);
267
+ const j = Math.floor(Math.random() * this.oscillators.length);
268
+ if (i !== j) this.connections.push([i, j, 0.5]);
269
+ }
270
+ break;
271
+ }
272
+ }
273
+
274
+ step(dt) {
275
+ const coupling = 0.1;
276
+
277
+ // Calculate phase updates
278
+ const updates = this.oscillators.map(() => 0);
279
+
280
+ for (const [i, j, weight] of this.connections) {
281
+ const interaction = Math.sin(
282
+ this.oscillators[j].phase - this.oscillators[i].phase
283
+ ) * weight;
284
+
285
+ updates[i] += coupling * interaction;
286
+ updates[j] -= coupling * interaction;
287
+ }
288
+
289
+ // Apply updates
290
+ for (let i = 0; i < this.oscillators.length; i++) {
291
+ this.oscillators[i].phase += (
292
+ this.oscillators[i].frequency + updates[i]
293
+ ) * dt;
294
+ }
295
+ }
296
+
297
+ getOrderParameter() {
298
+ // Kuramoto order parameter: R = |⟨e^(iθ)⟩|
299
+ let sumCos = 0, sumSin = 0;
300
+ for (const osc of this.oscillators) {
301
+ sumCos += Math.cos(osc.phase);
302
+ sumSin += Math.sin(osc.phase);
303
+ }
304
+ const n = this.oscillators.length;
305
+ return Math.sqrt(sumCos*sumCos + sumSin*sumSin) / n;
306
+ }
307
+ }
308
+ ```
309
+
310
+ ---
311
+
312
+ ## Custom Transforms
313
+
314
+ ### Transform Structure
315
+
316
+ ```javascript
317
+ const transform = {
318
+ n: 'transform_name', // Unique name
319
+ q: [2, 3, 5], // Query primes (to match)
320
+ r: [7, 11], // Result primes (replacement)
321
+ priority: 1, // Higher = applied first
322
+ condition: (state) => true, // Optional: when to apply
323
+ postProcess: (result) => result // Optional: after application
324
+ };
325
+ ```
326
+
327
+ ### Implementing Custom Transforms
328
+
329
+ ```javascript
330
+ class TransformLibrary {
331
+ constructor() {
332
+ this.transforms = [];
333
+ }
334
+
335
+ add(transform) {
336
+ this.transforms.push({
337
+ ...transform,
338
+ priority: transform.priority || 0
339
+ });
340
+ this.transforms.sort((a, b) => b.priority - a.priority);
341
+ }
342
+
343
+ apply(primes, state) {
344
+ let current = [...primes];
345
+ const applied = [];
346
+
347
+ for (const transform of this.transforms) {
348
+ // Check condition
349
+ if (transform.condition && !transform.condition(state)) {
350
+ continue;
351
+ }
352
+
353
+ // Check if query matches
354
+ if (this.matches(current, transform.q)) {
355
+ // Apply transformation
356
+ current = this.substitute(current, transform.q, transform.r);
357
+ applied.push(transform.n);
358
+
359
+ // Post-process
360
+ if (transform.postProcess) {
361
+ current = transform.postProcess(current);
362
+ }
363
+ }
364
+ }
365
+
366
+ return { primes: current, applied };
367
+ }
368
+
369
+ matches(primes, query) {
370
+ return query.every(q => primes.includes(q));
371
+ }
372
+
373
+ substitute(primes, query, result) {
374
+ const remaining = [...primes];
375
+
376
+ // Remove query primes
377
+ for (const q of query) {
378
+ const idx = remaining.indexOf(q);
379
+ if (idx >= 0) remaining.splice(idx, 1);
380
+ }
381
+
382
+ // Add result primes
383
+ return [...remaining, ...result];
384
+ }
385
+ }
386
+
387
+ // Usage
388
+ const library = new TransformLibrary();
389
+
390
+ library.add({
391
+ n: 'question_resolution',
392
+ q: [17, 19], // uncertainty + seeking
393
+ r: [23], // understanding
394
+ priority: 10
395
+ });
396
+
397
+ library.add({
398
+ n: 'contradiction_collapse',
399
+ q: [29, 31], // assertion + negation
400
+ r: [37], // paradox
401
+ priority: 20,
402
+ condition: (state) => state.entropy() > 0.5
403
+ });
404
+ ```
405
+
406
+ ### Transform Chains
407
+
408
+ ```javascript
409
+ class TransformChain {
410
+ constructor(transforms) {
411
+ this.transforms = transforms;
412
+ }
413
+
414
+ run(input, backend) {
415
+ let primes = backend.encode(input);
416
+ let state = backend.primesToState(primes);
417
+ const trace = [];
418
+
419
+ for (const transform of this.transforms) {
420
+ const beforeEntropy = state.entropy();
421
+
422
+ const result = this.applyTransform(primes, state, transform);
423
+ primes = result.primes;
424
+ state = backend.primesToState(primes);
425
+
426
+ const afterEntropy = state.entropy();
427
+
428
+ trace.push({
429
+ transform: transform.n,
430
+ entropyBefore: beforeEntropy,
431
+ entropyAfter: afterEntropy,
432
+ drop: beforeEntropy - afterEntropy
433
+ });
434
+
435
+ // Stop if entropy is minimal
436
+ if (afterEntropy < 0.1) break;
437
+ }
438
+
439
+ return {
440
+ primes,
441
+ state,
442
+ trace,
443
+ output: backend.decode(primes)
444
+ };
445
+ }
446
+
447
+ applyTransform(primes, state, transform) {
448
+ // Implementation
449
+ return { primes };
450
+ }
451
+ }
452
+ ```
453
+
454
+ ---
455
+
456
+ ## Performance Optimization
457
+
458
+ ### State Pooling
459
+
460
+ ```javascript
461
+ class StatePool {
462
+ constructor(dimension, poolSize = 100) {
463
+ this.dimension = dimension;
464
+ this.available = [];
465
+ this.inUse = new Set();
466
+
467
+ // Pre-allocate states
468
+ for (let i = 0; i < poolSize; i++) {
469
+ this.available.push(this.createState());
470
+ }
471
+ }
472
+
473
+ createState() {
474
+ return new Float64Array(this.dimension);
475
+ }
476
+
477
+ acquire() {
478
+ if (this.available.length === 0) {
479
+ // Expand pool
480
+ this.available.push(this.createState());
481
+ }
482
+
483
+ const state = this.available.pop();
484
+ this.inUse.add(state);
485
+ return state;
486
+ }
487
+
488
+ release(state) {
489
+ if (this.inUse.has(state)) {
490
+ this.inUse.delete(state);
491
+ state.fill(0); // Reset
492
+ this.available.push(state);
493
+ }
494
+ }
495
+
496
+ get stats() {
497
+ return {
498
+ available: this.available.length,
499
+ inUse: this.inUse.size,
500
+ total: this.available.length + this.inUse.size
501
+ };
502
+ }
503
+ }
504
+
505
+ // Usage
506
+ const pool = new StatePool(16, 1000);
507
+
508
+ function processWithPool(input, backend, pool) {
509
+ const components = pool.acquire();
510
+
511
+ try {
512
+ // Use components array directly
513
+ const primes = backend.encode(input);
514
+ backend.primesToComponents(primes, components);
515
+
516
+ // Process...
517
+ const entropy = calculateEntropy(components);
518
+
519
+ return { entropy };
520
+ } finally {
521
+ pool.release(components);
522
+ }
523
+ }
524
+ ```
525
+
526
+ ### Batch Processing
527
+
528
+ ```javascript
529
+ class BatchProcessor {
530
+ constructor(backend, batchSize = 100) {
531
+ this.backend = backend;
532
+ this.batchSize = batchSize;
533
+ this.queue = [];
534
+ this.results = new Map();
535
+ }
536
+
537
+ add(id, input) {
538
+ this.queue.push({ id, input });
539
+
540
+ if (this.queue.length >= this.batchSize) {
541
+ return this.flush();
542
+ }
543
+
544
+ return null;
545
+ }
546
+
547
+ async flush() {
548
+ if (this.queue.length === 0) return;
549
+
550
+ const batch = this.queue.splice(0, this.batchSize);
551
+
552
+ // Process all at once
553
+ const primesBatch = batch.map(item => this.backend.encode(item.input));
554
+ const statesBatch = this.backend.batchPrimesToStates(primesBatch);
555
+
556
+ for (let i = 0; i < batch.length; i++) {
557
+ this.results.set(batch[i].id, {
558
+ primes: primesBatch[i],
559
+ state: statesBatch[i],
560
+ entropy: statesBatch[i].entropy()
561
+ });
562
+ }
563
+
564
+ return batch.map(item => this.results.get(item.id));
565
+ }
566
+
567
+ get(id) {
568
+ return this.results.get(id);
569
+ }
570
+ }
571
+ ```
572
+
573
+ ### Caching Strategies
574
+
575
+ ```javascript
576
+ class LRUCache {
577
+ constructor(maxSize = 1000) {
578
+ this.maxSize = maxSize;
579
+ this.cache = new Map();
580
+ }
581
+
582
+ get(key) {
583
+ if (!this.cache.has(key)) return null;
584
+
585
+ // Move to end (most recently used)
586
+ const value = this.cache.get(key);
587
+ this.cache.delete(key);
588
+ this.cache.set(key, value);
589
+
590
+ return value;
591
+ }
592
+
593
+ set(key, value) {
594
+ if (this.cache.has(key)) {
595
+ this.cache.delete(key);
596
+ } else if (this.cache.size >= this.maxSize) {
597
+ // Remove least recently used
598
+ const oldest = this.cache.keys().next().value;
599
+ this.cache.delete(oldest);
600
+ }
601
+
602
+ this.cache.set(key, value);
603
+ }
604
+ }
605
+
606
+ // Multi-level cache
607
+ class HierarchicalCache {
608
+ constructor() {
609
+ this.l1 = new Map(); // Hot: 100 items
610
+ this.l2 = new LRUCache(1000); // Warm: 1000 items
611
+ // L3 could be disk/redis
612
+ }
613
+
614
+ get(key) {
615
+ // Check L1
616
+ if (this.l1.has(key)) {
617
+ return this.l1.get(key);
618
+ }
619
+
620
+ // Check L2
621
+ const l2Result = this.l2.get(key);
622
+ if (l2Result) {
623
+ // Promote to L1
624
+ if (this.l1.size < 100) {
625
+ this.l1.set(key, l2Result);
626
+ }
627
+ return l2Result;
628
+ }
629
+
630
+ return null;
631
+ }
632
+
633
+ set(key, value) {
634
+ this.l1.set(key, value);
635
+ this.l2.set(key, value);
636
+
637
+ // Evict from L1 if too large
638
+ if (this.l1.size > 100) {
639
+ const oldest = this.l1.keys().next().value;
640
+ this.l1.delete(oldest);
641
+ }
642
+ }
643
+ }
644
+ ```
645
+
646
+ ---
647
+
648
+ ## Debugging and Profiling
649
+
650
+ ### State Inspector
651
+
652
+ ```javascript
653
+ class StateInspector {
654
+ static inspect(state) {
655
+ return {
656
+ dimension: state.dimension,
657
+ norm: state.norm(),
658
+ entropy: state.entropy(),
659
+ components: state.components.map(c => c.toFixed(4)),
660
+
661
+ // Analyze structure
662
+ dominantAxis: this.findDominantAxis(state),
663
+ zeroCount: state.components.filter(c => Math.abs(c) < 1e-10).length,
664
+ maxComponent: Math.max(...state.components.map(Math.abs)),
665
+ minNonZero: Math.min(...state.components.filter(c => c !== 0).map(Math.abs))
666
+ };
667
+ }
668
+
669
+ static findDominantAxis(state) {
670
+ let maxIdx = 0;
671
+ let maxVal = 0;
672
+
673
+ for (let i = 0; i < state.components.length; i++) {
674
+ const absVal = Math.abs(state.components[i]);
675
+ if (absVal > maxVal) {
676
+ maxVal = absVal;
677
+ maxIdx = i;
678
+ }
679
+ }
680
+
681
+ return { index: maxIdx, value: state.components[maxIdx] };
682
+ }
683
+
684
+ static compare(state1, state2) {
685
+ return {
686
+ coherence: state1.coherence(state2),
687
+ normDiff: Math.abs(state1.norm() - state2.norm()),
688
+ entropyDiff: Math.abs(state1.entropy() - state2.entropy()),
689
+ componentDiffs: state1.components.map((c, i) =>
690
+ Math.abs(c - state2.components[i])
691
+ ),
692
+ isZeroDivisor: state1.isZeroDivisorWith(state2)
693
+ };
694
+ }
695
+ }
696
+ ```
697
+
698
+ ### Profiling Wrapper
699
+
700
+ ```javascript
701
+ class Profiler {
702
+ constructor() {
703
+ this.timings = new Map();
704
+ this.counts = new Map();
705
+ }
706
+
707
+ wrap(name, fn) {
708
+ return (...args) => {
709
+ const start = performance.now();
710
+ const result = fn(...args);
711
+ const elapsed = performance.now() - start;
712
+
713
+ if (!this.timings.has(name)) {
714
+ this.timings.set(name, []);
715
+ this.counts.set(name, 0);
716
+ }
717
+
718
+ this.timings.get(name).push(elapsed);
719
+ this.counts.set(name, this.counts.get(name) + 1);
720
+
721
+ return result;
722
+ };
723
+ }
724
+
725
+ report() {
726
+ const report = {};
727
+
728
+ for (const [name, timings] of this.timings) {
729
+ const sum = timings.reduce((a, b) => a + b, 0);
730
+ report[name] = {
731
+ calls: this.counts.get(name),
732
+ totalMs: sum.toFixed(2),
733
+ avgMs: (sum / timings.length).toFixed(4),
734
+ minMs: Math.min(...timings).toFixed(4),
735
+ maxMs: Math.max(...timings).toFixed(4)
736
+ };
737
+ }
738
+
739
+ return report;
740
+ }
741
+
742
+ reset() {
743
+ this.timings.clear();
744
+ this.counts.clear();
745
+ }
746
+ }
747
+
748
+ // Usage
749
+ const profiler = new Profiler();
750
+
751
+ const backend = new SemanticBackend(config);
752
+ backend.encode = profiler.wrap('encode', backend.encode.bind(backend));
753
+ backend.decode = profiler.wrap('decode', backend.decode.bind(backend));
754
+ backend.primesToState = profiler.wrap('primesToState', backend.primesToState.bind(backend));
755
+
756
+ // After running...
757
+ console.log(profiler.report());
758
+ ```
759
+
760
+ ### Entropy Tracer
761
+
762
+ ```javascript
763
+ class EntropyTracer {
764
+ constructor() {
765
+ this.trace = [];
766
+ this.checkpoints = [];
767
+ }
768
+
769
+ record(label, state) {
770
+ this.trace.push({
771
+ timestamp: Date.now(),
772
+ label,
773
+ entropy: state.entropy(),
774
+ norm: state.norm()
775
+ });
776
+ }
777
+
778
+ checkpoint(name) {
779
+ this.checkpoints.push({
780
+ name,
781
+ timestamp: Date.now(),
782
+ index: this.trace.length
783
+ });
784
+ }
785
+
786
+ analyze() {
787
+ if (this.trace.length < 2) return null;
788
+
789
+ const entropies = this.trace.map(t => t.entropy);
790
+
791
+ return {
792
+ initial: entropies[0],
793
+ final: entropies[entropies.length - 1],
794
+ min: Math.min(...entropies),
795
+ max: Math.max(...entropies),
796
+ totalDrop: entropies[0] - entropies[entropies.length - 1],
797
+ monotonic: this.isMonotonic(entropies),
798
+ spikes: this.findSpikes(entropies),
799
+ checkpoints: this.checkpoints.map(cp => ({
800
+ ...cp,
801
+ entropy: this.trace[cp.index]?.entropy
802
+ }))
803
+ };
804
+ }
805
+
806
+ isMonotonic(values) {
807
+ for (let i = 1; i < values.length; i++) {
808
+ if (values[i] > values[i-1]) return false;
809
+ }
810
+ return true;
811
+ }
812
+
813
+ findSpikes(values) {
814
+ const spikes = [];
815
+ for (let i = 1; i < values.length - 1; i++) {
816
+ if (values[i] > values[i-1] && values[i] > values[i+1]) {
817
+ spikes.push({ index: i, value: values[i] });
818
+ }
819
+ }
820
+ return spikes;
821
+ }
822
+
823
+ visualize() {
824
+ // Simple ASCII visualization
825
+ const width = 60;
826
+ const entropies = this.trace.map(t => t.entropy);
827
+ const max = Math.max(...entropies);
828
+
829
+ console.log('Entropy Trace:');
830
+ console.log('─'.repeat(width + 10));
831
+
832
+ for (let i = 0; i < this.trace.length; i++) {
833
+ const normalized = entropies[i] / max;
834
+ const barLength = Math.round(normalized * width);
835
+ const bar = '█'.repeat(barLength);
836
+ const label = this.trace[i].label.padEnd(10);
837
+ console.log(`${label} │${bar} ${entropies[i].toFixed(4)}`);
838
+ }
839
+
840
+ console.log('─'.repeat(width + 10));
841
+ }
842
+ }
843
+ ```
844
+
845
+ ---
846
+
847
+ ## Integration Patterns
848
+
849
+ ### Event-Driven Processing
850
+
851
+ ```javascript
852
+ const EventEmitter = require('events');
853
+
854
+ class AlephEventEngine extends EventEmitter {
855
+ constructor(backend) {
856
+ super();
857
+ this.backend = backend;
858
+ }
859
+
860
+ process(input) {
861
+ this.emit('start', { input });
862
+
863
+ const primes = this.backend.encode(input);
864
+ this.emit('encoded', { primes });
865
+
866
+ const state = this.backend.primesToState(primes);
867
+ this.emit('state-created', { state, entropy: state.entropy() });
868
+
869
+ let currentState = state;
870
+ let step = 0;
871
+
872
+ while (currentState.entropy() > 0.1) {
873
+ const transform = this.selectTransform(currentState);
874
+ if (!transform) break;
875
+
876
+ const newState = this.applyTransform(currentState, transform);
877
+
878
+ this.emit('transform-applied', {
879
+ step: ++step,
880
+ transform: transform.n,
881
+ entropyBefore: currentState.entropy(),
882
+ entropyAfter: newState.entropy()
883
+ });
884
+
885
+ currentState = newState;
886
+ }
887
+
888
+ const output = this.backend.decode(this.stateToPromes(currentState));
889
+
890
+ this.emit('complete', {
891
+ output,
892
+ steps: step,
893
+ finalEntropy: currentState.entropy()
894
+ });
895
+
896
+ return output;
897
+ }
898
+
899
+ selectTransform(state) {
900
+ // Implementation
901
+ return null;
902
+ }
903
+
904
+ applyTransform(state, transform) {
905
+ // Implementation
906
+ return state;
907
+ }
908
+
909
+ stateToPromes(state) {
910
+ // Implementation
911
+ return [];
912
+ }
913
+ }
914
+
915
+ // Usage
916
+ const engine = new AlephEventEngine(backend);
917
+
918
+ engine.on('start', data => console.log('Starting:', data.input));
919
+ engine.on('transform-applied', data => {
920
+ console.log(`Step ${data.step}: ${data.transform}`);
921
+ console.log(` Entropy: ${data.entropyBefore.toFixed(4)} → ${data.entropyAfter.toFixed(4)}`);
922
+ });
923
+ engine.on('complete', data => console.log('Complete:', data.output));
924
+
925
+ engine.process('What is wisdom?');
926
+ ```
927
+
928
+ ### Middleware Pipeline
929
+
930
+ ```javascript
931
+ class MiddlewarePipeline {
932
+ constructor() {
933
+ this.middleware = [];
934
+ }
935
+
936
+ use(fn) {
937
+ this.middleware.push(fn);
938
+ return this;
939
+ }
940
+
941
+ async process(input, context = {}) {
942
+ let idx = 0;
943
+
944
+ const next = async () => {
945
+ if (idx >= this.middleware.length) return;
946
+
947
+ const middleware = this.middleware[idx++];
948
+ await middleware(context, next);
949
+ };
950
+
951
+ context.input = input;
952
+ context.output = null;
953
+
954
+ await next();
955
+
956
+ return context.output;
957
+ }
958
+ }
959
+
960
+ // Usage
961
+ const pipeline = new MiddlewarePipeline();
962
+
963
+ pipeline.use(async (ctx, next) => {
964
+ console.log('Logging input:', ctx.input);
965
+ await next();
966
+ console.log('Logging output:', ctx.output);
967
+ });
968
+
969
+ pipeline.use(async (ctx, next) => {
970
+ ctx.primes = backend.encode(ctx.input);
971
+ await next();
972
+ });
973
+
974
+ pipeline.use(async (ctx, next) => {
975
+ ctx.state = backend.primesToState(ctx.primes);
976
+ await next();
977
+ });
978
+
979
+ pipeline.use(async (ctx, next) => {
980
+ // Final processing
981
+ ctx.output = {
982
+ primes: ctx.primes,
983
+ entropy: ctx.state.entropy()
984
+ };
985
+ });
986
+
987
+ const result = await pipeline.process('wisdom and truth');
988
+ ```
989
+
990
+ ---
991
+
992
+ ## Next Steps
993
+
994
+ - [Reference: Core Module →](../reference/01-core.md)
995
+ - [Reference: Physics Module →](../reference/02-physics.md)
996
+ - [Theory: All Documents →](../theory/README.md)