fallow-graph 3.22.0

Module graph construction and import resolution for fallow codebase intelligence
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
//! Persisted graph-cache identity contracts and on-disk store.
//!
//! The manifest types here define the invalidation surface a persisted graph
//! cache must satisfy before a cached graph can be trusted. Exact manifest hits
//! can reuse a previously-built `ModuleGraph`; stable-key resolver hits can
//! reuse resolver output and rebuild the graph with current `FileId`s.

use std::sync::Arc;

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

use fallow_types::discover::{DiscoveredFile, FileId, StableFileKey};
use fallow_types::extract::{ImportInfo, ReExportInfo};
use fallow_types::source_fingerprint::SourceFingerprint;
use oxc_span::Span;

use crate::resolve::{
    ResolveResult, ResolvedImport, ResolvedModule, ResolvedProject, ResolvedReExport,
    ResolvedReplacedModuleTarget,
};

mod store;

pub use store::GraphCacheStore;

/// Persisted graph cache schema version.
///
/// Bump this whenever the serialized shape of the persisted graph (any of the
/// graph types that derive serde for the cache, the manifest types, or the
/// store envelope) changes, so a stale `graph-cache.bin` written by an older
/// binary is rejected rather than deserialized into the wrong shape.
///
/// Bump it for import-resolution semantics changes too, not only for wire-shape
/// changes. The manifest compares this constant, the cache mode, and per-file
/// fingerprints, and carries no binary version, so a cache written before a
/// classification change replays the old classification verbatim on an
/// unmodified tree and silently hides the new behaviour. The same applies to
/// plugin config extraction, which seeds entry points and path aliases.
///
/// Bumped to 17 for issue #2031: cached resolver output retains canonical
/// test-root replacements and ESM/CommonJS mechanisms, while profiled graphs
/// retain target-sparse reachability masks plus exact compact reference routes.
/// Ordinary graphs omit unused provenance. Versions 7 through 16 were used by
/// published development commits for this change, so the final version remains
/// 17 rather than reusing a potentially stale intermediate cache version.
///
/// Bumped to 18 for issue #2083: reference provenance moved out of
/// `SymbolReference` into the per-export `reference_paths` side table, changing
/// the persisted layout of every export's reference list.
///
/// Bumped to 19 for issue #2084 (PR #2096): profiled test-reachability masking
/// now falls back to the legacy fail-open classification when a graph would
/// need more than the mask-profile cap, so caches written by the unbounded
/// profiling code must not replay their old profiled results on large
/// monorepos where the cap now engages.
///
/// Bumped to 20: cached re-export edges now carry the enclosing statement
/// span and the source string-literal span used to anchor unresolved-import
/// findings on the specifier. Warm 19 caches lack both spans.
///
/// Bumped to 21: persisted module graphs now carry the canonical effective
/// export index used for named and star re-export resolution. Warm 20 caches
/// lack that index and would replay the previous propagation semantics.
///
/// Bumped to 22: effective export names are interned once per graph and type
/// and value resolutions share one compact key. Warm 21 caches contain the
/// allocation-heavy intermediate index layout.
///
/// Bumped to 23: effective bindings distinguish direct declarations,
/// namespace objects, and implicit SFC default exports.
///
/// Bumped to 24: namespace-object bindings retain their source module so
/// consumers can enumerate the namespace through the canonical index.
///
/// Bumped to 25: export references retain their semantic Type or Value
/// namespace so one named re-export surface can route both without duplicate
/// graph symbols.
///
/// Bumped to 26: the effective export index retains typed declaration merge
/// groups for namespace-aware reference selection.
///
/// Bumped to 27: declaration merge groups are stored once and referenced by a
/// compact per-slot group identifier instead of cloning every group per slot.
///
/// Bumped to 28: reference-site deduplication now includes the exact import
/// span, so one consumer can retain multiple distinct imports of one binding.
///
/// Bumped to 29: resolved semantic facts retain directly required structural
/// type members used to protect explicit interface implementations.
///
/// Bumped to 30: declaration-merge references now propagate through named and
/// star barrel surfaces using the canonical effective binding group.
///
/// Bumped to 31 for issue #2213: speculative `__mocks__` sibling candidates
/// that resolve to package space are no longer emitted, so warm 30 caches
/// would keep replaying the phantom `@scope/__mocks__` package edges the
/// resolver no longer produces.
///
/// Bumped to 32: the effective export index resolves the type namespace in two
/// lanes (real declarations and value-derived fallbacks), stores a per-file
/// name index, and retains opaque bindings for known external named and
/// namespace re-export surfaces. Warm 31 payloads neither describe the same
/// structure nor carry those external bindings, so a consumed barrel export
/// could be falsely reported as unused.
///
/// Bumped to 33 for issue #2225: speculative root-level `__mocks__/<specifier>`
/// candidates from factory-less bare-specifier mocks now resolve to project
/// files. Warm 32 caches lack those edges, so root manual mocks would stay
/// reported as unused files.
/// Bumped to 34: the effective export index only seeds the value-derived type
/// fallback lane along re-export paths that reach a type-only re-export, and a
/// type query reads the value lane where that lane is absent. A warm 33 payload
/// is still read correctly, but a 33 reader would take an absent fallback lane
/// for an absent type meaning and report consumed exports as unused.
///
/// Bumped to 35 for issue #2348: JSX member-expression tags (`<SC.UsedStyle />`)
/// now record member accesses, and namespace narrowing bakes the credited
/// references into the persisted graph. Warm 34 caches carry the old empty
/// accessed-members verdict, so exports rendered only through JSX would stay
/// reported as unused on upgrade.
///
/// Bumped to 36 for issue #2356: `export` declarations inside a namespace
/// declared without the `export` keyword no longer contribute file-level
/// exports, and unused-export verdicts are read off the persisted export set.
/// Warm 35 caches still carry those local namespace members as file exports
/// and would keep reporting them as unused on upgrade.
///
/// Bumped to 37 for issue #2357 (36 was taken by issue #2356 while this
/// change was in review): a star re-export inside a
/// `declare module '<specifier>'` body no longer becomes a `ReExportEdge` on
/// the declaring module; the target's full ES star surface is credited
/// through a whole-module namespace edge instead, in both the type and the
/// value namespace and following the target's own `export *` and
/// `export * as ns` chains. Warm 36 caches persist the old edge, the
/// laundered re-export references, the runtime package usage for a
/// bare-specifier ambient star, and type-lane-only credits that leave the
/// value half of a same-name type and value pair unreferenced, and a
/// graph-cache hit would replay all of them.
///
/// Bumped to 38 for issue #2355 (37 was taken by issue #2357 while this
/// change was in review): Astro markup and MDX bodies now record member
/// accesses for member-expression component tags (`<SC.Card />`), and namespace
/// narrowing bakes the credited references into the persisted graph. Warm 37
/// caches carry the old empty accessed-members verdict for those consumers, so
/// exports rendered only in Astro or MDX markup would stay reported as unused
/// on upgrade.
///
/// Bumped to 39 for issues #2372 and #2373: a consumer that observes a whole
/// namespace object (a whole-object namespace use of an `import * as` or of an
/// `export * as` binding imported by name, a dynamic-import pattern match) and
/// an `export * as ns` chain an entry point exposes now credit the names the
/// target only exposes through its own `export *` and `export * as` chains,
/// and those references are baked into the persisted graph. Warm 38 caches
/// carry only the direct-export credit, so the star-forwarded and
/// nested-namespace exports would stay reported as unused on upgrade. The same
/// version covers the one direction that moves the other way: a plain
/// `export *` hop no longer carries a downstream `export * as default` onward,
/// so a chain behind such a namespace object can report one finding more than
/// a warm 38 cache holds.
///
/// Bumped to 40 for issue #2374: the per-module export-name index now treats
/// `default` as one importable name however each side spells it, so
/// `import { default as x } from './impl'`, an ambient
/// `declare module '<specifier>' { export { default } from './impl' }`, and a
/// plain `import x from './impl'` against an `export { x as default }` credit
/// the target's default export, and those references are baked into the
/// persisted graph. Warm 39 caches carry the uncredited verdict, so the
/// default export would stay reported as unused on upgrade.
///
/// Bumped to 41 for issue #2376 (40 was taken by issue #2374 while this
/// change was in review): an MDX prose line opening with the word
/// "import" (and any other line the statement parser rejects) no longer drops
/// every `import` of the file, so those files now resolve their imports and
/// credit their bodies. Warm 40 caches persist the import-less module and its
/// missing edges, so the imported modules would stay reported as unused files
/// on upgrade.
///
/// Bumped to 42 for issue #2377: a namespace import handed over whole (a call
/// argument, a JSX attribute value, an alias, an array or object literal
/// element, an initializer, an assignment right-hand side, a return value) no
/// longer narrows to its dotted accesses, and those mark-all verdicts are
/// baked into the persisted graph. Warm 41 caches carry the narrowed verdict,
/// so the siblings the consumer can still reach would stay reported as unused
/// on upgrade.
///
/// Bumped to 43 for issue #2365: `import X = require('./x')` now resolves to a
/// CommonJS namespace import edge, and the references it credits are baked into
/// the persisted graph. Warm 42 caches hold the module without that edge, so
/// the target would stay reported as an unused file on upgrade.
///
/// Bumped to 44 for issue #2375: `export type *` inside a `declare module`
/// body now carries a type-only-star symbol edge instead of a file-level star
/// re-export, and the type-lane-only credit it hands the target is baked into
/// the persisted graph. Warm 43 caches hold the re-export edge, the laundered
/// entry surface, and the value-lane credits, and a graph-cache hit skips the
/// build entirely.
///
/// Bumped to 45 for issues #2391, #2395, and #2397: namespace handover now
/// covers require, dynamic-import, Vue, and CSS Module bindings; ambient plain
/// stars retain star-surface exposure; equivalent default spellings share the
/// same duplicate-export rules; and proven CommonJS object maps use member
/// narrowing while resolved CommonJS and CSS Module default imports preserve
/// whole-object handoffs. Those reference outcomes are baked into the persisted
/// graph, so a warm 44 cache would skip the corrected build logic.
///
/// Bumped to 46 for PR #2436: a tsconfig reached through `references` without
/// `include` or `files` now applies only to files under its own directory
/// instead of every file, so `paths` from a referenced package no longer
/// resolve imports in sibling packages. Resolver output is persisted with the
/// graph and the cache key does not cover tsconfig scope, so a warm 45 cache
/// would keep replaying the leaked cross-package resolutions.
///
/// Bumped to 47 for issue #2444 (PR #2435): Yarn Plug'n'Play projects now
/// resolve bare specifiers through the inlined `.pnp.cjs` manifest, anchored
/// to the manifest directory, instead of missing on the empty `node_modules`
/// and falling back. The resolver output persisted in a warm 46 cache holds
/// those misses and would replay them as unresolved imports.
///
/// Bumped to 48: a directory a framework serves at a URL mount now resolves
/// root-absolute references from any HTML document, not only from Storybook's
/// preview fragments, and SvelteKit declares its `static/` directory as such a
/// mount. A warm 47 cache holds the resolver's earlier miss and would replay it
/// as an unresolved import plus an unused asset file.
pub const GRAPH_CACHE_VERSION: u32 = 48;

/// Cached form of a resolved target.
///
/// Internal targets are stored by stable file key, not by `FileId`, so resolver
/// output can be reused across a future FileId assignment shift. The persisted
/// `ModuleGraph` itself is still `FileId`-keyed; callers may only trust the
/// cached graph when the manifest's `file_id` assignments match, but they may
/// remap this resolver payload and rebuild the graph.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum CachedResolveResult {
    /// Resolved to a file within the project.
    InternalModule(StableFileKey),
    /// Resolved from CommonJS to a file within the project.
    CommonJsInternalModule(StableFileKey),
    /// Resolved to a project file through a framework convention auto-import.
    SyntheticAutoImport(StableFileKey),
    /// Resolved to a workspace or self package source file.
    InternalPackageModule {
        /// Stable source file reached by the package map.
        key: StableFileKey,
        /// Package name that was used in the import specifier.
        package_name: String,
    },
    /// Resolved from CommonJS to workspace or self-package source.
    CommonJsInternalPackageModule {
        /// Stable source file reached by the package map.
        key: StableFileKey,
        /// Package name used in the require specifier.
        package_name: String,
    },
    /// Resolved to a file outside the project.
    ExternalFile(PathBuf),
    /// Bare specifier.
    NpmPackage(String),
    /// Bare specifier referenced through CommonJS `require()`.
    CommonJsNpmPackage(String),
    /// Could not resolve.
    Unresolvable(String),
}

impl CachedResolveResult {
    fn from_resolve_result(
        target: &ResolveResult,
        key_by_file_id: &rustc_hash::FxHashMap<FileId, StableFileKey>,
    ) -> Option<Self> {
        Some(match target {
            ResolveResult::InternalModule(file_id) => {
                Self::InternalModule(key_by_file_id.get(file_id)?.clone())
            }
            ResolveResult::CommonJsInternalModule(file_id) => {
                Self::CommonJsInternalModule(key_by_file_id.get(file_id)?.clone())
            }
            ResolveResult::SyntheticAutoImport(file_id) => {
                Self::SyntheticAutoImport(key_by_file_id.get(file_id)?.clone())
            }
            ResolveResult::InternalPackageModule {
                file_id,
                package_name,
            } => Self::InternalPackageModule {
                key: key_by_file_id.get(file_id)?.clone(),
                package_name: package_name.clone(),
            },
            ResolveResult::CommonJsInternalPackageModule {
                file_id,
                package_name,
            } => Self::CommonJsInternalPackageModule {
                key: key_by_file_id.get(file_id)?.clone(),
                package_name: package_name.clone(),
            },
            ResolveResult::ExternalFile(path) => Self::ExternalFile(path.clone()),
            ResolveResult::NpmPackage(package_name) => Self::NpmPackage(package_name.clone()),
            ResolveResult::CommonJsNpmPackage(package_name) => {
                Self::CommonJsNpmPackage(package_name.clone())
            }
            ResolveResult::Unresolvable(specifier) => Self::Unresolvable(specifier.clone()),
        })
    }

    fn into_resolve_result(
        self,
        id_by_key: &rustc_hash::FxHashMap<StableFileKey, FileId>,
    ) -> Option<ResolveResult> {
        Some(match self {
            Self::InternalModule(key) => ResolveResult::InternalModule(*id_by_key.get(&key)?),
            Self::CommonJsInternalModule(key) => {
                ResolveResult::CommonJsInternalModule(*id_by_key.get(&key)?)
            }
            Self::SyntheticAutoImport(key) => {
                ResolveResult::SyntheticAutoImport(*id_by_key.get(&key)?)
            }
            Self::InternalPackageModule { key, package_name } => {
                ResolveResult::InternalPackageModule {
                    file_id: *id_by_key.get(&key)?,
                    package_name,
                }
            }
            Self::CommonJsInternalPackageModule { key, package_name } => {
                ResolveResult::CommonJsInternalPackageModule {
                    file_id: *id_by_key.get(&key)?,
                    package_name,
                }
            }
            Self::ExternalFile(path) => ResolveResult::ExternalFile(path),
            Self::NpmPackage(package_name) => ResolveResult::NpmPackage(package_name),
            Self::CommonJsNpmPackage(package_name) => {
                ResolveResult::CommonJsNpmPackage(package_name)
            }
            Self::Unresolvable(specifier) => ResolveResult::Unresolvable(specifier),
        })
    }
}

/// Cached import edge that can be restored without re-running resolution.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CachedResolvedImport {
    /// Import metadata mirrored from extraction or resolver synthesis.
    info: CachedImportInfo,
    /// Resolved target for this import edge.
    target: CachedResolveResult,
}

impl CachedResolvedImport {
    fn from_resolved(
        import: &ResolvedImport,
        key_by_file_id: &rustc_hash::FxHashMap<FileId, StableFileKey>,
    ) -> Option<Self> {
        Some(Self {
            info: CachedImportInfo::from(&import.info),
            target: CachedResolveResult::from_resolve_result(&import.target, key_by_file_id)?,
        })
    }

    fn into_resolved(
        self,
        id_by_key: &rustc_hash::FxHashMap<StableFileKey, FileId>,
    ) -> Option<ResolvedImport> {
        Some(ResolvedImport {
            info: self.info.into(),
            target: self.target.into_resolve_result(id_by_key)?,
        })
    }
}

/// Cached re-export edge that can be restored without re-running resolution.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CachedResolvedReExport {
    /// Re-export metadata mirrored from extraction.
    info: CachedReExportInfo,
    /// Resolved target for this re-export source.
    target: CachedResolveResult,
}

impl CachedResolvedReExport {
    fn from_resolved(
        re_export: &ResolvedReExport,
        key_by_file_id: &rustc_hash::FxHashMap<FileId, StableFileKey>,
    ) -> Option<Self> {
        Some(Self {
            info: CachedReExportInfo::from(&re_export.info),
            target: CachedResolveResult::from_resolve_result(&re_export.target, key_by_file_id)?,
        })
    }

    fn into_resolved(
        self,
        id_by_key: &rustc_hash::FxHashMap<StableFileKey, FileId>,
    ) -> Option<ResolvedReExport> {
        Some(ResolvedReExport {
            info: self.info.into(),
            target: self.target.into_resolve_result(id_by_key)?,
        })
    }
}

/// Cache-friendly mirror of [`ImportInfo`].
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CachedImportInfo {
    /// Import source specifier.
    source: String,
    /// Imported binding shape.
    imported_name: fallow_types::extract::ImportedName,
    /// Local binding name.
    local_name: String,
    /// Whether this import is type-only.
    is_type_only: bool,
    /// Whether this whole-module import only carries the target's type meanings.
    is_type_only_star: bool,
    /// Whether this import originated from a style context.
    from_style: bool,
    /// Span of the full import declaration.
    span: [u32; 2],
    /// Span of the import source literal.
    source_span: [u32; 2],
}

impl From<&ImportInfo> for CachedImportInfo {
    fn from(info: &ImportInfo) -> Self {
        Self {
            source: info.source.clone(),
            imported_name: info.imported_name.clone(),
            local_name: info.local_name.clone(),
            is_type_only: info.is_type_only,
            is_type_only_star: info.is_type_only_star,
            from_style: info.from_style,
            span: span_to_pair(info.span),
            source_span: span_to_pair(info.source_span),
        }
    }
}

impl From<CachedImportInfo> for ImportInfo {
    fn from(info: CachedImportInfo) -> Self {
        Self {
            source: info.source,
            imported_name: info.imported_name,
            local_name: info.local_name,
            is_type_only: info.is_type_only,
            is_type_only_star: info.is_type_only_star,
            from_style: info.from_style,
            span: pair_to_span(info.span),
            source_span: pair_to_span(info.source_span),
        }
    }
}

/// Cache-friendly mirror of [`ReExportInfo`].
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CachedReExportInfo {
    /// Re-export source specifier.
    source: String,
    /// Imported name from the source module.
    imported_name: String,
    /// Exported name from this module.
    exported_name: String,
    /// Whether this re-export is type-only.
    is_type_only: bool,
    /// Span of the re-export declaration.
    span: [u32; 2],
    /// Span of the enclosing re-export statement.
    statement_span: [u32; 2],
    /// Span of the source string literal.
    source_span: [u32; 2],
}

impl From<&ReExportInfo> for CachedReExportInfo {
    fn from(info: &ReExportInfo) -> Self {
        Self {
            source: info.source.clone(),
            imported_name: info.imported_name.clone(),
            exported_name: info.exported_name.clone(),
            is_type_only: info.is_type_only,
            span: span_to_pair(info.span),
            statement_span: span_to_pair(info.statement_span),
            source_span: span_to_pair(info.source_span),
        }
    }
}

impl From<CachedReExportInfo> for ReExportInfo {
    fn from(info: CachedReExportInfo) -> Self {
        Self {
            source: info.source,
            imported_name: info.imported_name,
            exported_name: info.exported_name,
            is_type_only: info.is_type_only,
            span: pair_to_span(info.span),
            statement_span: pair_to_span(info.statement_span),
            source_span: pair_to_span(info.source_span),
        }
    }
}

/// Cached resolver output for one module.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CachedResolvedModule {
    /// Stable identity of the source module.
    key: StableFileKey,
    /// Static import and require edges after resolution.
    resolved_imports: Vec<CachedResolvedImport>,
    /// Literal dynamic import edges after resolution.
    resolved_dynamic_imports: Vec<CachedResolvedImport>,
    /// Re-export source edges after resolution.
    re_exports: Vec<CachedResolvedReExport>,
    /// Dynamic import pattern targets, aligned with current extracted patterns.
    resolved_dynamic_pattern_targets: Vec<Vec<StableFileKey>>,
}

impl CachedResolvedModule {
    fn from_resolved(
        module: &ResolvedModule,
        key_by_file_id: &rustc_hash::FxHashMap<FileId, StableFileKey>,
    ) -> Option<Self> {
        Some(Self {
            key: key_by_file_id.get(&module.file_id)?.clone(),
            resolved_imports: module
                .resolved_imports
                .iter()
                .map(|import| CachedResolvedImport::from_resolved(import, key_by_file_id))
                .collect::<Option<Vec<_>>>()?,
            resolved_dynamic_imports: module
                .resolved_dynamic_imports
                .iter()
                .map(|import| CachedResolvedImport::from_resolved(import, key_by_file_id))
                .collect::<Option<Vec<_>>>()?,
            re_exports: module
                .re_exports
                .iter()
                .map(|re_export| CachedResolvedReExport::from_resolved(re_export, key_by_file_id))
                .collect::<Option<Vec<_>>>()?,
            resolved_dynamic_pattern_targets: module
                .resolved_dynamic_patterns
                .iter()
                .map(|(_, targets)| {
                    targets
                        .iter()
                        .map(|target| key_by_file_id.get(target).cloned())
                        .collect::<Option<Vec<_>>>()
                })
                .collect::<Option<Vec<_>>>()?,
        })
    }
}

/// Stable-key cache form of one resolved project-internal replacement.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct CachedResolvedReplacedModuleTarget {
    source_key: StableFileKey,
    target_key: StableFileKey,
}

impl CachedResolvedReplacedModuleTarget {
    fn from_resolved(
        target: ResolvedReplacedModuleTarget,
        key_by_file_id: &rustc_hash::FxHashMap<FileId, StableFileKey>,
    ) -> Option<Self> {
        Some(Self {
            source_key: key_by_file_id.get(&target.source_file)?.clone(),
            target_key: key_by_file_id.get(&target.target_file)?.clone(),
        })
    }

    fn into_resolved(
        self,
        id_by_key: &rustc_hash::FxHashMap<StableFileKey, FileId>,
    ) -> Option<ResolvedReplacedModuleTarget> {
        Some(ResolvedReplacedModuleTarget {
            source_file: *id_by_key.get(&self.source_key)?,
            target_file: *id_by_key.get(&self.target_key)?,
        })
    }
}

/// Cache-friendly mirror of the complete resolver output.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CachedResolvedProject {
    modules: Vec<CachedResolvedModule>,
    replaced_module_targets: Vec<CachedResolvedReplacedModuleTarget>,
}

/// Convert a resolved project into the compact graph-cache resolver payload.
#[must_use]
pub fn cache_resolved_project(
    root: &Path,
    files: &[DiscoveredFile],
    resolved: &ResolvedProject,
) -> Option<CachedResolvedProject> {
    let key_by_file_id = stable_key_by_file_id(root, files);
    let modules = resolved
        .modules
        .iter()
        .map(|module| CachedResolvedModule::from_resolved(module, &key_by_file_id))
        .collect::<Option<Vec<_>>>()?;
    let replaced_module_targets = resolved
        .replaced_module_targets
        .iter()
        .copied()
        .map(|target| CachedResolvedReplacedModuleTarget::from_resolved(target, &key_by_file_id))
        .collect::<Option<Vec<_>>>()?;
    Some(CachedResolvedProject {
        modules,
        replaced_module_targets,
    })
}

/// Restore a resolved project from cached resolver payloads and current parsed modules.
///
/// Returns `None` if the payload no longer aligns with the current parse result.
/// A normal graph-cache manifest hit should keep these aligned; this extra check
/// keeps corrupt or hand-edited cache files on the safe miss path.
#[must_use]
pub fn restore_resolved_project(
    root: &Path,
    modules: &[fallow_types::extract::ModuleInfo],
    files: &[DiscoveredFile],
    cached: &CachedResolvedProject,
) -> Option<ResolvedProject> {
    if modules.len() != cached.modules.len() {
        return None;
    }

    let mut indexes = RestoreResolvedModuleIndexes::new(root, modules, files);
    let resolved_modules = cached
        .modules
        .iter()
        .map(|entry| restore_cached_resolved_module(entry, &mut indexes))
        .collect::<Option<Vec<_>>>()?;
    let mut replaced_module_targets = cached
        .replaced_module_targets
        .iter()
        .cloned()
        .map(|target| target.into_resolved(&indexes.file_ids))
        .collect::<Option<Vec<_>>>()?;
    replaced_module_targets
        .sort_unstable_by_key(|target| (target.source_file.0, target.target_file.0));
    replaced_module_targets.dedup();
    Some(ResolvedProject {
        modules: resolved_modules,
        replaced_module_targets,
    })
}

struct RestoreResolvedModuleIndexes<'a> {
    file_ids: rustc_hash::FxHashMap<StableFileKey, FileId>,
    modules: rustc_hash::FxHashMap<StableFileKey, &'a fallow_types::extract::ModuleInfo>,
    paths: rustc_hash::FxHashMap<StableFileKey, std::path::PathBuf>,
}

impl<'a> RestoreResolvedModuleIndexes<'a> {
    fn new(
        root: &Path,
        modules: &'a [fallow_types::extract::ModuleInfo],
        files: &[DiscoveredFile],
    ) -> Self {
        let key_by_file_id = stable_key_by_file_id(root, files);
        let id_by_key: rustc_hash::FxHashMap<_, _> = key_by_file_id
            .iter()
            .map(|(file_id, key)| (key.clone(), *file_id))
            .collect();
        let by_key: rustc_hash::FxHashMap<_, _> = modules
            .iter()
            .filter_map(|module| {
                key_by_file_id
                    .get(&module.file_id)
                    .map(|key| (key.clone(), module))
            })
            .collect();
        let path_by_key: rustc_hash::FxHashMap<_, _> = files
            .iter()
            .map(|file| {
                (
                    StableFileKey::from_root_relative(root, &file.path),
                    file.path.clone(),
                )
            })
            .collect();

        Self {
            file_ids: id_by_key,
            modules: by_key,
            paths: path_by_key,
        }
    }
}

fn restore_cached_resolved_module(
    entry: &CachedResolvedModule,
    indexes: &mut RestoreResolvedModuleIndexes<'_>,
) -> Option<ResolvedModule> {
    let module = indexes.modules.remove(&entry.key)?;
    let path = indexes.paths.get(&entry.key)?.clone();
    let resolved_dynamic_pattern_targets =
        restore_dynamic_pattern_targets(entry, module, &indexes.file_ids)?;

    Some(ResolvedModule {
        file_id: module.file_id,
        path,
        exports: Arc::clone(&module.exports),
        re_exports: entry
            .re_exports
            .iter()
            .cloned()
            .map(|re_export| re_export.into_resolved(&indexes.file_ids))
            .collect::<Option<Vec<_>>>()?,
        resolved_imports: entry
            .resolved_imports
            .iter()
            .cloned()
            .map(|import| import.into_resolved(&indexes.file_ids))
            .collect::<Option<Vec<_>>>()?,
        resolved_dynamic_imports: entry
            .resolved_dynamic_imports
            .iter()
            .cloned()
            .map(|import| import.into_resolved(&indexes.file_ids))
            .collect::<Option<Vec<_>>>()?,
        resolved_dynamic_patterns: module
            .dynamic_import_patterns
            .iter()
            .cloned()
            .zip(resolved_dynamic_pattern_targets)
            .collect(),
        member_accesses: Arc::clone(&module.member_accesses),
        semantic_facts: Arc::clone(&module.semantic_facts),
        whole_object_uses: Arc::clone(&module.whole_object_uses),
        has_cjs_exports: module.has_cjs_exports,
        has_angular_component_template_url: module.has_angular_component_template_url,
        unused_import_bindings: module.unused_import_bindings.iter().cloned().collect(),
        type_referenced_import_bindings: module.type_referenced_import_bindings.clone(),
        value_referenced_import_bindings: module.value_referenced_import_bindings.clone(),
        namespace_object_aliases: module.namespace_object_aliases.clone(),
        exported_factory_returns: Arc::clone(&module.exported_factory_returns),
        exported_factory_return_object_shapes: Arc::clone(
            &module.exported_factory_return_object_shapes,
        ),
        type_member_types: Arc::clone(&module.type_member_types),
    })
}

fn restore_dynamic_pattern_targets(
    entry: &CachedResolvedModule,
    module: &fallow_types::extract::ModuleInfo,
    id_by_key: &rustc_hash::FxHashMap<StableFileKey, FileId>,
) -> Option<Vec<Vec<FileId>>> {
    if entry.resolved_dynamic_pattern_targets.len() != module.dynamic_import_patterns.len() {
        return None;
    }
    entry
        .resolved_dynamic_pattern_targets
        .iter()
        .map(|targets| {
            targets
                .iter()
                .map(|key| id_by_key.get(key).copied())
                .collect::<Option<Vec<_>>>()
        })
        .collect()
}

fn stable_key_by_file_id(
    root: &Path,
    files: &[DiscoveredFile],
) -> rustc_hash::FxHashMap<FileId, StableFileKey> {
    files
        .iter()
        .map(|file| (file.id, StableFileKey::from_root_relative(root, &file.path)))
        .collect()
}

fn span_to_pair(span: Span) -> [u32; 2] {
    [span.start, span.end]
}

fn pair_to_span(pair: [u32; 2]) -> Span {
    Span::new(pair[0], pair[1])
}

/// Serialize an [`oxc_span::Span`] as a `[start, end]` `u32` pair.
///
/// `oxc_span::Span` does not enable its own serde feature in this workspace, so
/// the graph types that carry spans route them through this module via
/// `#[serde(with = "crate::cache::span_serde")]`. A 2-element array keeps the
/// postcard encoding compact (two varints) and is trivially lossless: a `Span`
/// is fully described by its `start` / `end` offsets.
pub(crate) mod span_serde {
    use oxc_span::Span;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    #[expect(
        clippy::trivially_copy_pass_by_ref,
        reason = "serde `serialize_with` / `with` requires a `&T` signature"
    )]
    pub fn serialize<S: Serializer>(span: &Span, serializer: S) -> Result<S::Ok, S::Error> {
        [span.start, span.end].serialize(serializer)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Span, D::Error> {
        let [start, end] = <[u32; 2]>::deserialize(deserializer)?;
        Ok(Span::new(start, end))
    }
}

/// Lossless cache (de)serialization for `Vec<MemberInfo>`.
///
/// `fallow_types::extract::MemberInfo` derives only `serde::Serialize`, and its
/// `span` field uses `serialize_with` with no matching deserializer, so it
/// cannot be deserialized through a plain derive. Rather than change the shared
/// type's serde shape (which would ripple into JSON output), the cache mirrors
/// it field-for-field into a dedicated `CachedMemberInfo` and converts both
/// ways. Every `MemberInfo` field is carried, so the round-trip is lossless.
pub(crate) mod member_serde {
    use fallow_types::extract::{MemberInfo, MemberKind};
    use oxc_span::Span;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    #[derive(Serialize, Deserialize)]
    struct CachedMemberInfo {
        name: String,
        kind: MemberKind,
        span: [u32; 2],
        has_decorator: bool,
        decorator_names: Vec<String>,
        is_instance_returning_static: bool,
        is_self_returning: bool,
    }

    impl From<&MemberInfo> for CachedMemberInfo {
        fn from(member: &MemberInfo) -> Self {
            Self {
                name: member.name.clone(),
                kind: member.kind,
                span: [member.span.start, member.span.end],
                has_decorator: member.has_decorator,
                decorator_names: member.decorator_names.clone(),
                is_instance_returning_static: member.is_instance_returning_static,
                is_self_returning: member.is_self_returning,
            }
        }
    }

    impl From<CachedMemberInfo> for MemberInfo {
        fn from(cached: CachedMemberInfo) -> Self {
            Self {
                name: cached.name,
                kind: cached.kind,
                span: Span::new(cached.span[0], cached.span[1]),
                has_decorator: cached.has_decorator,
                decorator_names: cached.decorator_names,
                is_instance_returning_static: cached.is_instance_returning_static,
                is_self_returning: cached.is_self_returning,
            }
        }
    }

    pub fn serialize<S: Serializer>(
        members: &[MemberInfo],
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        let mirror: Vec<CachedMemberInfo> = members.iter().map(CachedMemberInfo::from).collect();
        mirror.serialize(serializer)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Vec<MemberInfo>, D::Error> {
        let mirror = Vec::<CachedMemberInfo>::deserialize(deserializer)?;
        Ok(mirror.into_iter().map(MemberInfo::from).collect())
    }
}

/// Option dimensions that affect graph construction.
///
/// The hashes are intentionally opaque to this crate. Callers decide which
/// resolver/plugin/entry-point inputs feed each hash, while this contract keeps
/// graph-cache validation explicit and typed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct GraphCacheMode {
    /// Import resolver and tsconfig-relevant options.
    pub resolver_options_hash: u64,
    /// Entry point set and reachability root options.
    pub entry_points_hash: u64,
    /// Plugin-derived graph-affecting configuration.
    pub plugin_config_hash: u64,
}

impl GraphCacheMode {
    /// Build a mode from explicit hash dimensions.
    #[must_use]
    pub const fn new(
        resolver_options_hash: u64,
        entry_points_hash: u64,
        plugin_config_hash: u64,
    ) -> Self {
        Self {
            resolver_options_hash,
            entry_points_hash,
            plugin_config_hash,
        }
    }
}

/// Source freshness for one file in a graph-cache manifest.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct GraphCacheFile {
    /// Persistable identity for the file.
    pub key: StableFileKey,
    /// Current in-memory identifier for the file.
    ///
    /// The stable key is the durable identity, but the persisted `ModuleGraph`
    /// is still `FileId`-keyed. Until a future graph-cache format remaps graph
    /// edges through stable keys, a changed assignment must miss rather than
    /// trust a graph whose `modules[file_id]` indexes point at different files.
    pub file_id: FileId,
    /// Metadata fingerprint for cache invalidation.
    pub fingerprint: SourceFingerprint,
}

impl GraphCacheFile {
    /// Build a graph-cache file row from a discovered file and fingerprint.
    #[must_use]
    fn from_discovered_file(
        root: &Path,
        file: &DiscoveredFile,
        fingerprint: SourceFingerprint,
    ) -> Self {
        Self {
            key: StableFileKey::from_root_relative(root, &file.path),
            file_id: file.id,
            fingerprint,
        }
    }
}

/// Manifest inputs required to trust a persisted graph cache entry.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct GraphCacheManifest {
    /// Schema version used by the persisted graph-cache entry.
    pub version: u32,
    /// Graph-affecting option dimensions.
    pub mode: GraphCacheMode,
    /// Stable file identities, current FileId assignments, and freshness metadata.
    pub files: Vec<GraphCacheFile>,
}

impl GraphCacheManifest {
    /// Build a manifest and sort files by stable key for deterministic compare.
    #[must_use]
    fn new(mode: GraphCacheMode, mut files: Vec<GraphCacheFile>) -> Self {
        sort_files(&mut files);
        Self {
            version: GRAPH_CACHE_VERSION,
            mode,
            files,
        }
    }

    /// Build a manifest from discovered files plus a fingerprint provider.
    pub fn from_discovered_files(
        root: &Path,
        files: &[DiscoveredFile],
        mode: GraphCacheMode,
        mut fingerprint_for_path: impl FnMut(&Path) -> SourceFingerprint,
    ) -> Self {
        let rows = files
            .iter()
            .map(|file| {
                GraphCacheFile::from_discovered_file(root, file, fingerprint_for_path(&file.path))
            })
            .collect();
        Self::new(mode, rows)
    }

    /// True when a persisted manifest matches the current graph inputs.
    #[must_use]
    pub fn matches_inputs(&self, current: &Self) -> bool {
        self.version == GRAPH_CACHE_VERSION
            && current.version == GRAPH_CACHE_VERSION
            && self.mode == current.mode
            && self.files == current.files
    }

    /// True when a persisted resolver payload can be remapped to current FileIds.
    ///
    /// Unlike [`Self::matches_inputs`], this intentionally ignores each row's
    /// `file_id`. It is not sufficient to trust the persisted `ModuleGraph`, but
    /// it is sufficient to reuse stable-keyed resolver output and rebuild the
    /// graph with current FileIds.
    #[must_use]
    pub fn matches_resolution_inputs(&self, current: &Self) -> bool {
        self.version == GRAPH_CACHE_VERSION
            && current.version == GRAPH_CACHE_VERSION
            && self.mode == current.mode
            && self.files.len() == current.files.len()
            && self
                .files
                .iter()
                .zip(current.files.iter())
                .all(|(cached, current)| {
                    cached.key == current.key && cached.fingerprint == current.fingerprint
                })
    }
}

fn sort_files(files: &mut [GraphCacheFile]) {
    files.sort_unstable_by(|a, b| a.key.cmp(&b.key));
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};

    use fallow_types::discover::FileId;
    use rustc_hash::FxHashMap;

    use super::*;

    fn file(id: u32, path: &str) -> DiscoveredFile {
        DiscoveredFile {
            id: FileId(id),
            path: PathBuf::from(path),
            size_bytes: 1,
        }
    }

    fn mode() -> GraphCacheMode {
        GraphCacheMode::new(1, 2, 3)
    }

    fn fingerprints(pairs: &[(&str, SourceFingerprint)]) -> FxHashMap<PathBuf, SourceFingerprint> {
        pairs
            .iter()
            .map(|(path, fingerprint)| (PathBuf::from(path), *fingerprint))
            .collect()
    }

    fn manifest(
        files: &[DiscoveredFile],
        mode: GraphCacheMode,
        map: &FxHashMap<PathBuf, SourceFingerprint>,
    ) -> GraphCacheManifest {
        GraphCacheManifest::from_discovered_files(Path::new("/project"), files, mode, |path| {
            *map.get(path).unwrap()
        })
    }

    fn import_info(source: &str) -> ImportInfo {
        ImportInfo {
            source: source.to_string(),
            imported_name: fallow_types::extract::ImportedName::SideEffect,
            local_name: String::new(),
            is_type_only: false,
            is_type_only_star: false,
            from_style: false,
            span: Span::new(0, 0),
            source_span: Span::new(0, 0),
        }
    }

    #[test]
    fn cached_import_info_round_trip_keeps_every_field() {
        // The resolver payload is replayed into a fresh graph build, so any
        // field the mirror drops silently changes analysis behaviour behind a
        // cache hit. Compare the debug rendering so a future field that is not
        // mirrored fails here instead of in a warm-only output diff.
        let original = ImportInfo {
            source: "./impl".to_string(),
            imported_name: fallow_types::extract::ImportedName::Namespace,
            local_name: "ns".to_string(),
            is_type_only: true,
            is_type_only_star: true,
            from_style: true,
            span: Span::new(3, 41),
            source_span: Span::new(17, 25),
        };

        let restored = ImportInfo::from(CachedImportInfo::from(&original));

        assert_eq!(format!("{restored:?}"), format!("{original:?}"));
    }

    #[test]
    fn manifest_sorts_by_stable_file_key() {
        let files = vec![file(0, "/project/src/z.ts"), file(1, "/project/src/a.ts")];
        let map = fingerprints(&[
            ("/project/src/z.ts", SourceFingerprint::new(10, 1)),
            ("/project/src/a.ts", SourceFingerprint::new(20, 1)),
        ]);

        let manifest = manifest(&files, mode(), &map);

        let keys: Vec<&str> = manifest
            .files
            .iter()
            .map(|file| file.key.as_str())
            .collect();
        assert_eq!(keys, vec!["src/a.ts", "src/z.ts"]);
    }

    #[test]
    fn manifest_misses_on_file_id_shift_until_graph_remap_exists() {
        let before = vec![file(0, "/project/src/a.ts"), file(1, "/project/src/c.ts")];
        let after = vec![file(9, "/project/src/c.ts"), file(2, "/project/src/a.ts")];
        let map = fingerprints(&[
            ("/project/src/a.ts", SourceFingerprint::new(10, 1)),
            ("/project/src/c.ts", SourceFingerprint::new(20, 1)),
        ]);

        let cached = manifest(&before, mode(), &map);
        let current = manifest(&after, mode(), &map);

        assert!(
            !cached.matches_inputs(&current),
            "the persisted graph is still FileId-keyed, so FileId shifts cannot trust it"
        );
        assert!(
            cached.matches_resolution_inputs(&current),
            "stable-keyed resolver payloads may be remapped across FileId shifts"
        );
    }

    #[test]
    fn cached_resolve_result_remaps_internal_targets_by_stable_key() {
        let key_a = StableFileKey::from_root_relative(
            Path::new("/project"),
            Path::new("/project/src/a.ts"),
        );
        let key_b = StableFileKey::from_root_relative(
            Path::new("/project"),
            Path::new("/project/src/b.ts"),
        );
        let key_by_file_id =
            FxHashMap::from_iter([(FileId(0), key_a.clone()), (FileId(1), key_b.clone())]);
        let id_by_key = FxHashMap::from_iter([(key_a, FileId(7)), (key_b, FileId(9))]);

        let cached = CachedResolveResult::from_resolve_result(
            &ResolveResult::InternalPackageModule {
                file_id: FileId(1),
                package_name: "@scope/pkg".to_string(),
            },
            &key_by_file_id,
        )
        .expect("target file id should map to a stable key");

        let restored = cached
            .into_resolve_result(&id_by_key)
            .expect("stable key should map to current FileId");

        assert!(matches!(
            restored,
            ResolveResult::InternalPackageModule {
                file_id: FileId(9),
                ref package_name,
            } if package_name == "@scope/pkg"
        ));
    }

    #[test]
    fn cached_resolve_result_preserves_commonjs_provenance() {
        let key = StableFileKey::from_root_relative(
            Path::new("/project"),
            Path::new("/project/src/dependency.ts"),
        );
        let key_by_file_id = FxHashMap::from_iter([(FileId(3), key.clone())]);
        let id_by_key = FxHashMap::from_iter([(key, FileId(8))]);

        let cached = CachedResolveResult::from_resolve_result(
            &ResolveResult::CommonJsInternalModule(FileId(3)),
            &key_by_file_id,
        )
        .expect("CommonJS target should map to a stable key");
        let restored = cached
            .into_resolve_result(&id_by_key)
            .expect("stable key should map to the current FileId");

        assert!(matches!(
            restored,
            ResolveResult::CommonJsInternalModule(FileId(8))
        ));
    }

    #[test]
    fn cached_resolve_result_preserves_commonjs_bare_package_provenance() {
        let cached = CachedResolveResult::from_resolve_result(
            &ResolveResult::CommonJsNpmPackage("shared-package".to_string()),
            &FxHashMap::default(),
        )
        .expect("bare CommonJS package should not need a stable file key");
        let restored = cached
            .into_resolve_result(&FxHashMap::default())
            .expect("bare CommonJS package should restore without a file map");

        assert!(matches!(
            restored,
            ResolveResult::CommonJsNpmPackage(package_name)
                if package_name == "shared-package"
        ));
    }

    #[test]
    fn cache_resolved_project_rejects_unknown_internal_targets() {
        let files = vec![file(0, "/project/src/a.ts")];
        let module = ResolvedModule {
            file_id: FileId(0),
            path: PathBuf::from("/project/src/a.ts"),
            resolved_imports: vec![ResolvedImport {
                info: import_info("./missing"),
                target: ResolveResult::InternalModule(FileId(1)),
            }],
            ..ResolvedModule::default()
        };
        let project = ResolvedProject {
            modules: vec![module],
            replaced_module_targets: Vec::new(),
        };

        let cached = cache_resolved_project(Path::new("/project"), &files, &project);

        assert!(cached.is_none());
    }

    #[test]
    fn cached_replaced_target_remaps_both_file_ids_by_stable_key() {
        let source_key = StableFileKey::from_root_relative(
            Path::new("/project"),
            Path::new("/project/src/example.test.ts"),
        );
        let target_key = StableFileKey::from_root_relative(
            Path::new("/project"),
            Path::new("/project/src/dependency.ts"),
        );
        let key_by_file_id = FxHashMap::from_iter([
            (FileId(2), source_key.clone()),
            (FileId(3), target_key.clone()),
        ]);
        let id_by_key = FxHashMap::from_iter([(source_key, FileId(8)), (target_key, FileId(9))]);
        let resolved = ResolvedReplacedModuleTarget {
            source_file: FileId(2),
            target_file: FileId(3),
        };

        let cached = CachedResolvedReplacedModuleTarget::from_resolved(resolved, &key_by_file_id)
            .expect("both file ids should map to stable keys");
        let restored = cached
            .into_resolved(&id_by_key)
            .expect("both stable keys should map to current file ids");

        assert_eq!(
            restored,
            ResolvedReplacedModuleTarget {
                source_file: FileId(8),
                target_file: FileId(9),
            }
        );
    }

    #[test]
    fn cache_resolved_project_rejects_unknown_replacement_targets() {
        let files = vec![file(0, "/project/src/example.test.ts")];
        let project = ResolvedProject {
            modules: vec![ResolvedModule {
                file_id: FileId(0),
                path: PathBuf::from("/project/src/example.test.ts"),
                ..ResolvedModule::default()
            }],
            replaced_module_targets: vec![ResolvedReplacedModuleTarget {
                source_file: FileId(0),
                target_file: FileId(1),
            }],
        };

        let cached = cache_resolved_project(Path::new("/project"), &files, &project);

        assert!(cached.is_none());
    }

    #[test]
    fn manifest_misses_on_fingerprint_change() {
        let files = vec![file(0, "/project/src/a.ts")];
        let cached_map = fingerprints(&[("/project/src/a.ts", SourceFingerprint::new(10, 1))]);
        let current_map = fingerprints(&[("/project/src/a.ts", SourceFingerprint::new(11, 1))]);

        let cached = manifest(&files, mode(), &cached_map);
        let current = manifest(&files, mode(), &current_map);

        assert!(!cached.matches_inputs(&current));
    }

    #[test]
    fn manifest_misses_on_file_deletion() {
        let before = vec![
            file(0, "/project/src/a.ts"),
            file(1, "/project/src/deleted.ts"),
        ];
        let after = vec![file(0, "/project/src/a.ts")];
        let map = fingerprints(&[
            ("/project/src/a.ts", SourceFingerprint::new(10, 1)),
            ("/project/src/deleted.ts", SourceFingerprint::new(20, 1)),
        ]);

        let cached = manifest(&before, mode(), &map);
        let current = manifest(&after, mode(), &map);

        assert!(!cached.matches_inputs(&current));
    }

    #[test]
    fn manifest_misses_on_file_rename_with_same_fingerprint() {
        let before = vec![file(0, "/project/src/old.ts")];
        let after = vec![file(0, "/project/src/new.ts")];
        let map = fingerprints(&[
            ("/project/src/old.ts", SourceFingerprint::new(10, 1)),
            ("/project/src/new.ts", SourceFingerprint::new(10, 1)),
        ]);

        let cached = manifest(&before, mode(), &map);
        let current = manifest(&after, mode(), &map);

        assert!(!cached.matches_inputs(&current));
    }

    #[test]
    fn manifest_misses_on_workspace_scoped_file_set() {
        let full_project = vec![
            file(0, "/project/packages/app/src/index.ts"),
            file(1, "/project/packages/shared/src/index.ts"),
        ];
        let workspace_scoped = vec![file(0, "/project/packages/app/src/index.ts")];
        let map = fingerprints(&[
            (
                "/project/packages/app/src/index.ts",
                SourceFingerprint::new(10, 1),
            ),
            (
                "/project/packages/shared/src/index.ts",
                SourceFingerprint::new(20, 1),
            ),
        ]);

        let cached = manifest(&full_project, mode(), &map);
        let current = manifest(&workspace_scoped, mode(), &map);

        assert!(!cached.matches_inputs(&current));
        assert!(!cached.matches_resolution_inputs(&current));
    }

    #[test]
    fn manifest_misses_on_mode_change() {
        let files = vec![file(0, "/project/src/a.ts")];
        let map = fingerprints(&[("/project/src/a.ts", SourceFingerprint::new(10, 1))]);

        let cached = manifest(&files, mode(), &map);
        let current = manifest(&files, GraphCacheMode::new(1, 99, 3), &map);

        assert!(!cached.matches_inputs(&current));
    }

    #[test]
    fn manifest_misses_on_version_change() {
        let files = vec![file(0, "/project/src/a.ts")];
        let map = fingerprints(&[("/project/src/a.ts", SourceFingerprint::new(10, 1))]);
        let mut cached = manifest(&files, mode(), &map);
        let current = manifest(&files, mode(), &map);

        cached.version = GRAPH_CACHE_VERSION + 1;

        assert!(!cached.matches_inputs(&current));
    }
}