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, CommentId, CommentKind, DraftReason, Error,
14    Identity, Landed, MergeOutcome, ReadCost, Recoverable, Result, Sha,
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. `16` is the failure
71/// vocabulary a publication's outcome inside [`VcsState::publications`] may name
72/// widening by one kind, `cancelled`, the way `10` widened it — no field moved, but a
73/// document naming it is one a version 15 build cannot read. No provider here waits on
74/// anything, so a publication this crate runs is never cancelled; a scenario may seed
75/// one. `17` is the field a `Retirement` gained inside a row of
76/// [`VcsState::preserved`]: `cause`, the read that failed for a branch kept as
77/// `unknown`, which every retirement writes — `null` for every other reason. No
78/// provider here classifies a branch, so a row this crate writes carries none; a
79/// scenario may seed one. `18` is what the record of a gate run and of a landing needs
80/// from a host: the field a `Check` gained inside [`HostState::checks`] —
81/// `completed_at`, when the host says that run completed — and
82/// [`HostState::merge_times`], when each merge this host performed reached its base.
83///
84/// **Every change to the document is versioned, an added field included.** A field
85/// that only ever appears when it holds something is *compatible* — that is what
86/// [`OLDEST_READABLE_VERSION`] is for — but compatible is not the same as
87/// unremarkable: the version is how a consumer's checked-in scenario says which
88/// shape it was written against, and a document that gained a field without saying
89/// so leaves nothing able to tell "this build wrote no body" from "this document
90/// predates bodies". The two answers differ for exactly the journey this crate
91/// exists to support.
92/// `19` adds the recovery branch tip; older rows default it to `None`. `20` is the
93/// review feedback a host holds: [`HostState::review_comments`], each change
94/// request's comments of every kind, [`HostState::replies`], every reply this host
95/// posted, and [`HostState::review_charges`], what it charges a read. `21` is what a
96/// stack of drafts needs from a host while people merge some of them on it:
97/// [`HostState::closed`], the change requests closed without merging,
98/// [`HostState::deleted_branches`], the branches gone from the origin,
99/// [`HostState::head_checks`], each required check's state per head commit, and
100/// [`HostState::ledger`], every call the host answered with what GitHub charges for it.
101/// `22` is what an elapsed watch arms: [`HostState::up_to_date_required`],
102/// [`HostState::allow_auto_merge`] and [`HostState::armed`], and a failed publication's
103/// armed merge. `23` is what a draft's watch reads per poll:
104/// [`HostState::check_readings`] and [`HostState::check_readings_after_lift`], the
105/// checks each reading of a change request reports in turn on each side of its lift,
106/// and [`HostState::head_activity`], what the host answers in turn about the work
107/// still running on its head.
108pub const STATE_VERSION: u32 = 23;
109
110/// The oldest document version this build reads.
111///
112/// Every version from here to [`STATE_VERSION`] is read and carried forward on the
113/// way in, which is how `onevcs`'s own registry document treats its older
114/// versions: what separates a readable older version from a refused one is whether
115/// its every field still means here what it meant there. `2` to `3` added a field
116/// and changed none, so a version 2 document reads as one whose change requests
117/// were opened with no body — which is what they were; `3` to `4` added two the same
118/// way, so a version 3 document reads as one whose preserved rows say nothing about a
119/// hold or a line count, which is what they said. `4` to `5` added one that every row
120/// answers rather than one that appears when it holds something, so a version 4
121/// document's rows are carried forward as the answer that list *was*: preserved work
122/// nobody published, which is work that did not land. `5` to `6` added two that
123/// appear only when they hold something, so a version 5 document's checks read as
124/// checks whose commit and address that build never recorded — which is what they
125/// were, and the one thing that must not be filled in from the change request's own
126/// head. `6` to `7` added two more of that kind, so a version 6 document reads as one
127/// whose change requests were opened before this crate could draft one — which is what
128/// they were: no draft reason recorded for any of them, and no lift ever asked for.
129/// `7` to `8` *removed* two from each identity, and a version 7 document reads past
130/// them: an identity is its origin and its gate here as it is in `onevcs`, and the two
131/// keys beside them are ones this build has no opinion on. `8` to `9` gave every
132/// draft reason a `kind`, and a reason written without one is read as the one kind
133/// there was — `awaiting-release`, whose four fields it carries unchanged — which is
134/// `drafts_of_any_version`'s whole job; the descriptions beside it are absent from a
135/// document written before them, which is the answer, since that build could describe
136/// nothing. `9` to `10` changed no field and no meaning: every failure kind a version 9
137/// document can hold is spelled here as it was there and means what it meant, so it
138/// reads unchanged and needs no carrying forward beyond its version. `10` to `11` added
139/// one that appears only when it holds something, so a version 10 document's preserved
140/// rows read as rows saying nothing about an origin — which is what they said, since
141/// that build had no verb that could put a branch on one. `11` to `12` added the
142/// labels, which appear only where a session was opened with some, and the two row
143/// fields that carry them, which a version 11 row reads as absent: a session nobody
144/// labelled, and a row that names no session — which is what that build's rows said,
145/// since it recorded neither. `12` to `13` added the row's retirement, which appears only
146/// where a row holds one, so a version 12 row reads as one nothing classified — which
147/// is what it was, since that build had no classification to record. `13` to `14`
148/// added fields that appear only when they hold something, so a version 13 document
149/// reads as one whose change requests were opened before the lifecycle drafted any,
150/// whose checks never change on a lift, whose host declares its required checks by
151/// the checks it was seeded with, and whose policy leaves approvals and drafts at
152/// their defaults — which is what that build published under. `14` to `15` added the
153/// session's conflict, which appears only where a session holds one, so a version 14
154/// document's sessions read as sessions that opened clean — which is what they were,
155/// since that build opened none over a merge. `15` to `16` changed no field and no
156/// meaning, as `9` to `10` did not: every failure kind a version 15 document can hold is
157/// spelled here as it was there, so it reads unchanged. `16` to `17` added the
158/// retirement's cause, which a version 16 retirement reads as `null` — which is what it
159/// said, since that build named no read that failed. `17` to `18` added two fields that
160/// appear only when they hold something, so a version 17 document's checks read as
161/// checks whose completion that build never recorded, and its merges as merges whose
162/// time it never recorded — which is what they were. `19` to `20` added three fields
163/// that appear only when they hold something, so a version 19 document reads as a
164/// host whose change requests carry no review feedback and that has posted no reply —
165/// which is what that build could hold. `20` to `21` added four more of that kind, so a
166/// version 20 document reads as a host on which nobody closed or deleted anything, whose
167/// checks are its change requests' own, and which has answered no call — which is what
168/// that build recorded. `21` to `22` added three host fields of that kind and one field
169/// of a failed publication, so a version 21 document reads as a host that requires no
170/// up-to-date branch, allows auto-merge and holds no armed merge, and as publications
171/// none of which left a merge armed — which is what that build could do. `22` to `23`
172/// added three host fields of that kind, so a version 22 document reads as a host whose
173/// checks hold still between readings and that reports nothing running on any head
174/// beyond its checks — which is what that build could answer.
175///
176/// `1` is refused rather than read for the opposite reason: it describes a provider
177/// that could not publish, and every session in it would read back as open — a
178/// wrong answer where a journey asserting on a session it had closed needs a
179/// refusal.
180pub const OLDEST_READABLE_VERSION: u32 = 2;
181
182/// Everything the repository side of a run knows about itself.
183///
184/// Every field is public and serializable, so a journey both seeds a scenario and
185/// asserts on what a run left behind. Everything but the version is omitted when
186/// it holds nothing, so a hand-written document names only the part of a scenario
187/// that matters — and a document written by a build that knew fewer fields still
188/// reads here.
189#[derive(Debug, Clone, Serialize, Deserialize)]
190#[serde(default)]
191pub struct VcsState {
192    /// The schema version this state was written at. A document that names none is
193    /// the one this build writes.
194    // llmlint: ignore[boundary_inputs_validated] deciding what to do with a version this
195    // build does not read is the whole of the check — and it is in `Checked::check` below,
196    // where a document is read, rather than here where serde only proves the shape.
197    pub version: u32,
198    /// The repository identities this provider can resolve. A
199    /// [`SessionRequest::repo`] naming none of them is refused, the way an
200    /// unregistered repository is.
201    #[serde(skip_serializing_if = "Vec::is_empty")]
202    pub identities: Vec<Identity>,
203    /// Every session opened or seeded, in the order they were opened.
204    #[serde(skip_serializing_if = "Vec::is_empty")]
205    pub sessions: Vec<Session>,
206    /// Which identity each session belongs to.
207    ///
208    /// Beyond the sketch this crate was specified from, and unavoidable: a
209    /// [`Session`] carries no identity, and a [`Recoverable`] must name one — so
210    /// preserving a session's branch could not answer the question `recoverable`
211    /// asks without this. `open_session` records it; nothing else writes it.
212    // llmlint: ignore[invalid_states_unrepresentable] an identity key is a `String`
213    // everywhere the crate this mirrors spells one — `Recoverable.identity`,
214    // `Identity.origin`, the registry document's own map key — and a newtype here would
215    // make a seeded state disagree with the types it is made of. Every value written to
216    // this map came out of `identity_of`, so it names an identity this provider holds.
217    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
218    pub session_identities: BTreeMap<SessionToken, String>,
219    /// The labels each session was opened with, for the sessions opened with any.
220    ///
221    /// Keyed by token the way [`session_identities`](Self::session_identities) is,
222    /// and for the same reason: a [`Session`] carries no labels, and both `session
223    /// holders` and every `recoverable` row report them. `open_session` records
224    /// them; nothing else writes it.
225    // llmlint: ignore[invalid_states_unrepresentable] keyed by session token, exactly as
226    // `session_identities` above is and for the same reason it gives.
227    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
228    pub session_labels: BTreeMap<SessionToken, BTreeMap<String, String>>,
229    /// Preserved work, newest last, as `recoverable` reports it.
230    ///
231    /// [`Recoverable`] rather than `PreservedBranch` — it *contains* the preserved
232    /// branch and adds the identity, the checkout, why the workstream stopped, and
233    /// the command that lands it, none of which are derivable from the branch
234    /// alone. One list rather than two that could disagree.
235    #[serde(skip_serializing_if = "Vec::is_empty")]
236    pub preserved: Vec<Recoverable>,
237    /// The sessions that have been closed. Every other session here is open.
238    ///
239    /// One way to say closed rather than two, so a scenario written by hand names
240    /// only the sessions whose lifecycle is not the one they were opened in.
241    // llmlint: ignore[invalid_states_unrepresentable] keyed by session token, exactly as
242    // `session_identities` above is and for the same reason: this document is a scenario
243    // somebody writes by hand, and a session is named once under `sessions` with the rest
244    // of the state keyed to it rather than nested inside a shape that could hold only one
245    // arrangement. A token here that names no opened session is refused in
246    // `Checked::check`, where the document is read — the same trust boundary every other
247    // cross-reference in it is checked at.
248    #[serde(skip_serializing_if = "BTreeSet::is_empty")]
249    pub closed_sessions: BTreeSet<SessionToken>,
250    /// The policy this provider publishes under.
251    ///
252    /// The answer a rules file gives the real implementation, which a provider has
253    /// none of — so a journey states it, and unset is the policy the contract's own
254    /// `default:` names ([`DEFAULT_PUBLICATION`](crate::DEFAULT_PUBLICATION)). A
255    /// per-run policy narrows it through [`MergePolicy::narrow`], which is the
256    /// rules system's rule rather than a restatement of it here.
257    #[serde(skip_serializing_if = "Option::is_none")]
258    pub policy: Option<MergePolicy>,
259    /// Whether this provider's changes need an approval, which is the other half of
260    /// what decides a green draft's ending: `change-open` with approvals required
261    /// keeps it for its user's review. Unset is the contract's own `default:`,
262    /// [`DEFAULT_APPROVALS`](crate::DEFAULT_APPROVALS).
263    #[serde(skip_serializing_if = "Option::is_none")]
264    pub approvals: Option<Approvals>,
265    /// The `drafts:` a rules file would give this provider's identity. Unset, and
266    /// each key it leaves unset, is the shipped default: the lifecycle on and the
267    /// early-lift warning on.
268    #[serde(skip_serializing_if = "Option::is_none")]
269    pub drafts: Option<Drafts>,
270    /// Every publication this provider performed, in the order it performed them.
271    ///
272    /// Both a record a journey asserts on and the answer to "has this session been
273    /// published already": a second publication of a session that landed has
274    /// nothing the base does not already carry, which is what the real
275    /// implementation reports for the same reason.
276    // llmlint: ignore[invalid_states_unrepresentable] this holds `onevcs::Publication`
277    // verbatim — the value `Vcs::publish` handed back, carrying its own session and branch
278    // — so a journey asserts on exactly what a caller would receive. A shape that made
279    // "this publication is of some other session's branch" unrepresentable could not hold
280    // that type, and would be a second spelling of the answer the crate next door already
281    // has. The cross-reference is checked in `Checked::check` instead, where the document
282    // is read.
283    #[serde(skip_serializing_if = "Vec::is_empty")]
284    pub publications: Vec<Publication>,
285}
286
287/// A repository side that knows nothing, at the version this build writes.
288impl Default for VcsState {
289    fn default() -> Self {
290        Self {
291            version: STATE_VERSION,
292            identities: Vec::new(),
293            sessions: Vec::new(),
294            session_identities: BTreeMap::new(),
295            session_labels: BTreeMap::new(),
296            preserved: Vec::new(),
297            closed_sessions: BTreeSet::new(),
298            policy: None,
299            approvals: None,
300            drafts: None,
301            publications: Vec::new(),
302        }
303    }
304}
305
306/// Everything the remote-host side of a run knows about itself.
307///
308/// Omitted-when-empty and versioned for the same reasons [`VcsState`] is.
309#[derive(Debug, Clone, Serialize, Deserialize)]
310#[serde(default)]
311pub struct HostState {
312    /// The schema version this state was written at. A document that names none is
313    /// the one this build writes.
314    // llmlint: ignore[boundary_inputs_validated] as on `VcsState::version`: the decision
315    // about an unreadable version is made in `Checked::check`, where the document is read.
316    pub version: u32,
317    /// Who the host says is calling. Empty is refused, exactly as a `gh` that
318    /// reports no authenticated user is.
319    // llmlint: ignore[invalid_states_unrepresentable] the interface this satisfies is
320    // `authenticated_user() -> Result<String>`, so the login is a `String` by contract and
321    // the one unusable value — a host that names nobody — is refused where it is read
322    // rather than made unrepresentable in a state a journey writes by hand.
323    pub authenticated_user: String,
324    /// Every change request that has been opened or seeded.
325    #[serde(skip_serializing_if = "Vec::is_empty")]
326    pub changes: Vec<ChangeRequest>,
327    /// The head branch each change request was opened from.
328    ///
329    /// Beyond the sketch, and unavoidable: [`ChangeRequest`] records only the base
330    /// it targets, and `find_changes` matches on the head as well.
331    // llmlint: ignore[invalid_states_unrepresentable] the matching `ChangeSpec.head` and
332    // `ChangeRequest.base` are `String` in the contract this mirrors, and a validated ref
333    // type here would disagree with them. Every value written to this map went through
334    // `addressable` in `open_change` first, which is the same refusal the real
335    // implementation makes at the same point.
336    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
337    pub heads: BTreeMap<ChangeId, String>,
338    /// The title each change request was opened under.
339    ///
340    /// Beyond the sketch, and for the same reason [`heads`](HostState::heads) is:
341    /// [`ChangeRequest`] records neither, and the title is what a publication's
342    /// commit subject becomes — so a journey asserting that the subject it asked
343    /// for is the one the host was given has nowhere else to read it.
344    // llmlint: ignore[invalid_states_unrepresentable] this records the `ChangeSpec.title`
345    // the contract fixes as a `String`, so a validated type here would disagree with the
346    // one it mirrors. `Subject` is not that type: it is `onevcs`'s rule for a *commit
347    // subject*, and a host's own limit is its own — spelling it here would
348    // refuse a seeded title a real host accepts, which is drift in the direction that
349    // looks like rigour. What the host itself refuses is a title that names nothing, and
350    // that is refused below and in `open_change`, at the boundary the value arrives at.
351    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
352    pub titles: BTreeMap<ChangeId, String>,
353    /// The body each change request was opened with, for the change requests that
354    /// were opened with one.
355    ///
356    /// Beside [`titles`](HostState::titles) and for its reason: the body is what a
357    /// caller passes on the `PublishRequest` and nothing else records it, so a
358    /// journey asserting that the body it drafted is the one the host was given has
359    /// nowhere else to read it. A change request with no entry was opened with no
360    /// body at all, which is what a publication nobody gave one does — the two are
361    /// different scenarios, and an empty string is the first rather than the second.
362    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
363    pub bodies: BTreeMap<ChangeId, String>,
364    /// The checks the host reports on each change request. A change with no entry
365    /// has no checks, which is what a repository with no CI reports.
366    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
367    pub checks: BTreeMap<ChangeId, Vec<Check>>,
368    /// The log the host hands over for a check, keyed by change request and then by
369    /// check name. Beyond the sketch: `check_log` is one of the six methods, and
370    /// without this the only log a journey could asssert on is a synthesized one.
371    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
372    pub check_logs: BTreeMap<ChangeId, BTreeMap<String, String>>,
373    /// The reason each change request that was opened as a **draft** was drafted
374    /// with, for the change requests that were.
375    ///
376    /// Beside [`bodies`](HostState::bodies) and for its reason: the reason is what a
377    /// caller passes on the `PublishRequest` and this is where a journey reads back
378    /// that the host was given it. A change with no entry is not a draft, which is
379    /// what every change request opened without one is.
380    ///
381    /// Nothing is refused about the reason itself here. Its shape — that every field
382    /// of it renders as the one line it is printed on — is `onevcs`'s own rule, and
383    /// it is applied where a publication takes one in, before any host is asked.
384    #[serde(
385        skip_serializing_if = "BTreeMap::is_empty",
386        deserialize_with = "drafts_of_any_version"
387    )]
388    pub drafts: BTreeMap<ChangeId, DraftReason>,
389    /// Every `ready_for_review` call this host has taken, in the order it took them
390    /// — the lifts it was asked to perform, never a request for a *reviewer*.
391    ///
392    /// A list rather than a set, and beyond the sketch for a reason a set could not
393    /// serve: lifting a draft is required to be *idempotent*, so what a journey
394    /// asserts is that a second publication asked the host for nothing — and only a
395    /// record of the calls themselves can say that. A change named here is not a
396    /// draft any more, whatever [`drafts`](HostState::drafts) says it was opened as.
397    #[serde(skip_serializing_if = "Vec::is_empty")]
398    pub made_ready: Vec<ChangeId>,
399    /// The change requests opened as a draft **while their required checks run** —
400    /// the lifecycle's draft, which no caller gave a reason for and so is not in
401    /// [`drafts`](HostState::drafts). A change named here is a draft until
402    /// [`made_ready`](HostState::made_ready) names it.
403    #[serde(skip_serializing_if = "BTreeSet::is_empty")]
404    pub awaiting_checks: BTreeSet<ChangeId>,
405    /// The checks the host reports on a change request once it has been lifted out of
406    /// its draft, in place of [`checks`](HostState::checks).
407    ///
408    /// What a repository whose workflow skips drafts looks like from outside: the
409    /// draft's checks are skipped or absent, and the run the lift triggers registers
410    /// after it. A change with no entry reports the same checks either side of a lift.
411    ///
412    /// A publication tells the run a lift triggered from the draft's by the run's own
413    /// identity, as it would on a real host: a check named here that the draft also
414    /// reported is a new run — running or settled — only where its
415    /// [`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
416    /// the draft's start, or reporting none, is the draft's run still standing.
417    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
418    pub checks_after_lift: BTreeMap<ChangeId, Vec<Check>>,
419    /// What this host answers when asked which checks a merge into a base requires.
420    ///
421    /// Unset is a host whose branch protection names exactly the checks it was seeded
422    /// as required, on any change request — a complete answer, and an empty one where
423    /// none is seeded required. Seeded, it is the answer for every base: an empty
424    /// complete one is a repository declaring no required check, and one naming an
425    /// `unconsulted` source is the incomplete answer a narrower credential gets.
426    #[serde(skip_serializing_if = "Option::is_none")]
427    pub required_checks: Option<RequiredChecks>,
428    /// Every `describe_change` call this host has taken, in the order it took them:
429    /// which change request, the title it was handed when it was handed one, and the
430    /// body.
431    ///
432    /// The calls themselves, for the reason [`made_ready`](HostState::made_ready) is:
433    /// what a journey asks is what a closeout *wrote*, call by call, and the current
434    /// title and body — which each call also writes into
435    /// [`titles`](HostState::titles) and [`bodies`](HostState::bodies), so
436    /// `change_description` answers from the same record `open_change` wrote — can
437    /// only say where the description ended up.
438    #[serde(skip_serializing_if = "Vec::is_empty")]
439    pub described: Vec<Described>,
440    /// Which sources this host answers about its checks from, which is what the
441    /// real implementation reports alongside them.
442    ///
443    /// Unset is a credential allowed to read everything: the whole rollup, exactly
444    /// what a host with nothing to hide reports. A journey states a narrower set to
445    /// be the credential the real one meets in CI — a fine-grained token, which
446    /// cannot read check runs at all and sees GitHub Actions and nothing else — and
447    /// states an *empty* one to be a credential that can read no source at all,
448    /// which is a refusal rather than "no checks". Unset and empty are therefore
449    /// different scenarios, which is why this is an `Option` rather than a set whose
450    /// emptiness means "not stated".
451    #[serde(skip_serializing_if = "Option::is_none")]
452    pub check_sources: Option<BTreeSet<CheckSource>>,
453    /// What merging each change request did.
454    ///
455    /// Both a script and a record: an entry seeded here is what `merge` answers,
456    /// whatever the policy asks for — which is how a journey expresses a host that
457    /// queues or refuses — and a merge the policy decided is written back here.
458    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
459    pub merges: BTreeMap<ChangeId, MergeOutcome>,
460    /// When each merged change request reached its base, as this host spells the
461    /// moment — what `merge_time` answers.
462    ///
463    /// Written beside [`merges`](HostState::merges) whenever this host performs a
464    /// merge, at the moment it performs it, and seedable for a merge a journey
465    /// seeded: a host that merged on its own clock, earlier than anybody asked, is
466    /// exactly what a late merge's record must report the time of. A merged change
467    /// with no entry is one whose time this host cannot say.
468    // llmlint: ignore[invalid_states_unrepresentable] this mirrors the answer
469    // `RemoteHost::merge_time` gives, which the contract fixes as the host's own spelling
470    // in an `Option<String>`; a timestamp type here would disagree with the seam it
471    // answers. A value that is not an RFC3339 moment is refused in `check`, where the
472    // document is read, and every one this host writes is `events::timestamp`'s.
473    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
474    pub merge_times: BTreeMap<ChangeId, String>,
475    /// Each change request's review feedback — review-thread comments, review
476    /// summaries and conversation comments — in the order it was posted.
477    ///
478    /// Both a script and a record: what a journey seeds here is what
479    /// `review_comments` reads, [`Host::add_comment`](crate::Host::add_comment),
480    /// [`Host::edit_comment`](crate::Host::edit_comment) and
481    /// [`Host::set_thread`](crate::Host::set_thread) move it as a reviewer would, and
482    /// every reply `reply_to_comment` posts is written back here beside them.
483    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
484    pub review_comments: BTreeMap<ChangeId, Vec<HostComment>>,
485    /// Every reply this host posted, in the order it posted them.
486    ///
487    /// The calls themselves, for the reason [`described`](HostState::described) is:
488    /// what a journey about idempotency asks is how many replies were *posted*, and
489    /// the comments a read returns can only say what is there now.
490    #[serde(default, skip_serializing_if = "Vec::is_empty")]
491    pub replies: Vec<Replied>,
492    /// What this host charges for each read of review feedback, one entry a read, in
493    /// order; a read with none left is charged the one GraphQL point a page that
494    /// `spike-review-loop` measured, and no REST request.
495    #[serde(default, skip_serializing_if = "Vec::is_empty")]
496    pub review_charges: Vec<ReadCost>,
497    /// The change requests closed without merging — by a person on the host, or because
498    /// the branch they target was deleted from under them.
499    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
500    pub closed: BTreeSet<ChangeId>,
501    /// The branches gone from the origin: a merged change request's head a person
502    /// deleted. A closed change request targeting one reads `base_deleted`, and nothing
503    /// is retargeted onto one.
504    // llmlint: ignore[invalid_states_unrepresentable] branch names, as `heads` holds them;
505    // each is held to git's grammar in `check`, where the document is read.
506    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
507    pub deleted_branches: BTreeSet<String>,
508    /// Each check's state on one head commit, in place of the change request's own
509    /// [`checks`](HostState::checks): what a host reports for a head pushed since, and
510    /// how a journey gives each change request of a stack its own verdict.
511    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
512    pub head_checks: BTreeMap<Sha, Vec<Check>>,
513    /// Every host call this host answered, in the order it answered them: the method,
514    /// the change requests it names and what GitHub charges the call the real host
515    /// sends — which is what a consumer sums over a whole review round.
516    #[serde(default, skip_serializing_if = "Vec::is_empty")]
517    pub ledger: Vec<HostCall>,
518    /// Whether this host requires a branch to be up to date with its base before it
519    /// merges one into it — GitHub branch protection's `strict` — which is what
520    /// `requires_up_to_date` answers. Unset is a host that requires it of no branch.
521    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
522    pub up_to_date_required: bool,
523    /// Whether the repository lets a change request be armed to merge itself once its
524    /// required checks pass — GitHub's `allow_auto_merge` — which is what
525    /// `allows_auto_merge` answers. Unset is a repository that allows it, so a
526    /// publication whose watch elapses arms the merge; `false` is one that does not,
527    /// so it is left as the elapsed watch left it. Only `false` is written, so allowed
528    /// has the one spelling.
529    #[serde(default = "allowed", skip_serializing_if = "is_allowed")]
530    pub allow_auto_merge: bool,
531    /// The change requests whose own merge is armed — by a `change-auto` publication,
532    /// or by one whose watch elapsed with no required check red. The host lands one
533    /// the moment its required checks are green, whoever asks next: a publication
534    /// watching it, or one asking for its merge again.
535    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
536    pub armed: BTreeSet<ChangeId>,
537    /// The checks each reading of a change request reports, in turn: the first
538    /// `change_checks` call about it answers the first entry, the second the second,
539    /// and the last entry answers every call after it — so a journey scripts each poll
540    /// of a watch rather than racing a clock. Seeded, it stands in for that change
541    /// request's [`checks`](HostState::checks), and for its
542    /// [`checks_after_lift`](HostState::checks_after_lift) unless
543    /// [`check_readings_after_lift`](HostState::check_readings_after_lift) scripts the
544    /// lift's side; a merge is judged on the entry the latest reading answered.
545    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
546    pub check_readings: BTreeMap<ChangeId, Vec<Vec<Check>>>,
547    /// The same script for the readings after a change request is lifted, counted from
548    /// its lift: the first `change_checks` call after `ready_for_review` answers the
549    /// first entry. A lift happens on a clock — the grace window — so the readings on
550    /// each side of it are scripted apart, and neither has to guess on which poll it
551    /// came.
552    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
553    pub check_readings_after_lift: BTreeMap<ChangeId, Vec<Vec<Check>>>,
554    /// What `head_activity` answers about a change request, in turn: one answer per
555    /// call, and the last answering every call after it. A change request with none
556    /// answers, completely, that nothing is running on the commit it was asked about —
557    /// a host whose checks are the whole of what runs, which is what every journey
558    /// written before this answer existed describes.
559    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
560    pub head_activity: BTreeMap<ChangeId, Vec<ActivityAnswer>>,
561}
562
563/// One answer a host gives about the work still running on a change request's head —
564/// what [`HostState::head_activity`] scripts per call.
565#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
566#[serde(rename_all = "kebab-case", tag = "answer")]
567pub enum ActivityAnswer {
568    /// An answer about the commit it was asked about, naming the work in progress on
569    /// it — none, where `in_progress` is empty.
570    Head {
571        /// The host's name for each piece of work still in progress.
572        // llmlint: ignore[invalid_states_unrepresentable] a scripted copy of
573        // `onevcs::HeadActivity::in_progress`, whose contract-fixed type it must hand
574        // back unchanged; any name a host could report is a valid one.
575        #[serde(default, skip_serializing_if = "Vec::is_empty")]
576        in_progress: Vec<String>,
577        /// Whether every source of such work was read: `false` is a credential that
578        /// could read the workflow runs and not the check suites.
579        // llmlint: ignore[invalid_states_unrepresentable] a scripted copy of the
580        // contract-fixed `onevcs::HeadActivity::complete: bool`, with the same two states.
581        #[serde(default = "allowed", skip_serializing_if = "is_allowed")]
582        complete: bool,
583    },
584    /// An answer about `head`, a commit other than the one asked about — a host that
585    /// has not processed the push yet.
586    Other {
587        /// The commit the answer is about.
588        head: Sha,
589        /// The host's name for each piece of work still in progress on it.
590        // llmlint: ignore[invalid_states_unrepresentable] as on `Head::in_progress`: the
591        // contract-fixed `HeadActivity::in_progress` this answer is handed back as.
592        #[serde(default, skip_serializing_if = "Vec::is_empty")]
593        in_progress: Vec<String>,
594    },
595    /// A refusal: a credential that may read neither source.
596    Refused,
597}
598
599/// Every method a ledger entry may name: each `RemoteHost` method this host answers.
600/// `Host::called` refuses to record any other, and
601/// `the_ledger_records_a_call_to_every_method_the_host_interface_declares` holds this
602/// list equal to the trait's own declaration, read out of its source.
603pub(crate) const LEDGER_METHODS: &[&str] = &[
604    "allows_auto_merge",
605    "authenticated_user",
606    "change_checks",
607    "change_description",
608    "change_standings",
609    "check_log",
610    "describe_change",
611    "find_changes",
612    "head_activity",
613    "is_draft",
614    "merge",
615    "merge_time",
616    "merged_at",
617    "mergeability",
618    "open_change",
619    "ready_for_review",
620    "reopen_change",
621    "reply_to_comment",
622    "required_checks_on",
623    "requires_up_to_date",
624    "retarget_change",
625    "review_comments",
626    "review_standings",
627    "visibility",
628];
629
630/// One host call a host answered, as its ledger records it.
631// llmlint: ignore[invalid_states_unrepresentable] `method` is the name of the
632// `RemoteHost` method that was called; `HostCall::checked` holds it to `LEDGER_METHODS`
633// where the document is read and where a call is recorded, and nothing reads a decision
634// out of the name.
635#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
636pub struct HostCall {
637    /// The `RemoteHost` method called, by its name.
638    pub method: String,
639    /// The change requests the call names, in the order it names them.
640    #[serde(default, skip_serializing_if = "Vec::is_empty")]
641    pub changes: Vec<ChangeId>,
642    /// What GitHub charges the call the real host sends.
643    pub charge: ReadCost,
644}
645
646impl HostCall {
647    /// Refuse an entry no call to this host could have written: a method it does not
648    /// answer, or a change request named by no identifier at all. A change request it
649    /// never opened is not refused — the real host charges a call it then refuses, and
650    /// so the ledger records one.
651    pub(crate) fn checked(&self) -> Result<()> {
652        if !LEDGER_METHODS.contains(&self.method.as_str()) {
653            return Err(Error::Invalid {
654                reason: format!(
655                    "the call ledger records a call to {:?}, which is no method this host \
656                     answers",
657                    self.method
658                ),
659            });
660        }
661        if self.changes.iter().any(|id| id.0.trim().is_empty()) {
662            return Err(Error::Invalid {
663                reason: format!(
664                    "the call ledger records a call to {:?} naming a change request with no \
665                     identifier",
666                    self.method
667                ),
668            });
669        }
670        Ok(())
671    }
672}
673
674/// One comment a host holds on a change request.
675///
676/// What `review_comments` answers a [`ReviewComment`](onevcs::ReviewComment) from:
677/// everything but `ours` and `reply_marker`, which are read out of the body exactly as
678/// the real host's are, and with the one thing a host keeps that a read does not
679/// show — when it last changed.
680// llmlint: ignore[invalid_states_unrepresentable] every text field is what the real host
681// reports as a string and `ReviewComment` carries as one; a seeded comment is the
682// journey's own scenario, and `check` refuses the two things no host could hold — an id
683// held twice, and a reply to a comment the change request does not carry.
684#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
685pub struct HostComment {
686    /// The host's id for it.
687    pub id: CommentId,
688    /// What kind it is, and — for a thread comment — its thread's flags.
689    pub kind: CommentKind,
690    /// Who wrote it.
691    pub author: String,
692    /// What it says.
693    pub body: String,
694    /// Where a person reads it.
695    pub url: String,
696    /// When it was written.
697    pub created_at: String,
698    /// When it last changed.
699    pub updated_at: String,
700    /// The comment it replies to in its thread.
701    #[serde(default, skip_serializing_if = "Option::is_none")]
702    pub in_reply_to: Option<CommentId>,
703    /// When, in this host's own count of changes to the change request's feedback, it
704    /// last changed — what a read marker is compared against. A seeded comment at `0`
705    /// is one every read from a marker has already seen.
706    #[serde(default)]
707    pub revision: u64,
708}
709
710/// One reply a host posted.
711#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
712pub struct Replied {
713    /// The change request it was posted on.
714    pub change: ChangeId,
715    /// The comment it was posted against.
716    pub comment: CommentId,
717    /// The idempotency key the call carried.
718    pub key: String,
719    /// The reply's own id.
720    pub reply: CommentId,
721    /// Whether it was posted in the comment's thread.
722    pub threaded: bool,
723}
724
725/// One description a host was handed for a change request after it was opened.
726///
727/// What `RemoteHost::describe_change` was given, verbatim: the title only where the
728/// call carried one, because a call that replaced the body alone left the title as
729/// it was, and a record that filled it in would say the caller wrote a title nobody
730/// wrote.
731// llmlint: ignore[invalid_states_unrepresentable] the title and body are the `&str`s the
732// seam hands over — a host places no shape on prose, and `onevcs`'s own `Subject` rule
733// was applied where the description was composed, before any host was asked.
734#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
735pub struct Described {
736    /// The change request the description was written to.
737    pub id: ChangeId,
738    /// The title the call replaced the change request's with, when it replaced one.
739    #[serde(default, skip_serializing_if = "Option::is_none")]
740    pub title: Option<String>,
741    /// The body the call replaced the change request's with.
742    pub body: String,
743}
744
745/// The `drafts` map of a document at any readable version.
746///
747/// A document written before version 9 spells a draft reason as the four fields of
748/// the one kind there was and no `kind` beside them; this build's reason is one of
749/// two kinds and says which. So a reason arriving without a `kind` is read as
750/// `awaiting-release` — exactly what it was — rather than refused, which is what
751/// keeps a consumer's checked-in scenario readable across the bump. A reason that
752/// *names* a kind is read as it names it, so nothing written by this build is
753/// reinterpreted.
754fn drafts_of_any_version<'de, D>(
755    deserializer: D,
756) -> std::result::Result<BTreeMap<ChangeId, DraftReason>, D::Error>
757where
758    D: serde::Deserializer<'de>,
759{
760    let raw: BTreeMap<ChangeId, serde_json::Map<String, serde_json::Value>> =
761        Deserialize::deserialize(deserializer)?;
762    raw.into_iter()
763        .map(|(id, mut fields)| {
764            fields
765                .entry("kind")
766                .or_insert_with(|| serde_json::Value::from("awaiting-release"));
767            serde_json::from_value::<DraftReason>(serde_json::Value::Object(fields))
768                .map(|reason| (id, reason))
769                .map_err(serde::de::Error::custom)
770        })
771        .collect()
772}
773
774/// Who a host with nothing seeded says is calling.
775///
776/// A host that answers nobody is refused by the real implementation, so a default
777/// state that answered nobody would be a provider that cannot run a publication
778/// until it is configured.
779pub const DEFAULT_AUTHENTICATED_USER: &str = "onevcs-testing";
780
781impl Default for HostState {
782    fn default() -> Self {
783        Self {
784            version: STATE_VERSION,
785            authenticated_user: DEFAULT_AUTHENTICATED_USER.to_owned(),
786            changes: Vec::new(),
787            heads: BTreeMap::new(),
788            titles: BTreeMap::new(),
789            bodies: BTreeMap::new(),
790            drafts: BTreeMap::new(),
791            made_ready: Vec::new(),
792            awaiting_checks: BTreeSet::new(),
793            checks_after_lift: BTreeMap::new(),
794            required_checks: None,
795            described: Vec::new(),
796            checks: BTreeMap::new(),
797            check_logs: BTreeMap::new(),
798            check_sources: None,
799            merges: BTreeMap::new(),
800            merge_times: BTreeMap::new(),
801            review_comments: BTreeMap::new(),
802            replies: Vec::new(),
803            review_charges: Vec::new(),
804            closed: BTreeSet::new(),
805            deleted_branches: BTreeSet::new(),
806            head_checks: BTreeMap::new(),
807            ledger: Vec::new(),
808            up_to_date_required: false,
809            allow_auto_merge: true,
810            armed: BTreeSet::new(),
811            check_readings: BTreeMap::new(),
812            check_readings_after_lift: BTreeMap::new(),
813            head_activity: BTreeMap::new(),
814        }
815    }
816}
817
818/// What a host document that says nothing about auto-merge allows: GitHub's default.
819fn allowed() -> bool {
820    true
821}
822
823/// Whether `allow_auto_merge` holds the default, which a written document omits.
824#[expect(
825    clippy::trivially_copy_pass_by_ref,
826    reason = "serde's skip_serializing_if passes a reference"
827)]
828fn is_allowed(allow: &bool) -> bool {
829    *allow
830}
831
832/// The identity a session request names, or the reason none of them is it.
833///
834/// Three ways to name one, mirroring what the registry accepts: the identity key
835/// itself, the `owner/name` tail of it, or the bare repository name.
836pub(crate) fn identity_of<'a>(state: &'a VcsState, origin_or_path: &str) -> Option<&'a Identity> {
837    let wanted = origin_or_path.trim_end_matches('/');
838    state
839        .identities
840        .iter()
841        .find(|identity| identity.origin == wanted)
842        .or_else(|| {
843            state.identities.iter().find(|identity| {
844                identity
845                    .origin
846                    .rsplit('/')
847                    .next()
848                    .is_some_and(|name| name == wanted)
849                    || identity.origin.ends_with(&format!("/{wanted}"))
850            })
851        })
852}
853
854/// The known identities, as a refusal names them.
855pub(crate) fn known(state: &VcsState) -> String {
856    if state.identities.is_empty() {
857        return "this provider was seeded with no identities".to_owned();
858    }
859    let names: Vec<&str> = state
860        .identities
861        .iter()
862        .map(|identity| identity.origin.as_str())
863        .collect();
864    format!("it knows {}", names.join(", "))
865}
866
867/// The identity a session belongs to, or the reason this provider cannot say.
868///
869/// `open_session` records it and nothing else writes it, so a session that arrived
870/// in a hand-written scenario without one is refused here rather than published
871/// against a repository nobody named.
872pub(crate) fn identity_for(state: &VcsState, token: &SessionToken) -> Result<String> {
873    state
874        .session_identities
875        .get(token)
876        .cloned()
877        .ok_or_else(|| Error::Invalid {
878            reason: format!(
879                "this provider has no record of session {:?}, so it cannot say which identity \
880                 its work belongs to",
881                token.0
882            ),
883        })
884}
885
886/// The session a token names.
887pub(crate) fn session_of<'a>(state: &'a VcsState, token: &SessionToken) -> Option<&'a Session> {
888    state
889        .sessions
890        .iter()
891        .find(|session| session.token == *token)
892}
893
894/// The branch a request asks for, or the one that is derived from the token.
895///
896/// `branch` and `branch_name` are two answers to one question — *continue this* and
897/// *cut one at this* — so a request naming both is refused here as the real
898/// implementation refuses it: that refusal is about the shape of the request rather
899/// than about anything a repository does, and a consumer proving it must meet the
900/// same answer on either side.
901///
902/// **What a provider deliberately does not do to `branch_name` is the rest**, and it
903/// is not approximated: the host's branch prefix is read out of an `onevcs` state
904/// root no provider has, and the first-free suffix is searched against an identity's
905/// checkouts and its origin, which a provider has neither of. So the name is taken as
906/// it was proposed and refused — naming it — where git would refuse it, rather than
907/// being sanitized by a second copy of a grammar that would then have to be held to
908/// the first. A consumer proving what the prefix, the sanitizer and the collision
909/// suffix do drives the real `onevcs`, which is where all three live.
910pub(crate) fn requested_branch(req: &SessionRequest, token: &SessionToken) -> Result<String> {
911    if let (Some(pinned), Some(proposed)) = (&req.branch, &req.branch_name) {
912        return Err(Error::Invalid {
913            reason: format!(
914                "this request names both a branch to continue ({pinned:?}) and a name to cut \
915                 ({proposed:?}), which are two answers to one question"
916            ),
917        });
918    }
919    let name = req
920        .branch
921        .clone()
922        .or_else(|| req.branch_name.clone())
923        .unwrap_or_else(|| format!("onevcs/{}", token.0));
924    named_branch(&name, "the branch")?;
925    Ok(name)
926}
927
928/// A branch name, refused here if git would refuse it.
929///
930/// The real implementation asks `git check-ref-format`, which is the parser that
931/// decides; a provider with no git carries `git-check-ref-format(1)`'s rules
932/// instead. That is a restatement, so it is gated rather than trusted:
933/// `refs.rs` in the suite runs both this and git itself over a table of names
934/// and holds them to each other, because a copy of somebody else's grammar with
935/// no gate is a copy that drifts.
936///
937/// One deliberate difference, and the gate knows about it: a leading `-` is
938/// refused here even though git accepts it as a ref, because such a name reaches
939/// a command line as an option rather than as the branch it spells.
940pub(crate) fn named_branch(value: &str, what: &str) -> Result<()> {
941    // Rule 1 is per slash-separated component; the rest are about the whole name.
942    let components_usable = !value.is_empty()
943        && value.split('/').all(|component| {
944            !component.is_empty() && !component.starts_with('.') && !component.ends_with(".lock")
945        });
946    let usable = components_usable
947        && !value.starts_with('-')
948        && !value.contains("..")
949        && !value.contains("@{")
950        && !value.ends_with('.')
951        && !value.ends_with('/')
952        && !value.chars().any(|c| {
953            c.is_whitespace() || c.is_ascii_control() || c == '\u{7f}' || "~^:?*[\\".contains(c)
954        });
955    if !usable {
956        return Err(Error::Invalid {
957            reason: format!("{what} {value:?} is a name git would not accept"),
958        });
959    }
960    Ok(())
961}
962
963/// A label, refused here where the real implementation refuses one: a key is one or
964/// more of `A-Z`, `a-z`, `0-9`, `_` and `-`, and a value is one line. The same rule
965/// spelled twice on purpose, for the reason [`named_branch`] gives — a provider with
966/// no `onevcs` state root carries the grammar, and the journeys over both providers
967/// hold the two to each other.
968pub(crate) fn label_pair(key: &str, value: &str) -> Result<()> {
969    let key_usable = !key.is_empty()
970        && key
971            .chars()
972            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
973    if !key_usable {
974        return Err(Error::Invalid {
975            reason: format!(
976                "{key:?} is not a label key; a key is one or more of A-Z, a-z, 0-9, `_` and `-`"
977            ),
978        });
979    }
980    if value.contains('\n') {
981        return Err(Error::Invalid {
982            reason: format!(
983                "the value of label {key:?} holds a newline; a label's value is one line"
984            ),
985        });
986    }
987    Ok(())
988}
989
990/// A seeded repository side is refused if it holds a session nothing could act on.
991impl Checked for VcsState {
992    fn check(&self) -> Result<()> {
993        readable_version(self.version)?;
994        for session in &self.sessions {
995            // The token names a file under the state root, and a branch goes on to
996            // spell a ref; both arrive from whoever wrote the document.
997            if !events::is_safe_name(&session.token.0) {
998                return Err(Error::Invalid {
999                    reason: format!("{:?} is not a session token", session.token.0),
1000                });
1001            }
1002            named_branch(&session.branch, "the branch")?;
1003            named_branch(&session.base, "the base")?;
1004        }
1005        for row in &self.preserved {
1006            known_identity(self, &row.identity, "preserved work")?;
1007            named_branch(&row.branch.branch, "the preserved branch")?;
1008            named_branch(&row.branch.base, "the preserved branch's base")?;
1009            // A hold that names a session is checked like the three below: a row
1010            // held by a session nobody opened is the same fiction, and the costly one
1011            // — it is the session an operator is told to wait for or close. A running
1012            // publication holds a branch under no session and names none.
1013            if let Some(token) = row.held_by.as_ref().and_then(|held| held.token.as_ref()) {
1014                opened(self, token, "holding preserved work")?;
1015            }
1016        }
1017        // Both of these name a session, so both are checked twice over: the token
1018        // has to be a plain name, because it goes on to spell the file its stream is
1019        // written in, and it has to name a session this state actually holds. A
1020        // document that closes or publishes a session nobody opened describes a run
1021        // that could not have happened, and answering `recoverable` or `session`
1022        // from it would be answering from a fiction rather than refusing one.
1023        for token in &self.closed_sessions {
1024            opened(self, token, "closed")?;
1025        }
1026        for (token, labels) in &self.session_labels {
1027            opened(self, token, "labelled")?;
1028            for (key, value) in labels {
1029                label_pair(key, value)?;
1030            }
1031        }
1032        for (token, origin) in &self.session_identities {
1033            opened(self, token, "given an identity")?;
1034            // The value as well as the key: this is what `identity_for` answers with,
1035            // and it goes on to spell the slug a change request is opened against and
1036            // the label every one of that session's events carries. An identity this
1037            // provider does not know is one it could not have opened the session for.
1038            known_identity(self, origin, &format!("session {:?}", token.0))?;
1039        }
1040        for publication in &self.publications {
1041            let session = opened(self, &publication.session, "published")?;
1042            named_branch(&publication.branch, "the published branch")?;
1043            // A publication of some other branch than the one the session is on is
1044            // the same kind of fiction, and the harder one to spot afterwards: the
1045            // branch is what a journey asserts the publication was of.
1046            if publication.branch != session.branch {
1047                return Err(Error::Invalid {
1048                    reason: format!(
1049                        "the publication of session {:?} names branch {:?}, but that session is \
1050                         on {:?}",
1051                        publication.session.0, publication.branch, session.branch
1052                    ),
1053                });
1054            }
1055        }
1056        Ok(())
1057    }
1058
1059    /// Every field an older readable document could hold means here what it meant
1060    /// there, and the two the repository side gained in version 4 are absent from one
1061    /// written before them — which is the answer, since that build held no hold and
1062    /// counted no lines.
1063    ///
1064    /// Version 5's field is the exception, and it is carried rather than left at its
1065    /// default: a document written before it *listed preserved work nobody had
1066    /// published*, which is the `no` this build spells out. Left at the default it
1067    /// would read as "nothing here can say", and a consumer's checked-in scenario
1068    /// would start reporting work it had always called unpublished as work that may
1069    /// have landed.
1070    fn carry_forward(&mut self) {
1071        if self.version < 5 {
1072            for row in &mut self.preserved {
1073                row.landed = Landed::No;
1074            }
1075        }
1076        self.version = STATE_VERSION;
1077    }
1078}
1079
1080/// Refuse a record kept about a change request this state does not hold.
1081fn opened_change(state: &HostState, id: &ChangeId, what: &str) -> Result<()> {
1082    if state.changes.iter().any(|change| change.id == *id) {
1083        return Ok(());
1084    }
1085    Err(Error::Invalid {
1086        reason: format!(
1087            "{what} is recorded for change request {:?}, but no change request by that \
1088             identifier was opened",
1089            id.0
1090        ),
1091    })
1092}
1093
1094/// Refuse an identity key this provider was not seeded with.
1095fn known_identity(state: &VcsState, origin: &str, what: &str) -> Result<()> {
1096    if state
1097        .identities
1098        .iter()
1099        .any(|identity| identity.origin == origin)
1100    {
1101        return Ok(());
1102    }
1103    Err(Error::Invalid {
1104        reason: format!(
1105            "{what} belongs to identity {origin:?}, which this provider does not know; {}",
1106            known(state)
1107        ),
1108    })
1109}
1110
1111/// A change request's title, refused when it names nothing.
1112///
1113/// The one thing a real host refuses about a title, and the only one this provider
1114/// may: how long a title may be is the host's own rule rather than `onevcs`'s
1115/// commit-subject rule, and a provider applying the stricter of the two would
1116/// refuse what the host it stands in for accepts.
1117pub(crate) fn titled(title: &str) -> Result<()> {
1118    if title.trim().is_empty() {
1119        return Err(Error::Invalid {
1120            reason: "a change request's title is blank, so it names no change".to_owned(),
1121        });
1122    }
1123    Ok(())
1124}
1125
1126/// The session a token names, refused when this state does not hold one.
1127fn opened<'a>(state: &'a VcsState, token: &SessionToken, what: &str) -> Result<&'a Session> {
1128    if !events::is_safe_name(&token.0) {
1129        return Err(Error::Invalid {
1130            reason: format!("{:?} is not a session token", token.0),
1131        });
1132    }
1133    session_of(state, token).ok_or_else(|| Error::Invalid {
1134        reason: format!(
1135            "session {:?} is {what} here, but no session by that token was opened",
1136            token.0
1137        ),
1138    })
1139}
1140
1141/// A seeded host side is refused if it holds a change nothing could address.
1142impl Checked for HostState {
1143    fn check(&self) -> Result<()> {
1144        readable_version(self.version)?;
1145        for change in &self.changes {
1146            named_branch(&change.base, "the base of a seeded change request")?;
1147            if change.id.0.is_empty() {
1148                return Err(Error::Invalid {
1149                    reason: "a seeded change request carries no identifier".to_owned(),
1150                });
1151            }
1152            // The commit a change request's checks are reported against is the whole
1153            // evidence that a change reached anything, and the real implementation
1154            // refuses a host answer that names none rather than passing a blank one
1155            // through. A seeded one is refused for the same reason.
1156            if change.head_sha.0.trim().is_empty() {
1157                return Err(Error::Invalid {
1158                    reason: format!(
1159                        "the seeded change request {:?} names no commit its checks are \
1160                         reported against",
1161                        change.id.0
1162                    ),
1163                });
1164            }
1165        }
1166        // Both of these are recorded *about* a change request, by `open_change` and
1167        // by nothing else, and both are read back by the id they are keyed under. An
1168        // entry for a change nobody opened is one no call could ever reach, so it is
1169        // refused rather than carried — unlike the checks, logs, and merge outcomes
1170        // below it, which a journey deliberately seeds for a change it has not
1171        // opened yet.
1172        for (id, head) in &self.heads {
1173            opened_change(self, id, "a head")?;
1174            named_branch(head, "the head of a seeded change request")?;
1175        }
1176        for (id, title) in &self.titles {
1177            opened_change(self, id, "a title")?;
1178            // The real host refuses a title that names nothing, so a seeded one is
1179            // refused for the same reason.
1180            titled(title)?;
1181        }
1182        for id in self.bodies.keys() {
1183            // Nothing is refused about the body itself: a host places no shape on
1184            // prose, and a change request opened with an empty one is a scenario.
1185            opened_change(self, id, "a body")?;
1186        }
1187        for (id, reason) in &self.drafts {
1188            opened_change(self, id, "a draft reason")?;
1189            // The publication rule the crate next door states, applied rather than
1190            // restated: a seeded reason no publication could have carried is refused
1191            // where the document is read, not answered from later.
1192            reason.checked()?;
1193        }
1194        for id in &self.made_ready {
1195            opened_change(self, id, "a lifted draft")?;
1196        }
1197        for id in &self.awaiting_checks {
1198            opened_change(self, id, "a draft awaiting its checks")?;
1199        }
1200        for described in &self.described {
1201            opened_change(self, &described.id, "a description")?;
1202            // The real host refuses a title that names nothing, so a seeded one is
1203            // refused for the same reason — and a body is prose, refused for nothing.
1204            if let Some(title) = &described.title {
1205                titled(title)?;
1206            }
1207        }
1208        // Review feedback is read by the change request it is keyed under, and a reply
1209        // names the comment it answers, so a comment on a change nobody opened, an id
1210        // held twice, or a reply to a comment that is not there is one no read could
1211        // answer as the real host would.
1212        for (id, comments) in &self.review_comments {
1213            opened_change(self, id, "review feedback")?;
1214            let mut held = BTreeSet::new();
1215            for comment in comments {
1216                if comment.id.0.trim().is_empty() || !held.insert(&comment.id) {
1217                    return Err(Error::Invalid {
1218                        reason: format!(
1219                            "the review feedback seeded for change request {:?} holds the \
1220                             comment id {:?} more than once, or an empty one",
1221                            id.0, comment.id.0
1222                        ),
1223                    });
1224                }
1225            }
1226            for comment in comments {
1227                // A read hands these on as the RFC 3339 moments the contract promises.
1228                for (field, at) in [
1229                    ("created_at", &comment.created_at),
1230                    ("updated_at", &comment.updated_at),
1231                ] {
1232                    if events::moment(at).is_none() {
1233                        return Err(Error::Invalid {
1234                            reason: format!(
1235                                "comment {:?} on change request {:?} has {field} {at:?}, which \
1236                                 is not an RFC 3339 moment",
1237                                comment.id.0, id.0
1238                            ),
1239                        });
1240                    }
1241                }
1242                if let Some(answered) = &comment.in_reply_to {
1243                    if !held.contains(answered) {
1244                        return Err(Error::Invalid {
1245                            reason: format!(
1246                                "comment {:?} on change request {:?} replies to {:?}, which \
1247                                 that change request does not carry",
1248                                comment.id.0, id.0, answered.0
1249                            ),
1250                        });
1251                    }
1252                }
1253            }
1254        }
1255        for id in &self.closed {
1256            opened_change(self, id, "a closing")?;
1257        }
1258        for id in &self.armed {
1259            opened_change(self, id, "an armed merge")?;
1260        }
1261        // Scripted, like the checks, for a change a journey has not opened yet. What is
1262        // refused is a script no call could answer from: one with no entry, which would
1263        // read as unseeded while saying it was seeded, and an answer about a commit
1264        // that names none.
1265        for (id, readings) in self
1266            .check_readings
1267            .iter()
1268            .chain(&self.check_readings_after_lift)
1269        {
1270            if readings.is_empty() {
1271                return Err(Error::Invalid {
1272                    reason: format!(
1273                        "the checks scripted for change request {:?} hold no reading",
1274                        id.0
1275                    ),
1276                });
1277            }
1278        }
1279        for (id, answers) in &self.head_activity {
1280            if answers.is_empty() {
1281                return Err(Error::Invalid {
1282                    reason: format!(
1283                        "the head activity scripted for change request {:?} holds no answer",
1284                        id.0
1285                    ),
1286                });
1287            }
1288            for answer in answers {
1289                if let ActivityAnswer::Other { head, .. } = answer {
1290                    if head.0.trim().is_empty() {
1291                        return Err(Error::Invalid {
1292                            reason: format!(
1293                                "the head activity scripted for change request {:?} answers \
1294                                 about a commit it does not name",
1295                                id.0
1296                            ),
1297                        });
1298                    }
1299                }
1300            }
1301        }
1302        for branch in &self.deleted_branches {
1303            named_branch(branch, "a deleted branch")?;
1304        }
1305        for call in &self.ledger {
1306            call.checked()?;
1307        }
1308        // A merge time is what `merge_time` answers and what a landing is recorded
1309        // with, so a seeded one that is not a moment is refused here, where the
1310        // document is read, rather than recorded as one.
1311        for (id, at) in &self.merge_times {
1312            if events::moment(at).is_none() {
1313                return Err(Error::Invalid {
1314                    reason: format!(
1315                        "the merge time seeded for change request {:?} is {at:?}, which is \
1316                         not an RFC3339 moment",
1317                        id.0
1318                    ),
1319                });
1320            }
1321        }
1322        Ok(())
1323    }
1324
1325    /// A version 2 document held no bodies, and a version 5 document's checks named
1326    /// no commit; each reads as what it was — change requests opened with none, and
1327    /// checks whose head that build never recorded. There is nothing to fill in — an
1328    /// absent field is already that answer, and a check's commit is the one thing
1329    /// that must never be inferred — so this is the version and nothing else. The one
1330    /// carry a version 8 document needs, the `kind` its draft reasons lack, is done
1331    /// where those are read (`drafts_of_any_version`), because it is a fact about
1332    /// one value's shape rather than about the document.
1333    fn carry_forward(&mut self) {
1334        self.version = STATE_VERSION;
1335    }
1336}
1337
1338/// Refuse a document written at a version this build does not read.
1339///
1340/// Named rather than guessed at: a state whose shape is a later build's reads one
1341/// way here and another way where that version is understood, and for a seeded
1342/// scenario those two readings are two different tests. The refusal names the
1343/// range as well as the version, because "too old" and "too new" are two different
1344/// things to do about it — one is a document to re-seed, the other a build to
1345/// update.
1346fn readable_version(declared: u32) -> Result<()> {
1347    if !(OLDEST_READABLE_VERSION..=STATE_VERSION).contains(&declared) {
1348        return Err(Error::Invalid {
1349            reason: format!(
1350                "the document declares version {declared}; this build reads versions \
1351                 {OLDEST_READABLE_VERSION} to {STATE_VERSION}"
1352            ),
1353        });
1354    }
1355    Ok(())
1356}