Skip to main content

zenkey_model/desired/
v2.rs

1//! `desired.v2`: desired documents, on a wire a far target can afford
2//! (`spec/profiles/desired/v2.md`, #986's J2).
3//!
4//! The profile's session-free half. It restates `desired.v1` by reference,
5//! so what did not change is [`super`]'s, used as it stands: the binding
6//! (§2.3), a document's comparison and its own revision (§2.7), the state
7//! machine's rules (`super::machine`) and §5's judges. What it replaces
8//! is here:
9//!
10//! ```text
11//! version_text(v) / parse_version(text)     ─▶ <run>/<seq>: the in-band stamp, 4 or 8 hex digits and a decimal  §2.4
12//! declaration(kind, template, …, uses)      ─▶ v1 §2.2's reading, and horizon_v1 checked last                   §2.2
13//! report_declaration(resource, roles, others) ─▶ declared {role | param, tables} │ invalid [reasons] │ not this profile's  §2.10
14//! Tables::place(pointer) / line(text)       ─▶ an index, the nearest listed ancestor's, or out_of_range        §2.10
15//! Tables::pointer(index) / detail(index)    ─▶ the word, the number past the table, or out_of_range            §2.10
16//! Report::write() / put(stamp)              ─▶ the packed record (tag 12), and its put's payload                §2.10, §3
17//! read(tag, bytes)                          ─▶ Read {fields, findings, report} │ core §7.6's refusal            §2.10
18//! Fields::check()                           ─▶ escape │ run_fields, observed_outcome, refusal, source, in_force, …  §2.10
19//! Target::observe(sample)                   ─▶ act │ revert │ adopted │ held │ unstamped │ same_version │ older │ confirmed  §2.6–§2.9
20//! Target::observe_no_entry(run, asof)       ─▶ revert │ held │ older │ no_verdict                              §2.8
21//! Target::unchanged(sent)                   ─▶ a conditional read answered unchanged: its last-known confirmed  §2.5, §2.9
22//! Target::finish(ended) / call() / held()   ─▶ the report updated; the stamp a conditional read sends         §2.5, §2.7
23//! Watch::heartbeat(beat, holds)             ─▶ revision │ refused │ older │ no_section │ unmoved │ outstanding │ read  §2.5
24//! Watch::answer(answer, holds) / heard(…)   ─▶ what the target expects of its author's section                 §2.5
25//! report_at(target, iface, role, resources) ─▶ none │ two │ invalid [reasons] │ at {key, tables}; then found(reply)  §2.10
26//! converged(target, author)                 ─▶ §5's first question, by run and seq, a snapshot with no entry read  §2.17
27//! super::refused / last_known / in_force    ─▶ §5's other three, over a `Read` as over v1's `Report`
28//! ```
29//!
30//! There is no I/O and no clock here. A target's runtime subscribes, reads
31//! its slice (conditionally, on a period or when its [`Watch`] says so),
32//! hands each version to [`Target::observe`], each snapshot with no entry
33//! to [`Target::observe_no_entry`] and each unchanged answer to
34//! [`Target::unchanged`], performs each [`Act`], tells [`Target::finish`]
35//! how it ended, and puts [`Target::report`] whenever it changes.
36
37use std::collections::BTreeMap;
38use std::sync::OnceLock;
39
40use serde_json::{Map, Value, json};
41
42use super::{
43    ActKind, Answer, Content, Finding, Invalid, Judged, Mutation, Reason, Reported, Seen, Source,
44    TargetReading, Via, machine,
45};
46use crate::authoring::{Kind, ParamType};
47use crate::contract::{Body, Contract, Resource};
48use crate::grammar::{self, Addr, IfaceId, Key, KindToken};
49use crate::heartbeat::Digest;
50use crate::packed::{self, Layout, ReadRefusal, Record, WriteRefusal};
51use crate::schema::TypeId;
52use crate::template::{Bindings, Template};
53use crate::wire::{Envelope, Run, Seq, Stamp, Tag};
54use crate::words;
55
56/// The profile's id, as a contract lists it in `uses`.
57pub const PROFILE: &str = "desired.v2";
58
59/// `desired.report` (§4): the role a report resource reports.
60pub const REPORT_KEY: &str = "desired.report";
61/// `desired.pointers` (§4): the places a refusal's `pointer` indexes.
62pub const POINTERS: &str = "desired.pointers";
63/// `desired.details` (§4): the lines a refusal's `detail` indexes.
64pub const DETAILS: &str = "desired.details";
65
66/// The published vocabulary (§4): the keys under `desired.` W105 reads for
67/// a contract that lists `desired.v2` (core §10, Appendix D).
68pub const VOCABULARY: &[&str] = &["target_param", "report", "pointers", "details"];
69
70/// The standard schema's stem (§3): `desired.v2.json`.
71pub const SCHEMA_STEM: &str = "desired.v2";
72/// The report's type name in the standard schema (§2.10, §3).
73pub const REPORT: &str = "Report";
74
75/// The standard schema's artifact ids the profile publishes (§3), oldest
76/// first. A packed `Report` of one of these artifacts is the profile's.
77pub const PUBLISHED: &[&str] =
78    &["sha256:1ac893a1cb14a102cc1b01ea526a317b19390a8ed6c40707f08754f4429532dd"];
79
80/// The `Report`'s tag (§3, core §7.6): CH is `0x0c` under a 16-bit run of
81/// its target, `0x1c` under a 32-bit one.
82pub const TAG: u8 = 12;
83
84/// The greatest revision a document may carry (§2.4): a report holds it in
85/// 32 bits.
86pub const MAX_REVISION: u64 = 4_294_967_295;
87
88/// How many runs a target remembers (§2.6): `desired.v1`'s sixteen ids.
89pub const REMEMBERED_RUNS: usize = super::REMEMBERED_IDS;
90
91/// The reserved word of `pointer` and `detail` (§2.10, §3).
92pub use crate::words::OUT_OF_RANGE;
93
94/// The greatest index a table holds (§2.10): 255 entries, from 0.
95pub const MAX_INDEX: u8 = 254;
96
97/// Whether `id` is one of the standard schema's published artifact ids.
98#[must_use]
99pub fn is_published(id: &str) -> bool {
100    PUBLISHED.contains(&id)
101}
102
103/// Whether a contract lists `desired.v2` in `uses`: its desired resources
104/// and its report resources are of this major (§0).
105#[must_use]
106pub fn uses_v2(c: &Contract) -> bool {
107    words::uses(c, PROFILE)
108}
109
110/// Which major of the profile a revision uses (§2.18): a target and a tool
111/// read it per author.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
113pub enum Major {
114    V1,
115    V2,
116}
117
118impl Major {
119    /// The major `c` lists in `uses`, `None` when it lists neither.
120    #[must_use]
121    pub fn of(c: &Contract) -> Option<Major> {
122        if uses_v2(c) {
123            Some(Major::V2)
124        } else if c.uses.iter().any(|u| u.to_string() == super::PROFILE) {
125            Some(Major::V1)
126        } else {
127            None
128        }
129    }
130}
131
132// --- §2.4: the version -----------------------------------------------------------
133
134/// One mutation of a document's key (§2.4): its in-band stamp, the run,
135/// with its width, and the seq. Two are the same when both are equal.
136pub type Version = Stamp;
137
138/// A version as §2.4 writes it: the run as a descriptor writes one (4
139/// lowercase hexadecimal digits for a 16-bit run, 8 for a 32-bit one), `/`,
140/// and the seq in decimal without leading zeros.
141#[must_use]
142pub fn version_text(v: Version) -> String {
143    format!("{}/{}", v.run, v.seq.get())
144}
145
146/// [`version_text`] read back. `None` for any other spelling: a run that
147/// is not 4 or 8 lowercase hexadecimal digits, a seq with a leading zero,
148/// a sign or a digit too many, or one above 16,777,215.
149#[must_use]
150pub fn parse_version(s: &str) -> Option<Version> {
151    let (run, seq) = s.split_once('/')?;
152    let digits = !seq.is_empty() && seq.len() <= 8 && seq.bytes().all(|b| b.is_ascii_digit());
153    if !digits || (seq.len() > 1 && seq.starts_with('0')) {
154        return None;
155    }
156    Some(Stamp {
157        run: Run::from_hex(run)?,
158        seq: Seq::new(seq.parse().ok()?)?,
159    })
160}
161
162// --- §2.2: the desired resource's declaration ---------------------------------
163
164/// Reads a desired resource's declaration under this major (§2.2): v1
165/// §2.2's reading, word for word ([`super::declaration`]), and one reason
166/// more, checked last and skipped where the resource is `not_state`:
167/// [`Invalid::HorizonV1`], a `freshness.ttl_s` above 0 in a revision whose
168/// `uses` does not list `freshness.v2`. `uses` says whether the revision
169/// lists a profile.
170#[must_use]
171pub fn declaration(
172    kind: Kind,
173    template: &Template,
174    params: &BTreeMap<String, ParamType>,
175    annotations: &BTreeMap<String, Value>,
176    uses: impl Fn(&str) -> bool,
177) -> super::Declaration {
178    let v1 = super::declaration(kind, template, params, annotations);
179    // The horizon core §4.3's table reads: a state's, above 0.
180    let horizon_v1 = kind == Kind::State
181        && crate::freshness::horizon(kind, annotations).ttl().is_some()
182        && !uses(crate::freshness::PROFILE_V2);
183    match v1 {
184        super::Declaration::NotThisProfiles => v1,
185        super::Declaration::Declared(_) if !horizon_v1 => v1,
186        super::Declaration::Declared(_) => super::Declaration::Invalid(vec![Invalid::HorizonV1]),
187        super::Declaration::Invalid(mut why) => {
188            if horizon_v1 {
189                why.push(Invalid::HorizonV1);
190            }
191            super::Declaration::Invalid(why)
192        }
193    }
194}
195
196/// [`declaration`] of a resource of a contract.
197#[must_use]
198pub fn declaration_of(c: &Contract, r: &Resource) -> super::Declaration {
199    declaration(r.kind, &r.template, &r.params, &r.annotations, |p| {
200        c.uses.iter().any(|u| u.to_string() == p)
201    })
202}
203
204// --- §2.10: the report resource's declaration ----------------------------------
205
206/// What a `desired.report` value names (§2.10).
207#[derive(Debug, Clone, PartialEq, Eq, Hash)]
208pub enum Names {
209    /// A role's name: the resource's one member is that role's report.
210    Role(String),
211    /// The resource's one parameter, written in braces: each member is the
212    /// report of the role its key's value of that parameter names.
213    Param(String),
214}
215
216impl Names {
217    /// Reads a `desired.report` value: a string in one of the two forms, a
218    /// name of at least one character and no brace, or such a name in
219    /// braces. `None` for a value in neither form, which names nothing.
220    #[must_use]
221    pub fn read(v: &Value) -> Option<Names> {
222        let s = v.as_str()?;
223        let name = |n: &str| !n.is_empty() && !n.contains(['{', '}']);
224        if let Some(inner) = s.strip_prefix('{').and_then(|x| x.strip_suffix('}')) {
225            return name(inner).then(|| Names::Param(inner.to_owned()));
226        }
227        name(s).then(|| Names::Role(s.to_owned()))
228    }
229
230    /// Whether the value can report `role`: by its name, or by a parameter
231    /// in braces.
232    #[must_use]
233    pub fn names(&self, role: &str) -> bool {
234        match self {
235            Names::Role(r) => r == role,
236            Names::Param(_) => true,
237        }
238    }
239}
240
241/// Why a report resource's declaration is invalid (§2.10), in the order
242/// checked.
243#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
244pub enum ReportInvalid {
245    /// The resource is not `state` or `@state`.
246    NotState,
247    /// Not a string in one of the two forms. No later check reads the
248    /// value.
249    Value,
250    /// A name that is no requirement of the contract.
251    NotARole,
252    /// Braces around a name that is no parameter of the template.
253    NotAParam,
254    /// Braces around a rest parameter.
255    RestParam,
256    /// A template parameter the value does not name.
257    ParamNotRole,
258    /// The resource's type is not the profile's `Report` (§3).
259    NotReport,
260    /// `desired.pointers` is no table of places.
261    Pointers,
262    /// `desired.details` is no table of lines.
263    Details,
264    /// Another report resource of the contract names the same role, or one
265    /// of the two names a parameter.
266    TwoReports,
267}
268
269impl ReportInvalid {
270    /// The fixture's token.
271    #[must_use]
272    pub fn as_str(self) -> &'static str {
273        match self {
274            Self::NotState => "not_state",
275            Self::Value => "value",
276            Self::NotARole => "not_a_role",
277            Self::NotAParam => "not_a_param",
278            Self::RestParam => "rest_param",
279            Self::ParamNotRole => "param_not_role",
280            Self::NotReport => "not_report",
281            Self::Pointers => "pointers",
282            Self::Details => "details",
283            Self::TwoReports => "two_reports",
284        }
285    }
286
287    /// What it says, for a linter's line.
288    #[must_use]
289    pub fn says(self) -> &'static str {
290        match self {
291            Self::NotState => "a report is state of its target",
292            Self::Value => {
293                "desired.report is a role's name, or the resource's one parameter in braces"
294            }
295            Self::NotARole => "the name is no requirement of the contract",
296            Self::NotAParam => "the name in braces is no parameter of the template",
297            Self::RestParam => "a rest parameter cannot name a role",
298            Self::ParamNotRole => {
299                "a template parameter the value does not name: one report per role"
300            }
301            Self::NotReport => "a report resource's type is the profile's packed Report",
302            Self::Pointers => {
303                "desired.pointers is 1 to 255 JSON Pointers, the first \"\", none twice"
304            }
305            Self::Details => "desired.details is at most 255 lines of at least one character",
306            Self::TwoReports => "another report resource of the contract can report the same role",
307        }
308    }
309}
310
311impl std::fmt::Display for ReportInvalid {
312    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313        f.write_str(self.says())
314    }
315}
316
317/// An index into one of a report resource's two tables, as a report
318/// carries it (§2.10, §3): a writer refuses a place above [`MAX_INDEX`],
319/// 255 being `out_of_range`'s code. What it reads as, with the table a
320/// reader holds, is a [`Word`]: the entry, the number past the table or
321/// with no revision of the target's contract in hand, or `out_of_range`
322/// (§2.10, "A reader reads an index"). The mechanism is [`crate::words`]'s,
323/// which `health.v2` shares.
324pub use crate::words::{Index, Word};
325
326/// The word of `index` in `table`, `None` when the reader holds no
327/// revision of the target's contract (§2.10, "A reader reads an index").
328#[must_use]
329pub fn word(table: Option<&[String]>, index: Index) -> Word<'_> {
330    words::read(table, index)
331}
332
333/// A report resource's two tables (§2.10), as a reader holds them.
334#[derive(Debug, Clone, PartialEq, Eq)]
335pub struct Tables {
336    /// `desired.pointers`: `[""]` for a resource without the key.
337    pub pointers: Vec<String>,
338    /// `desired.details`: empty for a resource without the key.
339    pub details: Vec<String>,
340}
341
342impl Default for Tables {
343    fn default() -> Self {
344        Self {
345            pointers: vec![String::new()],
346            details: Vec::new(),
347        }
348    }
349}
350
351fn index_of(i: usize) -> Index {
352    Index::at(i, MAX_INDEX)
353}
354
355impl Tables {
356    /// Where a refusal points, as a target writes it (§2.10): a place the
357    /// table holds its index, and one it does not hold its nearest listed
358    /// ancestor, the longest listed pointer other than `""` that the place
359    /// continues with a `/`. With none, `out_of_range`: index 0 says the
360    /// document itself is refused, never "somewhere".
361    #[must_use]
362    pub fn place(&self, pointer: &str) -> Index {
363        if let Some(i) = self.pointers.iter().position(|p| p == pointer) {
364            return index_of(i);
365        }
366        self.pointers
367            .iter()
368            .enumerate()
369            .filter(|(_, p)| {
370                !p.is_empty()
371                    && pointer
372                        .strip_prefix(p.as_str())
373                        .is_some_and(|rest| rest.starts_with('/'))
374            })
375            .max_by_key(|(_, p)| p.len())
376            .map_or(Index::OutOfRange, |(i, _)| index_of(i))
377    }
378
379    /// A refusal's line, as a target writes it (§2.10): its index, or
380    /// `out_of_range` for a line the table does not hold, whose words stay
381    /// in the target's log.
382    #[must_use]
383    pub fn line(&self, text: &str) -> Index {
384        words::write(&self.details, text, MAX_INDEX)
385    }
386
387    /// The place `index` names.
388    #[must_use]
389    pub fn pointer(&self, index: Index) -> Word<'_> {
390        word(Some(&self.pointers), index)
391    }
392
393    /// The line `index` names.
394    #[must_use]
395    pub fn detail(&self, index: Index) -> Word<'_> {
396        word(Some(&self.details), index)
397    }
398}
399
400/// Whether a string is a JSON Pointer (RFC 6901): empty, or starting with
401/// `/`, every `~` followed by `0` or `1`.
402fn is_json_pointer(s: &str) -> bool {
403    if !(s.is_empty() || s.starts_with('/')) {
404        return false;
405    }
406    let b = s.as_bytes();
407    (0..b.len()).all(|i| b[i] != b'~' || matches!(b.get(i + 1), Some(b'0' | b'1')))
408}
409
410/// `desired.pointers` read (§2.10): 1 to 255 JSON Pointers, the first
411/// `""`, none twice.
412fn read_pointers(v: &Value) -> Option<Vec<String>> {
413    words::list(v, usize::from(MAX_INDEX) + 1, is_json_pointer, true)
414        .filter(|out| out.first().is_some_and(String::is_empty))
415}
416
417/// `desired.details` read (§2.10): at most 255 strings of at least one
418/// character each. A line may be there twice.
419fn read_details(v: &Value) -> Option<Vec<String>> {
420    words::list(v, usize::from(MAX_INDEX) + 1, |d| !d.is_empty(), false)
421}
422
423/// A report resource's declaration (§2.10).
424#[derive(Debug, Clone, PartialEq, Eq)]
425pub enum ReportDeclaration {
426    /// No `desired.report`: no report resource, whatever tables it holds.
427    NotThisProfiles,
428    /// The reasons, in the order checked.
429    Invalid(Vec<ReportInvalid>),
430    /// What it reports, and its two tables as a reader holds them.
431    Declared { names: Names, tables: Tables },
432}
433
434impl ReportDeclaration {
435    /// The fixture's token.
436    #[must_use]
437    pub fn as_str(&self) -> &'static str {
438        match self {
439            Self::NotThisProfiles => "not_this_profiles",
440            Self::Invalid(_) => "invalid",
441            Self::Declared { .. } => "declared",
442        }
443    }
444}
445
446/// Whether a resource's type is the profile's `Report` (§3): the packed
447/// type of that name in an artifact the profile publishes, and in no
448/// other, whatever its types are named (core §7.1).
449#[must_use]
450pub fn is_report(ty: &TypeId) -> bool {
451    matches!(ty, TypeId::Packed { name, schema } if name == REPORT && is_published(schema))
452}
453
454/// A resource as §2.10 reads one: what a report resource's declaration and
455/// a tool's finding of a report need of it.
456#[derive(Debug, Clone, Copy)]
457pub struct ReportResource<'a> {
458    pub kind: Kind,
459    pub token: KindToken,
460    pub template: &'a Template,
461    /// Whether its type is the profile's `Report` ([`is_report`]).
462    pub is_report: bool,
463    /// Its resolved annotations (core §9.3).
464    pub annotations: &'a BTreeMap<String, Value>,
465}
466
467impl<'a> ReportResource<'a> {
468    /// A resource of a contract.
469    #[must_use]
470    pub fn of(r: &'a Resource) -> Self {
471        Self {
472            kind: r.kind,
473            token: r.token,
474            template: &r.template,
475            is_report: matches!(&r.body, Body::Data(d) if is_report(&d.type_)),
476            annotations: &r.annotations,
477        }
478    }
479}
480
481/// Reads a report resource's declaration (§2.10) from its resolved
482/// annotations: `is_role` says whether a name is a requirement of the
483/// same contract, and `others` are the `desired.report` values of the
484/// contract's other resources. Each check runs alone, in the text's order.
485/// After `value`, no later check reads the value, so `two_reports` is
486/// skipped with the three that read a name; after `not_a_param` or
487/// `rest_param`, `param_not_role` is skipped.
488#[must_use]
489pub fn report_declaration<'v>(
490    r: &ReportResource<'_>,
491    is_role: impl Fn(&str) -> bool,
492    others: impl IntoIterator<Item = &'v Value>,
493) -> ReportDeclaration {
494    let Some(v) = r.annotations.get(REPORT_KEY) else {
495        return ReportDeclaration::NotThisProfiles;
496    };
497    let mut why = Vec::new();
498    if r.kind != Kind::State {
499        why.push(ReportInvalid::NotState);
500    }
501    let names = Names::read(v);
502    let params: Vec<(&str, bool)> = r.template.params().collect();
503    match &names {
504        None => why.push(ReportInvalid::Value),
505        Some(Names::Role(name)) => {
506            if !is_role(name) {
507                why.push(ReportInvalid::NotARole);
508            }
509            if !params.is_empty() {
510                why.push(ReportInvalid::ParamNotRole);
511            }
512        }
513        Some(Names::Param(name)) => match params.iter().find(|(p, _)| p == name) {
514            None => why.push(ReportInvalid::NotAParam),
515            Some((_, true)) => why.push(ReportInvalid::RestParam),
516            Some((_, false)) => {
517                if params.iter().any(|(p, _)| p != name) {
518                    why.push(ReportInvalid::ParamNotRole);
519                }
520            }
521        },
522    }
523    if !r.is_report {
524        why.push(ReportInvalid::NotReport);
525    }
526    let pointers = match r.annotations.get(POINTERS) {
527        None => Some(Tables::default().pointers),
528        Some(v) => read_pointers(v),
529    };
530    if pointers.is_none() {
531        why.push(ReportInvalid::Pointers);
532    }
533    let details = match r.annotations.get(DETAILS) {
534        None => Some(Vec::new()),
535        Some(v) => read_details(v),
536    };
537    if details.is_none() {
538        why.push(ReportInvalid::Details);
539    }
540    if let Some(mine) = &names {
541        let clash = |other: &Names| match (mine, other) {
542            (Names::Role(a), Names::Role(b)) => a == b,
543            _ => true,
544        };
545        if others
546            .into_iter()
547            .filter_map(Names::read)
548            .any(|o| clash(&o))
549        {
550            why.push(ReportInvalid::TwoReports);
551        }
552    }
553    match (names, pointers, details) {
554        (Some(names), Some(pointers), Some(details)) if why.is_empty() => {
555            ReportDeclaration::Declared {
556                names,
557                tables: Tables { pointers, details },
558            }
559        }
560        _ => ReportDeclaration::Invalid(why),
561    }
562}
563
564/// [`report_declaration`] of a resource of a contract: its roles the
565/// contract's requirements, and the others the contract's other resources.
566#[must_use]
567pub fn report_declaration_of(c: &Contract, r: &Resource) -> ReportDeclaration {
568    report_declaration(
569        &ReportResource::of(r),
570        |name| c.requires.contains_key(name),
571        c.resources
572            .iter()
573            .filter(|o| !(o.token == r.token && o.template.as_str() == r.template.as_str()))
574            .filter_map(|o| o.annotations.get(REPORT_KEY)),
575    )
576}
577
578/// One finding of [`lint_contract`]: a resource, by its kind token and
579/// template, and the reason's token and words. [`crate::words`]'s shape,
580/// its `key` none: a reason of this profile names its key in its words.
581pub use crate::words::Lint;
582
583/// What a linter reports of a contract that lists `desired.v2` (§2.2,
584/// §2.10): each desired resource's and each report resource's invalid
585/// declaration, a reason a finding. None for any other contract.
586#[must_use]
587pub fn lint_contract(c: &Contract) -> Vec<Lint> {
588    if !uses_v2(c) {
589        return Vec::new();
590    }
591    let mut out = Vec::new();
592    for r in &c.resources {
593        let finding = |token, says| Lint {
594            profile: PROFILE,
595            at: Lint::place(r),
596            key: None,
597            token,
598            says,
599        };
600        if let super::Declaration::Invalid(why) = declaration_of(c, r) {
601            out.extend(why.iter().map(|w| finding(w.as_str(), w.says())));
602        }
603        if let ReportDeclaration::Invalid(why) = report_declaration_of(c, r) {
604            out.extend(why.iter().map(|w| finding(w.as_str(), w.says())));
605        }
606    }
607    out
608}
609
610// --- §2.10, §3: the report -------------------------------------------------------
611
612/// The last act's outcome (§2.10), `not_acted` with no act yet in this
613/// process.
614#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
615pub enum Outcome {
616    NotActed,
617    Converged,
618    Refused,
619    Failed,
620    Reverted,
621}
622
623impl Outcome {
624    const ALL: [Outcome; 5] = [
625        Outcome::NotActed,
626        Outcome::Converged,
627        Outcome::Refused,
628        Outcome::Failed,
629        Outcome::Reverted,
630    ];
631
632    /// The record's and the fixture's token.
633    #[must_use]
634    pub fn as_str(self) -> &'static str {
635        match self {
636            Self::NotActed => "not_acted",
637            Self::Converged => "converged",
638            Self::Refused => "refused",
639            Self::Failed => "failed",
640            Self::Reverted => "reverted",
641        }
642    }
643
644    fn parse(s: &str) -> Option<Self> {
645        Self::ALL.into_iter().find(|o| o.as_str() == s)
646    }
647
648    /// `desired.v1`'s outcome, `None` for `not_acted`, which v1 writes as
649    /// no `outcome`.
650    #[must_use]
651    pub fn acted(self) -> Option<super::Outcome> {
652        match self {
653            Self::NotActed => None,
654            Self::Converged => Some(super::Outcome::Converged),
655            Self::Refused => Some(super::Outcome::Refused),
656            Self::Failed => Some(super::Outcome::Failed),
657            Self::Reverted => Some(super::Outcome::Reverted),
658        }
659    }
660}
661
662impl From<Option<super::Outcome>> for Outcome {
663    fn from(o: Option<super::Outcome>) -> Self {
664        match o {
665            None => Self::NotActed,
666            Some(super::Outcome::Converged) => Self::Converged,
667            Some(super::Outcome::Refused) => Self::Refused,
668            Some(super::Outcome::Failed) => Self::Failed,
669            Some(super::Outcome::Reverted) => Self::Reverted,
670        }
671    }
672}
673
674/// A refusal's code (§2.10): the profile's five, as in v1, or the type's
675/// own, which the record writes as the escape.
676#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
677pub enum Code {
678    Undecodable,
679    Reach,
680    Sensitive,
681    Invalid,
682    Apply,
683    /// A code of the document type's own: the escape. A tool says "the
684    /// type's own".
685    Own,
686}
687
688impl Code {
689    const NAMED: [Code; 5] = [
690        Code::Undecodable,
691        Code::Reach,
692        Code::Sensitive,
693        Code::Invalid,
694        Code::Apply,
695    ];
696
697    /// The record's token, `None` for the type's own.
698    #[must_use]
699    pub fn as_str(self) -> Option<&'static str> {
700        match self {
701            Self::Undecodable => Some(super::UNDECODABLE),
702            Self::Reach => Some(super::REACH),
703            Self::Sensitive => Some(super::SENSITIVE),
704            Self::Invalid => Some(super::INVALID),
705            Self::Apply => Some(super::APPLY),
706            Self::Own => None,
707        }
708    }
709
710    /// A code as a target's handler names one: the profile's five by their
711    /// names, and any other the type's own.
712    #[must_use]
713    pub fn of(code: &str) -> Code {
714        Self::NAMED
715            .into_iter()
716            .find(|c| c.as_str() == Some(code))
717            .unwrap_or(Code::Own)
718    }
719
720    fn to_json(self) -> Value {
721        self.as_str().map_or(Value::Null, Value::from)
722    }
723
724    /// The record's reading, or the profile's: a name, or `null` for the
725    /// escape.
726    fn of_json(v: &Value) -> Result<Code, WriteRefusal> {
727        match v {
728            Value::Null => Ok(Code::Own),
729            Value::String(s) => Self::NAMED
730                .into_iter()
731                .find(|c| c.as_str() == Some(s.as_str()))
732                .ok_or(WriteRefusal::Value),
733            _ => Err(WriteRefusal::Value),
734        }
735    }
736}
737
738/// Why a document was refused, or failed to apply (§2.10): a code, and a
739/// place and a line as indices into the report resource's two tables
740/// ([`Tables::place`], [`Tables::line`]).
741#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
742pub struct Refusal {
743    pub code: Code,
744    pub pointer: Option<Index>,
745    pub detail: Option<Index>,
746}
747
748impl Refusal {
749    /// A refusal with a code alone.
750    #[must_use]
751    pub fn new(code: Code) -> Self {
752        Self {
753            code,
754            pointer: None,
755            detail: None,
756        }
757    }
758}
759
760/// A version with its document's own revision, where its type carries one
761/// (§2.4, §2.10).
762#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
763pub struct Observed {
764    pub version: Version,
765    /// At most [`MAX_REVISION`] in a report a target puts; a writer
766    /// refuses one above it, `range`.
767    pub revision: Option<u64>,
768}
769
770/// Which version is wholly in force, as the record says it (§2.10).
771#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
772pub enum InForce {
773    /// No version: the baseline, a call, or a failed act.
774    #[default]
775    None,
776    /// The observed version.
777    Observed,
778    /// Another version, which the four `in_force` fields name.
779    Other,
780}
781
782impl InForce {
783    const ALL: [InForce; 3] = [InForce::None, InForce::Observed, InForce::Other];
784
785    /// The record's token.
786    #[must_use]
787    pub fn as_str(self) -> &'static str {
788        match self {
789            Self::None => "none",
790            Self::Observed => "observed",
791            Self::Other => "other",
792        }
793    }
794}
795
796/// The standard schema's `Report`, without its descriptions, which are no
797/// part of a layout (core §7.6): `spec/profiles/desired/desired.v2.json`'s
798/// fields, in order. `tests/profiles.rs`'s `desired_v2_schema` holds this
799/// to the file's layout, its form's hash and its tag.
800fn schema() -> Value {
801    let int = |name: &str, maximum: u64| json!({"name": name, "type": "int", "minimum": 0, "maximum": maximum, "optional": true});
802    let index = |name: &str| {
803        json!({"name": name, "type": "int", "minimum": 0, "maximum": MAX_INDEX,
804               "reserved": [OUT_OF_RANGE], "optional": true})
805    };
806    json!({"types": {(REPORT): {"fields": [
807        {"name": "source", "type": "enum", "values": ["baseline", "desired", "call"], "escape": true},
808        {"name": "outcome", "type": "enum",
809         "values": ["not_acted", "converged", "refused", "failed", "reverted"], "escape": true},
810        {"name": "last_known", "type": "bool"},
811        {"name": "in_force", "type": "enum", "values": ["none", "observed", "other"]},
812        int("observed_run16", 65_535),
813        int("observed_run32", MAX_REVISION),
814        int("observed_seq", 16_777_215),
815        int("revision", MAX_REVISION),
816        int("in_force_run16", 65_535),
817        int("in_force_run32", MAX_REVISION),
818        int("in_force_seq", 16_777_215),
819        int("in_force_revision", MAX_REVISION),
820        {"name": "code", "type": "enum",
821         "values": ["undecodable", "reach", "sensitive", "invalid", "apply"],
822         "escape": true, "optional": true},
823        index("pointer"),
824        index("detail"),
825        packed::MARKER,
826    ]}}})
827}
828
829/// The `Report`'s layout (§3, core §7.6): its tag is [`TAG`], a record is
830/// 20 bits at the least, and a consistent one 215 at the most.
831#[must_use]
832pub fn layout() -> &'static Layout {
833    static LAYOUT: OnceLock<Layout> = OnceLock::new();
834    LAYOUT.get_or_init(|| {
835        packed::layout_in(&schema(), REPORT).expect("the standard Report's declaration reads")
836    })
837}
838
839/// A `Report` record's fields, as core §7.6 reads them (§3): an optional
840/// field absent is `None`, and an enum's escape is `None` for `source` and
841/// `outcome`, [`Code::Own`] for `code`. What a record says before §2.10's
842/// consistency is asked of it.
843#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
844pub struct Fields {
845    /// `None`: the escape, a value a later text names.
846    pub source: Option<Source>,
847    /// `None`: the escape.
848    pub outcome: Option<Outcome>,
849    pub last_known: bool,
850    pub in_force: InForce,
851    pub observed_run16: Option<u16>,
852    pub observed_run32: Option<u32>,
853    pub observed_seq: Option<u32>,
854    pub revision: Option<u32>,
855    pub in_force_run16: Option<u16>,
856    pub in_force_run32: Option<u32>,
857    pub in_force_seq: Option<u32>,
858    pub in_force_revision: Option<u32>,
859    pub code: Option<Code>,
860    pub pointer: Option<Index>,
861    pub detail: Option<Index>,
862}
863
864/// A version **stated** by its seq and exactly one of its two runs (§2.10,
865/// `run_fields`).
866fn stated(run16: Option<u16>, run32: Option<u32>, seq: Option<u32>) -> Option<Version> {
867    let run = match (run16, run32) {
868        (Some(r), None) => Run::U16(r),
869        (None, Some(r)) => Run::U32(r),
870        _ => return None,
871    };
872    Some(Stamp {
873        run,
874        seq: Seq::new(seq?)?,
875    })
876}
877
878impl Fields {
879    /// The observed version, where the fields state one.
880    #[must_use]
881    pub fn observed(&self) -> Option<Version> {
882        stated(self.observed_run16, self.observed_run32, self.observed_seq)
883    }
884
885    /// The version in force the four `in_force` fields state, where they
886    /// state one.
887    #[must_use]
888    pub fn other_in_force(&self) -> Option<Version> {
889        stated(self.in_force_run16, self.in_force_run32, self.in_force_seq)
890    }
891
892    /// The record's JSON reading (core §7.6): an absent optional field no
893    /// member, an enum's escape `null`, a reserved code its name.
894    #[must_use]
895    pub fn to_json(&self) -> Value {
896        let mut m = Map::new();
897        let mut put = |k: &str, v: Option<Value>| {
898            if let Some(v) = v {
899                m.insert(k.to_owned(), v);
900            }
901        };
902        put(
903            "source",
904            Some(self.source.map_or(Value::Null, |s| json!(s.as_str()))),
905        );
906        put(
907            "outcome",
908            Some(self.outcome.map_or(Value::Null, |o| json!(o.as_str()))),
909        );
910        put("last_known", Some(json!(self.last_known)));
911        put("in_force", Some(json!(self.in_force.as_str())));
912        put("observed_run16", self.observed_run16.map(Value::from));
913        put("observed_run32", self.observed_run32.map(Value::from));
914        put("observed_seq", self.observed_seq.map(Value::from));
915        put("revision", self.revision.map(Value::from));
916        put("in_force_run16", self.in_force_run16.map(Value::from));
917        put("in_force_run32", self.in_force_run32.map(Value::from));
918        put("in_force_seq", self.in_force_seq.map(Value::from));
919        put("in_force_revision", self.in_force_revision.map(Value::from));
920        put("code", self.code.map(Code::to_json));
921        put("pointer", self.pointer.map(Index::to_json));
922        put("detail", self.detail.map(Index::to_json));
923        Value::Object(m)
924    }
925
926    /// The fields of a record's JSON reading, as [`Layout::read`] gives
927    /// it.
928    ///
929    /// # Errors
930    /// The writer's refusal a value outside the type would draw: `value`
931    /// for a name the type does not declare or a wrong JSON type, `range`
932    /// for a number with no code.
933    pub fn of_json(v: &Value) -> Result<Fields, WriteRefusal> {
934        let Value::Object(o) = v else {
935            return Err(WriteRefusal::Value);
936        };
937        let number = |k: &str, max: u64| -> Result<Option<u64>, WriteRefusal> {
938            match o.get(k) {
939                None => Ok(None),
940                Some(Value::Number(n)) => match n.as_u64() {
941                    Some(x) if x <= max => Ok(Some(x)),
942                    _ => Err(WriteRefusal::Range),
943                },
944                Some(_) => Err(WriteRefusal::Value),
945            }
946        };
947        #[allow(clippy::cast_possible_truncation)]
948        let u16_of = |k: &str| number(k, u64::from(u16::MAX)).map(|x| x.map(|x| x as u16));
949        #[allow(clippy::cast_possible_truncation)]
950        let u32_of = |k: &str| number(k, u64::from(u32::MAX)).map(|x| x.map(|x| x as u32));
951        let named = |k: &str| match o.get(k) {
952            Some(Value::String(s)) => Ok(Some(s.as_str())),
953            Some(Value::Null) => Ok(None),
954            Some(_) => Err(WriteRefusal::Value),
955            None => Err(WriteRefusal::Missing),
956        };
957        let source = match named("source")? {
958            None => None,
959            Some(s) => Some(
960                [Source::Baseline, Source::Desired, Source::Call]
961                    .into_iter()
962                    .find(|x| x.as_str() == s)
963                    .ok_or(WriteRefusal::Value)?,
964            ),
965        };
966        let outcome = match named("outcome")? {
967            None => None,
968            Some(s) => Some(Outcome::parse(s).ok_or(WriteRefusal::Value)?),
969        };
970        let in_force = match o.get("in_force") {
971            Some(Value::String(s)) => InForce::ALL
972                .into_iter()
973                .find(|x| x.as_str() == s)
974                .ok_or(WriteRefusal::Value)?,
975            Some(_) => return Err(WriteRefusal::Value),
976            None => return Err(WriteRefusal::Missing),
977        };
978        let last_known = match o.get("last_known") {
979            Some(Value::Bool(b)) => *b,
980            Some(_) => return Err(WriteRefusal::Value),
981            None => return Err(WriteRefusal::Missing),
982        };
983        Ok(Fields {
984            source,
985            outcome,
986            last_known,
987            in_force,
988            observed_run16: u16_of("observed_run16")?,
989            observed_run32: u32_of("observed_run32")?,
990            observed_seq: u32_of("observed_seq")?,
991            revision: u32_of("revision")?,
992            in_force_run16: u16_of("in_force_run16")?,
993            in_force_run32: u32_of("in_force_run32")?,
994            in_force_seq: u32_of("in_force_seq")?,
995            in_force_revision: u32_of("in_force_revision")?,
996            code: o.get("code").map(Code::of_json).transpose()?,
997            pointer: o.get("pointer").map(Index::of_json).transpose()?,
998            detail: o.get("detail").map(Index::of_json).transpose()?,
999        })
1000    }
1001
1002    /// The record (§3), written by core §7.6's rules.
1003    ///
1004    /// # Errors
1005    /// [`WriteRefusal::Range`] for a value with no code: a seq above
1006    /// 16,777,215, or an index above [`MAX_INDEX`].
1007    pub fn record(&self) -> Result<Record, WriteRefusal> {
1008        layout().write(&self.to_json(), None)
1009    }
1010
1011    /// §2.10's consistency: the findings, every one that applies, in the
1012    /// order checked. `escape` is reported alone. A report with a finding
1013    /// is malformed, and answers nothing (§2.17).
1014    #[must_use]
1015    pub fn check(&self) -> Vec<Finding> {
1016        let (Some(source), Some(outcome)) = (self.source, self.outcome) else {
1017            return vec![Finding::Escape];
1018        };
1019        let mut out = Vec::new();
1020        let observed = self.observed();
1021        let other = self.other_in_force();
1022        let any_observed = self.observed_run16.is_some()
1023            || self.observed_run32.is_some()
1024            || self.observed_seq.is_some()
1025            || self.revision.is_some();
1026        let any_other = self.in_force_run16.is_some()
1027            || self.in_force_run32.is_some()
1028            || self.in_force_seq.is_some()
1029            || self.in_force_revision.is_some();
1030        if (any_observed && observed.is_none()) || (any_other && other.is_none()) {
1031            out.push(Finding::RunFields);
1032        }
1033        let acted = matches!(
1034            outcome,
1035            Outcome::Converged | Outcome::Refused | Outcome::Failed
1036        );
1037        if (observed.is_some() && outcome == Outcome::NotActed) || (acted && observed.is_none()) {
1038            out.push(Finding::ObservedOutcome);
1039        }
1040        let refusing = matches!(outcome, Outcome::Refused | Outcome::Failed);
1041        let refusal = self.code.is_some() || self.pointer.is_some() || self.detail.is_some();
1042        if (refusal && !refusing) || (refusing && self.code.is_none()) {
1043            out.push(Finding::Refusal);
1044        }
1045        if (source == Source::Desired && observed.is_none())
1046            || (outcome == Outcome::Converged && source == Source::Baseline)
1047            || (outcome == Outcome::Reverted && source == Source::Desired)
1048        {
1049            out.push(Finding::Source);
1050        }
1051        let names = self.in_force != InForce::None;
1052        let misplaced = names && (source != Source::Desired || outcome == Outcome::Failed);
1053        let not_observed = outcome == Outcome::Converged
1054            && source == Source::Desired
1055            && self.in_force != InForce::Observed;
1056        let no_observed = self.in_force == InForce::Observed && observed.is_none();
1057        let no_other = self.in_force == InForce::Other && (other.is_none() || other == observed);
1058        let stray = self.in_force != InForce::Other && any_other;
1059        if misplaced || not_observed || no_observed || no_other || stray {
1060            out.push(Finding::InForce);
1061        }
1062        if outcome == Outcome::Reverted && self.revision.is_some() {
1063            out.push(Finding::RevisionOnRevert);
1064        }
1065        if self.last_known && observed.is_none() {
1066            out.push(Finding::LastKnown);
1067        }
1068        out
1069    }
1070
1071    /// The profile's reading of consistent fields, `None` with a finding.
1072    #[must_use]
1073    pub fn report(&self) -> Option<Report> {
1074        if !self.check().is_empty() {
1075            return None;
1076        }
1077        let observed = self.observed().map(|version| Observed {
1078            version,
1079            revision: self.revision.map(u64::from),
1080        });
1081        let in_force = match self.in_force {
1082            InForce::None => None,
1083            InForce::Observed => observed,
1084            InForce::Other => self.other_in_force().map(|version| Observed {
1085                version,
1086                revision: self.in_force_revision.map(u64::from),
1087            }),
1088        };
1089        Some(Report {
1090            source: self.source?,
1091            outcome: self.outcome?,
1092            last_known: self.last_known,
1093            observed,
1094            in_force,
1095            refusal: self.code.map(|code| Refusal {
1096                code,
1097                pointer: self.pointer,
1098                detail: self.detail,
1099            }),
1100        })
1101    }
1102}
1103
1104/// A target's report of one role (§2.10), in the profile's reading: what
1105/// the packed `Report` says once its fields hold together.
1106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1107pub struct Report {
1108    /// What is in force.
1109    pub source: Source,
1110    /// The last act's, which an adoption keeps.
1111    pub outcome: Outcome,
1112    /// `true` when the observed version was read from an archive (§2.9).
1113    pub last_known: bool,
1114    /// The last version acted on or adopted in this process. None after a
1115    /// revert on a snapshot with no entry (§2.8).
1116    pub observed: Option<Observed>,
1117    /// The version wholly in force: absent is the record's `none`, one
1118    /// whose version is the observed one `observed`, and any other
1119    /// `other`.
1120    pub in_force: Option<Observed>,
1121    pub refusal: Option<Refusal>,
1122}
1123
1124fn revision_field(r: Option<u64>) -> Result<Option<u32>, WriteRefusal> {
1125    r.map(|r| u32::try_from(r).map_err(|_| WriteRefusal::Range))
1126        .transpose()
1127}
1128
1129fn observed_json(o: &Observed) -> Value {
1130    let mut m = Map::new();
1131    m.insert("version".into(), json!(version_text(o.version)));
1132    if let Some(r) = o.revision {
1133        m.insert("revision".into(), json!(r));
1134    }
1135    Value::Object(m)
1136}
1137
1138fn observed_of(v: &Value) -> Result<Observed, WriteRefusal> {
1139    let version = v
1140        .get("version")
1141        .and_then(Value::as_str)
1142        .and_then(parse_version)
1143        .ok_or(WriteRefusal::Value)?;
1144    let revision = match v.get("revision") {
1145        None => None,
1146        Some(r) => Some(r.as_u64().ok_or(WriteRefusal::Value)?),
1147    };
1148    Ok(Observed { version, revision })
1149}
1150
1151impl Report {
1152    /// A target's first report of a role, and the kill switch's (§2.10,
1153    /// §2.12): `source` `baseline`, `not_acted`. Its record is the 3 bytes
1154    /// `000000`.
1155    #[must_use]
1156    pub fn baseline() -> Self {
1157        Self {
1158            source: Source::Baseline,
1159            outcome: Outcome::NotActed,
1160            last_known: false,
1161            observed: None,
1162            in_force: None,
1163            refusal: None,
1164        }
1165    }
1166
1167    /// The record's fields (§3).
1168    ///
1169    /// # Errors
1170    /// [`WriteRefusal::Range`] for a revision above [`MAX_REVISION`],
1171    /// which has no code (§2.4).
1172    pub fn fields(&self) -> Result<Fields, WriteRefusal> {
1173        let mut f = Fields {
1174            source: Some(self.source),
1175            outcome: Some(self.outcome),
1176            last_known: self.last_known,
1177            ..Fields::default()
1178        };
1179        if let Some(o) = &self.observed {
1180            match o.version.run {
1181                Run::U16(r) => f.observed_run16 = Some(r),
1182                Run::U32(r) => f.observed_run32 = Some(r),
1183            }
1184            f.observed_seq = Some(o.version.seq.get());
1185            f.revision = revision_field(o.revision)?;
1186        }
1187        f.in_force = match (&self.in_force, &self.observed) {
1188            (None, _) => InForce::None,
1189            (Some(i), Some(o)) if i.version == o.version => {
1190                // The observed version's own fields say it; its revision
1191                // has to have a code all the same.
1192                revision_field(i.revision)?;
1193                InForce::Observed
1194            }
1195            (Some(i), _) => {
1196                match i.version.run {
1197                    Run::U16(r) => f.in_force_run16 = Some(r),
1198                    Run::U32(r) => f.in_force_run32 = Some(r),
1199                }
1200                f.in_force_seq = Some(i.version.seq.get());
1201                f.in_force_revision = revision_field(i.revision)?;
1202                InForce::Other
1203            }
1204        };
1205        if let Some(r) = &self.refusal {
1206            f.code = Some(r.code);
1207            f.pointer = r.pointer;
1208            f.detail = r.detail;
1209        }
1210        Ok(f)
1211    }
1212
1213    /// The packed record a target puts (§2.10, §3).
1214    ///
1215    /// # Errors
1216    /// The writer's refusal: `range` for a revision above
1217    /// [`MAX_REVISION`] or an index above [`MAX_INDEX`].
1218    pub fn write(&self) -> Result<Record, WriteRefusal> {
1219        self.fields()?.record()
1220    }
1221
1222    /// The payload of the report's put under the target's own `stamp`
1223    /// (core §7.5): a mutation's envelope, CH's tag [`TAG`], then the
1224    /// record.
1225    ///
1226    /// # Errors
1227    /// [`Report::write`]'s.
1228    pub fn put(&self, stamp: Stamp) -> Result<Vec<u8>, WriteRefusal> {
1229        let record = self.write()?;
1230        let tag = Tag::new(TAG).expect("12 is a tag");
1231        Ok(Envelope::mutation(tag, stamp, &record.bytes).write())
1232    }
1233
1234    /// The findings of the record this report writes, none for one a
1235    /// [`Target`] made.
1236    #[must_use]
1237    pub fn check(&self) -> Vec<Finding> {
1238        self.fields().map(|f| f.check()).unwrap_or_default()
1239    }
1240
1241    /// The profile's reading as JSON, as `reports.json` writes one:
1242    /// `{source, outcome, last_known, observed?, in_force?, refusal?}`,
1243    /// a version `<run>/<seq>`, a code `null` for the type's own, an
1244    /// index a number or `"out_of_range"`.
1245    #[must_use]
1246    pub fn reading(&self) -> Value {
1247        let mut m = Map::new();
1248        m.insert("source".into(), json!(self.source.as_str()));
1249        m.insert("outcome".into(), json!(self.outcome.as_str()));
1250        m.insert("last_known".into(), json!(self.last_known));
1251        if let Some(o) = &self.observed {
1252            m.insert("observed".into(), observed_json(o));
1253        }
1254        if let Some(i) = &self.in_force {
1255            m.insert("in_force".into(), observed_json(i));
1256        }
1257        if let Some(r) = &self.refusal {
1258            let mut x = Map::new();
1259            x.insert("code".into(), r.code.to_json());
1260            if let Some(p) = r.pointer {
1261                x.insert("pointer".into(), p.to_json());
1262            }
1263            if let Some(d) = r.detail {
1264                x.insert("detail".into(), d.to_json());
1265            }
1266            m.insert("refusal".into(), Value::Object(x));
1267        }
1268        Value::Object(m)
1269    }
1270
1271    /// [`Report::reading`] read back.
1272    ///
1273    /// # Errors
1274    /// The writer's refusal of what the reading holds: `value` for a name
1275    /// the type does not declare, a wrong JSON type or a version that is
1276    /// not `<run>/<seq>`, `range` for an index above 255.
1277    pub fn from_reading(v: &Value) -> Result<Report, WriteRefusal> {
1278        let name = |k: &str| v.get(k).and_then(Value::as_str).ok_or(WriteRefusal::Value);
1279        let source = name("source")?;
1280        let source = [Source::Baseline, Source::Desired, Source::Call]
1281            .into_iter()
1282            .find(|s| s.as_str() == source)
1283            .ok_or(WriteRefusal::Value)?;
1284        let outcome = Outcome::parse(name("outcome")?).ok_or(WriteRefusal::Value)?;
1285        let last_known = v
1286            .get("last_known")
1287            .and_then(Value::as_bool)
1288            .ok_or(WriteRefusal::Value)?;
1289        let refusal = match v.get("refusal") {
1290            None => None,
1291            Some(r) => Some(Refusal {
1292                code: Code::of_json(r.get("code").ok_or(WriteRefusal::Value)?)?,
1293                pointer: r.get("pointer").map(Index::of_json).transpose()?,
1294                detail: r.get("detail").map(Index::of_json).transpose()?,
1295            }),
1296        };
1297        Ok(Report {
1298            source,
1299            outcome,
1300            last_known,
1301            observed: v.get("observed").map(observed_of).transpose()?,
1302            in_force: v.get("in_force").map(observed_of).transpose()?,
1303            refusal,
1304        })
1305    }
1306}
1307
1308/// A report as a reader read it (§2.10): the record's fields, their
1309/// findings, and the profile's reading where there is none.
1310#[derive(Debug, Clone, PartialEq, Eq)]
1311pub struct Read {
1312    pub fields: Fields,
1313    /// §2.10's findings, in the order checked: a report with one is
1314    /// malformed.
1315    pub findings: Vec<Finding>,
1316    /// `Some` exactly with no finding.
1317    pub report: Option<Report>,
1318}
1319
1320/// Reads a report's record under the tag its envelope's CH carries
1321/// (§2.10): core §7.6's reading first, a later text's fields behind the
1322/// marker ignored, then §2.10's checks.
1323///
1324/// # Errors
1325/// Core §7.6's refusal, for which the report is unreadable: `tag`,
1326/// `length`, `code`, `extension` or `pad`.
1327pub fn read(tag: u8, bytes: &[u8]) -> Result<Read, ReadRefusal> {
1328    let value = layout().read(tag, bytes, None)?;
1329    // Every value the layout reads is one the type declares.
1330    let fields = Fields::of_json(&value).map_err(|_| ReadRefusal::Code)?;
1331    Ok(Read {
1332        fields,
1333        findings: fields.check(),
1334        report: fields.report(),
1335    })
1336}
1337
1338impl Reported for Read {
1339    fn facts(&self) -> Option<super::Facts> {
1340        let r = self.report.as_ref()?;
1341        Some(super::Facts {
1342            source: r.source,
1343            outcome: r.outcome.acted(),
1344            last_known: r.last_known,
1345            in_force: r.in_force.is_some(),
1346        })
1347    }
1348}
1349
1350// --- §2.6–§2.10: a target ------------------------------------------------------
1351
1352/// What an act is of (§2.6, §2.8): a version, a put's or a delete's, or a
1353/// snapshot with no entry, which names none.
1354#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1355pub enum Cause {
1356    Version(Version),
1357    /// The author's word that it holds no document for the target: its
1358    /// snapshot's run, and its asof.
1359    NoEntry {
1360        run: Run,
1361        asof: Seq,
1362    },
1363}
1364
1365impl machine::Mark for Cause {
1366    type Epoch = Run;
1367    type Tick = Seq;
1368    fn epoch(&self) -> Run {
1369        match self {
1370            Cause::Version(v) => v.run,
1371            Cause::NoEntry { run, .. } => *run,
1372        }
1373    }
1374    fn tick(&self) -> Seq {
1375        match self {
1376            Cause::Version(v) => v.seq,
1377            Cause::NoEntry { asof, .. } => *asof,
1378        }
1379    }
1380    fn floor(&self) -> bool {
1381        matches!(self, Cause::NoEntry { .. })
1382    }
1383}
1384
1385impl machine::Mark for Stamp {
1386    type Epoch = Run;
1387    type Tick = Seq;
1388    fn epoch(&self) -> Run {
1389        self.run
1390    }
1391    fn tick(&self) -> Seq {
1392        self.seq
1393    }
1394}
1395
1396/// One sample or entry of a target's slice, as its runtime received it
1397/// (§2.5): a put or a live entry, a delete or a tombstone.
1398#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1399pub struct Sample {
1400    pub via: Via,
1401    pub mutation: Mutation,
1402    /// The in-band stamp, `None` for a sample with no envelope (§2.6
1403    /// step 1).
1404    pub version: Option<Version>,
1405    /// The document type's own revision, when it carries one (§2.4). A
1406    /// delete has none. One above [`MAX_REVISION`] is carried here, and
1407    /// refused when the act ends ([`Act::bound`]).
1408    pub revision: Option<u64>,
1409    /// A put's document ([`Content`]); `None` for a delete, and for a put
1410    /// whose runtime did not compare it.
1411    pub content: Option<Content>,
1412}
1413
1414/// An act the target's runtime performs, then reports by
1415/// [`Target::finish`].
1416#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1417pub struct Act {
1418    pub kind: ActKind,
1419    pub cause: Cause,
1420    pub revision: Option<u64>,
1421    pub via: Via,
1422    pub content: Option<Content>,
1423}
1424
1425impl Act {
1426    /// The act's version, none for a revert on a snapshot with no entry.
1427    #[must_use]
1428    pub fn version(&self) -> Option<Version> {
1429        match self.cause {
1430            Cause::Version(v) => Some(v),
1431            Cause::NoEntry { .. } => None,
1432        }
1433    }
1434
1435    /// §2.4's bound: the refusal of a put whose document's revision is
1436    /// above [`MAX_REVISION`], whole, with the code `invalid`. `None` for
1437    /// a document within the bound, or with no revision.
1438    #[must_use]
1439    pub fn bound(&self) -> Option<Refusal> {
1440        (self.kind == ActKind::Apply && self.revision.is_some_and(|r| r > MAX_REVISION))
1441            .then(|| Refusal::new(Code::Invalid))
1442    }
1443}
1444
1445impl From<machine::Doing<Cause>> for Act {
1446    fn from(d: machine::Doing<Cause>) -> Self {
1447        Self {
1448            kind: d.kind,
1449            cause: d.mark,
1450            revision: d.revision,
1451            via: d.via,
1452            content: d.content,
1453        }
1454    }
1455}
1456
1457/// How an act ended (§2.7, §2.10), its refusal this major's.
1458pub type Ended = super::Ended<Refusal>;
1459
1460/// What a step of a target does (§2.6–§2.9).
1461#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1462pub enum Step {
1463    /// Start this act now.
1464    Act(Act),
1465    /// Admitted, and the same document as the last version acted on or
1466    /// adopted, or no document after none: no act, and the report moved.
1467    Adopted,
1468    /// Admitted while an act runs: held, replacing what waited.
1469    Held,
1470    /// No envelope: never acted on (§2.6 step 1).
1471    Unstamped,
1472    /// A version the target acted on, adopted or holds waiting, received
1473    /// again (§2.6 steps 3 and 4).
1474    SameVersion,
1475    /// A lower seq of a remembered run, one at or below a remembered asof,
1476    /// or a snapshot with no entry built before the held version (§2.6,
1477    /// §2.8).
1478    Older,
1479    /// The author's own delivery of a version held from an archive
1480    /// (§2.9). When no act runs, the report changed: its `last_known`
1481    /// went.
1482    Confirmed,
1483    /// An act ended, and nothing waits.
1484    Done,
1485    /// A snapshot with no entry that reverts nothing (§2.8): the target
1486    /// holds no put's version of its run.
1487    NoVerdict,
1488}
1489
1490impl Step {
1491    /// The fixture's token.
1492    #[must_use]
1493    pub fn as_str(&self) -> &'static str {
1494        match self {
1495            Self::Act(Act {
1496                kind: ActKind::Apply,
1497                ..
1498            }) => "act",
1499            Self::Act(Act {
1500                kind: ActKind::Revert,
1501                ..
1502            }) => "revert",
1503            Self::Adopted => "adopted",
1504            Self::Held => "held",
1505            Self::Unstamped => "unstamped",
1506            Self::SameVersion => "same_version",
1507            Self::Older => "older",
1508            Self::Confirmed => "confirmed",
1509            Self::Done => "done",
1510            Self::NoVerdict => "no_verdict",
1511        }
1512    }
1513}
1514
1515/// One process of a target's role (§2.6–§2.10): the version it last acted
1516/// on or adopted, the one it holds while an act runs, per run the highest
1517/// seq it acted on or adopted (or the asof it reverted on), and its
1518/// report. A new process is a new `Target`, holding nothing (§2.7). Its
1519/// rules are `desired.v1`'s machine's (`machine::Core`), read over runs
1520/// and seqs.
1521#[derive(Debug, Clone)]
1522pub struct Target {
1523    core: machine::Core<Cause, Refusal>,
1524}
1525
1526impl Default for Target {
1527    fn default() -> Self {
1528        Self::new()
1529    }
1530}
1531
1532impl Target {
1533    /// A role at its start: nothing held, its report the baseline's. An
1534    /// unbound role's is the same, and stays so (§2.12).
1535    #[must_use]
1536    pub fn new() -> Self {
1537        Self {
1538            core: machine::Core::new(),
1539        }
1540    }
1541
1542    /// The report, as the target puts it (§2.10). A revision above
1543    /// [`MAX_REVISION`] has no code, so its version is reported without
1544    /// one (§2.4).
1545    #[must_use]
1546    pub fn report(&self) -> Report {
1547        let seen = |(cause, revision): (Cause, Option<u64>)| match cause {
1548            Cause::Version(version) => Some(Observed {
1549                version,
1550                revision: revision.filter(|r| *r <= MAX_REVISION),
1551            }),
1552            Cause::NoEntry { .. } => None,
1553        };
1554        let l = self.core.ledger();
1555        Report {
1556            source: l.source,
1557            outcome: l.outcome.into(),
1558            last_known: l.last_known,
1559            observed: l.observed.and_then(seen),
1560            in_force: l.in_force.and_then(seen),
1561            refusal: l.refusal,
1562        }
1563    }
1564
1565    /// The act that runs, if one does.
1566    #[must_use]
1567    pub fn running(&self) -> Option<Act> {
1568        self.core.running().map(|d| Act::from(*d))
1569    }
1570
1571    /// The highest seq this process acted on or adopted a version of under
1572    /// `run`, or the asof it reverted on, if it remembers the run (§2.6
1573    /// step 4, §2.8).
1574    #[must_use]
1575    pub fn remembered(&self, run: Run) -> Option<Seq> {
1576        self.core.remembered(run)
1577    }
1578
1579    /// The stamp a conditional read sends (§2.5): that of the latest
1580    /// version the target admitted, the one it holds waiting, else the
1581    /// running act's, else the last it acted on or adopted. `None` where
1582    /// it holds no version: nothing yet, or a snapshot with no entry it
1583    /// admitted last.
1584    #[must_use]
1585    pub fn held(&self) -> Option<Version> {
1586        self.holds().map(|(_, v)| v)
1587    }
1588
1589    /// [`Target::held`], with whether that version is a put's or a
1590    /// delete's, as a [`Watch`] moves its digest by.
1591    #[must_use]
1592    pub fn holds(&self) -> Option<(Mutation, Version)> {
1593        let d = self.core.latest()?;
1594        match d.mark {
1595            Cause::Version(v) => Some((
1596                match d.kind {
1597                    ActKind::Apply => Mutation::Put,
1598                    ActKind::Revert => Mutation::Delete,
1599                },
1600                v,
1601            )),
1602            Cause::NoEntry { .. } => None,
1603        }
1604    }
1605
1606    /// Judges a version (§2.6): against the one last acted on or adopted
1607    /// (the running act's while one runs) and every run remembered, then,
1608    /// while an act runs, against what waits: an act to start, adopted,
1609    /// held while one runs, or ignored with why. After [`Step::Adopted`]
1610    /// and [`Step::Confirmed`] the report may have changed.
1611    pub fn observe(&mut self, s: Sample) -> Step {
1612        let Some(version) = s.version else {
1613            return Step::Unstamped;
1614        };
1615        let put = s.mutation == Mutation::Put;
1616        match self.core.observe(machine::Doing {
1617            kind: if put { ActKind::Apply } else { ActKind::Revert },
1618            mark: Cause::Version(version),
1619            revision: s.revision.filter(|_| put),
1620            via: s.via,
1621            content: s.content.filter(|_| put),
1622        }) {
1623            machine::Judged::Act(d) => Step::Act(d.into()),
1624            machine::Judged::Adopted => Step::Adopted,
1625            machine::Judged::Held => Step::Held,
1626            machine::Judged::SameVersion => Step::SameVersion,
1627            machine::Judged::Older => Step::Older,
1628            machine::Judged::Confirmed => Step::Confirmed,
1629        }
1630    }
1631
1632    /// Judges a snapshot with no entry (§2.8), its header's `run` and its
1633    /// `asof`: it reverts only where the target holds a document's
1634    /// version of that run with a seq at or below the asof. Under another
1635    /// run, over a delete or with nothing held it is no verdict, and a
1636    /// MUST NOT; built before the held version it is older. While an act
1637    /// runs it is judged against the running act's version, then against
1638    /// what waits, and admitted by both it waits as a delete does.
1639    pub fn observe_no_entry(&mut self, run: Run, asof: Seq) -> Step {
1640        match self.core.observe_floor(Cause::NoEntry { run, asof }) {
1641            machine::Floored::NoVerdict => Step::NoVerdict,
1642            machine::Floored::Older => Step::Older,
1643            machine::Floored::Held => Step::Held,
1644            machine::Floored::Act(d) => Step::Act(d.into()),
1645        }
1646    }
1647
1648    /// A conditional read answered unchanged, by the held stamp `sent`
1649    /// (§2.5): the author's own word of that version, which judges
1650    /// nothing and confirms a last-known one (§2.9). [`Step::Confirmed`]
1651    /// where the target holds `sent` from an archive, else
1652    /// [`Step::SameVersion`].
1653    pub fn unchanged(&mut self, sent: Version) -> Step {
1654        if self.core.unchanged(Cause::Version(sent)) {
1655            Step::Confirmed
1656        } else {
1657            Step::SameVersion
1658        }
1659    }
1660
1661    /// Ends the running act (§2.7, §2.10): the report updated, then what
1662    /// waits, if anything does, adopted or its act started, else
1663    /// [`Step::Done`]. With no act running, nothing changes.
1664    pub fn finish(&mut self, ended: Ended) -> Step {
1665        match self.core.finish(ended) {
1666            machine::Finished::Done => Step::Done,
1667            machine::Finished::Adopted => Step::Adopted,
1668            machine::Finished::Act(d) => Step::Act(d.into()),
1669        }
1670    }
1671
1672    /// The target's own operation changed what is in force (§2.7):
1673    /// `source` is `call` and `in_force` `none`. The rest stays.
1674    pub fn call(&mut self) {
1675        self.core.call();
1676    }
1677}
1678
1679// --- §2.5: the watch --------------------------------------------------------------
1680
1681/// One section of the author's heartbeat (§2.5, core §7.5): its desired
1682/// collection's digest and live count.
1683#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1684pub struct Section {
1685    pub digest: Digest,
1686    pub live: u64,
1687}
1688
1689/// One heartbeat of the author's, as `freshness.v2` §2.5's steps read it
1690/// with the author's revision (§2.5, "What it reads"). A group of an owner
1691/// heartbeat is read as a heartbeat is, its sequence the owner heartbeat
1692/// key's.
1693#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1694pub enum Beat {
1695    /// Of another revision than the author's: not read.
1696    Revision,
1697    /// One core §7.5 refuses, or a group whose sections are not read: not
1698    /// read.
1699    Refused,
1700    /// Read: its key's stamp, and the collection's section, `None` where
1701    /// its map bit is 0, or an owner heartbeat holds no group for the
1702    /// author's interface.
1703    Read {
1704        stamp: Stamp,
1705        section: Option<Section>,
1706    },
1707}
1708
1709/// What a watching target does with one heartbeat (§2.5's rule), the first
1710/// of its six steps that answers.
1711#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1712pub enum Decision {
1713    /// Not read, of another revision: it expects none, and makes no read.
1714    Revision,
1715    /// Not read, refused: the same.
1716    Refused,
1717    /// Not after the last read one, in its run: nothing changes.
1718    Older,
1719    /// The collection's map bit is 0: it expects none, and makes no read.
1720    NoSection,
1721    /// The section is the one it expects: nothing is read.
1722    Unmoved,
1723    /// The section moved, or it expects none, and a read is outstanding:
1724    /// it makes none.
1725    Outstanding,
1726    /// Make one conditional read of the slice, carrying this held stamp,
1727    /// or none where the target holds no version.
1728    Read { held: Option<Version> },
1729}
1730
1731impl Decision {
1732    /// The fixture's token.
1733    #[must_use]
1734    pub fn as_str(&self) -> &'static str {
1735        match self {
1736            Self::Revision => "revision",
1737            Self::Refused => "refused",
1738            Self::Older => "older",
1739            Self::NoSection => "no_section",
1740            Self::Unmoved => "unmoved",
1741            Self::Outstanding => "outstanding",
1742            Self::Read { .. } => "read",
1743        }
1744    }
1745}
1746
1747/// How the watch's read ended (§2.5, "The answer").
1748#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1749pub enum Answered {
1750    /// By the held stamp the target sent: its author holds that version
1751    /// still.
1752    Unchanged,
1753    /// By a snapshot: an entry, a tombstone or no entry, which the target
1754    /// judges (§2.6, §2.8).
1755    Whole,
1756    /// No answer: a timeout, or a held stamp it did not send (core §4.2,
1757    /// `held`).
1758    NoAnswer,
1759}
1760
1761impl Answered {
1762    /// The fixture's token.
1763    #[must_use]
1764    pub fn as_str(self) -> &'static str {
1765        match self {
1766            Self::Unchanged => "unchanged",
1767            Self::Whole => "whole",
1768            Self::NoAnswer => "no_answer",
1769        }
1770    }
1771}
1772
1773/// What a version of its own slice, heard live, did to what the target
1774/// expects (§2.5, "Its own change costs nothing").
1775#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1776pub enum Heard {
1777    /// The digest and the live count it expects moved with its change.
1778    Moved,
1779    /// Nothing moved: it does not move what it expects, it expects none,
1780    /// or it held no version. It reads once at the next heartbeat.
1781    Kept,
1782}
1783
1784impl Heard {
1785    /// The fixture's token.
1786    #[must_use]
1787    pub fn as_str(self) -> &'static str {
1788        match self {
1789            Self::Moved => "moved",
1790            Self::Kept => "kept",
1791        }
1792    }
1793}
1794
1795/// The read a heartbeat made the target make: that heartbeat's section,
1796/// and the held stamp the read carried.
1797#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1798struct Outstanding {
1799    section: Section,
1800    sent: Option<Version>,
1801}
1802
1803/// A target's watch of its author's heartbeat (§2.5): the section it
1804/// expects, a digest and a live count, or none. It reads the section for
1805/// one thing, whether it moved: an unmoved section is never its author's
1806/// confirmation of the version it holds, and confirms no last-known one.
1807/// A pure state machine: the runtime reads each heartbeat, makes the read
1808/// a [`Decision::Read`] asks for, at most one per heartbeat and never
1809/// while one is outstanding, and tells how it ended.
1810#[derive(Debug, Clone, PartialEq, Eq)]
1811pub struct Watch {
1812    key: String,
1813    moves: bool,
1814    sequence: crate::freshness::Sequence,
1815    expects: Option<Section>,
1816    outstanding: Option<Outstanding>,
1817}
1818
1819impl Watch {
1820    /// A watch of the slice at `key`, the member's base-relative key
1821    /// (core §7.5's digest reads it): it expects none, has read no
1822    /// heartbeat, and has no read outstanding. `moves` is §2.5's MAY: the
1823    /// target moves the digest it expects at a version of its slice heard
1824    /// live.
1825    #[must_use]
1826    pub fn new(key: impl Into<String>, moves: bool) -> Self {
1827        Self {
1828            key: key.into(),
1829            moves,
1830            sequence: crate::freshness::Sequence::default(),
1831            expects: None,
1832            outstanding: None,
1833        }
1834    }
1835
1836    /// The section it expects, or none.
1837    #[must_use]
1838    pub fn expects(&self) -> Option<Section> {
1839        self.expects
1840    }
1841
1842    /// Whether a read the watch asked for has not ended.
1843    #[must_use]
1844    pub fn outstanding(&self) -> bool {
1845        self.outstanding.is_some()
1846    }
1847
1848    /// Decides one heartbeat (§2.5's rule, steps 1 to 6). `holds` is the
1849    /// version the target holds ([`Target::held`]): the stamp the read
1850    /// carries.
1851    pub fn heartbeat(&mut self, beat: Beat, holds: Option<Version>) -> Decision {
1852        let (stamp, section) = match beat {
1853            Beat::Revision => {
1854                self.expects = None;
1855                return Decision::Revision;
1856            }
1857            Beat::Refused => {
1858                self.expects = None;
1859                return Decision::Refused;
1860            }
1861            Beat::Read { stamp, section } => (stamp, section),
1862        };
1863        let Some(read) = self.sequence.read(stamp) else {
1864            return Decision::Older;
1865        };
1866        // Out of sequence: it follows a change the target did not see.
1867        if read.gap || read.run {
1868            self.expects = None;
1869        }
1870        let Some(section) = section else {
1871            self.expects = None;
1872            return Decision::NoSection;
1873        };
1874        if self.expects == Some(section) {
1875            return Decision::Unmoved;
1876        }
1877        if self.outstanding.is_some() {
1878            return Decision::Outstanding;
1879        }
1880        self.outstanding = Some(Outstanding {
1881            section,
1882            sent: holds,
1883        });
1884        Decision::Read { held: holds }
1885    }
1886
1887    /// The outstanding read ended (§2.5, "The answer"). `holds` is the
1888    /// version the target holds now, after it judged a whole answer.
1889    /// Unchanged, it expects the section of the heartbeat that made it
1890    /// read where it still holds the version it sent, else none; whole,
1891    /// it expects none; with no answer, what it expects does not change,
1892    /// and the next heartbeat is its next trigger.
1893    pub fn answer(&mut self, answer: Answered, holds: Option<Version>) -> Answered {
1894        let Some(out) = self.outstanding.take() else {
1895            return Answered::NoAnswer;
1896        };
1897        match answer {
1898            Answered::Unchanged => {
1899                self.expects = (out.sent.is_some() && out.sent == holds).then_some(out.section);
1900            }
1901            Answered::Whole => self.expects = None,
1902            Answered::NoAnswer => {}
1903        }
1904        answer
1905    }
1906
1907    /// A version of the slice heard live and admitted (§2.5, "Its own
1908    /// change costs nothing"): `old` is what the target held before it, a
1909    /// put's or a delete's version, and `new` what it holds now. It moves
1910    /// only where it expects a section and held a version: a put over a
1911    /// put XORs the old value out and the new one in, a delete XORs the
1912    /// old value out and the live count falls by 1, and a put over a
1913    /// delete XORs the new value in and the count rises by 1.
1914    pub fn heard(&mut self, old: Option<(Mutation, Version)>, new: (Mutation, Version)) -> Heard {
1915        let (Some(section), Some(old), true) = (self.expects.as_mut(), old, self.moves) else {
1916            return Heard::Kept;
1917        };
1918        if old.0 == Mutation::Put {
1919            section.digest.toggle(&self.key, old.1);
1920            section.live = section.live.saturating_sub(1);
1921        }
1922        if new.0 == Mutation::Put {
1923            section.digest.toggle(&self.key, new.1);
1924            section.live = section.live.saturating_add(1);
1925        }
1926        Heard::Moved
1927    }
1928}
1929
1930// --- §2.10: a tool finds a target's report --------------------------------------
1931
1932/// Where a role's report is, by the target's contract (§2.10, "A tool
1933/// finds a target's report"): by type identity and by the annotation,
1934/// never by a resource's name.
1935#[derive(Debug, Clone, PartialEq, Eq)]
1936pub enum ReportAt {
1937    /// No resource names the role: no report was read.
1938    None,
1939    /// Two or more name it: the target's contract says two things of one
1940    /// role, and the report is unreadable.
1941    Two,
1942    /// One names it, and its declaration is invalid: no report was read,
1943    /// the reasons beside.
1944    Invalid(Vec<ReportInvalid>),
1945    /// One names it, declared: the report is the reply on this key, the
1946    /// resource's with its parameter filled with the role's name.
1947    At { key: Key, tables: Tables },
1948}
1949
1950/// Why a report is unreadable (§2.10).
1951#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1952pub enum Unreadable {
1953    /// Two or more resources name the role.
1954    TwoReports,
1955    /// Core §7.6 refuses the reply's record.
1956    Record(ReadRefusal),
1957}
1958
1959impl Unreadable {
1960    /// The fixture's token.
1961    #[must_use]
1962    pub fn as_str(self) -> &'static str {
1963        match self {
1964            Self::TwoReports => "two_reports",
1965            Self::Record(r) => r.token(),
1966        }
1967    }
1968}
1969
1970/// A tool's finding of one role's report (§2.10).
1971#[derive(Debug, Clone, PartialEq, Eq)]
1972pub enum Found {
1973    /// None was read, with the reasons of an invalid declaration.
1974    None(Vec<ReportInvalid>),
1975    /// Unreadable: a tool answers nothing from it (§2.17).
1976    Unreadable(Unreadable),
1977    /// The reply read; malformed where it has a finding.
1978    One(Read),
1979}
1980
1981impl Found {
1982    /// The fixture's token.
1983    #[must_use]
1984    pub fn as_str(&self) -> &'static str {
1985        match self {
1986            Self::None(_) => "none",
1987            Self::Unreadable(_) => "unreadable",
1988            Self::One(_) => "one",
1989        }
1990    }
1991}
1992
1993impl ReportAt {
1994    /// The report's key, where one resource names the role and is
1995    /// declared: the key whose reply S4's GET is read for.
1996    #[must_use]
1997    pub fn key(&self) -> Option<&Key> {
1998        match self {
1999            Self::At { key, .. } => Some(key),
2000            _ => None,
2001        }
2002    }
2003
2004    /// The finding, given the reply on [`ReportAt::key`] as a tool's merge
2005    /// left it (observer §4.1): its record's CH tag and its bytes, or
2006    /// `None` with no reply on that key.
2007    #[must_use]
2008    pub fn found(&self, reply: Option<(u8, &[u8])>) -> Found {
2009        match self {
2010            Self::None => Found::None(Vec::new()),
2011            Self::Two => Found::Unreadable(Unreadable::TwoReports),
2012            Self::Invalid(why) => Found::None(why.clone()),
2013            Self::At { .. } => match reply {
2014                None => Found::None(Vec::new()),
2015                Some((tag, bytes)) => match read(tag, bytes) {
2016                    Ok(r) => Found::One(r),
2017                    Err(e) => Found::Unreadable(Unreadable::Record(e)),
2018                },
2019            },
2020        }
2021    }
2022}
2023
2024/// Finds where `role`'s report is (§2.10): among `resources`, those of the
2025/// contract of the target `target` that declares the role, interface
2026/// `iface`, the ones whose `desired.report` names it, by its name or by a
2027/// parameter in braces. `is_role` says whether a name is a requirement of
2028/// that contract.
2029#[must_use]
2030pub fn report_at(
2031    target: &Addr,
2032    iface: &IfaceId,
2033    role: &str,
2034    resources: &[ReportResource<'_>],
2035    is_role: impl Fn(&str) -> bool,
2036) -> ReportAt {
2037    let naming: Vec<usize> = resources
2038        .iter()
2039        .enumerate()
2040        .filter(|(_, r)| {
2041            r.annotations
2042                .get(REPORT_KEY)
2043                .and_then(Names::read)
2044                .is_some_and(|n| n.names(role))
2045        })
2046        .map(|(i, _)| i)
2047        .collect();
2048    let at = match naming.as_slice() {
2049        [] => return ReportAt::None,
2050        [one] => *one,
2051        _ => return ReportAt::Two,
2052    };
2053    let r = &resources[at];
2054    let others = resources
2055        .iter()
2056        .enumerate()
2057        .filter(|(i, _)| *i != at)
2058        .filter_map(|(_, o)| o.annotations.get(REPORT_KEY));
2059    let (names, tables) = match report_declaration(r, is_role, others) {
2060        ReportDeclaration::Declared { names, tables } => (names, tables),
2061        ReportDeclaration::Invalid(why) => return ReportAt::Invalid(why),
2062        ReportDeclaration::NotThisProfiles => return ReportAt::None,
2063    };
2064    let mut values = Bindings::new();
2065    if let Names::Param(p) = names {
2066        values.insert(p, vec![role.to_owned()]);
2067    }
2068    let key = r.template.build(&values).ok().and_then(|chunks| {
2069        let refs: Vec<&str> = chunks.iter().map(String::as_str).collect();
2070        grammar::data_key(target, iface, r.token, &refs).ok()
2071    });
2072    match key {
2073        Some(key) => ReportAt::At { key, tables },
2074        // A declared resource has no parameter but the one filled.
2075        None => ReportAt::None,
2076    }
2077}
2078
2079/// [`report_at`] in a contract of the target's, the one that declares the
2080/// role.
2081#[must_use]
2082pub fn report_at_of(target: &Addr, c: &Contract, role: &str) -> ReportAt {
2083    let resources: Vec<ReportResource<'_>> = c.resources.iter().map(ReportResource::of).collect();
2084    report_at(target, &c.iface, role, &resources, |name| {
2085        c.requires.contains_key(name)
2086    })
2087}
2088
2089// --- §2.17, §5: what a tool may conclude ---------------------------------------
2090
2091/// The author's answer to S4's GET of the slice (§2.17 step 6): a member
2092/// read of one concrete key, answered by snapshot (§2.5).
2093#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2094pub enum Current {
2095    /// No GET made: with no revision of the author's interface in hand, a
2096    /// tool has no slice (§2.17).
2097    NotRead,
2098    /// A GET that ended at its timeout or with an error reply.
2099    Incomplete,
2100    /// A reply with no envelope, which carries no version.
2101    Unstamped,
2102    /// A GET that drew no reply.
2103    Silent,
2104    /// A live entry's version.
2105    Entry(Version),
2106    /// A tombstone's version.
2107    Tombstone(Version),
2108    /// A snapshot with no entry: its header's run.
2109    NoEntry(Run),
2110}
2111
2112/// What the tool read of the author (§2.17 step 6).
2113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2114pub struct AuthorReading {
2115    pub presence: Seen,
2116    pub current: Current,
2117}
2118
2119/// §5's first question, "has the target converged on its author's current
2120/// document?" (§2.17), of a `desired.v2` report: v1's premises and the
2121/// author's presence, then the author's version by its snapshot, compared
2122/// by run and seq. A snapshot with no entry answers only under the run of
2123/// the report's observed version, by the outcome: yes `reverted`, else not
2124/// yet `behind`; under another run, or with no observed version, it is
2125/// `author_silent`. No is the finding.
2126#[must_use]
2127pub fn converged(t: &TargetReading<'_, Read>, a: &AuthorReading) -> Judged {
2128    use Answer::{NotYet, Unobservable, Yes};
2129    let judged = |answer, reason| Judged { answer, reason };
2130    let report = match super::converging(t, a.presence) {
2131        Ok((
2132            Read {
2133                report: Some(r), ..
2134            },
2135            _,
2136        )) => *r,
2137        Ok(_) => return judged(Unobservable, Reason::ReportInvalid),
2138        Err(j) => return j,
2139    };
2140    let observed = report.observed.map(|o| o.version);
2141    let current = match a.current {
2142        Current::NotRead => return judged(Unobservable, Reason::AuthorNotRead),
2143        Current::Incomplete | Current::Unstamped => {
2144            return judged(Unobservable, Reason::AuthorReadIncomplete);
2145        }
2146        Current::Silent => return judged(Unobservable, Reason::AuthorSilent),
2147        Current::NoEntry(run) => {
2148            return match observed {
2149                Some(o) if o.run == run && report.outcome == Outcome::Reverted => {
2150                    judged(Yes, Reason::Reverted)
2151                }
2152                Some(o) if o.run == run => judged(NotYet, Reason::Behind),
2153                _ => judged(Unobservable, Reason::AuthorSilent),
2154            };
2155        }
2156        Current::Entry(v) | Current::Tombstone(v) => v,
2157    };
2158    match (observed, report.outcome.acted()) {
2159        (Some(o), Some(outcome)) => super::compared(&o, &current, outcome),
2160        _ => judged(NotYet, Reason::NotActed),
2161    }
2162}
2163
2164#[cfg(test)]
2165mod tests {
2166    use super::*;
2167
2168    fn v(text: &str) -> Version {
2169        parse_version(text).expect("a version")
2170    }
2171
2172    fn put(text: &str, revision: u64) -> Sample {
2173        Sample {
2174            via: Via::Owner,
2175            mutation: Mutation::Put,
2176            version: Some(v(text)),
2177            revision: Some(revision),
2178            content: Some(Content::of_json(&json!({"revision": revision}))),
2179        }
2180    }
2181
2182    #[test]
2183    fn a_version_is_written_as_its_run_and_its_seq() {
2184        assert_eq!(version_text(v("0007/12")), "0007/12");
2185        assert_eq!(version_text(v("00000007/12")), "00000007/12");
2186        assert_ne!(v("0007/12"), v("00000007/12"), "two widths are two runs");
2187        assert_eq!(v("ffff/16777215").seq, Seq::MAX);
2188        for bad in [
2189            "",
2190            "7/12",
2191            "007/12",
2192            "00007/12",
2193            "0007/",
2194            "/12",
2195            "0007/012",
2196            "0007/+1",
2197            "0007/1 ",
2198            "000G/1",
2199            "000A/1",
2200            "0007/16777216",
2201            "0007/1/2",
2202            "0007",
2203            "0007/-1",
2204            "0007/000000001",
2205        ] {
2206            assert_eq!(parse_version(bad), None, "{bad:?}");
2207        }
2208        assert_eq!(parse_version("0007/0"), Some(v("0007/0")));
2209    }
2210
2211    #[test]
2212    fn the_layout_is_the_texts() {
2213        let l = layout();
2214        assert_eq!(l.tag(), TAG);
2215        assert_eq!(l.min_bits(), 20);
2216        assert_eq!(Report::baseline().write().unwrap().bytes, [0, 0, 0]);
2217        // The longest consistent report (§3): refused over a document in
2218        // force, both versions on 32-bit runs.
2219        let longest = Report {
2220            source: Source::Desired,
2221            outcome: Outcome::Refused,
2222            last_known: true,
2223            observed: Some(Observed {
2224                version: v("00a1b2c3/9"),
2225                revision: Some(4),
2226            }),
2227            in_force: Some(Observed {
2228                version: v("00a1b2c3/4"),
2229                revision: Some(3),
2230            }),
2231            refusal: Some(Refusal {
2232                code: Code::Reach,
2233                pointer: Some(Index::At(3)),
2234                detail: Some(Index::OutOfRange),
2235            }),
2236        };
2237        let record = longest.write().unwrap();
2238        assert_eq!((record.bits, record.bytes.len()), (215, 27));
2239        assert_eq!(
2240            read(TAG, &record.bytes).unwrap().report,
2241            Some(longest),
2242            "every report reads back"
2243        );
2244    }
2245
2246    #[test]
2247    fn every_report_the_machine_makes_is_consistent() {
2248        let mut t = Target::new();
2249        let mut seen = vec![t.report()];
2250        let mut note = |t: &Target| seen.push(t.report());
2251        assert!(matches!(t.observe(put("0007/3", 1)), Step::Act(_)));
2252        assert_eq!(t.observe(put("0007/4", 2)), Step::Held);
2253        assert!(matches!(t.finish(Ended::Done), Step::Act(_)));
2254        note(&t);
2255        t.finish(Ended::Refused(Refusal::new(Code::Reach)));
2256        note(&t);
2257        t.call();
2258        note(&t);
2259        // A revision above the bound: refused whole, reported without one.
2260        let big = put("0007/5", MAX_REVISION + 1);
2261        let Step::Act(act) = t.observe(big) else {
2262            panic!("a new document is acted on");
2263        };
2264        let refusal = act.bound().expect("above the bound");
2265        t.finish(Ended::Refused(refusal));
2266        assert_eq!(t.report().observed.unwrap().revision, None);
2267        note(&t);
2268        // A snapshot with no entry under the held run reverts; a revert
2269        // that could not finish keeps the version it was reverting.
2270        let run = v("0007/0").run;
2271        let asof = Seq::new(20).unwrap();
2272        assert!(matches!(t.observe_no_entry(run, asof), Step::Act(_)));
2273        t.finish(Ended::Failed(Refusal::new(Code::Apply)));
2274        assert_eq!(t.report().outcome, Outcome::Failed);
2275        assert_eq!(t.report().observed.map(|o| o.version), Some(v("0007/5")));
2276        note(&t);
2277        assert_eq!(t.observe(put("0007/20", 3)), Step::Older, "at the asof");
2278        assert!(matches!(t.observe(put("0007/21", 3)), Step::Act(_)));
2279        t.finish(Ended::Done);
2280        note(&t);
2281        assert!(matches!(
2282            t.observe_no_entry(run, Seq::new(30).unwrap()),
2283            Step::Act(_)
2284        ));
2285        t.finish(Ended::Done);
2286        assert_eq!(t.report().observed, None);
2287        assert_eq!(t.held(), None, "after it the target holds no document");
2288        note(&t);
2289        for r in &seen {
2290            assert!(r.check().is_empty(), "{r:?}: {:?}", r.check());
2291            let record = r.write().expect("a record");
2292            assert_eq!(read(TAG, &record.bytes).unwrap().report.as_ref(), Some(r));
2293        }
2294    }
2295
2296    #[test]
2297    fn an_asof_at_the_held_seq_makes_that_version_older() {
2298        let mut t = Target::new();
2299        assert!(matches!(t.observe(put("0007/20", 1)), Step::Act(_)));
2300        t.finish(Ended::Done);
2301        assert_eq!(t.observe(put("0007/20", 1)), Step::SameVersion);
2302        let run = v("0007/0").run;
2303        assert!(matches!(
2304            t.observe_no_entry(run, Seq::new(20).unwrap()),
2305            Step::Act(_)
2306        ));
2307        t.finish(Ended::Done);
2308        // §2.8, "What it records": at or below the asof is older.
2309        assert_eq!(t.observe(put("0007/20", 1)), Step::Older);
2310        assert_eq!(t.remembered(run), Seq::new(20));
2311    }
2312
2313    #[test]
2314    fn an_unchanged_answer_confirms_only_the_version_held() {
2315        let archived = Sample {
2316            via: Via::Archive,
2317            ..put("0007/3", 1)
2318        };
2319        let mut t = Target::new();
2320        assert!(matches!(t.observe(archived), Step::Act(_)));
2321        t.finish(Ended::Done);
2322        assert!(t.report().last_known);
2323        assert_eq!(t.unchanged(v("0007/2")), Step::SameVersion);
2324        assert!(t.report().last_known, "another version's word");
2325        assert_eq!(t.unchanged(v("0007/3")), Step::Confirmed);
2326        assert!(!t.report().last_known);
2327        assert_eq!(t.unchanged(v("0007/3")), Step::SameVersion);
2328        // A run forgotten is never admitted by an unchanged answer.
2329        assert_eq!(t.unchanged(v("0099/1")), Step::SameVersion);
2330        assert_eq!(t.held(), Some(v("0007/3")));
2331    }
2332
2333    #[test]
2334    fn a_place_is_its_nearest_listed_ancestor() {
2335        let t = Tables {
2336            pointers: ["", "/a", "/a/b", "/a~1b"].map(str::to_owned).to_vec(),
2337            details: vec!["x".into()],
2338        };
2339        assert_eq!(t.place(""), Index::At(0));
2340        assert_eq!(t.place("/a/b/c/d"), Index::At(2));
2341        assert_eq!(t.place("/a/c"), Index::At(1));
2342        assert_eq!(t.place("/ab"), Index::OutOfRange);
2343        assert_eq!(t.place("/z"), Index::OutOfRange, "never index 0");
2344        assert_eq!(t.line("x"), Index::At(0));
2345        assert_eq!(t.line("y"), Index::OutOfRange);
2346        assert_eq!(t.pointer(Index::At(3)), Word::Entry("/a~1b"));
2347        assert_eq!(t.pointer(Index::At(9)), Word::Number(9));
2348        assert_eq!(word(None, Index::At(1)), Word::Number(1));
2349        assert_eq!(t.detail(Index::OutOfRange), Word::OutOfRange);
2350    }
2351
2352    #[test]
2353    fn a_watch_makes_no_read_while_one_is_outstanding() {
2354        let key = "zk2/lab/author/tasking.v2/state/tasks/lab/worker";
2355        let held = v("0007/3");
2356        let section = |seq: u32| Section {
2357            digest: Digest::of([(key, v(&format!("0007/{seq}")))]),
2358            live: 1,
2359        };
2360        let beat = |seq: u32, s: Section| Beat::Read {
2361            stamp: v(&format!("0021/{seq}")),
2362            section: Some(s),
2363        };
2364        let mut w = Watch::new(key, true);
2365        assert_eq!(
2366            w.heartbeat(beat(0, section(3)), Some(held)),
2367            Decision::Read { held: Some(held) }
2368        );
2369        assert!(w.outstanding());
2370        assert_eq!(
2371            w.heartbeat(beat(1, section(3)), Some(held)),
2372            Decision::Outstanding
2373        );
2374        assert_eq!(
2375            w.answer(Answered::Unchanged, Some(held)),
2376            Answered::Unchanged
2377        );
2378        assert_eq!(w.expects(), Some(section(3)));
2379        // An answer with no read outstanding changes nothing.
2380        assert_eq!(w.answer(Answered::Whole, Some(held)), Answered::NoAnswer);
2381        assert_eq!(w.expects(), Some(section(3)));
2382        // Its own change, moved: the next section is the one it expects.
2383        let new = v("0007/9");
2384        assert_eq!(
2385            w.heard(Some((Mutation::Put, held)), (Mutation::Put, new)),
2386            Heard::Moved
2387        );
2388        assert_eq!(
2389            w.heartbeat(beat(2, section(9)), Some(new)),
2390            Decision::Unmoved
2391        );
2392        // It held nothing: nothing to move.
2393        assert_eq!(w.heard(None, (Mutation::Put, new)), Heard::Kept);
2394    }
2395}