rto-render 5.10.2

Renderers for Roteiro: docs site, Obsidian vault, and optional MCP server. Implementation detail of the roteiro CLI; no API stability guarantee.
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
//! Render the graph as an **Open Knowledge Format** bundle (issue #663).
//!
//! OKF v0.2 is Google Cloud's vendor-neutral specification for the "LLM wiki"
//! pattern: a directory of markdown concept documents carrying YAML frontmatter,
//! reserved `index.md` and `log.md` files, and plain markdown links between
//! concepts. The whole specification fits on a page, and its only hard
//! requirement is that every concept document carries a non-empty `type`.
//!
//! <https://github.com/GoogleCloudPlatform/open-knowledge-format/blob/main/SPEC.md>
//!
//! # Why this replaced the Obsidian vault
//!
//! The vault was **one-way**: Roteiro wrote it, nothing read it back, and no
//! tool but Obsidian could consume it. An open format with named consumers earns
//! the same machinery better. Two concrete gains beyond that:
//!
//! - **The hierarchy retires a class of bug.** The vault flattened every note
//!   into one directory and appended a hash to each filename, because
//!   case-insensitive filesystems fold names that differ only in case — a defect
//!   that once cost this repository 104 notes of 8,144. OKF nests concepts in
//!   directories, so the collision the hash existed to survive does not arise.
//! - **Provenance stops being decoration.** Obsidian had nowhere to put it but a
//!   tag. OKF has a trust model, and it is the one Roteiro already computes.
//!
//! # The provenance mapping, which is the point
//!
//! Most producers will emit `type` and little else. Roteiro's authored/derived/
//! inferred distinction lands exactly on OKF's trust tiers (§5.3), which
//! consumers derive from `verified`:
//!
//! | [`Provenance`] | frontmatter | tier |
//! | --- | --- | --- |
//! | `Authored` — ADR and blueprint prose | `verified: [{ by: human:<id> }]` | human-reviewed |
//! | `Derived` — deterministic tree-sitter extraction | `verified: [{ by: roteiro/<version> }]` | machine-confirmed |
//! | `Inferred` — heuristic, carries a confidence | `generated:` alone | unverified |
//!
//! `Derived` is **machine-confirmed rather than unverified** on purpose: it is
//! reproduced deterministically from the AST at a known commit, so a consumer can
//! re-derive it. `Inferred` is a similarity judgement with a confidence score and
//! gets no `verified` key, because claiming otherwise would launder a guess into
//! a confirmation — the distinction the whole graph exists to keep.
//!
//! §7 makes the `human:` prefix load-bearing: it is the only thing that
//! separates human-reviewed from machine-confirmed, and producers **MUST** use it
//! for hand-authored content. Roteiro knows which nodes those are, and resolves
//! *which person* per document — the author of the commit that last changed that
//! document's path. Naming one author for the whole repository would record a
//! review that person never did, on every ADR at once.
//!
//! # One deliberate divergence
//!
//! §11 says consumers **MUST NOT** reject a bundle for broken cross-links.
//! Roteiro treats a broken authored link as drift and fails a gate over it. Both
//! are right — the specification asks consumers to be liberal; Roteiro is a
//! producer that guarantees more than it must. A Roteiro bundle should not
//! contain a broken link, and `roteiro check` is the reason.

// Conformance and hygiene checking. Its own module rather than more of
// `inspect`: `inspect` answers questions a bundle's *contents* raise, and this
// answers whether the bundle is well-formed — a different question, and the one
// with rules behind it.
pub mod conform;
pub mod inspect;
pub mod read;
// The viewer's model (ADR-0022). Rendering only — the HTTP layer is roteiro's
// `okf_viewer`, behind the `okf-viewer` feature. Kept out of that gate so the
// part with rules in it is compiled and tested by the default build.
pub mod view;

use std::collections::BTreeMap;
use std::fmt::Write as _;

use rto_graph::{Explanation, NodeSummary, Provenance};

/// The specification version this renderer targets, written into the bundle
/// root's `index.md` as `okf_version` (§10 — the one place frontmatter is
/// permitted in an index).
pub const OKF_VERSION: &str = "0.2";

/// The reserved filename for a directory listing (§8).
pub const INDEX_FILE: &str = "index.md";

/// The reserved filename for a change log (§9).
pub const LOG_FILE: &str = "log.md";

/// The namespace a cross-repo placeholder node's key carries (ADR-0009).
///
/// Spelled once here and checked against the graph's own writer by
/// `the_placeholder_prefix_is_the_graphs`, so the two cannot drift into
/// disagreeing about what a placeholder key looks like.
const EXTREF_PREFIX: &str = "extref:";

/// One rendered file in the bundle: a bundle-relative path and its content.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BundleFile {
    /// Path relative to the bundle root, always `/`-separated.
    pub path: String,
    /// The file's full text, including any frontmatter block.
    pub content: String,
}

/// Who produced or confirmed a concept, in the actor form §7 requires.
///
/// The three shapes are not interchangeable: a consumer classifying trust keys
/// off the `human:` prefix, so using the wrong one silently moves a concept
/// between tiers.
///
/// # Deliberately exhaustive
///
/// This is deliberately not `#[non_exhaustive]`, though these crates are
/// published and a fourth variant would therefore be a breaking change. **The
/// set is closed by the specification, not by us**: §7 defines exactly these
/// three forms, and a
/// fourth appearing means OKF changed. When that happens a caller matching on
/// this enum *should* stop compiling, because a new actor form is a decision
/// about trust that must be looked at rather than absorbed by a wildcard arm.
///
/// `#[non_exhaustive]` would buy version-compatibility at the price of making
/// that change silent — which is the opposite of what the trust model needs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Actor {
    /// A person: `human:<id>`. The only form that yields the human-reviewed tier.
    Human(String),
    /// A tool, as `<producer>/<version>`.
    Tool(String, String),
    /// An automated process: `process:<id>`.
    Process(String),
}

impl Actor {
    /// The wire form, exactly as §7 specifies it.
    #[must_use]
    pub fn as_token(&self) -> String {
        match self {
            Self::Human(id) => format!("human:{id}"),
            Self::Tool(producer, version) => format!("{producer}/{version}"),
            Self::Process(id) => format!("process:{id}"),
        }
    }
}

/// How a concept came to exist, rendered into `generated` / `verified`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Origin {
    /// The actor that produced the concept.
    pub by: Actor,
    /// When, as an ISO 8601 instant.
    pub at: String,
    /// Whether this origin also *confirms* the concept.
    ///
    /// `Authored` and `Derived` do; `Inferred` does not. See the module doc — a
    /// heuristic that claimed confirmation would launder a guess.
    pub confirms: bool,
}

/// A concept document's frontmatter.
///
/// Only [`Self::type_`] is required by the specification; every other field is
/// omitted entirely when absent rather than written empty, because §11 tells
/// consumers not to reject a document for a missing optional field and an empty
/// string is a different claim from silence.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Frontmatter {
    /// `type` — the one required key. Named with a trailing underscore because
    /// `type` is a Rust keyword; it is written as `type`.
    pub type_: String,
    /// `title` — human-readable display name.
    pub title: Option<String>,
    /// `description` — a single-sentence summary.
    pub description: Option<String>,
    /// `resource` — canonical URI for the underlying asset.
    pub resource: Option<String>,
    /// `tags` — categorisation strings.
    pub tags: Vec<String>,
    /// `status` — `draft` | `stable` | `deprecated`.
    pub status: Option<String>,
    /// The origin, split into `generated` and `verified` on render.
    pub origin: Option<Origin>,
    /// `sources` — where the concept derives from, each with a `resource`.
    pub sources: Vec<String>,
}

/// Quote a scalar for YAML, always, and escape everything a double-quoted scalar
/// cannot hold raw.
///
/// Quoting is unconditional rather than clever: a value that looks like a number,
/// a date, `yes`, `no`, `null` or `~` changes type under a YAML parser when
/// written bare, and a concept `type` of `no` becoming the boolean `false` is
/// exactly the failure that makes a bundle non-conformant while looking fine.
///
/// # Control characters, because the values are not ours
///
/// Every scalar here comes from somewhere a person can put anything: a git author
/// name, a document heading, a node key derived from a path. A raw newline inside
/// a quoted scalar does not merely look wrong — YAML folds it, so the value
/// changes; and a line of the injected text starting at column 0 with `key:` on
/// it ends the scalar and becomes a *sibling key*. That is frontmatter injection,
/// and in a document whose frontmatter decides a trust tier it is the one that
/// matters: a `verified:` block forged from inside a title.
///
/// So `\`, `"`, and every C0 control (plus DEL) are escaped — the common three by
/// name, the rest as `\uXXXX`, which YAML 1.2 §7.3.1 defines for exactly this.
fn yaml_scalar(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for ch in s.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            // C0 and DEL. `\uXXXX` is the general escape, used for everything
            // without a shorter name so nothing reaches the file raw.
            c if c.is_control() => {
                let _ = write!(out, "\\u{:04x}", u32::from(c));
            }
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

impl Frontmatter {
    /// Render the frontmatter block, `---` fences included.
    #[must_use]
    pub fn render(&self) -> String {
        let mut out = String::from("---\n");
        let _ = writeln!(out, "type: {}", yaml_scalar(&self.type_));
        for (key, value) in [
            ("title", self.title.as_deref()),
            ("description", self.description.as_deref()),
            ("resource", self.resource.as_deref()),
            ("status", self.status.as_deref()),
        ] {
            if let Some(v) = value {
                let _ = writeln!(out, "{key}: {}", yaml_scalar(v));
            }
        }
        if !self.tags.is_empty() {
            out.push_str("tags:\n");
            for t in &self.tags {
                let _ = writeln!(out, "  - {}", yaml_scalar(t));
            }
        }
        if let Some(origin) = &self.origin {
            // `generated` always: it records production, which happened whether or
            // not anyone confirmed the result.
            let _ = writeln!(
                out,
                "generated:\n  by: {}\n  at: {}",
                yaml_scalar(&origin.by.as_token()),
                yaml_scalar(&origin.at)
            );
            // `verified` only when the origin confirms. Its **absence** is the
            // unverified tier, so writing an empty list here would claim a
            // confirmation nobody made.
            if origin.confirms {
                let _ = writeln!(
                    out,
                    "verified:\n  - by: {}\n    at: {}",
                    yaml_scalar(&origin.by.as_token()),
                    yaml_scalar(&origin.at)
                );
            }
        }
        if !self.sources.is_empty() {
            out.push_str("sources:\n");
            for s in &self.sources {
                let _ = writeln!(out, "  - resource: {}", yaml_scalar(s));
            }
        }
        out.push_str("---\n");
        out
    }
}

/// The bundle directory a node kind belongs in.
///
/// Grouping by kind is what gives the bundle its hierarchy, and with it a
/// meaningful per-directory `index.md`. Code symbols share one directory rather
/// than splitting `fn` from `struct`, because a reader looking for a symbol does
/// not know which it is.
#[must_use]
pub fn section_for(kind: &str) -> &'static str {
    match kind {
        "adr" | "adr_section" => "decisions",
        "blueprint" => "blueprints",
        "doc" => "docs",
        "file" => "files",
        "marker" => "debt",
        _ => "symbols",
    }
}

/// The longest slug a filename may carry, before any disambiguating suffix.
///
/// `NAME_MAX` is 255 bytes on Linux and macOS. Real keys reach it: rendering this
/// repository failed with `File name too long (os error 63)` on a symbol key,
/// **after** writing part of the bundle — a unit test over short fixtures could
/// not have found it, and did not. The headroom below covers the `-` plus an
/// eight-character digest plus `.md`.
const MAX_SLUG: usize = 200;

/// Slug a node key into a filename that is safe on every filesystem and stable
/// across renders.
///
/// Unlike the vault this replaces, the result does **not** need a hash appended:
/// concepts live in per-kind directories, so the cross-kind collisions the vault
/// hashed around cannot occur here. Two keys that still slug identically within
/// one directory are disambiguated by the caller, which can see the whole set.
#[must_use]
pub fn slug(key: &str) -> String {
    let mut out = String::with_capacity(key.len());
    let mut last_dash = false;
    for ch in key.chars() {
        if ch.is_ascii_alphanumeric() {
            out.push(ch.to_ascii_lowercase());
            last_dash = false;
        } else if !last_dash && !out.is_empty() {
            out.push('-');
            last_dash = true;
        }
    }
    let trimmed = out.trim_end_matches('-').to_owned();
    if trimmed.is_empty() {
        return "concept".to_owned();
    }
    if trimmed.len() <= MAX_SLUG {
        return trimmed;
    }
    // Truncation can *create* a collision that the full keys did not have — two
    // long keys sharing a prefix become one name — so a shortened slug always
    // carries a digest of the whole key. Cutting on a char boundary is free here
    // because every retained character is ASCII.
    let keep = MAX_SLUG - 9;
    format!("{}-{}", &trimmed[..keep], short_digest(key))
}

/// The bundle-relative path a node takes in a single-project bundle whose slug
/// did not collide, always beginning with `/` so it can be used as a link target
/// verbatim (§6 — absolute, bundle-relative).
///
/// **Provisional, not authoritative.** [`assemble`] overwrites it, because the
/// real path also carries the workspace member's directory and a disambiguating
/// digest when two keys slug alike — neither of which is visible from one node.
/// Resolving a *link* with this function is the bug it exists to make obvious:
/// use the placement [`assemble`] passes to [`render_concept`].
#[must_use]
pub fn concept_path(node: &NodeSummary) -> String {
    format!("/{}/{}.md", section_for(&node.kind), slug(&node.key))
}

/// Map a graph provenance onto an OKF origin.
///
/// See the module documentation for why `Derived` confirms and `Inferred` does
/// not. `tool` is the producing tool's actor, used for everything a machine
/// produced; `human` is the authored content's confirmer, which the caller
/// resolves from the commit that introduced it.
///
/// # An imported concept re-emits the peer's own origin and does not come here
///
/// A fact imported from another repository's bundle (`external-*`, issue #706)
/// keeps the `generated`/`verified` block **that bundle carried**, recovered by
/// [`read::peer_origin`] and preferred by the caller. That is what stops the
/// round trip from re-tiering it: the peer's `verified: [{ by: human:alice }]`
/// goes back out naming Alice, so the next consumer learns who confirmed it
/// instead of being told this graph did.
///
/// The external arms below are the **fallback** for a concept whose bundle
/// recorded no origin at all. They confirm only when the caller supplies an
/// actor, on exactly `Authored`'s existing rule — an unknown confirmer yields no
/// confirmation rather than the wrong one. Naming `tool` as the confirmer would
/// be this graph vouching for a peer's fact on the strength of having read it.
/// The cost is honest and one-directional: an unattributed external concept
/// renders *unverified*, understating a claim rather than inventing one.
#[must_use]
pub fn origin_for(prov: Provenance, at: &str, tool: &Actor, human: Option<&Actor>) -> Origin {
    match prov {
        // Authored prose is confirmed by the person who wrote it. Falling back to
        // the tool when the author is unknown would move the concept from
        // human-reviewed to machine-confirmed, so an unknown author yields no
        // confirmation at all rather than the wrong one.
        //
        // Both **external** confirming tiers join this arm, including
        // `ExternalDerived` — which is the one place the imported tiers do not
        // simply follow their local namesake, and the difference is the reason
        // the tier is carried rather than the variant flattened. `Derived`
        // confirms below because *a consumer can re-derive it from the same
        // commit*; a consumer of **our** bundle cannot re-derive a peer's fact,
        // having neither their tree nor their extractor. What survives an import
        // is the peer's claim, and a claim needs a claimant's name on it to
        // confirm anything — which is exactly `Authored`'s rule, so it is
        // `Authored`'s arm.
        Provenance::Authored | Provenance::ExternalDerived | Provenance::ExternalAuthored => {
            match human {
                Some(actor) => Origin {
                    by: actor.clone(),
                    at: at.to_owned(),
                    confirms: true,
                },
                None => Origin {
                    by: tool.clone(),
                    at: at.to_owned(),
                    confirms: false,
                },
            }
        }
        // Deterministic extraction: a consumer can re-derive it from the same
        // commit and get the same answer, which is what machine-confirmed means.
        Provenance::Derived => Origin {
            by: tool.clone(),
            at: at.to_owned(),
            confirms: true,
        },
        // A similarity judgement carrying a confidence. Unverified, and honestly
        // so — and a peer's guess, or anything taken at *acknowledge* rather than
        // *trust*, is unverified for the same reason.
        Provenance::Inferred | Provenance::ExternalInferred => Origin {
            by: tool.clone(),
            at: at.to_owned(),
            confirms: false,
        },
    }
}

/// Render one node as an OKF concept document.
///
/// `body` is the node's prose when it has any. Relationships become plain
/// markdown links under a heading, which is how §6 says a relationship is
/// asserted — the link carries the relationship, and the surrounding prose says
/// what kind it is.
#[must_use]
pub fn render_concept(
    ex: &Explanation,
    fm: &Frontmatter,
    body: Option<&str>,
    resolve: &dyn Fn(&str) -> Option<String>,
) -> BundleFile {
    let mut content = fm.render();
    content.push('\n');
    let text = body.map(str::trim).filter(|t| !t.is_empty());
    // A document that opens with its own `#` heading keeps it. Writing the title
    // above it would give the concept two H1s saying nearly the same thing, and
    // the document's own is the better one — it is what its author wrote.
    let body_leads_with_heading = text.is_some_and(|t| t.starts_with("# "));
    if !body_leads_with_heading {
        let _ = writeln!(
            content,
            "# {}\n",
            fm.title.as_deref().unwrap_or(&ex.node.name)
        );
    }
    if let Some(text) = text {
        content.push_str(text);
        content.push_str("\n\n");
    }

    // Group by edge kind so the prose above each list can name the relationship.
    let mut groups: BTreeMap<&str, Vec<String>> = BTreeMap::new();
    for (edge, direction) in ex
        .outgoing
        .iter()
        .map(|e| (e, ""))
        .chain(ex.incoming.iter().map(|e| (e, "")))
    {
        if let Some(target) = resolve(&edge.node) {
            let label = edge.node.rsplit(':').next().unwrap_or(&edge.node);
            let confidence = edge
                .confidence
                .map(|c| format!(" (confidence {c:.2})"))
                .unwrap_or_default();
            groups
                .entry(edge.kind.as_str())
                .or_default()
                .push(format!("* {direction} [{label}]({target}){confidence}"));
        }
    }
    if !groups.is_empty() {
        content.push_str("## Relationships\n\n");
        for (kind, mut links) in groups {
            links.sort();
            links.dedup();
            let _ = writeln!(content, "### {kind}\n");
            for link in links {
                let _ = writeln!(content, "{link}");
            }
            content.push('\n');
        }
    }

    BundleFile {
        path: concept_path(&ex.node),
        content,
    }
}

/// One entry in a directory listing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexEntry {
    /// Display title.
    pub title: String,
    /// Link target, bundle-relative.
    pub target: String,
    /// Short description, taken from the concept's own frontmatter (§8 SHOULD).
    pub description: Option<String>,
}

/// Render a directory `index.md` (§8).
///
/// Deliberately **no frontmatter**: §8 permits it only in the bundle root, and a
/// stray block in a nested index would make the file a malformed concept rather
/// than a valid listing.
#[must_use]
pub fn render_index(heading: &str, entries: &[IndexEntry]) -> String {
    let mut out = format!("# {heading}\n\n");
    for e in entries {
        let desc = e
            .description
            .as_deref()
            .map(|d| format!(" - {d}"))
            .unwrap_or_default();
        let _ = writeln!(out, "* [{}]({}){desc}", e.title, e.target);
    }
    out
}

/// Render the bundle-root `index.md`, the one index that carries frontmatter.
#[must_use]
pub fn render_root_index(heading: &str, entries: &[IndexEntry]) -> String {
    let mut out = format!("---\nokf_version: {}\n---\n\n", yaml_scalar(OKF_VERSION));
    out.push_str(&render_index(heading, entries));
    out
}

/// One dated group of log entries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogDay {
    /// ISO 8601 `YYYY-MM-DD`. §9 requires this exact form for date headings.
    pub date: String,
    /// The day's entries, each already prefixed with its kind (`**Update**: …`).
    pub entries: Vec<String>,
}

/// Render `log.md` (§9): dated groups, newest first.
#[must_use]
pub fn render_log(heading: &str, days: &[LogDay]) -> String {
    let mut out = format!("# {heading}\n\n");
    for day in days {
        let _ = writeln!(out, "## {}\n", day.date);
        for entry in &day.entries {
            let _ = writeln!(out, "* {entry}");
        }
        out.push('\n');
    }
    out
}

/// A concept ready to be written: its node, its frontmatter, and its prose.
pub struct Concept<'a> {
    /// The graph node and its neighbourhood.
    pub explanation: &'a Explanation,
    /// The frontmatter to render.
    pub frontmatter: Frontmatter,
    /// The node's prose body, when it has one.
    pub body: Option<String>,
    /// The workspace member this concept came from, for a bundle spanning several
    /// repositories (ADR-0009). `None` for a single project.
    ///
    /// Nesting by member is what stops two repositories' `file:README.md` landing
    /// on one path. The vault this replaces solved the same problem by qualifying
    /// the *key* and hashing the filename, because it had one flat directory to
    /// work with; a bundle has directories, so the structure carries it.
    pub member: Option<String>,
}

/// One directory's concepts, each with the path [`assemble`]'s first pass gave
/// it — the intermediate the second pass renders from.
struct Placed<'a> {
    /// The workspace member these concepts came from, when the bundle spans one.
    /// Also the scope a link resolves in: the same key in two members is two
    /// concepts.
    member: Option<String>,
    /// The bundle-relative directory: `<member>/<section>`, or `<section>` alone.
    dir: String,
    /// Each concept and the bundle-relative path it will be written to.
    concepts: Vec<(Concept<'a>, String)>,
}

/// Assemble a whole bundle: every concept, an `index.md` for each section
/// directory, and the bundle-root `index.md` carrying `okf_version`.
///
/// A workspace **member's** directory carries no index of its own: it is a
/// container for that member's sections, and the root index links straight
/// through to `<member>/<section>`, so nothing is unreachable without one.
/// `an_index_lists_a_section_and_a_member_directory_is_a_container` pins that,
/// because the layout is documented in `docs/OKF_BUNDLE.md` and a bundle that
/// grew member indexes would make that page wrong without failing anything.
///
/// # Collisions are resolved here, and only here
///
/// [`slug`] can map two different keys onto one filename. The Obsidian vault this
/// replaces appended a hash to **every** note to survive that, because it wrote
/// one flat directory on filesystems that fold case — and it still lost 104 notes
/// of 8,144 before the hash existed. Nesting by kind removes most of the pressure,
/// but not all of it, so the remaining collisions are settled where the whole set
/// is visible rather than by a per-name rule that cannot see its neighbours.
///
/// A colliding name gets a short digest of its key appended. The **first** name in
/// key order keeps the bare slug, so a bundle re-rendered from an unchanged graph
/// is byte-identical: the disambiguation depends on the set, and the set is sorted.
///
/// Comparison is case-**insensitive** on purpose. `Foo` and `foo` are one file on
/// macOS and Windows, and a bundle that wrote both would silently lose one — which
/// is exactly how the vault lost notes.
///
/// # Links are resolved against the placement, not re-derived from the key
///
/// Which is why this happens in two passes. A concept's path depends on the whole
/// set — the member directory it nests under, and whether its slug collided — so
/// *any* rule that turns a key into a path on its own is guessing. The first pass
/// places every concept and records `key -> path`; the second renders, resolving
/// each relationship through that map. A key the map does not hold is not in the
/// bundle, and its link is dropped rather than written as a path that does not
/// exist.
///
/// The map is scoped **per member**: `file:README.md` is a different concept in
/// each repository of a workspace, so a link from one member's concept resolves
/// inside that member.
#[must_use]
pub fn assemble(concepts: Vec<Concept<'_>>, title: &str, log: &[LogDay]) -> Vec<BundleFile> {
    // Group by section, in key order, so both the output and the disambiguation
    // are deterministic.
    let mut by_section: BTreeMap<(Option<String>, &'static str), Vec<Concept<'_>>> =
        BTreeMap::new();
    let mut ordered = concepts;
    ordered.sort_by(|a, b| a.explanation.node.key.cmp(&b.explanation.node.key));
    for c in ordered {
        by_section
            .entry((c.member.clone(), section_for(&c.explanation.node.kind)))
            .or_default()
            .push(c);
    }

    // Pass one: place every concept. Nothing is rendered yet, because a link
    // written now could only guess at a path this pass is still deciding.
    let mut placed: Vec<Placed<'_>> = Vec::new();
    let mut index: BTreeMap<Option<String>, BTreeMap<String, String>> = BTreeMap::new();

    for ((member, section), members) in by_section {
        // `/<member>/<section>/` in a workspace, `/<section>/` on its own.
        let dir = member
            .as_deref()
            .map_or_else(|| section.to_owned(), |m| format!("{}/{section}", slug(m)));
        let mut taken: BTreeMap<String, usize> = BTreeMap::new();
        let mut concepts: Vec<(Concept<'_>, String)> = Vec::with_capacity(members.len());
        let member_index = index.entry(member.clone()).or_default();

        for c in members {
            // Case folding is already handled: `slug` lowercases, so no two slugs
            // can differ by case alone and this comparison needs no folding of its
            // own. An earlier version folded again here and read as the guard
            // against case-insensitive filesystems — it was a no-op, and removing
            // it changed no test, which is how the redundancy was found.
            let base = slug(&c.explanation.node.key);
            let name = match taken.get(&base) {
                None => base.clone(),
                Some(_) => format!("{base}-{}", short_digest(&c.explanation.node.key)),
            };
            *taken.entry(base).or_insert(0) += 1;

            let path = format!("/{dir}/{name}.md");
            member_index.insert(c.explanation.node.key.clone(), path.clone());
            concepts.push((c, path));
        }
        placed.push(Placed {
            member,
            dir,
            concepts,
        });
    }

    let mut files = Vec::new();
    let mut sections: Vec<IndexEntry> = Vec::new();

    // Pass two: render, resolving every link through the placement above.
    for section in placed {
        let member_index = index.get(&section.member);
        let dir = &section.dir;
        let mut entries: Vec<IndexEntry> = Vec::with_capacity(section.concepts.len());

        for (c, path) in &section.concepts {
            let title = c
                .frontmatter
                .title
                .clone()
                .unwrap_or_else(|| c.explanation.node.name.clone());
            entries.push(IndexEntry {
                title,
                target: path.clone(),
                description: c.frontmatter.description.clone(),
            });
            let mut file =
                render_concept(c.explanation, &c.frontmatter, c.body.as_deref(), &|key| {
                    // A cross-repo reference names a concept that is *in this
                    // bundle*, one member over. Following the placeholder's own
                    // key would land the reader on the stub standing in for it
                    // (see `cross_member_target`), which is a worse answer than
                    // the one the bundle already contains.
                    cross_member_target(&index, key)
                        .or_else(|| member_index.and_then(|m| m.get(key)).cloned())
                });
            file.path.clone_from(path);
            files.push(file);
        }

        files.push(BundleFile {
            path: format!("/{dir}/{INDEX_FILE}"),
            content: render_index(dir, &entries),
        });
        sections.push(IndexEntry {
            title: dir.clone(),
            target: format!("/{dir}/{INDEX_FILE}"),
            description: Some(format!("{} concept(s)", section.concepts.len())),
        });
    }

    if !log.is_empty() {
        files.push(BundleFile {
            path: format!("/{LOG_FILE}"),
            content: render_log("Update Log", log),
        });
    }
    files.push(BundleFile {
        path: format!("/{INDEX_FILE}"),
        content: render_root_index(title, &sections),
    });
    files.sort_by(|a, b| a.path.cmp(&b.path));
    files
}

/// Where a **cross-repo reference** actually points, when the member it names is
/// in this same bundle.
///
/// A workspace graph records a reference into another repository as an
/// `extref:<project>::<key>` placeholder node in the *referring* member
/// (ADR-0009): a stub standing in for a concept that member cannot see. But a
/// workspace **bundle** contains that other member, so the concept the reference
/// is about is right there — and linking to the stub instead would send a reader
/// to a document whose entire content is that it is not the document they wanted.
///
/// Both spellings reach the same place: the placeholder node's key
/// (`extref:<project>::<key>`, what an edge actually points at) and a bare
/// project-qualified key. What counts as *qualified* is
/// [`rto_graph::parse_qualified`]'s decision, not a second `::` rule invented
/// here — the keys were produced by that rule, so the bundle must not disagree
/// with it about where the project name ends.
///
/// `None` unless every part holds: the key parses as qualified, it names a member
/// of **this** bundle, and that member really has the concept. The caller falls
/// back to the member-scoped lookup then — which yields the placeholder, a file
/// that exists — because a stub in the bundle beats a link to nothing.
fn cross_member_target(
    index: &BTreeMap<Option<String>, BTreeMap<String, String>>,
    key: &str,
) -> Option<String> {
    let qualified = key.strip_prefix(EXTREF_PREFIX).unwrap_or(key);
    let (project, bare) = rto_graph::parse_qualified(qualified)?;
    // The membership test is what makes reading a bare key this way safe: a
    // symbol key containing `::` splits too, but its left half is never a
    // workspace member's name.
    index.get(&Some(project.to_owned()))?.get(bare).cloned()
}

/// A short, stable digest of a key, for disambiguating a collided slug.
///
/// FNV-1a rather than a cryptographic hash: this is a filename disambiguator, not
/// a security boundary, and it must stay identical across renders and platforms.
///
/// The **low 32 bits**, masked rather than sliced off the hex rendering. An
/// earlier version wrote `format!("{h:08x}")[..8]`, which is a string operation
/// wearing a number's clothes: `{:08x}` pads to 8 but does not truncate, so a
/// hash above `2^32` renders 9 to 16 digits and the slice then takes a *high*
/// window whose offset moves with the magnitude. The entropy is 32 bits either
/// way, so no collision was ever more likely — but which 32 bits you got depended
/// on how large the hash happened to be, and a filename rule nobody can state in
/// one sentence is a filename rule waiting to be got wrong.
fn short_digest(key: &str) -> String {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in key.as_bytes() {
        h ^= u64::from(*b);
        h = h.wrapping_mul(0x0000_0100_0000_01b3);
    }
    // Masked to 32 bits, so `{:08x}` renders exactly eight digits and no cast is
    // needed to say so. `MAX_SLUG`'s headroom is written against that eight.
    format!("{:08x}", h & 0xffff_ffff)
}

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

    fn node(key: &str, kind: &str, name: &str) -> NodeSummary {
        NodeSummary {
            key: key.to_owned(),
            kind: kind.to_owned(),
            name: name.to_owned(),
            path: None,
            lang: None,
        }
    }

    fn explanation(key: &str, kind: &str, name: &str) -> Explanation {
        Explanation {
            schema: rto_graph::SCHEMA,
            node: node(key, kind, name),
            meta: serde_json::Value::Null,
            outgoing: Vec::new(),
            incoming: Vec::new(),
        }
    }

    fn concept<'a>(ex: &'a Explanation, type_: &str) -> Concept<'a> {
        Concept {
            explanation: ex,
            frontmatter: Frontmatter {
                type_: type_.to_owned(),
                ..Frontmatter::default()
            },
            body: None,
            member: None,
        }
    }

    fn edge(to: &str) -> rto_graph::EdgeRef {
        rto_graph::EdgeRef {
            kind: "references".to_owned(),
            provenance: "authored",
            confidence: None,
            node: to.to_owned(),
        }
    }

    /// Every `](/…)` link in an emitted bundle, as `(containing file, target)`.
    fn internal_links(files: &[BundleFile]) -> Vec<(String, String)> {
        let mut out = Vec::new();
        for f in files {
            let mut rest = f.content.as_str();
            while let Some(open) = rest.find("](/") {
                rest = &rest[open + 2..];
                let Some(close) = rest.find(')') else { break };
                out.push((f.path.clone(), rest[..close].to_owned()));
                rest = &rest[close..];
            }
        }
        out
    }

    /// **Every internal link points at a file the bundle actually contains.**
    ///
    /// The conformance test above cannot make this assertion, and would not have
    /// caught its failure: §11 tells consumers they **MUST NOT** reject a bundle
    /// for a broken cross-link, so a bundle full of them is still conformant. It
    /// is still wrong, and this repository promises better (ADR-0021).
    ///
    /// Three ways a link target can differ from a key's own slug, all present in
    /// the fixture because a resolver that re-derives the path from the key gets
    /// each of them wrong:
    ///
    /// 1. a **workspace member** prefixes the directory;
    /// 2. a **collided slug** takes a digest suffix;
    /// 3. a node whose **kind and key disagree** about the section —
    ///    `blueprint_section` keys begin `blueprint:` but the concept files under
    ///    `symbols`, which is how 43 links broke in a real render of this
    ///    repository.
    #[test]
    fn every_emitted_link_resolves_to_a_file_that_exists() {
        // (3) key says `blueprint:`, kind says `blueprint_section` → `symbols`.
        let section = {
            let mut ex = explanation(
                "blueprint:docs/blueprint/roteiro.md#1-crate-placement",
                "blueprint_section",
                "1 · Crate placement",
            );
            ex.outgoing = vec![edge("blueprint:docs/blueprint/roteiro.md")];
            ex
        };
        let plan = {
            let mut ex = explanation(
                "blueprint:docs/blueprint/roteiro.md",
                "blueprint",
                "roteiro.md",
            );
            // (2) both collision partners, and the section above.
            ex.outgoing = vec![
                edge("blueprint:docs/blueprint/roteiro.md#1-crate-placement"),
                edge("sym:rust:a/b.rs#Thing"),
                edge("sym:rust:a-b.rs#thing"),
            ];
            ex
        };
        let thing_a = explanation("sym:rust:a/b.rs#Thing", "fn", "Thing");
        let thing_b = explanation("sym:rust:a-b.rs#thing", "fn", "thing");
        assert_eq!(
            slug(&thing_a.node.key),
            slug(&thing_b.node.key),
            "the fixture must actually collide, or the digest suffix is never exercised"
        );

        // (1) everything nests under one workspace member.
        let concepts: Vec<Concept<'_>> = [
            (&section, "blueprint_section"),
            (&plan, "blueprint"),
            (&thing_a, "fn"),
            (&thing_b, "fn"),
        ]
        .into_iter()
        .map(|(ex, type_)| {
            let mut c = concept(ex, type_);
            c.member = Some("Alpha".to_owned());
            c
        })
        .collect();

        let files = assemble(concepts, "Workspace", &[]);
        let emitted: std::collections::BTreeSet<&str> =
            files.iter().map(|f| f.path.as_str()).collect();

        // The fixture is load-bearing only if the placement really did all three
        // things. Asserted before the links, so a fixture that stopped exercising
        // one of them fails here rather than passing vacuously below.
        assert!(
            emitted
                .iter()
                .all(|p| *p == "/index.md" || p.starts_with("/alpha/")),
            "every concept must nest under its member: {emitted:?}"
        );
        assert!(
            emitted.contains("/alpha/symbols/sym-rust-a-b-rs-thing.md"),
            "the first collision partner keeps the bare slug: {emitted:?}"
        );
        assert!(
            emitted
                .iter()
                .any(|p| p.starts_with("/alpha/symbols/sym-rust-a-b-rs-thing-")),
            "the second takes a digest suffix: {emitted:?}"
        );
        assert!(
            emitted.contains(
                "/alpha/symbols/blueprint-docs-blueprint-roteiro-md-1-crate-placement.md"
            ),
            "a `blueprint_section` files under `symbols`, not under its key's \
             `blueprints`: {emitted:?}"
        );

        let links = internal_links(&files);
        // A resolver that drops what it cannot place satisfies the loop below by
        // emitting nothing, so count first: 4 relationship links (one per edge),
        // 4 concept entries across the two directory indexes, and 2 directory
        // entries in the root index.
        assert_eq!(links.len(), 4 + 4 + 2, "{links:?}");

        for (from, target) in &links {
            assert!(
                emitted.contains(target.as_str()),
                "{from} links to {target}, which the bundle does not contain: {emitted:?}"
            );
        }

        // Existence is not enough, and this is the half that is easy to miss: two
        // concepts whose slugs collided are *different files*, so a resolver that
        // re-derives the bare slug sends both links to whichever one kept it. That
        // target exists, so the loop above passes while the link points at the
        // wrong concept — silently wrong rather than broken. `plan` has three
        // distinct edge targets and must therefore emit three distinct paths.
        let plan_path = "/alpha/blueprints/blueprint-docs-blueprint-roteiro-md.md";
        let from_plan: std::collections::BTreeSet<&str> = links
            .iter()
            .filter(|(from, _)| from == plan_path)
            .map(|(_, target)| target.as_str())
            .collect();
        assert_eq!(
            from_plan.len(),
            plan.outgoing.len(),
            "{plan_path} has {} edges to distinct concepts but links to {} file(s): {from_plan:?}",
            plan.outgoing.len(),
            from_plan.len()
        );
    }

    /// Every file the bundle emits satisfies §11's conformance criteria.
    ///
    /// Asserted over the *emitted set* rather than over the renderer, because the
    /// specification is a statement about a bundle and a per-function test cannot
    /// make it.
    #[test]
    fn every_emitted_bundle_is_conformant() {
        let a = explanation("adr:0001#decision", "adr", "ADR-0001");
        let b = explanation("sym:rust:src/main.rs#greet", "fn", "greet");
        let files = assemble(
            vec![concept(&a, "adr"), concept(&b, "fn")],
            "Roteiro",
            &[LogDay {
                date: "2026-08-28".into(),
                entries: vec!["**Update**: rebuilt.".into()],
            }],
        );

        for f in &files {
            let reserved = f.path.ends_with(INDEX_FILE) || f.path.ends_with(LOG_FILE);
            if reserved {
                continue;
            }
            // §11.1 — a parseable frontmatter block, and §11.2 a non-empty `type`.
            assert!(
                f.content.starts_with("---\n"),
                "{} opens with no frontmatter block",
                f.path
            );
            let end = f.content[4..]
                .find("\n---\n")
                .expect("frontmatter must terminate");
            let block = &f.content[4..4 + end];
            assert!(
                block
                    .lines()
                    .any(|l| l.starts_with("type: ") && l.len() > 8),
                "{} carries no non-empty `type`: {block}",
                f.path
            );
        }

        // §8 — a nested index carries no frontmatter; only the root may.
        let nested = files
            .iter()
            .find(|f| f.path == "/decisions/index.md")
            .expect("a per-directory index");
        assert!(!nested.content.starts_with("---"), "{}", nested.content);
        let root = files
            .iter()
            .find(|f| f.path == "/index.md")
            .expect("a root index");
        assert!(
            root.content.contains("okf_version: \"0.2\""),
            "{}",
            root.content
        );
    }

    /// A document that brings its own heading is not given a second one.
    #[test]
    fn a_body_with_its_own_heading_is_not_double_titled() {
        let ex = explanation("adr:0010", "adr", "ADR-0010");
        let fm = Frontmatter {
            type_: "adr".into(),
            title: Some("Explorer web app".into()),
            ..Frontmatter::default()
        };
        let with = render_concept(
            &ex,
            &fm,
            Some("# ADR-0010: Explorer web app\n\nBody."),
            &|_| None,
        );
        let h1s = |c: &str| c.lines().filter(|l| l.starts_with("# ")).count();
        assert_eq!(h1s(&with.content), 1, "exactly one H1: {}", with.content);
        assert!(with.content.contains("# ADR-0010: Explorer web app"));
        assert!(
            !with.content.contains("# Explorer web app\n\n# ADR-0010"),
            "the frontmatter title must not be stacked above the document's own"
        );

        // A body with no heading still gets one, or the concept has no title at all.
        let without = render_concept(&ex, &fm, Some("Just prose."), &|_| None);
        assert!(
            without.content.contains("# Explorer web app"),
            "a headingless body still gets the title: {}",
            without.content
        );
        assert_eq!(h1s(&without.content), 1);
    }

    /// Two members' identically-named concepts do not collide.
    ///
    /// Every repository has a `README.md`, so `file:README.md` is the same key in
    /// each — the case the vault this replaces had to qualify keys and hash
    /// filenames to survive, because it wrote one flat directory. Nesting by
    /// member carries it structurally instead, and the assertion is again the one
    /// whose failure was invisible: **both concepts are written**.
    #[test]
    fn two_members_sharing_a_key_both_survive() {
        let a = explanation("file:README.md", "file", "README.md");
        let b = explanation("file:README.md", "file", "README.md");
        let mut ca = concept(&a, "file");
        ca.member = Some("app".to_owned());
        let mut cb = concept(&b, "file");
        cb.member = Some("lib".to_owned());

        let files = assemble(vec![ca, cb], "Workspace", &[]);
        let concepts: Vec<&BundleFile> = files
            .iter()
            .filter(|f| !f.path.ends_with(INDEX_FILE) && !f.path.ends_with(LOG_FILE))
            .collect();
        assert_eq!(concepts.len(), 2, "both members' README must be written");
        assert!(
            concepts.iter().any(|f| f.path.starts_with("/app/")),
            "one under its member: {:?}",
            concepts.iter().map(|f| &f.path).collect::<Vec<_>>()
        );
        assert!(concepts.iter().any(|f| f.path.starts_with("/lib/")));
    }

    /// The prefix this module strips is the one the graph writes.
    ///
    /// Two crates spelling a key namespace independently is how a resolver stops
    /// recognising the keys it is given, silently — the link would simply stop
    /// crossing, and every target still exists, so nothing else would notice.
    #[test]
    fn the_placeholder_prefix_is_the_graphs() {
        assert_eq!(rto_graph::external_ref_key(""), EXTREF_PREFIX);
    }

    /// **A cross-repo reference links to the other member's concept, not to the
    /// stub standing in for it.**
    ///
    /// A workspace graph records a reference into another repository as an
    /// `extref:<project>::<key>` placeholder in the *referring* member, because
    /// that member cannot see the target. A workspace **bundle** can: the other
    /// member is in it. Resolving the placeholder's own key — which is what a
    /// member-scoped lookup does — produces a link that works and teaches nothing,
    /// landing the reader on a document whose whole content is that it is not the
    /// document they wanted. An existence check cannot see that, which is why the
    /// assertion is the *destination* rather than that a link resolved.
    #[test]
    fn a_cross_repo_reference_reaches_the_other_members_concept() {
        // `app` has the real concept.
        let real = explanation("file:README.md", "file", "README.md");
        // `deploy` holds the placeholder, and a document that references it.
        let stub = explanation(
            "extref:app::file:README.md",
            "external_ref",
            "app::file:README.md",
        );
        let referrer = {
            let mut ex = explanation("doc:deploy.md", "doc", "deploy.md");
            ex.outgoing = vec![edge("extref:app::file:README.md")];
            ex
        };

        let member = |ex, type_, name: &str| {
            let mut c = concept(ex, type_);
            c.member = Some(name.to_owned());
            c
        };
        let files = assemble(
            vec![
                member(&real, "file", "app"),
                member(&stub, "external_ref", "deploy"),
                member(&referrer, "doc", "deploy"),
            ],
            "Workspace",
            &[],
        );

        let emitted: std::collections::BTreeSet<&str> =
            files.iter().map(|f| f.path.as_str()).collect();
        let target = "/app/files/file-readme-md.md";
        assert!(
            emitted.contains(target),
            "the fixture must place the real concept: {emitted:?}"
        );
        // The stub is still written — it is a concept of `deploy`'s graph — and
        // links must simply not prefer it.
        let stub_path = "/deploy/symbols/extref-app-file-readme-md.md";
        assert!(
            emitted.contains(stub_path),
            "the placeholder must still be a concept: {emitted:?}"
        );

        let links = internal_links(&files);
        let targets: Vec<&str> = links
            .iter()
            .filter(|(from, _)| from == "/deploy/docs/doc-deploy-md.md")
            .map(|(_, t)| t.as_str())
            .collect();
        assert_eq!(
            targets,
            vec![target],
            "the reference must reach `app`'s concept rather than `deploy`'s stub"
        );
    }

    /// **An `index.md` lists a section; a workspace member's directory is a
    /// container and has none.**
    ///
    /// §8 makes an index *optional* in any directory, so a missing one is not a
    /// conformance failure and no conformance check will ever mention it. What it
    /// is instead is a documented layout — `docs/OKF_BUNDLE.md`, ADR-0021 and the
    /// site each tell a reader which directories carry one — and prose the
    /// renderer can contradict without failing anything is how all three came to
    /// over-claim "each directory carries an `index.md`". Pinning the exact set
    /// means a bundle that grows member indexes has to move those pages with it.
    ///
    /// The member directory is not a dead end without one: the root index links
    /// straight through to `<member>/<section>`, which the second half asserts,
    /// because "no index here" is only defensible while nothing needs it.
    #[test]
    fn an_index_lists_a_section_and_a_member_directory_is_a_container() {
        let readme = explanation("file:README.md", "file", "README.md");
        let thing = explanation("sym:rust:a.rs#thing", "fn", "thing");

        let member = |ex, type_, name: &str| {
            let mut c = concept(ex, type_);
            c.member = Some(name.to_owned());
            c
        };
        let files = assemble(
            vec![
                member(&readme, "file", "app"),
                member(&thing, "fn", "deploy"),
            ],
            "Workspace",
            &[],
        );

        let emitted: std::collections::BTreeSet<&str> =
            files.iter().map(|f| f.path.as_str()).collect();
        // The fixture is load-bearing only if it really made two members whose
        // sections differ, so that is asserted before the set below — which an
        // empty bundle would otherwise satisfy by containing only a root index.
        assert!(
            emitted.contains("/app/files/file-readme-md.md")
                && emitted.contains("/deploy/symbols/sym-rust-a-rs-thing.md"),
            "the fixture must place a concept in each member: {emitted:?}"
        );

        // `/{INDEX_FILE}` rather than the bare name: a concept whose slug ends
        // `-index` would otherwise be counted as a directory listing.
        let index_suffix = format!("/{INDEX_FILE}");
        let indexes: Vec<&str> = files
            .iter()
            .map(|f| f.path.as_str())
            .filter(|p| p.ends_with(&index_suffix))
            .collect();
        assert_eq!(
            indexes,
            vec![
                "/app/files/index.md",
                "/deploy/symbols/index.md",
                "/index.md"
            ],
            "the bundle root and every section directory carry an index, and a \
             member directory carries none"
        );

        let from_root: Vec<String> = internal_links(&files)
            .into_iter()
            .filter(|(from, _)| from == "/index.md")
            .map(|(_, target)| target)
            .collect();
        assert_eq!(
            from_root,
            vec![
                "/app/files/index.md".to_owned(),
                "/deploy/symbols/index.md".to_owned()
            ],
            "the root index must reach each section directly, since the member \
             directory between them carries no index of its own"
        );
    }

    /// A key longer than the filesystem allows is truncated, and truncation does
    /// not merge two concepts into one.
    ///
    /// Found by *running* the renderer over this repository, not by a unit test:
    /// it failed with `File name too long (os error 63)` after writing part of
    /// the bundle. Short fixtures cannot reach this, which is why the earlier
    /// tests were all green while the real render was broken.
    #[test]
    fn an_overlong_key_is_truncated_without_colliding() {
        let long = "sym:rust:".to_owned() + &"a".repeat(400);
        // Same 400-character prefix, different tails: truncation alone would
        // merge them.
        let a = format!("{long}#one");
        let b = format!("{long}#two");

        assert!(
            slug(&a).len() <= MAX_SLUG,
            "slug must fit: {}",
            slug(&a).len()
        );
        assert!(slug(&b).len() <= MAX_SLUG);
        assert_ne!(
            slug(&a),
            slug(&b),
            "two keys sharing a truncated prefix must not slug to one name"
        );
        // And the cap leaves room for `.md` plus a disambiguating suffix inside
        // NAME_MAX (255).
        assert!(slug(&a).len() + ".md".len() + 9 <= 255);
    }

    #[test]
    fn colliding_slugs_do_not_lose_a_concept() {
        // Different keys, identical slug. (Case is not a separate hazard here:
        // `slug` lowercases, so a case-only difference cannot survive into a
        // filename at all.)
        let a = explanation("sym:rust:a/b.rs#Thing", "fn", "Thing");
        let b = explanation("sym:rust:a-b.rs#thing", "fn", "thing");
        assert_eq!(
            slug(&a.node.key).to_ascii_lowercase(),
            slug(&b.node.key).to_ascii_lowercase(),
            "fixture must actually collide, or this test proves nothing"
        );

        let files = assemble(vec![concept(&a, "fn"), concept(&b, "fn")], "T", &[]);
        let concepts: Vec<&BundleFile> = files
            .iter()
            .filter(|f| !f.path.ends_with(INDEX_FILE) && !f.path.ends_with(LOG_FILE))
            .collect();
        assert_eq!(concepts.len(), 2, "both concepts must be written");

        let paths: std::collections::BTreeSet<String> = concepts
            .iter()
            .map(|f| f.path.to_ascii_lowercase())
            .collect();
        assert_eq!(
            paths.len(),
            2,
            "and to distinct files even when case is folded: {paths:?}"
        );
    }

    /// The same graph renders to the same bytes, whatever order it arrives in.
    ///
    /// Both fixtures are in the **same section** on purpose. An earlier version
    /// used an `adr` and a `fn`, which land in different directories — so each
    /// section held one member, ordering within a section was never exercised,
    /// and deleting the sort changed nothing. The test passed and guarded nothing.
    #[test]
    fn assembly_is_deterministic() {
        let a = explanation("sym:rust:a.rs#a", "fn", "a");
        let b = explanation("sym:rust:z.rs#z", "fn", "z");
        assert_eq!(
            section_for(&a.node.kind),
            section_for(&b.node.kind),
            "the fixtures must share a section, or ordering is not under test"
        );
        let once = assemble(vec![concept(&a, "fn"), concept(&b, "fn")], "T", &[]);
        let twice = assemble(vec![concept(&b, "fn"), concept(&a, "fn")], "T", &[]);
        assert_eq!(once, twice, "input order must not change the bundle");
    }

    fn tool() -> Actor {
        Actor::Tool("roteiro".into(), "4.0.0".into())
    }

    #[test]
    fn the_only_required_field_is_type() {
        let fm = Frontmatter {
            type_: "adr".into(),
            ..Frontmatter::default()
        };
        let rendered = fm.render();
        assert_eq!(rendered, "---\ntype: \"adr\"\n---\n");
    }

    #[test]
    fn actors_use_the_forms_the_spec_requires() {
        assert_eq!(Actor::Human("pixie79".into()).as_token(), "human:pixie79");
        assert_eq!(tool().as_token(), "roteiro/4.0.0");
        assert_eq!(
            Actor::Process("nightly".into()).as_token(),
            "process:nightly"
        );
    }

    /// The trust tiers of §5.3, asserted through the rendered frontmatter rather
    /// than through `Origin`, because the tier is what a consumer derives.
    #[test]
    fn provenance_maps_onto_the_trust_tiers() {
        let human = Actor::Human("pixie79".into());
        let at = "2026-08-28T10:00:00Z";

        let authored = origin_for(Provenance::Authored, at, &tool(), Some(&human));
        let fm = Frontmatter {
            type_: "adr".into(),
            origin: Some(authored),
            ..Frontmatter::default()
        };
        let rendered = fm.render();
        assert!(
            rendered.contains("verified:") && rendered.contains("human:pixie79"),
            "authored prose is human-reviewed: {rendered}"
        );

        let derived = origin_for(Provenance::Derived, at, &tool(), Some(&human));
        let fm = Frontmatter {
            type_: "fn".into(),
            origin: Some(derived),
            ..Frontmatter::default()
        };
        let rendered = fm.render();
        assert!(
            rendered.contains("verified:"),
            "deterministic extraction is machine-confirmed: {rendered}"
        );
        assert!(
            !rendered.contains("human:"),
            "but it is not human-reviewed — the prefix is the only thing that \
             separates the tiers: {rendered}"
        );

        let inferred = origin_for(Provenance::Inferred, at, &tool(), Some(&human));
        let fm = Frontmatter {
            type_: "fn".into(),
            origin: Some(inferred),
            ..Frontmatter::default()
        };
        let rendered = fm.render();
        assert!(
            rendered.contains("generated:"),
            "a heuristic still records that it was produced: {rendered}"
        );
        assert!(
            !rendered.contains("verified:"),
            "but claims no confirmation — absence *is* the unverified tier, so an \
             empty list here would launder a guess: {rendered}"
        );
    }

    /// An authored node whose author is unknown must not silently become
    /// machine-confirmed.
    #[test]
    fn an_authored_node_with_no_known_human_claims_nothing() {
        let o = origin_for(Provenance::Authored, "2026-08-28T10:00:00Z", &tool(), None);
        assert!(
            !o.confirms,
            "falling back to the tool would move the concept between trust tiers"
        );
    }

    #[test]
    fn scalars_are_quoted_so_yaml_cannot_retype_them() {
        // `no`, `12:30` and `1.0` all change type when written bare.
        for raw in ["no", "yes", "null", "~", "12:30", "1.0", "on"] {
            let fm = Frontmatter {
                type_: raw.into(),
                ..Frontmatter::default()
            };
            assert_eq!(fm.render(), format!("---\ntype: \"{raw}\"\n---\n"));
        }
    }

    /// **A value cannot break out of its own scalar.**
    ///
    /// Every scalar here comes from somewhere a person can put anything — a git
    /// author name, a heading, a key derived from a path. A raw newline does not
    /// merely make the YAML ugly: the text after it starts a new line at column
    /// 0, so `verified:` written inside a *title* becomes a sibling key of the
    /// title, and this bundle's frontmatter is what a consumer derives a trust
    /// tier from (§5.3). Forging `verified` is the whole attack.
    ///
    /// Asserted as *the injected key never begins a line*, not merely as "the
    /// output contains `\\n`": a rendering that escaped the newline but left the
    /// text somewhere else would satisfy the weaker check.
    #[test]
    fn a_scalar_cannot_forge_a_sibling_key() {
        let forged = "Innocent Title\"\nverified:\n  - by: \"human:someone-else";
        let fm = Frontmatter {
            type_: "adr".into(),
            title: Some(forged.to_owned()),
            ..Frontmatter::default()
        };
        let rendered = fm.render();

        assert!(
            !rendered.lines().any(|l| l.starts_with("verified:")),
            "a title must not be able to open a `verified` block: {rendered}"
        );
        // Exactly three lines of frontmatter — the fences and one `type`, one
        // `title`. A forged key would add its own.
        assert_eq!(
            rendered.lines().count(),
            4,
            "the block must hold two keys and two fences: {rendered}"
        );
        assert!(
            rendered.contains("\\n"),
            "the newline is escaped: {rendered}"
        );

        // The control characters a quoted scalar cannot hold raw, each replaced
        // by an escape rather than written through.
        for (raw, escaped) in [
            ("a\nb", "\\n"),
            ("a\rb", "\\r"),
            ("a\tb", "\\t"),
            ("a\u{0}b", "\\u0000"),
            ("a\u{7}b", "\\u0007"),
            ("a\u{1b}b", "\\u001b"),
            ("a\u{7f}b", "\\u007f"),
        ] {
            let out = yaml_scalar(raw);
            assert!(out.contains(escaped), "{raw:?} -> {out}");
            assert!(
                !out.chars().any(char::is_control),
                "no control character may survive into the file: {out:?}"
            );
        }
    }

    #[test]
    fn a_nested_index_carries_no_frontmatter_but_the_root_does() {
        let entries = [IndexEntry {
            title: "ADR-0001".into(),
            target: "/decisions/adr-0001.md".into(),
            description: Some("The founding decision.".into()),
        }];
        let nested = render_index("Decisions", &entries);
        assert!(
            !nested.starts_with("---"),
            "§8 permits frontmatter only in the bundle root: {nested}"
        );
        assert!(nested.contains("* [ADR-0001](/decisions/adr-0001.md) - The founding decision."));

        let root = render_root_index("Bundle", &entries);
        assert!(
            root.starts_with("---\nokf_version: \"0.2\"\n---\n"),
            "{root}"
        );
    }

    #[test]
    fn log_days_use_iso_8601_headings() {
        let log = render_log(
            "Update Log",
            &[LogDay {
                date: "2026-08-28".into(),
                entries: vec!["**Update**: rebuilt from `74fad8f`.".into()],
            }],
        );
        assert!(log.contains("## 2026-08-28\n"), "{log}");
        assert!(
            log.contains("* **Update**: rebuilt from `74fad8f`."),
            "{log}"
        );
    }

    #[test]
    fn concepts_are_grouped_into_per_kind_directories() {
        assert_eq!(section_for("adr"), "decisions");
        assert_eq!(section_for("adr_section"), "decisions");
        assert_eq!(section_for("blueprint"), "blueprints");
        assert_eq!(section_for("file"), "files");
        assert_eq!(section_for("marker"), "debt");
        // Every code symbol shares one directory: a reader looking for `greet`
        // does not know whether it is a fn, a struct or a trait.
        assert_eq!(section_for("fn"), "symbols");
        assert_eq!(section_for("struct"), "symbols");
        assert_eq!(section_for("trait"), "symbols");
    }

    #[test]
    fn slugs_are_stable_and_filesystem_safe() {
        assert_eq!(
            slug("sym:rust:src/main.rs#greet"),
            "sym-rust-src-main-rs-greet"
        );
        assert_eq!(slug("adr:0001#decision"), "adr-0001-decision");
        // No trailing separator, no empty result, no run of dashes.
        assert_eq!(slug("a//b"), "a-b");
        assert_eq!(slug("trailing///"), "trailing");
        assert_eq!(slug("###"), "concept");
    }

    /// The digest is **always eight lowercase hex digits**, whatever the key.
    ///
    /// [`MAX_SLUG`]'s headroom is written against that eight — `slug` reserves
    /// `MAX_SLUG - 9` for a truncated name so the dash, the digest and `.md` fit
    /// inside `NAME_MAX`. A digest that could be wider would silently spend that
    /// reservation and put the failure back where it was found: a render dying on
    /// `File name too long` after writing part of the bundle.
    ///
    /// Nothing about the width is visible at the call sites, which is why it is
    /// asserted here rather than inferred from them.
    #[test]
    fn the_digest_is_always_eight_hex_digits() {
        // Long, empty, unicode, and enough varied keys to reach hashes on both
        // sides of 2^32 — the boundary the previous rendering was sensitive to.
        let mut keys: Vec<String> = vec![
            String::new(),
            "a".into(),
            "sym:rust:src/main.rs#greet".into(),
            "ünïcødé::key".into(),
            "x".repeat(4096),
        ];
        keys.extend((0..512).map(|i| format!("sym:rust:crates/a/src/b{i}.rs#Thing{i}")));

        for key in &keys {
            let digest = short_digest(key);
            assert_eq!(digest.len(), 8, "{key:?} -> {digest}");
            assert!(
                digest
                    .chars()
                    .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)),
                "lowercase hex only: {key:?} -> {digest}"
            );
        }
        // Stable across calls: the disambiguation must not move between renders.
        assert_eq!(short_digest("adr:0001"), short_digest("adr:0001"));
    }
}