dreamwell-engine 1.0.0

Dreamwell pure-logic engine library — transforms, hierarchy, canon pipeline, spatial math, hashing, tile rules, validation, waymark schema, material/lighting descriptors. No SpacetimeDB dependency.
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
// Canon event pipeline helpers — pure-logic extraction of the 9-step emission pipeline.
//
// The 9 steps of canon event emission:
//   1. Predicate check (validate preconditions)
//   2. Admission control (scope budget, token bucket)
//   3. Build params (construct event parameters)
//   4. emit_canon_event (insert event row)         — in lib.rs
//   5. Table insert (write to canon_events)        — in lib.rs
//   6. Edge creation (fabric graph edges)
//   7. Projection update (scope/actor state)
//   8. Chain update (scope chain head)
//   9. Done
//
// This module provides computation helpers for steps 1-3, 6-8. Actual
// SpacetimeDB table operations remain in lib.rs; these functions are pure,
// deterministic, and independently testable.
//
// All digest computation uses BLAKE3 with domain separation (v1.0.0 LTS).
// FNV-1a is no longer used for any security-relevant hashing in canon.

// =============================================================================
// Constants
// =============================================================================

/// Contract version identifier embedded in every canon event record.
pub const CONTRACT_VERSION: &str = "dreamwell.canon.v1.0.0";

/// Schema version for the canon event record format.
pub const EVENT_SCHEMA_VERSION: u32 = 1;

// =============================================================================
// Data Structures
// =============================================================================

/// Parameters for constructing a canon event.
#[derive(Clone, Debug)]
pub struct CanonEventParams {
    pub timeline_id: String,
    pub scope_key: String,
    pub event_type: String,
    pub actor_id: String,
    pub target_id: String,
    pub payload: String,
    pub impact_score: i32,
    pub world_id: String,
    /// Loom tier: 0=Critical, 1=Decision, 2=Action, 3=Detail, 4=Ephemeral.
    pub loom_tier: u8,
    pub irreversible: bool,
    /// Provenance kind: "actor", "system", "trigger", "director".
    pub provenance_kind: String,
    pub producer_id: String,
}

/// Result of building a canon event before table insertion.
pub struct CanonEventRecord {
    pub event_id: String,
    pub digest: String,
    pub prev_event_id: String,
    pub tick: u64,
    pub seq: u64,
    pub occurred_at: u64,
    pub contract_version: String,
    pub event_schema_version: u32,
}

// =============================================================================
// §1  Event ID Generation
// =============================================================================

/// Build a deterministic event ID: `"evt:{timeline}:{tick}:{seq:09}"`.
///
/// The sequence number is zero-padded to 9 digits for lexicographic sort
/// compatibility within a single tick (safe up to 999,999,999).
#[inline]
pub fn build_event_id(timeline_id: &str, tick: u64, seq: u64) -> String {
    format!("evt:{}:{}:{:09}", timeline_id, tick, seq)
}

// =============================================================================
// §2  Digest Computation
// =============================================================================

/// Compute BLAKE3 event digest with domain separation (v1.0.0 LTS).
/// Returns 64-character lowercase hex (256-bit collision resistance).
/// Replaces FNV-1a as of v1.0.0 — all downstream chains inherit BLAKE3 security.
pub fn compute_event_digest(
    event_id: &str,
    event_type: &str,
    tick: u64,
    seq: u64,
    timeline_id: &str,
    scope_key: &str,
    actor_id: &str,
    prev_event_id: &str,
) -> String {
    let mut hasher = blake3::Hasher::new_derive_key("dreamwell.canon.v1");
    hasher.update(event_id.as_bytes());
    hasher.update(b"|");
    hasher.update(event_type.as_bytes());
    hasher.update(b"|");
    hasher.update(&tick.to_le_bytes());
    hasher.update(&seq.to_le_bytes());
    hasher.update(b"|");
    hasher.update(timeline_id.as_bytes());
    hasher.update(b"|");
    hasher.update(scope_key.as_bytes());
    hasher.update(b"|");
    hasher.update(actor_id.as_bytes());
    hasher.update(b"|");
    hasher.update(prev_event_id.as_bytes());
    hasher.finalize().to_hex().to_string()
}

// =============================================================================
// §3  Scope Key Construction
// =============================================================================

/// Build a hierarchical scope key: `"tl:{timeline}/lvl:{level}/id:{scope_id}"`.
///
/// Scope keys partition the event stream into independent hash chains. Each
/// segment follows the `key:value` grammar enforced by `validation::validate_scope_key`.
///
/// Returns `Err` if any input contains characters that would produce an invalid scope key.
#[inline]
pub fn build_scope_key(timeline_id: &str, level: &str, scope_id: &str) -> Result<String, String> {
    let key = format!("tl:{}/lvl:{}/id:{}", timeline_id, level, scope_id);
    crate::validation::validate_scope_key(&key)?;
    Ok(key)
}

// =============================================================================
// §4  Admission Control
// =============================================================================

/// Check if a scope budget allows an event.
///
/// Returns `Ok(())` if `events_this_tick < budget`, or an error string if the
/// budget is exhausted for this tick.
#[inline]
pub fn check_scope_budget(events_this_tick: u64, budget: u64) -> Result<(), String> {
    if events_this_tick >= budget {
        Err(format!(
            "scope_budget_exhausted: {} events (budget {})",
            events_this_tick, budget
        ))
    } else {
        Ok(())
    }
}

/// Check if a token bucket has capacity.
///
/// Returns `Ok(())` if `tokens >= cost`, or an error string if insufficient
/// tokens remain.
#[inline]
pub fn check_token_bucket(tokens: u32, cost: u32) -> Result<(), String> {
    if tokens < cost {
        Err(format!("token_bucket_insufficient: {} tokens (cost {})", tokens, cost))
    } else {
        Ok(())
    }
}

/// Compute token refill: `min(current + refill_rate, max_tokens)`.
///
/// Saturates at `max_tokens` to enforce the bucket ceiling. All arithmetic
/// uses `u32` — no intermediate overflow possible for reasonable refill rates.
#[inline]
pub fn refill_tokens(current: u32, refill_rate: u32, max_tokens: u32) -> u32 {
    current.saturating_add(refill_rate).min(max_tokens)
}

// =============================================================================
// §5  Projection Helpers
// =============================================================================

/// Compute a scope state ID from timeline + scope_key.
///
/// Format: `"{timeline_id}:{scope_key}"`. Used as the primary key for the
/// `scope_states` projection table.
#[inline]
pub fn build_scope_state_id(timeline_id: &str, scope_key: &str) -> String {
    format!("{}:{}", timeline_id, scope_key)
}

/// Compute an actor state ID from timeline + actor_id.
///
/// Format: `"{timeline_id}:{actor_id}"`. Used as the primary key for the
/// `actor_states` projection table.
#[inline]
pub fn build_actor_state_id(timeline_id: &str, actor_id: &str) -> String {
    format!("{}:{}", timeline_id, actor_id)
}

/// Compute a player state ID from actor_id.
///
/// Format: `"{actor_id}"`. Player states are indexed by actor identity,
/// not scoped by timeline — a player's aggregate stats span all timelines.
#[inline]
pub fn build_player_state_id(actor_id: &str) -> String {
    actor_id.to_string()
}

/// Compute a ledger ID from scope level and ID.
///
/// Format: `"ledger:{scope_level}:{scope_id}"`. Used as the primary key for
/// aggregate ledger tracking at each scope granularity.
#[inline]
pub fn build_ledger_id(scope_level: &str, scope_id: &str) -> String {
    format!("ledger:{}:{}", scope_level, scope_id)
}

// =============================================================================
// §6  Tick Hash Computation
// =============================================================================

/// Compute the BLAKE3 hash of all events at a given tick.
///
/// Events must be sorted by `seq` before calling. The hash uses domain
/// separation and binary-encodes sequence numbers for unambiguous framing.
///
/// An empty slice produces the hash of the empty input under the tick domain key.
/// Maximum events processed per tick hash computation.
const MAX_TICK_HASH_EVENTS: usize = 65536;

pub fn compute_tick_hash(events: &[(String, u64)]) -> String {
    let capped = &events[..events.len().min(MAX_TICK_HASH_EVENTS)];
    let mut hasher = blake3::Hasher::new_derive_key("dreamwell.tick.v1");
    for (event_id, seq) in capped {
        hasher.update(event_id.as_bytes());
        hasher.update(b":");
        hasher.update(&seq.to_le_bytes());
        hasher.update(b"|");
    }
    hasher.finalize().to_hex().to_string()
}

/// Compute the BLAKE3 hash of all events at a given tick (no-alloc variant).
///
/// Accepts pre-borrowed string slices to avoid cloning event IDs. Events
/// must be sorted by `seq` before calling.
pub fn compute_tick_hash_ref(events: &[(&str, u64)]) -> String {
    if events.len() > MAX_TICK_HASH_EVENTS {
        #[cfg(not(target_arch = "wasm32"))]
        eprintln!(
            "warn: compute_tick_hash_ref capped at {} events (had {})",
            MAX_TICK_HASH_EVENTS,
            events.len()
        );
    }
    let capped = &events[..events.len().min(MAX_TICK_HASH_EVENTS)];
    let mut hasher = blake3::Hasher::new_derive_key("dreamwell.tick.v1");
    for (event_id, seq) in capped {
        hasher.update(event_id.as_bytes());
        hasher.update(b":");
        hasher.update(&seq.to_le_bytes());
        hasher.update(b"|");
    }
    hasher.finalize().to_hex().to_string()
}

// =============================================================================
// §7  Block Hash Computation
// =============================================================================

/// Compute a block hash covering a range of ticks.
///
/// Chains from the previous block hash. The input is the pipe-separated
/// concatenation of `"{tick}:{hash}"` pairs, prefixed by the previous block
/// hash. This creates an unbroken chain from genesis through every block.
///
/// An empty `tick_hashes` slice produces a hash that commits only to the
/// previous block hash.
pub fn compute_block_hash(tick_hashes: &[(u64, String)], prev_block_hash: &str) -> String {
    let mut hasher = blake3::Hasher::new_derive_key("dreamwell.block.v1");
    hasher.update(prev_block_hash.as_bytes());
    for (tick, hash) in tick_hashes {
        hasher.update(b"|");
        hasher.update(&tick.to_le_bytes());
        hasher.update(b":");
        hasher.update(hash.as_bytes());
    }
    hasher.finalize().to_hex().to_string()
}

/// Block hash computation with borrowed tick hash slices.
pub fn compute_block_hash_ref(tick_hashes: &[(u64, &str)], prev_block_hash: &str) -> String {
    let mut hasher = blake3::Hasher::new_derive_key("dreamwell.block.v1");
    hasher.update(prev_block_hash.as_bytes());
    for (tick, hash) in tick_hashes {
        hasher.update(b"|");
        hasher.update(&tick.to_le_bytes());
        hasher.update(b":");
        hasher.update(hash.as_bytes());
    }
    hasher.finalize().to_hex().to_string()
}

// =============================================================================
// §8  Impact Score Classification
// =============================================================================

/// Classify impact score into tiers.
///
/// | Score | Tier |
/// |-------|------|
/// | 0-2   | trivial |
/// | 3-5   | minor |
/// | 6-7   | moderate |
/// | 8-9   | major |
/// | 10    | critical |
/// | other | unknown |
#[inline]
pub fn classify_impact(score: i32) -> &'static str {
    match score {
        0..=2 => "trivial",
        3..=5 => "minor",
        6..=7 => "moderate",
        8..=9 => "major",
        10 => "critical",
        _ => "unknown",
    }
}

// =============================================================================
// §9  Event Type Validation
// =============================================================================

/// Validate that an event type string is well-formed.
///
/// Required format: `"{domain}.{variant}"` where both domain and variant are
/// non-empty and contain only ASCII lowercase letters, digits, and underscores.
/// Examples: `"combat.attack"`, `"trade.offer"`, `"system.tick_advance"`.
pub fn validate_event_type(event_type: &str) -> Result<(), String> {
    let dot_pos = match event_type.find('.') {
        Some(pos) => pos,
        None => {
            return Err(format!(
                "event_type_invalid_format: '{}' missing dot separator (expected domain.variant)",
                event_type
            ));
        }
    };

    let domain = &event_type[..dot_pos];
    let variant = &event_type[dot_pos + 1..];

    if domain.is_empty() {
        return Err("event_type_empty_domain".to_string());
    }
    if variant.is_empty() {
        return Err("event_type_empty_variant".to_string());
    }

    // Reject additional dots — format is strictly two segments.
    if variant.contains('.') {
        return Err(format!(
            "event_type_too_many_segments: '{}' (expected exactly domain.variant)",
            event_type
        ));
    }

    if !domain
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
    {
        return Err(format!(
            "event_type_invalid_domain_chars: '{}' (allowed: a-z, 0-9, _)",
            domain
        ));
    }

    if !variant
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
    {
        return Err(format!(
            "event_type_invalid_variant_chars: '{}' (allowed: a-z, 0-9, _)",
            variant
        ));
    }

    Ok(())
}

// =============================================================================
// §10 Occurred-At Computation
// =============================================================================

/// Derive occurred_at microseconds from tick and tick_rate_ms.
///
/// `occurred_at = tick * tick_rate_ms * 1000` — converting tick index to
/// microseconds via the per-tick millisecond duration. Consistent with
/// `spatial::occurred_at_from_tick`.
#[inline]
pub fn compute_occurred_at(tick: u64, tick_rate_ms: u32) -> u64 {
    tick * tick_rate_ms as u64 * 1000
}

// =============================================================================
// §11 Record Builder
// =============================================================================

/// Build a complete `CanonEventRecord` from pipeline inputs.
///
/// Combines event ID generation, digest computation, and occurred-at derivation
/// into a single call. The caller supplies tick state (tick, seq) and chain
/// state (prev_event_id) obtained from table lookups.
pub fn build_canon_event_record(
    params: &CanonEventParams,
    tick: u64,
    seq: u64,
    prev_event_id: &str,
    tick_rate_ms: u32,
) -> CanonEventRecord {
    let event_id = build_event_id(&params.timeline_id, tick, seq);
    let digest = compute_event_digest(
        &event_id,
        &params.event_type,
        tick,
        seq,
        &params.timeline_id,
        &params.scope_key,
        &params.actor_id,
        prev_event_id,
    );
    let occurred_at = compute_occurred_at(tick, tick_rate_ms);

    CanonEventRecord {
        event_id,
        digest,
        prev_event_id: prev_event_id.to_string(),
        tick,
        seq,
        occurred_at,
        contract_version: CONTRACT_VERSION.to_string(),
        event_schema_version: EVENT_SCHEMA_VERSION,
    }
}

// =============================================================================
// §12  Ed25519 Event Signing (feature-gated)
// =============================================================================

/// Sign a BLAKE3 event digest with Ed25519.
/// Returns a 64-byte signature.
#[cfg(feature = "signing")]
pub fn sign_event_digest(digest_hex: &str, key: &ed25519_dalek::SigningKey) -> [u8; 64] {
    use ed25519_dalek::Signer;
    key.sign(digest_hex.as_bytes()).to_bytes()
}

/// Verify an Ed25519 signature against a BLAKE3 event digest.
#[cfg(feature = "signing")]
pub fn verify_event_signature(digest_hex: &str, signature: &[u8; 64], key: &ed25519_dalek::VerifyingKey) -> bool {
    use ed25519_dalek::Verifier;
    let sig = ed25519_dalek::Signature::from_bytes(signature);
    key.verify(digest_hex.as_bytes(), &sig).is_ok()
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // -- Event ID generation -------------------------------------------------

    #[test]
    fn event_id_basic_format() {
        assert_eq!(build_event_id("main", 100, 3), "evt:main:100:000000003");
    }

    #[test]
    fn event_id_zero_tick_and_seq() {
        assert_eq!(build_event_id("tl_alpha", 0, 0), "evt:tl_alpha:0:000000000");
    }

    #[test]
    fn event_id_large_seq() {
        assert_eq!(build_event_id("main", 1, 999999), "evt:main:1:000999999");
    }

    #[test]
    fn event_id_seq_overflow_pads_beyond_nine() {
        // Sequences exceeding 9 digits still format correctly — just wider.
        let id = build_event_id("main", 1, 1_000_000_000);
        assert_eq!(id, "evt:main:1:1000000000");
    }

    // -- Digest computation --------------------------------------------------

    #[test]
    fn digest_is_64_hex_chars() {
        let d = compute_event_digest(
            "evt:m:1:000000",
            "combat.attack",
            1,
            0,
            "m",
            "world:a",
            "actor1",
            "genesis",
        );
        assert_eq!(d.len(), 64);
        assert!(d.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn digest_deterministic() {
        let a = compute_event_digest("evt:m:1:000000", "combat.attack", 1, 0, "m", "s", "a", "genesis");
        let b = compute_event_digest("evt:m:1:000000", "combat.attack", 1, 0, "m", "s", "a", "genesis");
        assert_eq!(a, b);
    }

    #[test]
    fn digest_changes_with_prev_event() {
        let a = compute_event_digest("evt:m:1:000000", "t", 1, 0, "m", "s", "a", "genesis");
        let b = compute_event_digest("evt:m:1:000000", "t", 1, 0, "m", "s", "a", "evt:m:0:000000");
        assert_ne!(a, b);
    }

    #[test]
    fn digest_changes_with_event_type() {
        let a = compute_event_digest("e", "combat.attack", 1, 0, "m", "s", "a", "g");
        let b = compute_event_digest("e", "trade.offer", 1, 0, "m", "s", "a", "g");
        assert_ne!(a, b);
    }

    // -- Scope key construction ----------------------------------------------

    #[test]
    fn scope_key_format() {
        assert_eq!(
            build_scope_key("main", "world", "ayora").unwrap(),
            "tl:main/lvl:world/id:ayora"
        );
    }

    #[test]
    fn scope_key_with_region() {
        assert_eq!(
            build_scope_key("tl_1", "region", "heartland").unwrap(),
            "tl:tl_1/lvl:region/id:heartland"
        );
    }

    #[test]
    fn scope_key_rejects_invalid_chars() {
        assert!(build_scope_key("main", "world", "bad chars!").is_err());
    }

    // -- Admission control ---------------------------------------------------

    #[test]
    fn scope_budget_allows_under_limit() {
        assert!(check_scope_budget(5, 10).is_ok());
    }

    #[test]
    fn scope_budget_rejects_at_limit() {
        assert!(check_scope_budget(10, 10).is_err());
    }

    #[test]
    fn scope_budget_rejects_over_limit() {
        assert!(check_scope_budget(11, 10).is_err());
    }

    #[test]
    fn scope_budget_allows_zero_of_nonzero() {
        assert!(check_scope_budget(0, 1).is_ok());
    }

    #[test]
    fn token_bucket_allows_sufficient() {
        assert!(check_token_bucket(10, 5).is_ok());
    }

    #[test]
    fn token_bucket_allows_exact() {
        assert!(check_token_bucket(5, 5).is_ok());
    }

    #[test]
    fn token_bucket_rejects_insufficient() {
        assert!(check_token_bucket(3, 5).is_err());
    }

    #[test]
    fn token_bucket_zero_cost_always_passes() {
        assert!(check_token_bucket(0, 0).is_ok());
    }

    #[test]
    fn refill_tokens_basic() {
        assert_eq!(refill_tokens(5, 3, 10), 8);
    }

    #[test]
    fn refill_tokens_caps_at_max() {
        assert_eq!(refill_tokens(8, 5, 10), 10);
    }

    #[test]
    fn refill_tokens_already_at_max() {
        assert_eq!(refill_tokens(10, 5, 10), 10);
    }

    #[test]
    fn refill_tokens_overflow_saturates() {
        assert_eq!(refill_tokens(u32::MAX, 1, u32::MAX), u32::MAX);
    }

    #[test]
    fn refill_tokens_zero_refill() {
        assert_eq!(refill_tokens(5, 0, 10), 5);
    }

    // -- Projection helpers --------------------------------------------------

    #[test]
    fn scope_state_id_format() {
        assert_eq!(build_scope_state_id("main", "world:ayora"), "main:world:ayora");
    }

    #[test]
    fn actor_state_id_format() {
        assert_eq!(build_actor_state_id("main", "actor_42"), "main:actor_42");
    }

    #[test]
    fn player_state_id_format() {
        assert_eq!(build_player_state_id("player_7"), "player_7");
    }

    #[test]
    fn ledger_id_format() {
        assert_eq!(build_ledger_id("world", "ayora"), "ledger:world:ayora");
    }

    // -- Tick hash computation -----------------------------------------------

    #[test]
    fn tick_hash_single_event() {
        let events = vec![("evt:m:1:000000".to_string(), 0u64)];
        let h = compute_tick_hash(&events);
        assert_eq!(h.len(), 64);
        assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn tick_hash_deterministic() {
        let events = vec![
            ("evt:m:1:000000".to_string(), 0u64),
            ("evt:m:1:000001".to_string(), 1u64),
        ];
        let a = compute_tick_hash(&events);
        let b = compute_tick_hash(&events);
        assert_eq!(a, b);
    }

    #[test]
    fn tick_hash_order_matters() {
        let events_a = vec![
            ("evt:m:1:000000".to_string(), 0u64),
            ("evt:m:1:000001".to_string(), 1u64),
        ];
        let events_b = vec![
            ("evt:m:1:000001".to_string(), 1u64),
            ("evt:m:1:000000".to_string(), 0u64),
        ];
        assert_ne!(compute_tick_hash(&events_a), compute_tick_hash(&events_b));
    }

    #[test]
    fn tick_hash_empty_events() {
        let events: Vec<(String, u64)> = vec![];
        let h = compute_tick_hash(&events);
        // BLAKE3 hash of empty input — still a valid 64-char hex digest.
        assert_eq!(h.len(), 64);
    }

    #[test]
    fn tick_hash_ref_matches_owned() {
        let events_owned = vec![
            ("evt:m:1:000000".to_string(), 0u64),
            ("evt:m:1:000001".to_string(), 1u64),
        ];
        let events_ref: Vec<(&str, u64)> = vec![("evt:m:1:000000", 0u64), ("evt:m:1:000001", 1u64)];
        assert_eq!(compute_tick_hash(&events_owned), compute_tick_hash_ref(&events_ref));
    }

    // -- Block hash computation ----------------------------------------------

    #[test]
    fn block_hash_chains_from_prev() {
        let ticks = vec![(1u64, "aaaa000000000000".to_string())];
        let a = compute_block_hash(&ticks, "genesis");
        let b = compute_block_hash(&ticks, "other_prev");
        assert_ne!(a, b);
    }

    #[test]
    fn block_hash_deterministic() {
        let ticks = vec![
            (1u64, "aaaa000000000000".to_string()),
            (2u64, "bbbb000000000000".to_string()),
        ];
        let a = compute_block_hash(&ticks, "genesis");
        let b = compute_block_hash(&ticks, "genesis");
        assert_eq!(a, b);
    }

    #[test]
    fn block_hash_empty_ticks() {
        let ticks: Vec<(u64, String)> = vec![];
        let h = compute_block_hash(&ticks, "genesis");
        // BLAKE3 hash of just "genesis" under the block domain key.
        assert_eq!(h.len(), 64);
    }

    #[test]
    fn block_hash_ref_matches_owned() {
        let ticks_owned = vec![(1u64, "abcdef0123456789".to_string())];
        let ticks_ref: Vec<(u64, &str)> = vec![(1u64, "abcdef0123456789")];
        assert_eq!(
            compute_block_hash(&ticks_owned, "gen"),
            compute_block_hash_ref(&ticks_ref, "gen")
        );
    }

    // -- Impact classification -----------------------------------------------

    #[test]
    fn impact_trivial() {
        assert_eq!(classify_impact(0), "trivial");
        assert_eq!(classify_impact(1), "trivial");
        assert_eq!(classify_impact(2), "trivial");
    }

    #[test]
    fn impact_minor() {
        assert_eq!(classify_impact(3), "minor");
        assert_eq!(classify_impact(5), "minor");
    }

    #[test]
    fn impact_moderate() {
        assert_eq!(classify_impact(6), "moderate");
        assert_eq!(classify_impact(7), "moderate");
    }

    #[test]
    fn impact_major() {
        assert_eq!(classify_impact(8), "major");
        assert_eq!(classify_impact(9), "major");
    }

    #[test]
    fn impact_critical() {
        assert_eq!(classify_impact(10), "critical");
    }

    #[test]
    fn impact_negative_is_unknown() {
        assert_eq!(classify_impact(-1), "unknown");
    }

    #[test]
    fn impact_above_10_is_unknown() {
        assert_eq!(classify_impact(11), "unknown");
        assert_eq!(classify_impact(100), "unknown");
    }

    // -- Event type validation -----------------------------------------------

    #[test]
    fn event_type_valid() {
        assert!(validate_event_type("combat.attack").is_ok());
        assert!(validate_event_type("trade.offer").is_ok());
        assert!(validate_event_type("system.tick_advance").is_ok());
        assert!(validate_event_type("quest.complete_stage").is_ok());
    }

    #[test]
    fn event_type_with_digits() {
        assert!(validate_event_type("v2.init").is_ok());
        assert!(validate_event_type("system.phase3").is_ok());
    }

    #[test]
    fn event_type_missing_dot() {
        let err = validate_event_type("combatattack").unwrap_err();
        assert!(err.contains("missing dot separator"));
    }

    #[test]
    fn event_type_empty_domain() {
        assert!(validate_event_type(".attack").is_err());
    }

    #[test]
    fn event_type_empty_variant() {
        assert!(validate_event_type("combat.").is_err());
    }

    #[test]
    fn event_type_too_many_dots() {
        let err = validate_event_type("combat.attack.crit").unwrap_err();
        assert!(err.contains("too_many_segments"));
    }

    #[test]
    fn event_type_uppercase_rejected() {
        assert!(validate_event_type("Combat.attack").is_err());
        assert!(validate_event_type("combat.Attack").is_err());
    }

    #[test]
    fn event_type_special_chars_rejected() {
        assert!(validate_event_type("combat.attack!").is_err());
        assert!(validate_event_type("combat-system.attack").is_err());
        assert!(validate_event_type("combat.attack hit").is_err());
    }

    #[test]
    fn event_type_empty_string() {
        assert!(validate_event_type("").is_err());
    }

    // -- Occurred-at computation ---------------------------------------------

    #[test]
    fn occurred_at_basic() {
        // tick=10, 100ms per tick -> 10 * 100 * 1000 = 1_000_000 microseconds
        assert_eq!(compute_occurred_at(10, 100), 1_000_000);
    }

    #[test]
    fn occurred_at_zero_tick() {
        assert_eq!(compute_occurred_at(0, 100), 0);
    }

    #[test]
    fn occurred_at_zero_rate() {
        assert_eq!(compute_occurred_at(100, 0), 0);
    }

    #[test]
    fn occurred_at_one_tick_one_ms() {
        // 1 tick * 1 ms * 1000 = 1000 microseconds
        assert_eq!(compute_occurred_at(1, 1), 1000);
    }

    // -- Record builder ------------------------------------------------------

    #[test]
    fn build_record_populates_all_fields() {
        let params = CanonEventParams {
            timeline_id: "main".to_string(),
            scope_key: "tl:main/lvl:world/id:ayora".to_string(),
            event_type: "combat.attack".to_string(),
            actor_id: "actor_1".to_string(),
            target_id: "actor_2".to_string(),
            payload: "{}".to_string(),
            impact_score: 5,
            world_id: "ayora".to_string(),
            loom_tier: 2,
            irreversible: false,
            provenance_kind: "actor".to_string(),
            producer_id: "0xabc".to_string(),
        };
        let record = build_canon_event_record(&params, 42, 7, "genesis", 100);

        assert_eq!(record.event_id, "evt:main:42:000000007");
        assert_eq!(record.prev_event_id, "genesis");
        assert_eq!(record.tick, 42);
        assert_eq!(record.seq, 7);
        assert_eq!(record.occurred_at, 42 * 100 * 1000);
        assert_eq!(record.contract_version, CONTRACT_VERSION);
        assert_eq!(record.event_schema_version, EVENT_SCHEMA_VERSION);
        assert_eq!(record.digest.len(), 64);
    }

    #[test]
    fn build_record_digest_matches_standalone() {
        let params = CanonEventParams {
            timeline_id: "t".to_string(),
            scope_key: "s".to_string(),
            event_type: "e.v".to_string(),
            actor_id: "a".to_string(),
            target_id: "".to_string(),
            payload: "".to_string(),
            impact_score: 0,
            world_id: "w".to_string(),
            loom_tier: 0,
            irreversible: false,
            provenance_kind: "system".to_string(),
            producer_id: "".to_string(),
        };
        let record = build_canon_event_record(&params, 1, 0, "prev", 50);
        let expected_digest = compute_event_digest(&build_event_id("t", 1, 0), "e.v", 1, 0, "t", "s", "a", "prev");
        assert_eq!(record.digest, expected_digest);
    }

    // -- Constants -----------------------------------------------------------

    #[test]
    fn contract_version_format() {
        assert!(CONTRACT_VERSION.starts_with("dreamwell.canon."));
        assert!(CONTRACT_VERSION.contains("v1"));
    }

    #[test]
    fn event_schema_version_is_one() {
        assert_eq!(EVENT_SCHEMA_VERSION, 1);
    }

    #[cfg(feature = "signing")]
    #[test]
    fn ed25519_sign_and_verify() {
        use ed25519_dalek::SigningKey;
        // Deterministic test key (32 bytes). Never use fixed keys in production.
        let seed: [u8; 32] = [
            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12,
            0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
        ];
        let signing_key = SigningKey::from_bytes(&seed);
        let verifying_key = signing_key.verifying_key();
        let digest = compute_event_digest(
            "evt:t1:1:000000001",
            "test",
            1,
            1,
            "t1",
            "scope:test",
            "actor:1",
            "none",
        );
        let sig = sign_event_digest(&digest, &signing_key);
        assert!(verify_event_signature(&digest, &sig, &verifying_key));
        // Tampered digest should fail
        assert!(!verify_event_signature("tampered", &sig, &verifying_key));
    }
}