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
//! End-to-end test: build a tiny synthetic Unity project tree, run bake,
//! verify the binary store lookups.

use std::fs;
use std::path::{Path, PathBuf};

use unity_assetdb::bake::{BakeOptions, bake};
use unity_assetdb::store;

/// Drives the `BakeOptions` API with the canonical
/// `<root>/Library/unity-assetdb/` out dir, no sanitizer, silent sinks.
fn bake_at(root: &Path) -> PathBuf {
    let out_dir = out_dir_for(root);
    let opts = BakeOptions {
        project_root: root.to_path_buf(),
        out_dir: out_dir.clone(),
        name_sanitizer: None,
        on_warn: None,
        on_progress: None,
        verbose_timing: false,
        verbose_collisions: false,
    };
    bake(&opts).unwrap();
    out_dir
}

fn out_dir_for(root: &Path) -> PathBuf {
    root.join("Library").join("unity-assetdb")
}

fn db_file(root: &Path) -> PathBuf {
    store::db_path(&out_dir_for(root))
}

fn cache_file(root: &Path) -> PathBuf {
    store::cache_path(&out_dir_for(root))
}

fn write(path: &Path, body: &str) {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).unwrap();
    }
    fs::write(path, body).unwrap();
}

fn make_fixture(root: &Path) {
    // Mark this dir as a Unity project root.
    fs::create_dir_all(root.join("ProjectSettings")).unwrap();
    write(
        &root.join("ProjectSettings/ProjectVersion.txt"),
        "m_EditorVersion: 2022.3.0f1\n",
    );

    // A prefab + its meta.
    let prefab_dir = root.join("Assets/UI");
    write(
        &prefab_dir.join("Foo.prefab"),
        "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1001 &100100000\nPrefabInstance:\n  m_ObjectHideFlags: 0\n",
    );
    write(
        &prefab_dir.join("Foo.prefab.meta"),
        "fileFormatVersion: 2\nguid: aaaa1111aaaa1111aaaa1111aaaa1111\nPrefabImporter:\n  externalObjects: {}\n",
    );

    // A ScriptableObject .asset → AssetType::Script
    write(
        &root.join("Assets/SO/Bar.asset"),
        "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!114 &11400000\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_Script: {fileID: 11500000, guid: bbbb2222bbbb2222bbbb2222bbbb2222, type: 3}\n  m_Name: Bar\n",
    );
    write(
        &root.join("Assets/SO/Bar.asset.meta"),
        "fileFormatVersion: 2\nguid: cccc3333cccc3333cccc3333cccc3333\nNativeFormatImporter: {}\n",
    );

    // A texture with sprite-sheet sub-assets in its .meta.
    write(&root.join("Assets/Tex/Sheet.png"), "fake-png-bytes");
    write(
        &root.join("Assets/Tex/Sheet.png.meta"),
        "fileFormatVersion: 2
guid: dddd4444dddd4444dddd4444dddd4444
TextureImporter:
  spriteSheet:
    sprites:
    - serializedVersion: 2
      name: spr_a
      internalID: 11111
    - serializedVersion: 2
      name: spr_b
      internalID: 22222
",
    );
}

fn unique_tmp(label: &str) -> std::path::PathBuf {
    let pid = std::process::id();
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    std::env::temp_dir().join(format!("unity-assetdb-bake-test-{label}-{pid}-{nanos}"))
}

#[test]
fn bake_then_load_roundtrip() {
    let root = unique_tmp("roundtrip");
    let _ = fs::remove_dir_all(&root);
    make_fixture(&root);

    let _out_dir = bake_at(&root);

    let bin = db_file(&root);
    assert!(
        bin.exists(),
        "asset-db.bin not created at {}",
        bin.display()
    );

    let db = store::read(&bin).unwrap();
    assert_eq!(
        db.entries.len(),
        3,
        "expected 3 entries, got {:?}",
        db.entries
    );

    // Foo.prefab
    let foo = db
        .find_by_guid(0xaaaa1111aaaa1111aaaa1111aaaa1111_u128)
        .expect("Foo.prefab missing");
    assert_eq!(&*foo.name, "Foo");
    match foo.asset_type {
        store::AssetType::Native(n) => {
            assert_eq!(n, unity_assetdb::class_id::ClassId::Prefab as u32);
        }
        store::AssetType::Script(_) => {
            panic!("expected Native(Prefab) for Foo, got {:?}", foo.asset_type)
        }
    }

    // Bar.asset → Script(...) referencing the script guid.
    let bar = db
        .find_by_guid(0xcccc3333cccc3333cccc3333cccc3333_u128)
        .expect("Bar.asset missing");
    assert_eq!(&*bar.name, "Bar");
    match bar.asset_type {
        store::AssetType::Script(idx) => {
            assert_eq!(db.script_guid(idx), 0xbbbb2222bbbb2222bbbb2222bbbb2222_u128);
        }
        store::AssetType::Native(_) => {
            panic!("expected Script for Bar, got {:?}", bar.asset_type)
        }
    }

    // Sheet.png → Native(Texture2D), 2 sub-assets.
    let sheet = db
        .find_by_guid(0xdddd4444dddd4444dddd4444dddd4444_u128)
        .expect("Sheet.png missing");
    assert_eq!(&*sheet.name, "Sheet");
    match sheet.asset_type {
        store::AssetType::Native(n) => {
            assert_eq!(n, unity_assetdb::class_id::ClassId::Texture2D as u32);
        }
        store::AssetType::Script(_) => panic!("expected Native(Texture2D) for Sheet"),
    }
    assert_eq!(sheet.sub_assets.len(), 2);
    assert_eq!(sheet.sub_assets[0].file_id, 11111);
    assert_eq!(&*sheet.sub_assets[0].name, "spr_a");
    assert_eq!(sheet.sub_assets[1].file_id, 22222);
    assert_eq!(&*sheet.sub_assets[1].name, "spr_b");

    // Entries are guid-sorted on disk.
    let guids: Vec<u128> = db.entries.iter().map(|e| e.guid).collect();
    let mut sorted = guids.clone();
    sorted.sort_unstable();
    assert_eq!(guids, sorted);

    fs::remove_dir_all(&root).ok();
}

#[test]
fn cache_reuse_preserves_names() {
    let root = unique_tmp("cache");
    let _ = fs::remove_dir_all(&root);
    make_fixture(&root);

    // First bake.
    let _out_dir = bake_at(&root);
    let first = store::read(&db_file(&root)).unwrap();

    // Second bake without touching anything → identical contents.
    let _out_dir = bake_at(&root);
    let second = store::read(&db_file(&root)).unwrap();

    assert_eq!(first.entries.len(), second.entries.len());
    for (a, b) in first.entries.iter().zip(second.entries.iter()) {
        assert_eq!(a.guid, b.guid);
        assert_eq!(a.name, b.name);
        assert_eq!(a.sub_assets.len(), b.sub_assets.len());
    }

    fs::remove_dir_all(&root).ok();
}

#[test]
fn duplicate_top_level_guid_hard_fails() {
    // Two .meta sharing a GUID (hand-edited copy-paste) — neither under a
    // Unity-hidden directory, so the walker filter doesn't catch them.
    let root = unique_tmp("dup-guid");
    let _ = fs::remove_dir_all(&root);
    fs::create_dir_all(root.join("ProjectSettings")).unwrap();
    write(
        &root.join("ProjectSettings/ProjectVersion.txt"),
        "m_EditorVersion: 2022.3.0f1\n",
    );
    write(
        &root.join("Assets/A.prefab"),
        "--- !u!1001 &100100000\nPrefabInstance: {}\n",
    );
    write(
        &root.join("Assets/A.prefab.meta"),
        "fileFormatVersion: 2\nguid: 1111111111111111111111111111aaaa\nPrefabImporter: {}\n",
    );
    write(
        &root.join("Assets/B.prefab"),
        "--- !u!1001 &100100000\nPrefabInstance: {}\n",
    );
    write(
        &root.join("Assets/B.prefab.meta"),
        "fileFormatVersion: 2\nguid: 1111111111111111111111111111aaaa\nPrefabImporter: {}\n",
    );

    let opts = BakeOptions {
        project_root: root.to_path_buf(),
        out_dir: out_dir_for(&root),
        name_sanitizer: None,
        on_warn: None,
        on_progress: None,
        verbose_timing: false,
        verbose_collisions: false,
    };
    let err = bake(&opts).expect_err("expected hard-fail on duplicate GUID");
    let msg = format!("{err}");
    assert!(
        msg.contains("duplicate top-level GUID"),
        "unexpected error: {msg}"
    );

    fs::remove_dir_all(&root).ok();
}

/// Integration smoke for the implicit-Sprite synthesis path:
/// Single-mode Sprite texture with an empty `sprites:` list bakes to a
/// single sub-asset row carrying Sprite's canonical fileID and the
/// texture's stem. Pure-function predicate branches (Multiple-mode,
/// non-Sprite textureType, non-empty sheet) are exercised cheaper as
/// unit tests at `bake::tests::synthesize_implicit_sprite_*`.
#[test]
fn implicit_sprite_subasset_synthesis() {
    use unity_assetdb::class_id::ClassId;

    let root = unique_tmp("synth-single");
    let _ = fs::remove_dir_all(&root);
    fs::create_dir_all(root.join("ProjectSettings")).unwrap();
    write(
        &root.join("ProjectSettings/ProjectVersion.txt"),
        "m_EditorVersion: 2022.3.0f1\n",
    );
    write(&root.join("Assets/Tex/Icon.png"), "fake-png-bytes");
    write(
        &root.join("Assets/Tex/Icon.png.meta"),
        "fileFormatVersion: 2
guid: eeee5555eeee5555eeee5555eeee5555
TextureImporter:
  textureType: 8
  spriteMode: 1
  spriteSheet:
    sprites: []
",
    );

    let _out_dir = bake_at(&root);
    let db = store::read(&db_file(&root)).unwrap();
    let entry = db
        .find_by_guid(0xeeee5555eeee5555eeee5555eeee5555_u128)
        .expect("Icon.png missing from db");

    assert_eq!(&*entry.name, "Icon");
    assert_eq!(
        entry.sub_assets.len(),
        1,
        "Single-mode Sprite texture with empty sheet should bake to exactly one sub-asset"
    );
    assert_eq!(
        entry.sub_assets[0].file_id,
        ClassId::Sprite.canonical_subobject_fid()
    );
    assert_eq!(&*entry.sub_assets[0].name, "Icon");

    fs::remove_dir_all(&root).ok();
}

/// Cache integrity: when neither the `.meta` nor the asset file mtime
/// changed between bakes, the second bake reuses cached entries
/// verbatim and produces a byte-identical `asset-db.bin`. Pins the
/// fast-path that skips the asset stat when the `.meta` mtime matches.
#[test]
fn cache_hit_path_byte_identical_rebake() {
    let root = unique_tmp("cache-hit-bytes");
    let _ = fs::remove_dir_all(&root);
    make_fixture(&root);

    let _out_dir = bake_at(&root);
    let first = fs::read(db_file(&root)).unwrap();

    // Sleep ≥1ms so any spurious mtime-on-touch debug couldn't false-hit.
    // We don't TOUCH anything, but we also don't want to mask a bug where
    // bake re-stamps an mtime as a side-effect.
    std::thread::sleep(std::time::Duration::from_millis(5));

    let _out_dir = bake_at(&root);
    let second = fs::read(db_file(&root)).unwrap();

    assert_eq!(first, second, "second-bake bytes drifted from first");
    fs::remove_dir_all(&root).ok();
}

/// Cache trade-off: pinning the warm-path assumption. Touching only
/// the asset file (without touching its `.meta`) does NOT invalidate the
/// cache — the fast path keys on `.meta` mtime alone. Under Unity's
/// importer this never happens (it stamps the `.meta` on every import),
/// so the cached row stays correct in practice. Out-of-Unity asset
/// edits land in the asset DB on the next `.meta` touch (or a manual
/// `rm asset-db.cache.bin`).
///
/// Documented assumption in `process_one`; test pins the current
/// behavior so any future invariant flip surfaces here.
#[test]
fn cache_does_not_detect_asset_only_touch() {
    let root = unique_tmp("cache-asset-only-touch");
    let _ = fs::remove_dir_all(&root);
    make_fixture(&root);

    let _out_dir = bake_at(&root);
    let asset_path = root.join("Assets/UI/Foo.prefab");
    let pre_meta_mtime = mtime_ns_of(&root.join("Assets/UI/Foo.prefab.meta"));

    // Touch only the asset (Unity workflow can never produce this).
    std::thread::sleep(std::time::Duration::from_millis(10));
    let now = filetime::FileTime::now();
    set_mtime(&asset_path, now);

    let _out_dir = bake_at(&root);
    let c = store::read_cache(&cache_file(&root)).unwrap();
    let foo = c
        .entries
        .iter()
        .find(|e| &*e.hint == "Assets/UI/Foo.prefab")
        .unwrap();
    // The cache's recorded asset_mtime is the *original* — fast path
    // bypassed the companion stat, so the bake never noticed the touch.
    assert_ne!(
        foo.asset_mtime_ns,
        mtime_ns_of(&asset_path),
        "asset-only touch was unexpectedly detected (fast path may have changed)"
    );
    // Sanity: the meta mtime IS the value we'd expect (unchanged across
    // bakes), confirming the fast path actually fired.
    assert_eq!(
        foo.meta_mtime_ns, pre_meta_mtime,
        "meta mtime drifted between bakes — fixture leaked",
    );
    fs::remove_dir_all(&root).ok();
}

/// Cache integrity: when both `.meta` and asset get touched (normal
/// Unity reimport pattern), the second bake re-parses and the cache
/// records the fresh mtimes. The most common warm-bake-invalidation
/// case in practice.
#[test]
fn cache_invalidates_on_meta_and_asset_touch() {
    let root = unique_tmp("cache-both-touch");
    let _ = fs::remove_dir_all(&root);
    make_fixture(&root);

    let _out_dir = bake_at(&root);
    let meta_path = root.join("Assets/UI/Foo.prefab.meta");
    let asset_path = root.join("Assets/UI/Foo.prefab");

    std::thread::sleep(std::time::Duration::from_millis(10));
    let now = filetime::FileTime::now();
    set_mtime(&meta_path, now);
    set_mtime(&asset_path, now);

    let _out_dir = bake_at(&root);
    let c = store::read_cache(&cache_file(&root)).unwrap();
    let foo = c
        .entries
        .iter()
        .find(|e| &*e.hint == "Assets/UI/Foo.prefab")
        .unwrap();
    assert_eq!(foo.meta_mtime_ns, mtime_ns_of(&meta_path));
    assert_eq!(foo.asset_mtime_ns, mtime_ns_of(&asset_path));
    fs::remove_dir_all(&root).ok();
}

/// Cache integrity: changing the `.meta` mtime alone (without asset
/// edits) must still cause re-parse — the meta stat is what gates the
/// fast path, so a drift there has to fall through to the slow path.
#[test]
fn cache_invalidates_on_meta_mtime_drift() {
    let root = unique_tmp("cache-meta-drift");
    let _ = fs::remove_dir_all(&root);
    make_fixture(&root);

    let _out_dir = bake_at(&root);

    std::thread::sleep(std::time::Duration::from_millis(10));
    let meta_path = root.join("Assets/UI/Foo.prefab.meta");
    let now = filetime::FileTime::now();
    set_mtime(&meta_path, now);

    let _out_dir = bake_at(&root);
    let c = store::read_cache(&cache_file(&root)).unwrap();
    let foo = c
        .entries
        .iter()
        .find(|e| &*e.hint == "Assets/UI/Foo.prefab")
        .unwrap();
    let new_meta_mtime = mtime_ns_of(&meta_path);
    assert_eq!(
        foo.meta_mtime_ns, new_meta_mtime,
        "cache meta_mtime not bumped after meta touch"
    );
    fs::remove_dir_all(&root).ok();
}

/// Cache integrity: deleting an asset between bakes drops it from the
/// resulting database. Guards against a fast-path bug that might serve
/// the cached row even when the companion no longer exists.
#[test]
fn cache_drops_entry_when_asset_deleted() {
    let root = unique_tmp("cache-asset-deleted");
    let _ = fs::remove_dir_all(&root);
    make_fixture(&root);

    let _out_dir = bake_at(&root);
    let first = store::read(&db_file(&root)).unwrap();
    assert!(
        first
            .find_by_guid(0xaaaa1111aaaa1111aaaa1111aaaa1111_u128)
            .is_some(),
        "Foo prefab should exist before deletion",
    );

    fs::remove_file(root.join("Assets/UI/Foo.prefab")).unwrap();
    fs::remove_file(root.join("Assets/UI/Foo.prefab.meta")).unwrap();

    let _out_dir = bake_at(&root);
    let second = store::read(&db_file(&root)).unwrap();
    assert!(
        second
            .find_by_guid(0xaaaa1111aaaa1111aaaa1111aaaa1111_u128)
            .is_none(),
        "deleted Foo prefab still in db",
    );
    fs::remove_dir_all(&root).ok();
}

fn set_mtime(path: &Path, t: filetime::FileTime) {
    filetime::set_file_mtime(path, t).unwrap();
}

fn mtime_ns_of(path: &Path) -> u64 {
    let md = fs::metadata(path).unwrap();
    let st = md
        .modified()
        .unwrap()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap();
    st.as_nanos() as u64
}

/// A corrupt `asset-db.cache.bin` (wrong magic, truncated bytes, schema
/// drift, …) must NOT crash the bake. The bake's contract is "rebuild
/// from scratch if the cache is unreadable" — guards against a hand-
/// edited cache file or a half-written one from a kill -9'd bake.
#[test]
fn bake_recovers_from_corrupt_cache() {
    let root = unique_tmp("corrupt-cache");
    let _ = fs::remove_dir_all(&root);
    make_fixture(&root);

    // First bake → produces a real cache file.
    let _out_dir = bake_at(&root);
    let cache_path = cache_file(&root);
    assert!(cache_path.exists());

    // Corrupt it: replace contents with garbage. The bake-side decode
    // hits a magic mismatch / decode error and falls back to "empty
    // cache" path.
    fs::write(&cache_path, b"this is not a valid cache file").unwrap();

    // Should not panic; should produce a correct asset-db.bin.
    let _out_dir = bake_at(&root);
    let db = store::read(&db_file(&root)).unwrap();
    assert_eq!(
        db.entries.len(),
        3,
        "bake recovered, but entry count drifted: {}",
        db.entries.len(),
    );
    fs::remove_dir_all(&root).ok();
}

/// Zero-asset-but-valid-project: a Unity project with `Assets/` +
/// `ProjectSettings/` but no actual assets must still produce a valid
/// empty `asset-db.bin`, not panic at the dedup pass.
#[test]
fn empty_project_bakes_cleanly() {
    let root = unique_tmp("empty-project");
    let _ = fs::remove_dir_all(&root);
    fs::create_dir_all(root.join("Assets")).unwrap();
    fs::create_dir_all(root.join("ProjectSettings")).unwrap();
    write(
        &root.join("ProjectSettings/ProjectVersion.txt"),
        "m_EditorVersion: 2022.3.0f1\n",
    );

    let _out_dir = bake_at(&root);
    let db = store::read(&db_file(&root)).unwrap();
    assert_eq!(db.entries.len(), 0);
    assert_eq!(db.script_types.len(), 0);
    fs::remove_dir_all(&root).ok();
}

/// Deeply-nested asset (10+ dirs) still gets indexed. The walker has
/// no built-in depth limit, but `ignore::WalkBuilder` does expose one;
/// pin that we don't accidentally enable a low default.
#[test]
fn deeply_nested_assets_are_indexed() {
    let root = unique_tmp("deep-nesting");
    let _ = fs::remove_dir_all(&root);
    fs::create_dir_all(root.join("ProjectSettings")).unwrap();
    write(
        &root.join("ProjectSettings/ProjectVersion.txt"),
        "m_EditorVersion: 2022.3.0f1\n",
    );

    // 12 levels deep — well beyond any sane production project but
    // a useful contract pin.
    let mut deep = root.join("Assets");
    for i in 0..12 {
        deep = deep.join(format!("L{i}"));
    }
    write(
        &deep.join("Deep.prefab"),
        "--- !u!1001 &100100000\nPrefabInstance: {}\n",
    );
    write(
        &deep.join("Deep.prefab.meta"),
        "fileFormatVersion: 2\nguid: deadbeefdeadbeefdeadbeefdeadbeef\nPrefabImporter: {}\n",
    );

    let _out_dir = bake_at(&root);
    let db = store::read(&db_file(&root)).unwrap();
    assert!(
        db.find_by_guid(0xdeadbeefdeadbeefdeadbeefdeadbeef_u128)
            .is_some(),
        "deeply-nested prefab not indexed",
    );
    fs::remove_dir_all(&root).ok();
}

/// Pin: a `.gitignore` *inside* `Assets/` (or `Packages/`) does NOT
/// hide its targets from the bake. Unity itself doesn't honor
/// gitignore — and a gitignored `.cs.meta` or `.asset` still has a
/// Unity-assigned guid that other prefabs can reference. Excluding
/// would cause spurious "unresolved asset reference" hard-fails on
/// the consumer side. Pins the `standard_filters(false)` walker
/// behavior set in `src/walk.rs`.
///
/// Out-of-tree `.gitignore` paths (`<project>/.gitignore`, the
/// usual Unity-project shape that excludes Library/Temp/) stay
/// effective because the walker is rooted at Assets/Packages — those
/// paths are siblings, never visited. Pinned by
/// `walker_ignores_library_temp_and_unity_hidden`.
#[test]
fn walker_does_not_honor_gitignore_inside_assets() {
    let root = unique_tmp("inside-gitignore");
    let _ = fs::remove_dir_all(&root);
    fs::create_dir_all(root.join("ProjectSettings")).unwrap();
    write(
        &root.join("ProjectSettings/ProjectVersion.txt"),
        "m_EditorVersion: 2022.3.0f1\n",
    );

    let prefab_body = "--- !u!1001 &100100000\nPrefabInstance: {}\n";
    let make_meta =
        |guid: &str| format!("fileFormatVersion: 2\nguid: {guid}\nPrefabImporter: {{}}\n");

    // A `.gitignore` inside Assets/Foo/ that ignores the prefab.
    write(&root.join("Assets/Foo/.gitignore"), "Ignored.prefab\n");
    write(&root.join("Assets/Foo/Ignored.prefab"), prefab_body);
    write(
        &root.join("Assets/Foo/Ignored.prefab.meta"),
        &make_meta("aaaa1111aaaa1111aaaa1111aaaa1111"),
    );
    // A normal sibling that's not ignored.
    write(&root.join("Assets/Foo/Kept.prefab"), prefab_body);
    write(
        &root.join("Assets/Foo/Kept.prefab.meta"),
        &make_meta("bbbb2222bbbb2222bbbb2222bbbb2222"),
    );

    let _out_dir = bake_at(&root);
    let db = store::read(&db_file(&root)).unwrap();
    let hints: Vec<&str> = db.entries.iter().map(|e| &*e.hint).collect();

    assert!(
        hints.contains(&"Assets/Foo/Ignored.prefab"),
        "inside-Assets gitignore was honored (should not be); hints: {hints:?}",
    );
    assert!(
        hints.contains(&"Assets/Foo/Kept.prefab"),
        "Kept.prefab missing: {hints:?}",
    );
    fs::remove_dir_all(&root).ok();
}

/// Walker ignore audit: pin the four paths that must NEVER surface in
/// the asset DB.
/// 1. `Library/` — gitignored, regenerated by Unity; baking it would
///    self-reference convert artifacts on rebuild.
/// 2. `Temp/` — Unity scratch space, similarly gitignored.
/// 3. `Assets/.Hidden/` — Unity-hidden by convention (leading dot).
/// 4. `Assets/Foo~/` — Unity-hidden by convention (trailing tilde).
///
/// The first two are caught by `ignore`'s gitignore handling; the last
/// two by the `is_unity_hidden` filter in `walk.rs`. Both contracts
/// pin here.
#[test]
fn walker_ignores_library_temp_and_unity_hidden() {
    let root = unique_tmp("walker-ignores");
    let _ = fs::remove_dir_all(&root);
    fs::create_dir_all(root.join("ProjectSettings")).unwrap();
    write(
        &root.join("ProjectSettings/ProjectVersion.txt"),
        "m_EditorVersion: 2022.3.0f1\n",
    );
    // gitignore for the regenerable dirs.
    write(&root.join(".gitignore"), "/Library/\n/Temp/\n");

    let make_meta = |guid: &str| {
        format!("fileFormatVersion: 2\nguid: {guid}\nPrefabImporter: {{}}\n")
    };
    let make_prefab = "--- !u!1001 &100100000\nPrefabInstance: {}\n";

    // Real, must survive.
    write(&root.join("Assets/Visible/Bar.prefab"), make_prefab);
    write(
        &root.join("Assets/Visible/Bar.prefab.meta"),
        &make_meta("aaaa1111aaaa1111aaaa1111aaaa1111"),
    );
    // Library/ — gitignored.
    write(&root.join("Library/Scratch/InLib.prefab"), make_prefab);
    write(
        &root.join("Library/Scratch/InLib.prefab.meta"),
        &make_meta("bbbb2222bbbb2222bbbb2222bbbb2222"),
    );
    // Temp/ — gitignored.
    write(&root.join("Temp/Scratch/InTemp.prefab"), make_prefab);
    write(
        &root.join("Temp/Scratch/InTemp.prefab.meta"),
        &make_meta("cccc3333cccc3333cccc3333cccc3333"),
    );
    // .Hidden/ — Unity-hidden.
    write(&root.join("Assets/.Hidden/InHidden.prefab"), make_prefab);
    write(
        &root.join("Assets/.Hidden/InHidden.prefab.meta"),
        &make_meta("dddd4444dddd4444dddd4444dddd4444"),
    );
    // Foo~/ — Unity-hidden.
    write(&root.join("Assets/Foo~/InTilde.prefab"), make_prefab);
    write(
        &root.join("Assets/Foo~/InTilde.prefab.meta"),
        &make_meta("eeee5555eeee5555eeee5555eeee5555"),
    );

    let _out_dir = bake_at(&root);
    let db = store::read(&db_file(&root)).unwrap();

    let hints: Vec<&str> = db.entries.iter().map(|e| &*e.hint).collect();
    assert!(
        hints.contains(&"Assets/Visible/Bar.prefab"),
        "real asset missing: {hints:?}",
    );
    for ignored in [
        "Library/Scratch/InLib.prefab",
        "Temp/Scratch/InTemp.prefab",
        "Assets/.Hidden/InHidden.prefab",
        "Assets/Foo~/InTilde.prefab",
    ] {
        assert!(
            !hints.contains(&ignored),
            "expected to be ignored, found: {ignored}",
        );
    }
    assert_eq!(db.entries.len(), 1, "only the visible asset should bake");

    fs::remove_dir_all(&root).ok();
}

#[test]
fn cache_file_lives_alongside_bin() {
    let root = unique_tmp("cache-file");
    let _ = fs::remove_dir_all(&root);
    make_fixture(&root);

    let _out_dir = bake_at(&root);
    let cache = cache_file(&root);
    assert!(
        cache.exists(),
        "cache file not created at {}",
        cache.display()
    );

    // Cache stores hints + mtimes; convert artifact does not.
    let c = store::read_cache(&cache).unwrap();
    assert_eq!(c.entries.len(), 3);
    // Hints are project-root-relative so Assets/ and Packages/ share one scheme.
    let foo = c
        .entries
        .iter()
        .find(|e| &*e.hint == "Assets/UI/Foo.prefab")
        .unwrap();
    assert!(foo.meta_mtime_ns > 0);
    assert!(foo.asset_mtime_ns > 0);

    fs::remove_dir_all(&root).ok();
}