spec-driven-docs 0.10.0

Spec-driven documentation: current specs, immutable decision records, and executable gates kept coherent for people and coding agents.
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
//! The pure function from what was observed to what will be done.
//!
//! Nothing here reads a disk, reaches a network, or asks a clock. Every
//! one of those is an input, so the same inputs produce the same plan and
//! the same fingerprint. That is what lets an approval bind to a plan and
//! an apply prove it is still executing the plan that was approved.

use std::collections::BTreeMap;

use crate::domain::ownership::Sha256;
use crate::domain::profile::{ProfileId, resolve_destination};
use crate::domain::projection::Declaration;
use crate::plan::classify::{Classification, Signals, classify};
use crate::plan::decision::{self, AnswerSchema, Choice, Decision, Selections};
use crate::plan::evidence::{Ledger, Producer};
use crate::plan::finding::{Finding, FindingKind, StyleCandidate, detector};
use crate::plan::fingerprint::{Value, fingerprint};
use crate::plan::observe::{Observation, RecordedFile};
use crate::plan::operation::{Class, Operation, TargetPath, no_duplicate_destination};
use crate::plan::readiness::{Evaluation, Precondition, Readiness, Requirement, readiness};
use crate::plan::{
    Declared, DesiredState, Identity, ObservedState, PLAN_SCHEMA, Plan, Postcondition,
    ReleaseSource,
};

/// What the planner is given besides the observation.
#[derive(Debug, Clone)]
pub struct Inputs<'a> {
    /// What was observed at the target.
    pub observation: &'a Observation,
    /// What the destination release declares it lands.
    pub declaration: &'a Declaration,
    /// Each destination's bytes in the destination release, by source path.
    pub candidate: &'a BTreeMap<String, Sha256>,
    /// Each destination's bytes in the recorded release, where it could be
    /// read. Absent means the baseline was not observed.
    pub baseline: Option<&'a BTreeMap<String, Sha256>>,
    /// What the caller asked for, before resolution.
    pub selector: String,
    /// The release the selector resolved to.
    pub release: String,
    /// The digest over that release's content.
    pub release_sha256: Sha256,
    /// Where the release's facts came from.
    pub provenance: String,
    /// The registry checksum, where a registry served it.
    pub registry_checksum: Option<Sha256>,
    /// Whether the registry marks the release yanked.
    pub yanked: bool,
    /// What the destination release needs of this engine.
    pub compatibility: Option<&'a crate::plan::compatibility::Compatibility>,
    /// The interval the plan crosses, for the compatibility check.
    pub interval: Option<&'a crate::plan::compatibility::Interval>,
    /// What the interval's releases ask of this target.
    pub briefing: Option<&'a crate::plan::guidance::Briefing>,
    /// What one landing would write, where the caller computed it.
    ///
    /// The installer owns that computation, so the planner takes its
    /// answer rather than deriving a second one that could disagree.
    pub proposed: Option<&'a [Operation]>,
    /// What the operator selected.
    pub selections: &'a Selections,
    /// Paths no delivered gate judges, as the caller reserved them.
    pub reserve: &'a [String],
    /// What the budget gates measured at the target.
    ///
    /// The gates decide pass or fail; the planner reports a number over a
    /// cap as debt a corpus arrived with. One measurement, so a finding
    /// and a ceiling can never disagree about what a budget is.
    pub budget: &'a [crate::domain::debt::Measurement],
    /// The declarations a front carries, rendered for the fingerprint.
    ///
    /// A front's flags reach the record and no other operation, so a plan
    /// that recorded a different plan zone would otherwise share an id
    /// with one that did not.
    pub declared: Option<&'a str>,
    /// Whether the caller already settled the three declarations.
    ///
    /// A front carries them as flags, and an omitted flag keeps whatever
    /// is recorded. So the questions are answered before the plan is
    /// computed, and asking them again would ask an operator to repeat
    /// something they already said.
    pub declarations_settled: bool,
    /// The clock, as an input.
    pub now: String,
}

/// Compute one plan.
///
/// The order is fixed: classify from what was observed, read the findings,
/// offer the decisions, derive the operations the selected decisions allow,
/// evaluate the preconditions, and take the readiness from the worst of
/// them. The fingerprint is last, over exactly the parts that decide what
/// the apply would do.
#[must_use]
pub fn plan(inputs: &Inputs<'_>) -> Plan {
    let observation = inputs.observation;
    let (ledger, refs, release_ref) = ledger_of(inputs);

    let profile = chosen_profile(inputs);
    let classification = classification_of(inputs, profile);
    let findings = findings_of(inputs, profile, classification);
    let style_candidates = style_candidates_of(inputs, classification);
    let structural = findings
        .iter()
        .filter(|found| found.kind == FindingKind::Structural)
        .count();
    let mut decisions = decisions_of(inputs, classification, profile, structural, &findings);
    if let Some(briefing) = inputs.briefing {
        decisions.extend(briefing.decisions.iter().cloned());
    }
    let operations = inputs.proposed.map_or_else(
        || derived_operations(inputs, profile, classification, &decisions),
        <[Operation]>::to_vec,
    );

    let mut preconditions =
        preconditions_of(inputs, classification, &operations, &decisions, structural);
    if let (Some(held), Some(interval)) = (inputs.compatibility, inputs.interval) {
        preconditions.extend(crate::plan::compatibility::preconditions(held, interval));
    }
    if let Some(briefing) = inputs.briefing {
        preconditions.extend(briefing.preconditions.iter().cloned());
    }
    let verdict = readiness(&preconditions);

    let desired_state = DesiredState {
        selector: inputs.selector.clone(),
        release: inputs.release.clone(),
        release_sha256: inputs.release_sha256.clone(),
        profile,
        reserved: inputs.reserve.to_vec(),
        declared: Declared {
            payload_schema: inputs.declaration.payload_schema,
            managed: inputs.declaration.managed.len(),
            adopted: inputs.declaration.adopted.len(),
            sentinels: inputs.declaration.sentinels.len(),
        },
    };
    let observed_state = ObservedState {
        repository: observation.repository.clone(),
        installation: observation.installation.clone(),
        host: observation.host.clone(),
        corpus: observation.corpus.clone(),
        evidence_refs: refs,
    };
    let release = ReleaseSource {
        version: inputs.release.clone(),
        provenance: inputs.provenance.clone(),
        registry_checksum: inputs.registry_checksum.clone(),
        yanked: inputs.yanked,
        minimum_engine: inputs
            .compatibility
            .map(|held| held.minimum_engine.to_string()),
        guidance_coverage: inputs.interval.and_then(|interval| {
            inputs
                .briefing
                .map(|_| crate::plan::guidance::Coverage::Complete)
                .filter(|_| interval.recorded.is_some())
        }),
        guidance_steps: inputs
            .briefing
            .map(|briefing| briefing.applicable.clone())
            .unwrap_or_default(),
        guidance_excluded: inputs.briefing.map_or(0, |briefing| briefing.excluded),
        evidence_refs: vec![release_ref],
    };
    let digest = fingerprint(&inputs_projection(
        inputs,
        classification,
        &operations,
        &preconditions,
        &decisions,
    ));
    Plan {
        identity: Identity {
            schema: PLAN_SCHEMA.to_string(),
            plan_id: digest.to_string(),
            created_at: inputs.now.clone(),
            engine_version: env!("CARGO_PKG_VERSION").to_string(),
        },
        classification,
        findings,
        style_candidates,
        desired_state,
        observed_state,
        release,
        operations,
        preconditions,
        decisions,
        postconditions: postconditions_of(classification),
        evidence: ledger.items,
        readiness: verdict,
        input_fingerprint: digest,
    }
}

/// Everything the plan observed, and the references its sections cite.
fn ledger_of(inputs: &Inputs<'_>) -> (Ledger, Vec<String>, String) {
    let mut ledger = Ledger::new();
    let mut refs = Vec::new();
    refs.push(ledger.record(
        "target",
        "the target's working tree",
        Producer::Disk,
        &inputs.now,
        None,
        "walked, skipping version control and build output",
    ));
    if let Some(installation) = inputs.observation.installation.as_ref() {
        refs.push(ledger.record(
            "record",
            "the instance record",
            Producer::Record,
            &inputs.now,
            Some(installation.record_sha256.clone()),
            "read and parsed",
        ));
        if let Some(digest) = installation.declaration_sha256.as_ref() {
            refs.push(ledger.record(
                "declaration",
                "the project's own declaration",
                Producer::Declaration,
                &inputs.now,
                Some(digest.clone()),
                "read from the target",
            ));
        }
    }
    let release_ref = ledger.record(
        "release",
        "the destination release",
        Producer::Bundle,
        &inputs.now,
        Some(inputs.release_sha256.clone()),
        "read through the release seam",
    );
    refs.push(ledger.record(
        "host",
        "the resolved user-scope paths",
        Producer::Host,
        &inputs.now,
        None,
        "read from the environment",
    ));
    (ledger, refs, release_ref)
}

/// The profile this plan lands, where one is settled.
fn chosen_profile(inputs: &Inputs<'_>) -> Option<ProfileId> {
    if let Some(installation) = inputs.observation.installation.as_ref() {
        return Some(installation.profile);
    }
    match inputs
        .selections
        .get(decision::id::PROFILE)
        .map(String::as_str)
    {
        Some("codebase") => Some(ProfileId::Codebase),
        Some("knowledge-base") => Some(ProfileId::KnowledgeBase),
        _ => None,
    }
}

fn classification_of(inputs: &Inputs<'_>, profile: Option<ProfileId>) -> Classification {
    let observation = inputs.observation;
    let drifted = observation
        .installation
        .as_ref()
        .is_some_and(crate::plan::observe::Installation::drifted);
    let at_destination = observation
        .installation
        .as_ref()
        .is_some_and(|installed| installed.canon_version.to_string() == inputs.release);
    let _ = profile;
    classify(Signals {
        invalid: observation.invalid.is_some(),
        installed: observation.installation.is_some(),
        at_destination,
        drifted,
        settled: observation.corpus.settled(),
    })
}

/// Every finding the program can prove.
fn findings_of(
    inputs: &Inputs<'_>,
    profile: Option<ProfileId>,
    classification: Classification,
) -> Vec<Finding> {
    let mut findings = Vec::new();
    if classification != Classification::Migration {
        return findings;
    }
    // A number over a cap is debt the corpus arrived with, never a defect
    // in it. It records as a ceiling and comes down as documents shrink.
    findings.extend(inputs.budget.iter().filter_map(budget_finding));

    let corpus = &inputs.observation.corpus;
    // The foreign-root detector needs the profile, so it waits for the
    // decision rather than judging against a default.
    if let Some(profile) = profile
        && let Some(docs_root) = inputs.declaration.docs_root(profile)
    {
        for root in &corpus.populated_doc_roots {
            if root == docs_root.as_str() {
                continue;
            }
            if let Ok(path) = TargetPath::new(root) {
                findings.push(Finding {
                    kind: FindingKind::Structural,
                    path,
                    rule: detector::FOREIGN_DOCS_ROOT.to_string(),
                    statement: format!(
                        "{root} holds documents and the {profile} profile keeps them under {docs_root}"
                    ),
                    measurement: None,
                });
            }
        }
        if corpus.settled()
            && !corpus.has_specs_directory
            && let Ok(path) = TargetPath::new(&format!("{docs_root}/specs"))
        {
            findings.push(Finding {
                kind: FindingKind::Structural,
                path,
                rule: detector::NO_SPECS_DIRECTORY.to_string(),
                statement: "the corpus is settled and no specifications directory holds its rules"
                    .to_string(),
                measurement: None,
            });
        }
    }
    for path in &corpus.spec_without_rule_id {
        findings.push(Finding {
            kind: FindingKind::Structural,
            path: path.clone(),
            rule: detector::SPEC_WITHOUT_RULE_ID.to_string(),
            statement: "the document is shaped like a specification and defines no rule ID"
                .to_string(),
            measurement: None,
        });
    }
    for path in &corpus.ordinal_named {
        findings.push(Finding {
            kind: FindingKind::Structural,
            path: path.clone(),
            rule: detector::ORDINAL_FILENAME.to_string(),
            statement: "the document is named by its position rather than its subject".to_string(),
            measurement: None,
        });
    }
    for path in &corpus.records_outside_decisions {
        findings.push(Finding {
            kind: FindingKind::Structural,
            path: path.clone(),
            rule: detector::RECORD_OUTSIDE_DECISIONS.to_string(),
            statement: "the decision record sits outside a decisions directory".to_string(),
            measurement: None,
        });
    }
    findings
}

/// Documents written before the instance, named and never judged.
fn style_candidates_of(inputs: &Inputs<'_>, classification: Classification) -> Vec<StyleCandidate> {
    if classification != Classification::Migration {
        return Vec::new();
    }
    inputs
        .observation
        .corpus
        .documents
        .iter()
        .map(|path| StyleCandidate {
            path: path.clone(),
            reason: "the document predates the instance, and no gate judges its prose".to_string(),
        })
        .collect()
}

fn choice(id: &str, consequence: &str) -> Choice {
    Choice {
        id: id.to_string(),
        consequence: consequence.to_string(),
    }
}

/// Every decision the plan is waiting on, in dependency order.
fn decisions_of(
    inputs: &Inputs<'_>,
    classification: Classification,
    profile: Option<ProfileId>,
    structural: usize,
    findings: &[Finding],
) -> Vec<Decision> {
    let mut decisions = Vec::new();
    let selected = |id: &str| inputs.selections.get(id).cloned();

    if inputs.observation.installation.is_none()
        && matches!(
            classification,
            Classification::Setup | Classification::Migration
        )
    {
        decisions.push(Decision {
            id: decision::id::PROFILE.to_string(),
            question: "which profile does this repository take?".to_string(),
            schema: AnswerSchema::Choice {
                choices: vec![
                    choice("codebase", "records live under docs/"),
                    choice("knowledge-base", "records live under _docs/"),
                ],
            },
            depends_on: Vec::new(),
            selected: selected(decision::id::PROFILE),
        });
    }

    // Everything below is profile-relative, so it waits for the profile.
    if profile.is_some() {
        if inputs.observation.installation.is_none() && !inputs.declarations_settled {
            let depends: Vec<String> = if decisions
                .iter()
                .any(|held| held.id == decision::id::PROFILE)
            {
                vec![decision::id::PROFILE.to_string()]
            } else {
                Vec::new()
            };
            decisions.push(Decision {
                id: decision::id::PLAN_ZONE.to_string(),
                question: "where does the planning tool write its entry documents?".to_string(),
                schema: AnswerSchema::ChoiceOrValue {
                    choices: vec![
                        choice("env", "wherever the plan-zone variable points"),
                        choice("none", "the project keeps no plan zone"),
                    ],
                    prefixes: vec!["project:".to_string(), "untracked:".to_string()],
                },
                depends_on: depends.clone(),
                selected: selected(decision::id::PLAN_ZONE),
            });
            decisions.push(Decision {
                id: decision::id::DOCS_SCRATCH.to_string(),
                question: "where does material that is not a statement yet stage?".to_string(),
                schema: AnswerSchema::ChoiceOrValue {
                    choices: vec![choice("none", "the project stages nothing")],
                    // A recorded scratch is a path. The variable overrides
                    // it at read time, so there is no `env` to record.
                    prefixes: vec!["project:".to_string(), "external:".to_string()],
                },
                depends_on: depends.clone(),
                selected: selected(decision::id::DOCS_SCRATCH),
            });
            decisions.push(Decision {
                id: decision::id::WRITING_STYLE.to_string(),
                question: "which writing source does the project select?".to_string(),
                schema: AnswerSchema::ChoiceOrValue {
                    choices: vec![
                        choice("builtin", "this convention's own chapter, served offline"),
                        choice("none", "no route and no conversion obligation"),
                    ],
                    prefixes: vec!["project:".to_string()],
                },
                depends_on: depends,
                selected: selected(decision::id::WRITING_STYLE),
            });
        }

        if classification == Classification::Migration {
            decisions.extend(migration_decisions(inputs, structural, findings));
        }
    }

    if inputs.yanked {
        decisions.push(Decision {
            id: decision::id::ACCEPT_YANKED.to_string(),
            question: format!(
                "the registry marks {} yanked; land it anyway?",
                inputs.release
            ),
            schema: AnswerSchema::Choice {
                choices: vec![
                    choice("accept", "the release lands, yanked and named as such"),
                    choice("refuse", "nothing lands; name another release"),
                ],
            },
            depends_on: Vec::new(),
            selected: selected(decision::id::ACCEPT_YANKED),
        });
    }
    decisions
}

/// What a migration asks before it moves anything.
fn migration_decisions(
    inputs: &Inputs<'_>,
    structural: usize,
    findings: &[Finding],
) -> Vec<Decision> {
    let selected = |id: &str| inputs.selections.get(id).cloned();
    let mut decisions = Vec::new();
    let mut choices = vec![choice(
        "sweep",
        "every durable fact moves into its owner, and the old convention retires",
    )];
    // Incremental is offered only where nothing structural would
    // make two conventions coexist.
    if structural == 0 {
        choices.push(choice(
            "incremental",
            "each document converts the next time somebody edits it",
        ));
    }
    decisions.push(Decision {
        id: decision::id::MIGRATION_SCOPE.to_string(),
        question: "how much of the corpus moves?".to_string(),
        schema: AnswerSchema::Choice { choices },
        depends_on: vec![decision::id::PROFILE.to_string()],
        selected: selected(decision::id::MIGRATION_SCOPE),
    });
    if findings
        .iter()
        .any(|found| found.kind == FindingKind::Budget)
    {
        decisions.push(Decision {
            id: decision::id::DEBT_BASELINE.to_string(),
            question: "are the inherited violations recorded as debt?".to_string(),
            schema: AnswerSchema::Choice {
                choices: vec![
                    choice(
                        "record",
                        "each inherited violation becomes a ceiling that only comes down",
                    ),
                    choice(
                        "skip",
                        "nothing is recorded, and each violation fails its gate",
                    ),
                ],
            },
            depends_on: vec![decision::id::MIGRATION_SCOPE.to_string()],
            selected: selected(decision::id::DEBT_BASELINE),
        });
    }
    decisions
}

/// Every write the plan derives for itself, where the caller gave none.
///
/// Until the profile is chosen, every destination is unknown, so the
/// planner offers no operation rather than one against a default nobody
/// selected.
fn derived_operations(
    inputs: &Inputs<'_>,
    profile: Option<ProfileId>,
    classification: Classification,
    decisions: &[Decision],
) -> Vec<Operation> {
    if profile.is_none() {
        return Vec::new();
    }
    // A first landing is a whole projection: the managed and adopted files,
    // the two marked regions, and the record. The caller derives that from
    // one computation and hands it over. Deriving a partial one here would
    // offer an operator a landing that leaves a target the verifier cannot
    // read, so where the caller gave none there is none.
    if matches!(
        classification,
        Classification::Setup | Classification::Migration
    ) {
        return Vec::new();
    }
    operations_of(inputs, profile, classification, decisions)
}

/// Every write the plan will make.
fn operations_of(
    inputs: &Inputs<'_>,
    profile: Option<ProfileId>,
    classification: Classification,
    decisions: &[Decision],
) -> Vec<Operation> {
    let mut operations = Vec::new();
    if matches!(
        classification,
        Classification::Invalid | Classification::Current
    ) {
        return operations;
    }
    let Some(profile) = profile else {
        return operations;
    };
    let Some(docs_root) = inputs.declaration.docs_root(profile) else {
        return operations;
    };
    let held = crate::plan::observe::held_by_path(inputs.observation.installation.as_ref());
    let recorded: BTreeMap<&str, &RecordedFile> = inputs
        .observation
        .installation
        .iter()
        .flat_map(|installation| installation.adopted.iter())
        .map(|file| (file.path.as_str(), file))
        .collect();

    for projection in &inputs.declaration.managed {
        let Some(after) = inputs.candidate.get(&projection.source) else {
            continue;
        };
        let Ok(path) = TargetPath::new(&projection.destination) else {
            continue;
        };
        let before = held.get(path.as_str()).cloned();
        if before.as_ref() == Some(after) {
            continue;
        }
        operations.push(Operation::WriteFile {
            path,
            class: Class::Managed,
            before,
            after: after.clone(),
        });
    }

    for projection in &inputs.declaration.adopted {
        let Some(seed) = inputs.candidate.get(&projection.source) else {
            continue;
        };
        let destination = resolve_destination(&projection.destination, docs_root);
        let Ok(path) = TargetPath::new(destination.as_str()) else {
            continue;
        };
        match held.get(path.as_str()) {
            // An adopted file the target holds is the project's. Only the
            // baseline it is read against moves.
            Some(current) => {
                let baseline_before = recorded
                    .get(path.as_str())
                    .and_then(|file| file.baseline.clone())
                    .or_else(|| {
                        inputs
                            .baseline
                            .and_then(|held| held.get(&projection.source).cloned())
                    });
                let Some(baseline_before) = baseline_before else {
                    continue;
                };
                if &baseline_before == seed {
                    continue;
                }
                operations.push(Operation::KeepFile {
                    path,
                    held: current.clone(),
                    baseline_before,
                    baseline_after: seed.clone(),
                });
            }
            None => operations.push(Operation::WriteFile {
                path,
                class: Class::Adopted,
                before: None,
                after: seed.clone(),
            }),
        }
    }

    // The two operator-invoked writes into adopted state appear only when
    // their decision is selected, never because a version moved.
    let selected = |id: &str| {
        decisions
            .iter()
            .find(|decision| decision.id == id)
            .and_then(|decision| decision.selected.as_deref())
    };
    // The debt write waits for the budget findings that give it content:
    // an operation whose bytes nothing carries is an operation an apply
    // could not execute, and the plan does not offer one.
    let _ = selected(decision::id::DEBT_BASELINE);
    operations
}

/// Everything that must hold before the apply.
fn preconditions_of(
    inputs: &Inputs<'_>,
    classification: Classification,
    operations: &[Operation],
    decisions: &[Decision],
    structural: usize,
) -> Vec<Precondition> {
    let mut preconditions: Vec<Precondition> = Vec::new();
    macro_rules! require {
        ($id:expr, $statement:expr, $requirement:expr, $evaluation:expr) => {
            preconditions.push(Precondition {
                id: ($id).to_string(),
                statement: $statement,
                requirement: $requirement,
                evaluation: $evaluation,
                resolved_by: None,
                evidence_refs: Vec::new(),
            });
        };
    }

    if let Some(reason) = inputs.observation.invalid.as_ref() {
        require!(
            "record-is-readable",
            "the instance record parses".to_string(),
            Requirement::Required,
            Evaluation::Unsatisfied {
                reason: reason.clone(),
            }
        );
    }

    let waiting = decision_preconditions(decisions);

    let edited = edited_managed_files(inputs);
    if !edited.is_empty() {
        require!(
            "managed-files-are-unedited",
            "every managed file still holds what the record says".to_string(),
            Requirement::Required,
            Evaluation::Unsatisfied {
                reason: edited.join("; "),
            }
        );
    }

    if inputs.baseline.is_none() && inputs.observation.installation.is_some() {
        require!(
            "baseline-is-readable",
            "the recorded release's bundle can be read for baselines".to_string(),
            Requirement::Advisory,
            Evaluation::NotObserved {
                reason:
                    "the recorded release's bundle was not read, so an adopted baseline cannot move"
                        .to_string(),
            }
        );
    }

    // An incremental migration over a structural finding would start a
    // second convention beside the first, which is the harm the sweep
    // exists to stop.
    let scope = decisions
        .iter()
        .find(|decision| decision.id == decision::id::MIGRATION_SCOPE)
        .and_then(|decision| decision.selected.as_deref());
    if classification == Classification::Migration && scope == Some("incremental") && structural > 0
    {
        require!(
            "incremental-scope-has-no-structural-finding",
            "an incremental migration leaves no structural finding behind".to_string(),
            Requirement::Required,
            Evaluation::Unsatisfied {
                reason: format!(
                    "{structural} structural finding(s) would make two conventions coexist"
                ),
            }
        );
    }

    preconditions.extend(waiting);

    if let Err(clash) = no_duplicate_destination(operations) {
        require!(
            "no-destination-is-written-twice",
            "each destination is written by at most one operation".to_string(),
            Requirement::Required,
            Evaluation::Unsatisfied {
                reason: clash.to_string(),
            }
        );
    }
    preconditions
}

/// One measurement that is over its budget, as a finding.
///
/// A count over its cap and a condition that does not hold are both debt
/// the corpus arrived with. The second carries no number, so it reports as
/// one against zero: the dimension is the fact, and what the ceiling
/// records is that the exception exists.
fn budget_finding(measured: &crate::domain::debt::Measurement) -> Option<Finding> {
    let path = TargetPath::new(&measured.path).ok()?;
    let (statement, found, cap) = match measured.value {
        crate::domain::debt::Measured::Count { value, budget } if value > budget => (
            format!(
                "{} is {value} {} against a budget of {budget}",
                measured.path, measured.dimension
            ),
            value as u64,
            budget as u64,
        ),
        crate::domain::debt::Measured::Flag(true) => (
            format!("{} carries {}", measured.path, measured.dimension),
            1,
            0,
        ),
        _ => return None,
    };
    Some(Finding {
        kind: FindingKind::Budget,
        path,
        rule: measured.gate.to_string(),
        statement,
        measurement: Some(crate::plan::finding::Measurement {
            dimension: measured.dimension.to_string(),
            found,
            cap,
        }),
    })
}

/// Every managed file the target no longer holds as the record says.
///
/// Collected in one pass rather than refused one at a time, so an operator
/// sees the whole conflict set in one run.
fn edited_managed_files(inputs: &Inputs<'_>) -> Vec<String> {
    let mut edited = Vec::new();
    let Some(installation) = inputs.observation.installation.as_ref() else {
        return edited;
    };
    for file in &installation.managed {
        match file.held.as_ref() {
            Some(found) if found == &file.recorded => {}
            Some(_) => edited.push(format!("{} was edited", file.path)),
            None => edited.push(format!("{} is gone", file.path)),
        }
    }
    // A marked region is managed too. The next landing re-splices it, so
    // an edit inside the markers would be lost. Every byte outside them is
    // the project's own and is not compared.
    for block in &installation.blocks {
        match block.held.as_ref() {
            Some(found) if found == &block.recorded => {}
            Some(_) => edited.push(format!("the managed block in {} was edited", block.path)),
            None => edited.push(format!("the managed block in {} is gone", block.path)),
        }
    }
    edited
}

/// One precondition per decision the operator has not answered.
fn decision_preconditions(decisions: &[Decision]) -> Vec<Precondition> {
    decisions
        .iter()
        .map(|decision| Precondition {
            id: format!("decision:{}", decision.id),
            statement: decision.question.clone(),
            requirement: Requirement::DecisionRequired,
            evaluation: decision.selected.as_ref().map_or_else(
                || Evaluation::Unsatisfied {
                    reason: "the operator has not answered it".to_string(),
                },
                |_| Evaluation::Satisfied,
            ),
            resolved_by: Some(decision.id.clone()),
            evidence_refs: Vec::new(),
        })
        .collect()
}

/// What the apply proves once it has finished.
fn postconditions_of(classification: Classification) -> Vec<Postcondition> {
    if classification == Classification::Invalid {
        return Vec::new();
    }
    vec![
        Postcondition {
            id: "record-matches-the-tree".to_string(),
            statement: "every operation's destination holds the digest the plan named".to_string(),
        },
        Postcondition {
            id: "verification-passes".to_string(),
            statement: "sdd verify reports OK against the target".to_string(),
        },
    ]
}

/// Exactly the parts that decide what the apply would do.
///
/// Timestamps, presentation text, and advisory evidence are out: a plan
/// recomputed a second later must carry the same identity, or an approval
/// could never survive the moment it was given.
fn inputs_projection(
    inputs: &Inputs<'_>,
    classification: Classification,
    operations: &[Operation],
    preconditions: &[Precondition],
    decisions: &[Decision],
) -> Value {
    let operations = Value::List(
        operations
            .iter()
            // The record carries the moment of installation, which is
            // exactly what the fingerprint must exclude, so its digest
            // cannot stand for it. What it uniquely says is projected
            // below instead: dropping the whole operation would let two
            // plans that record different declarations share one id.
            .filter(|operation| !matches!(operation, Operation::WriteRecord { .. }))
            .map(|operation| {
                Value::map([
                    ("kind", Value::text(operation.kind())),
                    ("path", Value::text(operation.path().as_str())),
                    (
                        "before",
                        Value::maybe(operation.before().map(std::string::ToString::to_string)),
                    ),
                    (
                        "after",
                        Value::maybe(operation.after().map(std::string::ToString::to_string)),
                    ),
                ])
            })
            .collect(),
    );
    // Only a precondition that can change readiness or operations belongs
    // here. An advisory one cannot, by definition.
    let gates = Value::List(
        preconditions
            .iter()
            .filter(|precondition| precondition.requirement != Requirement::Advisory)
            .map(|precondition| {
                Value::map([
                    ("id", Value::text(precondition.id.as_str())),
                    (
                        "state",
                        Value::text(match precondition.evaluation {
                            Evaluation::Satisfied => "satisfied",
                            Evaluation::NotObserved { .. } => "not-observed",
                            Evaluation::Unsatisfied { .. } => "unsatisfied",
                        }),
                    ),
                ])
            })
            .collect(),
    );
    let selected = Value::Map(
        decisions
            .iter()
            .filter_map(|decision| {
                decision
                    .selected
                    .as_ref()
                    .map(|answer| (decision.id.clone(), Value::text(answer.as_str())))
            })
            .collect(),
    );
    Value::map([
        ("schema", Value::text(PLAN_SCHEMA)),
        ("classification", Value::text(classification.as_str())),
        ("release", Value::text(inputs.release.as_str())),
        (
            "release_sha256",
            Value::text(inputs.release_sha256.as_str()),
        ),
        (
            "target",
            Value::text(inputs.observation.repository.root.as_str()),
        ),
        (
            "record",
            Value::maybe(
                inputs
                    .observation
                    .installation
                    .as_ref()
                    .map(|installation| installation.record_sha256.to_string()),
            ),
        ),
        (
            "declaration",
            Value::maybe(
                inputs
                    .observation
                    .installation
                    .as_ref()
                    .and_then(|installation| installation.declaration_sha256.as_ref())
                    .map(std::string::ToString::to_string),
            ),
        ),
        ("operations", operations),
        ("preconditions", gates),
        ("decisions", selected),
        ("declared", declared_projection(inputs)),
    ])
}

/// What the record will say that no other operation carries.
///
/// The record's own digest cannot go in the fingerprint: it carries the
/// moment of installation, and a plan recomputed a second later would
/// stop matching itself. So the fields that decide what the record says
/// are projected on their own, and the timestamp alone stays out.
fn declared_projection(inputs: &Inputs<'_>) -> Value {
    Value::map([
        (
            "profile",
            Value::maybe(
                inputs
                    .selections
                    .get(crate::plan::decision::id::PROFILE)
                    .cloned(),
            ),
        ),
        (
            "reserved",
            Value::List(
                inputs
                    .reserve
                    .iter()
                    .map(|path| Value::text(path.as_str()))
                    .collect(),
            ),
        ),
        (
            "record",
            Value::maybe(inputs.declared.map(std::string::ToString::to_string)),
        ),
    ])
}

/// Whether a plan may be applied, for a caller that has only the verdict.
#[must_use]
pub const fn is_ready(verdict: Readiness) -> bool {
    matches!(verdict, Readiness::Ready)
}