dreamwell-runtime 1.0.0

Dreamwell Runtime — cross-platform GPU-accelerated game client
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
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
// SimulationService — the DreamRealityContainer.
//
// Dual-purpose: Studio→Play preview AND Published .exe builds.
// Manages the full play lifecycle: Braid mount → reality check → scene instantiation
// → CausalComputeKernel init → GPU sync → stitch → first frame confirmation → frame loop → shutdown.
//
// Input is NEVER enabled before the 7-step initialization completes.
// The Seer must be Happy.
//
// Uses CausalComputeKernel + SDK Decoherence instead of ParticleController.
// Every input is dispatched through Oracle as a SacredWeave with BLAKE3 attestation.

use dreamwell_attention::encoder::CausalEngineEncoder;
use dreamwell_attention::{CausalComputeKernel, InputPacket, KernelResult};
use dreamwell_engine::game_object::GameObjectScene;
use dreamwell_engine::input::particle::particle_sphere_offsets;
use dreamwell_engine::physics::simulation::SuperpositionObserver;
use dreamwell_fabric::causal_observer_lane::{causal_observer_lane_channel, CausalObserverLaneReceiver};
use dreamwell_gates::{DreamGate, GateConfig};
use dreamwell_gpu::quantum_bridge::QuantumBridge;
use dreamwell_sdk::{
    decohere::{Decoherence, DecoherenceConfig, DecoherenceInputMode},
    ledger_lane_channel,
    loom_budgeter::LoomBudgeter,
    loom_limiter::LoomLimiter,
    LedgerLaneReceiver, Oracle, OracleConfig,
};

/// Simulation mode discriminator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SimulationMode {
    /// Studio→Play preview (editor-hosted).
    Preview,
    /// Published standalone build.
    Published,
}

/// Runtime readiness signal — mirrors editor RuntimeReadiness.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuntimeReadiness {
    Pending,
    Syncing,
    Ready,
    Failed,
}

/// A journal entry for the simulation session.
#[derive(Debug, Clone)]
pub struct SimulationJournalEntry {
    pub frame: u64,
    pub kind: String,
    pub detail: String,
}

/// SimulationService — the DreamRealityContainer.
pub struct SimulationService {
    /// Active scene objects.
    pub scene: GameObjectScene,
    /// CausalComputeKernel — synced from encoder for collision/POI checks.
    pub kernel: Option<CausalComputeKernel>,
    /// CausalEngineEncoder — authoritative encode boundary (wraps SuperBodyController → Kernel).
    pub encoder: Option<CausalEngineEncoder>,
    /// QuantumBridge — formal CPU→GPU transfer with DreamMemory + SacredSeal.
    pub bridge: Option<QuantumBridge>,
    /// Last bridge packet for decoder path (app.rs consumes this).
    pub last_bridge_packet: Option<dreamwell_gpu::quantum_bridge::BridgePacket>,
    /// SDK Decoherence facade (input → Weave → Oracle).
    pub decoherence: Option<Decoherence>,
    /// Oracle — SacredPath validation + BLAKE3 attestation router.
    pub oracle: Option<Oracle>,
    /// Spatial decoherence zones from scene tags.
    pub decoherence_fields: Vec<dreamwell_quantum::DecoherenceField>,
    /// Last kernel tick result for rendering.
    pub last_result: Option<KernelResult>,
    /// Last SuperBody frame descriptor for GPU upload (backward compat).
    pub last_descriptor: Option<dreamwell_attention::SuperBodyFrameDescriptor>,
    /// Player entity ID (CanonicalObserverObject).
    pub player_object_id: u64,
    /// Pre-computed sphere offsets for particle particles.
    pub particle_offsets: Vec<[f32; 3]>,
    /// Observer context for quantum culling.
    pub observer: SuperpositionObserver,
    /// Session journal.
    pub journal: Vec<SimulationJournalEntry>,
    /// Console messages (for UI display).
    pub console: Vec<String>,
    /// Simulation mode.
    pub mode: SimulationMode,
    /// Readiness signal — input is gated on this.
    pub readiness: RuntimeReadiness,
    /// Current frame index.
    pub frame: u64,
    /// Total ticks processed.
    pub tick: u64,
    /// Quantum cull radius in meters.
    pub quantum_cull_radius: f32,
    /// Accumulated elapsed time in seconds.
    pub elapsed_time: f32,
    /// DreamGate — high-throughput Weave validation and dispatch.
    pub gate: Option<DreamGate>,
    /// LoomLimiter — per-frame mutation rate limiting.
    pub limiter: Option<LoomLimiter>,
    /// LoomBudgeter — hardware-derived resource budgets.
    pub budgeter: Option<LoomBudgeter>,
    /// LedgerLane receiver for cold-path draining.
    pub ledger_rx: Option<LedgerLaneReceiver>,
    /// CausalObserverLane receiver for GPU frame cold-path draining.
    pub causal_observer_rx: Option<CausalObserverLaneReceiver>,
    /// CausalObserverLane sender (stored here for wiring to renderer).
    pub causal_observer_tx: Option<dreamwell_fabric::CausalObserverLaneSender>,
    /// Active topology layer index (0-9).
    pub active_zone_index: usize,
    /// Metaphor profile for the bridge evaluator.
    pub metaphor_profile: dreamwell_metaphors::MetaphorProfile,
    /// Active particle count (decremented by POI siphon, regenerated over time).
    pub active_particle_count: f32,
    /// Form coherence target: 1.0=Cohere (fibonacci), 0.0=Wave (sinusoidal). TAB cycles.
    pub coherence_target: f32,
    /// Current coherence — smooth-lerped toward target (0.5s transition).
    pub coherence_current: f32,
    /// Gather mode active (Ctrl held).
    pub gather_active: bool,
    /// Primary action emit strength [0,1].
    pub emit_strength: f32,
    /// Universe connection: snapshot receiver (from QuantumServer).
    pub universe_snapshot_rx: Option<crossbeam_channel::Receiver<dreamwell_universe::FieldSnapshot>>,
    /// Universe connection: update sender (to QuantumServer).
    pub universe_update_tx: Option<crossbeam_channel::Sender<dreamwell_universe::ClientUpdate>>,
    /// Universe client ID.
    pub universe_client_id: u64,
    /// Whether universe is connected.
    pub universe_connected: bool,
}

impl SimulationService {
    /// Default quantum cull radius: 9.14m (30ft).
    pub const DEFAULT_QUANTUM_CULL_RADIUS: f32 = 9.14;

    /// Create a new simulation service.
    pub fn new(scene_name: &str, mode: SimulationMode) -> Self {
        Self {
            scene: GameObjectScene::new(scene_name.into()),
            kernel: None,
            encoder: None,
            bridge: None,
            last_bridge_packet: None,
            decoherence: None,
            oracle: None,
            decoherence_fields: Vec::new(),
            last_result: None,
            last_descriptor: None,
            player_object_id: 0,
            particle_offsets: Vec::new(),
            observer: SuperpositionObserver::new([0.0; 3], Self::DEFAULT_QUANTUM_CULL_RADIUS),
            journal: Vec::new(),
            console: Vec::new(),
            mode,
            readiness: RuntimeReadiness::Pending,
            frame: 0,
            tick: 0,
            quantum_cull_radius: Self::DEFAULT_QUANTUM_CULL_RADIUS,
            elapsed_time: 0.0,
            gate: None,
            limiter: None,
            budgeter: None,
            ledger_rx: None,
            causal_observer_rx: None,
            causal_observer_tx: None,
            active_zone_index: 9,
            metaphor_profile: dreamwell_metaphors::MetaphorProfile::wave(),
            active_particle_count: dreamwell_metaphors::DEFAULT_PARTICLE_COUNT as f32,
            coherence_target: 1.0,
            coherence_current: 1.0,
            gather_active: false,
            emit_strength: 0.0,
            universe_snapshot_rx: None,
            universe_update_tx: None,
            universe_client_id: 0,
            universe_connected: false,
        }
    }

    /// Whether input is enabled. Requires encoder (authoritative pipeline).
    pub fn input_enabled(&self) -> bool {
        self.readiness == RuntimeReadiness::Ready && self.encoder.is_some()
    }

    /// Connect to a universe server (spawns background kernel thread).
    /// Returns the shutdown sender so the caller can stop the universe.
    pub fn connect_universe(&mut self) -> crossbeam_channel::Sender<()> {
        let config = dreamwell_universe::UniverseConfig::default();
        let (shutdown_tx, shutdown_rx) = crossbeam_channel::bounded(1);

        // Create the field and connection protocol on the main thread,
        // then move the kernel to a background thread.
        let mut field = dreamwell_universe::QuantumField::new(&config);
        let mut connections = dreamwell_universe::ConnectionProtocol::new(config.max_clients);

        // Connect this client on layer 9 (Point — default play layer).
        let (client_id, snapshot_rx, update_tx) = connections
            .connect(&mut field, 9)
            .expect("Failed to connect to universe");

        self.universe_snapshot_rx = Some(snapshot_rx);
        self.universe_update_tx = Some(update_tx);
        self.universe_client_id = client_id;
        self.universe_connected = true;

        log::info!("Connected to universe on layer 9 (client_id={})", client_id);

        // Spawn the universe kernel in a background thread.
        let config_clone = config.clone();
        std::thread::Builder::new()
            .name("dreamwell-universe".into())
            .spawn(move || {
                let mut kernel = dreamwell_universe::UniverseKernel {
                    config: config_clone.clone(),
                    field,
                    connections,
                    metrics: dreamwell_universe::metrics::UniverseMetrics::new(),
                    shutdown_rx,
                };
                // Expose the fields that were moved
                kernel.run();
            })
            .expect("Failed to spawn universe thread");

        shutdown_tx
    }

    /// Set form coherence target. 1.0=Cohere, 0.0=Wave.
    pub fn set_coherence_target(&mut self, t: f32) {
        self.coherence_target = t.clamp(0.0, 1.0);
    }

    /// Set gather mode.
    pub fn set_gather(&mut self, active: bool) {
        self.gather_active = active;
    }

    /// Set primary action emit strength.
    pub fn set_emit_strength(&mut self, s: f32) {
        self.emit_strength = s.clamp(0.0, 1.0);
    }

    /// Initialize the simulation from a scene and spawn position.
    /// Runs the 7-step initialization sequence with CausalComputeKernel + SDK Decoherence.
    ///
    /// Returns Ok(()) if all steps pass, Err with failure description.
    pub fn initialize(
        &mut self,
        scene: GameObjectScene,
        spawn_pos: [f32; 3],
        particle_count: u32,
    ) -> Result<(), String> {
        // Step 1: Mount Braid
        self.scene = scene;
        self.journal.push(SimulationJournalEntry {
            frame: 0,
            kind: "mount_braid".into(),
            detail: format!("scene: {}, objects: {}", self.scene.name, self.scene.objects.len()),
        });
        self.console.push(format!(
            "[Info] Braid mounted from Chronoshift checkpoint (tick: {}).",
            self.tick,
        ));

        // Step 2: Reality check
        if self.scene.objects.is_empty() {
            self.readiness = RuntimeReadiness::Failed;
            return Err("reality_check: empty scene".into());
        }
        self.console.push("[Info] Reality check: all phases passed.".into());

        // Step 3: Scene instantiation
        let obj_count = self.scene.objects.len();
        self.console
            .push(format!("[Info] Scene instantiated: {obj_count} objects."));

        // Step 4: CausalComputeKernel + SuperBodyController + Encoder + Bridge + SDK Decoherence init
        let kernel = CausalComputeKernel::new(spawn_pos, particle_count);
        self.kernel = Some(kernel);
        self.encoder = Some(CausalEngineEncoder::new(spawn_pos, particle_count, 42));
        let mut bridge = QuantumBridge::new(particle_count);
        bridge.set_metaphor_profile(self.metaphor_profile.clone());
        self.bridge = Some(bridge);

        let decoherence = Decoherence::with_config(DecoherenceConfig {
            input_mode: DecoherenceInputMode::Particle,
            ..DecoherenceConfig::default()
        });
        self.decoherence = Some(decoherence);

        let mut oracle = Oracle::new(OracleConfig::default());
        let (tx, rx) = ledger_lane_channel();
        oracle.connect_ledger(tx);
        oracle.begin_frame(0);
        self.oracle = Some(oracle);
        self.ledger_rx = Some(rx);

        // CausalObserverLane channel for GPU cold path.
        let (causal_observer_tx, causal_observer_rx) = causal_observer_lane_channel();
        self.causal_observer_tx = Some(causal_observer_tx);
        self.causal_observer_rx = Some(causal_observer_rx);

        // DreamGate pipeline: Budgeter → Limiter → Gate.
        let hw = dreamwell_sdk::loom_budgeter::HardwareProfile::mid_range();
        let budgeter = LoomBudgeter::from_hardware(hw);
        let mut limiter = LoomLimiter::default();
        budgeter.apply_to_limiter(&mut limiter);
        let gate = DreamGate::new(GateConfig::from_services(&limiter, &budgeter));
        self.gate = Some(gate);
        self.limiter = Some(limiter);
        self.budgeter = Some(budgeter);

        self.particle_offsets = particle_sphere_offsets(particle_count);

        // Find player object ID and starting topology layer.
        self.player_object_id = self
            .scene
            .objects
            .iter()
            .find(|o| {
                o.property_tags
                    .iter()
                    .any(|t| t == "isInputReceiver" || t == "isPlayer")
            })
            .map(|o| o.id)
            .unwrap_or(1);

        let starting_layer = self
            .scene
            .objects
            .iter()
            .filter(|o| o.property_tags.iter().any(|t| t == "isInputReceiver"))
            .flat_map(|o| o.property_tags.iter())
            .find_map(|t| {
                t.strip_prefix("isStartingOnTopologyLayer")
                    .and_then(|v| v.parse::<u8>().ok())
            })
            .unwrap_or(9);
        if let Some(ref mut k) = self.kernel {
            k.active_topology_layer = starting_layer;
        }
        if let Some(ref mut enc) = self.encoder {
            enc.kernel_mut().active_topology_layer = starting_layer;
        }
        self.active_zone_index = starting_layer as usize;

        self.observer.position = spawn_pos;
        self.observer.active_radius = self.quantum_cull_radius;
        self.console.push(format!(
            "[Info] CausalComputeKernel mounted at [{:.1}, {:.1}, {:.1}] ({particle_count} particles).",
            spawn_pos[0], spawn_pos[1], spawn_pos[2],
        ));
        self.journal.push(SimulationJournalEntry {
            frame: 0,
            kind: "avatar_init".into(),
            detail: format!("particles: {particle_count}, pos: {spawn_pos:?}, sdk: active"),
        });

        // Step 5: GPU sync (headless: no-op)
        self.console.push("[Info] GPU resources synced.".into());

        // Step 6: Stitch
        if self.encoder.is_none() || self.scene.objects.is_empty() {
            self.readiness = RuntimeReadiness::Failed;
            return Err("stitch: render graph validation failed".into());
        }
        self.readiness = RuntimeReadiness::Syncing;
        self.console
            .push("[Info] Stitch passed: render graph validated.".into());

        // Step 7: First frame confirmation
        self.readiness = RuntimeReadiness::Ready;
        self.console
            .push("[Info] Seer is happy, reality rendered without concern.".into());
        self.console
            .push("[Info] Input controls attached to CausalComputeKernel.".into());
        self.console.push(format!(
            "[Info] Quantum pipeline: {} particles, density matrix 5×5, adaptive Hamiltonian (Model 1).",
            particle_count,
        ));
        self.console
            .push("[Info] Couplings will adapt to movement patterns via parameter shift gradient.".into());
        log::info!(
            "Quantum locomotion active: {} particles, F(12)={}, adaptive Hamiltonian learning enabled",
            particle_count,
            particle_count == 144,
        );

        // Step 7c: Connect to universe (persistent quantum field server).
        // Spawns the CausalSimulationKernel in a background thread at φ-scaled 1618Hz.
        let _universe_shutdown = self.connect_universe();
        self.console
            .push("[Info] Universe connected: persistent quantum field at 1618Hz (φ-scaled).".into());

        // Step 7b: Dispatch session begin weave through SDK pipeline.
        if let (Some(ref decoherence), Some(ref mut gate)) = (&self.decoherence, &mut self.gate) {
            let weave = decoherence.build_session_begin_weave(0);
            gate.submit(weave, 100);
        }

        Ok(())
    }

    /// Process one simulation tick via single-encoder authority pipeline.
    ///
    /// Round trip (THE_BRAIDED_PATH):
    /// (1) Build Input Weave → submit to DreamGate
    /// (2) Encoder tick (single authority: Encoder → SuperBody → Kernel → AttentionSolver)
    /// (3) Build Observation + Locomotion Weaves → submit to DreamGate
    /// (4) Gate dispatch: spindle → SacredPath → scene
    /// (5) Bridge: encode → GPU-ready BridgePacket (DreamMemory + SacredSeal)
    ///
    /// Returns the KernelResult, or None if input is not enabled.
    pub fn tick(&mut self, packet: &InputPacket) -> Option<KernelResult> {
        if !self.input_enabled() {
            return None;
        }

        self.frame += 1;
        self.tick += 1;
        self.elapsed_time += packet.dt;

        // Exponential coherence lerp toward target. Rate 6.0 ≈ 0.4s to 95% settle.
        // Frame-rate independent: identical at 30/60/144fps.
        let coherence_rate = 6.0_f32;
        let coherence_t = 1.0 - (-coherence_rate * packet.dt).exp();
        self.coherence_current += (self.coherence_target - self.coherence_current) * coherence_t;

        let gate = self.gate.as_mut()?;
        let tick = self.tick;

        gate.begin_frame(tick);
        if let Some(ref mut limiter) = self.limiter {
            limiter.begin_frame(tick);
        }

        // (1) Build Input Weave → submit to DreamGate
        if let Some(ref mut decoherence) = self.decoherence {
            let actions = packet.actions_as_u8();
            let movement = packet.movement;
            let look = [packet.camera_yaw, 0.0];
            let input_weave = decoherence.build_input_weave(tick, actions, movement, look, 0.0);
            gate.submit(input_weave, 100);
        }

        // (2) SINGLE encoder tick — authoritative quantum evolution.
        // Patch authoritative state onto packet before encoding:
        //   grounded:         from encoder kernel (previous frame's physics result)
        //   timestamp:        from elapsed_time (just incremented above)
        //   coherence_target: from coherence_current (just lerped above — NOT the raw target)
        let encoder = self.encoder.as_mut()?;
        let mut enc_packet = packet.clone();
        enc_packet.grounded = encoder.kernel().grounded;
        enc_packet.timestamp = self.elapsed_time as f64;
        enc_packet.coherence_target = self.coherence_current;
        let encode_result = encoder.encode_frame(&enc_packet, &self.decoherence_fields);

        // ── Model 1: Adaptive Hamiltonian (online gradient learning) ──
        // Every other frame, compute parameter shift gradient of free energy w.r.t.
        // Hamiltonian couplings and update them. Adapts locomotion feel to the
        // player's movement patterns in real time. Cost: ~14µs (0.085% budget).
        if self.frame % 2 == 0 {
            let kernel = encoder.kernel_mut();
            let bias = kernel.quantum.hamiltonian.bias;
            let couplings = kernel.quantum.hamiltonian.couplings;
            // Reconstruct input bias from kernel movement state.
            let moving = kernel.velocity[0].abs() > 0.01 || kernel.velocity[2].abs() > 0.01;
            let sprinting = enc_packet.sprint && moving;
            let input_bias = [
                if !moving { 2.0 } else { 0.0 },
                if moving && !sprinting { 2.0 } else { 0.0 },
                if enc_packet.jump { 3.0 } else { 0.0 },
                if kernel.landing_timer > 0.0 { 2.0 } else { 0.0 },
                if sprinting { 2.0 } else { 0.0 },
            ];
            let shift = std::f32::consts::FRAC_PI_2;
            let lr = 0.005_f32;

            let mut new_couplings = couplings;
            for k in 0..5 {
                let mut c_plus = couplings;
                c_plus[k] = (c_plus[k] + shift).min(2.0);
                let f_plus = kernel.quantum.rho.free_energy(&bias, &input_bias, &c_plus);

                let mut c_minus = couplings;
                c_minus[k] = (c_minus[k] - shift).max(0.1);
                let f_minus = kernel.quantum.rho.free_energy(&bias, &input_bias, &c_minus);

                let grad = (f_plus - f_minus) / 2.0;
                // Descend — minimize free energy for stability (not maximize).
                new_couplings[k] = (new_couplings[k] - lr * grad).clamp(0.1, 2.0);
            }
            kernel.quantum.hamiltonian.couplings = new_couplings;

            if self.frame % 120 == 0 {
                log::info!(
                    "Adaptive Hamiltonian: couplings=[{:.3}, {:.3}, {:.3}, {:.3}, {:.3}] F={:.4}",
                    new_couplings[0],
                    new_couplings[1],
                    new_couplings[2],
                    new_couplings[3],
                    new_couplings[4],
                    kernel.quantum.rho.free_energy(&bias, &input_bias, &new_couplings),
                );
            }
        }

        // Extract authoritative result from encoder (single source of truth).
        // (Universe coupling happens below, after mutable encoder borrow is released.)
        let pos = encode_result.kernel_result.position;

        // Sync standalone kernel for collision/POI checks.
        if let Some(ref mut k) = self.kernel {
            k.position = pos;
            k.velocity = encoder.kernel().velocity;
            k.grounded = encoder.kernel().grounded;
            k.facing_yaw = encoder.kernel().facing_yaw;
        }

        // (3) Observation + Locomotion Weaves → submit to DreamGate
        if let Some(ref mut decoherence) = self.decoherence {
            let facing_yaw = encoder.kernel().facing_yaw;
            let obs_weave = decoherence.build_observe_weave(tick, pos, facing_yaw);
            gate.submit(obs_weave, 100);

            // Locomotion Weave if mode changed
            if let Some(ref prev) = self.last_result {
                if encode_result.kernel_result.locomotion_mode != prev.locomotion_mode {
                    let loco_state = match encode_result.kernel_result.locomotion_mode {
                        0 => dreamwell_sdk::decohere::LocomotionState::Idle,
                        1 => dreamwell_sdk::decohere::LocomotionState::Walking,
                        2 => dreamwell_sdk::decohere::LocomotionState::Running,
                        3 => dreamwell_sdk::decohere::LocomotionState::Jumping,
                        4 => dreamwell_sdk::decohere::LocomotionState::Falling,
                        _ => dreamwell_sdk::decohere::LocomotionState::Idle,
                    };
                    let loco_weave = decoherence.build_locomotion_weave(tick, loco_state);
                    gate.submit(loco_weave, 90);
                }
            }

            // Topology transition if layer changed
            if encode_result.kernel_result.layer_changed {
                self.active_zone_index = encode_result.kernel_result.topology_layer as usize;
            }
        }

        // (4) Gate dispatch: spindle → SacredPath → scene
        if let Some(ref mut oracle) = self.oracle {
            let (_accepted, _rejected, _mutations) = gate.dispatch_through_oracle(oracle, &mut self.scene);
            oracle.end_frame();
            oracle.begin_frame(self.tick);
        }

        // (4b) Drain GPU causal observer lane → forward to Oracle's ledger for QuantumCloud archival.
        if let Some(ref causal_observer_rx) = self.causal_observer_rx {
            let gpu_events = causal_observer_rx.drain();
            if !gpu_events.is_empty() {
                log::trace!("causal_observer_lane: drained {} GPU frame events", gpu_events.len());
            }
        }

        // (5) Bridge: encode → GPU-ready packets (validates + seals + captures to DreamMemory).
        // Evaluate TagInfluenceFrame from scene POIs before bridging.
        let tag_frame = self.evaluate_tag_influences(pos);
        if let Some(ref mut bridge) = self.bridge {
            bridge.set_tag_frame(tag_frame);
            let (bp, _validation) = bridge.bridge(&encode_result, packet.dt, self.elapsed_time);
            self.last_bridge_packet = Some(bp);
        }

        // (5b) Particle siphon + regeneration based on POI proximity.
        self.update_particle_siphon(pos, packet.dt);

        // Update observer + store lightweight snapshot for next-frame locomotion comparison.
        // Only the locomotion_mode is consumed (line 381). Avoid cloning String/Vec per frame.
        self.observer.position = pos;
        let result = encode_result.kernel_result;

        self.last_result = Some(KernelResult {
            position: result.position,
            locomotion_mode: result.locomotion_mode,
            form: result.form,
            coherence: result.coherence,
            populations: result.populations,
            entropy: result.entropy,
            purity: result.purity,
            active_clip: String::new(),
            moved: result.moved,
            coalesce_events: Vec::new(),
            topology_layer: result.topology_layer,
            layer_changed: false,
        });

        // ── Universe coupling (Blaed's Algorithm: client ↔ server field) ──
        if self.universe_connected {
            // Send our state to the universe server.
            if let Some(ref tx) = self.universe_update_tx {
                if let Some(ref enc) = self.encoder {
                    let k = enc.kernel();
                    let update = dreamwell_universe::ClientUpdate {
                        client_id: self.universe_client_id,
                        populations: k.quantum.rho.populations(),
                        coherences: k.quantum.rho.off_diagonal_pairs(),
                        position: k.position,
                        layer: self.active_zone_index as u8,
                        frame: self.frame,
                    };
                    let _ = tx.try_send(update);
                }
            }
            // Receive field snapshot and apply coupling.
            if let Some(ref rx) = self.universe_snapshot_rx {
                if let Ok(snapshot) = rx.try_recv() {
                    if let Some(ref mut enc) = self.encoder {
                        let layer = self.active_zone_index;
                        let channel = &snapshot.channels[layer];
                        let coupling_eps = 0.03 * packet.dt;
                        let field_coh = channel.coherence_magnitude;
                        let rho = &mut enc.kernel_mut().quantum.rho;
                        for i in 0..5 {
                            for j in 0..5 {
                                if i != j {
                                    let retain = 1.0 - coupling_eps * (1.0 - field_coh);
                                    rho.entries[i * 5 + j] = rho.entries[i * 5 + j].scale(retain.max(0.0));
                                }
                            }
                        }
                        if self.frame % 300 == 0 {
                            log::info!(
                                "Universe sync: tick={} field_coh={:.4} field_F={:.4}",
                                snapshot.tick,
                                field_coh,
                                channel.free_energy,
                            );
                        }
                    }
                }
            }
        }

        Some(result)
    }

    /// Current authoritative position: encoder first, kernel fallback.
    fn observer_position(&self) -> Option<[f32; 3]> {
        self.encoder
            .as_ref()
            .map(|e| e.kernel().position)
            .or_else(|| self.kernel.as_ref().map(|k| k.position))
    }

    /// Check for collisions with isWall/isCollider objects within threshold.
    pub fn check_collisions(&self, threshold: f32) -> Vec<(u64, f32)> {
        let pos = match self.observer_position() {
            Some(p) => p,
            None => return Vec::new(),
        };

        self.scene
            .objects
            .iter()
            .filter_map(|o| {
                let is_collider = o.property_tags.iter().any(|t| t == "isWall" || t == "isCollider");
                if !is_collider {
                    return None;
                }
                let dx = o.transform.position[0] - pos[0];
                let dy = o.transform.position[1] - pos[1];
                let dz = o.transform.position[2] - pos[2];
                let dist = (dx * dx + dy * dy + dz * dz).sqrt();
                if dist <= threshold {
                    Some((o.id, dist))
                } else {
                    None
                }
            })
            .collect()
    }

    /// Check POI proximity. Returns Vec of (object_id, distance).
    pub fn check_poi_proximity(&self, radius: f32) -> Vec<(u64, f32)> {
        let pos = match self.observer_position() {
            Some(p) => p,
            None => return Vec::new(),
        };

        self.scene
            .objects
            .iter()
            .filter_map(|o| {
                let is_poi = o.property_tags.iter().any(|t| t == "poi" || t == "isInteractable");
                if !is_poi {
                    return None;
                }
                let dx = o.transform.position[0] - pos[0];
                let dy = o.transform.position[1] - pos[1];
                let dz = o.transform.position[2] - pos[2];
                let dist = (dx * dx + dy * dy + dz * dz).sqrt();
                if dist <= radius {
                    Some((o.id, dist))
                } else {
                    None
                }
            })
            .collect()
    }

    /// Check POI proximity and dispatch interaction weaves for nearby POIs.
    pub fn tick_poi_interactions(&mut self) {
        let pois = self.check_poi_proximity(5.0);
        if pois.is_empty() {
            return;
        }

        let gate = match &mut self.gate {
            Some(g) => g,
            None => return,
        };
        let decoherence = match &self.decoherence {
            Some(d) => d,
            None => return,
        };
        let tick = self.tick;

        for (poi_id, dist) in &pois {
            if *dist < 2.0 {
                let weave = decoherence.build_interaction_weave(tick, *poi_id);
                gate.submit(weave, 80);
            }
        }
    }

    /// Apply collision pushback from wall/collider objects.
    pub fn tick_collisions(&mut self) {
        let collisions = self.check_collisions(2.0);
        if collisions.is_empty() {
            return;
        }

        // Try encoder kernel first, fall back to direct kernel.
        let kernel = if let Some(ref mut enc) = self.encoder {
            enc.kernel_mut()
        } else if let Some(ref mut k) = self.kernel {
            k
        } else {
            return;
        };
        for (obj_id, dist) in &collisions {
            if let Some(obj) = self.scene.find(*obj_id) {
                if *dist < 0.01 {
                    continue;
                }
                let push_str = (1.0 - dist / 2.0).max(0.0) * 0.5;
                let dx = kernel.position[0] - obj.transform.position[0];
                let dz = kernel.position[2] - obj.transform.position[2];
                let len = (dx * dx + dz * dz).sqrt().max(0.001);
                kernel.position[0] += (dx / len) * push_str;
                kernel.position[2] += (dz / len) * push_str;
            }
        }
    }

    /// Evaluate TagInfluenceFrame from scene POI objects near the observer.
    /// Scans for `isPointOfInterest` tagged objects within quantum_cull_radius.
    fn evaluate_tag_influences(&self, pos: [f32; 3]) -> dreamwell_metaphors::TagInfluenceFrame {
        let mut frame = dreamwell_metaphors::TagInfluenceFrame::empty();
        let aoi_radius = self.quantum_cull_radius;

        for obj in &self.scene.objects {
            let is_poi = obj
                .property_tags
                .iter()
                .any(|t| t == "isPointOfInterest" || t == "poi" || t == "isInteractable");
            if !is_poi {
                continue;
            }

            let dx = obj.transform.position[0] - pos[0];
            let dy = obj.transform.position[1] - pos[1];
            let dz = obj.transform.position[2] - pos[2];
            let dist = (dx * dx + dy * dy + dz * dz).sqrt();
            if dist > aoi_radius {
                continue;
            }

            // Coupling strength: inverse-distance falloff, 1.0 at contact, 0.0 at radius edge.
            let coupling = (1.0 - dist / aoi_radius).max(0.0);
            let siphon_eligible = obj.property_tags.iter().any(|t| t == "isSiphon" || t == "isFractal");

            frame.poi_couplings.push(dreamwell_metaphors::PoiCoupling {
                poi_id: obj.id,
                distance: dist,
                coupling,
                siphon_eligible,
            });
        }

        // Zone biases from topology transition tags.
        for obj in &self.scene.objects {
            let is_zone = obj
                .property_tags
                .iter()
                .any(|t| t.starts_with("isTopologyTransition") || t == "isDecoherenceZone");
            if !is_zone {
                continue;
            }

            let dx = obj.transform.position[0] - pos[0];
            let dz = obj.transform.position[2] - pos[2];
            let dist = (dx * dx + dz * dz).sqrt();
            if dist > aoi_radius {
                continue;
            }

            let proximity = (1.0 - dist / aoi_radius).max(0.0);
            frame.zone_biases.push(dreamwell_metaphors::ZoneBias {
                zone_id: obj.id,
                morph_bias: proximity * 0.3,
                coherence_bias: -proximity * 0.2, // zones reduce coherence
            });
        }

        frame
    }

    /// Update particle siphon + regeneration based on POI proximity.
    /// Siphon: nearby siphon-eligible POIs reduce active_particle_count.
    /// Regeneration: particle count slowly restores to default when not siphoned.
    fn update_particle_siphon(&mut self, pos: [f32; 3], dt: f32) {
        let default_count = dreamwell_metaphors::DEFAULT_PARTICLE_COUNT as f32;
        let siphon_rate = 30.0; // particles per second per coupling unit
        let regen_rate = 10.0; // particles per second when below default

        let mut total_siphon = 0.0f32;
        for obj in &self.scene.objects {
            let is_siphon = obj.property_tags.iter().any(|t| t == "isSiphon" || t == "isFractal");
            if !is_siphon {
                continue;
            }

            let dx = obj.transform.position[0] - pos[0];
            let dy = obj.transform.position[1] - pos[1];
            let dz = obj.transform.position[2] - pos[2];
            let dist = (dx * dx + dy * dy + dz * dz).sqrt();
            let coupling = (1.0 - dist / self.quantum_cull_radius).max(0.0);
            if coupling > 0.1 {
                total_siphon += coupling;
            }
        }

        if total_siphon > 0.0 {
            self.active_particle_count -= siphon_rate * total_siphon * dt;
        } else if self.active_particle_count < default_count {
            self.active_particle_count += regen_rate * dt;
        }

        // Clamp to valid range.
        self.active_particle_count = self.active_particle_count.clamp(16.0, default_count);
    }

    /// Set the active metaphor profile and propagate to the bridge evaluator.
    pub fn set_metaphor_profile(&mut self, profile: dreamwell_metaphors::MetaphorProfile) {
        self.metaphor_profile = profile.clone();
        if let Some(ref mut bridge) = self.bridge {
            bridge.set_metaphor_profile(profile);
        }
    }

    /// Cycle to the next metaphor profile (Wave → Fibonacci → Stream → Wave).
    /// Returns the name of the newly active profile.
    pub fn cycle_metaphor(&mut self) -> &'static str {
        let new = dreamwell_metaphors::cycle_next(self.metaphor_profile.name);
        let name = new.name;
        self.set_metaphor_profile(new);
        name
    }

    /// End the simulation session.
    pub fn end_session(&mut self) {
        // Dispatch session end weave before teardown.
        if let (Some(ref decoherence), Some(ref mut oracle), Some(ref mut gate)) =
            (&self.decoherence, &mut self.oracle, &mut self.gate)
        {
            let weave = decoherence.build_session_end_weave(self.tick);
            gate.submit(weave, 100);
            let _ = gate.dispatch_through_oracle(oracle, &mut self.scene);
        }

        self.readiness = RuntimeReadiness::Pending;
        self.kernel = None;
        self.encoder = None;
        self.bridge = None;
        self.last_bridge_packet = None;
        self.decoherence = None;
        self.oracle = None;
        self.causal_observer_rx = None;
        self.causal_observer_tx = None;
        self.decoherence_fields.clear();
        self.last_result = None;
        self.last_descriptor = None;
        self.console.push("[Info] Client closing.. Chronoshift success.".into());
        self.console
            .push("[Info] Reality checked and loaded. Editor session restored.".into());
        self.journal.push(SimulationJournalEntry {
            frame: self.frame,
            kind: "end_session".into(),
            detail: "play".into(),
        });
    }
}

// ── Tests ─────────────────────────────────────────────────────────────

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

    fn test_scene() -> GameObjectScene {
        let mut s = GameObjectScene::new("test".into());
        s.spawn("Avatar Start".into()).unwrap();
        s.objects[0].property_tags.push("isPlayer".into());
        s.objects[0].property_tags.push("isInputReceiver".into());
        s.objects[0].transform.position = [0.0, 0.5, 0.0];
        s.spawn("Ground".into()).unwrap();
        s.objects[1].property_tags.push("isStatic".into());
        s.objects[1].property_tags.push("isGround".into());
        s
    }

    #[test]
    fn simulation_new() {
        let sim = SimulationService::new("test", SimulationMode::Preview);
        assert_eq!(sim.readiness, RuntimeReadiness::Pending);
        assert!(!sim.input_enabled());
    }

    #[test]
    fn simulation_initialize_7_steps() {
        let mut sim = SimulationService::new("test", SimulationMode::Preview);
        let scene = test_scene();
        let result = sim.initialize(scene, [0.0, 0.5, 0.0], 128);
        assert!(result.is_ok(), "init should succeed: {:?}", result.err());
        assert_eq!(sim.readiness, RuntimeReadiness::Ready);
        assert!(sim.input_enabled());
        assert!(sim.kernel.is_some());
        assert!(sim.encoder.is_some());
        assert!(sim.bridge.is_some());
        assert!(sim.decoherence.is_some());
        assert!(sim.oracle.is_some());
        assert!(sim.console.iter().any(|m| m.contains("Seer is happy")));
        assert!(sim.console.iter().any(|m| m.contains("CausalComputeKernel")));
    }

    #[test]
    fn simulation_input_gated_before_ready() {
        let mut sim = SimulationService::new("test", SimulationMode::Preview);
        let packet = InputPacket {
            movement: [0.0, 1.0],
            ..InputPacket::idle(1.0 / 60.0, 0)
        };
        let result = sim.tick(&packet);
        assert!(result.is_none(), "input should be gated before init");
    }

    #[test]
    fn simulation_tick_moves_player() {
        let mut sim = SimulationService::new("test", SimulationMode::Preview);
        sim.initialize(test_scene(), [0.0, 0.5, 0.0], 128).unwrap();
        let packet = InputPacket {
            movement: [0.0, 1.0],
            ..InputPacket::idle(1.0 / 60.0, 1)
        };
        let result = sim.tick(&packet);
        assert!(result.is_some());
        let r = result.unwrap();
        assert!(r.position != [0.0, 0.5, 0.0], "player should move after forward input");
    }

    #[test]
    fn simulation_collision_detection() {
        let mut sim = SimulationService::new("test", SimulationMode::Preview);
        let mut scene = test_scene();
        scene.spawn("Wall".into()).unwrap();
        let wall_idx = scene.objects.len() - 1;
        scene.objects[wall_idx].property_tags.push("isWall".into());
        scene.objects[wall_idx].property_tags.push("isCollider".into());
        scene.objects[wall_idx].transform.position = [0.5, 0.5, 0.0];
        sim.initialize(scene, [0.0, 0.5, 0.0], 128).unwrap();

        let collisions = sim.check_collisions(1.0);
        assert!(!collisions.is_empty());
    }

    #[test]
    fn simulation_poi_proximity() {
        let mut sim = SimulationService::new("test", SimulationMode::Preview);
        let mut scene = test_scene();
        scene.spawn("POI".into()).unwrap();
        let poi_idx = scene.objects.len() - 1;
        scene.objects[poi_idx].property_tags.push("isInteractable".into());
        scene.objects[poi_idx].transform.position = [0.0, 0.5, -1.0];
        sim.initialize(scene, [0.0, 0.5, 0.0], 128).unwrap();

        let pois = sim.check_poi_proximity(2.0);
        assert!(!pois.is_empty());
    }

    #[test]
    fn simulation_end_session() {
        let mut sim = SimulationService::new("test", SimulationMode::Preview);
        sim.initialize(test_scene(), [0.0, 0.5, 0.0], 128).unwrap();
        sim.end_session();
        assert_eq!(sim.readiness, RuntimeReadiness::Pending);
        assert!(!sim.input_enabled());
        assert!(sim.kernel.is_none());
        assert!(sim.encoder.is_none());
        assert!(sim.bridge.is_none());
        assert!(sim.decoherence.is_none());
        assert!(sim.oracle.is_none());
        assert!(sim.console.iter().any(|m| m.contains("Chronoshift success")));
    }

    #[test]
    fn simulation_empty_scene_fails() {
        let mut sim = SimulationService::new("test", SimulationMode::Preview);
        let scene = GameObjectScene::new("empty".into());
        let result = sim.initialize(scene, [0.0; 3], 128);
        assert!(result.is_err());
        assert_eq!(sim.readiness, RuntimeReadiness::Failed);
    }

    #[test]
    fn simulation_mode_variants() {
        assert_ne!(SimulationMode::Preview, SimulationMode::Published);
    }

    #[test]
    fn cycle_metaphor_changes_profile() {
        let mut sim = SimulationService::new("test", SimulationMode::Preview);
        sim.initialize(test_scene(), [0.0, 0.5, 0.0], 128).unwrap();
        assert_eq!(sim.metaphor_profile.name, "wave");
        let name = sim.cycle_metaphor();
        assert_eq!(name, "keynote_fibonacci");
        assert_eq!(sim.metaphor_profile.name, "keynote_fibonacci");
        let name = sim.cycle_metaphor();
        assert_eq!(name, "cohered_stream");
        let name = sim.cycle_metaphor();
        assert_eq!(name, "wave");
    }

    #[test]
    fn default_profile_is_wave() {
        let sim = SimulationService::new("test", SimulationMode::Preview);
        assert_eq!(sim.metaphor_profile.name, "wave");
    }

    #[test]
    fn simulation_quantum_cull_radius() {
        let sim = SimulationService::new("test", SimulationMode::Preview);
        assert!((sim.quantum_cull_radius - SimulationService::DEFAULT_QUANTUM_CULL_RADIUS).abs() < 0.01);
    }

    #[test]
    fn simulation_observer_position_updates() {
        let mut sim = SimulationService::new("test", SimulationMode::Preview);
        sim.initialize(test_scene(), [0.0, 0.5, 0.0], 128).unwrap();
        let packet = InputPacket {
            movement: [0.0, 1.0],
            ..InputPacket::idle(1.0, 1)
        };
        sim.tick(&packet);
        assert!(
            sim.observer.position != [0.0, 0.5, 0.0],
            "observer should follow kernel position"
        );
    }

    #[test]
    fn simulation_journal_records_lifecycle() {
        let mut sim = SimulationService::new("test", SimulationMode::Preview);
        sim.initialize(test_scene(), [0.0, 0.5, 0.0], 128).unwrap();
        assert!(sim.journal.iter().any(|e| e.kind == "mount_braid"));
        assert!(sim.journal.iter().any(|e| e.kind == "avatar_init"));
        sim.end_session();
        assert!(sim.journal.iter().any(|e| e.kind == "end_session"));
    }
}