jubarte-edit 0.20.0

The edit product of the jubarte engine: edit plans as tracked changes, text diff views, capabilities and staged publication
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
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0

//! V2-13 (issue #845): the checker core for `--expect` evaluations.
//!
//! See jubarte-edit-implementation-plan.md P5 and jubarte-cli-proposal-b-revised.md
//! §10 for the design. The wiring into the apply path is staged in V2-08;
//! this module owns the types, the parser, the evaluator and the receipt.
//! The standalone `jubarte check OUTPUT --expect FILE` CLI is a separate
//! scope and is not implemented here.
//!
//! The model:
//! - `ExpectationsV1` is the closed `schema_version: 1` document.
//! - `SourceToOutputCorrespondence` is an input type: V2-08 will construct
//!   it from the prepared transaction; the standalone `check` case uses
//!   `identity_correspondence` (the inspected file IS the reopened
//!   output). The `output` indices address the projection below;
//!   duplicate short ids refuse at construction.
//! - `evaluate` reads the source and the reopened output bytes, projects
//!   the output's paragraphs in the final projection — the body's in
//!   body order, then the story paragraphs (`header1`, `header1.p1`,
//!   ...) story by story, the order `inspect::markdown` prints — and
//!   judges each typed check on its target. Both halves of a target
//!   must name the same entity through the one ids codec, or the check
//!   refuses `Ambiguous`. A missing, unmapped, merged, split or
//!   unsupported target refuses, a correspondence index outside the
//!   projection refuses `StaleCorrespondence` (never a panic), and a
//!   vanished paragraph never passes `text_absent`.
//! - Natural-language requirements whose `checks` are empty are listed
//!   in `ExpectationReport::unassessed_requirements`, apart from the
//!   typed checks (no pseudo-check with a fabricated kind); a passing
//!   typed check is one check, not the whole requirement.
//! - `ExpectationReport` carries the per-check outcomes and a receipt
//!   with the path, digest (`None` when absent, never a fake empty
//!   string), schema version, the fixed final projection, separate
//!   counts of checks that ran, refused, were unsupported and
//!   requirements left unassessed, the evaluated targets, and any
//!   caller-declared provenance, never an independence or
//!   completeness claim.

/// The expected schema version, per `jubarte-expectations-v1.schema.json`.
pub const EXPECTATIONS_SCHEMA_VERSION: u32 = 1;

/// Text view required by the initial profile: the FINAL logical projection
/// (insertions included, deletions excluded, no review markup).
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TextView {
    /// Insertions included, deletions excluded, with no review markup.
    Final,
}

/// The wire shape of a `Check`'s `target` field. Both ids must name the
/// same entity in the hash-bound original source; the parser checks shape
/// and non-empty strings, the evaluator checks identity against the
/// correspondence and refuses on a mismatch.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct Target {
    /// Snapshot-relative short id (`p12`, `header1.p0`).
    pub short_id: String,
    /// Long id (the contract's `j:short` form or `document.w:p.j:short.pN`).
    pub long_id: String,
}

/// The three typed checks of the initial profile.
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CheckKind {
    /// Exact final text of the target paragraph; empty is allowed.
    TextEquals,
    /// The target paragraph's final text contains the given text.
    TextContains,
    /// The target paragraph's final text does NOT contain the given text.
    TextAbsent,
}

/// One typed check, with kind, target and text payload.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct Check {
    /// Which typed check to run.
    pub kind: CheckKind,
    /// The paragraph this check judges.
    pub target: Target,
    /// The text payload of the check.
    pub text: String,
}

/// One requirement: a key, a natural-language description, and zero or
/// more typed checks. A requirement with zero checks stays `unassessed`.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct Requirement {
    /// Settled id: `[A-Za-z][A-Za-z0-9_.-]*`, unique per document.
    pub key: String,
    /// Natural-language description. The initial profile does not assess
    /// it; callers read it as reference text.
    pub description: String,
    /// Typed checks; an empty array means the requirement is unassessed.
    /// The schema requires this field, so missing keys refuse.
    pub checks: Vec<Check>,
}

/// The source-digest binding.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct Source {
    /// Exactly 64 lowercase hexadecimal characters.
    pub sha256: String,
}

/// The closed `schema_version: 1` expectations document.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct ExpectationsV1 {
    /// Always 1 in this profile.
    pub schema_version: u32,
    /// The source revision the expectations name.
    pub source: Source,
    /// The projection the checks evaluate. `final` only in this profile.
    pub text_view: TextView,
    /// One or more requirements.
    pub requirements: Vec<Requirement>,
}

/// The outcome of a single typed check.
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
    /// The predicate held against the reopened output.
    Passed,
    /// The predicate did not hold; the change has not been made.
    Failed,
    /// The target was missing, unmapped, merged, split, ambiguous or
    /// unsupported; the predicate could not be evaluated. A refusal
    /// never counts as a passing `text_absent`.
    Refused,
    /// The check had no typed predicate; the natural-language
    /// description is the requirement's only content.
    Unassessed,
}

/// A `Refused` reason, kept for the receipt (proposal §10).
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RefusalReason {
    /// The target's `short_id` is not present in the correspondence.
    TargetMissing,
    /// The target was mapped to multiple output paragraphs.
    Merged,
    /// The target was mapped to no output paragraph.
    Split,
    /// The two halves of the target name different entities.
    Ambiguous,
    /// The target is not a paragraph the initial profile supports.
    Unsupported,
    /// The expectations' `source.sha256` does not name the bytes the
    /// correspondence is built from.
    StaleSource,
    /// The output bytes cannot be opened for projection.
    InvalidOutput,
    /// The correspondence maps the target to an output index outside
    /// the reopened output's projection: a stale or foreign
    /// correspondence, not a judgement about the document.
    StaleCorrespondence,
}

/// Per-check report.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CheckOutcome {
    /// Requirement key this check belongs to.
    pub key: String,
    /// Target's short id, when the target resolved.
    pub target: String,
    /// Kind of the check.
    pub kind: CheckKind,
    /// What happened.
    pub outcome: Outcome,
    /// Evidence text: the projected paragraph text when resolved,
    /// or a refusal reason.
    pub evidence: Option<String>,
    /// Refusal reason when `outcome == Refused`.
    pub reason: Option<RefusalReason>,
}

/// Marker fields the receipt never prints: a separately supplied file is
/// not an independence claim, and no deterministic profile completes the
/// caller's task. They stay `false` for library readers and out of the
/// wire shape entirely.
fn is_false(value: &bool) -> bool {
    !*value
}

/// Human-readable refusal reasons, matching the serde names.
impl std::fmt::Display for RefusalReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            Self::TargetMissing => "target missing",
            Self::Merged => "merged target",
            Self::Split => "split or removed target",
            Self::Ambiguous => "ambiguous target ids",
            Self::Unsupported => "unsupported target",
            Self::StaleSource => "stale source binding",
            Self::InvalidOutput => "unopenable output",
            Self::StaleCorrespondence => "stale correspondence",
        };
        f.write_str(name)
    }
}

/// The compact, structured receipt (proposal §10 / #1017, edit plan P5:
/// "state which checks ran, were unsupported or remained unassessed").
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct ExpectationReceipt {
    /// Schema version of the parsed expectations.
    pub schema_version: u32,
    /// The source digest the expectations name.
    pub source_sha256: String,
    /// The digest of the expectations bytes themselves, when the caller
    /// supplied one. A missing digest is `None`, never an empty string
    /// that reads like one (review row 11).
    pub expectations_sha256: Option<String>,
    /// Path of the expectations file, when supplied.
    pub expectations_path: Option<String>,
    /// The fixed final projection the checks evaluated (edit plan P5:
    /// the receipt records the projection; `final` only in this
    /// profile).
    pub text_view: TextView,
    /// Typed checks that ran (passed or failed). A refused check never
    /// ran, in any branch (review row 3).
    pub checks_run: usize,
    /// Typed checks that refused, for any reason except an unsupported
    /// target.
    pub checks_refused: usize,
    /// Typed checks that refused because their target is not a
    /// paragraph the initial profile supports.
    pub checks_unsupported: usize,
    /// Natural-language requirements that remained unassessed (their
    /// `checks` list was empty).
    pub requirements_unassessed: usize,
    /// Targets evaluated, in encounter order, deduplicated.
    pub targets: Vec<String>,
    /// Caller-declared provenance string, if any; the receipt carries it
    /// verbatim but does not verify it.
    pub declared_provenance: Option<String>,
    /// Always `false`. A separately supplied file is not a claim of
    /// independence. Never serialized: the wire never carries the word.
    #[serde(default, skip_serializing_if = "is_false")]
    pub independent: bool,
    /// Always `false`. The CLI cannot claim the user's task is complete.
    #[serde(default, skip_serializing_if = "is_false")]
    pub complete_task: bool,
}

/// One source paragraph and the set of output paragraphs it mapped to
/// during preparation. The initial profile requires exact one-to-one
/// correspondence: the `output` slice must have exactly one element for
/// a passing typed check; anything else refuses.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CorrespondenceEntry {
    /// The source paragraph's short id (`p0`, `header1.p0`).
    pub short_id: String,
    /// The output paragraph indices this source paragraph maps to.
    pub output: Vec<usize>,
    /// Whether the target's two ids name the same source entity. The
    /// initial profile refuses when they disagree.
    pub identity_ok: bool,
}

impl ExpectationReport {
    /// The first check that blocks publication: a `Failed` predicate, or
    /// any `Refused` check (missing, ambiguous, stale, unsupported or
    /// unopenable target). `None` when every typed check passed or stayed
    /// unassessed; unassessed requirements never block (proposal §10).
    pub fn blocking_failure(&self) -> Option<&CheckOutcome> {
        self.checks
            .iter()
            .find(|c| matches!(c.outcome, Outcome::Failed | Outcome::Refused))
    }

    /// Whether any typed check blocks publication (see
    /// [`Self::blocking_failure`]).
    pub fn has_blocking_failure(&self) -> bool {
        self.blocking_failure().is_some()
    }
}

impl CorrespondenceEntry {
    /// A 1:1 mapping of one source paragraph to one output paragraph.
    pub fn one_to_one(short_id: impl Into<String>, output: usize) -> Self {
        Self {
            short_id: short_id.into(),
            output: vec![output],
            identity_ok: true,
        }
    }

    /// A merged mapping (one source paragraph → many output paragraphs).
    pub fn merged(short_id: impl Into<String>, outputs: &[usize]) -> Self {
        Self {
            short_id: short_id.into(),
            output: outputs.to_vec(),
            identity_ok: true,
        }
    }

    /// A split/vanished mapping (one source paragraph → no output
    /// paragraph).
    pub fn split(short_id: impl Into<String>) -> Self {
        Self {
            short_id: short_id.into(),
            output: Vec::new(),
            identity_ok: true,
        }
    }
}

/// The S→output correspondence V2-08 will supply, and the standalone
/// `check` case builds with [`identity_correspondence`]. The `output`
/// indices of its entries address the projected output paragraphs in
/// the checker's projection order: the body's paragraphs in body order,
/// then the story paragraphs (`header1`, `header1.p1`, ...) story by
/// story.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct SourceToOutputCorrespondence {
    entries: Vec<CorrespondenceEntry>,
    /// short id → position in `entries`, so [`Self::lookup`] is one hash
    /// lookup instead of a linear scan per check.
    index: std::collections::HashMap<String, usize>,
}

impl SourceToOutputCorrespondence {
    /// Build a correspondence from explicit entries. Order is preserved.
    ///
    /// # Errors
    ///
    /// A plain string, when two entries share a `short_id`: a
    /// correspondence names each source paragraph once, and a silent
    /// first-wins lookup would hide the construction bug until it
    /// surfaced as the wrong paragraph.
    pub fn from_entries(entries: Vec<CorrespondenceEntry>) -> Result<Self, String> {
        let mut index = std::collections::HashMap::with_capacity(entries.len());
        for (position, entry) in entries.iter().enumerate() {
            if index.insert(entry.short_id.clone(), position).is_some() {
                return Err(format!(
                    "duplicate correspondence short id: {}",
                    entry.short_id
                ));
            }
        }
        Ok(Self { entries, index })
    }

    /// The correspondence entries.
    pub fn entries(&self) -> &[CorrespondenceEntry] {
        &self.entries
    }

    /// Look up an entry by source short id.
    pub fn lookup(&self, short_id: &str) -> Option<&CorrespondenceEntry> {
        self.index
            .get(short_id)
            .map(|&position| &self.entries[position])
    }
}

/// The full per-check report and the receipt.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct ExpectationReport {
    /// Per-check outcomes in encounter order. Only typed checks appear
    /// here; an unassessed requirement is listed below, never as a
    /// pseudo-check with a fabricated kind (review row 12).
    pub checks: Vec<CheckOutcome>,
    /// Requirement keys whose `checks` list was empty: reported
    /// `unassessed`, apart from the checks, in encounter order.
    pub unassessed_requirements: Vec<String>,
    /// An output-bound copy of the evaluated expectations (new
    /// `source.sha256` naming the inspected primary, references rebound
    /// to the output's own ids), when the caller supplied one. The
    /// caller's input file is never rewritten (proposal §10).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output_bound: Option<ExpectationsV1>,
    /// The compact, structured receipt.
    pub receipt: ExpectationReceipt,
}

/// Parse the closed `schema_version: 1` expectations document. The
/// Rust type's `deny_unknown_fields` and the explicit checks below
/// enforce every constraint the bundled JSON Schema states, so the
/// parser does not need a runtime JSON Schema validator (the WASM and
/// Python lockfiles therefore stay free of `jsonschema` and ~40
/// transitive crates for a closed object with four fields). The tests
/// run the accepted/rejected corpus through both this function and
/// the bundled schema to keep them in lockstep.
///
/// The parser is additionally stricter on two document classes the
/// bundled schema accepts (the safe direction; pinned by
/// `parser_is_stricter_than_the_bundled_schema_on_two_pinned_divergences`):
/// - `"schema_version": 1.0` (or `1e0`): JSON Schema `const` compares
///   numbers by mathematical equality, so the schema's `const: 1`
///   accepts it, while serde cannot deserialize a float into the
///   `u32` field.
/// - a JSON object with a duplicated field: the schema side reads a
///   last-value-wins `serde_json::Value`, while the derived
///   `Deserialize` errors on the duplicate field.
///
/// Parsing fails with a plain string for the caller to surface.
pub fn parse_expectations(json: &str) -> Result<ExpectationsV1, String> {
    // Closed shape first (Rust type, deny_unknown_fields).
    let parsed: ExpectationsV1 =
        serde_json::from_str(json).map_err(|e| format!("expectations Rust type rejected: {e}"))?;

    // schema_version == 1 (the schema's `const`).
    if parsed.schema_version != EXPECTATIONS_SCHEMA_VERSION {
        return Err(format!(
            "schema_version {} is not supported (expected {})",
            parsed.schema_version, EXPECTATIONS_SCHEMA_VERSION
        ));
    }

    // source.sha256: exactly 64 lowercase hexadecimal characters, no
    // trailing newline (the schema's anchored `^[0-9a-f]{64}$`).
    if !is_lowercase_hex_64(&parsed.source.sha256) {
        return Err(
            "source.sha256 must be exactly 64 lowercase hexadecimal characters".to_string(),
        );
    }

    // text_view: `final` only at this stage (the schema's `const`).
    if !matches!(parsed.text_view, TextView::Final) {
        return Err("text_view must be \"final\"".to_string());
    }

    // requirements: non-empty (the schema's `minItems: 1`).
    if parsed.requirements.is_empty() {
        return Err("requirements must contain at least one item".to_string());
    }

    let mut seen: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
    for requirement in &parsed.requirements {
        // key: `^[A-Za-z][A-Za-z0-9_.-]*$` (the schema's `pattern`
        // plus its `not` clause, which forbids any character outside
        // the allowed set including whitespace).
        if !is_valid_key(&requirement.key) {
            return Err(format!(
                "requirement key {:?} must match ^[A-Za-z][A-Za-z0-9_.-]*$",
                requirement.key
            ));
        }

        // description: non-empty (the schema's `minLength: 1`).
        if requirement.description.is_empty() {
            return Err(format!(
                "requirement {:?} description must be non-empty",
                requirement.key
            ));
        }

        // The schema's `$comment` calls for a "compiler check" on
        // unique keys; `uniqueItems` does not express it because the
        // keys are object properties, not array elements.
        if !seen.insert(requirement.key.as_str()) {
            return Err(format!("duplicate requirement key: {}", requirement.key));
        }

        for check in &requirement.checks {
            // target: short_id and long_id must be non-empty
            // (the schema's `minLength: 1`).
            if check.target.short_id.is_empty() || check.target.long_id.is_empty() {
                return Err(format!(
                    "requirement {:?} check target requires non-empty short_id and long_id",
                    requirement.key
                ));
            }

            // text_contains / text_absent: non-empty text. text_equals
            // allows empty text (the schema's per-kind `minLength`).
            if matches!(check.kind, CheckKind::TextContains | CheckKind::TextAbsent)
                && check.text.is_empty()
            {
                return Err(format!(
                    "requirement {:?} text_contains/text_absent requires non-empty text",
                    requirement.key
                ));
            }
        }
    }

    Ok(parsed)
}

/// True iff `s` is exactly 64 bytes of `[0-9a-f]` (no trailing
/// newline, no uppercase).
fn is_lowercase_hex_64(s: &str) -> bool {
    let bytes = s.as_bytes();
    bytes.len() == 64
        && bytes
            .iter()
            .all(|&b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// True iff `s` matches the schema's key regex `^[A-Za-z][A-Za-z0-9_.-]*$`.
fn is_valid_key(s: &str) -> bool {
    let bytes = s.as_bytes();
    if bytes.is_empty() {
        return false;
    }
    let first = bytes[0];
    if !first.is_ascii_alphabetic() {
        return false;
    }
    bytes[1..]
        .iter()
        .all(|&b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.' || b == b'-')
}

/// SHA-256 of arbitrary content, lowercase hex.
pub fn content_sha256(bytes: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(bytes);
    digest.iter().map(|b| format!("{b:02x}")).collect()
}

/// Build the identity correspondence: the inspected file IS the reopened
/// output. Used for the standalone `check` case (#943) and for tests
/// that bind the expectations to the file the inspector reads. Covers
/// the story paragraphs too (`header1`, `header1.p1`, ...): the ids
/// `docx_text`/`jubarte read` print are checkable targets, in the same
/// projection order [`evaluate`] uses.
///
/// # Errors
///
/// A plain string when the file cannot be opened for projection.
pub fn identity_correspondence(
    source_bytes: &[u8],
) -> Result<SourceToOutputCorrespondence, String> {
    let paragraphs =
        projected_paragraphs(source_bytes).map_err(|e| format!("cannot open source: {e}"))?;
    let entries = paragraphs
        .into_iter()
        .enumerate()
        .map(|(index, p)| CorrespondenceEntry::one_to_one(p.id, index))
        .collect();
    Ok(SourceToOutputCorrespondence::from_entries(entries)
        .expect("the inspector reports each paragraph id once"))
}

/// The paragraphs a expectations run judges, in the fixed projection
/// order: the body's paragraphs in body order, then the story
/// paragraphs (`header1`, `header1.p1`, ...) story by story — the same
/// order `inspect::markdown` prints.
fn projected_paragraphs(
    bytes: &[u8],
) -> Result<Vec<crate::inspect::Paragraph>, crate::inspect::InspectError> {
    let mut all = crate::inspect::paragraphs(bytes)?;
    for story in crate::inspect::stories(bytes)? {
        all.extend(story.paragraphs);
    }
    Ok(all)
}

/// Evaluate typed checks on the reopened output, given the bytes the
/// correspondence was built from, the output bytes, and the
/// correspondence.
pub fn evaluate(
    spec: &ExpectationsV1,
    source: &[u8],
    output: &[u8],
    correspondence: &SourceToOutputCorrespondence,
) -> ExpectationReport {
    evaluate_with_receipt(spec, source, output, correspondence, ReceiptMeta::default())
}

/// Metadata for the receipt: the file path the caller read, the digest
/// of the file bytes, and any declared provenance.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ReceiptMeta {
    /// Path of the expectations file (verbatim from the caller).
    pub path: Option<String>,
    /// SHA-256 of the expectations file bytes.
    pub digest: Option<String>,
    /// Caller-declared provenance string.
    pub declared_provenance: Option<String>,
}

/// As [`evaluate`], but also records receipt metadata: the file path,
/// the file digest, and any caller-declared provenance.
pub fn evaluate_with_receipt(
    spec: &ExpectationsV1,
    source: &[u8],
    output: &[u8],
    correspondence: &SourceToOutputCorrespondence,
    meta: ReceiptMeta,
) -> ExpectationReport {
    let mut checks: Vec<CheckOutcome> = Vec::new();
    let mut unassessed_requirements: Vec<String> = Vec::new();
    let mut targets: Vec<String> = Vec::new();
    let mut seen_targets: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();

    // Project the output's paragraphs in the final projection: the
    // body's, then the stories'. Unopenable output bytes refuse every
    // typed check with its real kind and target (review row 2);
    // natural-language requirements stay unassessed, listed apart
    // from the checks.
    let output_paragraphs = match projected_paragraphs(output) {
        Ok(paragraphs) => paragraphs,
        Err(error) => {
            for requirement in &spec.requirements {
                if requirement.checks.is_empty() {
                    unassessed_requirements.push(requirement.key.clone());
                } else {
                    for check in &requirement.checks {
                        checks.push(CheckOutcome {
                            key: requirement.key.clone(),
                            target: check.target.short_id.clone(),
                            kind: check.kind,
                            outcome: Outcome::Refused,
                            evidence: Some(error.to_string()),
                            reason: Some(RefusalReason::InvalidOutput),
                        });
                    }
                }
            }
            return assemble_report(spec, meta, checks, unassessed_requirements, targets);
        }
    };
    let source_sha = content_sha256(source);
    let stale_source = source_sha != spec.source.sha256;
    // The source's `w14:paraId` inventory: the correspondence reports
    // each target's short id only, so the pair's native-key half is
    // proven here against the document it must name.
    let native_keys = native_key_inventory(source);

    for requirement in &spec.requirements {
        if requirement.checks.is_empty() {
            // Unassessed, listed apart from the checks: no pseudo-check
            // with a fabricated kind (review row 12).
            unassessed_requirements.push(requirement.key.clone());
            continue;
        }
        for check in &requirement.checks {
            let target_label = check.target.short_id.clone();

            if stale_source {
                checks.push(CheckOutcome {
                    key: requirement.key.clone(),
                    target: target_label,
                    kind: check.kind,
                    outcome: Outcome::Refused,
                    evidence: Some(
                        "source.sha256 does not name the bytes the correspondence was built from"
                            .to_string(),
                    ),
                    reason: Some(RefusalReason::StaleSource),
                });
                continue;
            }

            // The initial profile checks paragraphs only: the body's
            // `pN`, a story's own first paragraph (`header1`) or a
            // story's `pN`. Targets naming anything else (tables,
            // ranges, comments, revisions) refuse as unsupported --
            // before the correspondence lookup, so the reason does not
            // depend on what the correspondence happens to carry
            // (review row 5).
            if !is_paragraph_target(&check.target.short_id) {
                checks.push(CheckOutcome {
                    key: requirement.key.clone(),
                    target: target_label,
                    kind: check.kind,
                    outcome: Outcome::Refused,
                    evidence: Some(
                        "target is not a paragraph the initial profile supports".to_string(),
                    ),
                    reason: Some(RefusalReason::Unsupported),
                });
                continue;
            }

            // Both ids must name the SAME entity (schema `$defs.target`),
            // judged through the one ids codec: a disagreeing pair
            // refuses as ambiguous before any lookup (review row 6).
            if !ids_name_one_entity(&check.target.short_id, &check.target.long_id, &native_keys) {
                checks.push(CheckOutcome {
                    key: requirement.key.clone(),
                    target: target_label,
                    kind: check.kind,
                    outcome: Outcome::Refused,
                    evidence: Some(
                        "the target's short id and long id do not name the same entity".to_string(),
                    ),
                    reason: Some(RefusalReason::Ambiguous),
                });
                continue;
            }

            let Some(entry) = correspondence.lookup(&check.target.short_id) else {
                checks.push(CheckOutcome {
                    key: requirement.key.clone(),
                    target: target_label,
                    kind: check.kind,
                    outcome: Outcome::Refused,
                    evidence: Some("target is not in the correspondence".to_string()),
                    reason: Some(RefusalReason::TargetMissing),
                });
                continue;
            };
            if !entry.identity_ok {
                checks.push(CheckOutcome {
                    key: requirement.key.clone(),
                    target: target_label,
                    kind: check.kind,
                    outcome: Outcome::Refused,
                    evidence: Some("target ids disagree".to_string()),
                    reason: Some(RefusalReason::Ambiguous),
                });
                continue;
            }
            if entry.output.is_empty() {
                checks.push(CheckOutcome {
                    key: requirement.key.clone(),
                    target: target_label,
                    kind: check.kind,
                    outcome: Outcome::Refused,
                    evidence: Some("target mapped to no output paragraph".to_string()),
                    reason: Some(RefusalReason::Split),
                });
                continue;
            }
            if entry.output.len() != 1 {
                checks.push(CheckOutcome {
                    key: requirement.key.clone(),
                    target: target_label,
                    kind: check.kind,
                    outcome: Outcome::Refused,
                    evidence: Some(format!(
                        "target mapped to {} output paragraphs (one-to-one required)",
                        entry.output.len()
                    )),
                    reason: Some(RefusalReason::Merged),
                });
                continue;
            }
            let Some(paragraph) = output_paragraphs.get(entry.output[0]) else {
                checks.push(CheckOutcome {
                    key: requirement.key.clone(),
                    target: target_label,
                    kind: check.kind,
                    outcome: Outcome::Refused,
                    evidence: Some(format!(
                        "correspondence maps the target to output paragraph {}, but the \
                         reopened output's projection holds {} paragraphs",
                        entry.output[0],
                        output_paragraphs.len()
                    )),
                    reason: Some(RefusalReason::StaleCorrespondence),
                });
                continue;
            };
            let evidence = paragraph.text.clone();
            let outcome = match check.kind {
                CheckKind::TextEquals => {
                    if paragraph.text == check.text {
                        Outcome::Passed
                    } else {
                        Outcome::Failed
                    }
                }
                CheckKind::TextContains => {
                    if paragraph.text.contains(&check.text) {
                        Outcome::Passed
                    } else {
                        Outcome::Failed
                    }
                }
                CheckKind::TextAbsent => {
                    if paragraph.text.contains(&check.text) {
                        Outcome::Failed
                    } else {
                        Outcome::Passed
                    }
                }
            };
            // Only an evaluated check ran, and only an evaluated check
            // lists its target (review row 3).
            if seen_targets.insert(target_label.clone()) {
                targets.push(target_label.clone());
            }
            checks.push(CheckOutcome {
                key: requirement.key.clone(),
                target: target_label,
                kind: check.kind,
                outcome,
                evidence: Some(evidence),
                reason: None,
            });
        }
    }

    assemble_report(spec, meta, checks, unassessed_requirements, targets)
}

/// Assemble the report and its receipt. Both the evaluated path and
/// the InvalidOutput path end here, so the receipt's counts mean one
/// thing in every branch (review row 3): `checks_run` counts the
/// checks that ran (passed or failed), never the refused ones.
fn assemble_report(
    spec: &ExpectationsV1,
    meta: ReceiptMeta,
    checks: Vec<CheckOutcome>,
    unassessed_requirements: Vec<String>,
    targets: Vec<String>,
) -> ExpectationReport {
    let checks_run = checks
        .iter()
        .filter(|c| matches!(c.outcome, Outcome::Passed | Outcome::Failed))
        .count();
    let checks_unsupported = checks
        .iter()
        .filter(|c| {
            matches!(
                (c.outcome, &c.reason),
                (Outcome::Refused, Some(RefusalReason::Unsupported))
            )
        })
        .count();
    let checks_refused = checks
        .iter()
        .filter(|c| {
            c.outcome == Outcome::Refused
                && !matches!(c.reason.as_ref(), Some(RefusalReason::Unsupported))
        })
        .count();
    let requirements_unassessed = unassessed_requirements.len();
    ExpectationReport {
        checks,
        unassessed_requirements,
        output_bound: None,
        receipt: ExpectationReceipt {
            schema_version: spec.schema_version,
            source_sha256: spec.source.sha256.clone(),
            expectations_sha256: meta.digest,
            expectations_path: meta.path,
            text_view: spec.text_view,
            checks_run,
            checks_refused,
            checks_unsupported,
            requirements_unassessed,
            targets,
            declared_provenance: meta.declared_provenance,
            independent: false,
            complete_task: false,
        },
    }
}

/// Whether a target's two ids name the same entity, judged through the
/// one ids codec (`crate::ids`); there is no second parser. The short
/// id must parse as the paragraph place this profile checks, the long
/// id must be the four-field form `PART.ELEMENT.ATTRIBUTE.VALUE`
/// (short-and-long id contract §5: parse on the first three literal
/// dots, the remainder is the VALUE), its ELEMENT must be `w:p`, and
/// its PART must be the part the short id's story lives in
/// (`document` for the body). When the ATTRIBUTE is the contract's
/// `j:short`, its VALUE must parse to the very same
/// [`crate::ids::ShortId`]; when it is the native key `w14:paraId`, its
/// VALUE must be the exact attribute spelling
/// [`native_key_inventory`] recorded for the paragraph the short id
/// names — what the apply path's pair resolver compares as the whole
/// long id (`TARGET_ID_MISMATCH`). A long id of any other shape, one
/// carrying an unregistered attribute, or one naming another entity,
/// makes the pair ambiguous.
fn ids_name_one_entity(
    short_id: &str,
    long_id: &str,
    native_keys: &std::collections::HashMap<String, String>,
) -> bool {
    use crate::ids::{ShortId, Story};
    let Ok(short) = short_id.parse::<ShortId>() else {
        return false;
    };
    let ShortId::Block { story, .. } = &short else {
        return false;
    };
    let fields: Vec<&str> = long_id.splitn(4, '.').collect();
    let [part, element, attribute, value] = fields.as_slice() else {
        return false;
    };
    if *element != "w:p" {
        return false;
    }
    let part_matches = match story {
        Story::Body => *part == "document",
        Story::Part(stem) => *part == stem.as_str(),
    };
    if !part_matches {
        return false;
    }
    match *attribute {
        "j:short" => value.parse::<ShortId>().is_ok_and(|named| named == short),
        "w14:paraId" => native_keys
            .get(short_id)
            .is_some_and(|named| named == value),
        _ => false,
    }
}

/// The `w14:paraId` native key each source paragraph carries, keyed by
/// the printed short id the correspondence carries (`p0`, `header1`,
/// `header1.p2`). The shared native-key policy
/// ([`crate::edit::native_keys::para_id`]) decides whether the attribute
/// is a key at all, and a key another paragraph of the same story
/// repeats is no long-id key — the pair resolver spells `j:short` for
/// it — so a `w14:paraId` pair naming one is ambiguous too. An
/// unopenable source or story yields no entries for it, which refuses
/// every native-key pair aimed there rather than guessing.
fn native_key_inventory(source: &[u8]) -> std::collections::HashMap<String, String> {
    let mut keys = std::collections::HashMap::new();
    let Ok(opened) = crate::inspect::Opened::open(source) else {
        return keys;
    };
    story_keys(
        &opened.dom,
        &crate::inspect::body_paragraph_nodes(&opened.dom, opened.body),
        crate::inspect::BODY_STORY,
        &mut keys,
    );
    for (id, _, part) in opened.story_parts() {
        if let Ok((dom, _, root)) = crate::inspect::parse_part(&opened.pkg, &part) {
            story_keys(
                &dom,
                &crate::inspect::story_paragraph_nodes(&dom, root),
                &id,
                &mut keys,
            );
        }
    }
    keys
}

/// [`native_key_inventory`] for one story's paragraphs, in the same
/// walk order [`crate::ids::paragraph_id`] numbers them in.
fn story_keys(
    dom: &crate::xmllinq::Dom,
    nodes: &[crate::xmllinq::NodeId],
    story: &str,
    out: &mut std::collections::HashMap<String, String>,
) {
    let para_id = crate::namespaces::W14::name("paraId");
    let mut counts: std::collections::HashMap<u32, usize> = std::collections::HashMap::new();
    for &node in nodes {
        if let Some(key) = dom
            .attribute(node, &para_id)
            .and_then(crate::edit::native_keys::para_id)
        {
            *counts.entry(key).or_default() += 1;
        }
    }
    for (index, &node) in nodes.iter().enumerate() {
        let Some(raw) = dom.attribute(node, &para_id) else {
            continue;
        };
        if crate::edit::native_keys::para_id(raw).is_some_and(|key| counts[&key] == 1) {
            out.insert(crate::ids::paragraph_id(story, index), raw.to_string());
        }
    }
}

fn is_paragraph_target(short_id: &str) -> bool {
    // The initial profile supports paragraph short ids: the body's `pN`
    // (a cell's paragraphs carry their flat body `pN` too), a story's
    // own first paragraph (`header1`) and a story's `header1.pN`,
    // `footer1.pN`, `footnotes.pN`, ... — the same set
    // `ids::parse_location` resolves as a paragraph. Tables, ranges,
    // comments and revisions are unsupported until an explicit
    // alternative predicate/mapping lands.
    use crate::ids::{ShortId, Step, Story};
    match short_id.parse::<ShortId>() {
        Ok(ShortId::Block { story, path }) => matches!(
            (story, path.as_slice()),
            (Story::Body, [Step::Paragraph(_)]) | (Story::Part(_), [] | [Step::Paragraph(_)])
        ),
        Ok(ShortId::Range { .. }) => false,
        Ok(_) => false,
        Err(_) => false,
    }
}

/// Build the output-bound copy of evaluated expectations (proposal §10:
/// "The apply receipt may expose an explicitly output-bound copy of
/// evaluated text expectations, with new references/hash, for later
/// rechecking"). Each typed check's target is rebound through the
/// correspondence to the output paragraph it was evaluated against, and
/// `source.sha256` becomes the primary's own digest, so standalone
/// `check OUTPUT --expect` accepts the copy.
///
/// The copy is complete or absent: `None` when the output cannot be
/// opened for the identity walk, or any requirement's check cannot be
/// spelled in the output's own ids. It is all-or-nothing on purpose
/// (#1084 review F3): this runs only after every blocking check passed,
/// so the lookups it repeats already succeeded during evaluation and a
/// failure here is an internal inconsistency — while a partial copy
/// would silently drop the affected checks and let a later
/// `check OUTPUT --expect copy` pass vacuously. The caller's input file
/// is never rewritten.
pub fn rebind_to_output(
    spec: &ExpectationsV1,
    correspondence: &SourceToOutputCorrespondence,
    output: &[u8],
) -> Option<ExpectationsV1> {
    let identity = identity_correspondence(output).ok()?;
    // output index -> the output's own short id (the identity walk).
    let mut by_index = std::collections::HashMap::new();
    for entry in identity.entries() {
        if let [index] = entry.output.as_slice() {
            by_index.insert(index, entry.short_id.clone());
        }
    }
    let long_id_of = |short: &str| -> Option<String> {
        use crate::ids::{ShortId, Story};
        let parsed = short.parse::<ShortId>().ok()?;
        let part = match &parsed {
            ShortId::Block { story, .. } => match story {
                Story::Body => "document",
                Story::Part(stem) => stem.as_str(),
            },
            _ => return None,
        };
        Some(format!("{part}.w:p.j:short.{short}"))
    };
    let mut requirements = Vec::with_capacity(spec.requirements.len());
    for requirement in &spec.requirements {
        let mut checks = Vec::with_capacity(requirement.checks.len());
        for check in &requirement.checks {
            let entry = correspondence.lookup(&check.target.short_id)?;
            let [index] = entry.output.as_slice() else {
                return None;
            };
            let short = by_index.get(&index)?.clone();
            let long = long_id_of(&short)?;
            checks.push(Check {
                kind: check.kind,
                target: Target {
                    short_id: short,
                    long_id: long,
                },
                text: check.text.clone(),
            });
        }
        requirements.push(Requirement {
            key: requirement.key.clone(),
            description: requirement.description.clone(),
            checks,
        });
    }
    Some(ExpectationsV1 {
        schema_version: spec.schema_version,
        source: Source {
            sha256: content_sha256(output),
        },
        text_view: spec.text_view,
        requirements,
    })
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod shape_branch_tests {
    use super::*;

    #[test]
    fn keys_start_with_a_letter_and_take_word_dots_and_dashes() {
        for good in ["a", "a_b", "a.b", "a-b", "A9"] {
            assert!(is_valid_key(good), "{good}");
        }
        for bad in ["", "9a", "_a", "a b", "a/b"] {
            assert!(!is_valid_key(bad), "{bad}");
        }
    }

    #[test]
    fn a_pair_names_one_paragraph_only_in_its_own_part() {
        let keys = std::collections::HashMap::from([("p1".to_string(), "1A2B3C4D".to_string())]);
        assert!(ids_name_one_entity("p0", "document.w:p.j:short.p0", &keys));
        assert!(ids_name_one_entity(
            "p1",
            "document.w:p.w14:paraId.1A2B3C4D",
            &keys
        ));
        assert!(ids_name_one_entity(
            "header1.p0",
            "header1.w:p.j:short.header1.p0",
            &keys
        ));
        for (short, long) in [
            ("not an id", "document.w:p.j:short.p0"),
            ("c5", "comments.w:comment.w:id.5"),
            ("p0", "document.w:p"),
            ("p0", "document.w:tbl.j:short.p0"),
            ("p0", "header1.w:p.j:short.p0"),
            ("header1.p0", "document.w:p.j:short.header1.p0"),
            ("p0", "document.w:p.j:short.p1"),
            ("p2", "document.w:p.w14:paraId.1A2B3C4D"),
            ("p0", "document.w:p.w:id.0"),
        ] {
            assert!(!ids_name_one_entity(short, long, &keys), "{short} {long}");
        }
    }

    #[test]
    fn unopenable_output_refuses_checks_and_leaves_prose_unassessed() {
        let source =
            crate::markdown::markdown_to_docx("One.\n", &crate::markdown::DocxOptions::default())
                .unwrap()
                .docx;
        let spec = parse_expectations(
            &serde_json::json!({
                "schema_version": 1,
                "source": {"sha256": crate::inspect::source_sha256(&source)},
                "text_view": "final",
                "requirements": [
                    {"key": "prose", "description": "reads well", "checks": []},
                    {"key": "typed", "description": "keeps one", "checks": [{
                        "kind": "text_equals",
                        "target": {"short_id": "p0", "long_id": "document.w:p.j:short.p0"},
                        "text": "One.",
                    }]},
                ],
            })
            .to_string(),
        )
        .unwrap();
        let identity = identity_correspondence(&source).unwrap();
        let report = evaluate(&spec, &source, b"not a docx", &identity);
        assert_eq!(report.unassessed_requirements, vec!["prose".to_string()]);
        assert_eq!(report.checks.len(), 1);
        assert_eq!(report.checks[0].reason, Some(RefusalReason::InvalidOutput));
    }
}