moss-core 0.2.0

Pure-Rust content engine for moss: AST, render, resolve, validate, frontmatter, schema.
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
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
//! Typed URL resolution: walk a [`Document`] and classify every
//! [`Url::Unresolved`] into a [`Url::Resolved`] with the right [`UrlKind`].
//!
//! Phase 4 PR6 (2026-05-28): replaces the two Stage 1 passes
//! (`markdown_refs::resolve_markdown_refs` for bare-filename image refs,
//! `markdown_links::resolve_markdown_links` for standard `[text](url)`
//! markdown links) with one typed visitor over the AST.
//!
//! Phase 4 PR7a (2026-05-28): `markdown_refs::resolve_markdown_refs` was
//! deleted after its parity with this visitor was proven.
//!
//! Phase 4 PR7a-stage1b (2026-05-28): `markdown_links::resolve_markdown_links`
//! was deleted in this PR. The visitor's `resolve_link_urls` now emits the
//! same `moss-resolved:<path>` sentinel Stage 1 emitted, leaving the URL
//! as `Url::Unresolved` so src-tauri's `classify_url_prod` decoder can
//! apply `page_map` / `external_url_map` / wikilink-class-aware decoding
//! unchanged. The sentinel IS the moss-core ↔ src-tauri layering seam:
//! moss-core resolves filesystem paths, src-tauri owns the deployed URL
//! space.
//!
//! ## Why one function, not two
//!
//! Stage 1 split bare-image refs and standard-link refs into separate
//! line-level passes because each had its own source-rewriting needs
//! (bare images got a relative path; standard links got a `moss-resolved:`
//! prefix that downstream code decoded). The typed AST distinguishes
//! `Inline::Image::src` (image refs, always asset URLs) from
//! `Inline::Link::url` (standard links, may be markdown targets or assets)
//! structurally — one walk classifies both correctly.
//!
//! ## Fence-awareness is automatic
//!
//! Stage 1 carried 100+ lines of fence-tracking regex per pass to skip
//! code blocks (since both passes scanned raw markdown text). The typed
//! AST handles this structurally — `Block::CodeBlock` and inline
//! `Inline::Code` are not visited by [`visit_urls_mut`]. The visitor
//! never sees a URL inside a code fence.
//!
//! ## OutgoingLink contract
//!
//! The returned `Vec<OutgoingLink>` carries the same load-bearing
//! shape (target_path, link_type, document-order sequence) Stage 1's
//! `markdown_refs::resolve_markdown_refs` + `markdown_links::
//! resolve_markdown_links` produced before deletion. The visitor uses
//! parsed inline text for `display_text`; Stage 1 used the raw source
//! between `[` and `]`. Since `display_text` has no production
//! consumer, this divergence is non-breaking — recorded as a known
//! shape-spec deviation in `link_wrapping_image_target_path`.

use super::document::Document;
use super::node::{Block, Inline};
use super::shortcode::Shortcode;
use super::url::{ResolvedUrl, Url, UrlKind};
use super::visit::visit_urls_mut;
use crate::content_graph::ContentGraph;
use crate::resolve::asset_class::{resolve_asset_ref, AssetIndex, AssetResolution};
use crate::resolve::fuzzy_path::{relative_asset_path, resolve_reference, ResolvedRef};
use crate::resolve::{LinkType, OutgoingLink};

// ---------------------------------------------------------------------------
// GraphAssetIndex: adapts ContentGraph to the AssetIndex trait so the pure
// engine (resolve_asset_ref) can run against a real content graph.
// ---------------------------------------------------------------------------

/// Adapts [`ContentGraph`] to the [`AssetIndex`] trait.
///
/// Wraps a borrowed `ContentGraph` so that `resolve_asset_ref` (the pure
/// shared engine in `moss_core::resolve::asset_class`) can be driven by the
/// build-time in-memory index — identical to how `FsAssetIndex` in src-tauri
/// drives it from the live filesystem. Exposed `pub` so integration tests and
/// editor↔build parity tests can construct both adapters over the same file set.
pub struct GraphAssetIndex<'a>(pub &'a ContentGraph);

impl<'a> AssetIndex for GraphAssetIndex<'a> {
    fn contains(&self, p: &str) -> bool {
        self.0.asset_contains(p)
    }
    fn contains_ci(&self, p: &str) -> Option<String> {
        self.0.asset_contains_ci(p)
    }
    fn find_by_suffix(&self, s: &str) -> Vec<String> {
        self.0.asset_find_by_suffix(s)
    }
}

/// Walk every URL in `doc` and classify it into [`Url::Resolved`].
///
/// Returns the list of [`OutgoingLink`] entries discovered during resolution
/// — byte-equivalent to today's Stage 1 `markdown_refs` + `markdown_links`
/// combined output (same shape, same sequence).
///
/// # Arguments
///
/// * `doc` — the typed document. Every [`Url::Unresolved`] is replaced in
///   place with a [`Url::Resolved`]. URLs that are already [`Url::Resolved`]
///   are left untouched (idempotent on a resolved document).
/// * `graph` — the content graph for bare-filename / cross-page lookups.
/// * `source_path` — the file containing the URLs, used by
///   [`resolve_reference`] for relative-path disambiguation and by
///   [`relative_asset_path`] for computing relative asset hrefs.
pub fn resolve_urls(
    doc: &mut Document,
    graph: &ContentGraph,
    source_path: &str,
) -> Vec<OutgoingLink> {
    // Phase 1: walk asset URLs (image refs) and accumulate their
    // OutgoingLink entries. This pass replaces the deleted Stage 1
    // `resolve::markdown_refs::resolve_markdown_refs` — it only touches
    // asset URLs and produces OutgoingLink for resolved bare-filename
    // images. The companion AST visitor lives at `resolve_image_urls`
    // below.
    let mut outgoing: Vec<OutgoingLink> = Vec::new();
    resolve_image_urls(doc, graph, source_path, &mut outgoing);

    // Phase 2: walk link URLs and accumulate their OutgoingLink entries.
    // Replaces the deleted Stage 1
    // `resolve::markdown_links::resolve_markdown_links` — only touches
    // link URLs and produces OutgoingLink for resolved cross-page links.
    // The AST visitor lives at `resolve_link_urls` below.
    //
    // Two-pass ordering matches Stage 1's resolve.rs sequence (refs first,
    // then links). The image-URL display_text comes from alt; the link-URL
    // display_text comes from the link text. Each phase appends to the
    // shared `outgoing` Vec in document order.
    resolve_link_urls(doc, graph, source_path, &mut outgoing);

    // Phase 3 (NOT done by default): the renderer's invariant requires
    // every URL be `Url::Resolved` at HTML emission time. For non-graph
    // URLs the visitor left as `Url::Unresolved` (resolver-prefixed,
    // anchors that fell through, edge cases), the caller is responsible
    // for one more classification pass before rendering. Callers that
    // need a complete classification can call
    // [`classify_remaining_urls`] explicitly. The src-tauri host pipeline
    // chains a second `visit_urls_mut` to apply its `classify_url_prod`
    // for page_map-aware decoding of the three sentinel prefixes.

    outgoing
}

// ---------------------------------------------------------------------------
// Phase 1: image (Inline::Image::src) URL resolution
// ---------------------------------------------------------------------------

/// Walk every `Inline::Image::src` URL and resolve bare-filename references.
///
/// Replaces the deleted Stage 1 `resolve::markdown_refs::resolve_markdown_refs`
/// (Phase 4 PR7a, 2026-05-28). Contract:
/// - Only touches Inline::Image::src URLs (not Link URLs).
/// - Bare filename + has-extension + no-path-separators → graph lookup.
/// - On `Found`: rewrite to relative asset path; push OutgoingLink.
/// - On `Unresolved`: leave URL as author-input (mark resolved-as-asset so
///   the renderer accepts it).
/// - Pipe-bearing URLs pass through unchanged (Phase 3 PR3 contract).
/// - External / data / mailto / anchor / explicit-relative pass through.
fn resolve_image_urls(
    doc: &mut Document,
    graph: &ContentGraph,
    source_path: &str,
    outgoing: &mut Vec<OutgoingLink>,
) {
    walk_inline_images_mut(doc, &mut |inline| {
        let (src, alt) = match inline {
            Inline::Image { src, alt, .. } => (src, alt.clone()),
            _ => return,
        };
        resolve_asset_url(src, &alt, graph, source_path, outgoing);
    });
    // Hero/Gallery shortcodes carry image URLs as typed fields on the
    // shortcode args (not as `Inline::Image`). Walk those structural
    // URLs through the same bare-filename resolver so wikilink targets
    // like `![[hero.jpg]]` resolve to `assets/hero.jpg` against the
    // graph, mirroring the `Inline::Image` path. Regression fix for
    // the chps-site home hero (2026-05-29): the previous skip left
    // `args.image` as `Url::Unresolved("hero.jpg")` → the renderer
    // emitted `<img src="hero.jpg">` instead of the depth-correct
    // `assets/hero.jpg`.
    for block in &mut doc.blocks {
        resolve_shortcode_image_urls(block, graph, source_path, outgoing);
    }
}

/// Resolve one image-kind `Url` field against the content graph.
///
/// Extracted from `resolve_image_urls`'s per-`Inline::Image` body so the
/// same logic can apply to structural image URLs that live on shortcode
/// args (Hero, Gallery). Behavior:
/// - Already `Url::Resolved` → no-op.
/// - Pipe-bearing → pass through verbatim (Phase 3 PR3 contract).
/// - External, anchor, data URLs → pass through (engine returns NotFound for
///   these, so they fall through to the verbatim passthrough arm).
/// - Separator-bearing or bare filename → routed through [`resolve_asset_ref`]
///   (the unified engine). On `Resolved`: rewrite to relative asset path and
///   push an OutgoingLink. On `Ambiguous`: pick the shortest match, warn, push.
///   On `NotFound`: leave as authored (matches Stage 1 behavior, no hard fail).
/// - `/`-absolute: the engine resolves from root; re-emit as `/<root_rel>` so
///   the absolute form is preserved in the rendered HTML (no pretty-URL nesting).
fn resolve_asset_url(
    url: &mut Url,
    alt: &str,
    graph: &ContentGraph,
    source_path: &str,
    outgoing: &mut Vec<OutgoingLink>,
) {
    let raw = match url {
        Url::Unresolved(s) => s.clone(),
        Url::Resolved(_) => return,
    };

    // Pipe-bearing URLs pass through unchanged (Phase 3 PR3): authors
    // use `![[file.jpg|attrs]]` for typed params; pipe in standard
    // markdown URL is literal and intentionally 404s.
    if raw.contains('|') {
        *url = Url::Resolved(ResolvedUrl::new(raw, UrlKind::Asset));
        return;
    }

    // External, anchor, and data URLs are not asset filesystem references.
    // Pass them through before invoking the engine (which only understands
    // filesystem paths) so we don't misinterpret `https://...` as a path.
    if raw.starts_with('#')
        || raw.starts_with("http://")
        || raw.starts_with("https://")
        || raw.starts_with("//")
        || raw.starts_with("data:")
        || raw.starts_with("mailto:")
    {
        *url = Url::Resolved(ResolvedUrl::new(raw, UrlKind::Asset));
        return;
    }

    // Route ALL remaining refs (bare filenames, separator paths, absolute
    // `/…` paths) through the unified asset engine. This replaces BOTH the
    // old `is_bare_filename` branch (which called `resolve_reference`) and
    // the old passthrough branch (which emitted the verbatim separator path,
    // causing 404s for cross-directory relative paths).
    //
    // NOTE: provenance (SeparatorFallback / CaseMismatch / Ambiguous) is
    // intentionally NOT logged here — moss-core is the pure, side-effect-free
    // kernel (no `log`/I/O). The advisory author-facing warning is surfaced by
    // the editor adapter (`editor::asset_resolver`) via the `@codemirror/lint`
    // hover tooltip. The build's job here is only to emit a correct URL; a
    // build-time console warning is a deferred follow-up (would require
    // surfacing provenance to the src-tauri build layer).
    let is_absolute = raw.starts_with('/');
    match resolve_asset_ref(&raw, source_path, &GraphAssetIndex(graph)) {
        AssetResolution::Resolved { root_rel, provenance: _ } => {
            if is_absolute {
                // R3: absolute paths stay absolute — re-emit with leading `/`
                // so the browser resolves from the site root, not from the
                // pretty-URL directory. Never run through relative_asset_path.
                *url = Url::Resolved(ResolvedUrl::new(format!("/{root_rel}"), UrlKind::Asset));
                return;
            }
            let rel = relative_asset_path(source_path, &root_rel);
            outgoing.push(OutgoingLink {
                target_path: root_rel,
                display_text: alt.to_string(),
                link_type: LinkType::Standard,
            });
            *url = Url::Resolved(ResolvedUrl::new(rel, UrlKind::Asset));
        }
        AssetResolution::Ambiguous { chosen, candidates: _ } => {
            let rel = relative_asset_path(source_path, &chosen);
            outgoing.push(OutgoingLink {
                target_path: chosen,
                display_text: alt.to_string(),
                link_type: LinkType::Standard,
            });
            *url = Url::Resolved(ResolvedUrl::new(rel, UrlKind::Asset));
        }
        AssetResolution::NotFound => {
            // Unchanged: pass through verbatim. Matches Stage 1 behavior —
            // the build never hard-fails on unresolved asset refs.
            *url = Url::Resolved(ResolvedUrl::new(raw, UrlKind::Asset));
        }
    }
}

/// Recursively descend into shortcode-bearing blocks and resolve any
/// structural image `Url` fields (HeroShortcode::image, GalleryItem::src).
/// Container shortcodes (Grid, Hero overlay) may nest other shortcodes —
/// recurse through their inner blocks. Skips Inline::Image-bearing
/// blocks because the `walk_inline_images_mut` pass above already
/// handled them.
fn resolve_shortcode_image_urls(
    block: &mut Block,
    graph: &ContentGraph,
    source_path: &str,
    outgoing: &mut Vec<OutgoingLink>,
) {
    match block {
        Block::Shortcode(sc) => match sc {
            Shortcode::Hero(args) => {
                if let Some(image_url) = args.image.as_mut() {
                    resolve_asset_url(image_url, "", graph, source_path, outgoing);
                }
                // Overlay may itself contain shortcodes (e.g. `::::buttons`
                // inside `:::hero`); recurse so any nested Hero/Gallery
                // structural image URLs resolve too.
                for nested in &mut args.overlay {
                    resolve_shortcode_image_urls(nested, graph, source_path, outgoing);
                }
            }
            Shortcode::Gallery(args) => {
                for item in &mut args.items {
                    let alt = item.alt.clone();
                    resolve_asset_url(&mut item.src, &alt, graph, source_path, outgoing);
                }
            }
            Shortcode::Grid(args) => {
                for cell in &mut args.cells {
                    for nested in cell {
                        resolve_shortcode_image_urls(nested, graph, source_path, outgoing);
                    }
                }
            }
            Shortcode::Subscribe(_) | Shortcode::Buttons(_) | Shortcode::Recent(_) | Shortcode::Apply(_) => {}
        },
        // Container blocks: recurse so nested shortcodes (Hero inside a
        // Callout, Grid inside a list, etc.) are reached.
        Block::Callout { children, .. } | Block::BlockQuote(children) => {
            for nested in children {
                resolve_shortcode_image_urls(nested, graph, source_path, outgoing);
            }
        }
        Block::List { items, .. } => {
            for item_blocks in items {
                for nested in item_blocks {
                    resolve_shortcode_image_urls(nested, graph, source_path, outgoing);
                }
            }
        }
        Block::LinkCard { children, .. } => {
            for nested in children {
                resolve_shortcode_image_urls(nested, graph, source_path, outgoing);
            }
        }
        // Leaf / inline-only blocks: nothing structural to resolve here.
        Block::Heading { .. }
        | Block::Paragraph(_)
        | Block::Table { .. }
        | Block::Figure { .. }
        | Block::CodeBlock { .. }
        | Block::ThematicBreak
        | Block::Other(_) => {}
    }
}

// ---------------------------------------------------------------------------
// Phase 2: link (Inline::Link::url + Block::LinkCard::url) URL resolution
// ---------------------------------------------------------------------------

/// Walk every link URL (Inline::Link::url, Block::LinkCard::url) and
/// resolve markdown / asset targets via the content graph.
///
/// Mirrors `markdown_links::resolve_markdown_links`:
/// - Only touches Link URLs (image URLs were handled in phase 1).
/// - Resolvable targets (not external / not anchor / not protocol /
///   not absolute-path / not already-prefixed) → graph lookup.
/// - On `Found`: classify into Internal (markdown) / Asset (binary) and
///   push OutgoingLink with target_path = resolved path.
/// - On `Unresolved`: leave URL author-input; Stage 1 emitted a diagnostic
///   here, but PR6 mirrors the byte-equivalence contract (no diagnostic in
///   the OutgoingLink Vec since Diagnostic is a separate stream).
/// - Anchor / mailto / tel / external pass through with the matching
///   UrlKind so the renderer attaches the right attributes.
fn resolve_link_urls(
    doc: &mut Document,
    graph: &ContentGraph,
    source_path: &str,
    outgoing: &mut Vec<OutgoingLink>,
) {
    walk_links_mut(doc, &mut |link_url, display_text, is_wikilink| {
        let raw = match link_url {
            Url::Unresolved(s) => s.clone(),
            Url::Resolved(_) => return,
        };

        // Author-facing short-circuits: classify and stop.
        if let Some(rest) = raw.strip_prefix("mailto:") {
            *link_url = Url::Resolved(ResolvedUrl::new(format!("mailto:{rest}"), UrlKind::Mailto));
            return;
        }
        if let Some(rest) = raw.strip_prefix("tel:") {
            *link_url = Url::Resolved(ResolvedUrl::new(format!("tel:{rest}"), UrlKind::Tel));
            return;
        }
        if raw.starts_with('#') {
            // Same-page anchor. For wikilinks (`[[#Heading]]`) slug the
            // fragment so it matches the rendered heading id; markdown
            // anchors (`[x](#frag)`) stay raw (literal author-supplied id).
            let href = if is_wikilink {
                slug_wikilink_suffix(&raw)
            } else {
                raw
            };
            *link_url = Url::Resolved(ResolvedUrl::new(href, UrlKind::Anchor));
            return;
        }
        if raw.starts_with("http://")
            || raw.starts_with("https://")
            || raw.starts_with("//")
            || raw.starts_with("data:")
        {
            *link_url = Url::Resolved(ResolvedUrl::new(raw, UrlKind::External));
            return;
        }

        // Stage 1 carry-over: URLs already prefixed with a resolver
        // sentinel (`moss-resolved:`, `moss-newtab:`, `wikilink:`) carry
        // Stage 1 / upstream state the visitor cannot decode in isolation
        // — the final pretty URL depends on the host's `page_map`, which
        // lives in src-tauri's pipeline context. Leave these as
        // `Url::Unresolved` so the host's per-URL classifier
        // (`classify_url_prod` in src-tauri's pipeline) can apply the
        // page_map-aware decoding. This preserves the byte-equivalence
        // contract (no OutgoingLink emitted for already-resolved targets
        // — Stage 1 already counted them) while letting the host close
        // the prefix-decoding loop.
        if raw.starts_with("moss-resolved:")
            || raw.starts_with("moss-newtab:")
            || raw.starts_with("wikilink:")
        {
            // Leave Unresolved; host pass classifies.
            return;
        }

        // Absolute filesystem path — treat as opaque. Mirrors
        // markdown_links: `if url.starts_with('/') { return false; }`.
        if raw.starts_with('/') {
            *link_url = Url::Resolved(ResolvedUrl::new(raw, UrlKind::Internal));
            return;
        }

        // Resolvable: split query/fragment, look up the path against the
        // content graph, push OutgoingLink, emit the `moss-resolved:`
        // sentinel for the host classifier. Mirrors
        // markdown_links::rewrite_line byte-for-byte: same sentinel shape
        // (`moss-resolved:<path>[<suffix>]`), same suffix concatenation.
        //
        // Phase 4 PR7a-stage1b (2026-05-28): moss-core resolves the
        // filesystem path; src-tauri's `classify_url_prod` decodes the
        // sentinel into the final pretty / external / asset URL using
        // `page_map`, `external_url_map`, and the wikilink-class signal.
        // The sentinel IS the moss-core ↔ src-tauri layering seam — the
        // visitor must NOT collapse it to a final `Url::Resolved` or
        // page_map decoding silently breaks.
        let (path_part, suffix) = split_path_suffix(&raw);
        match resolve_reference(path_part, graph, source_path) {
            ResolvedRef::Found(resolved) => {
                outgoing.push(OutgoingLink {
                    target_path: resolved.clone(),
                    display_text: display_text.to_string(),
                    link_type: LinkType::Standard,
                });
                // For wikilinks, slug the `#fragment` so the emitted href
                // matches the rendered heading id. The `?query` portion (if
                // any) is preserved by `slug_wikilink_suffix`. Markdown links
                // keep their suffix raw — a literal author-supplied URL.
                let sentinel = match suffix {
                    Some(s) => {
                        let s = if is_wikilink {
                            slug_wikilink_suffix(s)
                        } else {
                            s.to_string()
                        };
                        format!("moss-resolved:{}{}", resolved, s)
                    }
                    None => format!("moss-resolved:{}", resolved),
                };
                *link_url = Url::Unresolved(sentinel);
            }
            ResolvedRef::Unresolved => {
                // Mirrors Stage 1: leave the URL as-is in the rewritten
                // source — no `moss-resolved:` prefix, no diagnostic in
                // the OutgoingLink Vec. Mark Internal so the renderer's
                // `Url::Resolved` invariant holds.
                *link_url = Url::Resolved(ResolvedUrl::new(raw, UrlKind::Internal));
            }
        }
    });
}

/// Split a URL into (path, suffix) where `suffix` is `?query` and/or
/// `#fragment` in source order. Suffix is opaque — round-trip parity with
/// `crate::build::markdown::pipeline::classify_url_prod` (the src-tauri
/// decoder) is the contract; this function must not reorder, normalize,
/// or escape the suffix bytes.
///
/// The parallel src-tauri implementation lives at
/// `src-tauri/src/build/markdown/pipeline.rs::split_path_suffix` and must
/// share this exact shape.
fn split_path_suffix(url: &str) -> (&str, Option<&str>) {
    let q = url.find('?');
    let h = url.find('#');
    let cut = match (q, h) {
        (Some(a), Some(b)) => Some(a.min(b)),
        (Some(a), None) => Some(a),
        (None, Some(b)) => Some(b),
        (None, None) => None,
    };
    match cut {
        #[allow(clippy::string_slice)]
        Some(pos) => (&url[..pos], Some(&url[pos..])),
        None => (url, None),
    }
}

/// Slug the `#fragment` of a wikilink `suffix` so the emitted href matches
/// the rendered heading id (`obsidian_heading_anchor`). Only the fragment is
/// transformed: any leading `?query` is preserved verbatim. Block refs
/// (`#^id`) keep their id raw (minus the caret), mirroring
/// [`crate::resolve::wikilink_dispatch`]'s `build_anchor`. This must ONLY be
/// called for wikilinks (`is_wikilink: true`); regular markdown links keep
/// their fragment raw (it is a literal URL — `#L42`, hand-authored ids, etc.).
///
/// `suffix` is the value returned by [`split_path_suffix`] — it begins with
/// `?` or `#`. Shapes handled:
/// - `#frag` → `#<slug>`
/// - `?query` → `?query` (no fragment, untouched)
/// - `?query#frag` → `?query#<slug>` (query verbatim, fragment slugged)
fn slug_wikilink_suffix(suffix: &str) -> String {
    use crate::heading::anchor::obsidian_heading_anchor;

    // Find the fragment (`#…`); everything before it is a `?query` we leave
    // untouched. There is at most one `#` in a well-formed suffix.
    match suffix.find('#') {
        None => suffix.to_string(), // query-only (or empty) — nothing to slug
        Some(h) => {
            #[allow(clippy::string_slice)]
            let (head, frag_with_hash) = (&suffix[..h], &suffix[h + 1..]);
            let slugged = if let Some(block_id) = frag_with_hash.strip_prefix('^') {
                // Block ref: keep the id raw (caret stripped). Matches build_anchor.
                block_id.to_string()
            } else {
                obsidian_heading_anchor(frag_with_hash)
            };
            format!("{head}#{slugged}")
        }
    }
}

// ---------------------------------------------------------------------------
// Phase 3: ensure no Url::Unresolved survives
// ---------------------------------------------------------------------------

/// Classify any URL left as `Url::Unresolved` after phases 1 + 2 into a
/// best-effort `Url::Resolved`. The renderer's invariant requires no
/// `Url::Unresolved` reaches HTML emission; this is the safety net that
/// catches URLs the per-kind phases didn't visit (e.g., a future
/// `Inline::Link` variant added before its phase-2 arm is wired).
///
/// Callers that follow [`resolve_urls`] with their own per-URL classifier
/// (e.g., src-tauri's pipeline calling `classify_url_prod` for
/// resolver-prefix decoding) should NOT call this — let the secondary
/// classifier handle the remaining URLs. Callers that have no secondary
/// pass should call this to maintain the render invariant.
pub fn classify_remaining_urls(doc: &mut Document) {
    visit_urls_mut(doc, |url| {
        if let Url::Unresolved(raw) = url {
            // Conservative fallback: treat as External (opens in new tab,
            // no graph lookup). Unknown URLs are external by nature;
            // guessing Internal would be wrong and new-tab is safe.
            let kind = classify_unresolved_kind(raw);
            let raw_owned = std::mem::take(raw);
            *url = Url::Resolved(ResolvedUrl::new(raw_owned, kind));
        }
    });
}

/// Best-effort kind classification for an Unresolved URL that escaped the
/// per-kind phases. Mirrors the prefix-based detection in
/// `pipeline::classify_url_prod` for consistency.
fn classify_unresolved_kind(raw: &str) -> UrlKind {
    if raw.starts_with("mailto:") {
        UrlKind::Mailto
    } else if raw.starts_with("tel:") {
        UrlKind::Tel
    } else if raw.starts_with('#') {
        UrlKind::Anchor
    } else if raw.starts_with("http://")
        || raw.starts_with("https://")
        || raw.starts_with("//")
        || raw.starts_with("data:")
    {
        UrlKind::External
    } else {
        UrlKind::Internal
    }
}

// ---------------------------------------------------------------------------
// Per-kind walkers (image-only / link-only)
// ---------------------------------------------------------------------------

/// Walk every `Inline::Image` in the document and invoke `f` with a `&mut`
/// reference to the inline. Used by phase 1 — separates image src
/// classification from link URL classification.
fn walk_inline_images_mut<F>(doc: &mut Document, f: &mut F)
where
    F: FnMut(&mut Inline),
{
    for block in &mut doc.blocks {
        walk_images_in_block(block, f);
    }
}

fn walk_images_in_block<F>(block: &mut Block, f: &mut F)
where
    F: FnMut(&mut Inline),
{
    match block {
        Block::Heading { children, .. } | Block::Paragraph(children) => {
            for inline in children {
                walk_images_in_inline(inline, f);
            }
        }
        Block::Callout { children, .. } | Block::BlockQuote(children) => {
            for nested in children {
                walk_images_in_block(nested, f);
            }
        }
        Block::List { items, .. } => {
            for item_blocks in items {
                for nested in item_blocks {
                    walk_images_in_block(nested, f);
                }
            }
        }
        Block::Table { header, rows, .. } => {
            for cell in header {
                for inline in cell {
                    walk_images_in_inline(inline, f);
                }
            }
            for row in rows {
                for cell in row {
                    for inline in cell {
                        walk_images_in_inline(inline, f);
                    }
                }
            }
        }
        Block::Shortcode(sc) => {
            walk_images_in_shortcode(sc, f);
        }
        Block::Figure { image, caption, .. } => {
            walk_images_in_inline(image, f);
            if let Some(cap) = caption {
                for inline in cap {
                    walk_images_in_inline(inline, f);
                }
            }
        }
        Block::LinkCard { children, .. } => {
            for nested in children {
                walk_images_in_block(nested, f);
            }
        }
        Block::CodeBlock { .. } | Block::ThematicBreak | Block::Other(_) => {}
    }
}

fn walk_images_in_shortcode<F>(sc: &mut Shortcode, f: &mut F)
where
    F: FnMut(&mut Inline),
{
    match sc {
        Shortcode::Subscribe(_) | Shortcode::Buttons(_) | Shortcode::Recent(_) | Shortcode::Apply(_) => {}
        Shortcode::Gallery(args) => {
            // Gallery items carry their src as a structural `Url` on
            // GalleryItem, not as an `Inline::Image`. The Inline-image
            // walker has nothing to do here; the structural URL is
            // resolved by `resolve_shortcode_image_urls` instead.
            let _ = args;
        }
        Shortcode::Hero(args) => {
            // Hero's image is a structural `Url` field, not an
            // `Inline::Image` — resolved by `resolve_shortcode_image_urls`.
            // The overlay blocks may still contain `Inline::Image`s
            // (e.g. inside markdown paragraphs); descend so those reach
            // the inline walker.
            for block in &mut args.overlay {
                walk_images_in_block(block, f);
            }
        }
        Shortcode::Grid(args) => {
            for cell_blocks in &mut args.cells {
                for block in cell_blocks {
                    walk_images_in_block(block, f);
                }
            }
        }
    }
}

fn walk_images_in_inline<F>(inline: &mut Inline, f: &mut F)
where
    F: FnMut(&mut Inline),
{
    match inline {
        Inline::Image { .. } => {
            f(inline);
        }
        Inline::Link { children, .. } => {
            for nested in children {
                walk_images_in_inline(nested, f);
            }
        }
        Inline::Emphasis(children) | Inline::Strong(children) => {
            for nested in children {
                walk_images_in_inline(nested, f);
            }
        }
        Inline::Text(_) | Inline::Code(_) | Inline::LineBreak | Inline::Other(_) => {}
    }
}

/// Walk every link URL in the document (Inline::Link::url +
/// Block::LinkCard::url) and invoke `f` with `(&mut Url, display_text)`.
///
/// The `display_text` is the link text (concatenated from the Link's
/// children) — needed for the OutgoingLink::display_text contract.
fn walk_links_mut<F>(doc: &mut Document, f: &mut F)
where
    F: FnMut(&mut Url, &str, bool),
{
    for block in &mut doc.blocks {
        walk_links_in_block(block, f);
    }
}

fn walk_links_in_block<F>(block: &mut Block, f: &mut F)
where
    F: FnMut(&mut Url, &str, bool),
{
    match block {
        Block::Heading { children, .. } | Block::Paragraph(children) => {
            for inline in children {
                walk_links_in_inline(inline, f);
            }
        }
        Block::Callout { children, .. } | Block::BlockQuote(children) => {
            for nested in children {
                walk_links_in_block(nested, f);
            }
        }
        Block::List { items, .. } => {
            for item_blocks in items {
                for nested in item_blocks {
                    walk_links_in_block(nested, f);
                }
            }
        }
        Block::Table { header, rows, .. } => {
            for cell in header {
                for inline in cell {
                    walk_links_in_inline(inline, f);
                }
            }
            for row in rows {
                for cell in row {
                    for inline in cell {
                        walk_links_in_inline(inline, f);
                    }
                }
            }
        }
        Block::Shortcode(sc) => {
            walk_links_in_shortcode(sc, f);
        }
        Block::Figure { caption, .. } => {
            if let Some(cap) = caption {
                for inline in cap {
                    walk_links_in_inline(inline, f);
                }
            }
        }
        Block::LinkCard { url, children } => {
            // Compound-link card: the wrapping href is a link URL. Use
            // the inner text content as display_text by recursively
            // gathering it from the children (best-effort — empty string
            // if no text is found).
            // LinkCard wrapping href is never a wikilink (it's a compound
            // markdown link card), so pass is_wikilink=false.
            let display = gather_text_blocks(children);
            f(url, &display, false);
            for nested in children {
                walk_links_in_block(nested, f);
            }
        }
        Block::CodeBlock { .. } | Block::ThematicBreak | Block::Other(_) => {}
    }
}

fn walk_links_in_shortcode<F>(sc: &mut Shortcode, f: &mut F)
where
    F: FnMut(&mut Url, &str, bool),
{
    match sc {
        Shortcode::Subscribe(_) | Shortcode::Recent(_) | Shortcode::Apply(_) => {}
        Shortcode::Buttons(args) => {
            for item in &mut args.items {
                // ButtonItem display text comes from item.text per the
                // shortcode shape (crates/moss-core/src/ast/shortcode.rs).
                // Button URLs are authored markdown targets, not wikilinks.
                let text = item.text.clone();
                f(&mut item.url, &text, false);
            }
        }
        Shortcode::Gallery(_) => {
            // Gallery items use src URLs (image-kind), not link URLs.
            // No link-walk action.
        }
        Shortcode::Hero(args) => {
            for block in &mut args.overlay {
                walk_links_in_block(block, f);
            }
        }
        Shortcode::Grid(args) => {
            for cell_blocks in &mut args.cells {
                for block in cell_blocks {
                    walk_links_in_block(block, f);
                }
            }
        }
    }
}

fn walk_links_in_inline<F>(inline: &mut Inline, f: &mut F)
where
    F: FnMut(&mut Url, &str, bool),
{
    match inline {
        Inline::Link {
            url,
            children,
            is_wikilink,
            ..
        } => {
            // display_text = concatenated plain text of the children.
            // Matches markdown_links::rewrite_line, which uses the raw
            // text between `[` and `]` (no rendering, just the literal).
            let display = gather_text_inlines(children);
            f(url, &display, *is_wikilink);
            // Descend so nested Links (rare in CommonMark but possible
            // via parser quirks) get visited too.
            for nested in children {
                walk_links_in_inline(nested, f);
            }
        }
        Inline::Image { .. } => {
            // Image src is a Url but it's image-kind — handled by phase 1.
        }
        Inline::Emphasis(children) | Inline::Strong(children) => {
            for nested in children {
                walk_links_in_inline(nested, f);
            }
        }
        Inline::Text(_) | Inline::Code(_) | Inline::LineBreak | Inline::Other(_) => {}
    }
}

/// Concatenate the plain-text content of a list of inlines, mirroring
/// pulldown-cmark's behavior of treating link text as a verbatim string.
/// Used to populate `OutgoingLink::display_text`.
fn gather_text_inlines(inlines: &[Inline]) -> String {
    let mut s = String::new();
    for inline in inlines {
        gather_text_inline(inline, &mut s);
    }
    s
}

fn gather_text_inline(inline: &Inline, out: &mut String) {
    match inline {
        Inline::Text(t) => out.push_str(t),
        Inline::Code(c) => out.push_str(c),
        Inline::Emphasis(children) | Inline::Strong(children) => {
            for nested in children {
                gather_text_inline(nested, out);
            }
        }
        Inline::Link { children, .. } => {
            for nested in children {
                gather_text_inline(nested, out);
            }
        }
        Inline::Image { alt, .. } => out.push_str(alt),
        Inline::LineBreak => out.push('\n'),
        Inline::Other(_) => {}
    }
}

/// Concatenate the plain-text content of a list of blocks. Used by
/// Block::LinkCard arm to populate the OutgoingLink::display_text.
fn gather_text_blocks(blocks: &[Block]) -> String {
    let mut s = String::new();
    for block in blocks {
        gather_text_block(block, &mut s);
    }
    s
}

fn gather_text_block(block: &Block, out: &mut String) {
    match block {
        Block::Heading { children, .. } | Block::Paragraph(children) => {
            for inline in children {
                gather_text_inline(inline, out);
            }
        }
        Block::Figure { image, caption, .. } => {
            if let Inline::Image { alt, .. } = image {
                out.push_str(alt);
            }
            if let Some(cap) = caption {
                for inline in cap {
                    gather_text_inline(inline, out);
                }
            }
        }
        _ => {}
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::parser::parse;
    use crate::content_graph::ContentGraphBuilder;

    fn graph_with(paths: &[&str]) -> crate::content_graph::ContentGraph {
        let mut b = ContentGraphBuilder::new();
        for p in paths {
            b.add_file(p, p);
        }
        b.build()
    }

    // -----------------------------------------------------------------
    // Single-shot resolve_urls behavior
    // -----------------------------------------------------------------

    #[test]
    fn markdown_link_fragment_preserved_raw_not_slugged() {
        // Unit test of `split_path_suffix` PURITY: it splits path from
        // suffix but never slugs — the returned suffix is byte-identical to
        // the source. (Slugging, when it happens, is layered on top by
        // `slug_wikilink_suffix`, exercised separately.)
        //
        // Design split (corrected): a MARKDOWN link (`[t](page#Heading)`) is
        // a literal URL — its `#fragment` stays RAW by design, so authored
        // `#L42` / hand-authored ids / external anchors survive untouched.
        // A WIKILINK (`[[page#Heading]]`) is NOT a literal URL: its fragment
        // IS slugged to match the rendered heading id — `resolve_link_urls`
        // routes wikilinks through `slug_wikilink_suffix` (see the
        // end-to-end guard `markdown_link_fragment_stays_raw_not_slugged`
        // and the `wikilink_*_fragment_is_slugged` tests below). The earlier
        // claim that "authoring correctness comes from editor autocomplete"
        // was the flawed premise behind the link-path bug; wikilink slugging
        // now happens in resolve_urls itself.
        let (path, suffix) = split_path_suffix("page#My Heading");
        assert_eq!(path, "page");
        assert_eq!(suffix, Some("#My Heading")); // raw, spaces + case intact
    }

    #[test]
    fn resolves_standard_markdown_link_to_internal() {
        let mut doc = parse("[文字](文字.md)");
        let graph = graph_with(&["index.md", "文字/文字.md"]);
        let outgoing = resolve_urls(&mut doc, &graph, "index.md");

        assert_eq!(outgoing.len(), 1);
        assert_eq!(outgoing[0].target_path, "文字/文字.md");
        assert_eq!(outgoing[0].display_text, "文字");
        assert_eq!(outgoing[0].link_type, LinkType::Standard);

        // Phase 4 PR7a-stage1b (2026-05-28): the visitor emits a
        // `moss-resolved:` sentinel for internal links (Url::Unresolved)
        // so src-tauri's host classifier can decode it via page_map.
        // The renderer doesn't see this state — the host's
        // `classify_url_prod` pass replaces Unresolved before render.
        match &doc.blocks[0] {
            Block::Paragraph(children) => match &children[0] {
                Inline::Link { url, .. } => {
                    assert!(url.is_unresolved(), "expected sentinel, got: {url:?}");
                    match url {
                        Url::Unresolved(s) => assert_eq!(s, "moss-resolved:文字/文字.md"),
                        Url::Resolved(_) => unreachable!(),
                    }
                }
                _ => panic!("expected Link"),
            },
            _ => panic!("expected Paragraph"),
        }
    }

    #[test]
    fn passes_through_external_link() {
        let mut doc = parse("[ex](https://example.com)");
        let graph = graph_with(&["index.md"]);
        let outgoing = resolve_urls(&mut doc, &graph, "index.md");

        assert!(outgoing.is_empty());
        match &doc.blocks[0] {
            Block::Paragraph(children) => match &children[0] {
                Inline::Link { url, .. } => {
                    let Url::Resolved(r) = url else {
                        panic!("expected Resolved, got {url:?}")
                    };
                    assert_eq!(r.kind, UrlKind::External);
                    assert_eq!(r.href, "https://example.com");
                }
                _ => panic!("expected Link"),
            },
            _ => panic!("expected Paragraph"),
        }
    }

    #[test]
    fn classifies_anchor_link() {
        let mut doc = parse("[top](#top)");
        let graph = graph_with(&["index.md"]);
        let outgoing = resolve_urls(&mut doc, &graph, "index.md");
        assert!(outgoing.is_empty());
        match &doc.blocks[0] {
            Block::Paragraph(children) => match &children[0] {
                Inline::Link { url, .. } => {
                    let Url::Resolved(r) = url else {
                        panic!("expected Resolved, got {url:?}")
                    };
                    assert_eq!(r.kind, UrlKind::Anchor);
                    assert_eq!(r.href, "#top");
                }
                _ => panic!("expected Link"),
            },
            _ => panic!("expected Paragraph"),
        }
    }

    #[test]
    fn classifies_mailto() {
        let mut doc = parse("[Mail](mailto:test@example.com)");
        let graph = graph_with(&["index.md"]);
        let _ = resolve_urls(&mut doc, &graph, "index.md");
        match &doc.blocks[0] {
            Block::Paragraph(children) => match &children[0] {
                Inline::Link { url, .. } => {
                    let Url::Resolved(r) = url else {
                        panic!("expected Resolved, got {url:?}")
                    };
                    assert_eq!(r.kind, UrlKind::Mailto);
                    assert_eq!(r.href, "mailto:test@example.com");
                }
                _ => panic!("expected Link"),
            },
            _ => panic!("expected Paragraph"),
        }
    }

    #[test]
    fn resolves_bare_filename_image_against_graph() {
        let mut doc = parse("![My Photo](photo.jpg)");
        let mut b = ContentGraphBuilder::new();
        b.add_file("assets/photo.jpg", "photo");
        let graph = b.build();
        let outgoing = resolve_urls(&mut doc, &graph, "articles/post.md");

        assert_eq!(outgoing.len(), 1);
        assert_eq!(outgoing[0].target_path, "assets/photo.jpg");
        assert_eq!(outgoing[0].display_text, "My Photo");
        assert_eq!(outgoing[0].link_type, LinkType::Standard);

        // Image src rewritten to relative asset path.
        match &doc.blocks[0] {
            Block::Paragraph(children) => match &children[0] {
                Inline::Image { src, .. } => {
                    let Url::Resolved(r) = src else {
                        panic!("expected Resolved, got {src:?}")
                    };
                    assert_eq!(r.href, "../assets/photo.jpg");
                    assert_eq!(r.kind, UrlKind::Asset);
                }
                Inline::Link {
                    children: link_kids,
                    ..
                } => {
                    // pulldown-cmark may wrap an image-only paragraph in a
                    // figure or other structure depending on detection;
                    // accept either the direct image or one-level
                    // deeper.
                    if let Some(Inline::Image { src, .. }) = link_kids.first() {
                        let Url::Resolved(r) = src else {
                            panic!("expected Resolved, got {src:?}")
                        };
                        assert_eq!(r.href, "../assets/photo.jpg");
                    }
                }
                _ => panic!("expected Image, got {children:?}"),
            },
            Block::Figure { image, .. } => {
                // PR3's Block::Figure: image-only paragraph may parse as
                // Figure directly.
                if let Inline::Image { src, .. } = image {
                    let Url::Resolved(r) = src else {
                        panic!("expected Resolved, got {src:?}")
                    };
                    assert_eq!(r.href, "../assets/photo.jpg");
                }
            }
            _ => panic!("expected Paragraph or Figure, got {:?}", doc.blocks[0]),
        }
    }

    #[test]
    fn unresolved_bare_filename_passes_through() {
        let mut doc = parse("![](nonexistent.jpg)");
        let graph = graph_with(&["index.md"]);
        let outgoing = resolve_urls(&mut doc, &graph, "articles/post.md");

        assert!(outgoing.is_empty());
        // URL stays as raw "nonexistent.jpg" but becomes Resolved (Asset
        // kind) so the renderer's invariant holds.
        let mut found_image = false;
        for block in &doc.blocks {
            if let Block::Paragraph(children) = block {
                for inline in children {
                    if let Inline::Image { src, .. } = inline {
                        let Url::Resolved(r) = src else {
                            panic!("expected Resolved, got {src:?}")
                        };
                        assert_eq!(r.href, "nonexistent.jpg");
                        assert_eq!(r.kind, UrlKind::Asset);
                        found_image = true;
                    }
                }
            }
            if let Block::Figure { image, .. } = block {
                if let Inline::Image { src, .. } = image {
                    let Url::Resolved(r) = src else {
                        panic!("expected Resolved, got {src:?}")
                    };
                    assert_eq!(r.href, "nonexistent.jpg");
                    found_image = true;
                }
            }
        }
        assert!(found_image, "expected an Inline::Image in the parsed doc");
    }

    #[test]
    fn does_not_resolve_url_inside_code_block() {
        // visit_urls_mut never descends into Block::CodeBlock, so the
        // visitor never sees URLs in code fences. This matches Stage 1's
        // fence-aware behavior structurally.
        let mut doc = parse("```\n[link](inside.md)\n```\n");
        let graph = graph_with(&["index.md", "inside.md"]);
        let outgoing = resolve_urls(&mut doc, &graph, "index.md");
        assert!(
            outgoing.is_empty(),
            "code block content must not produce OutgoingLink"
        );
    }

    #[test]
    fn fragment_preserved_on_internal_link() {
        let mut doc = parse("[x](文字/文字.md#sec)");
        let graph = graph_with(&["index.md", "文字/文字.md"]);
        let outgoing = resolve_urls(&mut doc, &graph, "index.md");

        assert_eq!(outgoing.len(), 1);
        assert_eq!(outgoing[0].target_path, "文字/文字.md");

        // Sentinel emit: suffix concatenated verbatim after the resolved path.
        match &doc.blocks[0] {
            Block::Paragraph(children) => match &children[0] {
                Inline::Link { url, .. } => match url {
                    Url::Unresolved(s) => assert_eq!(s, "moss-resolved:文字/文字.md#sec"),
                    Url::Resolved(r) => panic!("expected sentinel, got Resolved({r:?})"),
                },
                _ => panic!("expected Link"),
            },
            _ => panic!("expected Paragraph"),
        }
    }

    #[test]
    fn query_string_preserved_on_internal_link() {
        let mut b = ContentGraphBuilder::new();
        b.add_file("index.md", "x");
        b.add_file("assets/scale-compare.html", "h");
        let graph = b.build();

        let mut doc = parse("[demo](scale-compare.html?a=major_pent&r=major_pent%3AD)");
        let outgoing = resolve_urls(&mut doc, &graph, "index.md");

        assert_eq!(outgoing.len(), 1);
        assert_eq!(outgoing[0].target_path, "assets/scale-compare.html");

        // Sentinel emit: suffix concatenated verbatim after the resolved path.
        match &doc.blocks[0] {
            Block::Paragraph(children) => match &children[0] {
                Inline::Link { url, .. } => match url {
                    Url::Unresolved(s) => assert_eq!(
                        s,
                        "moss-resolved:assets/scale-compare.html?a=major_pent&r=major_pent%3AD"
                    ),
                    Url::Resolved(r) => panic!("expected sentinel, got Resolved({r:?})"),
                },
                _ => panic!("expected Link"),
            },
            _ => panic!("expected Paragraph"),
        }
    }

    // -----------------------------------------------------------------
    // OutgoingLink + sentinel-shape coverage
    // -----------------------------------------------------------------
    //
    // Phase 4 PR7a-stage1b (2026-05-28): the Stage 1 pass
    // `markdown_links::resolve_markdown_links` was deleted in this PR
    // alongside the matching `byte_equivalence_*` baseline helpers. The
    // visitor now emits the same `moss-resolved:<path>` sentinel Stage 1
    // emitted, byte-for-byte — proven by the per-test sentinel
    // assertions below. The companion Stage 1 pass
    // `markdown_refs::resolve_markdown_refs` was already deleted in the
    // prior PR; its parity is covered by
    // `resolves_bare_filename_image_against_graph` above.

    #[test]
    fn standard_markdown_link_emits_sentinel() {
        let source = "index.md";
        let content = "[文字](文字.md)";
        let graph = graph_with(&["index.md", "文字/文字.md"]);

        let mut doc = parse(content);
        let visitor = resolve_urls(&mut doc, &graph, source);

        assert_eq!(visitor.len(), 1);
        assert_eq!(visitor[0].target_path, "文字/文字.md");
        assert_eq!(visitor[0].display_text, "文字");
        assert_eq!(visitor[0].link_type, LinkType::Standard);
        // The sentinel shape is what `classify_url_prod` in src-tauri
        // expects to decode via `page_map` / `external_url_map`.
        match &doc.blocks[0] {
            Block::Paragraph(children) => match &children[0] {
                Inline::Link {
                    url: Url::Unresolved(s),
                    ..
                } => {
                    assert_eq!(s, "moss-resolved:文字/文字.md");
                }
                _ => panic!("expected Url::Unresolved sentinel, got {:?}", children[0]),
            },
            _ => panic!("expected Paragraph"),
        }
    }

    #[test]
    fn multiple_links_one_line_emit_sentinels() {
        let source = "index.md";
        let content = "[a](foo.md) and [b](bar.md)";
        let graph = graph_with(&["index.md", "foo.md", "bar.md"]);

        let mut doc = parse(content);
        let visitor = resolve_urls(&mut doc, &graph, source);

        assert_eq!(visitor.len(), 2);
        assert_eq!(visitor[0].target_path, "foo.md");
        assert_eq!(visitor[1].target_path, "bar.md");
    }

    #[test]
    fn external_links_no_outgoing() {
        let source = "index.md";
        let content = "[ext](https://example.com) [anchor](#top) [mail](mailto:a@b)";
        let graph = graph_with(&["index.md"]);

        let mut doc = parse(content);
        let visitor = resolve_urls(&mut doc, &graph, source);

        assert!(visitor.is_empty());
    }

    #[test]
    fn unresolved_link_no_outgoing() {
        let source = "index.md";
        let content = "[missing](missing.md)";
        let graph = graph_with(&["index.md"]);

        let mut doc = parse(content);
        let visitor = resolve_urls(&mut doc, &graph, source);

        assert!(visitor.is_empty());
        // The unresolved URL stays as-is (no sentinel) but is marked
        // Url::Resolved so the renderer's invariant holds.
        match &doc.blocks[0] {
            Block::Paragraph(children) => match &children[0] {
                Inline::Link { url, .. } => {
                    let Url::Resolved(r) = url else {
                        panic!("expected Resolved, got {url:?}")
                    };
                    assert_eq!(r.href, "missing.md");
                    assert_eq!(r.kind, UrlKind::Internal);
                }
                _ => panic!("expected Link"),
            },
            _ => panic!("expected Paragraph"),
        }
    }

    #[test]
    fn code_block_urls_not_visited() {
        let source = "index.md";
        let content =
            "Before\n\n```\n[link](inside.md)\n![](photo.jpg)\n```\n\nAfter [link](inside.md).";
        let mut b = ContentGraphBuilder::new();
        b.add_file("index.md", "x");
        b.add_file("inside.md", "i");
        b.add_file("assets/photo.jpg", "p");
        let graph = b.build();

        let mut doc = parse(content);
        let visitor = resolve_urls(&mut doc, &graph, source);

        // Only the trailing `[link](inside.md)` (outside the fence) emits
        // an OutgoingLink. URLs inside `Block::CodeBlock` are not visited.
        assert_eq!(visitor.len(), 1);
        assert_eq!(visitor[0].target_path, "inside.md");
    }

    #[test]
    fn query_and_fragment_sentinel_shape() {
        let source = "index.md";
        let content = "[d](app.html?x=1#sec)";
        let mut b = ContentGraphBuilder::new();
        b.add_file("index.md", "x");
        b.add_file("assets/app.html", "h");
        let graph = b.build();

        let mut doc = parse(content);
        let visitor = resolve_urls(&mut doc, &graph, source);

        assert_eq!(visitor.len(), 1);
        assert_eq!(visitor[0].target_path, "assets/app.html");
        match &doc.blocks[0] {
            Block::Paragraph(children) => match &children[0] {
                Inline::Link {
                    url: Url::Unresolved(s),
                    ..
                } => {
                    assert_eq!(s, "moss-resolved:assets/app.html?x=1#sec");
                }
                _ => panic!("expected sentinel, got {:?}", children[0]),
            },
            _ => panic!("expected Paragraph"),
        }
    }

    #[test]
    fn link_wrapping_image_target_path() {
        // Shape produced by `[![[image.png]]](target.html?q)` after the
        // wikilinks pass rewrites the embed to `![alt](path)`.
        // Pre-PR7a-stage1b this test compared to a Stage 1 baseline that
        // used the raw markdown source between `[` and `]` for
        // display_text; the visitor uses parsed plain text (alt text).
        // That divergence was non-breaking (display_text has no
        // production consumer). With Stage 1 deleted we assert on the
        // visitor's behavior directly: load-bearing fields (target_path,
        // link_type) plus the documented display_text.
        //
        // Task 6 (asset-engine routing, 2026-06-03): the engine now also
        // resolves separator-path image references through the graph and
        // emits an OutgoingLink for the discovered dependency edge. So
        // this test now expects TWO OutgoingLink entries:
        //   [0] — image: assets/scale-compare.png (phase 1, image resolver)
        //   [1] — link: assets/scale-compare.html (phase 2, link resolver)
        // Previously [0] was absent because separator-path images were
        // passed through verbatim (the 404 bug). The href for the image
        // is unchanged ("assets/scale-compare.png" from index.md root).
        let source = "index.md";
        let content = "[![scale-compare](assets/scale-compare.png)](scale-compare.html?a=major_pent&r=major_pent%3AD)";
        let mut b = ContentGraphBuilder::new();
        b.add_file("index.md", "x");
        b.add_file("assets/scale-compare.html", "h");
        b.add_file("assets/scale-compare.png", "p");
        let graph = b.build();

        let mut doc = parse(content);
        let visitor = resolve_urls(&mut doc, &graph, source);

        // Phase 1 emits the image dependency edge; phase 2 emits the link.
        assert_eq!(visitor.len(), 2, "expected image + link OutgoingLinks, got: {visitor:?}");
        // Find the link entry by target (order: phase 1 image first, then phase 2 link).
        let link_entry = visitor
            .iter()
            .find(|o| o.target_path == "assets/scale-compare.html")
            .expect("OutgoingLink for scale-compare.html not found");
        assert_eq!(link_entry.link_type, LinkType::Standard);
        assert_eq!(link_entry.display_text, "scale-compare");
        // Image dependency edge also present.
        assert!(
            visitor.iter().any(|o| o.target_path == "assets/scale-compare.png"),
            "OutgoingLink for scale-compare.png not found"
        );
    }

    // -----------------------------------------------------------------
    // Edge cases
    // -----------------------------------------------------------------

    #[test]
    fn pipe_bearing_image_url_unchanged() {
        let mut doc = parse("![alt](photo.jpg|contain)");
        let mut b = ContentGraphBuilder::new();
        b.add_file("assets/photo.jpg", "p");
        let graph = b.build();
        let outgoing = resolve_urls(&mut doc, &graph, "articles/post.md");

        // Phase 3 PR3 contract: pipe-bearing URLs pass through verbatim,
        // no OutgoingLink emitted.
        assert!(outgoing.is_empty());
    }

    #[test]
    fn idempotent_on_already_resolved_url() {
        // If the document already carries Resolved URLs (e.g. a previous
        // pass ran), the visitor should not double-process. Single
        // invocation should produce the SAME state.
        let mut doc = parse("[文字](文字.md)");
        let graph = graph_with(&["index.md", "文字/文字.md"]);
        let outgoing1 = resolve_urls(&mut doc, &graph, "index.md");

        let outgoing2 = resolve_urls(&mut doc, &graph, "index.md");
        // After the first pass everything is Resolved; the second pass
        // produces no new OutgoingLink entries.
        assert!(
            outgoing2.is_empty(),
            "idempotency violated: {:?}",
            outgoing2
        );
        assert_eq!(outgoing1.len(), 1);
    }

    #[test]
    fn absolute_path_passes_through() {
        let mut doc = parse("[abs](/about.html)");
        let graph = graph_with(&["index.md", "about.html"]);
        let outgoing = resolve_urls(&mut doc, &graph, "index.md");
        // Absolute paths bypass the graph (mirrors markdown_links).
        assert!(outgoing.is_empty());
        match &doc.blocks[0] {
            Block::Paragraph(children) => match &children[0] {
                Inline::Link { url, .. } => {
                    let Url::Resolved(r) = url else {
                        panic!("expected Resolved, got {url:?}")
                    };
                    assert_eq!(r.href, "/about.html");
                }
                _ => panic!("expected Link"),
            },
            _ => panic!("expected Paragraph"),
        }
    }

    // -----------------------------------------------------------------
    // Hero / Gallery shortcode image resolution
    // -----------------------------------------------------------------
    //
    // Regression coverage for the chps-site home hero regression
    // (2026-05-29): `:::hero` with a body-image fallback `![[hero.jpg]]`
    // (or `image=hero.jpg` attribute) stores the wikilink target as a
    // `Url::Unresolved("hero.jpg")` on `HeroShortcode::image`. Before the
    // fix, `walk_images_in_shortcode`'s Hero arm explicitly skipped that
    // field, deferring to `classify_remaining_urls` — but the fallback
    // classifier only assigns a `UrlKind`, never consulting the
    // ContentGraph. Result: the renderer emitted `<img src="hero.jpg">`
    // instead of the depth-correct `assets/hero.jpg`. The fix routes
    // `args.image` (Hero) and `item.src` (Gallery) through the same
    // bare-filename graph lookup that `Inline::Image` already uses.

    fn extract_hero_image_href(doc: &Document) -> Option<String> {
        for block in &doc.blocks {
            if let Block::Shortcode(Shortcode::Hero(args)) = block {
                if let Some(Url::Resolved(r)) = &args.image {
                    return Some(r.href.clone());
                }
                return None;
            }
        }
        None
    }

    #[test]
    fn hero_body_wikilink_resolves_against_graph_at_depth_0() {
        // chps-site home page shape: `:::hero` with `![[hero.jpg]]`
        // wikilink as the body-image fallback. The asset lives at
        // `assets/hero.jpg` on disk. From depth-0 (home), the emitted
        // href must be `assets/hero.jpg`, not the bare wikilink target.
        let mut doc = parse(":::hero\n![[hero.jpg]]\n# Welcome\n:::\n");
        let mut b = ContentGraphBuilder::new();
        b.add_file("index.md", "home");
        b.add_file("assets/hero.jpg", "hero");
        let graph = b.build();
        let outgoing = resolve_urls(&mut doc, &graph, "index.md");

        let href = extract_hero_image_href(&doc).expect("hero image must be Resolved");
        assert_eq!(
            href, "assets/hero.jpg",
            "hero body-wikilink must resolve to depth-0 asset path, got {href:?}"
        );
        // OutgoingLink registers the discovered dependency edge.
        assert!(
            outgoing.iter().any(|o| o.target_path == "assets/hero.jpg"),
            "expected OutgoingLink to assets/hero.jpg, got {outgoing:?}"
        );
    }

    #[test]
    fn hero_body_wikilink_resolves_with_relative_prefix_at_depth_1() {
        // Source one directory deep (e.g. `articles/post.md`) must emit
        // a `../assets/hero.jpg` href so it resolves from the deployed
        // pretty-URL `/articles/post/index.html`. Mirrors the
        // `resolves_bare_filename_image_against_graph` test's relative-
        // path assertion for `Inline::Image`.
        let mut doc = parse(":::hero\n![[hero.jpg]]\n:::\n");
        let mut b = ContentGraphBuilder::new();
        b.add_file("articles/post.md", "post");
        b.add_file("assets/hero.jpg", "hero");
        let graph = b.build();
        let _ = resolve_urls(&mut doc, &graph, "articles/post.md");

        let href = extract_hero_image_href(&doc).expect("hero image must be Resolved");
        assert_eq!(
            href, "../assets/hero.jpg",
            "hero body-wikilink at source-depth 1 must resolve with `../` prefix, got {href:?}"
        );
    }

    #[test]
    fn hero_unresolved_wikilink_passes_through() {
        // If the wikilink target isn't in the graph, leave the URL as
        // the author wrote it (Resolved Asset kind, so the renderer
        // invariant holds). Mirrors `unresolved_bare_filename_passes_through`.
        let mut doc = parse(":::hero\n![[missing.jpg]]\n:::\n");
        let graph = graph_with(&["index.md"]);
        let _ = resolve_urls(&mut doc, &graph, "index.md");

        let href = extract_hero_image_href(&doc).expect("hero image must be Resolved");
        assert_eq!(href, "missing.jpg");
    }

    // -----------------------------------------------------------------
    // Wikilink #fragment slugging (keystone bug fix)
    //
    // Authored `[[Page#Heading]]` wikilinks must resolve to a SLUGGED
    // fragment so the emitted href matches the rendered heading id
    // (`<h2 id="getting-started">`). Regular markdown links `[x](page#frag)`
    // stay RAW (a markdown link is a literal URL). The discriminator is
    // `Inline::Link::is_wikilink`, which `parse()` sets for `[[…]]` syntax
    // (ENABLE_WIKILINKS). Block refs (`#^id`) keep the id raw minus the
    // caret, mirroring `wikilink_dispatch::build_anchor`.
    // -----------------------------------------------------------------

    /// Pull the resolved Url string out of the first Link inline in the
    /// first paragraph. Works for both `Url::Unresolved` (sentinel) and
    /// `Url::Resolved` (anchor / external) variants.
    fn first_link_href(doc: &Document) -> String {
        match &doc.blocks[0] {
            Block::Paragraph(children) => {
                let link = children
                    .iter()
                    .find(|i| matches!(i, Inline::Link { .. }))
                    .expect("expected an Inline::Link");
                match link {
                    Inline::Link { url, .. } => match url {
                        Url::Unresolved(s) => s.clone(),
                        Url::Resolved(r) => r.href.clone(),
                    },
                    _ => unreachable!(),
                }
            }
            other => panic!("expected Paragraph, got {other:?}"),
        }
    }

    #[test]
    fn wikilink_cross_page_fragment_is_slugged() {
        // `[[other#Getting Started]]` → sentinel `moss-resolved:other.md#getting-started`.
        let mut doc = parse("[[other#Getting Started]]");
        let graph = graph_with(&["index.md", "other.md"]);
        let _ = resolve_urls(&mut doc, &graph, "index.md");
        assert_eq!(first_link_href(&doc), "moss-resolved:other.md#getting-started");
    }

    #[test]
    fn wikilink_same_page_fragment_is_slugged() {
        // Same-page `[[#Local Section]]` → bare anchor `#local-section`,
        // no `moss-resolved:` prefix (the path part is empty).
        let mut doc = parse("[[#Local Section]]");
        let graph = graph_with(&["index.md"]);
        let _ = resolve_urls(&mut doc, &graph, "index.md");
        assert_eq!(first_link_href(&doc), "#local-section");
    }

    #[test]
    fn markdown_link_fragment_stays_raw_not_slugged() {
        // Regression guard for the design decision: a NON-wikilink markdown
        // link keeps its fragment RAW (case intact, no slugging). This MUST
        // still hold after the wikilink fix. (CommonMark forbids spaces in a
        // bare link destination, so we use a case-bearing fragment to make
        // the raw-vs-slug distinction observable: raw `#GettingStarted`
        // would slug to `#gettingstarted`.)
        let mut doc = parse("[x](other#GettingStarted)");
        let graph = graph_with(&["index.md", "other.md"]);
        let _ = resolve_urls(&mut doc, &graph, "index.md");
        assert_eq!(first_link_href(&doc), "moss-resolved:other.md#GettingStarted");
    }

    #[test]
    fn wikilink_block_ref_keeps_id_raw() {
        // Block refs (`#^id`) strip the caret but keep the id RAW (no slug),
        // mirroring `wikilink_dispatch::build_anchor`. Use space + uppercase
        // so slugging would be observably different.
        let mut doc = parse("[[other#^Block Id]]");
        let graph = graph_with(&["index.md", "other.md"]);
        let _ = resolve_urls(&mut doc, &graph, "index.md");
        let href = first_link_href(&doc);
        assert!(href.contains("#Block Id"), "expected raw block-ref, got: {href}");
        assert!(!href.contains("#block-id"), "block-ref was slugged: {href}");
    }

    #[test]
    fn wikilink_cjk_fragment_preserved() {
        // CJK characters are preserved by obsidian_heading_anchor.
        let mut doc = parse("[[other#中文标题]]");
        let graph = graph_with(&["index.md", "other.md"]);
        let _ = resolve_urls(&mut doc, &graph, "index.md");
        assert_eq!(first_link_href(&doc), "moss-resolved:other.md#中文标题");
    }

    #[test]
    fn slug_wikilink_suffix_preserves_query() {
        // A `?query#frag` suffix: only the `#frag` is slugged; the query
        // passes through untouched.
        assert_eq!(slug_wikilink_suffix("?a=1#My Heading"), "?a=1#my-heading");
        // Query-only suffix is untouched.
        assert_eq!(slug_wikilink_suffix("?a=1"), "?a=1");
        // Fragment-only suffix is slugged.
        assert_eq!(slug_wikilink_suffix("#My Heading"), "#my-heading");
        // Block ref keeps id raw (caret stripped).
        assert_eq!(slug_wikilink_suffix("#^Block Id"), "#Block Id");
    }

    // -----------------------------------------------------------------
    // Task 6: engine routing tests for resolve_asset_url
    //
    // These tests exercise the unified asset engine (resolve_asset_ref)
    // through the resolve_asset_url path. They cover:
    //   - Separator-bearing paths that the old code passed through verbatim
    //     (the 404 bug), now rebased via SeparatorFallback.
    //   - Absolute `/`-prefixed paths that must stay absolute (R3).
    //   - Case-mismatched paths that the engine canonicalises.
    //   - Bare filenames that must behave identically to the old
    //     resolve_reference path (the `image_bare_unchanged_from_today` gate).
    // -----------------------------------------------------------------

    /// Test seam: build a `Url::Unresolved(raw)`, run it through `resolve_asset_url`,
    /// and return the resolved `href` string. The `graph` is built with
    /// `ContentGraph::from_paths`.
    fn resolve_image_src(raw: &str, source_path: &str, graph: &crate::content_graph::ContentGraph) -> String {
        let mut url = Url::Unresolved(raw.to_string());
        let mut outgoing = Vec::new();
        resolve_asset_url(&mut url, "", graph, source_path, &mut outgoing);
        match url {
            Url::Resolved(r) => r.href,
            Url::Unresolved(s) => s,
        }
    }

    #[test]
    fn image_separator_fallback_rebases_to_root() {
        // The 404 bug: `./assets/AGU2025.jpg` authored in `News/post.md` is
        // not adjacent (no `News/assets/` dir). Old code passed it verbatim →
        // 404. New engine: SeparatorFallback → root `assets/AGU2025.jpg` →
        // `relative_asset_path("News/post.md", "assets/AGU2025.jpg")` = "../assets/AGU2025.jpg".
        // (The downstream +1 ../ for pretty-URL nesting is added by
        // adjust_relative_paths_for_pretty_urls in src-tauri, not here.)
        let graph = graph_with(&["assets/AGU2025.jpg", "News/post.md"]);
        assert_eq!(
            resolve_image_src("./assets/AGU2025.jpg", "News/post.md", &graph),
            "../assets/AGU2025.jpg"
        );
    }

    #[test]
    fn image_absolute_stays_absolute() {
        // R3: an absolute `/`-prefixed asset reference must be emitted with
        // its leading `/` intact, never run through relative_asset_path.
        let graph = graph_with(&["assets/x.jpg"]);
        assert_eq!(
            resolve_image_src("/assets/x.jpg", "News/post.md", &graph),
            "/assets/x.jpg"
        );
    }

    #[test]
    fn image_case_mismatch_emits_canonical() {
        // `./assets/Hoon.jpg` authored in `Team.md` (root); disk is `Hoon.JPG`.
        // Engine: CaseMismatch → root_rel = "assets/Hoon.JPG".
        // relative_asset_path("Team.md", "assets/Hoon.JPG"):
        //   from_dir = "" (Team.md is at root) → ups = 0 → "assets/Hoon.JPG"
        //   (no leading `../` because the source is at the project root).
        let graph = graph_with(&["assets/Hoon.JPG"]);
        assert_eq!(
            resolve_image_src("./assets/Hoon.jpg", "Team.md", &graph),
            "assets/Hoon.JPG"
        );
    }

    #[test]
    fn image_bare_unchanged_from_today() {
        // Gate: bare-filename resolution must produce the SAME result via the
        // engine as the old resolve_reference path did. `photo.jpg` from
        // `post.md` (root) → BareFuzzy → root_rel = "assets/photo.jpg" →
        // relative_asset_path("post.md", "assets/photo.jpg") = "assets/photo.jpg".
        let graph = graph_with(&["assets/photo.jpg", "post.md"]);
        assert_eq!(
            resolve_image_src("photo.jpg", "post.md", &graph),
            "assets/photo.jpg"
        );
    }
}