memstead-base 0.27.0

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
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
//! The engine-owned **preparation registry** — the one place that says which
//! preparations exist, on which anchor grains, at which engine touchpoint,
//! and what each grain's PREPARED FORM is.
//!
//! A source declares at most one preparation ([`crate::pipeline::Source::preparation`],
//! a string identifier). The engine refuses any identifier this registry
//! does not know ([`crate::binding::CapabilityError::PreparationUnsupported`],
//! raised by [`crate::binding::validate_binding`] and mirrored on the
//! brief-render path for a record that acquired one by hand) and consults the
//! registry at exactly two touchpoints:
//!
//! - **Touchpoint A — prepared form.** Anchor observation asks the registry
//!   for an artifact's prepared form before hashing it (the engine's one
//!   per-anchor observation site). The standalone `verify-anchors` operation
//!   and the binding-backed verify share that site, so both inherit every
//!   registered preparation without redesign.
//! - **Touchpoint B — delivery units.** The ingest delivery path asks the
//!   registry for a source's unit sequence ([`unitize`]): one file can carry
//!   many delivery units, addressed `<path>#<key>`, and the units of a whole
//!   source form one deterministic total order derived from the units' own
//!   keys ([`Touchpoint::DeliveryUnits`], first entry [`DATED_ENTRIES`]).
//!   A source declaring no delivery preparation keeps file-granularity
//!   delivery unchanged.
//!
//! **Identity.** [`crate::binding::PREPARATION_IMPL_VERSION`] is hashed into
//! every binding's `hash(D)` next to the declared identifier. Landing or
//! changing an implementation bumps the constant, which invalidates every
//! finding keyed on the old hash by construction (`ingest::findings` keys on
//! `hash(D)` alone).
//!
//! **Prepared forms per grain.** The path grains (`span` / `file`) hash their
//! bytes through [`crate::anchor::prepared_content_hash`] (the minimal
//! canonicalization: BOM, line endings, final newline). The `url` grain uses
//! the **same canonicalization over observation-supplied content** — the
//! engine never fetches, so whoever observed the URL supplies the bytes at
//! write time (`AnchorInput::content`) — and defaults to `hash_stability:
//! unstable`, a served page being a moving target. The `entity` grain's
//! prepared form is computed from the live graph, never from supplied bytes:
//! the canonical rendered markdown by default, or — under
//! [`ENTITY_LOAD_BEARING`] — the stable serialization of the type's
//! load-bearing sections.
//!
//! **Non-goal, by standing decision:** PDF / DOCX / audio conversion. An
//! agent with a capable read tool extracts; the raw-byte fallback of the
//! prepared-content hash already drift-detects a binary artifact.

use serde::{Deserialize, Serialize};

use crate::anchor::{AnchorGrain, AnchorHashStability, prepared_content_hash};
use crate::entity::Entity;

/// The engine touchpoint a registered preparation plugs into.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Touchpoint {
    /// Touchpoint A: anchor observation asks the registry for the prepared
    /// form an artifact hashes as (content and code-map flavours).
    PreparedForm,
    /// Touchpoint B: the ingest delivery path asks the registry for a
    /// source's unit sequence (the delivery flavour).
    DeliveryUnits,
}

/// One registered preparation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Preparation {
    /// The identifier a source declares (`Source::preparation`).
    pub id: &'static str,
    /// Which engine touchpoint consults it.
    pub touchpoint: Touchpoint,
    /// The anchor grains it produces a prepared form for. A binding may
    /// declare it only over a medium whose anchor namespace admits at least
    /// one of these grains (checked at binding validation).
    pub grains: &'static [AnchorGrain],
    /// One sentence for the operator and the refusal payloads.
    pub description: &'static str,
}

/// Content preparation on the `entity` grain: the prepared form is the stable
/// serialization of the entity type's **load-bearing sections** (see
/// [`load_bearing_sections`]), so a dependent's prepared hash breaks when a
/// load-bearing sentence changes and holds when a comma lands in the notes.
pub const ENTITY_LOAD_BEARING: &str = "entity-load-bearing";

/// Delivery preparation on path-shaped sources: a file is a sequence of
/// **dated entries**. A unit begins at every line that opens with an ISO
/// date or date-time (`2026-08-24`, `2026-08-24 10:05`, `2026-08-24T10:05:00Z`,
/// after any leading markdown markers such as `## `, `- `, `> `, `[`); it
/// runs to the next such line. Text before the first entry folds into the
/// first unit; a file with no dated line is one unit keyed
/// [`WHOLE_FILE_UNIT`]. The unit key is the stamp normalized to
/// `YYYY-MM-DDTHH:MM:SS` (missing time parts read `00`), with `.2`, `.3`, …
/// appended to the second, third, … entry carrying the same stamp in one
/// file, in file order — so appending entries never renames an existing
/// unit. The order key is the normalized stamp; across a whole source, units
/// sort by stamp, then path, then key, which is what makes a chronological
/// corpus deliver in its own order regardless of how files were discovered.
/// Undated files (order key empty) come first, in path order. Fractional
/// seconds and zone designators are accepted and ignored for ordering.
pub const DATED_ENTRIES: &str = "dated-entries";

/// The key of the single unit a file yields when a delivery preparation finds
/// no unit boundary in it — the whole file, still addressable as
/// `<path>#whole`.
pub const WHOLE_FILE_UNIT: &str = "whole";

/// Code-map preparation on path-shaped sources (touchpoint A): a scoped
/// file's prepared form is its **interface digest** — imports, exports and
/// declarations with their signatures; comments, formatting and bodies are
/// invisible. The digest is heuristic and language-family aware by file
/// extension: C-like families (JS/TS, Rust, Go, Java, Kotlin, Swift, C#, C,
/// C++, PHP, Dart, Scala) keep top-level declaration lines and class or
/// object member signatures, cut at the body's opening brace; Python keeps
/// imports, `def`/`class` lines (top level and one level in), decorators and
/// upper-case module constants; a Vue single-file component is its script
/// block under the C-like rule; JSON is its canonical compact form; every
/// other file is taken whole. A `tree`-grain anchor under this preparation
/// hashes the digest of every scoped file under the tree (path and file
/// hash, path order), which is what closes the tree grain's
/// recorded-but-unhashed residue for code sources. Values inside
/// declarations (a config object's members, an array literal's contents
/// beyond its first line, a scalar property value) are body, not
/// interface: the digest sees names and signatures. A literal object
/// restructured between one line and many reads as a shape change.
pub const CODE_MAP: &str = "code-map";

/// Quoted-phrase preparation on the text-bearing grains (touchpoint A): the
/// artifact `<path-or-url-or-entity-id>#<phrase>` addresses **the occurrence
/// of a literal phrase** in a text, and its prepared form is the phrase
/// itself. While the text still carries the phrase (an exact substring
/// match after the minimal canonicalization of line endings), the anchor
/// resolves; when the words are gone the unit is absent and the anchor reads
/// `orphaned`, whatever else changed around it. A citation anchor, then: "this
/// document still says X", quiet under every rewrite that keeps the words
/// and loud the moment they leave. Applies to `span` (a file, read live),
/// `url` (observation-supplied content: the engine never fetches) and
/// `entity` (the live entity's canonical markdown). An artifact under this
/// preparation that names no `#<phrase>` keeps the grain's whole-text form.
pub const QUOTED_PHRASE: &str = "quoted-phrase";

/// The registry — every preparation this engine implements. The refusal in
/// [`crate::binding::validate_binding`] is exactly "not in this list".
pub const REGISTRY: &[Preparation] = &[
    Preparation {
        id: ENTITY_LOAD_BEARING,
        touchpoint: Touchpoint::PreparedForm,
        grains: &[AnchorGrain::Entity],
        description: "an entity's prepared form is the stable serialization of its type's \
                      load-bearing sections (explicitly declared, else the required sections, \
                      else every section) — notes-only edits keep dependents' anchors resolving",
    },
    Preparation {
        id: DATED_ENTRIES,
        touchpoint: Touchpoint::DeliveryUnits,
        grains: &[AnchorGrain::Span],
        description: "a file is a sequence of entries opening with an ISO date or date-time; \
                      each entry is one delivery unit `<path>#<stamp>`, and a source's units \
                      deliver in stamp order, identical on every pass — a chronological corpus \
                      (logs, transcripts, journals, mail threads) is never shuffled",
    },
    Preparation {
        id: CODE_MAP,
        touchpoint: Touchpoint::PreparedForm,
        grains: &[AnchorGrain::File, AnchorGrain::Span, AnchorGrain::Tree],
        description: "a scoped code file's prepared form is its interface digest (imports, \
                      exports, declarations and their signatures; comments, formatting and \
                      bodies invisible), and a tree's is the digest of every scoped file under \
                      it — an anchor drifts when an interface changes and stays quiet when \
                      only an implementation does",
    },
    Preparation {
        id: QUOTED_PHRASE,
        touchpoint: Touchpoint::PreparedForm,
        grains: &[AnchorGrain::Span, AnchorGrain::Url, AnchorGrain::Entity],
        description: "an artifact `<path-or-url-or-entity>#<phrase>` addresses the occurrence of \
                      a literal phrase in a text and its prepared form is the phrase itself — the \
                      anchor resolves while the file, the observed page or the entity still says \
                      those words and reads orphaned once they are gone, whatever else changed",
    },
];

/// Every registered preparation.
pub fn registry() -> &'static [Preparation] {
    REGISTRY
}

/// Look a declared identifier up.
pub fn lookup(id: &str) -> Option<&'static Preparation> {
    REGISTRY.iter().find(|p| p.id == id)
}

/// Whether `id` names a registered preparation.
pub fn is_registered(id: &str) -> bool {
    lookup(id).is_some()
}

/// The registered identifiers, in registry order — the recovery payload of
/// the unknown-identifier refusal.
pub fn registered_identifiers() -> Vec<&'static str> {
    REGISTRY.iter().map(|p| p.id).collect()
}

/// The delivery preparation a source declares, if its declared identifier
/// is a registered touchpoint-B entry — `None` for no declaration, an
/// unregistered identifier, or a prepared-form (touchpoint A) flavour.
pub fn delivery_preparation(declared: Option<&str>) -> Option<&'static Preparation> {
    lookup(declared?).filter(|p| p.touchpoint == Touchpoint::DeliveryUnits)
}

/// Whether a registered preparation can apply over a medium whose anchor
/// namespace is `anchor_namespace` (see
/// [`crate::binding::medium_capabilities`]): at least one of the
/// preparation's grains must be expressible there. `entity-load-bearing`
/// over a `codebase` source would never meet an entity-grain anchor, so it
/// is refused at declaration rather than silently never applying.
pub fn applies_to_namespace(preparation: &Preparation, anchor_namespace: &str) -> bool {
    preparation
        .grains
        .iter()
        .any(|g| g.supported_by_namespace(anchor_namespace))
}

// ---------------------------------------------------------------------------
// Per-grain prepared forms
// ---------------------------------------------------------------------------

/// The medium-declared default hash stability per grain. A `url` anchor
/// defaults to `unstable` — a served page is a moving target, so a hash
/// break resolves `recheck`, never `drifted`, unless the author asserts
/// `stable` explicitly. Every other grain keeps its `stable` default.
pub fn default_hash_stability(grain: AnchorGrain) -> AnchorHashStability {
    match grain {
        AnchorGrain::Url => AnchorHashStability::Unstable,
        AnchorGrain::Span | AnchorGrain::File | AnchorGrain::Tree | AnchorGrain::Entity => {
            AnchorHashStability::Stable
        }
    }
}

/// The `url` grain's canonicalization entry: the prepared form of a URL
/// artifact is the observation-supplied content under the same minimal
/// canonicalization the path grains use, so a `url` anchor's recorded hash
/// means the same thing a `file` anchor's does. The engine never fetches;
/// the observer supplies the bytes.
pub fn url_prepared_hash(content: &[u8]) -> String {
    prepared_content_hash(content)
}

/// The prepared-content hash of **supplied** content for a grain — the
/// write-time observation an agent performs when it hands the engine what it
/// read (`AnchorInput::content`). `None` for a grain whose prepared form
/// is never computed from supplied bytes: `entity` (computed from the live
/// graph, so a supplied rendering could disagree with the store) and `tree`
/// (its prepared form is a digest over the enumerated scoped files —
/// observation-side work no single supplied byte-string can represent).
pub fn supplied_content_hash(grain: AnchorGrain, content: &[u8]) -> Option<String> {
    match grain {
        AnchorGrain::Span | AnchorGrain::File => Some(prepared_content_hash(content)),
        AnchorGrain::Url => Some(url_prepared_hash(content)),
        AnchorGrain::Tree | AnchorGrain::Entity => None,
    }
}

// ---------------------------------------------------------------------------
// Touchpoint A for path grains: the prepared form of a file or tree
// ---------------------------------------------------------------------------

/// What a path-grain observation yields under a source's preparation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathPrepared {
    /// The prepared-content hash to record or compare.
    Hash(String),
    /// The grain has no prepared form at this single-artifact touchpoint (a
    /// `tree`, whose digest needs its files enumerated — the caller's job):
    /// observe no hash here, resolve `recheck` where no digest arrives.
    NoHash,
    /// The artifact addresses a sub-file unit the file no longer yields (a
    /// `<path>#<key>` span under a delivery preparation): an absent artifact.
    UnitAbsent,
}

/// The prepared-content hash of one path-grain artifact's bytes under
/// `preparation` — the one rule anchor observation and the write-time
/// `content` path share, so a hash recorded at write time is the hash a
/// later observation computes. No preparation (or one that does not prepare
/// path grains): the file's bytes under the minimal canonicalization for
/// `file`/`span`. [`DATED_ENTRIES`]: a `<path>#<key>`
/// span hashes its unit ([`PathPrepared::UnitAbsent`] when the key is gone),
/// a bare file its bytes. [`CODE_MAP`]: `file`/`span` hash the interface
/// digest. A `tree` needs its files enumerated, which is the caller's job
/// under every preparation ([`code_map_tree_digest`] /
/// [`plain_tree_digest`]), so it answers `NoHash` here.
pub fn path_prepared_hash(
    preparation: Option<&str>,
    artifact: &str,
    grain: AnchorGrain,
    bytes: &[u8],
) -> PathPrepared {
    let (path, locator) = split_unit_id(artifact);
    match (preparation, grain) {
        (Some(QUOTED_PHRASE), AnchorGrain::Span | AnchorGrain::Url) if locator.is_some() => {
            quoted_phrase_prepared(locator.unwrap_or_default(), &String::from_utf8_lossy(bytes))
        }
        (_, AnchorGrain::Url | AnchorGrain::Entity | AnchorGrain::Tree) => PathPrepared::NoHash,
        (Some(DATED_ENTRIES), AnchorGrain::Span) if locator.is_some() => {
            let text = String::from_utf8_lossy(bytes);
            match unitize(DATED_ENTRIES, &text)
                .and_then(|units| units.into_iter().find(|u| Some(u.key.as_str()) == locator))
            {
                Some(unit) => PathPrepared::Hash(unit.hash),
                None => PathPrepared::UnitAbsent,
            }
        }
        (Some(CODE_MAP), AnchorGrain::File | AnchorGrain::Span) => {
            let text = String::from_utf8_lossy(bytes);
            PathPrepared::Hash(prepared_content_hash(
                code_map_digest(path, &text).as_bytes(),
            ))
        }
        (_, AnchorGrain::File | AnchorGrain::Span) => {
            PathPrepared::Hash(prepared_content_hash(bytes))
        }
    }
}

/// Touchpoint A under [`QUOTED_PHRASE`]: the prepared form of `text` for the
/// artifact `…#<phrase>`. The phrase is matched as an exact substring after
/// the minimal canonicalization the path grains share (a BOM and `\r\n`
/// line endings never decide a citation); present, the prepared form is the
/// phrase and the hash is stable for as long as the words stand; absent, the
/// unit is gone ([`PathPrepared::UnitAbsent`]) and the anchor reads
/// `orphaned`. An empty phrase addresses nothing and is absent by
/// definition, so a `#` with nothing after it can never resolve clean.
pub fn quoted_phrase_prepared(phrase: &str, text: &str) -> PathPrepared {
    let phrase = phrase.trim();
    if phrase.is_empty() {
        return PathPrepared::UnitAbsent;
    }
    let canonical_text = canonical_text(text);
    let canonical_phrase = canonical_text_owned(phrase);
    if canonical_text.contains(canonical_phrase.as_str()) {
        PathPrepared::Hash(prepared_content_hash(canonical_phrase.as_bytes()))
    } else {
        PathPrepared::UnitAbsent
    }
}

/// The text a phrase is matched against: BOM stripped, `\r\n` folded to
/// `\n` — the same two normalizations `prepared_content_hash` applies, so a
/// phrase that resolves on one platform resolves on every other.
fn canonical_text(text: &str) -> String {
    canonical_text_owned(text)
}

fn canonical_text_owned(text: &str) -> String {
    text.strip_prefix('\u{feff}')
        .unwrap_or(text)
        .replace("\r\n", "\n")
}

// ---------------------------------------------------------------------------
// Quoted spans: the canonical form a span is checked and hashed in
// ---------------------------------------------------------------------------

/// The **canonical span form**: the one text form a quoted span
/// ([`crate::anchor::Anchor::span`]) is compared in, at write (is the span in
/// the supplied `content`?), at observation (is it still in the observed
/// text?) and when hashed ([`span_hash`]). One function serves all three
/// sites, so a span that passed the write check is the span the observation
/// looks for.
///
/// It removes exactly the noise two extractions of one document disagree on,
/// and nothing else:
///
/// - Unicode NFC composition (a decomposed umlaut matches a composed one);
/// - a soft hyphen (U+00AD) is removed;
/// - typographic quotes (`‘ ’ ‚ ‛ “ ” „ ‟ ‹ › « »`) become their ASCII forms
///   (`'` and `"`), and typographic dashes (U+2010 to U+2015, U+2212) become
///   `-`;
/// - the ligatures ff fi fl ffi ffl ſt st resolve to their letter pairs;
/// - a hyphen directly followed by a line break is removed, together with
///   the break and the indentation after it, so a word split at a line end
///   matches its unsplit form;
/// - every run of whitespace (spaces, tabs, line breaks, non-breaking
///   spaces) becomes one space, a space directly after an opening bracket
///   or before a closing one (`(`, `[`, `{` and their closers) is removed,
///   and the ends are trimmed.
///
/// Digits, decimal marks, units, case and word order are untouched: beyond
/// this form the match is exact, and no similarity threshold exists on any
/// path. Case folding is deliberately absent (capitalisation carries meaning
/// in the sources' languages) and so is NFKC (it would equate `m²` with
/// `m2`, a changed unit).
///
/// The form is a function of its text alone, so the span's hash
/// ([`span_hash`]) is one value wherever the span is quoted. The line-end
/// hyphen is the one fold that loses a distinction (`statement-\nlevel`
/// may be a split `statementlevel` or a compound `statement-level`), and
/// the text side of a comparison answers it: [`span_occurs`] looks for
/// the span in the joined form and in the form that keeps the hyphen
/// ([`canonical_text_forms`]), so both readings are found and no rule
/// has to guess from the rest of the document.
pub fn canonical_span_form(text: &str) -> String {
    canonical_form(text, LineEndHyphen::Join)
}

/// The two canonical forms of an observed TEXT a span is looked for in:
/// the joined form ([`canonical_span_form`], a hyphen at a line end is a
/// split word) and the form that keeps the hyphen (a compound word broken
/// at the line end: `statement-\nlevel` reads `statement-level`). The
/// second is omitted when it equals the first (no hyphen sat at a line
/// end), so a text without the ambiguity costs one form.
pub fn canonical_text_forms(text: &str) -> Vec<String> {
    let joined = canonical_form(text, LineEndHyphen::Join);
    let kept = canonical_form(text, LineEndHyphen::Keep);
    if kept == joined {
        vec![joined]
    } else {
        vec![joined, kept]
    }
}

/// What a hyphen directly before a line break becomes in a canonical form.
#[derive(Clone, Copy, PartialEq, Eq)]
enum LineEndHyphen {
    /// The hyphen, the break and the indentation go: a split word rejoins.
    Join,
    /// The hyphen stays, the break and the indentation go: a compound word
    /// broken at the line end keeps its hyphen, with nothing around it.
    Keep,
}

fn canonical_form(text: &str, line_end_hyphen: LineEndHyphen) -> String {
    use unicode_normalization::UnicodeNormalization;
    let composed: String = text.nfc().collect();
    let mut mapped = String::with_capacity(composed.len());
    for c in composed.chars() {
        match c {
            '\u{00AD}' => {}
            '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' | '\u{2039}' | '\u{203A}' => {
                mapped.push('\'');
            }
            '\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' | '\u{00AB}' | '\u{00BB}' => {
                mapped.push('"');
            }
            '\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2014}' | '\u{2015}'
            | '\u{2212}' => mapped.push('-'),
            '\u{FB00}' => mapped.push_str("ff"),
            '\u{FB01}' => mapped.push_str("fi"),
            '\u{FB02}' => mapped.push_str("fl"),
            '\u{FB03}' => mapped.push_str("ffi"),
            '\u{FB04}' => mapped.push_str("ffl"),
            '\u{FB05}' | '\u{FB06}' => mapped.push_str("st"),
            other => mapped.push(other),
        }
    }
    // A hyphen at a line end: the break and any indentation that follows
    // go, and the hyphen goes with them (a split word rejoins) or stays (a
    // compound word keeps its hyphen), as the caller asked.
    let mut joined = String::with_capacity(mapped.len());
    let mut chars = mapped.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '-' {
            let mut ahead = chars.clone();
            let mut consumed = 0usize;
            if ahead.peek() == Some(&'\r') {
                ahead.next();
                consumed += 1;
            }
            if ahead.peek() == Some(&'\n') {
                ahead.next();
                consumed += 1;
                while matches!(ahead.peek(), Some(' ') | Some('\t')) {
                    ahead.next();
                    consumed += 1;
                }
                for _ in 0..consumed {
                    chars.next();
                }
                if line_end_hyphen == LineEndHyphen::Keep {
                    joined.push('-');
                }
                continue;
            }
        }
        joined.push(c);
    }
    // Whitespace runs become one space, except directly inside a bracket
    // pair, where typesetting puts a space the words never had.
    let mut out = String::with_capacity(joined.len());
    let mut pending_space = false;
    for c in joined.chars() {
        if c.is_whitespace() {
            pending_space = !out.is_empty();
        } else {
            if pending_space {
                let after_opener = out.ends_with(['(', '[', '{']);
                let before_closer = matches!(c, ')' | ']' | '}');
                if !after_opener && !before_closer {
                    out.push(' ');
                }
                pending_space = false;
            }
            out.push(c);
        }
    }
    out
}

/// Whether `span` occurs in `text`: the span in the canonical span form,
/// the text in each of its canonical forms ([`canonical_text_forms`]), so
/// a span quoting a compound word the text breaks at a line end
/// (`statement-level` against `statement-\nlevel`) is found as surely as
/// a split word (`generated` against `gener-\nated`). An empty span (empty
/// after canonicalisation) occurs nowhere: it names no words, and the
/// write path refuses it before it can be stored.
pub fn span_occurs(span: &str, text: &str) -> bool {
    let span = canonical_span_form(span);
    if span.is_empty() {
        return false;
    }
    canonical_text_forms(text)
        .iter()
        .any(|form| form.contains(span.as_str()))
}

/// The hash a span row records for its span: the house prepared-content
/// hash over the canonical span form, so two writers quoting the same words
/// with different quote marks or line breaks record the same value.
pub fn span_hash(span: &str) -> String {
    prepared_content_hash(canonical_span_form(span).as_bytes())
}

/// The code map of a tree: one line per scoped file under it, `<file digest
/// hash>  <path>`, in path order — hashed by the caller through
/// [`prepared_content_hash`]. A file joining, leaving, or changing its
/// interface changes the tree's map; an implementation edit does not.
pub fn code_map_tree_digest(files: &[(String, String)]) -> String {
    let mut rows: Vec<(&str, &str)> = files
        .iter()
        .map(|(path, text)| (path.as_str(), text.as_str()))
        .collect();
    rows.sort();
    rows.iter()
        .map(|(path, text)| {
            format!(
                "{}  {path}",
                prepared_content_hash(code_map_digest(path, text).as_bytes())
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// The plain digest of a tree: one line per scoped file under it,
/// `<prepared-content hash>  <path>`, in path order — hashed by the caller
/// through [`prepared_content_hash`]. Any byte change in any scoped file,
/// and any file joining or leaving the tree, changes the digest — the same
/// whole-content posture a `file` anchor has, lifted to the directory. This
/// is the no-preparation counterpart of [`code_map_tree_digest`]; it is what
/// lets a plain `tree` anchor adjudicate deterministically instead of
/// resting in `recheck` forever.
pub fn plain_tree_digest(files: &[(String, Vec<u8>)]) -> String {
    let mut rows: Vec<(&str, &[u8])> = files
        .iter()
        .map(|(path, bytes)| (path.as_str(), bytes.as_slice()))
        .collect();
    rows.sort();
    rows.iter()
        .map(|(path, bytes)| format!("{}  {path}", prepared_content_hash(bytes)))
        .collect::<Vec<_>>()
        .join("\n")
}

/// The interface digest of one file's text under [`CODE_MAP`].
pub fn code_map_digest(path: &str, text: &str) -> String {
    match family_of(path) {
        Family::Text => text.to_string(),
        Family::Json => serde_json::from_str::<serde_json::Value>(text)
            .map(|v| v.to_string())
            .unwrap_or_else(|_| text.to_string()),
        Family::Vue => {
            declaration_lines(&strip_c_comments(&vue_script_blocks(text)), Family::CLike)
        }
        Family::CLike => declaration_lines(&strip_c_comments(text), Family::CLike),
        Family::Rust => declaration_lines(&strip_c_comments(text), Family::Rust),
        Family::Python => declaration_lines(&strip_python_comments(text), Family::Python),
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Family {
    CLike,
    /// C-like braces, but a struct field is interface only with `pub`
    /// (a `key: Type` line without it is body), and enum variants are.
    Rust,
    Python,
    Json,
    Vue,
    Text,
}

fn family_of(path: &str) -> Family {
    let name = path.rsplit('/').next().unwrap_or(path);
    let ext = match name.rsplit_once('.') {
        Some((_, ext)) => ext.to_ascii_lowercase(),
        None => return Family::Text,
    };
    match ext.as_str() {
        "rs" => Family::Rust,
        "js" | "mjs" | "cjs" | "jsx" | "ts" | "tsx" | "mts" | "cts" | "go" | "java" | "kt"
        | "kts" | "swift" | "cs" | "c" | "h" | "cc" | "cpp" | "hpp" | "m" | "mm" | "php"
        | "dart" | "scala" => Family::CLike,
        "py" | "pyi" => Family::Python,
        "json" => Family::Json,
        "vue" | "svelte" => Family::Vue,
        _ => Family::Text,
    }
}

/// The concatenated `<script>` blocks of a single-file component (the
/// template and styles are not interface).
fn vue_script_blocks(text: &str) -> String {
    let lower = text.to_ascii_lowercase();
    let mut out = String::new();
    let mut from = 0;
    while let Some(open) = lower[from..].find("<script") {
        let open = from + open;
        let Some(tag_end) = lower[open..].find('>') else {
            break;
        };
        let body_start = open + tag_end + 1;
        let Some(close) = lower[body_start..].find("</script") else {
            out.push_str(&text[body_start..]);
            break;
        };
        out.push_str(&text[body_start..body_start + close]);
        out.push('\n');
        from = body_start + close + 8;
    }
    out
}

/// Strip `//` line comments and `/* */` block comments, outside string
/// literals (a `'`/`"` string ends at its line; a template literal may span
/// lines). Newlines are kept so line structure survives.
fn strip_c_comments(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    let mut in_str: Option<char> = None;
    let mut escape = false;
    while let Some(c) = chars.next() {
        if let Some(q) = in_str {
            out.push(c);
            if escape {
                escape = false;
            } else if c == '\\' {
                escape = true;
            } else if c == q || (c == '\n' && q != '`') {
                in_str = None;
            }
            continue;
        }
        match c {
            '"' | '\'' | '`' => {
                in_str = Some(c);
                out.push(c);
            }
            '/' => match chars.peek() {
                Some('/') => {
                    for n in chars.by_ref() {
                        if n == '\n' {
                            out.push('\n');
                            break;
                        }
                    }
                }
                Some('*') => {
                    chars.next();
                    let mut prev = '\0';
                    for n in chars.by_ref() {
                        if n == '\n' {
                            out.push('\n');
                        }
                        if prev == '*' && n == '/' {
                            break;
                        }
                        prev = n;
                    }
                }
                _ => out.push(c),
            },
            _ => out.push(c),
        }
    }
    out
}

/// Strip `#` comments outside strings and drop triple-quoted strings whole
/// (docstrings and block literals are never interface).
fn strip_python_comments(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let bytes: Vec<char> = text.chars().collect();
    let mut i = 0;
    let mut in_str: Option<char> = None;
    let mut triple: Option<char> = None;
    while i < bytes.len() {
        let c = bytes[i];
        if let Some(q) = triple {
            if c == q && i + 2 < bytes.len() && bytes[i + 1] == q && bytes[i + 2] == q {
                triple = None;
                i += 3;
                continue;
            }
            if c == '\n' {
                out.push('\n');
            }
            i += 1;
            continue;
        }
        if let Some(q) = in_str {
            out.push(c);
            if c == '\\' && i + 1 < bytes.len() {
                out.push(bytes[i + 1]);
                i += 2;
                continue;
            }
            if c == q || c == '\n' {
                in_str = None;
            }
            i += 1;
            continue;
        }
        match c {
            '"' | '\'' => {
                if i + 2 < bytes.len() && bytes[i + 1] == c && bytes[i + 2] == c {
                    triple = Some(c);
                    i += 3;
                    continue;
                }
                in_str = Some(c);
                out.push(c);
            }
            '#' => {
                while i < bytes.len() && bytes[i] != '\n' {
                    i += 1;
                }
                continue;
            }
            _ => out.push(c),
        }
        i += 1;
    }
    out
}

const C_LIKE_TOP_LEVEL: &[&str] = &[
    "import ",
    "export ",
    "module.exports",
    "exports.",
    "function ",
    "async function ",
    "class ",
    "interface ",
    "type ",
    "enum ",
    "declare ",
    "const ",
    "let ",
    "var ",
    "pub ",
    "fn ",
    "struct ",
    "trait ",
    "impl ",
    "impl<",
    "mod ",
    "use ",
    "static ",
    "macro_rules!",
    "package ",
    "func ",
    "namespace ",
    "using ",
    "#include",
    "#[",
    "@",
    "public ",
    "private ",
    "protected ",
    "abstract ",
    "final ",
    "override ",
    "typedef ",
    "extern ",
    "template",
    "def ",
];

const C_LIKE_MEMBER: &[&str] = &[
    "pub ",
    "fn ",
    "public ",
    "private ",
    "protected ",
    "static ",
    "abstract ",
    "override ",
    "readonly ",
    "async ",
    "get ",
    "set ",
    "constructor",
    "#[",
    "@",
];

/// A member signature: an optionally qualified identifier followed by a
/// parameter list.
fn method_re() -> &'static regex::Regex {
    static METHOD: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    METHOD.get_or_init(|| {
        regex::Regex::new(r"^(?:(?:async|static|get|set|public|private|protected|override)\s+)*[A-Za-z_$][\w$]*\s*(?:<[^>]*>)?\s*\(").unwrap()
    })
}

/// A property member (`key: …`, an optional `readonly`/`?`), whatever its
/// value: an object literal's member, an interface member's type, a bare
/// key a formatter broke away from its value. Scalar values are cut later.
fn property_re() -> &'static regex::Regex {
    static PROPERTY: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    PROPERTY.get_or_init(|| {
        regex::Regex::new(r#"^(?:readonly\s+)?(?:['"]?)[A-Za-z_$][\w$]*(?:['"]?)\??\s*:"#).unwrap()
    })
}

/// An interface's method member: a signature carrying a return type and no
/// body (`load(id: string): Promise<void>`, an optional `?` after the name,
/// a trailing `;`). A ternary statement (`f(a) ? b : c`) is not one: its
/// `?` is followed by a space, a member's never is.
fn typed_member_re() -> &'static regex::Regex {
    static TYPED_MEMBER: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    TYPED_MEMBER.get_or_init(|| {
        regex::Regex::new(
            r"^(?:readonly\s+)?[A-Za-z_$][\w$]*\??\s*(?:<[^>]*>)?\s*\(.*\)\s*:\s*[^{;]+[;,]?$",
        )
        .unwrap()
    })
}

fn typed_member(line: &str) -> bool {
    typed_member_re().is_match(line) && !line.contains("? ")
}

/// An enum member (`Blue`, `Blue = 2,`): a capitalized bare identifier line.
fn enum_member_re() -> &'static regex::Regex {
    static ENUM_MEMBER: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    ENUM_MEMBER
        .get_or_init(|| regex::Regex::new(r"^[A-Z][A-Za-z0-9_]*(?:\s*=\s*[^,]+)?,?$").unwrap())
}

/// Whether a kept depth-1 or depth-2 line was kept ONLY as a member
/// signature (not by a keyword prefix, not as a property): such a line must
/// open a body once joined, or it was a wrapped call statement, not a
/// signature.
fn member_signature_only(line: &str, depth: i32) -> bool {
    depth >= 1
        && !C_LIKE_MEMBER.iter().any(|p| line.starts_with(p))
        && !property_re().is_match(line)
        && !typed_member(line)
        && method_re().is_match(line)
}

fn c_like_keeps(line: &str, depth: i32, next_opens_body: bool, properties: bool) -> bool {
    let method = method_re();
    let property = property_re();
    // A member signature opens a body (`{`, on this line or, Allman-style,
    // on the next), or is wrapped across lines (ends with `(` or `,`); a
    // finished call statement ends with `)` and is followed by anything else.
    let signature_shaped = |line: &str| {
        method.is_match(line)
            && !line.starts_with("if ")
            && !line.starts_with("for ")
            && !line.starts_with("while ")
            && !line.starts_with("switch ")
            && !line.starts_with("return ")
            && !line.starts_with("catch ")
            && (line.ends_with('{')
                || line.ends_with('(')
                || line.ends_with(',')
                || (line.ends_with(')') && next_opens_body))
    };
    match depth {
        0 => C_LIKE_TOP_LEVEL.iter().any(|p| line.starts_with(p)),
        1 => {
            C_LIKE_MEMBER.iter().any(|p| line.starts_with(p))
                || signature_shaped(line)
                || (properties && (property.is_match(line) || typed_member(line)))
                || enum_member_re().is_match(line)
        }
        2 => signature_shaped(line),
        _ => false,
    }
}

fn python_keeps(line: &str, indent: usize) -> bool {
    static CONSTANT: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    let constant = CONSTANT
        .get_or_init(|| regex::Regex::new(r"^(?:[A-Z_][A-Z0-9_]*|__all__)\s*[:=]").unwrap());
    let decl = line.starts_with("def ")
        || line.starts_with("async def ")
        || line.starts_with("class ")
        || line.starts_with('@');
    if indent == 0 {
        decl || line.starts_with("import ") || line.starts_with("from ") || constant.is_match(line)
    } else {
        indent <= 4 && decl
    }
}

/// For a Python module constant (`NAME = value`, `NAME: type = value`), the
/// byte index just past the `=`; `None` for any other line.
fn python_constant_cut(line: &str) -> Option<usize> {
    static CONSTANT: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    let constant = CONSTANT.get_or_init(|| {
        regex::Regex::new(r"^(?:[A-Z_][A-Z0-9_]*|__all__)(?:\s*:\s*[^=]+?)?\s*=").unwrap()
    });
    constant.find(line).map(|m| m.end())
}

fn paren_balance(s: &str) -> i32 {
    s.chars()
        .map(|c| match c {
            '(' => 1,
            ')' => -1,
            _ => 0,
        })
        .sum()
}

fn brace_delta(s: &str) -> i32 {
    s.chars()
        .map(|c| match c {
            '{' => 1,
            '}' => -1,
            _ => 0,
        })
        .sum()
}

/// Cut a declaration at its body: the first `{` outside parentheses for a
/// C-like line (an import, `use`, or re-export list is not a body and is
/// kept whole), the trailing `:` for Python.
fn cut_at_body(sig: &str, family: Family) -> String {
    match family {
        Family::Python => sig.trim_end_matches(':').trim_end().to_string(),
        _ if sig.starts_with("import ")
            || sig.starts_with("use ")
            || sig.starts_with("export {")
            || sig.starts_with("export type {")
            || sig.starts_with("export * ") =>
        {
            sig.trim_end().to_string()
        }
        _ => {
            // The body opens at the first `{` outside parentheses, or, for
            // an arrow whose body is an expression, right after the `=>`:
            // an expression body is body whatever line it wraps onto.
            let mut depth = 0i32;
            let mut cut = sig.len();
            let bytes = sig.as_bytes();
            for (i, c) in sig.char_indices() {
                match c {
                    '(' | '[' => depth += 1,
                    ')' | ']' => depth -= 1,
                    '{' if depth <= 0 => {
                        cut = i;
                        break;
                    }
                    '=' if depth <= 0 && bytes.get(i + 1) == Some(&b'>') => {
                        let rest = sig[i + 2..].trim_start();
                        if !rest.starts_with('{') {
                            cut = i + 2;
                            break;
                        }
                    }
                    _ => {}
                }
            }
            sig[..cut].trim_end().to_string()
        }
    }
}

/// Normalize a kept declaration so that formatting inside it is invisible:
/// trailing semicolons dropped, double quotes read as single quotes, runs of
/// whitespace collapsed, and no whitespace next to punctuation — so
/// `f(a,b)`, `f(a, b)` and a signature wrapped across lines digest alike,
/// while every token that carries meaning survives.
fn normalize_signature(sig: &str) -> String {
    let collapsed: Vec<&str> = sig
        .trim()
        .trim_end_matches(';')
        .split_whitespace()
        .collect();
    let joined = collapsed.join(" ").replace('"', "'");
    let is_punct = |c: char| "()[]{},;:=<>|&?!-+*/.".contains(c);
    let mut out = String::with_capacity(joined.len());
    let chars: Vec<char> = joined.chars().collect();
    for (i, &c) in chars.iter().enumerate() {
        if c == ' ' {
            let before = chars[..i].iter().rev().find(|x| **x != ' ').copied();
            let after = chars[i + 1..].iter().find(|x| **x != ' ').copied();
            if before.is_some_and(is_punct) || after.is_some_and(is_punct) {
                continue;
            }
        }
        out.push(c);
    }
    // Trailing commas are a formatter's choice, never a signature's: drop
    // one before a closing bracket and at the end of the line.
    let out = out
        .replace(",)", ")")
        .replace(",]", "]")
        .replace(",}", "}")
        .replace(",>", ">");
    let out = out.trim_end_matches(',').to_string();
    // A union type wrapped by a formatter leads its first member with `|`.
    let out = out.replace("=|", "=");
    // A kept line that opens a body keeps nothing of the brace itself.
    let out = out.trim_end_matches('{').trim_end().to_string();
    // Formatter defaults that are not signatures: a quoted property key
    // reads as the bare key; `(x)=>` reads as `x=>`; a Python import list's
    // parentheses (black's wrapped form) vanish.
    static QUOTED_KEY: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    static ARROW_PARENS: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    let quoted_key =
        QUOTED_KEY.get_or_init(|| regex::Regex::new(r"^'([A-Za-z_$][\w$]*)':").unwrap());
    let arrow_parens =
        ARROW_PARENS.get_or_init(|| regex::Regex::new(r"\(([A-Za-z_$][\w$]*)\)=>").unwrap());
    let out = quoted_key.replace(&out, "$1:").into_owned();
    let out = arrow_parens.replace_all(&out, "$1=>").into_owned();
    // A scalar property value (`name: 'Auth'`, `port: 3000`) is body, exactly
    // as a one-line literal's members are: keep the key alone.
    static SCALAR_PROPERTY: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    let scalar = SCALAR_PROPERTY
        .get_or_init(|| regex::Regex::new(r#"^([A-Za-z_$][\w$]*:)(?:'|`|-?\d)"#).unwrap());
    let out = match scalar.captures(&out) {
        Some(caps) => caps[1].to_string(),
        None => out,
    };
    if out.starts_with("from ") || out.starts_with("import ") {
        return out
            .replace('(', " ")
            .replace(')', "")
            .split_whitespace()
            .collect::<Vec<_>>()
            .join(" ");
    }
    out
}

/// A top-level binding whose value is not a function is cut right after its
/// `=` (and a default export that is not a function or object literal right
/// after `default`): the value is body, so its wrapping, its operators and
/// its literal shape never reach the digest. A function-valued binding keeps
/// its signature. `None` when the line is not such a binding.
fn cut_value_binding(line: &str) -> Option<String> {
    static BINDING: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    static DEFAULT: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    let binding = BINDING.get_or_init(|| {
        regex::Regex::new(
            r"^((?:(?:export\s+)?(?:pub(?:\([^)]*\))?\s+)?(?:(?:static|readonly|private|public|protected|declare|override|const|let|var)\s+)*(?:[A-Za-z_$][\w$]*|\{[^}]*\}|\[[^\]]*\])(?:\s*:\s*[^=]+?)?|(?:module\.)?exports(?:\.[A-Za-z_$][\w$]*)?)\s*=)\s*(.*)$",
        )
        .unwrap()
    });
    let default =
        DEFAULT.get_or_init(|| regex::Regex::new(r"^(export\s+default)\s+(.*)$").unwrap());
    let function_like = |value: &str| {
        static ARROW: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
        let arrow = ARROW
            .get_or_init(|| regex::Regex::new(r"^(?:async\s+)?[A-Za-z_$][\w$]*\s*=>").unwrap());
        value.starts_with('(')
            || value.starts_with("async ")
            || value.starts_with("async(")
            || value.starts_with("function")
            || value.starts_with("class")
            || arrow.is_match(value)
    };
    if let Some(caps) = binding.captures(line) {
        let value = caps[2].trim();
        // The `=` of an arrow `=>` (a property whose type annotation the
        // regex read as `key: (params)`) is not an assignment.
        if value.starts_with('>') {
            return None;
        }
        // A module's object-literal export (`module.exports = {`) is an
        // interface container like `export default {`: its members stay.
        let module_export = caps[1].starts_with("exports") || caps[1].starts_with("module.exports");
        // An empty value means a formatter broke it onto the next line:
        // still a value, still body (the caller skips that line).
        if function_like(value) || (module_export && value.starts_with('{')) {
            return None;
        }
        return Some(caps[1].to_string());
    }
    if let Some(caps) = default.captures(line) {
        let value = caps[2].trim();
        if value.is_empty() || value.starts_with('{') || function_like(value) {
            return None;
        }
        return Some(caps[1].to_string());
    }
    None
}

fn angle_balance(s: &str) -> i32 {
    // Generics only: `->` and `=>` carry a `>` that is not a bracket.
    let s = s.replace("->", " ").replace("=>", " ");
    s.chars()
        .map(|c| match c {
            '<' => 1,
            '>' => -1,
            _ => 0,
        })
        .sum::<i32>()
        .max(0)
}

fn bracket_balance(s: &str) -> i32 {
    s.chars()
        .map(|c| match c {
            '[' => 1,
            ']' => -1,
            _ => 0,
        })
        .sum()
}

/// A binding whose destructuring pattern a formatter wrapped: the pattern
/// opens on the binding line (`const {`, `let [`) and closes on a later one.
fn opens_destructure(line: &str) -> bool {
    static DESTRUCTURE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    let re = DESTRUCTURE
        .get_or_init(|| regex::Regex::new(r"^(?:export\s+)?(?:const|let|var)\s+[\{\[]").unwrap());
    re.is_match(line) && brace_delta(line) + bracket_balance(line) > 0
}

/// An import, `use`, or re-export list wraps across lines on its braces;
/// nothing else joins on a brace (a brace elsewhere opens a body).
fn is_list_declaration(sig: &str) -> bool {
    sig.starts_with("import ")
        || sig.starts_with("use ")
        || sig.starts_with("export {")
        || sig.starts_with("export type {")
}

fn declaration_lines(stripped: &str, family: Family) -> String {
    let lines: Vec<&str> = stripped.lines().collect();
    let mut out: Vec<String> = Vec::new();
    let mut depth: i32 = 0;
    // After a binding whose value was cut as body, the value's own lines
    // are skipped whole until every bracket the value opened has closed:
    // (brace, bracket, paren) balances accumulated from the binding line.
    let mut body_skip: Option<(i32, i32, i32)> = None;
    let mut i = 0;
    while i < lines.len() {
        let raw = lines[i];
        let line = raw.trim();
        if line.is_empty() {
            i += 1;
            continue;
        }
        if let Some((braces, brackets, parens)) = body_skip {
            let braces = braces + brace_delta(raw);
            let brackets = brackets + bracket_balance(raw);
            let parens = parens + paren_balance(raw);
            depth += brace_delta(raw);
            body_skip = if braces <= 0 && brackets <= 0 && parens <= 0 {
                None
            } else {
                Some((braces, brackets, parens))
            };
            i += 1;
            continue;
        }
        let indent = raw.len() - raw.trim_start().len();
        let next_opens_body = lines[i + 1..]
            .iter()
            .map(|l| l.trim())
            .find(|l| !l.is_empty())
            .is_some_and(|l| l.starts_with('{'));
        let keep = match family {
            Family::Python => python_keeps(line, indent),
            _ => c_like_keeps(line, depth, next_opens_body, family != Family::Rust),
        };
        if keep
            && family == Family::Python
            && indent == 0
            && let Some(eq) = python_constant_cut(line)
        {
            // A module constant's value is body, as a JS binding's is.
            out.push(normalize_signature(&line[..eq]));
            i += 1;
            continue;
        }
        // A destructuring pattern a formatter wrapped (`const {\n  a,\n  b,\n} = …`)
        // joins across its brackets before the binding rule sees it, so the
        // names inside are interface in the wrapped form as in the one-line form.
        let mut binding_end = i;
        let destructured = if keep && family != Family::Python && opens_destructure(line) {
            let mut joined = line.to_string();
            while brace_delta(&joined) + bracket_balance(&joined) > 0
                && binding_end + 1 < lines.len()
                && binding_end - i < 60
            {
                binding_end += 1;
                if lines[binding_end].trim().is_empty() {
                    continue;
                }
                joined.push(' ');
                joined.push_str(lines[binding_end].trim());
            }
            Some(joined)
        } else {
            None
        };
        let binding_line = destructured.as_deref().unwrap_or(line);
        if keep
            && family != Family::Python
            && !(depth >= 1 && enum_member_re().is_match(line))
            && let Some(cut) = cut_value_binding(binding_line)
        {
            // (An enum member's explicit value is interface, not a binding's
            // body: `Green = 2,` keeps its value.)
            // The value is body: keep the binding's name, count its braces,
            // and skip the value's lines until every bracket it opened closes.
            out.push(normalize_signature(&cut));
            let span = &lines[i..=binding_end];
            let mut opened = (
                span.iter().map(|l| brace_delta(l)).sum::<i32>(),
                span.iter().map(|l| bracket_balance(l)).sum::<i32>(),
                span.iter().map(|l| paren_balance(l)).sum::<i32>(),
            );
            depth += opened.0;
            i = binding_end + 1;
            if binding_line.trim_end().ends_with('=') {
                // The value starts on the next non-empty line: consume it
                // and whatever it opens.
                while i < lines.len() && lines[i].trim().is_empty() {
                    i += 1;
                }
                if i < lines.len() {
                    let v = lines[i];
                    opened = (
                        opened.0 + brace_delta(v),
                        opened.1 + bracket_balance(v),
                        opened.2 + paren_balance(v),
                    );
                    depth += brace_delta(v);
                    i += 1;
                }
            }
            if opened.0 > 0 || opened.1 > 0 || opened.2 > 0 {
                body_skip = Some(opened);
            }
            continue;
        }
        if keep {
            // A signature wrapped across lines joins on its parentheses, a
            // wrapped array literal on its brackets, a wrapped import or
            // export list on its braces — so a formatter's line width is
            // invisible and a member added inside a wrapped list is not.
            let mut sig = line.to_string();
            let mut j = i;
            let c_like = family != Family::Python;
            // Continuation: an open bracket of any kind, or (C-like) a next
            // line a formatter led with an operator (`|` in a union type,
            // `.` in a chain, `?`/`:` in a ternary, `&&`/`||`/`+`).
            let next_is_operator_led = |k: usize| {
                c_like
                    && lines[k + 1..]
                        .iter()
                        .map(|l| l.trim())
                        .find(|l| !l.is_empty())
                        .is_some_and(|l| {
                            l.starts_with('|')
                                || l.starts_with('&')
                                || l.starts_with('?')
                                || l.starts_with(':')
                                || l.starts_with('.')
                                || l.starts_with('+')
                        })
            };
            // A line that ends by opening a body (`{`) joins nothing: what
            // follows is body, even inside a callback argument's parentheses.
            // An import or export list's brace opens a list, not a body.
            // A line that ends in `=` or `:` (a formatter broke the value or
            // the type onto the next line) joins its continuation.
            let ends_open = |s: &str| {
                let t = s.trim_end();
                c_like && (t.ends_with('=') || t.ends_with(':'))
            };
            while (!sig.trim_end().ends_with('{') || is_list_declaration(&sig))
                && (paren_balance(&sig) > 0
                    || bracket_balance(&sig) > 0
                    || (c_like && angle_balance(&sig) > 0)
                    || (is_list_declaration(&sig) && brace_delta(&sig) > 0)
                    || ends_open(&sig)
                    || next_is_operator_led(j))
                && j + 1 < lines.len()
                && j - i < 60
            {
                j += 1;
                if lines[j].trim().is_empty() {
                    continue;
                }
                sig.push(' ');
                sig.push_str(lines[j].trim());
            }
            // A line kept only as a member signature must open a body once
            // joined; a wrapped call statement joins to `name(args)` with no
            // body after it and is dropped, as its one-line form would be.
            // Judged on the joined signature: a typed member a formatter
            // wrapped (`load(\n  id: string,\n): Promise<void>`) is typed.
            let opens_body = sig.trim_end().ends_with('{')
                || sig.contains("=>")
                || lines[j + 1..]
                    .iter()
                    .map(|l| l.trim())
                    .find(|l| !l.is_empty())
                    .is_some_and(|l| l.starts_with('{'));
            if c_like && member_signature_only(&sig, depth) && !opens_body {
                for l in &lines[i..=j] {
                    depth += brace_delta(l);
                }
                i = j + 1;
                continue;
            }
            out.push(normalize_signature(&cut_at_body(&sig, family)));
            if c_like {
                for l in &lines[i..=j] {
                    depth += brace_delta(l);
                }
            }
            i = j + 1;
        } else {
            if family != Family::Python {
                depth += brace_delta(raw);
            }
            i += 1;
        }
    }
    out.join("\n")
}

/// The load-bearing sections of a type, in the type's declared order:
///
/// 1. the sections declaring `load_bearing: true`, when any does;
/// 2. otherwise the required sections, minus any declaring
///    `load_bearing: false`, when that leaves at least one;
/// 3. otherwise every section — a type with no required sections and no
///    declaration has no notes/claim split the engine can honour, and an
///    empty set would hash to a constant that never drifts.
pub fn load_bearing_sections(
    type_def: &memstead_schema::types::TypeDefinition,
) -> Vec<&memstead_schema::types::SectionDef> {
    let explicit: Vec<_> = type_def
        .sections
        .iter()
        .filter(|s| s.load_bearing == Some(true))
        .collect();
    if !explicit.is_empty() {
        return explicit;
    }
    let required: Vec<_> = type_def
        .sections
        .iter()
        .filter(|s| s.required && s.load_bearing != Some(false))
        .collect();
    if !required.is_empty() {
        return required;
    }
    type_def.sections.iter().collect()
}

/// The `entity-load-bearing` prepared form: the entity's load-bearing
/// sections serialized stably — each as `## <key>`, a blank line, the
/// trimmed content, a blank line — in the type's declared section order.
/// Keyed by section KEY (not heading) so a heading rename in the schema
/// does not read as a content change; a section the entity does not carry
/// is skipped. Title, metadata, and relationships are outside the form:
/// the anchor's artifact is the entity id, and a rename orphans the anchor
/// on its own. Without a type definition (a type the mem's schema does not
/// declare) every section the entity carries is load-bearing, in the
/// entity's own order.
pub fn entity_load_bearing_form(
    entity: &Entity,
    type_def: Option<&memstead_schema::types::TypeDefinition>,
) -> String {
    fn push(out: &mut String, key: &str, content: &str) {
        out.push_str("## ");
        out.push_str(key);
        out.push_str("\n\n");
        out.push_str(content.trim());
        out.push_str("\n\n");
    }
    let mut out = String::new();
    match type_def {
        Some(td) => {
            for section in load_bearing_sections(td) {
                if let Some(content) = entity.sections.get(&section.key) {
                    push(&mut out, &section.key, content);
                }
            }
        }
        None => {
            for (key, content) in &entity.sections {
                push(&mut out, key, content);
            }
        }
    }
    out
}

/// The prepared hash of ONE load-bearing section, in the same unit form
/// [`entity_load_bearing_form`] serializes it into (`## <key>`, a blank
/// line, the trimmed content). The key rides inside the hashed bytes, so
/// the same prose moved to another section key is a different mark.
///
/// The per-section grain exists because the whole-form hash collapses a
/// type's load-bearing sections to one bit: an owner who rewrites one of
/// three sections would clear a mark that still covers the other two, and
/// a contributor's remaining claims would be served as the workspace's own
/// prose.
pub fn entity_section_prepared_hash(key: &str, content: &str) -> String {
    prepared_content_hash(format!("## {key}\n\n{}\n\n", content.trim()).as_bytes())
}

/// One prepared hash per load-bearing section the entity carries, keyed by
/// section key. The section set is the type's
/// ([`load_bearing_sections`]), or every section the entity carries when
/// the type is unknown, matching [`entity_load_bearing_form`].
///
/// Empty sections are skipped deliberately. A mark over an empty section
/// would match every entity whose same section is empty, which is the one
/// way this comparison could brand unrelated content.
pub fn entity_load_bearing_section_marks(
    entity: &Entity,
    type_def: Option<&memstead_schema::types::TypeDefinition>,
) -> std::collections::BTreeMap<String, String> {
    let mut out = std::collections::BTreeMap::new();
    let mut add = |key: &String, content: &String| {
        if !content.trim().is_empty() {
            out.insert(key.clone(), entity_section_prepared_hash(key, content));
        }
    };
    match type_def {
        Some(td) => {
            for section in load_bearing_sections(td) {
                if let Some(content) = entity.sections.get(&section.key) {
                    add(&section.key, content);
                }
            }
        }
        None => {
            for (key, content) in &entity.sections {
                add(key, content);
            }
        }
    }
    out
}

/// Touchpoint A for the `entity` grain: the prepared-content hash of an
/// entity under the source's declared preparation. `None` declares
/// nothing — the canonical rendered markdown, byte-for-byte today's form.
/// [`ENTITY_LOAD_BEARING`] hashes [`entity_load_bearing_form`]. An
/// identifier the registry does not know yields `None`: the form cannot be
/// computed, and observation reports the anchor unobserved rather than
/// hashing a fabricated form (validation refuses such a record at every
/// edit path; only a hand-edited file reaches here).
pub fn entity_prepared_hash(
    entity: &Entity,
    type_def: Option<&memstead_schema::types::TypeDefinition>,
    preparation: Option<&str>,
) -> Option<String> {
    match entity_prepared(entity, type_def, preparation, None) {
        PathPrepared::Hash(h) => Some(h),
        PathPrepared::NoHash | PathPrepared::UnitAbsent => None,
    }
}

/// [`entity_prepared_hash`] with the artifact's `#<locator>` in hand: under
/// [`QUOTED_PHRASE`] the locator is the phrase and the prepared form is the
/// phrase where the entity's canonical markdown still carries it
/// ([`PathPrepared::UnitAbsent`] where it does not); every other
/// preparation ignores the locator and answers as [`entity_prepared_hash`]
/// does, [`PathPrepared::NoHash`] for an identifier the registry does not
/// prepare entities under.
pub fn entity_prepared(
    entity: &Entity,
    type_def: Option<&memstead_schema::types::TypeDefinition>,
    preparation: Option<&str>,
    locator: Option<&str>,
) -> PathPrepared {
    let form = match preparation {
        None => crate::render::render_entity_markdown(entity, None),
        Some(ENTITY_LOAD_BEARING) => entity_load_bearing_form(entity, type_def),
        Some(QUOTED_PHRASE) => {
            let rendered = crate::render::render_entity_markdown(entity, None);
            return match locator {
                Some(phrase) => quoted_phrase_prepared(phrase, &rendered),
                None => PathPrepared::Hash(prepared_content_hash(rendered.as_bytes())),
            };
        }
        Some(_) => return PathPrepared::NoHash,
    };
    PathPrepared::Hash(prepared_content_hash(form.as_bytes()))
}

// ---------------------------------------------------------------------------
// Touchpoint B: delivery units
// ---------------------------------------------------------------------------

/// One delivery unit of a file under a delivery preparation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeliveryUnit {
    /// The unit's key, unique within its file; the addressed form is
    /// `<path>#<key>` ([`unit_id`]).
    pub key: String,
    /// The intrinsic key the source's units sort by (a normalized stamp for
    /// [`DATED_ENTRIES`]); empty for a [`WHOLE_FILE_UNIT`].
    pub order_key: String,
    /// First line of the unit, 1-based.
    pub start_line: usize,
    /// Last line of the unit, 1-based, inclusive.
    pub end_line: usize,
    /// The prepared-content hash of the unit's text — what a span anchor
    /// over the unit records, and what a change run compares.
    pub hash: String,
}

/// How a unit changed between two states of its file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum UnitChange {
    /// The key is new.
    Added,
    /// The key existed; the unit's text changed.
    Modified,
    /// The key is gone.
    Deleted,
}

/// The addressed form of a unit: `<path>#<key>`.
pub fn unit_id(path: &str, key: &str) -> String {
    format!("{path}#{key}")
}

/// Split an artifact id into its path and, when it addresses a unit, the
/// unit key after the first `#`.
pub fn split_unit_id(id: &str) -> (&str, Option<&str>) {
    match id.find('#') {
        Some(cut) => (&id[..cut], Some(&id[cut + 1..])),
        None => (id, None),
    }
}

/// Touchpoint B: the delivery units of one file's content under a delivery
/// preparation, in file order. `None` when `preparation` is not a registered
/// delivery preparation (the caller keeps file-granularity delivery).
pub fn unitize(preparation: &str, content: &str) -> Option<Vec<DeliveryUnit>> {
    match preparation {
        DATED_ENTRIES => Some(dated_entries(content)),
        _ => None,
    }
}

/// The text of one unit, lines `start_line..=end_line` of `content`.
pub fn unit_text(content: &str, unit: &DeliveryUnit) -> String {
    content
        .lines()
        .skip(unit.start_line.saturating_sub(1))
        .take(unit.end_line + 1 - unit.start_line.max(1))
        .collect::<Vec<_>>()
        .join("\n")
}

/// The units that differ between two states of one file, keyed by unit key:
/// a key only in `after` is [`UnitChange::Added`], a key in both whose hash
/// differs is [`UnitChange::Modified`] (the `after` unit), a key only in
/// `before` is [`UnitChange::Deleted`] (the `before` unit, so its order key
/// still places it). Unchanged units are not delivered again.
pub fn diff_units(
    before: &[DeliveryUnit],
    after: &[DeliveryUnit],
) -> Vec<(DeliveryUnit, UnitChange)> {
    let old: std::collections::BTreeMap<&str, &DeliveryUnit> =
        before.iter().map(|u| (u.key.as_str(), u)).collect();
    let new: std::collections::BTreeMap<&str, &DeliveryUnit> =
        after.iter().map(|u| (u.key.as_str(), u)).collect();
    let mut out = Vec::new();
    for u in after {
        match old.get(u.key.as_str()) {
            None => out.push((u.clone(), UnitChange::Added)),
            Some(prev) if prev.hash != u.hash => out.push((u.clone(), UnitChange::Modified)),
            Some(_) => {}
        }
    }
    for u in before {
        if !new.contains_key(u.key.as_str()) {
            out.push((u.clone(), UnitChange::Deleted));
        }
    }
    out
}

fn dated_entries(content: &str) -> Vec<DeliveryUnit> {
    let lines: Vec<&str> = content.lines().collect();
    let starts: Vec<(usize, String)> = lines
        .iter()
        .enumerate()
        .filter_map(|(i, line)| leading_stamp(line).map(|stamp| (i, stamp)))
        .collect();
    if starts.is_empty() {
        return vec![DeliveryUnit {
            key: WHOLE_FILE_UNIT.to_string(),
            order_key: String::new(),
            start_line: 1,
            end_line: lines.len().max(1),
            hash: prepared_content_hash(content.as_bytes()),
        }];
    }
    let mut seen: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
    let mut units = Vec::with_capacity(starts.len());
    for (n, (start, stamp)) in starts.iter().enumerate() {
        // The preamble (anything before the first stamp) folds into the
        // first unit: it is context for the entries, never a unit of its own.
        let from = if n == 0 { 0 } else { *start };
        let to = starts.get(n + 1).map_or(lines.len(), |(next, _)| *next);
        let text = lines[from..to].join("\n");
        let count = seen
            .entry(stamp.clone())
            .and_modify(|c| *c += 1)
            .or_insert(1);
        let key = if *count == 1 {
            stamp.clone()
        } else {
            format!("{stamp}.{count}")
        };
        units.push(DeliveryUnit {
            key,
            order_key: stamp.clone(),
            start_line: from + 1,
            end_line: to,
            hash: prepared_content_hash(text.as_bytes()),
        });
    }
    units
}

/// The ISO stamp a line opens with (after leading markdown markers),
/// normalized to `YYYY-MM-DDTHH:MM:SS`; `None` when the line opens with
/// anything else or the stamp is out of range.
fn leading_stamp(line: &str) -> Option<String> {
    static STAMP: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    let re = STAMP.get_or_init(|| {
        regex::Regex::new(
            r"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)?\b",
        )
        .expect("the stamp regex compiles")
    });
    let s = line.trim_start_matches(|c: char| {
        c.is_whitespace() || matches!(c, '#' | '-' | '*' | '>' | '[' | '(' | '|' | '`' | '+')
    });
    let caps = re.captures(s)?;
    let num = |i: usize| -> u32 {
        caps.get(i)
            .map(|m| m.as_str().parse().unwrap_or(0))
            .unwrap_or(0)
    };
    let (y, mo, d, h, mi, sec) = (num(1), num(2), num(3), num(4), num(5), num(6));
    let days_in_month = match mo {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 => 29,
        _ => return None,
    };
    if !(1..=days_in_month).contains(&d) || h > 23 || mi > 59 || sec > 59 {
        return None;
    }
    Some(format!("{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{sec:02}"))
}

#[cfg(test)]
mod tests;