Skip to main content

onevcs_testing/
state.rs

1//! What a provider knows, in a shape a journey can write down and read back.
2//!
3//! One state type per interface, shared by both flavours of it — the in-memory
4//! provider and the file-backed one differ in where the state lives and in nothing
5//! else, so a scenario seeded for one is the same scenario for the other.
6
7use std::collections::{BTreeMap, BTreeSet};
8
9use serde::{Deserialize, Serialize};
10
11use onevcs::{
12    ChangeId, ChangeRequest, Check, CheckSource, Error, Identity, Landed, MergeOutcome,
13    Recoverable, Result,
14};
15use onevcs::{MergePolicy, Publication, Session, SessionRequest, SessionToken};
16
17use crate::events;
18use crate::store::Checked;
19
20/// The version of the state document this build writes.
21///
22/// A file-backed state outlives the process that wrote it and is read by the next
23/// one, which makes it a stored contract like `onevcs`'s own registry document —
24/// and like that document, the version a document declares decides what is done
25/// with it rather than being guessed at. [`STATE_VERSION`] is the shape the goldens in
26/// `tests/golden/` hold, and those goldens are compared byte for byte, so a change
27/// to the document cannot reach a consumer without the diff saying so.
28///
29/// `2` was what both sides learned when publishing and closing a session came
30/// through the interface: [`VcsState::policy`], [`VcsState::closed_sessions`],
31/// [`VcsState::publications`], and [`HostState::titles`]. `3` is
32/// [`HostState::bodies`], the body a change request was opened with. `4` is the two
33/// fields a `Recoverable` gained inside [`VcsState::preserved`] — the live session
34/// holding a branch, and the lines it would land when it removes more than it adds.
35/// `5` is one more of those: whether the branch's work reached its base, and what
36/// says so.
37///
38/// **Every change to the document is versioned, an added field included.** A field
39/// that only ever appears when it holds something is *compatible* — that is what
40/// [`OLDEST_READABLE_VERSION`] is for — but compatible is not the same as
41/// unremarkable: the version is how a consumer's checked-in scenario says which
42/// shape it was written against, and a document that gained a field without saying
43/// so leaves nothing able to tell "this build wrote no body" from "this document
44/// predates bodies". The two answers differ for exactly the journey this crate
45/// exists to support.
46pub const STATE_VERSION: u32 = 5;
47
48/// The oldest document version this build reads.
49///
50/// Every version from here to [`STATE_VERSION`] is read and carried forward on the
51/// way in, which is how `onevcs`'s own registry document treats its older
52/// versions: what separates a readable older version from a refused one is whether
53/// its every field still means here what it meant there. `2` to `3` added a field
54/// and changed none, so a version 2 document reads as one whose change requests
55/// were opened with no body — which is what they were; `3` to `4` added two the same
56/// way, so a version 3 document reads as one whose preserved rows say nothing about a
57/// hold or a line count, which is what they said. `4` to `5` added one that every row
58/// answers rather than one that appears when it holds something, so a version 4
59/// document's rows are carried forward as the answer that list *was*: preserved work
60/// nobody published, which is work that did not land.
61///
62/// `1` is refused rather than read for the opposite reason: it describes a provider
63/// that could not publish, and every session in it would read back as open — a
64/// wrong answer where a journey asserting on a session it had closed needs a
65/// refusal.
66pub const OLDEST_READABLE_VERSION: u32 = 2;
67
68/// Everything the repository side of a run knows about itself.
69///
70/// Every field is public and serializable, so a journey both seeds a scenario and
71/// asserts on what a run left behind. Everything but the version is omitted when
72/// it holds nothing, so a hand-written document names only the part of a scenario
73/// that matters — and a document written by a build that knew fewer fields still
74/// reads here.
75#[derive(Debug, Clone, Serialize, Deserialize)]
76#[serde(default)]
77pub struct VcsState {
78    /// The schema version this state was written at. A document that names none is
79    /// the one this build writes.
80    // llmlint: ignore[boundary_inputs_validated] deciding what to do with a version this
81    // build does not read is the whole of the check — and it is in `Checked::check` below,
82    // where a document is read, rather than here where serde only proves the shape.
83    pub version: u32,
84    /// The repository identities this provider can resolve. A
85    /// [`SessionRequest::repo`] naming none of them is refused, the way an
86    /// unregistered repository is.
87    #[serde(skip_serializing_if = "Vec::is_empty")]
88    pub identities: Vec<Identity>,
89    /// Every session opened or seeded, in the order they were opened.
90    #[serde(skip_serializing_if = "Vec::is_empty")]
91    pub sessions: Vec<Session>,
92    /// Which identity each session belongs to.
93    ///
94    /// Beyond the sketch this crate was specified from, and unavoidable: a
95    /// [`Session`] carries no identity, and a [`Recoverable`] must name one — so
96    /// preserving a session's branch could not answer the question `recoverable`
97    /// asks without this. `open_session` records it; nothing else writes it.
98    // llmlint: ignore[invalid_states_unrepresentable] an identity key is a `String`
99    // everywhere the crate this mirrors spells one — `Recoverable.identity`,
100    // `Identity.origin`, the registry document's own map key — and a newtype here would
101    // make a seeded state disagree with the types it is made of. Every value written to
102    // this map came out of `identity_of`, so it names an identity this provider holds.
103    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
104    pub session_identities: BTreeMap<SessionToken, String>,
105    /// Preserved work, newest last, as `recoverable` reports it.
106    ///
107    /// [`Recoverable`] rather than `PreservedBranch` — it *contains* the preserved
108    /// branch and adds the identity, the checkout, why the workstream stopped, and
109    /// the command that lands it, none of which are derivable from the branch
110    /// alone. One list rather than two that could disagree.
111    #[serde(skip_serializing_if = "Vec::is_empty")]
112    pub preserved: Vec<Recoverable>,
113    /// The sessions that have been closed. Every other session here is open.
114    ///
115    /// One way to say closed rather than two, so a scenario written by hand names
116    /// only the sessions whose lifecycle is not the one they were opened in.
117    // llmlint: ignore[invalid_states_unrepresentable] keyed by session token, exactly as
118    // `session_identities` above is and for the same reason: this document is a scenario
119    // somebody writes by hand, and a session is named once under `sessions` with the rest
120    // of the state keyed to it rather than nested inside a shape that could hold only one
121    // arrangement. A token here that names no opened session is refused in
122    // `Checked::check`, where the document is read — the same trust boundary every other
123    // cross-reference in it is checked at.
124    #[serde(skip_serializing_if = "BTreeSet::is_empty")]
125    pub closed_sessions: BTreeSet<SessionToken>,
126    /// The policy this provider publishes under.
127    ///
128    /// The answer a rules file gives the real implementation, which a provider has
129    /// none of — so a journey states it, and unset is the policy the contract's own
130    /// `default:` names ([`DEFAULT_PUBLICATION`](crate::DEFAULT_PUBLICATION)). A
131    /// per-run policy narrows it through [`MergePolicy::narrow`], which is the
132    /// rules system's rule rather than a restatement of it here.
133    #[serde(skip_serializing_if = "Option::is_none")]
134    pub policy: Option<MergePolicy>,
135    /// Every publication this provider performed, in the order it performed them.
136    ///
137    /// Both a record a journey asserts on and the answer to "has this session been
138    /// published already": a second publication of a session that landed has
139    /// nothing the base does not already carry, which is what the real
140    /// implementation reports for the same reason.
141    // llmlint: ignore[invalid_states_unrepresentable] this holds `onevcs::Publication`
142    // verbatim — the value `Vcs::publish` handed back, carrying its own session and branch
143    // — so a journey asserts on exactly what a caller would receive. A shape that made
144    // "this publication is of some other session's branch" unrepresentable could not hold
145    // that type, and would be a second spelling of the answer the crate next door already
146    // has. The cross-reference is checked in `Checked::check` instead, where the document
147    // is read.
148    #[serde(skip_serializing_if = "Vec::is_empty")]
149    pub publications: Vec<Publication>,
150}
151
152/// A repository side that knows nothing, at the version this build writes.
153impl Default for VcsState {
154    fn default() -> Self {
155        Self {
156            version: STATE_VERSION,
157            identities: Vec::new(),
158            sessions: Vec::new(),
159            session_identities: BTreeMap::new(),
160            preserved: Vec::new(),
161            closed_sessions: BTreeSet::new(),
162            policy: None,
163            publications: Vec::new(),
164        }
165    }
166}
167
168/// Everything the remote-host side of a run knows about itself.
169///
170/// Omitted-when-empty and versioned for the same reasons [`VcsState`] is.
171#[derive(Debug, Clone, Serialize, Deserialize)]
172#[serde(default)]
173pub struct HostState {
174    /// The schema version this state was written at. A document that names none is
175    /// the one this build writes.
176    // llmlint: ignore[boundary_inputs_validated] as on `VcsState::version`: the decision
177    // about an unreadable version is made in `Checked::check`, where the document is read.
178    pub version: u32,
179    /// Who the host says is calling. Empty is refused, exactly as a `gh` that
180    /// reports no authenticated user is.
181    // llmlint: ignore[invalid_states_unrepresentable] the interface this satisfies is
182    // `authenticated_user() -> Result<String>`, so the login is a `String` by contract and
183    // the one unusable value — a host that names nobody — is refused where it is read
184    // rather than made unrepresentable in a state a journey writes by hand.
185    pub authenticated_user: String,
186    /// Every change request that has been opened or seeded.
187    #[serde(skip_serializing_if = "Vec::is_empty")]
188    pub changes: Vec<ChangeRequest>,
189    /// The head branch each change request was opened from.
190    ///
191    /// Beyond the sketch, and unavoidable: [`ChangeRequest`] records only the base
192    /// it targets, and `find_changes` matches on the head as well.
193    // llmlint: ignore[invalid_states_unrepresentable] the matching `ChangeSpec.head` and
194    // `ChangeRequest.base` are `String` in the contract this mirrors, and a validated ref
195    // type here would disagree with them. Every value written to this map went through
196    // `addressable` in `open_change` first, which is the same refusal the real
197    // implementation makes at the same point.
198    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
199    pub heads: BTreeMap<ChangeId, String>,
200    /// The title each change request was opened under.
201    ///
202    /// Beyond the sketch, and for the same reason [`heads`](HostState::heads) is:
203    /// [`ChangeRequest`] records neither, and the title is what a publication's
204    /// commit subject becomes — so a journey asserting that the subject it asked
205    /// for is the one the host was given has nowhere else to read it.
206    // llmlint: ignore[invalid_states_unrepresentable] this records the `ChangeSpec.title`
207    // the contract fixes as a `String`, so a validated type here would disagree with the
208    // one it mirrors. `Subject` is not that type: it is `onevcs`'s rule for a *commit
209    // subject*, and a host's own limit is its own — spelling it here would
210    // refuse a seeded title a real host accepts, which is drift in the direction that
211    // looks like rigour. What the host itself refuses is a title that names nothing, and
212    // that is refused below and in `open_change`, at the boundary the value arrives at.
213    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
214    pub titles: BTreeMap<ChangeId, String>,
215    /// The body each change request was opened with, for the change requests that
216    /// were opened with one.
217    ///
218    /// Beside [`titles`](HostState::titles) and for its reason: the body is what a
219    /// caller passes on the `PublishRequest` and nothing else records it, so a
220    /// journey asserting that the body it drafted is the one the host was given has
221    /// nowhere else to read it. A change request with no entry was opened with no
222    /// body at all, which is what a publication nobody gave one does — the two are
223    /// different scenarios, and an empty string is the first rather than the second.
224    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
225    pub bodies: BTreeMap<ChangeId, String>,
226    /// The checks the host reports on each change request. A change with no entry
227    /// has no checks, which is what a repository with no CI reports.
228    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
229    pub checks: BTreeMap<ChangeId, Vec<Check>>,
230    /// The log the host hands over for a check, keyed by change request and then by
231    /// check name. Beyond the sketch: `check_log` is one of the six methods, and
232    /// without this the only log a journey could asssert on is a synthesized one.
233    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
234    pub check_logs: BTreeMap<ChangeId, BTreeMap<String, String>>,
235    /// Which sources this host answers about its checks from, which is what the
236    /// real implementation reports alongside them.
237    ///
238    /// Unset is a credential allowed to read everything: the whole rollup, exactly
239    /// what a host with nothing to hide reports. A journey states a narrower set to
240    /// be the credential the real one meets in CI — a fine-grained token, which
241    /// cannot read check runs at all and sees GitHub Actions and nothing else — and
242    /// states an *empty* one to be a credential that can read no source at all,
243    /// which is a refusal rather than "no checks". Unset and empty are therefore
244    /// different scenarios, which is why this is an `Option` rather than a set whose
245    /// emptiness means "not stated".
246    #[serde(skip_serializing_if = "Option::is_none")]
247    pub check_sources: Option<BTreeSet<CheckSource>>,
248    /// What merging each change request did.
249    ///
250    /// Both a script and a record: an entry seeded here is what `merge` answers,
251    /// whatever the policy asks for — which is how a journey expresses a host that
252    /// queues or refuses — and a merge the policy decided is written back here.
253    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
254    pub merges: BTreeMap<ChangeId, MergeOutcome>,
255}
256
257/// Who a host with nothing seeded says is calling.
258///
259/// A host that answers nobody is refused by the real implementation, so a default
260/// state that answered nobody would be a provider that cannot run a publication
261/// until it is configured.
262pub const DEFAULT_AUTHENTICATED_USER: &str = "onevcs-testing";
263
264impl Default for HostState {
265    fn default() -> Self {
266        Self {
267            version: STATE_VERSION,
268            authenticated_user: DEFAULT_AUTHENTICATED_USER.to_owned(),
269            changes: Vec::new(),
270            heads: BTreeMap::new(),
271            titles: BTreeMap::new(),
272            bodies: BTreeMap::new(),
273            checks: BTreeMap::new(),
274            check_logs: BTreeMap::new(),
275            check_sources: None,
276            merges: BTreeMap::new(),
277        }
278    }
279}
280
281/// The identity a session request names, or the reason none of them is it.
282///
283/// Three ways to name one, mirroring what the registry accepts: the identity key
284/// itself, the `owner/name` tail of it, or the bare repository name.
285pub(crate) fn identity_of<'a>(state: &'a VcsState, origin_or_path: &str) -> Option<&'a Identity> {
286    let wanted = origin_or_path.trim_end_matches('/');
287    state
288        .identities
289        .iter()
290        .find(|identity| identity.origin == wanted)
291        .or_else(|| {
292            state.identities.iter().find(|identity| {
293                identity
294                    .origin
295                    .rsplit('/')
296                    .next()
297                    .is_some_and(|name| name == wanted)
298                    || identity.origin.ends_with(&format!("/{wanted}"))
299            })
300        })
301}
302
303/// The known identities, as a refusal names them.
304pub(crate) fn known(state: &VcsState) -> String {
305    if state.identities.is_empty() {
306        return "this provider was seeded with no identities".to_owned();
307    }
308    let names: Vec<&str> = state
309        .identities
310        .iter()
311        .map(|identity| identity.origin.as_str())
312        .collect();
313    format!("it knows {}", names.join(", "))
314}
315
316/// The identity a session belongs to, or the reason this provider cannot say.
317///
318/// `open_session` records it and nothing else writes it, so a session that arrived
319/// in a hand-written scenario without one is refused here rather than published
320/// against a repository nobody named.
321pub(crate) fn identity_for(state: &VcsState, token: &SessionToken) -> Result<String> {
322    state
323        .session_identities
324        .get(token)
325        .cloned()
326        .ok_or_else(|| Error::Invalid {
327            reason: format!(
328                "this provider has no record of session {:?}, so it cannot say which identity \
329                 its work belongs to",
330                token.0
331            ),
332        })
333}
334
335/// The session a token names.
336pub(crate) fn session_of<'a>(state: &'a VcsState, token: &SessionToken) -> Option<&'a Session> {
337    state
338        .sessions
339        .iter()
340        .find(|session| session.token == *token)
341}
342
343/// The branch a request asks for, or the one that is derived from the token.
344pub(crate) fn requested_branch(req: &SessionRequest, token: &SessionToken) -> Result<String> {
345    let name = req
346        .branch
347        .clone()
348        .unwrap_or_else(|| format!("onevcs/{}", token.0));
349    named_branch(&name, "the branch")?;
350    Ok(name)
351}
352
353/// A branch name, refused here if git would refuse it.
354///
355/// The real implementation asks `git check-ref-format`, which is the parser that
356/// decides; a provider with no git carries `git-check-ref-format(1)`'s rules
357/// instead. That is a restatement, so it is gated rather than trusted:
358/// `refs.rs` in the suite runs both this and git itself over a table of names
359/// and holds them to each other, because a copy of somebody else's grammar with
360/// no gate is a copy that drifts.
361///
362/// One deliberate difference, and the gate knows about it: a leading `-` is
363/// refused here even though git accepts it as a ref, because such a name reaches
364/// a command line as an option rather than as the branch it spells.
365pub(crate) fn named_branch(value: &str, what: &str) -> Result<()> {
366    // Rule 1 is per slash-separated component; the rest are about the whole name.
367    let components_usable = !value.is_empty()
368        && value.split('/').all(|component| {
369            !component.is_empty() && !component.starts_with('.') && !component.ends_with(".lock")
370        });
371    let usable = components_usable
372        && !value.starts_with('-')
373        && !value.contains("..")
374        && !value.contains("@{")
375        && !value.ends_with('.')
376        && !value.ends_with('/')
377        && !value.chars().any(|c| {
378            c.is_whitespace() || c.is_ascii_control() || c == '\u{7f}' || "~^:?*[\\".contains(c)
379        });
380    if !usable {
381        return Err(Error::Invalid {
382            reason: format!("{what} {value:?} is a name git would not accept"),
383        });
384    }
385    Ok(())
386}
387
388/// A seeded repository side is refused if it holds a session nothing could act on.
389impl Checked for VcsState {
390    fn check(&self) -> Result<()> {
391        readable_version(self.version)?;
392        for session in &self.sessions {
393            // The token names a file under the state root, and a branch goes on to
394            // spell a ref; both arrive from whoever wrote the document.
395            if !events::is_safe_name(&session.token.0) {
396                return Err(Error::Invalid {
397                    reason: format!("{:?} is not a session token", session.token.0),
398                });
399            }
400            named_branch(&session.branch, "the branch")?;
401            named_branch(&session.base, "the base")?;
402        }
403        for row in &self.preserved {
404            known_identity(self, &row.identity, "preserved work")?;
405            named_branch(&row.branch.branch, "the preserved branch")?;
406            named_branch(&row.branch.base, "the preserved branch's base")?;
407            // The hold names a session, so it is checked like the three below: a row
408            // held by a session nobody opened is the same fiction, and the costly one
409            // — it is the session an operator is told to wait for or close.
410            if let Some(held) = &row.held_by {
411                opened(self, &held.token, "holding preserved work")?;
412            }
413        }
414        // Both of these name a session, so both are checked twice over: the token
415        // has to be a plain name, because it goes on to spell the file its stream is
416        // written in, and it has to name a session this state actually holds. A
417        // document that closes or publishes a session nobody opened describes a run
418        // that could not have happened, and answering `recoverable` or `session`
419        // from it would be answering from a fiction rather than refusing one.
420        for token in &self.closed_sessions {
421            opened(self, token, "closed")?;
422        }
423        for (token, origin) in &self.session_identities {
424            opened(self, token, "given an identity")?;
425            // The value as well as the key: this is what `identity_for` answers with,
426            // and it goes on to spell the slug a change request is opened against and
427            // the label every one of that session's events carries. An identity this
428            // provider does not know is one it could not have opened the session for.
429            known_identity(self, origin, &format!("session {:?}", token.0))?;
430        }
431        for publication in &self.publications {
432            let session = opened(self, &publication.session, "published")?;
433            named_branch(&publication.branch, "the published branch")?;
434            // A publication of some other branch than the one the session is on is
435            // the same kind of fiction, and the harder one to spot afterwards: the
436            // branch is what a journey asserts the publication was of.
437            if publication.branch != session.branch {
438                return Err(Error::Invalid {
439                    reason: format!(
440                        "the publication of session {:?} names branch {:?}, but that session is \
441                         on {:?}",
442                        publication.session.0, publication.branch, session.branch
443                    ),
444                });
445            }
446        }
447        Ok(())
448    }
449
450    /// Every field an older readable document could hold means here what it meant
451    /// there, and the two the repository side gained in version 4 are absent from one
452    /// written before them — which is the answer, since that build held no hold and
453    /// counted no lines.
454    ///
455    /// Version 5's field is the exception, and it is carried rather than left at its
456    /// default: a document written before it *listed preserved work nobody had
457    /// published*, which is the `no` this build spells out. Left at the default it
458    /// would read as "nothing here can say", and a consumer's checked-in scenario
459    /// would start reporting work it had always called unpublished as work that may
460    /// have landed.
461    fn carry_forward(&mut self) {
462        if self.version < 5 {
463            for row in &mut self.preserved {
464                row.landed = Landed::No;
465            }
466        }
467        self.version = STATE_VERSION;
468    }
469}
470
471/// Refuse a record kept about a change request this state does not hold.
472fn opened_change(state: &HostState, id: &ChangeId, what: &str) -> Result<()> {
473    if state.changes.iter().any(|change| change.id == *id) {
474        return Ok(());
475    }
476    Err(Error::Invalid {
477        reason: format!(
478            "{what} is recorded for change request {:?}, but no change request by that \
479             identifier was opened",
480            id.0
481        ),
482    })
483}
484
485/// Refuse an identity key this provider was not seeded with.
486fn known_identity(state: &VcsState, origin: &str, what: &str) -> Result<()> {
487    if state
488        .identities
489        .iter()
490        .any(|identity| identity.origin == origin)
491    {
492        return Ok(());
493    }
494    Err(Error::Invalid {
495        reason: format!(
496            "{what} belongs to identity {origin:?}, which this provider does not know; {}",
497            known(state)
498        ),
499    })
500}
501
502/// A change request's title, refused when it names nothing.
503///
504/// The one thing a real host refuses about a title, and the only one this provider
505/// may: how long a title may be is the host's own rule rather than `onevcs`'s
506/// commit-subject rule, and a provider applying the stricter of the two would
507/// refuse what the host it stands in for accepts.
508pub(crate) fn titled(title: &str) -> Result<()> {
509    if title.trim().is_empty() {
510        return Err(Error::Invalid {
511            reason: "a change request's title is blank, so it names no change".to_owned(),
512        });
513    }
514    Ok(())
515}
516
517/// The session a token names, refused when this state does not hold one.
518fn opened<'a>(state: &'a VcsState, token: &SessionToken, what: &str) -> Result<&'a Session> {
519    if !events::is_safe_name(&token.0) {
520        return Err(Error::Invalid {
521            reason: format!("{:?} is not a session token", token.0),
522        });
523    }
524    session_of(state, token).ok_or_else(|| Error::Invalid {
525        reason: format!(
526            "session {:?} is {what} here, but no session by that token was opened",
527            token.0
528        ),
529    })
530}
531
532/// A seeded host side is refused if it holds a change nothing could address.
533impl Checked for HostState {
534    fn check(&self) -> Result<()> {
535        readable_version(self.version)?;
536        for change in &self.changes {
537            named_branch(&change.base, "the base of a seeded change request")?;
538            if change.id.0.is_empty() {
539                return Err(Error::Invalid {
540                    reason: "a seeded change request carries no identifier".to_owned(),
541                });
542            }
543            // The commit a change request's checks are reported against is the whole
544            // evidence that a change reached anything, and the real implementation
545            // refuses a host answer that names none rather than passing a blank one
546            // through. A seeded one is refused for the same reason.
547            if change.head_sha.0.trim().is_empty() {
548                return Err(Error::Invalid {
549                    reason: format!(
550                        "the seeded change request {:?} names no commit its checks are \
551                         reported against",
552                        change.id.0
553                    ),
554                });
555            }
556        }
557        // Both of these are recorded *about* a change request, by `open_change` and
558        // by nothing else, and both are read back by the id they are keyed under. An
559        // entry for a change nobody opened is one no call could ever reach, so it is
560        // refused rather than carried — unlike the checks, logs, and merge outcomes
561        // below it, which a journey deliberately seeds for a change it has not
562        // opened yet.
563        for (id, head) in &self.heads {
564            opened_change(self, id, "a head")?;
565            named_branch(head, "the head of a seeded change request")?;
566        }
567        for (id, title) in &self.titles {
568            opened_change(self, id, "a title")?;
569            // The real host refuses a title that names nothing, so a seeded one is
570            // refused for the same reason.
571            titled(title)?;
572        }
573        for id in self.bodies.keys() {
574            // Nothing is refused about the body itself: a host places no shape on
575            // prose, and a change request opened with an empty one is a scenario.
576            opened_change(self, id, "a body")?;
577        }
578        Ok(())
579    }
580
581    /// A version 2 document held no bodies, and reads as what it was: change
582    /// requests opened with none. There is nothing to fill in — an absent entry is
583    /// already that answer — so this is the version and nothing else.
584    fn carry_forward(&mut self) {
585        self.version = STATE_VERSION;
586    }
587}
588
589/// Refuse a document written at a version this build does not read.
590///
591/// Named rather than guessed at: a state whose shape is a later build's reads one
592/// way here and another way where that version is understood, and for a seeded
593/// scenario those two readings are two different tests. The refusal names the
594/// range as well as the version, because "too old" and "too new" are two different
595/// things to do about it — one is a document to re-seed, the other a build to
596/// update.
597fn readable_version(declared: u32) -> Result<()> {
598    if !(OLDEST_READABLE_VERSION..=STATE_VERSION).contains(&declared) {
599        return Err(Error::Invalid {
600            reason: format!(
601                "the document declares version {declared}; this build reads versions \
602                 {OLDEST_READABLE_VERSION} to {STATE_VERSION}"
603            ),
604        });
605    }
606    Ok(())
607}