unity-assetdb 0.2.0

Unity asset GUID → name index baker. Walks Assets/, parses .meta and asset YAML, writes a compact bincode database.
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
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
//! Bake orchestrator: walk → parse → cache → write.
//!
//! Per-file flow:
//! 1. Stat `.meta` and the companion asset file. If both mtimes match the
//!    cached values → reuse cached entry, skip parse.
//! 2. Else read `.meta` → guid + sprite-sheet sub-assets.
//! 3. Read the asset file → top-level class ID + sub-asset rows.
//! 4. Resolve `AssetType`: native `class_id` or `Script(script_guid)`.
//! 5. Derive alias from the filename stem.
//!
//! Post-walk: alias-collision sweep (filename stems can clash; we suffix
//! with parent dir on conflict and warn).

use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc;
use std::time::{Instant, SystemTime};

use ahash::{AHashMap, AHashSet};

use anyhow::{Context, Result};

use crate::asset;
use crate::class_id::{ClassId, class_from_ext};
use crate::meta::{self, SPRITE_MODE_SINGLE, TEXTURE_TYPE_SPRITE};
use crate::store::{
    self, AssetDb, AssetEntry, AssetType, BakeCache, CachedAssetType, CachedEntry, StoreError,
    SubAsset, CACHE_FILENAME, DB_FILENAME,
};
use crate::walk::{walk_meta_files, WalkError};

/// Errors from a bake run.
///
/// `Store(StoreError)` and `Walk(WalkError)` surface the typed source
/// errors from those modules — match on them when you need to
/// distinguish (e.g. "is this a schema-mismatch that needs re-bake?").
/// `Other` carries the remaining anyhow-chained errors (cache I/O,
/// dedup hard-fails, duplicate-guid checks) — most consumers propagate
/// these untouched.
#[derive(Debug, thiserror::Error)]
pub enum BakeError {
    #[error("{0}")]
    Store(#[from] StoreError),
    #[error("{0}")]
    Walk(#[from] WalkError),
    #[error("{0}")]
    Other(#[from] anyhow::Error),
}

/// Caller-supplied name sanitizer. Returns `Some(rewritten)` when the
/// input contains characters the consumer wants to scrub from asset
/// names; `None` to keep the input as-is. Bake calls this once per
/// top-level filename stem and once per sub-asset YAML `m_Name`.
///
/// Bound is `Send + Sync + 'static` because [`BakeOptions`] flows into
/// `ignore::WalkParallel` worker closures.
///
/// Default behavior (no sanitizer) leaves all names verbatim.
pub type NameSanitizer = Box<dyn Fn(&str) -> Option<String> + Send + Sync + 'static>;

/// Caller-supplied warning sink. Bake invokes this for non-fatal events
/// (worker errors during the parallel walk, name-collision rewrites,
/// sanitizer rewrites). The library never writes to stderr itself.
pub type WarnSink = Box<dyn Fn(&str) + Send + Sync + 'static>;

/// Caller-supplied progress sink. Bake invokes this with the post-bake
/// summary line and (when `BakeOptions::verbose_timing` is true) with
/// per-phase timing. Separate from [`WarnSink`] so consumers can route
/// "info" output and warnings to different places.
pub type ProgressSink = Box<dyn Fn(&str) + Send + Sync + 'static>;

/// Borrowed view of a [`NameSanitizer`] for internal helpers. Kept as a
/// named type so per-call signatures don't trip clippy's `type_complexity`.
type NameSanitizerRef<'a> = &'a (dyn Fn(&str) -> Option<String> + Send + Sync);

/// Borrowed view of a [`WarnSink`]. See [`NameSanitizerRef`].
type WarnSinkRef<'a> = &'a (dyn Fn(&str) + Send + Sync);

/// File extensions whose asset has embedded sub-asset docs that should
/// NOT join the global dedup pool — they live in the parent's namespace
/// and consumers resolve them via parent-scoped addressing (`$Sub@Parent`).
///
/// Extension-keyed rather than `AssetType`-keyed because the top doc of a
/// `.playable` file is whichever sub-doc Unity sorts first by hashed fileID
/// (often an `AnimationTrack`, not the `TimelineAsset` itself), so the
/// resulting `AssetTypeRaw::Script(...)` carries an unstable script guid.
/// The extension is the only stable container discriminator.
const EMBEDDED_CONTAINER_EXTS: &[&str] = &["prefab", "controller", "anim", "mixer", "playable"];

fn is_embedded_container(hint: &str) -> bool {
    Path::new(hint)
        .extension()
        .and_then(|s| s.to_str())
        .is_some_and(|ext| EMBEDDED_CONTAINER_EXTS.contains(&ext))
}

/// True when `class_id` is a structural sub-doc that should be filtered
/// out at parse time for the given container extension.
///
/// `.prefab`: GO / Transform / RectTransform / MonoBehaviour are all
/// part of the GameObject tree — never addressable as sub-assets.
/// `.controller` / `.anim` / `.mixer` / `.playable`: MonoBehaviour-114
/// docs ARE addressable sub-assets (Timeline tracks, AudioMixerGroup,
/// etc.) — only filter the GO-tree triplet, which doesn't appear in
/// these files anyway (the predicate is a no-op there but stays valid
/// for future-proofing).
fn is_filterable_subdoc_for_ext(class_id: u32, ext: &str) -> bool {
    let cls = ClassId::from_raw(class_id);
    let is_go_tree = matches!(
        cls,
        Some(ClassId::GameObject | ClassId::Transform | ClassId::RectTransform)
    );
    let is_component = matches!(cls, Some(ClassId::MonoBehaviour));
    is_go_tree || (is_component && ext == "prefab")
}

/// Convert `SystemTime` → ns-since-UNIX. Saturates to 0 on pre-epoch
/// (which would only happen if the user's clock is bogus).
fn mtime_ns(t: SystemTime) -> u64 {
    t.duration_since(SystemTime::UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos() as u64)
}

/// One raw bake result, before name dedup. `script_guid` is the unmapped
/// GUID for MonoBehaviour assets — interning happens after the walk so we
/// only need one final sort.
#[derive(Clone)]
struct RawEntry {
    guid: u128,
    asset_type_raw: AssetTypeRaw,
    hint: String,
    name: String,
    meta_mtime_ns: u64,
    asset_mtime_ns: u64,
    sub_assets: Vec<SubAsset>,
}

/// Hashable type discriminator: `Native(classID)` for built-in classes
/// and `Script(scriptGuid)` for MonoBehaviour-backed assets. Hashable so
/// the dedup pass can bucket by `(name, asset_type)` without depending
/// on the post-walk script-intern table.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum AssetTypeRaw {
    Native(u32),
    Script(u128),
}

/// Per-worker-thread accumulator. Sends its collected `entries` + `errors`
/// to the main thread via Drop — `ignore::WalkBuilder::run` drops each
/// thread's visitor closure (and thus its captured `ThreadLocal`) on
/// thread exit, so the main thread sees all batches once `walker.run`
/// returns.
struct ThreadLocal {
    entries: Vec<RawEntry>,
    errors: Vec<String>,
    raw_tx: mpsc::Sender<Vec<RawEntry>>,
    err_tx: mpsc::Sender<Vec<String>>,
}

impl Drop for ThreadLocal {
    fn drop(&mut self) {
        let entries = std::mem::take(&mut self.entries);
        let errors = std::mem::take(&mut self.errors);
        // Channel-closed errors are unreachable here — main thread holds
        // the receivers until after `walker.run` returns.
        let _ = self.raw_tx.send(entries);
        let _ = self.err_tx.send(errors);
    }
}

/// Cache key: hint (Assets-relative, forward-slashed). ahash beats siphash
/// by ~2x for our small-string keys.
type CacheMap = AHashMap<String, RawEntry>;

/// Run a `Result<Option<T>>`-producing closure under `catch_unwind` and
/// flatten the four-way outcome (success-with-value / success-skip /
/// inner-err / panic) into `Result<Option<T>, String>`. The closure
/// is wrapped in `AssertUnwindSafe` because parallel-walk visitors
/// capture Arc state by ref, and the bake worker treats process_one
/// as panic-safe on its inputs.
///
/// `label` prefixes both inner errors and panic reports with the
/// asset path; `task_name` names the operation in the panic line
/// (e.g. `"process_one"`) so the message reads
/// `"<path>: panic in <task_name>: <payload>"`.
///
/// Pulled out of the inline closure inside `bake_action`'s parallel
/// walk so panic-payload extraction (string / String / non-string)
/// can be unit-tested without spinning up a project tree.
fn run_with_panic_safety<T, F>(label: &str, task_name: &str, f: F) -> Result<Option<T>, String>
where
    F: FnOnce() -> Result<Option<T>>,
{
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
        Ok(Ok(opt)) => Ok(opt),
        Ok(Err(e)) => Err(format!("{label}: {e}")),
        Err(panic) => {
            let msg = panic
                .downcast_ref::<&str>()
                .map(|s| (*s).to_string())
                .or_else(|| panic.downcast_ref::<String>().cloned())
                .unwrap_or_else(|| "<non-string panic payload>".to_string());
            Err(format!("{label}: panic in {task_name}: {msg}"))
        }
    }
}

/// Build the in-memory cache from a previously-saved `BakeCache`. Each
/// `CachedEntry` becomes a `RawEntry` keyed by its hint. Cache hits during
/// the walk drop straight into the post-walk pipeline.
///
/// `String::from(Box<str>)` is O(1) — Rust hands the heap allocation
/// directly from the box to the new String, no copy. The map key is then
/// cloned once for the parallel field on `RawEntry` (one alloc per entry).
fn build_cache(cache: BakeCache) -> CacheMap {
    let mut out = AHashMap::with_capacity(cache.entries.len());
    for e in cache.entries {
        let asset_type_raw = match e.asset_type {
            CachedAssetType::Native(n) => AssetTypeRaw::Native(n),
            CachedAssetType::Script(g) => AssetTypeRaw::Script(g),
        };
        let hint = String::from(e.hint);
        let raw = RawEntry {
            guid: e.guid,
            asset_type_raw,
            hint: hint.clone(),
            name: String::new(), // re-derived in build_db
            meta_mtime_ns: e.meta_mtime_ns,
            asset_mtime_ns: e.asset_mtime_ns,
            sub_assets: e.sub_assets,
        };
        out.insert(hint, raw);
    }
    out
}

/// Build the on-disk cache from the post-walk raw entries. Sorted by hint
/// so the file is byte-stable across re-bakes when nothing changed.
fn build_bake_cache(raw: &[RawEntry]) -> BakeCache {
    let mut entries: Vec<CachedEntry> = raw
        .iter()
        .map(|r| CachedEntry {
            hint: r.hint.clone().into_boxed_str(),
            meta_mtime_ns: r.meta_mtime_ns,
            asset_mtime_ns: r.asset_mtime_ns,
            guid: r.guid,
            asset_type: match r.asset_type_raw {
                AssetTypeRaw::Native(n) => CachedAssetType::Native(n),
                AssetTypeRaw::Script(g) => CachedAssetType::Script(g),
            },
            sub_assets: r.sub_assets.clone(),
        })
        .collect();
    entries.sort_by(|a, b| a.hint.cmp(&b.hint));
    BakeCache {
        schema_version: store::SCHEMA_VERSION,
        entries,
    }
}

/// Caller-supplied bake configuration.
///
/// Built by the consumer's CLI / library entry point and handed to
/// [`bake`]. The library never reads env vars, never resolves the
/// project root for you, and never writes to stderr — every side
/// channel routes through one of the optional sinks below.
pub struct BakeOptions {
    /// Project root containing `Assets/` + `ProjectSettings/`. Caller
    /// resolves this (typically via [`crate::walk::resolve_project_root`])
    /// before constructing options.
    pub project_root: PathBuf,
    /// Directory where `asset-db.bin` and `asset-db.cache.bin` are written.
    /// Caller composes the convention (e.g. `<project>/Library/unity-assetdb/`
    /// or a fixture-staging path).
    pub out_dir: PathBuf,
    /// Optional name sanitizer; see [`NameSanitizer`].
    pub name_sanitizer: Option<NameSanitizer>,
    /// Optional warning sink; see [`WarnSink`]. `None` discards warnings.
    pub on_warn: Option<WarnSink>,
    /// Optional progress sink; see [`ProgressSink`]. `None` discards the
    /// summary line.
    pub on_progress: Option<ProgressSink>,
    /// When true, [`on_progress`] also receives a per-phase timing line
    /// (cache / walk / build / write). Env-var-driven behavior is the
    /// consumer's call.
    pub verbose_timing: bool,
    /// When true, [`on_warn`] receives a line for each name-collision
    /// rewrite during dedup. Off by default to keep steady-state warm
    /// bakes quiet.
    pub verbose_collisions: bool,
}

/// Bake entry-point. Walks `Assets/`, parses `.meta` + asset YAML,
/// writes `<out_dir>/asset-db.bin` and `<out_dir>/asset-db.cache.bin`.
pub fn bake(opts: &BakeOptions) -> Result<(), BakeError> {
    bake_inner(opts).map_err(|e| {
        // Surface typed source errors when they bubbled up via `?`
        // without context wrapping — consumers can match on
        // `BakeError::Store` etc. Otherwise fall through to `Other`.
        match e.downcast::<StoreError>() {
            Ok(s) => return BakeError::Store(s),
            Err(e) => match e.downcast::<WalkError>() {
                Ok(w) => return BakeError::Walk(w),
                Err(e) => BakeError::Other(e),
            },
        }
    })
}

fn bake_inner(opts: &BakeOptions) -> Result<()> {
    let project_root = &opts.project_root;
    std::fs::create_dir_all(&opts.out_dir)
        .with_context(|| format!("create out-dir: {}", opts.out_dir.display()))?;
    let db_file = opts.out_dir.join(DB_FILENAME);
    let cache_file = opts.out_dir.join(CACHE_FILENAME);
    let t_start = Instant::now();

    // Load bake-only cache. Missing/corrupt → empty (first bake or stale).
    let cache: CacheMap = match store::read_cache(&cache_file) {
        Ok(c) => build_cache(c),
        Err(_) => AHashMap::new(),
    };
    let cache_size = cache.len();
    let t_cache = t_start.elapsed();

    // Per-thread accumulators: each worker drops its `Vec<RawEntry>` and
    // `Vec<String>` (errors) into channels at thread exit via `Drop`. Avoids
    // the Mutex<Vec> contention 16k pushes on 8 cores produced — measured
    // ~3-4 ms warm savings on meow-tower.
    //
    // `ignore::WalkParallel::run` requires `'static + Send` visitors, so
    // shared state goes through `Arc`. Each worker clones the Arc once at
    // factory time — the clone cost is negligible vs the per-entry work.
    let (raw_tx, raw_rx) = mpsc::channel::<Vec<RawEntry>>();
    let (err_tx, err_rx) = mpsc::channel::<Vec<String>>();
    let cache_arc = Arc::new(cache);
    let cache_hits = Arc::new(AtomicUsize::new(0));
    let walked = Arc::new(AtomicUsize::new(0));
    let project_root_arc: Arc<PathBuf> = Arc::new(project_root.clone());

    walk_meta_files(project_root, || {
        let raw_tx = raw_tx.clone();
        let err_tx = err_tx.clone();
        let cache = Arc::clone(&cache_arc);
        let cache_hits = Arc::clone(&cache_hits);
        let walked = Arc::clone(&walked);
        let project_root = Arc::clone(&project_root_arc);
        let mut local = ThreadLocal {
            entries: Vec::with_capacity(2048),
            errors: Vec::new(),
            raw_tx,
            err_tx,
        };
        move |meta_path: &Path| {
            walked.fetch_add(1, Ordering::Relaxed);
            // Catch panics so a single malformed .meta or unforeseen
            // bug doesn't silently terminate the worker thread (which
            // would lose its ThreadLocal accumulator). `ignore::WalkParallel`
            // doesn't propagate visitor panics; without this, a panic in
            // `process_one` produces a partial DB with no surfaced error.
            // Helper does the catch_unwind + payload-downcast — see
            // `run_with_panic_safety`.
            let label = meta_path.display().to_string();
            match run_with_panic_safety(&label, "process_one", || {
                process_one(meta_path, &project_root, &cache, &cache_hits)
            }) {
                Ok(Some(r)) => local.entries.push(r),
                Ok(None) => {}
                Err(msg) => local.errors.push(msg),
            }
        }
    })?;
    drop(raw_tx);
    drop(err_tx);
    let t_walk = t_start.elapsed();

    let mut errors: Vec<String> = Vec::new();
    for v in err_rx.iter() {
        errors.extend(v);
    }
    if let Some(sink) = opts.on_warn.as_ref() {
        for e in &errors {
            sink(&format!("warning: {e}"));
        }
    }

    let mut raw: Vec<RawEntry> = Vec::with_capacity(cache_size + 256);
    for v in raw_rx.iter() {
        raw.extend(v);
    }
    // Build cache from `raw` (consumes nothing) before `build_db` consumes
    // it. Sequence the writes so the cache is only persisted after the
    // convert artifact lands — a half-baked cache without a matching db
    // would let a later run skip parsing for entries that aren't in the
    // db yet.
    let bake_cache = build_bake_cache(&raw);
    let db = build_db(
        raw,
        opts.name_sanitizer.as_deref(),
        opts.on_warn.as_deref(),
        opts.verbose_collisions,
    )?;
    let t_build = t_start.elapsed();

    // No-op skip: every entry came from cache AND nothing was dropped from
    // cache (count stable). Skips ~2-3 ms of bincode encode + file write
    // on the steady-state warm path. Still skips only when both files are
    // present — first run or after a manual delete writes anyway.
    let hit_n = cache_hits.load(Ordering::Relaxed);
    let no_op =
        hit_n == cache_size && hit_n == db.entries.len() && db_file.exists() && cache_file.exists();

    if !no_op {
        store::write(&db_file, &db)
            .with_context(|| format!("write asset-db: {}", db_file.display()))?;
        store::write_cache(&cache_file, &bake_cache)
            .with_context(|| format!("write cache: {}", cache_file.display()))?;
    }
    let t_write = t_start.elapsed();

    if let Some(sink) = opts.on_progress.as_ref() {
        sink(&format!(
            "baked {} entries → {}",
            db.entries.len(),
            db_file.display()
        ));
        if opts.verbose_timing {
            let walked_n = walked.load(Ordering::Relaxed);
            let parsed_n = db.entries.len() - hit_n;
            let write_phase = if no_op { "skipped" } else { "wrote" };
            sink(&format!(
                "  walked={walked_n} hit={hit_n} parsed={parsed_n} | cache={:?} walk={:?} build={:?} write={:?} ({write_phase}) total={:?}",
                t_cache,
                t_walk - t_cache,
                t_build - t_walk,
                t_write - t_build,
                t_write,
            ));
        }
    }
    Ok(())
}

/// Per-`.meta` work. Returns `Ok(None)` when the meta has no companion file
/// to describe (e.g. orphaned `.meta`, directory `.meta`).
fn process_one(
    meta_path: &Path,
    project_root: &Path,
    cache: &CacheMap,
    cache_hits: &AtomicUsize,
) -> Result<Option<RawEntry>> {
    let companion =
        strip_meta_suffix(meta_path).ok_or_else(|| anyhow::anyhow!("not a .meta path"))?;

    let hint = rel_hint(project_root, &companion)?;

    // Cache-hit fast path: stat `.meta` only. If the mtime matches the
    // cache, trust the cached row outright — no companion stat. Saves
    // ~1 stat × N entries on the warm bake, the bake's dominant cost
    // (warm walk against meow-tower dropped from 47 ms → ~26 ms).
    //
    // **Cache assumption**: Unity's importer touches the `.meta` mtime
    // whenever it re-imports the asset, so a `.meta` mtime drift is the
    // canonical "this asset changed" signal. Hand-editing the asset YAML
    // *without* touching the .meta will serve a stale cached row until
    // the next .meta touch (or a manual `rm asset-db.cache.bin`).
    // Documented + pinned by `tests/bake.rs::cache_does_not_detect_asset_only_touch`.
    let meta_md =
        std::fs::metadata(meta_path).with_context(|| format!("stat: {}", meta_path.display()))?;
    let meta_mtime_ns = mtime_ns(meta_md.modified().unwrap_or(SystemTime::UNIX_EPOCH));

    if let Some(cached) = cache.get(&hint)
        && cached.meta_mtime_ns == meta_mtime_ns
    {
        cache_hits.fetch_add(1, Ordering::Relaxed);
        return Ok(Some(cached.clone()));
    }

    // Cache miss. Now stat the companion — handles directory-`.meta`
    // exclusion too. Slow path beyond here re-parses both files.
    let Ok(companion_md) = std::fs::metadata(&companion) else {
        return Ok(None);
    };
    if companion_md.is_dir() {
        return Ok(None);
    }
    let asset_mtime_ns = mtime_ns(companion_md.modified().unwrap_or(SystemTime::UNIX_EPOCH));

    process_one_uncached(meta_path, &companion, &hint, meta_mtime_ns, asset_mtime_ns)
}

/// Slow path: parse `.meta` + asset YAML, build a `RawEntry`. Shared
/// between the "no cache row at all" and "cache row but companion mtime
/// drifted" cases — both end up doing the same parse work.
fn process_one_uncached(
    meta_path: &Path,
    companion: &Path,
    hint: &str,
    meta_mtime_ns: u64,
    asset_mtime_ns: u64,
) -> Result<Option<RawEntry>> {
    // Cache miss → parse.
    let meta_text = std::fs::read_to_string(meta_path)
        .with_context(|| format!("read .meta: {}", meta_path.display()))?;
    let meta_info = meta::parse(&meta_text)?;

    let ext = companion.extension().and_then(|s| s.to_str()).unwrap_or("");
    let from_ext = class_from_ext(ext);

    let mut sub_assets: Vec<SubAsset> = Vec::new();
    let mut top_class_id: Option<u32> = None;
    let mut script_guid: Option<u128> = None;

    // YAML peek strategy:
    //  - WithSubAssets: types where extra docs ARE addressable from outside.
    //    `.asset`/`.spriteatlas`/`.spriteatlasv2` host explicit sub-assets;
    //    `.prefab`/`.controller`/`.anim`/`.mixer`/`.playable` can host
    //    embedded sub-asset docs (legacy `AnimationClip` inline in a
    //    prefab; AnimatorState in a controller; AudioMixerGroup in a
    //    mixer; Timeline tracks in a playable) that other prefabs
    //    address as `{fileID, guid: <parent.guid>, type: 3}`. Without
    //    capturing them the embedded ref encodes as `&#f<fid>` and
    //    cross-prefab refs degrade to the parent alias + `#f<fid>` suffix.
    //    Embeds are excluded from the global dedup pool — see
    //    `is_embedded` in `build_db`.
    //  - TopOnly: types whose extra docs are internal scene-graph that
    //    isn't addressable from outside (`.unity`, `.mat`, `.mask`).
    //  - None: extension already says everything (`.png`, `.fbx`, scripts).
    let parse_mode: Option<asset::ParseMode> = match ext {
        "asset" | "spriteatlas" | "spriteatlasv2" | "prefab" | "controller" | "anim"
        | "mixer" | "playable" => Some(asset::ParseMode::WithSubAssets),
        "mat" | "mask" | "unity" => Some(asset::ParseMode::TopOnly),
        _ => None,
    };

    if let Some(mode) = parse_mode {
        let asset_text = read_asset_for_mode(companion, mode)?;
        let info = asset::parse(&asset_text, mode)?;
        top_class_id = info.top_class_id;
        script_guid = info.script_guid;
        for s in info.sub_assets {
            if s.name.is_empty() {
                continue;
            }
            if is_filterable_subdoc_for_ext(s.class_id, ext) {
                continue;
            }
            sub_assets.push(SubAsset {
                file_id: s.file_id,
                class_id: s.class_id,
                name: s.name.into_boxed_str(),
            });
        }
    }

    // Precedence: script_guid (MonoBehaviour-backed) > from_ext > top_class_id.
    // `.prefab` and `.unity` deliberately let from_ext win — their YAML's first
    // doc is a *contained* object (GameObject = classID 1), not the asset's
    // class (Prefab = 1001). Falling back to top_class_id only for extensions
    // without a stable class mapping (e.g. `.asset`, where the YAML peek is
    // the only signal).
    let asset_type_raw = if let Some(g) = script_guid {
        AssetTypeRaw::Script(g)
    } else if let Some(cls) = from_ext {
        AssetTypeRaw::Native(cls as u32)
    } else if let Some(cls) = top_class_id.and_then(ClassId::from_raw) {
        AssetTypeRaw::Native(cls as u32)
    } else if let Some(cls) = top_class_id {
        // Unknown raw class ID — store anyway; lookup will treat as Native.
        AssetTypeRaw::Native(cls)
    } else {
        return Ok(None);
    };

    let name = filename_stem(companion);

    // Implicit Sprite sub-asset for Single-mode textures. Compute first
    // (borrows `meta_info` whole); the for-loop below moves
    // `meta_info.sprite_sheet`, so the predicate must run before that.
    let implicit_sprite = synthesize_implicit_sprite(&meta_info, &name);

    // Texture sprite-sheet sub-assets (from .meta). Always class Sprite —
    // .meta `sprites:` entries are by definition Sprite sub-assets of the
    // texture (Unity's Sprite-mode importer creates them at fileID-as-hash).
    for (fid, name) in meta_info.sprite_sheet {
        sub_assets.push(SubAsset {
            file_id: fid,
            class_id: ClassId::Sprite as u32,
            name: name.into_boxed_str(),
        });
    }

    if let Some(sub) = implicit_sprite {
        sub_assets.push(sub);
    }

    Ok(Some(RawEntry {
        guid: meta_info.guid,
        asset_type_raw,
        hint: hint.to_string(),
        name,
        meta_mtime_ns,
        asset_mtime_ns,
        sub_assets,
    }))
}

/// Synthesize the implicit Sprite sub-asset Unity auto-generates for
/// Single-mode Sprite textures. Unity creates one Sprite (fileID
/// `21300000` = `ClassId::Sprite × 100_000`) named after the texture
/// file but never writes it to the `.meta` — the `sprites:` list stays
/// empty. Without synthesizing it here, `AssetMap::elidable_subasset_fid`
/// (`mapping/asset_map.rs`) can't fire and `_sprite: $TexName` fields
/// keep the redundant `#f21300000` suffix on pull.
///
/// Returns `None` when:
///   - the `.meta`'s `spriteSheet.sprites:` list is non-empty (explicit
///     entries own the sub-asset list — atlases, multi-sprite sheets);
///   - `textureType` isn't 8 (Sprite); or
///   - `spriteMode` isn't 1 (Single).
///
/// Branches pinned by `bake_asset_db::bake::tests::synthesize_implicit_sprite_*`.
fn synthesize_implicit_sprite(meta: &meta::MetaInfo, stem: &str) -> Option<SubAsset> {
    if meta.sprite_sheet.is_empty()
        && meta.texture_type == Some(TEXTURE_TYPE_SPRITE)
        && meta.sprite_mode == Some(SPRITE_MODE_SINGLE)
    {
        Some(SubAsset {
            file_id: ClassId::Sprite.canonical_subobject_fid(),
            class_id: ClassId::Sprite as u32,
            name: stem.to_string().into_boxed_str(),
        })
    } else {
        None
    }
}

fn warn_sanitized(on_warn: Option<WarnSinkRef<'_>>, kind: &str, hint: &str, old: &str, new: &str) {
    if let Some(sink) = on_warn {
        sink(&format!(
            "warning: {kind} {hint} name `{old}` contains ref-reserved char; renamed to `{new}`",
        ));
    }
}

fn build_db(
    mut raw: Vec<RawEntry>,
    sanitizer: Option<NameSanitizerRef<'_>>,
    on_warn: Option<WarnSinkRef<'_>>,
    verbose_collisions: bool,
) -> Result<AssetDb> {
    // Stable order: sort by hint so dedup picks the same "winner" each bake.
    raw.sort_by(|a, b| a.hint.cmp(&b.hint));

    // Reset every entry's name to its raw filename stem before dedup
    // (cached entries arrive with their previously-suffixed name; if we
    // dedup against that, collisions compound across bakes), then sanitize
    // ref-reserved chars in both top-level and sub-asset names — covers the
    // three name sources (filename stem, YAML m_Name sub-assets, `.meta`
    // sprite-sheet entries) in one pass before dedup uses `r.name` as key.
    for r in raw.iter_mut() {
        r.name = filename_stem_from_hint(&r.hint);
        if let Some(san) = sanitizer
            && let Some(clean) = san(&r.name)
        {
            warn_sanitized(on_warn, "asset", &r.hint, &r.name, &clean);
            r.name = clean;
        }
        if let Some(san) = sanitizer {
            for sub in r.sub_assets.iter_mut() {
                if let Some(clean) = san(&sub.name) {
                    warn_sanitized(on_warn, "sub-asset of", &r.hint, &sub.name, &clean);
                    sub.name = clean.into_boxed_str();
                }
            }
        }
    }

    // Type-aware dedup: collisions are scoped by `(name, asset_type)`.
    // Same-name entries of distinct `asset_type` (`Foo.png` Texture2D +
    // `Foo.prefab` Prefab) get distinct alias buckets — the consuming
    // field's C# type discriminates at decode. Embedded sub-asset docs
    // of container types are excluded from the global pool entirely
    // (see [Name collisions](docs/asset-database.md#name-collisions)).

    // Pass 1: tally distinct-guid owners per `(name, asset_type)` bucket.
    let mut owners: AHashMap<(String, AssetTypeRaw), AHashSet<u128>> =
        AHashMap::with_capacity(raw.len());
    for r in &raw {
        let key = (r.name.clone(), r.asset_type_raw);
        owners.entry(key).or_default().insert(r.guid);
        if is_embedded_container(&r.hint) {
            continue;
        }
        for sub in &r.sub_assets {
            let key = (
                sub.name.to_string(),
                AssetTypeRaw::Native(sub.class_id),
            );
            owners.entry(key).or_default().insert(r.guid);
        }
    }
    let contested = |name: &str, t: AssetTypeRaw| {
        owners
            .get(&(name.to_string(), t))
            .is_some_and(|s| s.len() > 1)
    };

    // Pass 2: walk entries in hint-sorted order, renaming every contested
    // claim. `taken` tracks `(name, asset_type) → guid` pairs already
    // claimed in this pass so the disambiguator never picks a candidate
    // that collides with an earlier (different-guid) entry of the same
    // type; same-guid sharing remains allowed.
    let mut taken: AHashMap<(String, AssetTypeRaw), u128> = AHashMap::with_capacity(raw.len());
    for r in raw.iter_mut() {
        let top_type = r.asset_type_raw;
        if contested(&r.name, top_type) {
            let new_name = disambiguate(&r.name, &r.hint, r.guid, top_type, &taken)?;
            if verbose_collisions && let Some(sink) = on_warn {
                sink(&format!(
                    "warning: name collision on `{}` (guid {:032x}); renamed to `{}`",
                    r.name, r.guid, new_name,
                ));
            }
            r.name = new_name;
        }
        match taken.get(&(r.name.clone(), top_type)) {
            Some(&prev) if prev != r.guid => anyhow::bail!(
                "asset-db: name `{}` claimed by both guid {:032x} and {prev:032x} \
                 after dedup — `disambiguate` produced a non-unique alias",
                r.name,
                r.guid,
            ),
            _ => {
                taken.insert((r.name.clone(), top_type), r.guid);
            }
        }

        if is_embedded_container(&r.hint) {
            // Prefab-embedded sub-assets bypass the global dedup pool;
            // sanitization already happened above. Names stay as authored
            // and resolve via `$Sub@Parent` at the codec layer.
            continue;
        }
        for sub in r.sub_assets.iter_mut() {
            let sub_type = AssetTypeRaw::Native(sub.class_id);
            if contested(&sub.name, sub_type) {
                let original = sub.name.to_string();
                let new_name = disambiguate(&original, &r.hint, r.guid, sub_type, &taken)?;
                if verbose_collisions && let Some(sink) = on_warn {
                    sink(&format!(
                        "warning: sub-asset name collision on `{}` (parent guid {:032x}); renamed to `{}`",
                        original, r.guid, new_name,
                    ));
                }
                sub.name = new_name.into_boxed_str();
            }
            // Same-guid sharing is allowed — a sub-asset's deduped name
            // will often equal the parent's deduped alias (same hint
            // feeds disambiguate), and that's the desired outcome.
            let key = (sub.name.to_string(), sub_type);
            if !taken.contains_key(&key) {
                taken.insert(key, r.guid);
            }
        }
    }

    // Intern script types and finalize entries.
    let mut db = AssetDb::new();
    let entries: Vec<AssetEntry> = raw
        .into_iter()
        .map(|r| {
            let asset_type = match r.asset_type_raw {
                AssetTypeRaw::Native(n) => AssetType::Native(n),
                AssetTypeRaw::Script(g) => AssetType::Script(db.intern_script(g)),
            };
            AssetEntry {
                guid: r.guid,
                asset_type,
                name: r.name.into_boxed_str(),
                sub_assets: r.sub_assets,
                hint: r.hint.into_boxed_str(),
            }
        })
        .collect();
    db.entries = entries;
    db.sort();
    check_no_full_duplicates(&db)?;
    Ok(db)
}

/// Hard-fail on two corruption cases:
///
/// 1. **Two top-level entries share a GUID.** Hand-edited or copy-pasted
///    `.meta` whose GUID wasn't rewritten. The name-dedup loop only
///    renames when guids *differ*, so same-guid pairs flow through with
///    distinct names and `db.sort()` doesn't merge them. Catches the
///    duplicate-`.meta` case the Unity-hidden walker filter also guards
///    against — belt and braces.
///
/// 2. **Within-entry sub-asset rows share `(name, fileID)`.** Two YAML
///    sub-docs in the same asset declared identical names + fileIDs —
///    asset-side corruption, parser bug, or atlas content collision.
fn check_no_full_duplicates(db: &AssetDb) -> Result<()> {
    // Top-level: guid uniqueness. `db.entries` is already guid-sorted, so
    // a single pass over consecutive pairs catches every dup.
    for w in db.entries.windows(2) {
        if w[0].guid == w[1].guid {
            anyhow::bail!(
                "duplicate top-level GUID: {:032x} between names `{}` and `{}` — likely two .meta files share a GUID",
                w[0].guid,
                w[0].name,
                w[1].name,
            );
        }
    }

    // Sub-assets: (guid, fileID, name) uniqueness within each entry.
    let mut seen: AHashSet<(i64, &str)> = AHashSet::new();
    for e in &db.entries {
        seen.clear();
        for s in &e.sub_assets {
            if !seen.insert((s.file_id, &*s.name)) {
                anyhow::bail!(
                    "duplicate sub-asset record: name={} guid={:032x} fileID={} type={:?}",
                    s.name,
                    e.guid,
                    s.file_id,
                    e.asset_type,
                );
            }
        }
    }
    Ok(())
}

/// Read just enough of the asset to satisfy `mode`.
///
/// `TopOnly` reads the first 4 KiB and truncates at the last newline — that
/// covers a YAML preamble (`%YAML 1.1\n%TAG …\n`), the first
/// `--- !u!<id> &<fid>` header, and a `m_Script` line for .asset
/// MonoBehaviours (≤ ~200 bytes). `WithSubAssets` reads the full file.
///
/// Trimming at the last newline guards against UTF-8 boundary cuts inside a
/// multi-byte character — every YAML line is complete UTF-8.
fn read_asset_for_mode(path: &Path, mode: asset::ParseMode) -> Result<String> {
    use std::io::Read;
    match mode {
        asset::ParseMode::WithSubAssets => {
            std::fs::read_to_string(path).with_context(|| format!("read asset: {}", path.display()))
        }
        asset::ParseMode::TopOnly => {
            const HEAD_BYTES: u64 = 4096;
            let f = std::fs::File::open(path)
                .with_context(|| format!("open asset: {}", path.display()))?;
            let mut buf = Vec::with_capacity(HEAD_BYTES as usize);
            f.take(HEAD_BYTES)
                .read_to_end(&mut buf)
                .with_context(|| format!("read asset: {}", path.display()))?;
            // Drop trailing partial line so .lines() yields only complete
            // (and thus complete-UTF-8) lines. If the head has no newline at
            // all (pathological — single-line YAML > 4 KiB), keep the buffer
            // and let `from_utf8` decide.
            if let Some(last_nl) = buf.iter().rposition(|&b| b == b'\n') {
                buf.truncate(last_nl + 1);
            }
            String::from_utf8(buf)
                .with_context(|| format!("non-utf8 asset head: {}", path.display()))
        }
    }
}

fn strip_meta_suffix(p: &Path) -> Option<PathBuf> {
    let s = p.to_str()?;
    s.strip_suffix(".meta").map(PathBuf::from)
}

fn rel_hint(project_root: &Path, companion: &Path) -> Result<String> {
    // Strip the project root, not just `Assets/`. The walker now visits both
    // `<project>/Assets/` and `<project>/Packages/`, so hints look like
    // `Assets/Foo.prefab` or `Packages/com.boxcat.libs/Bar.mixer`.
    let rel = companion
        .strip_prefix(project_root)
        .with_context(|| format!("strip prefix: {}", companion.display()))?;
    let s = rel.to_string_lossy().replace('\\', "/");
    Ok(s)
}

fn filename_stem(p: &Path) -> String {
    p.file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("")
        .to_string()
}

fn filename_stem_from_hint(hint: &str) -> String {
    Path::new(hint)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("")
        .to_string()
}

/// Pick a unique alias for `stem` given `hint` and an existing `taken` map.
/// Strategy: try `stem^dir` for successively-deeper parent dirs. A candidate
/// is considered "free" iff it's absent from `taken` *or* already mapped to
/// `owner_guid` (the latter covers the same-guid sub-asset case where the
/// parent's deduped top-level alias is a valid name to share).
///
/// `asset_type` scopes the dedup bucket — a candidate is "taken" only when
/// another guid has claimed the exact `(name, asset_type)` pair. Two assets
/// of different `asset_type` (e.g. Texture2D `Foo.png` vs Prefab `Foo.prefab`)
/// share the bare alias `Foo` without contesting because the codec layer
/// uses the field's declared C# type to pick the right one at lookup time.
///
/// Hard-fails when no parent segment yields a free candidate — ambiguity
/// surfaces at bake time rather than getting papered over with a guid suffix.
/// See [Name collisions](docs/asset-database.md#name-collisions) for the
/// `^` separator rationale.
fn disambiguate(
    stem: &str,
    hint: &str,
    owner_guid: u128,
    asset_type: AssetTypeRaw,
    taken: &AHashMap<(String, AssetTypeRaw), u128>,
) -> Result<String> {
    let parts: Vec<&str> = Path::new(hint)
        .parent()
        .map(|p| p.iter().filter_map(|c| c.to_str()).collect::<Vec<_>>())
        .unwrap_or_default();

    // Walk parent segments from nearest to root, picking the shortest
    // suffix that doesn't collide with a different-guid owner.
    let mut suffix = String::new();
    for seg in parts.iter().rev() {
        if !suffix.is_empty() {
            suffix.insert(0, '/');
        }
        suffix.insert_str(0, seg);
        let candidate = format!("{stem}^{suffix}");
        match taken.get(&(candidate.clone(), asset_type)) {
            None => return Ok(candidate),
            Some(&prev) if prev == owner_guid => return Ok(candidate),
            Some(_) => continue,
        }
    }
    anyhow::bail!(
        "asset-db: cannot disambiguate name `{stem}` for guid {owner_guid:032x} \
         (hint `{hint}`) — every parent-segment suffix is already taken by \
         another asset. Rename one of the colliding assets in source.",
    )
}

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

    #[test]
    fn run_with_panic_safety_passes_through_ok_some() {
        let r: Result<Option<i32>, String> = run_with_panic_safety("path", "task", || Ok(Some(42)));
        assert_eq!(r, Ok(Some(42)));
    }

    #[test]
    fn run_with_panic_safety_passes_through_ok_none() {
        let r: Result<Option<i32>, String> = run_with_panic_safety("path", "task", || Ok(None));
        assert_eq!(r, Ok(None));
    }

    #[test]
    fn run_with_panic_safety_formats_inner_error_with_label() {
        let r: Result<Option<i32>, String> = run_with_panic_safety("foo.meta", "task", || {
            Err(anyhow::anyhow!("malformed yaml"))
        });
        assert_eq!(r, Err("foo.meta: malformed yaml".to_string()));
    }

    #[test]
    fn run_with_panic_safety_catches_str_panic() {
        let r: Result<Option<i32>, String> =
            run_with_panic_safety("foo.meta", "process_one", || {
                std::panic::panic_any("boom (&str payload)")
            });
        assert_eq!(
            r,
            Err("foo.meta: panic in process_one: boom (&str payload)".to_string())
        );
    }

    #[test]
    fn run_with_panic_safety_catches_string_panic() {
        let r: Result<Option<i32>, String> =
            run_with_panic_safety("foo.meta", "process_one", || {
                // String payloads come from `panic!("{x}")` via the format!
                // path — the runtime hands a String, not a &str.
                panic!("formatted {}", "msg")
            });
        assert_eq!(
            r,
            Err("foo.meta: panic in process_one: formatted msg".to_string())
        );
    }

    #[test]
    fn run_with_panic_safety_handles_non_string_panic_payload() {
        // `panic_any(42_i32)` produces a panic whose payload isn't &str
        // or String. The helper falls back to a sentinel message rather
        // than dropping the error silently.
        let r: Result<Option<i32>, String> =
            run_with_panic_safety("foo.meta", "process_one", || std::panic::panic_any(42_i32));
        assert_eq!(
            r,
            Err("foo.meta: panic in process_one: <non-string panic payload>".to_string())
        );
    }

    fn meta_for(
        texture_type: Option<u32>,
        sprite_mode: Option<u32>,
        sprites: Vec<(i64, String)>,
    ) -> meta::MetaInfo {
        meta::MetaInfo {
            guid: 0,
            sprite_sheet: sprites,
            texture_type,
            sprite_mode,
        }
    }

    #[test]
    fn synthesize_implicit_sprite_fires_on_single_mode_sprite_with_empty_sheet() {
        let m = meta_for(Some(TEXTURE_TYPE_SPRITE), Some(SPRITE_MODE_SINGLE), vec![]);
        let sub = synthesize_implicit_sprite(&m, "Icon").expect("synthesis should fire");
        assert_eq!(sub.file_id, ClassId::Sprite.canonical_subobject_fid());
        assert_eq!(&*sub.name, "Icon");
    }

    #[test]
    fn synthesize_implicit_sprite_skips_when_sheet_non_empty() {
        // Explicit sprites own the sub-asset list — atlas-shaped meta
        // doesn't get a phantom main-Sprite layered on top.
        let m = meta_for(
            Some(TEXTURE_TYPE_SPRITE),
            Some(SPRITE_MODE_SINGLE),
            vec![(12345, "explicit_a".into())],
        );
        assert!(synthesize_implicit_sprite(&m, "Icon").is_none());
    }

    #[test]
    fn synthesize_implicit_sprite_skips_on_multiple_mode() {
        // spriteMode: 2 (Multiple = atlas) means "the sprites: list is
        // canonical, even if currently empty". No synthesis.
        let m = meta_for(Some(TEXTURE_TYPE_SPRITE), Some(2), vec![]);
        assert!(synthesize_implicit_sprite(&m, "Icon").is_none());
    }

    #[test]
    fn synthesize_implicit_sprite_skips_on_non_sprite_texture() {
        // textureType: 0 (Default) — texture isn't a Sprite at all.
        let m = meta_for(Some(0), Some(SPRITE_MODE_SINGLE), vec![]);
        assert!(synthesize_implicit_sprite(&m, "Icon").is_none());
    }

    #[test]
    fn synthesize_implicit_sprite_skips_when_predicates_absent() {
        // Both texture_type and sprite_mode None — `.meta` from a
        // non-texture asset (or a stale .meta missing the fields).
        let m = meta_for(None, None, vec![]);
        assert!(synthesize_implicit_sprite(&m, "Icon").is_none());
    }

    /// `is_filterable_subdoc_for_ext` is the single point where parse-
    /// time sub-asset filtering decides what's a structural prefab tree
    /// doc vs. a real sub-asset. Pin the contract per extension.
    #[test]
    fn is_filterable_subdoc_for_ext_branches_correctly() {
        // .prefab: GO + Transform + RectTransform + MonoBehaviour-as-component.
        for cls in [1, 4, 224, 114] {
            assert!(
                is_filterable_subdoc_for_ext(cls, "prefab"),
                "class {cls} should be filtered for .prefab",
            );
        }
        // .playable: Timeline tracks live as MB-114 — must NOT filter.
        // GO/Transform never appear in .playable but the predicate stays
        // valid (no-op).
        assert!(!is_filterable_subdoc_for_ext(114, "playable"));
        assert!(is_filterable_subdoc_for_ext(1, "playable"));
        // .controller: AnimatorState (1102), BlendTree (206) — never
        // filtered.
        assert!(!is_filterable_subdoc_for_ext(1102, "controller"));
        assert!(!is_filterable_subdoc_for_ext(114, "controller"));
        // .mixer: AudioMixerGroup (273) — never filtered.
        assert!(!is_filterable_subdoc_for_ext(273, "mixer"));
        assert!(!is_filterable_subdoc_for_ext(114, "mixer"));
        // .asset / .spriteatlas: MB-114 are real ScriptableObject sub-
        // assets. Real classes (Sprite=213) are never filtered either.
        assert!(!is_filterable_subdoc_for_ext(114, "asset"));
        assert!(!is_filterable_subdoc_for_ext(213, "spriteatlas"));
    }

    #[test]
    fn stem_basic() {
        assert_eq!(filename_stem(Path::new("foo/Bar.prefab")), "Bar");
        assert_eq!(filename_stem_from_hint("foo/Bar.prefab"), "Bar");
    }

    #[test]
    fn disambiguate_walks_parents() {
        let t = AssetTypeRaw::Native(ClassId::Texture2D as u32);
        let mut taken = AHashMap::new();
        taken.insert(("Foo".to_string(), t), 1u128);
        // Nearest parent suffix wins on first try.
        let alias = disambiguate("Foo", "pkg/Editor/Foo.cs", 2, t, &taken).unwrap();
        assert_eq!(alias, "Foo^Editor");

        // First-level parent already taken (by a different guid, same type)
        // → falls back to deeper path.
        taken.insert(("Foo^Editor".to_string(), t), 3);
        let alias = disambiguate("Foo", "pkg/Editor/Foo.cs", 2, t, &taken).unwrap();
        assert_eq!(alias, "Foo^pkg/Editor");
    }

    #[test]
    fn disambiguate_ignores_collisions_in_other_types() {
        // A different `AssetTypeRaw` claiming the same alias does NOT
        // contest — type-aware dedup gives each `(name, type)` its own
        // bucket. PNG (Texture2D) and prefab (Prefab) named `Foo` both
        // keep bare `Foo`.
        let png = AssetTypeRaw::Native(ClassId::Texture2D as u32);
        let prefab = AssetTypeRaw::Native(ClassId::Prefab as u32);
        let mut taken = AHashMap::new();
        taken.insert(("Foo".to_string(), png), 1u128);
        // disambiguate against the prefab bucket — `Foo` is free here.
        let alias = disambiguate("Foo", "Assets/Bar/Foo.prefab", 2, prefab, &taken).unwrap();
        // Walk produces `Foo^Bar` because we always step at least one
        // parent (disambiguate's contract is "produce a suffixed form");
        // the contention check upstream is what decides whether to call.
        assert_eq!(alias, "Foo^Bar");
    }

    #[test]
    fn disambiguate_returns_existing_when_same_owner() {
        // When the candidate suffix is already mapped to `owner_guid`, the
        // sub-asset can safely share that alias — its lookup path resolves
        // back to the same guid, so no real ambiguity exists.
        let t = AssetTypeRaw::Native(ClassId::Texture2D as u32);
        let mut taken = AHashMap::new();
        taken.insert(("Cloud1".to_string(), t), 0xa0_u128);
        taken.insert(("Cloud1^Tower".to_string(), t), 0xb0_u128);
        let alias =
            disambiguate("Cloud1", "Assets/Tower/Cloud1.png", 0xb0_u128, t, &taken).unwrap();
        assert_eq!(alias, "Cloud1^Tower");
    }

    #[test]
    fn disambiguate_hard_fails_when_no_parent_segments() {
        let t = AssetTypeRaw::Native(ClassId::Texture2D as u32);
        let mut taken = AHashMap::new();
        taken.insert(("Foo".to_string(), t), 1u128);
        // Hint has no directories — nothing to suffix with. Must error
        // rather than silently fall back to a guid suffix.
        let err =
            disambiguate("Foo", "Foo.cs", 2u128, t, &taken).expect_err("must hard-fail");
        let msg = format!("{err:#}");
        assert!(msg.contains("disambiguate"), "msg: {msg}");
        assert!(msg.contains("Foo"), "msg: {msg}");
    }

    fn raw_native(hint: &str, guid: u128, sub_assets: Vec<SubAsset>) -> RawEntry {
        RawEntry {
            guid,
            asset_type_raw: AssetTypeRaw::Native(ClassId::Texture2D as u32),
            hint: hint.to_string(),
            // `build_db`'s first pass overwrites `name` from `hint`, so any
            // value here is fine. Empty kept the test minimal.
            name: String::new(),
            meta_mtime_ns: 0,
            asset_mtime_ns: 0,
            sub_assets,
        }
    }

    /// Pin: when a name is claimed by ≥2 distinct guids of the same
    /// `asset_type`, every claimant must rename — no "first wins" carve-out.
    /// The deduped form is consistent across claimants: each entry resolves
    /// through `disambiguate` against its own hint.
    ///
    /// Two same-type Texture2D `Cloud1.png` files in different folders
    /// share the bare alias `Cloud1` until type-aware dedup forces both to
    /// suffix.
    #[test]
    fn build_db_renames_every_claimant_when_name_is_contested() {
        let png_a_guid = 0xa0_u128;
        let png_b_guid = 0xb0_u128;
        let sprite_fid: i64 = 21300000;

        let raw = vec![
            raw_native("Assets/Other/Cloud1.png", png_a_guid, vec![]),
            raw_native(
                "Assets/Tower/Cloud1.png",
                png_b_guid,
                vec![SubAsset {
                    file_id: sprite_fid,
                    class_id: ClassId::Sprite as u32,
                    name: "Cloud1".into(),
                }],
            ),
        ];

        let db = build_db(raw, None, None, false).expect("build_db should succeed");

        let a_entry = db.find_by_guid(png_a_guid).unwrap();
        let b_entry = db.find_by_guid(png_b_guid).unwrap();

        // Neither entry keeps the bare alias — both renamed.
        assert_ne!(&*a_entry.name, "Cloud1");
        assert_ne!(&*b_entry.name, "Cloud1");
        assert!(
            a_entry.name.starts_with("Cloud1^"),
            "first png top-level not deduped: {}",
            a_entry.name,
        );
        assert!(
            b_entry.name.starts_with("Cloud1^"),
            "second png top-level not deduped: {}",
            b_entry.name,
        );
        // Distinct hints → distinct deduped suffixes.
        assert_ne!(&*a_entry.name, &*b_entry.name);

        // Sub-asset dedup: the Sprite sub-asset's `Cloud1` lives in its own
        // type-bucket (Sprite, not Texture2D), so it isn't contested by the
        // Texture2D collision above. It stays bare. The png_b entry is the
        // only Sprite-bucket owner.
        let png_b_sub = &b_entry.sub_assets[0];
        assert_eq!(png_b_sub.file_id, sprite_fid);
        assert_eq!(
            &*png_b_sub.name, "Cloud1",
            "Sprite sub-asset should stay bare under type-aware dedup",
        );
    }

    /// Pin type-aware dedup: a Texture2D and a Prefab sharing the stem
    /// `Foo` both keep the bare alias. Reverse lookup discriminates by
    /// the field's declared C# type at the consumer layer.
    #[test]
    fn build_db_keeps_bare_alias_for_type_distinct_collisions() {
        let png_guid = 0xa0_u128;
        let prefab_guid = 0xb0_u128;
        let raw = vec![
            RawEntry {
                guid: png_guid,
                asset_type_raw: AssetTypeRaw::Native(ClassId::Texture2D as u32),
                hint: "Assets/UI/Foo.png".to_string(),
                name: String::new(),
                meta_mtime_ns: 0,
                asset_mtime_ns: 0,
                sub_assets: vec![],
            },
            RawEntry {
                guid: prefab_guid,
                asset_type_raw: AssetTypeRaw::Native(ClassId::Prefab as u32),
                hint: "Assets/UI/Foo.prefab".to_string(),
                name: String::new(),
                meta_mtime_ns: 0,
                asset_mtime_ns: 0,
                sub_assets: vec![],
            },
        ];
        let db = build_db(raw, None, None, false).expect("build_db should succeed");
        // Both keep bare `Foo` because they live in distinct type buckets.
        assert_eq!(&*db.find_by_guid(png_guid).unwrap().name, "Foo");
        assert_eq!(&*db.find_by_guid(prefab_guid).unwrap().name, "Foo");
    }

    /// Pin: AnimatorController-embedded sub-assets are excluded from the
    /// global dedup pool, mirroring the prefab-embedded rule. Without the
    /// exclusion, an embedded AnimatorState named `Idle` would contest a
    /// hypothetical standalone `.asset` of the same name AND same Unity
    /// classID (AnimatorState exists as both an embedded sub of
    /// `.controller` and a top-level `.asset` in Unity), forcing both to
    /// rename via parent-dir suffix. The exclusion keeps the embedded
    /// state in its parent's namespace where it's addressed via
    /// `$Idle@Player` at the consumer layer.
    #[test]
    fn build_db_skips_controller_embedded_subassets_in_global_pool() {
        const ANIMATOR_STATE_CLASS_ID: u32 = 1102;
        let controller_guid = 0xc0_u128;
        let other_state_guid = 0xd0_u128;
        let raw = vec![
            RawEntry {
                guid: controller_guid,
                asset_type_raw: AssetTypeRaw::Native(ClassId::AnimatorController as u32),
                hint: "Assets/Anim/Player.controller".to_string(),
                name: String::new(),
                meta_mtime_ns: 0,
                asset_mtime_ns: 0,
                sub_assets: vec![SubAsset {
                    file_id: -123_456_789_012,
                    class_id: ANIMATOR_STATE_CLASS_ID,
                    name: "Idle".into(),
                }],
            },
            // Standalone .asset whose top class IS AnimatorState — same
            // (name, class_id) bucket as the embedded one. With
            // exclusion, only this one claims the global `Idle` alias.
            RawEntry {
                guid: other_state_guid,
                asset_type_raw: AssetTypeRaw::Native(ANIMATOR_STATE_CLASS_ID),
                hint: "Assets/Other/Idle.asset".to_string(),
                name: String::new(),
                meta_mtime_ns: 0,
                asset_mtime_ns: 0,
                sub_assets: vec![],
            },
        ];
        let db = build_db(raw, None, None, false).expect("build_db should succeed");
        // Standalone keeps bare `Idle`.
        assert_eq!(&*db.find_by_guid(other_state_guid).unwrap().name, "Idle");
        // Embedded state stays as authored in the parent's namespace.
        let ctrl_entry = db.find_by_guid(controller_guid).unwrap();
        assert_eq!(&*ctrl_entry.sub_assets[0].name, "Idle");
    }

    /// Same shape as the controller test, for AudioMixerController:
    /// AudioMixerGroup sub-asset class collides with itself between an
    /// embedded `Main.mixer` group and a hypothetical standalone
    /// `.asset` of the same class. Exclusion keeps the embed in the
    /// parent's namespace.
    #[test]
    fn build_db_skips_mixer_embedded_subassets_in_global_pool() {
        const AUDIO_MIXER_GROUP_CLASS_ID: u32 = 273;
        let mixer_guid = 0xe0_u128;
        let other_group_guid = 0xf0_u128;
        let raw = vec![
            RawEntry {
                guid: mixer_guid,
                asset_type_raw: AssetTypeRaw::Native(ClassId::AudioMixerController as u32),
                hint: "Assets/Audio/Main.mixer".to_string(),
                name: String::new(),
                meta_mtime_ns: 0,
                asset_mtime_ns: 0,
                sub_assets: vec![SubAsset {
                    file_id: 9_001,
                    class_id: AUDIO_MIXER_GROUP_CLASS_ID,
                    name: "Master".into(),
                }],
            },
            RawEntry {
                guid: other_group_guid,
                asset_type_raw: AssetTypeRaw::Native(AUDIO_MIXER_GROUP_CLASS_ID),
                hint: "Assets/Other/Master.asset".to_string(),
                name: String::new(),
                meta_mtime_ns: 0,
                asset_mtime_ns: 0,
                sub_assets: vec![],
            },
        ];
        let db = build_db(raw, None, None, false).expect("build_db should succeed");
        assert_eq!(&*db.find_by_guid(other_group_guid).unwrap().name, "Master");
        let mixer_entry = db.find_by_guid(mixer_guid).unwrap();
        assert_eq!(&*mixer_entry.sub_assets[0].name, "Master");
    }

    /// Pin: `.playable` files are treated as embedded containers — their
    /// Timeline track sub-assets bypass the global dedup pool. Many
    /// `.playable` files in a project share Unity-default track names like
    /// `Animation Track (2)`; without the exclusion they contest in the
    /// global pool and `disambiguate` hard-fails when the shared
    /// parent-dir suffixes are exhausted. Exclusion is keyed on the
    /// `.playable` extension (`is_embedded_container`) because the
    /// top-doc script guid of a playable is whichever sub-doc Unity
    /// sorts first by hashed fileID — unstable as a discriminator.
    #[test]
    fn build_db_skips_playable_embedded_tracks_in_global_pool() {
        // Track class id + script guid placeholders — bake stores both
        // but doesn't validate them against any registry. Extension is
        // the discriminator that triggers the exclusion.
        const ANIMATION_TRACK_CLASS_ID: u32 = 5004;
        let some_script_guid = 0xd21dcc2386d650c4597f3633c75a1f98_u128;
        let pa_guid = 0xa0_u128;
        let pb_guid = 0xb0_u128;
        let raw = vec![
            RawEntry {
                guid: pa_guid,
                asset_type_raw: AssetTypeRaw::Script(some_script_guid),
                hint: "Assets/Anim/PlayableA.playable".to_string(),
                name: String::new(),
                meta_mtime_ns: 0,
                asset_mtime_ns: 0,
                sub_assets: vec![SubAsset {
                    file_id: -123_456_789,
                    class_id: ANIMATION_TRACK_CLASS_ID,
                    name: "Animation Track (2)".into(),
                }],
            },
            RawEntry {
                guid: pb_guid,
                asset_type_raw: AssetTypeRaw::Script(some_script_guid),
                hint: "Assets/Anim/PlayableB.playable".to_string(),
                name: String::new(),
                meta_mtime_ns: 0,
                asset_mtime_ns: 0,
                sub_assets: vec![SubAsset {
                    file_id: -987_654_321,
                    class_id: ANIMATION_TRACK_CLASS_ID,
                    name: "Animation Track (2)".into(),
                }],
            },
        ];
        let db = build_db(raw, None, None, false).expect("build_db should succeed");
        // Both playables keep their embedded track names as authored —
        // sub-assets live in the parent's namespace, not the global pool.
        assert_eq!(
            &*db.find_by_guid(pa_guid).unwrap().sub_assets[0].name,
            "Animation Track (2)"
        );
        assert_eq!(
            &*db.find_by_guid(pb_guid).unwrap().sub_assets[0].name,
            "Animation Track (2)"
        );
    }

    /// Pin: prefab-embedded sub-assets are excluded from the global dedup
    /// pool. Their names stay as authored even when another asset in the
    /// project shares the name. They resolve via `$Sub@Parent` at the
    /// consumer layer, not the global alias bucket.
    #[test]
    fn build_db_skips_prefab_embedded_subassets_in_global_pool() {
        let prefab_guid = 0xa0_u128;
        let other_clip_guid = 0xb0_u128;
        let raw = vec![
            RawEntry {
                guid: prefab_guid,
                asset_type_raw: AssetTypeRaw::Native(ClassId::Prefab as u32),
                hint: "Assets/UI/PatternBG.prefab".to_string(),
                name: String::new(),
                meta_mtime_ns: 0,
                asset_mtime_ns: 0,
                sub_assets: vec![SubAsset {
                    file_id: -4_468_419_427_481_386_445,
                    class_id: ClassId::AnimationClip as u32,
                    name: "Animation".into(),
                }],
            },
            RawEntry {
                guid: other_clip_guid,
                asset_type_raw: AssetTypeRaw::Native(ClassId::AnimationClip as u32),
                hint: "Assets/Other/Animation.anim".to_string(),
                name: String::new(),
                meta_mtime_ns: 0,
                asset_mtime_ns: 0,
                sub_assets: vec![],
            },
        ];
        let db = build_db(raw, None, None, false).expect("build_db should succeed");
        // Standalone .anim keeps bare `Animation` — the prefab-embedded
        // `Animation` doesn't claim the global alias.
        assert_eq!(
            &*db.find_by_guid(other_clip_guid).unwrap().name,
            "Animation"
        );
        // Prefab-embedded sub-asset keeps its raw name (lives in parent's
        // namespace; `$Animation@PatternBG` at the consumer layer).
        let prefab_entry = db.find_by_guid(prefab_guid).unwrap();
        assert_eq!(&*prefab_entry.sub_assets[0].name, "Animation");
    }

    /// Pin: a single-owner name (one guid only, even if it appears as both
    /// a top-level alias and one of its own sub-assets) is *not*
    /// contested — it stays bare. Guards against over-renaming the common
    /// case of a Texture2D and its lone same-named Sprite sub-asset.
    #[test]
    fn build_db_keeps_bare_alias_when_name_is_uncontested() {
        let png_guid = 0xb0_u128;
        let raw = vec![raw_native(
            "Assets/Tower/Lone.png",
            png_guid,
            vec![SubAsset {
                file_id: 21300000,
                class_id: ClassId::Sprite as u32,
                name: "Lone".into(),
            }],
        )];

        let db = build_db(raw, None, None, false).expect("build_db should succeed");
        let entry = db.find_by_guid(png_guid).unwrap();
        assert_eq!(&*entry.name, "Lone");
        assert_eq!(&*entry.sub_assets[0].name, "Lone");
    }

    /// Pin: when a top-level alias is genuinely unresolvable (no parent
    /// segments left to walk and the bare stem is already taken), the
    /// bake hard-fails rather than silently falling back to a `^<guid8>`
    /// suffix. Per the project policy: ambiguity surfaces at bake time,
    /// not encode time.
    #[test]
    fn build_db_fails_when_dedup_cannot_resolve() {
        let raw = vec![
            // Two top-level entries with the same bare stem and no parent
            // segments to walk — `disambiguate` has nothing to suffix with.
            raw_native("Foo.asset", 0x01_u128, vec![]),
            raw_native("Foo.prefab", 0x02_u128, vec![]),
        ];

        let err = build_db(raw, None, None, false).expect_err("collision with no parent dirs must hard-fail");
        let msg = format!("{err:#}");
        assert!(
            msg.contains("Foo") && msg.contains("disambiguate"),
            "error message should name the collision and the dedup pass: {msg}",
        );
    }
}