euv-cli 0.51.0

Cross-platform CLI tool for the euv native UI framework supporting run, build, check, fmt, doctor, new, and Hyperlane SSE dynamic updates across all supported platforms.
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
use super::*;

/// Canonical wire-label helpers for `BlenderAssetFormat`.
impl BlenderAssetFormat {
    /// Returns the lowercase canonical label for this 3D asset format.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Lowercase format string (`blend`, `glb`, `gltf`, `euv3d`, or `obj`).
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Blend => FORMAT_LABEL_BLEND,
            Self::Glb => FORMAT_LABEL_GLB,
            Self::Gltf => FORMAT_LABEL_GLTF,
            Self::Euv3d => FORMAT_LABEL_EUV3D,
            Self::Obj => FORMAT_LABEL_OBJ,
        }
    }
}

/// Canonical wire-label helpers for `BlenderBinarySource`.
impl BlenderBinarySource {
    /// Returns the canonical kebab-case label describing how the Blender binary was discovered.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Binary source string.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::CliFlag => SOURCE_LABEL_CLI_FLAG,
            Self::EnvVar => SOURCE_LABEL_ENV_VAR,
            Self::Path => SOURCE_LABEL_PATH,
            Self::OsInstall => SOURCE_LABEL_OS_INSTALL,
            Self::NotFound => SOURCE_LABEL_NOT_FOUND,
        }
    }
}

/// Sensible defaults for `BlenderDoctorConfig`.
impl Default for BlenderDoctorConfig {
    /// Returns default Blender doctor settings probing port `9876` and checking glTF exporter readiness.
    ///
    /// # Returns
    ///
    /// - `Self` - Default `BlenderDoctorConfig`.
    fn default() -> Self {
        Self {
            blender_bin: None,
            mcp_port: DEFAULT_BLENDER_MCP_PORT,
            probe_gltf_exporter: true,
        }
    }
}

/// Sensible defaults for `BlenderImportConfig`.
impl Default for BlenderImportConfig {
    /// Returns default import settings targeting current directory with 4 QEM LODs, meshlets, and BVH4 enabled.
    ///
    /// # Returns
    ///
    /// - `Self` - Default `BlenderImportConfig`.
    fn default() -> Self {
        Self {
            input: PathBuf::new(),
            out_dir: PathBuf::from("."),
            blender_bin: None,
            bake: false,
            lods: DEFAULT_BLENDER_BAKE_LODS,
            build_meshlets: true,
            bake_bvh4: true,
            plan: false,
        }
    }
}

/// Sensible defaults for `BlenderBakeConfig`.
impl Default for BlenderBakeConfig {
    /// Returns default `.euv3d` bake settings with 4 QEM LODs, spatial meshlets, and SIMD BVH4 enabled.
    ///
    /// # Returns
    ///
    /// - `Self` - Default `BlenderBakeConfig`.
    fn default() -> Self {
        Self {
            input: PathBuf::new(),
            out_file: PathBuf::new(),
            blender_bin: None,
            lods: DEFAULT_BLENDER_BAKE_LODS,
            build_meshlets: true,
            bake_bvh4: true,
            plan: false,
        }
    }
}

/// Sensible defaults for `BlenderLiveSyncConfig`.
impl Default for BlenderLiveSyncConfig {
    /// Returns default Live-Link HTTP+SSE daemon settings bound to `127.0.0.1:9877`.
    ///
    /// # Returns
    ///
    /// - `Self` - Default `BlenderLiveSyncConfig`.
    fn default() -> Self {
        Self {
            host: DEFAULT_BLENDER_SYNC_HOST.to_string(),
            port: DEFAULT_BLENDER_SYNC_PORT,
            out_dir: None,
            heartbeat_ms: DEFAULT_BLENDER_HEARTBEAT_MS,
            replay_capacity: DEFAULT_BLENDER_EVENT_REPLAY_CAP,
            max_asset_bytes: DEFAULT_BLENDER_MAX_ASSET_BYTES,
            once: false,
        }
    }
}

/// Sensible defaults for `BlenderWatchConfig`.
impl Default for BlenderWatchConfig {
    /// Returns default watch + Live-Link configuration polling every `350ms` on port `9877`.
    ///
    /// # Returns
    ///
    /// - `Self` - Default `BlenderWatchConfig`.
    fn default() -> Self {
        Self {
            path: PathBuf::from("."),
            out_dir: PathBuf::from("."),
            host: DEFAULT_BLENDER_SYNC_HOST.to_string(),
            port: DEFAULT_BLENDER_SYNC_PORT,
            blender_bin: None,
            poll_ms: DEFAULT_BLENDER_WATCH_POLL_MS,
            lods: DEFAULT_BLENDER_BAKE_LODS,
            once: false,
        }
    }
}

/// Conversion helpers constructing `BlenderNativeBlendSummary` from `euv_core::BlendInspectionReport`.
impl BlenderNativeBlendSummary {
    /// Converts a pure-Rust `BlendInspectionReport` into a JSON-serializable CLI summary.
    ///
    /// # Arguments
    ///
    /// - `&BlendInspectionReport` - Core `.blend` inspection report.
    ///
    /// # Returns
    ///
    /// - `Self` - Serializable CLI summary.
    #[must_use]
    pub fn from_blend_report(report: &BlendInspectionReport) -> Self {
        let compression: &str = match report.get_compression() {
            BlendCompression::None => BLENDER_COMP_NONE,
            BlendCompression::Gzip => BLENDER_COMP_GZIP,
            BlendCompression::Zstd => BLENDER_COMP_ZSTD,
        };
        Self {
            version: report.get_version_string().clone(),
            pointer_size_bytes: report.get_pointer_size_bytes(),
            is_little_endian: report.get_is_little_endian(),
            is_large_header_v5: report.get_is_large_header_v5(),
            compression: compression.to_string(),
            block_count: report.get_block_count(),
            dna_struct_count: report.get_dna_struct_count(),
            scenes: report.get_scenes().clone(),
            collections: report.get_collections().clone(),
            objects: report.get_objects().clone(),
            meshes: report.get_meshes().clone(),
            materials: report.get_materials().clone(),
            cameras: report.get_cameras().clone(),
            lights: report.get_lights().clone(),
            armatures: report.get_armatures().clone(),
            actions: report.get_actions().clone(),
            images: report.get_images().clone(),
            node_trees: report.get_node_trees().clone(),
            warnings: report.get_warnings().clone(),
        }
    }
}

/// Conversion helpers constructing `BlenderSceneSummary` from `euv_core::ImportedScene3D`.
impl BlenderSceneSummary {
    /// Builds a concise CLI inventory summary from an `ImportedScene3D`.
    ///
    /// # Arguments
    ///
    /// - `&ImportedScene3D` - Parsed glTF, GLB, `.euv3d`, or converted OBJ scene.
    ///
    /// # Returns
    ///
    /// - `Self` - Aggregated counts and asset names.
    #[must_use]
    pub fn from_imported_scene(scene: &ImportedScene3D) -> Self {
        let mut total_vertices: usize = 0;
        let mut total_triangles: usize = 0;
        for mesh in scene.get_meshes().iter() {
            total_vertices = total_vertices.saturating_add(mesh.get_vertices().len());
            total_triangles = total_triangles.saturating_add(mesh.get_indices().len());
        }
        let collections: Vec<String> = scene
            .get_scene_graph()
            .get_collections()
            .get_entries()
            .iter()
            .map(|entry: &CollectionEntry3D| entry.get_name().clone())
            .collect();
        let material_names: Vec<String> = scene
            .get_materials()
            .iter()
            .map(|mat: &PrincipledMaterial3D| mat.get_name().clone())
            .collect();
        let animation_names: Vec<String> = scene
            .get_animations()
            .iter()
            .map(|clip: &ImportedAnimationClip3D| clip.get_name().clone())
            .collect();
        Self {
            name: scene.get_name().clone(),
            generator: scene.get_generator().clone(),
            node_count: scene.get_scene_graph().get_nodes().len(),
            collections,
            mesh_count: scene.get_meshes().len(),
            total_vertices,
            total_triangles,
            material_count: scene.get_materials().len(),
            material_names,
            texture_count: scene.get_textures().len(),
            skin_count: scene.get_skins().len(),
            animation_count: scene.get_animations().len(),
            animation_names,
            camera_count: scene.get_cameras().len(),
            light_count: scene.get_lights().len(),
        }
    }
}

/// Shared state management and SSE fan-out methods for `BlenderLiveSyncState`.
#[cfg(feature = "update-server")]
impl BlenderLiveSyncState {
    /// Creates a new concurrent Live-Link state backed by a Hyperlane `SseHub`.
    ///
    /// # Arguments
    ///
    /// - `SseConfig` - SSE heartbeat, retry, and replay configuration.
    /// - `Option<PathBuf>` - Optional directory mirroring hot-swapped binary assets to disk.
    /// - `usize` - Maximum accepted binary asset payload size in bytes.
    /// - `usize` - Maximum replay events retained in memory.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized Live-Link daemon state.
    #[must_use]
    pub fn new(
        sse_config: SseConfig,
        out_dir: Option<PathBuf>,
        max_asset_bytes: usize,
        replay_capacity: usize,
    ) -> Self {
        let sse_hub: SseHub = SseHub::new(sse_config.clone());
        Self {
            sse_hub,
            sse_config,
            out_dir,
            max_asset_bytes: max_asset_bytes.max(1024),
            replay_capacity: replay_capacity.clamp(8, 2048),
            next_seq: AtomicU64::new(0),
            delta_count: AtomicU64::new(0),
            asset_count: AtomicU64::new(0),
            event_log: Mutex::new(Vec::new()),
            assets: RwLock::new(BTreeMap::new()),
            latest_delta: RwLock::new(None),
            running: AtomicBool::new(true),
        }
    }

    /// Returns a reference to the shared Hyperlane `SseHub`.
    ///
    /// # Returns
    ///
    /// - `&SseHub` - Live-Link SSE pub/sub hub.
    #[must_use]
    pub fn sse_hub(&self) -> &SseHub {
        let Self { sse_hub, .. } = self;
        sse_hub
    }

    /// Returns the active SSE heartbeat and retry configuration.
    ///
    /// # Returns
    ///
    /// - `&SseConfig` - Active SSE configuration.
    #[must_use]
    pub fn sse_config(&self) -> &SseConfig {
        let Self { sse_config, .. } = self;
        sse_config
    }

    /// Returns the maximum permitted binary upload size in bytes.
    ///
    /// # Returns
    ///
    /// - `usize` - Maximum payload size in bytes.
    #[must_use]
    pub fn max_asset_bytes(&self) -> usize {
        let Self {
            max_asset_bytes, ..
        } = *self;
        max_asset_bytes
    }

    /// Returns whether the Live-Link daemon is still running.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` while active.
    #[must_use]
    pub fn is_running(&self) -> bool {
        let Self { running, .. } = self;
        running.load(Ordering::Acquire)
    }

    /// Marks the Live-Link daemon as stopped.
    pub fn stop(&self) {
        let Self { running, .. } = self;
        running.store(false, Ordering::Release);
    }

    /// Returns the latest monotonic event sequence number emitted so far.
    ///
    /// # Returns
    ///
    /// - `u64` - Latest sequence number (`0` before any events).
    #[must_use]
    pub fn latest_seq(&self) -> u64 {
        let Self { next_seq, .. } = self;
        next_seq.load(Ordering::Acquire)
    }

    /// Returns total JSON scene deltas accepted since startup.
    ///
    /// # Returns
    ///
    /// - `u64` - Delta counter.
    #[must_use]
    pub fn delta_count(&self) -> u64 {
        let Self { delta_count, .. } = self;
        delta_count.load(Ordering::Acquire)
    }

    /// Returns total binary asset hot-swaps accepted since startup.
    ///
    /// # Returns
    ///
    /// - `u64` - Asset hot-swap counter.
    #[must_use]
    pub fn asset_count(&self) -> u64 {
        let Self { asset_count, .. } = self;
        asset_count.load(Ordering::Acquire)
    }

    /// Returns sorted asset identifiers currently stored in memory.
    ///
    /// # Returns
    ///
    /// - `Vec<String>` - Cached asset identifiers.
    #[must_use]
    pub fn asset_ids(&self) -> Vec<String> {
        let Self { assets, .. } = self;
        assets
            .read()
            .ok()
            .map(
                |guard: RwLockReadGuard<'_, BTreeMap<String, BlenderStoredAsset>>| {
                    guard.keys().cloned().collect()
                },
            )
            .unwrap_or_default()
    }

    /// Retrieves a stored binary asset by identifier.
    ///
    /// # Arguments
    ///
    /// - `&str` - Sanitized asset identifier.
    ///
    /// # Returns
    ///
    /// - `Option<BlenderStoredAsset>` - Cloned asset entry if present.
    #[must_use]
    pub fn get_asset(&self, asset_id: &str) -> Option<BlenderStoredAsset> {
        let Self { assets, .. } = self;
        assets.read().ok().and_then(
            |guard: RwLockReadGuard<'_, BTreeMap<String, BlenderStoredAsset>>| {
                guard.get(asset_id).cloned()
            },
        )
    }

    /// Returns the most recent JSON delta payload received from Blender, if any.
    ///
    /// # Returns
    ///
    /// - `Option<BlenderLiveDeltaPayload>` - Latest delta payload.
    #[must_use]
    pub fn latest_delta(&self) -> Option<BlenderLiveDeltaPayload> {
        let Self { latest_delta, .. } = self;
        latest_delta
            .read()
            .ok()
            .and_then(|guard: RwLockReadGuard<'_, Option<BlenderLiveDeltaPayload>>| guard.clone())
    }

    /// Returns buffered replay events strictly newer than `cursor`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Last sequence number already observed by the SSE client.
    ///
    /// # Returns
    ///
    /// - `Vec<BlenderLiveEventRecord>` - Ordered replay event records.
    #[must_use]
    pub fn events_after(&self, cursor: u64) -> Vec<BlenderLiveEventRecord> {
        let Self { event_log, .. } = self;
        event_log
            .lock()
            .ok()
            .map(|guard: MutexGuard<'_, Vec<BlenderLiveEventRecord>>| {
                guard
                    .iter()
                    .filter(|rec: &&BlenderLiveEventRecord| rec.get_seq() > cursor)
                    .cloned()
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Records a JSON scene delta, appends it to the replay log, and broadcasts a `blender.delta` SSE event.
    ///
    /// # Arguments
    ///
    /// - `BlenderLiveDeltaPayload` - Parsed Blender transform/camera/light/material/morph delta.
    ///
    /// # Returns
    ///
    /// - `io::Result<BlenderLiveEventRecord>` - Recorded SSE envelope.
    pub fn record_delta(
        &self,
        payload: BlenderLiveDeltaPayload,
    ) -> io::Result<BlenderLiveEventRecord> {
        let Self {
            sse_hub,
            replay_capacity,
            next_seq,
            delta_count,
            event_log,
            latest_delta,
            ..
        } = self;
        let seq: u64 = next_seq.fetch_add(1, Ordering::AcqRel) + 1;
        let _: u64 = delta_count.fetch_add(1, Ordering::AcqRel);
        if let Ok(mut guard) = latest_delta.write() {
            *guard = Some(payload.clone());
        }
        let delta_json: String =
            to_string(&payload).map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
        let wrapped_json: String =
            format!("{{\"seq\":{seq},\"kind\":\"delta\",\"delta\":{delta_json}}}");
        let record: BlenderLiveEventRecord = BlenderLiveEventRecord::new(
            seq,
            BlenderLiveEventKind::Delta,
            BLENDER_SSE_EVENT_DELTA.to_string(),
            wrapped_json.clone(),
        );
        if let Ok(mut log_guard) = event_log.lock() {
            log_guard.push(record.clone());
            if log_guard.len() > *replay_capacity {
                let overflow: usize = log_guard.len() - *replay_capacity;
                let _: Vec<BlenderLiveEventRecord> = log_guard.drain(0..overflow).collect();
            }
        }
        let sse_event: SseEvent = SseEvent::new(wrapped_json)
            .with_id(seq.to_string())
            .with_event(BLENDER_SSE_EVENT_DELTA);
        let _: Result<u64, SseError> = sse_hub.publish(BLENDER_LIVE_SSE_TOPIC, sse_event);
        Ok(record)
    }

    /// Validates, caches, optionally persists, and broadcasts a hot-swapped binary `.glb` or `.euv3d` asset.
    ///
    /// # Arguments
    ///
    /// - `&str` - Sanitized asset identifier (`{id}`).
    /// - `Vec<u8>` - Raw `.glb`, `.gltf`, or `.euv3d` binary payload.
    ///
    /// # Returns
    ///
    /// - `io::Result<BlenderLiveAssetNotice>` - Verified asset notice broadcast over SSE.
    pub fn record_asset(
        &self,
        asset_id: &str,
        bytes: Vec<u8>,
    ) -> io::Result<BlenderLiveAssetNotice> {
        let Self {
            sse_hub,
            out_dir,
            max_asset_bytes,
            replay_capacity,
            next_seq,
            asset_count,
            event_log,
            assets,
            ..
        } = self;
        validate_blender_asset_id(asset_id)?;
        if bytes.is_empty() {
            return Err(Error::new(ErrorKind::InvalidInput, ERR_BLENDER_EMPTY_ASSET));
        }
        if bytes.len() > *max_asset_bytes {
            return Err(Error::new(
                ErrorKind::InvalidData,
                BLENDER_ERR_PAYLOAD_TOO_LARGE,
            ));
        }
        let (format, mesh_count, triangle_count): (BlenderAssetFormat, usize, usize) =
            validate_live_asset_payload(&bytes)?;
        let disk_path: Option<String> = if let Some(dir) = out_dir.as_ref() {
            let ext: &str = format.as_str();
            let target: PathBuf = dir.join(format!("{asset_id}.{ext}"));
            atomic_write_synced(&target, &bytes)?;
            Some(target.display().to_string())
        } else {
            None
        };
        let seq: u64 = next_seq.fetch_add(1, Ordering::AcqRel) + 1;
        let _: u64 = asset_count.fetch_add(1, Ordering::AcqRel);
        let sha256: String = sha256_hex(&bytes);
        let notice: BlenderLiveAssetNotice = BlenderLiveAssetNotice {
            seq,
            asset_id: asset_id.to_string(),
            format,
            size_bytes: bytes.len(),
            sha256,
            mesh_count,
            triangle_count,
            asset_url: format!("/blender/asset/{asset_id}"),
            disk_path,
        };
        if let Ok(mut map_guard) = assets.write() {
            let _: Option<BlenderStoredAsset> = map_guard.insert(
                asset_id.to_string(),
                BlenderStoredAsset {
                    notice: notice.clone(),
                    bytes,
                },
            );
        }
        let notice_json: String =
            to_string(&notice).map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
        let record: BlenderLiveEventRecord = BlenderLiveEventRecord::new(
            seq,
            BlenderLiveEventKind::Asset,
            BLENDER_SSE_EVENT_ASSET.to_string(),
            notice_json.clone(),
        );
        if let Ok(mut log_guard) = event_log.lock() {
            log_guard.push(record);
            if log_guard.len() > *replay_capacity {
                let overflow: usize = log_guard.len() - *replay_capacity;
                let _: Vec<BlenderLiveEventRecord> = log_guard.drain(0..overflow).collect();
            }
        }
        let sse_event: SseEvent = SseEvent::new(notice_json)
            .with_id(seq.to_string())
            .with_event(BLENDER_SSE_EVENT_ASSET);
        let _: Result<u64, SseError> = sse_hub.publish(BLENDER_LIVE_SSE_TOPIC, sse_event);
        Ok(notice)
    }

    /// Builds a machine-readable status report for this Live-Link server bound at `base_url`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Base HTTP URL (`http://host:port`).
    /// - `bool` - Whether the command ran in `--once` smoke mode.
    ///
    /// # Returns
    ///
    /// - `BlenderLiveSyncReport` - Snapshot of routes, counters, and cached asset IDs.
    #[must_use]
    pub fn build_report(&self, base_url: &str, once: bool) -> BlenderLiveSyncReport {
        BlenderLiveSyncReport {
            url: base_url.to_string(),
            delta_url: format!("{base_url}{BLENDER_ROUTE_DELTA}"),
            asset_url: format!("{base_url}{BLENDER_ROUTE_ASSET}"),
            events_url: format!("{base_url}{BLENDER_ROUTE_EVENTS}"),
            status_url: format!("{base_url}{BLENDER_ROUTE_STATUS}"),
            latest_seq: self.latest_seq(),
            delta_count: self.delta_count(),
            asset_count: self.asset_count(),
            asset_ids: self.asset_ids(),
            once,
        }
    }
}

/// Lifecycle control methods on `BlenderLiveSyncHandle`.
#[cfg(feature = "update-server")]
impl BlenderLiveSyncHandle {
    /// Returns the concrete bound `SocketAddr` of the running Hyperlane Live-Link daemon.
    ///
    /// # Returns
    ///
    /// - `SocketAddr` - Bound TCP socket address.
    #[must_use]
    pub fn address(&self) -> SocketAddr {
        let Self { address, .. } = *self;
        address
    }

    /// Returns the base HTTP URL (`http://host:port`) of this Live-Link server.
    ///
    /// # Returns
    ///
    /// - `String` - Base HTTP URL.
    #[must_use]
    pub fn url(&self) -> String {
        format!("http://{}", self.address())
    }

    /// Returns a reference to the shared `BlenderLiveSyncState`.
    ///
    /// # Returns
    ///
    /// - `&Arc<BlenderLiveSyncState>` - Shared Live-Link state.
    #[must_use]
    pub fn state(&self) -> &Arc<BlenderLiveSyncState> {
        let Self { state, .. } = self;
        state
    }

    /// Returns whether this Live-Link server is currently running.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` while active.
    #[must_use]
    pub fn is_running(&self) -> bool {
        let Self { state, .. } = self;
        state.is_running()
    }

    /// Produces a machine-readable `BlenderLiveSyncReport` for this live server handle.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether this invocation runs in `--once` validation mode.
    ///
    /// # Returns
    ///
    /// - `BlenderLiveSyncReport` - Active Live-Link report.
    #[must_use]
    pub fn report(&self, once: bool) -> BlenderLiveSyncReport {
        let base_url: String = self.url();
        self.state().build_report(&base_url, once)
    }

    /// Cleanly stops the Hyperlane Live-Link listener, unregisters its address, and shuts down the Tokio runtime.
    pub fn shutdown(&mut self) {
        let Self {
            address,
            state,
            control,
            runtime,
        } = self;
        state.stop();
        unregister_blender_live_sync_state(*address);
        if let Some(ctrl) = control.take()
            && let Some(rt) = runtime.as_ref()
        {
            rt.block_on(async move {
                ctrl.shutdown().await;
            });
        }
        if let Some(rt) = runtime.take() {
            rt.shutdown_timeout(Duration::from_millis(250));
        }
    }
}

/// Automatic listener cleanup when `BlenderLiveSyncHandle` is dropped.
#[cfg(feature = "update-server")]
impl Drop for BlenderLiveSyncHandle {
    /// Stops the Live-Link Hyperlane listener cleanly on drop.
    fn drop(&mut self) {
        self.shutdown();
    }
}

/// Hyperlane `ServerHook` ingesting JSON scene deltas at `POST /blender/delta`.
#[cfg(feature = "update-server")]
impl ServerHook for BlenderDeltaRouteHook {
    /// Constructs a stateless `BlenderDeltaRouteHook`.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Incoming client stream.
    /// - `&mut Context` - Active Hyperlane request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Validates incoming JSON delta payloads and broadcasts `blender.delta` SSE frames.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Active client stream.
    /// - `&mut Context` - Active Hyperlane request context.
    ///
    /// # Returns
    ///
    /// - `Status` - Request lifecycle status.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        if ctx.get_request().get_method().is_options() {
            return send_hyperlane_bytes(stream, ctx, 204, BLENDER_MIME_JSON, Vec::new()).await;
        }
        if !ctx.get_request().get_method().is_post() {
            return send_hyperlane_bytes(
                stream,
                ctx,
                405,
                BLENDER_MIME_JSON,
                BLENDER_ERR_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
            )
            .await;
        }
        let Some(state) = resolve_blender_live_sync_state(stream) else {
            return send_hyperlane_bytes(
                stream,
                ctx,
                503,
                BLENDER_MIME_JSON,
                BLENDER_ERR_UNCONFIGURED.as_bytes().to_vec(),
            )
            .await;
        };
        let raw_body: String = ctx.get_request().get_body_string();
        let Ok(payload) = from_str::<BlenderLiveDeltaPayload>(&raw_body) else {
            return send_hyperlane_bytes(
                stream,
                ctx,
                400,
                BLENDER_MIME_JSON,
                BLENDER_ERR_BAD_REQUEST.as_bytes().to_vec(),
            )
            .await;
        };
        match state.record_delta(payload) {
            Ok(rec) => {
                let body: String = format!(
                    "{{\"ok\":true,\"seq\":{},\"kind\":\"delta\"}}",
                    rec.get_seq()
                );
                let _: &mut Response = ctx
                    .get_mut_response()
                    .set_header(CACHE_CONTROL, BLENDER_CACHE_NO_CACHE);
                send_hyperlane_bytes(stream, ctx, 200, BLENDER_MIME_JSON, body.into_bytes()).await
            }
            Err(_) => {
                send_hyperlane_bytes(
                    stream,
                    ctx,
                    400,
                    BLENDER_MIME_JSON,
                    BLENDER_ERR_BAD_REQUEST.as_bytes().to_vec(),
                )
                .await
            }
        }
    }
}

/// Hyperlane `ServerHook` handling binary `.glb`/`.euv3d` hot-swaps (`POST`) and fetches (`GET`/`HEAD`) at `/blender/asset/{id}`.
#[cfg(feature = "update-server")]
impl ServerHook for BlenderAssetRouteHook {
    /// Constructs a stateless `BlenderAssetRouteHook`.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Incoming client stream.
    /// - `&mut Context` - Active Hyperlane request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Stores uploaded `.glb`/`.euv3d` binaries (`POST`) or serves the latest cached asset (`GET`/`HEAD`).
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Active client stream.
    /// - `&mut Context` - Active Hyperlane request context.
    ///
    /// # Returns
    ///
    /// - `Status` - Request lifecycle status.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        if ctx.get_request().get_method().is_options() {
            return send_hyperlane_bytes(stream, ctx, 204, BLENDER_MIME_JSON, Vec::new()).await;
        }
        let Some(state) = resolve_blender_live_sync_state(stream) else {
            return send_hyperlane_bytes(
                stream,
                ctx,
                503,
                BLENDER_MIME_JSON,
                BLENDER_ERR_UNCONFIGURED.as_bytes().to_vec(),
            )
            .await;
        };
        let Some(asset_id) = ctx.try_get_route_param(BLENDER_ROUTE_PARAM_ID) else {
            return send_hyperlane_bytes(
                stream,
                ctx,
                400,
                BLENDER_MIME_JSON,
                BLENDER_ERR_BAD_REQUEST.as_bytes().to_vec(),
            )
            .await;
        };
        if validate_blender_asset_id(&asset_id).is_err() {
            return send_hyperlane_bytes(
                stream,
                ctx,
                400,
                BLENDER_MIME_JSON,
                BLENDER_ERR_BAD_REQUEST.as_bytes().to_vec(),
            )
            .await;
        }
        if ctx.get_request().get_method().is_post() {
            let body: Vec<u8> = ctx.get_request().get_body().clone();
            if body.len() > state.max_asset_bytes() {
                return send_hyperlane_bytes(
                    stream,
                    ctx,
                    413,
                    BLENDER_MIME_JSON,
                    BLENDER_ERR_PAYLOAD_TOO_LARGE.as_bytes().to_vec(),
                )
                .await;
            }
            return match state.record_asset(&asset_id, body) {
                Ok(notice) => {
                    let encoded: Vec<u8> = to_vec(&notice).unwrap_or_default();
                    let _: &mut Response = ctx
                        .get_mut_response()
                        .set_header(CACHE_CONTROL, BLENDER_CACHE_NO_CACHE);
                    send_hyperlane_bytes(stream, ctx, 200, BLENDER_MIME_JSON, encoded).await
                }
                Err(_) => {
                    send_hyperlane_bytes(
                        stream,
                        ctx,
                        400,
                        BLENDER_MIME_JSON,
                        BLENDER_ERR_BAD_REQUEST.as_bytes().to_vec(),
                    )
                    .await
                }
            };
        }
        let is_read: bool = {
            let method: &Method = ctx.get_request().get_method();
            method.is_get() || method.is_head()
        };
        if !is_read {
            return send_hyperlane_bytes(
                stream,
                ctx,
                405,
                BLENDER_MIME_JSON,
                BLENDER_ERR_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
            )
            .await;
        }
        let Some(stored) = state.get_asset(&asset_id) else {
            return send_hyperlane_bytes(
                stream,
                ctx,
                404,
                BLENDER_MIME_JSON,
                BLENDER_ERR_NOT_FOUND.as_bytes().to_vec(),
            )
            .await;
        };
        let mime: &str = match stored.get_notice().get_format() {
            BlenderAssetFormat::Glb => BLENDER_MIME_GLB,
            BlenderAssetFormat::Gltf => BLENDER_MIME_JSON,
            _ => BLENDER_MIME_OCTET,
        };
        let etag: String = format!("\"{}\"", stored.get_notice().get_sha256());
        let _: &mut Response = ctx
            .get_mut_response()
            .set_header(CACHE_CONTROL, BLENDER_CACHE_NO_CACHE)
            .set_header(BLENDER_HDR_ETAG, etag);
        send_hyperlane_bytes(stream, ctx, 200, mime, stored.get_bytes().clone()).await
    }
}

/// Hyperlane `ServerHook` streaming `blender.delta` and `blender.asset` SSE events at `GET /blender/events`.
#[cfg(feature = "update-server")]
impl ServerHook for BlenderEventsRouteHook {
    /// Constructs a stateless `BlenderEventsRouteHook`.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Incoming client stream.
    /// - `&mut Context` - Active Hyperlane request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Streams `Last-Event-ID` replay frames followed by live Blender Live-Link SSE notifications.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Long-lived client SSE stream.
    /// - `&mut Context` - Active Hyperlane request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Reject` after closing stream cleanly.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        if ctx.get_request().get_method().is_options() {
            return send_hyperlane_bytes(stream, ctx, 204, BLENDER_MIME_JSON, Vec::new()).await;
        }
        if !ctx.get_request().get_method().is_get() {
            return send_hyperlane_bytes(
                stream,
                ctx,
                405,
                BLENDER_MIME_JSON,
                BLENDER_ERR_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
            )
            .await;
        }
        let Some(state) = resolve_blender_live_sync_state(stream) else {
            return send_hyperlane_bytes(
                stream,
                ctx,
                503,
                BLENDER_MIME_JSON,
                BLENDER_ERR_UNCONFIGURED.as_bytes().to_vec(),
            )
            .await;
        };
        let last_event_id: Option<String> = ctx
            .get_request()
            .try_get_header_front(BLENDER_HDR_LAST_EVENT_ID)
            .or_else(|| {
                ctx.get_request()
                    .try_get_query_front(BLENDER_QUERY_LAST_EVENT_ID)
            });
        let Ok(subscription) = state.sse_hub().subscribe(BLENDER_LIVE_SSE_TOPIC, None) else {
            return send_hyperlane_bytes(
                stream,
                ctx,
                503,
                BLENDER_MIME_JSON,
                BLENDER_ERR_UNCONFIGURED.as_bytes().to_vec(),
            )
            .await;
        };
        let replay: Vec<BlenderLiveEventRecord> = match last_event_id
            .as_deref()
            .and_then(|raw: &str| raw.trim().parse::<u64>().ok())
        {
            Some(cursor) => state.events_after(cursor),
            None => Vec::new(),
        };
        let _: Result<(), SseError> =
            serve_blender_sse_stream(stream, ctx, replay, subscription, state.sse_config()).await;
        stream.set_closed(true);
        Status::Reject
    }
}

/// Hyperlane `ServerHook` serving JSON Live-Link status diagnostics at `GET /blender/status` and `GET /healthz`.
#[cfg(feature = "update-server")]
impl ServerHook for BlenderStatusRouteHook {
    /// Constructs a stateless `BlenderStatusRouteHook`.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Incoming client stream.
    /// - `&mut Context` - Active Hyperlane request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Serves a JSON snapshot of active Live-Link endpoints, event counters, and cached asset IDs.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Active client stream.
    /// - `&mut Context` - Active Hyperlane request context.
    ///
    /// # Returns
    ///
    /// - `Status` - Request lifecycle status.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        if ctx.get_request().get_method().is_options() {
            return send_hyperlane_bytes(stream, ctx, 204, BLENDER_MIME_JSON, Vec::new()).await;
        }
        let method_ok: bool = {
            let method: &Method = ctx.get_request().get_method();
            method.is_get() || method.is_head()
        };
        if !method_ok {
            return send_hyperlane_bytes(
                stream,
                ctx,
                405,
                BLENDER_MIME_JSON,
                BLENDER_ERR_METHOD_NOT_ALLOWED.as_bytes().to_vec(),
            )
            .await;
        }
        let Some(state) = resolve_blender_live_sync_state(stream) else {
            return send_hyperlane_bytes(
                stream,
                ctx,
                503,
                BLENDER_MIME_JSON,
                BLENDER_ERR_UNCONFIGURED.as_bytes().to_vec(),
            )
            .await;
        };
        let base_url: String = stream
            .get_local_addr()
            .map(|addr: SocketAddr| format!("http://{addr}"))
            .unwrap_or_else(|_| {
                format!("http://{DEFAULT_BLENDER_SYNC_HOST}:{DEFAULT_BLENDER_SYNC_PORT}")
            });
        let report: BlenderLiveSyncReport = state.build_report(&base_url, false);
        let payload: Vec<u8> = to_vec(&report).unwrap_or_default();
        let _: &mut Response = ctx
            .get_mut_response()
            .set_header(CACHE_CONTROL, BLENDER_CACHE_NO_CACHE);
        send_hyperlane_bytes(stream, ctx, 200, BLENDER_MIME_JSON, payload).await
    }
}