minuet 0.4.0

Holographic memory systems built on amari-holographic — the optical table for holographic computing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
// Copyright (C) 2026 Industrial Algebra
// SPDX-License-Identifier: AGPL-3.0-only
//! Integration tests for the optical module.

use super::*;
use amari_holographic::optical::{CodebookConfig, LeeEncoderConfig, OpticalFieldAlgebra};
use std::time::Duration;
use tempfile::tempdir;

fn test_encoder_config() -> LeeEncoderConfig {
    LeeEncoderConfig {
        carrier_frequency: 0.25,
        carrier_angle: 0.0,
        dimensions: (256, 256),
    }
}

fn test_codebook_config() -> CodebookConfig {
    CodebookConfig {
        dimensions: (256, 256),
        base_seed: 12345,
    }
}

#[test]
fn test_symbolic_expression_roundtrip() {
    let expr = SymbolicExpression::bind(
        SymbolicExpression::symbol("AGENT"),
        SymbolicExpression::symbol("John"),
    );

    let json = serde_json::to_string(&expr).unwrap();
    let restored: SymbolicExpression = serde_json::from_str(&json).unwrap();

    assert_eq!(expr, restored);
}

#[test]
fn test_journal_replay_consistency() {
    let mut journal = MemoryJournal::new(test_encoder_config(), test_codebook_config());

    // Record operations
    journal.ops.push(MemoryOp::RegisterSymbol {
        symbol: amari_holographic::optical::SymbolId::new("AGENT"),
        seed: Some(12345),
        timestamp: 1000,
    });
    journal.ops.push(MemoryOp::Store {
        key: SymbolicExpression::symbol("test_key"),
        value: SymbolicExpression::symbol("test_value"),
        strength: 1.0,
        timestamp: 2000,
    });

    let state = journal.replay_to_state();

    assert_eq!(state.associations.len(), 1);
    assert!(state
        .symbol_seeds
        .contains_key(&amari_holographic::optical::SymbolId::new("AGENT")));
}

#[test]
fn test_checkpoint_restore_same_hardware() {
    let dir = tempdir().unwrap();
    let journal_path = dir.path().join("test_journal.bin");

    let hardware = MockOpticalHardware::new(42);
    let config = CheckpointConfig {
        journal_path: journal_path.clone(),
        interval: Duration::from_secs(3600), // Long interval to control checkpointing
        ..Default::default()
    };

    let mut memory = CheckpointedOpticalMemory::new(
        hardware,
        test_encoder_config(),
        test_codebook_config(),
        config.clone(),
    )
    .unwrap();

    // Store some memories
    memory
        .store(
            SymbolicExpression::role_filler("AGENT", "John"),
            SymbolicExpression::role_filler("ACTION", "run"),
        )
        .unwrap();

    memory.checkpoint().unwrap();

    // Simulate restart with same hardware
    drop(memory);
    let same_hardware = MockOpticalHardware::new(42);
    let mut restored = CheckpointedOpticalMemory::restore(same_hardware, config).unwrap();

    // Should retrieve
    let result = restored
        .retrieve(&SymbolicExpression::role_filler("AGENT", "John"))
        .unwrap();

    assert!(result.is_some());
}

#[test]
fn test_checkpoint_restore_different_hardware() {
    let dir = tempdir().unwrap();
    let journal_path = dir.path().join("test_journal.bin");

    let hardware = MockOpticalHardware::new(42);
    let config = CheckpointConfig {
        journal_path: journal_path.clone(),
        interval: Duration::from_secs(3600),
        ..Default::default()
    };

    let mut memory = CheckpointedOpticalMemory::new(
        hardware,
        test_encoder_config(),
        test_codebook_config(),
        config.clone(),
    )
    .unwrap();

    memory
        .store(
            SymbolicExpression::role_filler("AGENT", "John"),
            SymbolicExpression::role_filler("ACTION", "run"),
        )
        .unwrap();

    memory.checkpoint().unwrap();

    // Restart with DIFFERENT hardware
    drop(memory);
    let different_hardware = MockOpticalHardware::new(999); // Different seed = different T
    let mut restored = CheckpointedOpticalMemory::restore(different_hardware, config).unwrap();

    // Should still retrieve (recalibrated to new hardware)
    let result = restored
        .retrieve(&SymbolicExpression::role_filler("AGENT", "John"))
        .unwrap();

    assert!(result.is_some());
}

#[test]
fn test_fingerprint_detects_drift() {
    let mut hardware = MockOpticalHardware::new(42);
    let fingerprint = TMatrixFingerprint::capture(&mut hardware, 5).unwrap();

    // Should be valid immediately
    let validation = fingerprint.validate(&mut hardware).unwrap();
    assert!(matches!(validation, FingerprintValidation::Valid));

    // Simulate significant drift
    hardware.drift_t_matrix(0.5);

    // Should detect drift or different hardware
    let validation = fingerprint.validate(&mut hardware).unwrap();
    assert!(!matches!(validation, FingerprintValidation::Valid));
}

#[test]
fn test_fingerprint_detects_different_hardware() {
    let mut hardware1 = MockOpticalHardware::new(42);
    let fingerprint = TMatrixFingerprint::capture(&mut hardware1, 5).unwrap();

    // Validate against different hardware
    let mut hardware2 = MockOpticalHardware::new(999);
    let validation = fingerprint.validate(&mut hardware2).unwrap();

    assert!(matches!(
        validation,
        FingerprintValidation::DifferentHardware { .. }
    ));
}

#[test]
fn test_store_retrieve_basic() {
    let dir = tempdir().unwrap();
    let journal_path = dir.path().join("test_journal.bin");

    let hardware = MockOpticalHardware::new(42);
    let config = CheckpointConfig {
        journal_path,
        interval: Duration::from_secs(3600),
        ..Default::default()
    };

    let mut memory = CheckpointedOpticalMemory::new(
        hardware,
        test_encoder_config(),
        test_codebook_config(),
        config,
    )
    .unwrap();

    // Store
    memory
        .store(
            SymbolicExpression::symbol("cat"),
            SymbolicExpression::symbol("meow"),
        )
        .unwrap();

    memory
        .store(
            SymbolicExpression::symbol("dog"),
            SymbolicExpression::symbol("bark"),
        )
        .unwrap();

    // Retrieve
    let cat_result = memory.retrieve(&SymbolicExpression::symbol("cat")).unwrap();
    assert!(cat_result.is_some());
    assert_eq!(
        cat_result.unwrap().value,
        SymbolicExpression::symbol("meow")
    );

    let dog_result = memory.retrieve(&SymbolicExpression::symbol("dog")).unwrap();
    assert!(dog_result.is_some());
    assert_eq!(
        dog_result.unwrap().value,
        SymbolicExpression::symbol("bark")
    );
}

#[test]
fn test_memory_decay() {
    let dir = tempdir().unwrap();
    let journal_path = dir.path().join("test_journal.bin");

    let hardware = MockOpticalHardware::new(42);
    let config = CheckpointConfig {
        journal_path,
        interval: Duration::from_secs(3600),
        ..Default::default()
    };

    let mut memory = CheckpointedOpticalMemory::new(
        hardware,
        test_encoder_config(),
        test_codebook_config(),
        config,
    )
    .unwrap();

    memory
        .store(
            SymbolicExpression::symbol("key"),
            SymbolicExpression::symbol("value"),
        )
        .unwrap();

    // Apply decay
    memory.decay(0.5).unwrap();

    let stats = memory.stats();
    assert_eq!(stats.n_associations, 1);

    // Apply more decay until association is removed
    memory.decay(0.01).unwrap();

    let stats = memory.stats();
    assert_eq!(stats.n_associations, 0);
}

#[test]
fn test_memory_forget() {
    let dir = tempdir().unwrap();
    let journal_path = dir.path().join("test_journal.bin");

    let hardware = MockOpticalHardware::new(42);
    let config = CheckpointConfig {
        journal_path,
        interval: Duration::from_secs(3600),
        ..Default::default()
    };

    let mut memory = CheckpointedOpticalMemory::new(
        hardware,
        test_encoder_config(),
        test_codebook_config(),
        config,
    )
    .unwrap();

    memory
        .store(
            SymbolicExpression::symbol("key1"),
            SymbolicExpression::symbol("value1"),
        )
        .unwrap();
    memory
        .store(
            SymbolicExpression::symbol("key2"),
            SymbolicExpression::symbol("value2"),
        )
        .unwrap();

    assert_eq!(memory.stats().n_associations, 2);

    memory.forget(&SymbolicExpression::symbol("key1")).unwrap();

    assert_eq!(memory.stats().n_associations, 1);

    let result = memory
        .retrieve(&SymbolicExpression::symbol("key1"))
        .unwrap();
    assert!(result.is_none());
}

#[test]
fn test_hardware_info() {
    let dir = tempdir().unwrap();
    let journal_path = dir.path().join("test_journal.bin");

    let hardware = MockOpticalHardware::new(42);
    let config = CheckpointConfig {
        journal_path,
        ..Default::default()
    };

    let memory = CheckpointedOpticalMemory::new(
        hardware,
        test_encoder_config(),
        test_codebook_config(),
        config,
    )
    .unwrap();

    let info = memory.hardware_info();
    assert!(info.is_ready);
    assert!(info.is_calibrated);
    assert_eq!(info.dimensions, (256, 256));
    assert_eq!(info.n_modes, 100);
}

#[test]
fn test_journal_compaction() {
    let mut journal = MemoryJournal::new(test_encoder_config(), test_codebook_config());

    // Add many operations
    for i in 0..100 {
        journal.append(MemoryOp::store(
            SymbolicExpression::symbol(format!("key{}", i)),
            SymbolicExpression::symbol(format!("value{}", i)),
            1.0,
        ));
    }

    assert_eq!(journal.ops.len(), 100);
    assert!(journal.base_state.is_none());

    // Compact
    journal.compact();

    assert!(journal.ops.is_empty());
    assert!(journal.base_state.is_some());
    assert_eq!(journal.base_state.as_ref().unwrap().associations.len(), 100);
}

#[test]
fn test_journal_save_load() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("test_journal.bin");

    let mut journal = MemoryJournal::new(test_encoder_config(), test_codebook_config());
    journal.append(MemoryOp::store(
        SymbolicExpression::symbol("key"),
        SymbolicExpression::symbol("value"),
        1.0,
    ));

    // Save
    journal.save(&path).unwrap();

    // Load
    let loaded = MemoryJournal::load(&path).unwrap();
    assert_eq!(loaded.ops.len(), 1);
}

// ---- WS 5: optical_store compute path (bind + bundle) ----

/// Helper: build a `CheckpointedOpticalMemory` on a `MockOpticalHardware`.
fn make_memory(dir: &tempfile::TempDir) -> CheckpointedOpticalMemory<MockOpticalHardware> {
    let hardware = MockOpticalHardware::new(42);
    let config = CheckpointConfig {
        journal_path: dir.path().join("journal.bin"),
        interval: Duration::from_secs(3600),
        ..Default::default()
    };
    CheckpointedOpticalMemory::new(
        hardware,
        test_encoder_config(),
        test_codebook_config(),
        config,
    )
    .expect("memory constructs")
}

/// A freshly-constructed memory's trace is the binding identity (no stores yet).
/// This is the baseline against which `store` is shown to accumulate.
#[test]
fn ws5_memory_trace_starts_at_identity() {
    let dir = tempdir().unwrap();
    let memory = make_memory(&dir);

    let algebra = OpticalFieldAlgebra::new(test_encoder_config().dimensions);
    let identity = algebra.identity();
    // Cosine similarity 1.0 against the identity it was initialized to.
    assert!((algebra.similarity(memory.memory_trace(), &identity) - 1.0).abs() < 1e-5);
}

/// `optical_store` is no longer a no-op: after one `store`, the trace differs
/// from the identity (a real bind+bundle happened).
#[test]
fn ws5_store_writes_the_trace() {
    let dir = tempdir().unwrap();
    let mut memory = make_memory(&dir);

    let algebra = OpticalFieldAlgebra::new(test_encoder_config().dimensions);
    let identity = algebra.identity();
    assert!(
        (algebra.similarity(memory.memory_trace(), &identity) - 1.0).abs() < 1e-5,
        "baseline: trace starts at identity"
    );

    memory
        .store(
            SymbolicExpression::role_filler("AGENT", "John"),
            SymbolicExpression::role_filler("ACTION", "run"),
        )
        .unwrap();

    assert!(
        algebra.similarity(memory.memory_trace(), &identity) < 0.999,
        "trace must change after a store (bind+bundle ran)"
    );
}

/// The trace accumulates across stores (superposition): trace after two stores
/// differs from trace after one.
#[test]
fn ws5_trace_accumulates_across_stores() {
    let dir = tempdir().unwrap();
    let mut memory = make_memory(&dir);

    memory
        .store(
            SymbolicExpression::role_filler("AGENT", "John"),
            SymbolicExpression::role_filler("ACTION", "run"),
        )
        .unwrap();
    let trace_after_one = memory.memory_trace().clone();

    memory
        .store(
            SymbolicExpression::role_filler("AGENT", "Mary"),
            SymbolicExpression::role_filler("ACTION", "walk"),
        )
        .unwrap();
    let trace_after_two = memory.memory_trace().clone();

    let algebra = OpticalFieldAlgebra::new(test_encoder_config().dimensions);
    assert!(
        algebra.similarity(&trace_after_one, &trace_after_two) < 0.999,
        "trace must accumulate: two stores differ from one"
    );
}

/// The bound `key ⊛ value` is genuinely present in the trace: the trace is more
/// similar to `key ⊛ value` than to an unrelated random field. This is the core
/// "the compute path does a real bind" proof (§9 checklist).
#[test]
fn ws5_bound_key_value_is_present_in_trace() {
    let dir = tempdir().unwrap();
    let mut memory = make_memory(&dir);

    let key_expr = SymbolicExpression::role_filler("AGENT", "John");
    let value_expr = SymbolicExpression::role_filler("ACTION", "run");
    memory.store(key_expr.clone(), value_expr.clone()).unwrap();

    // Recover the bound field the trace was built from.
    let key_field = memory.instantiate(&key_expr).unwrap();
    let value_field = memory.instantiate(&value_expr).unwrap();
    let algebra = OpticalFieldAlgebra::new(test_encoder_config().dimensions);
    let bound = algebra.bind(&key_field, &value_field);

    let sim_to_bound = algebra.similarity(memory.memory_trace(), &bound);
    let sim_to_random = algebra.similarity(memory.memory_trace(), &algebra.random(99));

    assert!(sim_to_bound > sim_to_random,
        "trace must contain key⊛value (sim_to_bound={sim_to_bound}) more than random (sim_to_random={sim_to_random})");
}

/// `measure_via_hardware` round-trips the trace through `MockOpticalHardware`:
/// it returns a measurement whose mode count matches the hardware's mode count
/// and whose total intensity is non-negative. (Mock simulates the physics; we
/// assert the round-trip completes and is well-formed, not a specific intensity.)
#[test]
fn ws5_measure_via_hardware_roundtrips() {
    let dir = tempdir().unwrap();
    let mut memory = make_memory(&dir);

    // An empty (identity) trace still encodes + measures.
    let m0 = memory.measure_via_hardware().unwrap();
    assert!(!m0.mode_amplitudes.is_empty());
    assert!(m0.total_intensity >= 0.0);

    memory
        .store(
            SymbolicExpression::role_filler("AGENT", "John"),
            SymbolicExpression::role_filler("ACTION", "run"),
        )
        .unwrap();

    let m1 = memory.measure_via_hardware().unwrap();
    assert_eq!(
        m1.mode_amplitudes.len(),
        m0.mode_amplitudes.len(),
        "mode count is fixed by the hardware"
    );
    assert!(m1.total_intensity >= 0.0);
}