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::rules::{Approvals, Drafts};
12use onevcs::{
13    ChangeId, ChangeRequest, Check, CheckSource, DraftReason, Error, Identity, Landed,
14    MergeOutcome, Recoverable, Result,
15};
16use onevcs::{MergePolicy, Publication, RequiredChecks, Session, SessionRequest, SessionToken};
17
18use crate::events;
19use crate::store::Checked;
20
21/// The version of the state document this build writes.
22///
23/// A file-backed state outlives the process that wrote it and is read by the next
24/// one, which makes it a stored contract like `onevcs`'s own registry document —
25/// and like that document, the version a document declares decides what is done
26/// with it rather than being guessed at. [`STATE_VERSION`] is the shape the goldens in
27/// `tests/golden/` hold, and those goldens are compared byte for byte, so a change
28/// to the document cannot reach a consumer without the diff saying so.
29///
30/// `2` was what both sides learned when publishing and closing a session came
31/// through the interface: [`VcsState::policy`], [`VcsState::closed_sessions`],
32/// [`VcsState::publications`], and [`HostState::titles`]. `3` is
33/// [`HostState::bodies`], the body a change request was opened with. `4` is the two
34/// fields a `Recoverable` gained inside [`VcsState::preserved`] — the live session
35/// holding a branch, and the lines it would land when it removes more than it adds.
36/// `5` is one more of those: whether the branch's work reached its base, and what
37/// says so. `6` is the two a `Check` gained inside [`HostState::checks`] — the
38/// commit the host attached that check to, and where the check is on the host. `7`
39/// is the two a draft change request needs — [`HostState::drafts`], the reason each
40/// change request was opened as a draft with, and [`HostState::made_ready`], the
41/// `ready_for_review` calls it took. `8` is the two an [`Identity`] inside
42/// [`VcsState::identities`] **lost** — `workflow` and `repo_type`, the registry's
43/// inferences from whether an origin had a host, which every decision they made now
44/// takes from the resolved publication policy instead. `9` is the draft reason inside
45/// [`HostState::drafts`] becoming one of two kinds and saying which — `kind` is
46/// `awaiting-release` or `held` — and [`HostState::described`], the descriptions a
47/// host was handed for a change request after it was opened. `10` is the failure
48/// vocabulary a publication's outcome inside [`VcsState::publications`] may name
49/// widening by one kind, `host-prerequisite` — no field moved, but a document naming
50/// it is one a version 9 build cannot read, and the version is how it says so. `11` is
51/// one more field a `Recoverable` gained inside [`VcsState::preserved`], the same way
52/// `4` and `5` were: where `onevcs preserve` put that branch on its identity's origin,
53/// and the commit the origin carries it at. `12` is the labels a session is opened
54/// with — [`VcsState::session_labels`], keyed by token the way its identity is — and
55/// the two fields a `Recoverable` gained inside [`VcsState::preserved`] to carry them:
56/// the session that answers for the row, and that session's labels. `13` is one more
57/// field a `Recoverable` gained there: the branch's retirement classification — whether
58/// it provably holds nothing beyond its base, was superseded by a retry that landed, or
59/// is kept, and the evidence for it. No provider here classifies a row, so a row this
60/// crate writes carries none; a scenario may seed one. `14` is the draft lifecycle:
61/// [`HostState::awaiting_checks`], the change requests opened as a draft while their
62/// required checks run, [`HostState::checks_after_lift`], the checks a host registers
63/// only once a change is lifted, and [`HostState::required_checks`], what the host
64/// says a merge into a base requires — beside [`VcsState::approvals`] and
65/// [`VcsState::drafts`], the two policy fields a provider's publication now routes
66/// the lifecycle on. A publication outcome inside [`VcsState::publications`] may also
67/// be `change-review-draft`. `15` is the field a `Session` gained inside
68/// [`VcsState::sessions`]: `conflict`, the merge a continued branch's session opened
69/// over and left in progress. No provider here merges a base into a branch, so a
70/// session this crate opens carries none; a scenario may seed one.
71///
72/// **Every change to the document is versioned, an added field included.** A field
73/// that only ever appears when it holds something is *compatible* — that is what
74/// [`OLDEST_READABLE_VERSION`] is for — but compatible is not the same as
75/// unremarkable: the version is how a consumer's checked-in scenario says which
76/// shape it was written against, and a document that gained a field without saying
77/// so leaves nothing able to tell "this build wrote no body" from "this document
78/// predates bodies". The two answers differ for exactly the journey this crate
79/// exists to support.
80pub const STATE_VERSION: u32 = 15;
81
82/// The oldest document version this build reads.
83///
84/// Every version from here to [`STATE_VERSION`] is read and carried forward on the
85/// way in, which is how `onevcs`'s own registry document treats its older
86/// versions: what separates a readable older version from a refused one is whether
87/// its every field still means here what it meant there. `2` to `3` added a field
88/// and changed none, so a version 2 document reads as one whose change requests
89/// were opened with no body — which is what they were; `3` to `4` added two the same
90/// way, so a version 3 document reads as one whose preserved rows say nothing about a
91/// hold or a line count, which is what they said. `4` to `5` added one that every row
92/// answers rather than one that appears when it holds something, so a version 4
93/// document's rows are carried forward as the answer that list *was*: preserved work
94/// nobody published, which is work that did not land. `5` to `6` added two that
95/// appear only when they hold something, so a version 5 document's checks read as
96/// checks whose commit and address that build never recorded — which is what they
97/// were, and the one thing that must not be filled in from the change request's own
98/// head. `6` to `7` added two more of that kind, so a version 6 document reads as one
99/// whose change requests were opened before this crate could draft one — which is what
100/// they were: no draft reason recorded for any of them, and no lift ever asked for.
101/// `7` to `8` *removed* two from each identity, and a version 7 document reads past
102/// them: an identity is its origin and its gate here as it is in `onevcs`, and the two
103/// keys beside them are ones this build has no opinion on. `8` to `9` gave every
104/// draft reason a `kind`, and a reason written without one is read as the one kind
105/// there was — `awaiting-release`, whose four fields it carries unchanged — which is
106/// `drafts_of_any_version`'s whole job; the descriptions beside it are absent from a
107/// document written before them, which is the answer, since that build could describe
108/// nothing. `9` to `10` changed no field and no meaning: every failure kind a version 9
109/// document can hold is spelled here as it was there and means what it meant, so it
110/// reads unchanged and needs no carrying forward beyond its version. `10` to `11` added
111/// one that appears only when it holds something, so a version 10 document's preserved
112/// rows read as rows saying nothing about an origin — which is what they said, since
113/// that build had no verb that could put a branch on one. `11` to `12` added the
114/// labels, which appear only where a session was opened with some, and the two row
115/// fields that carry them, which a version 11 row reads as absent: a session nobody
116/// labelled, and a row that names no session — which is what that build's rows said,
117/// since it recorded neither. `12` to `13` added the row's retirement, which appears only
118/// where a row holds one, so a version 12 row reads as one nothing classified — which
119/// is what it was, since that build had no classification to record. `13` to `14`
120/// added fields that appear only when they hold something, so a version 13 document
121/// reads as one whose change requests were opened before the lifecycle drafted any,
122/// whose checks never change on a lift, whose host declares its required checks by
123/// the checks it was seeded with, and whose policy leaves approvals and drafts at
124/// their defaults — which is what that build published under. `14` to `15` added the
125/// session's conflict, which appears only where a session holds one, so a version 14
126/// document's sessions read as sessions that opened clean — which is what they were,
127/// since that build opened none over a merge.
128///
129/// `1` is refused rather than read for the opposite reason: it describes a provider
130/// that could not publish, and every session in it would read back as open — a
131/// wrong answer where a journey asserting on a session it had closed needs a
132/// refusal.
133pub const OLDEST_READABLE_VERSION: u32 = 2;
134
135/// Everything the repository side of a run knows about itself.
136///
137/// Every field is public and serializable, so a journey both seeds a scenario and
138/// asserts on what a run left behind. Everything but the version is omitted when
139/// it holds nothing, so a hand-written document names only the part of a scenario
140/// that matters — and a document written by a build that knew fewer fields still
141/// reads here.
142#[derive(Debug, Clone, Serialize, Deserialize)]
143#[serde(default)]
144pub struct VcsState {
145    /// The schema version this state was written at. A document that names none is
146    /// the one this build writes.
147    // llmlint: ignore[boundary_inputs_validated] deciding what to do with a version this
148    // build does not read is the whole of the check — and it is in `Checked::check` below,
149    // where a document is read, rather than here where serde only proves the shape.
150    pub version: u32,
151    /// The repository identities this provider can resolve. A
152    /// [`SessionRequest::repo`] naming none of them is refused, the way an
153    /// unregistered repository is.
154    #[serde(skip_serializing_if = "Vec::is_empty")]
155    pub identities: Vec<Identity>,
156    /// Every session opened or seeded, in the order they were opened.
157    #[serde(skip_serializing_if = "Vec::is_empty")]
158    pub sessions: Vec<Session>,
159    /// Which identity each session belongs to.
160    ///
161    /// Beyond the sketch this crate was specified from, and unavoidable: a
162    /// [`Session`] carries no identity, and a [`Recoverable`] must name one — so
163    /// preserving a session's branch could not answer the question `recoverable`
164    /// asks without this. `open_session` records it; nothing else writes it.
165    // llmlint: ignore[invalid_states_unrepresentable] an identity key is a `String`
166    // everywhere the crate this mirrors spells one — `Recoverable.identity`,
167    // `Identity.origin`, the registry document's own map key — and a newtype here would
168    // make a seeded state disagree with the types it is made of. Every value written to
169    // this map came out of `identity_of`, so it names an identity this provider holds.
170    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
171    pub session_identities: BTreeMap<SessionToken, String>,
172    /// The labels each session was opened with, for the sessions opened with any.
173    ///
174    /// Keyed by token the way [`session_identities`](Self::session_identities) is,
175    /// and for the same reason: a [`Session`] carries no labels, and both `session
176    /// holders` and every `recoverable` row report them. `open_session` records
177    /// them; nothing else writes it.
178    // llmlint: ignore[invalid_states_unrepresentable] keyed by session token, exactly as
179    // `session_identities` above is and for the same reason it gives.
180    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
181    pub session_labels: BTreeMap<SessionToken, BTreeMap<String, String>>,
182    /// Preserved work, newest last, as `recoverable` reports it.
183    ///
184    /// [`Recoverable`] rather than `PreservedBranch` — it *contains* the preserved
185    /// branch and adds the identity, the checkout, why the workstream stopped, and
186    /// the command that lands it, none of which are derivable from the branch
187    /// alone. One list rather than two that could disagree.
188    #[serde(skip_serializing_if = "Vec::is_empty")]
189    pub preserved: Vec<Recoverable>,
190    /// The sessions that have been closed. Every other session here is open.
191    ///
192    /// One way to say closed rather than two, so a scenario written by hand names
193    /// only the sessions whose lifecycle is not the one they were opened in.
194    // llmlint: ignore[invalid_states_unrepresentable] keyed by session token, exactly as
195    // `session_identities` above is and for the same reason: this document is a scenario
196    // somebody writes by hand, and a session is named once under `sessions` with the rest
197    // of the state keyed to it rather than nested inside a shape that could hold only one
198    // arrangement. A token here that names no opened session is refused in
199    // `Checked::check`, where the document is read — the same trust boundary every other
200    // cross-reference in it is checked at.
201    #[serde(skip_serializing_if = "BTreeSet::is_empty")]
202    pub closed_sessions: BTreeSet<SessionToken>,
203    /// The policy this provider publishes under.
204    ///
205    /// The answer a rules file gives the real implementation, which a provider has
206    /// none of — so a journey states it, and unset is the policy the contract's own
207    /// `default:` names ([`DEFAULT_PUBLICATION`](crate::DEFAULT_PUBLICATION)). A
208    /// per-run policy narrows it through [`MergePolicy::narrow`], which is the
209    /// rules system's rule rather than a restatement of it here.
210    #[serde(skip_serializing_if = "Option::is_none")]
211    pub policy: Option<MergePolicy>,
212    /// Whether this provider's changes need an approval, which is the other half of
213    /// what decides a green draft's ending: `change-open` with approvals required
214    /// keeps it for its user's review. Unset is the contract's own `default:`,
215    /// [`DEFAULT_APPROVALS`](crate::DEFAULT_APPROVALS).
216    #[serde(skip_serializing_if = "Option::is_none")]
217    pub approvals: Option<Approvals>,
218    /// The `drafts:` a rules file would give this provider's identity. Unset, and
219    /// each key it leaves unset, is the shipped default: the lifecycle on and the
220    /// early-lift warning on.
221    #[serde(skip_serializing_if = "Option::is_none")]
222    pub drafts: Option<Drafts>,
223    /// Every publication this provider performed, in the order it performed them.
224    ///
225    /// Both a record a journey asserts on and the answer to "has this session been
226    /// published already": a second publication of a session that landed has
227    /// nothing the base does not already carry, which is what the real
228    /// implementation reports for the same reason.
229    // llmlint: ignore[invalid_states_unrepresentable] this holds `onevcs::Publication`
230    // verbatim — the value `Vcs::publish` handed back, carrying its own session and branch
231    // — so a journey asserts on exactly what a caller would receive. A shape that made
232    // "this publication is of some other session's branch" unrepresentable could not hold
233    // that type, and would be a second spelling of the answer the crate next door already
234    // has. The cross-reference is checked in `Checked::check` instead, where the document
235    // is read.
236    #[serde(skip_serializing_if = "Vec::is_empty")]
237    pub publications: Vec<Publication>,
238}
239
240/// A repository side that knows nothing, at the version this build writes.
241impl Default for VcsState {
242    fn default() -> Self {
243        Self {
244            version: STATE_VERSION,
245            identities: Vec::new(),
246            sessions: Vec::new(),
247            session_identities: BTreeMap::new(),
248            session_labels: BTreeMap::new(),
249            preserved: Vec::new(),
250            closed_sessions: BTreeSet::new(),
251            policy: None,
252            approvals: None,
253            drafts: None,
254            publications: Vec::new(),
255        }
256    }
257}
258
259/// Everything the remote-host side of a run knows about itself.
260///
261/// Omitted-when-empty and versioned for the same reasons [`VcsState`] is.
262#[derive(Debug, Clone, Serialize, Deserialize)]
263#[serde(default)]
264pub struct HostState {
265    /// The schema version this state was written at. A document that names none is
266    /// the one this build writes.
267    // llmlint: ignore[boundary_inputs_validated] as on `VcsState::version`: the decision
268    // about an unreadable version is made in `Checked::check`, where the document is read.
269    pub version: u32,
270    /// Who the host says is calling. Empty is refused, exactly as a `gh` that
271    /// reports no authenticated user is.
272    // llmlint: ignore[invalid_states_unrepresentable] the interface this satisfies is
273    // `authenticated_user() -> Result<String>`, so the login is a `String` by contract and
274    // the one unusable value — a host that names nobody — is refused where it is read
275    // rather than made unrepresentable in a state a journey writes by hand.
276    pub authenticated_user: String,
277    /// Every change request that has been opened or seeded.
278    #[serde(skip_serializing_if = "Vec::is_empty")]
279    pub changes: Vec<ChangeRequest>,
280    /// The head branch each change request was opened from.
281    ///
282    /// Beyond the sketch, and unavoidable: [`ChangeRequest`] records only the base
283    /// it targets, and `find_changes` matches on the head as well.
284    // llmlint: ignore[invalid_states_unrepresentable] the matching `ChangeSpec.head` and
285    // `ChangeRequest.base` are `String` in the contract this mirrors, and a validated ref
286    // type here would disagree with them. Every value written to this map went through
287    // `addressable` in `open_change` first, which is the same refusal the real
288    // implementation makes at the same point.
289    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
290    pub heads: BTreeMap<ChangeId, String>,
291    /// The title each change request was opened under.
292    ///
293    /// Beyond the sketch, and for the same reason [`heads`](HostState::heads) is:
294    /// [`ChangeRequest`] records neither, and the title is what a publication's
295    /// commit subject becomes — so a journey asserting that the subject it asked
296    /// for is the one the host was given has nowhere else to read it.
297    // llmlint: ignore[invalid_states_unrepresentable] this records the `ChangeSpec.title`
298    // the contract fixes as a `String`, so a validated type here would disagree with the
299    // one it mirrors. `Subject` is not that type: it is `onevcs`'s rule for a *commit
300    // subject*, and a host's own limit is its own — spelling it here would
301    // refuse a seeded title a real host accepts, which is drift in the direction that
302    // looks like rigour. What the host itself refuses is a title that names nothing, and
303    // that is refused below and in `open_change`, at the boundary the value arrives at.
304    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
305    pub titles: BTreeMap<ChangeId, String>,
306    /// The body each change request was opened with, for the change requests that
307    /// were opened with one.
308    ///
309    /// Beside [`titles`](HostState::titles) and for its reason: the body is what a
310    /// caller passes on the `PublishRequest` and nothing else records it, so a
311    /// journey asserting that the body it drafted is the one the host was given has
312    /// nowhere else to read it. A change request with no entry was opened with no
313    /// body at all, which is what a publication nobody gave one does — the two are
314    /// different scenarios, and an empty string is the first rather than the second.
315    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
316    pub bodies: BTreeMap<ChangeId, String>,
317    /// The checks the host reports on each change request. A change with no entry
318    /// has no checks, which is what a repository with no CI reports.
319    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
320    pub checks: BTreeMap<ChangeId, Vec<Check>>,
321    /// The log the host hands over for a check, keyed by change request and then by
322    /// check name. Beyond the sketch: `check_log` is one of the six methods, and
323    /// without this the only log a journey could asssert on is a synthesized one.
324    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
325    pub check_logs: BTreeMap<ChangeId, BTreeMap<String, String>>,
326    /// The reason each change request that was opened as a **draft** was drafted
327    /// with, for the change requests that were.
328    ///
329    /// Beside [`bodies`](HostState::bodies) and for its reason: the reason is what a
330    /// caller passes on the `PublishRequest` and this is where a journey reads back
331    /// that the host was given it. A change with no entry is not a draft, which is
332    /// what every change request opened without one is.
333    ///
334    /// Nothing is refused about the reason itself here. Its shape — that every field
335    /// of it renders as the one line it is printed on — is `onevcs`'s own rule, and
336    /// it is applied where a publication takes one in, before any host is asked.
337    #[serde(
338        skip_serializing_if = "BTreeMap::is_empty",
339        deserialize_with = "drafts_of_any_version"
340    )]
341    pub drafts: BTreeMap<ChangeId, DraftReason>,
342    /// Every `ready_for_review` call this host has taken, in the order it took them
343    /// — the lifts it was asked to perform, never a request for a *reviewer*.
344    ///
345    /// A list rather than a set, and beyond the sketch for a reason a set could not
346    /// serve: lifting a draft is required to be *idempotent*, so what a journey
347    /// asserts is that a second publication asked the host for nothing — and only a
348    /// record of the calls themselves can say that. A change named here is not a
349    /// draft any more, whatever [`drafts`](HostState::drafts) says it was opened as.
350    #[serde(skip_serializing_if = "Vec::is_empty")]
351    pub made_ready: Vec<ChangeId>,
352    /// The change requests opened as a draft **while their required checks run** —
353    /// the lifecycle's draft, which no caller gave a reason for and so is not in
354    /// [`drafts`](HostState::drafts). A change named here is a draft until
355    /// [`made_ready`](HostState::made_ready) names it.
356    #[serde(skip_serializing_if = "BTreeSet::is_empty")]
357    pub awaiting_checks: BTreeSet<ChangeId>,
358    /// The checks the host reports on a change request once it has been lifted out of
359    /// its draft, in place of [`checks`](HostState::checks).
360    ///
361    /// What a repository whose workflow skips drafts looks like from outside: the
362    /// draft's checks are skipped or absent, and the run the lift triggers registers
363    /// after it. A change with no entry reports the same checks either side of a lift.
364    ///
365    /// A publication tells the run a lift triggered from the draft's by the run's own
366    /// identity, as it would on a real host: a check named here that the draft also
367    /// reported is a new run — running or settled — only where its
368    /// [`started_at`](Check::started_at) is one no draft-era run of that check reported. So seed a re-run with a start of its own — an entry repeating
369    /// the draft's start, or reporting none, is the draft's run still standing.
370    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
371    pub checks_after_lift: BTreeMap<ChangeId, Vec<Check>>,
372    /// What this host answers when asked which checks a merge into a base requires.
373    ///
374    /// Unset is a host whose branch protection names exactly the checks it was seeded
375    /// as required, on any change request — a complete answer, and an empty one where
376    /// none is seeded required. Seeded, it is the answer for every base: an empty
377    /// complete one is a repository declaring no required check, and one naming an
378    /// `unconsulted` source is the incomplete answer a narrower credential gets.
379    #[serde(skip_serializing_if = "Option::is_none")]
380    pub required_checks: Option<RequiredChecks>,
381    /// Every `describe_change` call this host has taken, in the order it took them:
382    /// which change request, the title it was handed when it was handed one, and the
383    /// body.
384    ///
385    /// The calls themselves, for the reason [`made_ready`](HostState::made_ready) is:
386    /// what a journey asks is what a closeout *wrote*, call by call, and the current
387    /// title and body — which each call also writes into
388    /// [`titles`](HostState::titles) and [`bodies`](HostState::bodies), so
389    /// `change_description` answers from the same record `open_change` wrote — can
390    /// only say where the description ended up.
391    #[serde(skip_serializing_if = "Vec::is_empty")]
392    pub described: Vec<Described>,
393    /// Which sources this host answers about its checks from, which is what the
394    /// real implementation reports alongside them.
395    ///
396    /// Unset is a credential allowed to read everything: the whole rollup, exactly
397    /// what a host with nothing to hide reports. A journey states a narrower set to
398    /// be the credential the real one meets in CI — a fine-grained token, which
399    /// cannot read check runs at all and sees GitHub Actions and nothing else — and
400    /// states an *empty* one to be a credential that can read no source at all,
401    /// which is a refusal rather than "no checks". Unset and empty are therefore
402    /// different scenarios, which is why this is an `Option` rather than a set whose
403    /// emptiness means "not stated".
404    #[serde(skip_serializing_if = "Option::is_none")]
405    pub check_sources: Option<BTreeSet<CheckSource>>,
406    /// What merging each change request did.
407    ///
408    /// Both a script and a record: an entry seeded here is what `merge` answers,
409    /// whatever the policy asks for — which is how a journey expresses a host that
410    /// queues or refuses — and a merge the policy decided is written back here.
411    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
412    pub merges: BTreeMap<ChangeId, MergeOutcome>,
413}
414
415/// One description a host was handed for a change request after it was opened.
416///
417/// What `RemoteHost::describe_change` was given, verbatim: the title only where the
418/// call carried one, because a call that replaced the body alone left the title as
419/// it was, and a record that filled it in would say the caller wrote a title nobody
420/// wrote.
421// llmlint: ignore[invalid_states_unrepresentable] the title and body are the `&str`s the
422// seam hands over — a host places no shape on prose, and `onevcs`'s own `Subject` rule
423// was applied where the description was composed, before any host was asked.
424#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
425pub struct Described {
426    /// The change request the description was written to.
427    pub id: ChangeId,
428    /// The title the call replaced the change request's with, when it replaced one.
429    #[serde(default, skip_serializing_if = "Option::is_none")]
430    pub title: Option<String>,
431    /// The body the call replaced the change request's with.
432    pub body: String,
433}
434
435/// The `drafts` map of a document at any readable version.
436///
437/// A document written before version 9 spells a draft reason as the four fields of
438/// the one kind there was and no `kind` beside them; this build's reason is one of
439/// two kinds and says which. So a reason arriving without a `kind` is read as
440/// `awaiting-release` — exactly what it was — rather than refused, which is what
441/// keeps a consumer's checked-in scenario readable across the bump. A reason that
442/// *names* a kind is read as it names it, so nothing written by this build is
443/// reinterpreted.
444fn drafts_of_any_version<'de, D>(
445    deserializer: D,
446) -> std::result::Result<BTreeMap<ChangeId, DraftReason>, D::Error>
447where
448    D: serde::Deserializer<'de>,
449{
450    let raw: BTreeMap<ChangeId, serde_json::Map<String, serde_json::Value>> =
451        Deserialize::deserialize(deserializer)?;
452    raw.into_iter()
453        .map(|(id, mut fields)| {
454            fields
455                .entry("kind")
456                .or_insert_with(|| serde_json::Value::from("awaiting-release"));
457            serde_json::from_value::<DraftReason>(serde_json::Value::Object(fields))
458                .map(|reason| (id, reason))
459                .map_err(serde::de::Error::custom)
460        })
461        .collect()
462}
463
464/// Who a host with nothing seeded says is calling.
465///
466/// A host that answers nobody is refused by the real implementation, so a default
467/// state that answered nobody would be a provider that cannot run a publication
468/// until it is configured.
469pub const DEFAULT_AUTHENTICATED_USER: &str = "onevcs-testing";
470
471impl Default for HostState {
472    fn default() -> Self {
473        Self {
474            version: STATE_VERSION,
475            authenticated_user: DEFAULT_AUTHENTICATED_USER.to_owned(),
476            changes: Vec::new(),
477            heads: BTreeMap::new(),
478            titles: BTreeMap::new(),
479            bodies: BTreeMap::new(),
480            drafts: BTreeMap::new(),
481            made_ready: Vec::new(),
482            awaiting_checks: BTreeSet::new(),
483            checks_after_lift: BTreeMap::new(),
484            required_checks: None,
485            described: Vec::new(),
486            checks: BTreeMap::new(),
487            check_logs: BTreeMap::new(),
488            check_sources: None,
489            merges: BTreeMap::new(),
490        }
491    }
492}
493
494/// The identity a session request names, or the reason none of them is it.
495///
496/// Three ways to name one, mirroring what the registry accepts: the identity key
497/// itself, the `owner/name` tail of it, or the bare repository name.
498pub(crate) fn identity_of<'a>(state: &'a VcsState, origin_or_path: &str) -> Option<&'a Identity> {
499    let wanted = origin_or_path.trim_end_matches('/');
500    state
501        .identities
502        .iter()
503        .find(|identity| identity.origin == wanted)
504        .or_else(|| {
505            state.identities.iter().find(|identity| {
506                identity
507                    .origin
508                    .rsplit('/')
509                    .next()
510                    .is_some_and(|name| name == wanted)
511                    || identity.origin.ends_with(&format!("/{wanted}"))
512            })
513        })
514}
515
516/// The known identities, as a refusal names them.
517pub(crate) fn known(state: &VcsState) -> String {
518    if state.identities.is_empty() {
519        return "this provider was seeded with no identities".to_owned();
520    }
521    let names: Vec<&str> = state
522        .identities
523        .iter()
524        .map(|identity| identity.origin.as_str())
525        .collect();
526    format!("it knows {}", names.join(", "))
527}
528
529/// The identity a session belongs to, or the reason this provider cannot say.
530///
531/// `open_session` records it and nothing else writes it, so a session that arrived
532/// in a hand-written scenario without one is refused here rather than published
533/// against a repository nobody named.
534pub(crate) fn identity_for(state: &VcsState, token: &SessionToken) -> Result<String> {
535    state
536        .session_identities
537        .get(token)
538        .cloned()
539        .ok_or_else(|| Error::Invalid {
540            reason: format!(
541                "this provider has no record of session {:?}, so it cannot say which identity \
542                 its work belongs to",
543                token.0
544            ),
545        })
546}
547
548/// The session a token names.
549pub(crate) fn session_of<'a>(state: &'a VcsState, token: &SessionToken) -> Option<&'a Session> {
550    state
551        .sessions
552        .iter()
553        .find(|session| session.token == *token)
554}
555
556/// The branch a request asks for, or the one that is derived from the token.
557///
558/// `branch` and `branch_name` are two answers to one question — *continue this* and
559/// *cut one at this* — so a request naming both is refused here as the real
560/// implementation refuses it: that refusal is about the shape of the request rather
561/// than about anything a repository does, and a consumer proving it must meet the
562/// same answer on either side.
563///
564/// **What a provider deliberately does not do to `branch_name` is the rest**, and it
565/// is not approximated: the host's branch prefix is read out of an `onevcs` state
566/// root no provider has, and the first-free suffix is searched against an identity's
567/// checkouts and its origin, which a provider has neither of. So the name is taken as
568/// it was proposed and refused — naming it — where git would refuse it, rather than
569/// being sanitized by a second copy of a grammar that would then have to be held to
570/// the first. A consumer proving what the prefix, the sanitizer and the collision
571/// suffix do drives the real `onevcs`, which is where all three live.
572pub(crate) fn requested_branch(req: &SessionRequest, token: &SessionToken) -> Result<String> {
573    if let (Some(pinned), Some(proposed)) = (&req.branch, &req.branch_name) {
574        return Err(Error::Invalid {
575            reason: format!(
576                "this request names both a branch to continue ({pinned:?}) and a name to cut \
577                 ({proposed:?}), which are two answers to one question"
578            ),
579        });
580    }
581    let name = req
582        .branch
583        .clone()
584        .or_else(|| req.branch_name.clone())
585        .unwrap_or_else(|| format!("onevcs/{}", token.0));
586    named_branch(&name, "the branch")?;
587    Ok(name)
588}
589
590/// A branch name, refused here if git would refuse it.
591///
592/// The real implementation asks `git check-ref-format`, which is the parser that
593/// decides; a provider with no git carries `git-check-ref-format(1)`'s rules
594/// instead. That is a restatement, so it is gated rather than trusted:
595/// `refs.rs` in the suite runs both this and git itself over a table of names
596/// and holds them to each other, because a copy of somebody else's grammar with
597/// no gate is a copy that drifts.
598///
599/// One deliberate difference, and the gate knows about it: a leading `-` is
600/// refused here even though git accepts it as a ref, because such a name reaches
601/// a command line as an option rather than as the branch it spells.
602pub(crate) fn named_branch(value: &str, what: &str) -> Result<()> {
603    // Rule 1 is per slash-separated component; the rest are about the whole name.
604    let components_usable = !value.is_empty()
605        && value.split('/').all(|component| {
606            !component.is_empty() && !component.starts_with('.') && !component.ends_with(".lock")
607        });
608    let usable = components_usable
609        && !value.starts_with('-')
610        && !value.contains("..")
611        && !value.contains("@{")
612        && !value.ends_with('.')
613        && !value.ends_with('/')
614        && !value.chars().any(|c| {
615            c.is_whitespace() || c.is_ascii_control() || c == '\u{7f}' || "~^:?*[\\".contains(c)
616        });
617    if !usable {
618        return Err(Error::Invalid {
619            reason: format!("{what} {value:?} is a name git would not accept"),
620        });
621    }
622    Ok(())
623}
624
625/// A label, refused here where the real implementation refuses one: a key is one or
626/// more of `A-Z`, `a-z`, `0-9`, `_` and `-`, and a value is one line. The same rule
627/// spelled twice on purpose, for the reason [`named_branch`] gives — a provider with
628/// no `onevcs` state root carries the grammar, and the journeys over both providers
629/// hold the two to each other.
630pub(crate) fn label_pair(key: &str, value: &str) -> Result<()> {
631    let key_usable = !key.is_empty()
632        && key
633            .chars()
634            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
635    if !key_usable {
636        return Err(Error::Invalid {
637            reason: format!(
638                "{key:?} is not a label key; a key is one or more of A-Z, a-z, 0-9, `_` and `-`"
639            ),
640        });
641    }
642    if value.contains('\n') {
643        return Err(Error::Invalid {
644            reason: format!(
645                "the value of label {key:?} holds a newline; a label's value is one line"
646            ),
647        });
648    }
649    Ok(())
650}
651
652/// A seeded repository side is refused if it holds a session nothing could act on.
653impl Checked for VcsState {
654    fn check(&self) -> Result<()> {
655        readable_version(self.version)?;
656        for session in &self.sessions {
657            // The token names a file under the state root, and a branch goes on to
658            // spell a ref; both arrive from whoever wrote the document.
659            if !events::is_safe_name(&session.token.0) {
660                return Err(Error::Invalid {
661                    reason: format!("{:?} is not a session token", session.token.0),
662                });
663            }
664            named_branch(&session.branch, "the branch")?;
665            named_branch(&session.base, "the base")?;
666        }
667        for row in &self.preserved {
668            known_identity(self, &row.identity, "preserved work")?;
669            named_branch(&row.branch.branch, "the preserved branch")?;
670            named_branch(&row.branch.base, "the preserved branch's base")?;
671            // The hold names a session, so it is checked like the three below: a row
672            // held by a session nobody opened is the same fiction, and the costly one
673            // — it is the session an operator is told to wait for or close.
674            if let Some(held) = &row.held_by {
675                opened(self, &held.token, "holding preserved work")?;
676            }
677        }
678        // Both of these name a session, so both are checked twice over: the token
679        // has to be a plain name, because it goes on to spell the file its stream is
680        // written in, and it has to name a session this state actually holds. A
681        // document that closes or publishes a session nobody opened describes a run
682        // that could not have happened, and answering `recoverable` or `session`
683        // from it would be answering from a fiction rather than refusing one.
684        for token in &self.closed_sessions {
685            opened(self, token, "closed")?;
686        }
687        for (token, labels) in &self.session_labels {
688            opened(self, token, "labelled")?;
689            for (key, value) in labels {
690                label_pair(key, value)?;
691            }
692        }
693        for (token, origin) in &self.session_identities {
694            opened(self, token, "given an identity")?;
695            // The value as well as the key: this is what `identity_for` answers with,
696            // and it goes on to spell the slug a change request is opened against and
697            // the label every one of that session's events carries. An identity this
698            // provider does not know is one it could not have opened the session for.
699            known_identity(self, origin, &format!("session {:?}", token.0))?;
700        }
701        for publication in &self.publications {
702            let session = opened(self, &publication.session, "published")?;
703            named_branch(&publication.branch, "the published branch")?;
704            // A publication of some other branch than the one the session is on is
705            // the same kind of fiction, and the harder one to spot afterwards: the
706            // branch is what a journey asserts the publication was of.
707            if publication.branch != session.branch {
708                return Err(Error::Invalid {
709                    reason: format!(
710                        "the publication of session {:?} names branch {:?}, but that session is \
711                         on {:?}",
712                        publication.session.0, publication.branch, session.branch
713                    ),
714                });
715            }
716        }
717        Ok(())
718    }
719
720    /// Every field an older readable document could hold means here what it meant
721    /// there, and the two the repository side gained in version 4 are absent from one
722    /// written before them — which is the answer, since that build held no hold and
723    /// counted no lines.
724    ///
725    /// Version 5's field is the exception, and it is carried rather than left at its
726    /// default: a document written before it *listed preserved work nobody had
727    /// published*, which is the `no` this build spells out. Left at the default it
728    /// would read as "nothing here can say", and a consumer's checked-in scenario
729    /// would start reporting work it had always called unpublished as work that may
730    /// have landed.
731    fn carry_forward(&mut self) {
732        if self.version < 5 {
733            for row in &mut self.preserved {
734                row.landed = Landed::No;
735            }
736        }
737        self.version = STATE_VERSION;
738    }
739}
740
741/// Refuse a record kept about a change request this state does not hold.
742fn opened_change(state: &HostState, id: &ChangeId, what: &str) -> Result<()> {
743    if state.changes.iter().any(|change| change.id == *id) {
744        return Ok(());
745    }
746    Err(Error::Invalid {
747        reason: format!(
748            "{what} is recorded for change request {:?}, but no change request by that \
749             identifier was opened",
750            id.0
751        ),
752    })
753}
754
755/// Refuse an identity key this provider was not seeded with.
756fn known_identity(state: &VcsState, origin: &str, what: &str) -> Result<()> {
757    if state
758        .identities
759        .iter()
760        .any(|identity| identity.origin == origin)
761    {
762        return Ok(());
763    }
764    Err(Error::Invalid {
765        reason: format!(
766            "{what} belongs to identity {origin:?}, which this provider does not know; {}",
767            known(state)
768        ),
769    })
770}
771
772/// A change request's title, refused when it names nothing.
773///
774/// The one thing a real host refuses about a title, and the only one this provider
775/// may: how long a title may be is the host's own rule rather than `onevcs`'s
776/// commit-subject rule, and a provider applying the stricter of the two would
777/// refuse what the host it stands in for accepts.
778pub(crate) fn titled(title: &str) -> Result<()> {
779    if title.trim().is_empty() {
780        return Err(Error::Invalid {
781            reason: "a change request's title is blank, so it names no change".to_owned(),
782        });
783    }
784    Ok(())
785}
786
787/// The session a token names, refused when this state does not hold one.
788fn opened<'a>(state: &'a VcsState, token: &SessionToken, what: &str) -> Result<&'a Session> {
789    if !events::is_safe_name(&token.0) {
790        return Err(Error::Invalid {
791            reason: format!("{:?} is not a session token", token.0),
792        });
793    }
794    session_of(state, token).ok_or_else(|| Error::Invalid {
795        reason: format!(
796            "session {:?} is {what} here, but no session by that token was opened",
797            token.0
798        ),
799    })
800}
801
802/// A seeded host side is refused if it holds a change nothing could address.
803impl Checked for HostState {
804    fn check(&self) -> Result<()> {
805        readable_version(self.version)?;
806        for change in &self.changes {
807            named_branch(&change.base, "the base of a seeded change request")?;
808            if change.id.0.is_empty() {
809                return Err(Error::Invalid {
810                    reason: "a seeded change request carries no identifier".to_owned(),
811                });
812            }
813            // The commit a change request's checks are reported against is the whole
814            // evidence that a change reached anything, and the real implementation
815            // refuses a host answer that names none rather than passing a blank one
816            // through. A seeded one is refused for the same reason.
817            if change.head_sha.0.trim().is_empty() {
818                return Err(Error::Invalid {
819                    reason: format!(
820                        "the seeded change request {:?} names no commit its checks are \
821                         reported against",
822                        change.id.0
823                    ),
824                });
825            }
826        }
827        // Both of these are recorded *about* a change request, by `open_change` and
828        // by nothing else, and both are read back by the id they are keyed under. An
829        // entry for a change nobody opened is one no call could ever reach, so it is
830        // refused rather than carried — unlike the checks, logs, and merge outcomes
831        // below it, which a journey deliberately seeds for a change it has not
832        // opened yet.
833        for (id, head) in &self.heads {
834            opened_change(self, id, "a head")?;
835            named_branch(head, "the head of a seeded change request")?;
836        }
837        for (id, title) in &self.titles {
838            opened_change(self, id, "a title")?;
839            // The real host refuses a title that names nothing, so a seeded one is
840            // refused for the same reason.
841            titled(title)?;
842        }
843        for id in self.bodies.keys() {
844            // Nothing is refused about the body itself: a host places no shape on
845            // prose, and a change request opened with an empty one is a scenario.
846            opened_change(self, id, "a body")?;
847        }
848        for (id, reason) in &self.drafts {
849            opened_change(self, id, "a draft reason")?;
850            // The publication rule the crate next door states, applied rather than
851            // restated: a seeded reason no publication could have carried is refused
852            // where the document is read, not answered from later.
853            reason.checked()?;
854        }
855        for id in &self.made_ready {
856            opened_change(self, id, "a lifted draft")?;
857        }
858        for id in &self.awaiting_checks {
859            opened_change(self, id, "a draft awaiting its checks")?;
860        }
861        for described in &self.described {
862            opened_change(self, &described.id, "a description")?;
863            // The real host refuses a title that names nothing, so a seeded one is
864            // refused for the same reason — and a body is prose, refused for nothing.
865            if let Some(title) = &described.title {
866                titled(title)?;
867            }
868        }
869        Ok(())
870    }
871
872    /// A version 2 document held no bodies, and a version 5 document's checks named
873    /// no commit; each reads as what it was — change requests opened with none, and
874    /// checks whose head that build never recorded. There is nothing to fill in — an
875    /// absent field is already that answer, and a check's commit is the one thing
876    /// that must never be inferred — so this is the version and nothing else. The one
877    /// carry a version 8 document needs, the `kind` its draft reasons lack, is done
878    /// where those are read (`drafts_of_any_version`), because it is a fact about
879    /// one value's shape rather than about the document.
880    fn carry_forward(&mut self) {
881        self.version = STATE_VERSION;
882    }
883}
884
885/// Refuse a document written at a version this build does not read.
886///
887/// Named rather than guessed at: a state whose shape is a later build's reads one
888/// way here and another way where that version is understood, and for a seeded
889/// scenario those two readings are two different tests. The refusal names the
890/// range as well as the version, because "too old" and "too new" are two different
891/// things to do about it — one is a document to re-seed, the other a build to
892/// update.
893fn readable_version(declared: u32) -> Result<()> {
894    if !(OLDEST_READABLE_VERSION..=STATE_VERSION).contains(&declared) {
895        return Err(Error::Invalid {
896            reason: format!(
897                "the document declares version {declared}; this build reads versions \
898                 {OLDEST_READABLE_VERSION} to {STATE_VERSION}"
899            ),
900        });
901    }
902    Ok(())
903}