Skip to main content

ossctl_core/protocol/
journal.rs

1//! Public wire DTOs for the event-sourced release journal (ADR-0003).
2//!
3//! Two durable representations ride on these types:
4//!
5//! - **`journal.jsonl`** — the append-only event log: one [`JournalEvent`] per
6//!   line, each self-contained (it carries its own [`JOURNAL_SCHEMA_VERSION`], a
7//!   monotonic [`JournalEvent::seq`], a [`JournalEvent::ts`], an
8//!   [`JournalEvent::idempotency_key`], and its [`EventKind`] payload). The log
9//!   is the **single source of truth**.
10//! - **`manifest.json`** — the materialized [`RunState`] projection reduced from
11//!   the log. It is **disposable and reconstructable** from the events (ADR-0003
12//!   §2): if the manifest cannot be rebuilt from the journal there would be two
13//!   sources of truth, which is forbidden. It exists only as an O(1) cache for
14//!   `release show`.
15//!
16//! ## Versioning + forward tolerance
17//!
18//! The journal is durable across `ossctl` upgrades — a run started under one
19//! version must be resumable under the next — so each event carries its **own**
20//! [`JOURNAL_SCHEMA_VERSION`], independent of the envelope [`crate::SCHEMA_VERSION`]
21//! that versions the `--json` wire surface. Additive fields are tolerated (serde
22//! ignores unknown fields on read); a *newer required* event schema is refused
23//! with an actionable error rather than silently mutating state (the refusal
24//! lives in [`crate::release::journal`], which reads these back).
25//!
26//! These DTOs are **owned by the journal**: siblings (the plan model, the
27//! adapters) may hold richer in-memory receipt types, but what the journal
28//! *persists* is exactly the shape here.
29
30use std::collections::{BTreeMap, BTreeSet};
31
32use serde::{Deserialize, Serialize};
33
34/// Schema version stamped on every [`JournalEvent`] and [`RunState`].
35///
36/// Monotonic integer, **independent** of [`crate::SCHEMA_VERSION`]: that one
37/// versions the transient `--json`/`--output=jsonl` wire surface; this one
38/// versions the *durable* on-disk journal, which must survive `ossctl` upgrades.
39/// Bump on a breaking event/state change (removing/renaming fields, changing a
40/// variant's semantics); additive optional fields do not bump it.
41///
42/// **v2** (2026-08-05): added the [`EventKind::TargetDelegated`] event class and
43/// the post-tag [`Phase::Dist`] barrier (a new event *kind* / phase value an
44/// older reader cannot interpret, so the version is bumped per the migration
45/// rule — a v1 `ossctl` refuses a v2 line rather than misreading it). A v2 run
46/// carries no v1-incompatible receipt shape; the reduce path stays
47/// backward-tolerant of v1 logs (which simply lack these events).
48///
49/// **v3** (2026-08-05): added the [`EventKind::GithubReleaseDelegated`] event class
50/// (the coordinator delegating GitHub Release creation to a target's CI, e.g.
51/// `cargo-dist`). This is a **new event kind a v2 reader cannot interpret**, so the
52/// migration rule requires its own bump — folding it into v2 would defeat the
53/// version gate ([`read_events`](crate::release::journal::read_events)), letting a
54/// v2 binary silently choke on a `github_release_delegated` line instead of refusing
55/// it with an upgrade error. (This matters even though the engine has never cut a
56/// release itself: a build from `main` between the v2 and v3 commits can emit a v2
57/// journal, and that journal must stay readable while a v3 line is refused by the
58/// older binary.) The reduce path stays backward-tolerant of v1/v2 logs (which lack
59/// this event); `TagState::github_release_delegated` is `#[serde(default)]`.
60pub const JOURNAL_SCHEMA_VERSION: u32 = 3;
61
62/// The five coordinator phases, in barrier order (ADR-0002): the derived
63/// `PartialOrd`/`Ord` follows declaration order, so `DryRun < Build < Publish <
64/// Tag < Dist` — the order the projection sorts phase records in.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
66#[serde(rename_all = "snake_case")]
67pub enum Phase {
68    /// Dry-run-all: every adapter proves it *can* publish, nothing lands.
69    DryRun,
70    /// Build-all: every adapter produces its release artifact.
71    Build,
72    /// Publish-all: artifacts are pushed to their registries (point of no return
73    /// per target — receipts are written per target before the next is tried).
74    Publish,
75    /// Tag-once: the coordinator (never an adapter) creates and pushes the tag
76    /// and the GitHub Release.
77    Tag,
78    /// Dist (post-tag finalize): distribution targets whose artifact only exists
79    /// *after* the tag is pushed are finalized here — the Homebrew formula, whose
80    /// `url` is the just-created tag archive, is fetched, hashed, and its `.rb`
81    /// written with the real `sha256`. Runs after [`Self::Tag`]; its `Ok`
82    /// completion is what flips the run to [`RunStatus::Completed`]. A cut with no
83    /// post-tag target still runs this barrier as a clean no-op so completion is
84    /// uniform (ADR-0002 §2, extended by `release-engine-cut-cargo-dist-flow`).
85    Dist,
86}
87
88impl Phase {
89    /// The wire string for this phase (matches the `Serialize` derive), so text
90    /// diagnostics and JSON never drift.
91    #[must_use]
92    pub fn as_str(self) -> &'static str {
93        match self {
94            Self::DryRun => "dry_run",
95            Self::Build => "build",
96            Self::Publish => "publish",
97            Self::Tag => "tag",
98            Self::Dist => "dist",
99        }
100    }
101}
102
103/// How a phase barrier finished.
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(rename_all = "snake_case")]
106pub enum PhaseOutcome {
107    /// Every target cleared the barrier.
108    Ok,
109    /// The barrier failed (at least one target did not clear it); the run does
110    /// not advance past a failed barrier.
111    Failed,
112}
113
114/// Terminal-or-not status of a run, derived from the event stream.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
116#[serde(rename_all = "snake_case")]
117pub enum RunStatus {
118    /// The run is live (created, not yet completed or abandoned).
119    InProgress,
120    /// The final [`Phase::Dist`] barrier completed [`PhaseOutcome::Ok`].
121    Completed,
122    /// A `run_abandoned` event was recorded (see [`RunState::abandon_reason`]).
123    Abandoned,
124}
125
126impl RunStatus {
127    /// The wire string for this status (matches the `Serialize` derive), so text
128    /// diagnostics and JSON never drift.
129    #[must_use]
130    pub fn as_str(self) -> &'static str {
131        match self {
132            Self::InProgress => "in_progress",
133            Self::Completed => "completed",
134            Self::Abandoned => "abandoned",
135        }
136    }
137}
138
139/// The per-target publish receipt the journal persists — the fact "this exact
140/// artifact landed" that resume/reconcile checks against the registry (the
141/// remote is ground truth, ADR-0003 §4).
142///
143/// Written **per target before the next target is attempted**, never batched, so
144/// an interrupted publish-all leaves an accurate record of exactly what landed.
145/// Every descriptive field is optional so an adapter that cannot supply (say) a
146/// content digest still records a usable receipt.
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148pub struct PublishReceipt {
149    /// The ecosystem the artifact was published to (`cargo`, `npm`, …).
150    pub ecosystem: String,
151    /// The published package/crate name, when the ecosystem has one.
152    pub package: Option<String>,
153    /// The version string that was published.
154    pub version: String,
155    /// The registry URL of the published artifact, when the adapter reports one.
156    pub registry_url: Option<String>,
157    /// A content digest of the published artifact, when available — the strongest
158    /// signal for `verify()`'s `Matches`/`Conflicts` decision on resume.
159    pub digest: Option<String>,
160}
161
162/// The progress of one release tag through its landing steps. Every field is a
163/// monotonic (`false → true`) fact set by its own journal event, so re-applying a
164/// tag event is a no-op. `created_local` and `pushed_remote` are orthogonal landing
165/// facts; `github_release` vs `github_release_delegated` are the two
166/// **mutually-exclusive** dispositions of the Release step (created-by-engine vs
167/// delegated-to-CI) — the coordinator writes exactly one, and refuses to record a
168/// second contradictory one (`crate::release::coordinator`'s tag phase), so the
169/// illegal both-true state is unreachable for a valid run. They stay flat flags
170/// (with a `clippy::struct_excessive_bools` allow) rather than a
171/// `ReleaseDisposition` enum for consistency with the surrounding flat-flag style
172/// and a `#[serde(default)]`-friendly additive wire shape; folding them into an
173/// enum is a tracked cleanup, not a correctness fix given the write-time guard.
174#[allow(clippy::struct_excessive_bools)]
175#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
176pub struct TagState {
177    /// The annotated tag exists in the local repository.
178    pub created_local: bool,
179    /// The tag has been pushed to the remote.
180    pub pushed_remote: bool,
181    /// The GitHub Release for the tag has been created.
182    pub github_release: bool,
183    /// The GitHub Release URL, once created.
184    pub github_release_url: Option<String>,
185    /// The GitHub Release was **delegated to CI** rather than created by the
186    /// coordinator: the plan carried a CI-delegated target (e.g. `cargo-dist`'s
187    /// `release.yml`) whose tag-triggered workflow owns Release creation and the
188    /// cross-platform binary upload. Mutually exclusive in practice with
189    /// [`Self::github_release`] — the coordinator either creates the Release or
190    /// delegates it, never both — and, like the others, monotonic (`false → true`).
191    /// Resume/verify treat a delegated Release as an intentional non-step, never a
192    /// missing one to re-attempt (`coordinator-release-vs-cargo-dist-ownership`).
193    /// `#[serde(default)]` so a pre-field manifest still deserializes (the manifest
194    /// is disposable and rebuilt from the log anyway).
195    #[serde(default)]
196    pub github_release_delegated: bool,
197}
198
199/// One completed-phase record in the [`RunState`] projection.
200#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
201pub struct PhaseRecord {
202    /// Which barrier completed.
203    pub phase: Phase,
204    /// How it completed.
205    pub outcome: PhaseOutcome,
206}
207
208/// The payload of a journal event — the ADR-0002 event classes. Serialized
209/// **internally tagged** on a `kind` discriminator, flattened into the
210/// [`JournalEvent`] envelope so each JSONL line is one flat object.
211#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
212#[serde(tag = "kind", rename_all = "snake_case")]
213pub enum EventKind {
214    /// The run was created: fixes its identity (`run_id`), the approved plan it
215    /// executes (`plan_id`), and the ordered target set. Always the first event.
216    RunCreated {
217        /// The run's unique id (a ULID from the injected `IdGen`).
218        run_id: String,
219        /// The sealed, content-addressed plan id this run executes (ADR-0002).
220        plan_id: String,
221        /// The chosen release version this run publishes — the human's approved
222        /// bump, sealed into `plan_id` and journalled as an input so `resume`
223        /// (wave-3) can reconstruct the plan from the durable record alone
224        /// (ADR-0002 §3; the plan module persists exactly `plan_id` + `version`).
225        ///
226        /// A **required** field of the v1 event, deliberately *not* `#[serde(default)]`:
227        /// a `RunCreated` without it is corrupt (a resume must never fabricate an
228        /// empty version and hash it into a wrong `plan_id`), so [`crate::release::journal::read_events`]
229        /// refuses such a line with an actionable error rather than defaulting to `""`.
230        version: String,
231        /// The ordered target set (e.g. `["rust", "node"]`).
232        targets: Vec<String>,
233    },
234    /// A phase barrier was entered.
235    PhaseEntered {
236        /// The barrier now in progress.
237        phase: Phase,
238    },
239    /// A phase barrier completed.
240    PhaseCompleted {
241        /// The barrier that completed.
242        phase: Phase,
243        /// Its outcome.
244        outcome: PhaseOutcome,
245    },
246    /// A target cleared its dry-run.
247    TargetDryRun {
248        /// The target id.
249        target: String,
250    },
251    /// A target's release artifact was built.
252    TargetBuilt {
253        /// The target id.
254        target: String,
255    },
256    /// A target was published — the point-of-no-return fact, with its receipt.
257    TargetPublished {
258        /// The target id.
259        target: String,
260        /// The receipt proving exactly what landed.
261        receipt: PublishReceipt,
262    },
263    /// A target was cancelled (skipped) with a reason.
264    TargetCancelled {
265        /// The target id.
266        target: String,
267        /// Why it was cancelled.
268        reason: String,
269    },
270    /// A **CI-delegated** target was skipped in the publish phase: its artifact is
271    /// produced out-of-band by the tag-triggered CI (e.g. `cargo-dist`'s
272    /// `release.yml`, a `release-please` merge job, or `PyPI`'s trusted-publisher
273    /// workflow), not by the engine's `publish` step. Distinct from
274    /// [`Self::TargetCancelled`] (a deliberate operator skip): a delegated target
275    /// is *expected* to land via CI, so resume/verify treat it as neither
276    /// engine-published nor missing/failed — the engine simply does not own it
277    /// (`release-engine-cut-cargo-dist-flow`).
278    TargetDelegated {
279        /// The target id.
280        target: String,
281        /// The adapter identity that declared itself CI-delegated (its wire
282        /// string, e.g. `"cargo-dist"`), for the operator-facing record.
283        adapter: String,
284    },
285    /// The release tag was created locally.
286    TagCreatedLocal {
287        /// The tag name.
288        tag: String,
289    },
290    /// The release tag was pushed to the remote.
291    TagPushedRemote {
292        /// The tag name.
293        tag: String,
294    },
295    /// The GitHub Release for the tag was created.
296    GithubReleaseCreated {
297        /// The tag name.
298        tag: String,
299        /// The Release URL, when GitHub reports one.
300        url: Option<String>,
301    },
302    /// The GitHub Release for the tag was **delegated to CI** — recorded in place
303    /// of [`Self::GithubReleaseCreated`]. The plan carries a CI-delegated target
304    /// (e.g. `cargo-dist`'s tag-triggered `release.yml`) whose workflow creates and
305    /// finalizes the Release and uploads the cross-platform binaries, so the
306    /// coordinator still creates and pushes the tag (that tag is what triggers CI)
307    /// but deliberately does **not** create the Release itself — doing so would
308    /// clash with CI over ownership of the same Release (creating it first, then CI
309    /// either fails on "release already exists" or uploads into an engine-created
310    /// stub). This fact is what lets resume/verify treat the missing engine-created
311    /// Release as intentional rather than a step to re-attempt
312    /// (`coordinator-release-vs-cargo-dist-ownership`).
313    GithubReleaseDelegated {
314        /// The tag name whose Release creation was delegated to CI.
315        tag: String,
316        /// The adapter identity whose CI owns the Release (its wire string, e.g.
317        /// `"cargo-dist"`) — the operator-facing record of *what* the Release was
318        /// delegated to, mirroring [`Self::TargetDelegated`]'s `adapter`.
319        delegated_to: String,
320    },
321    /// The run was abandoned. Terminal; there is **no** auto-rollback (ADR-0002).
322    RunAbandoned {
323        /// Why the run was abandoned.
324        reason: String,
325    },
326}
327
328/// One line of `journal.jsonl`: a schema-versioned, sequenced, timestamped
329/// envelope around an [`EventKind`].
330///
331/// The `kind` payload is `#[serde(flatten)]`ed so the on-disk line is a single
332/// flat JSON object (`{"schema_version":1,"seq":3,"ts":…,"idempotency_key":…,
333/// "kind":"target_published","target":"cargo","receipt":{…}}`), keeping it
334/// `jq`/`tail`-friendly (AGENTS-AI-FIRST-CLI §2).
335#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
336pub struct JournalEvent {
337    /// The durable schema version of this event (see [`JOURNAL_SCHEMA_VERSION`]).
338    pub schema_version: u32,
339    /// Monotonic sequence number within the run, starting at 1. The reducer's
340    /// high-water mark: an event at or below the applied `seq` is a no-op on
341    /// replay (append-then-apply crash recovery, ADR-0003 §2).
342    pub seq: u64,
343    /// Event time as whole seconds since the Unix epoch, from the injected
344    /// `Clock` (never wall-clock directly, so runs are deterministic under test).
345    pub ts: u64,
346    /// Stable semantic key identifying *what subject* this event records (e.g.
347    /// `published:cargo`, `phase_completed:build`). It is **metadata**, not the
348    /// append gate: it deliberately ignores the payload (a phase's `outcome`, a
349    /// receipt's version), so it is safe for diagnostics and for a coordinator's
350    /// own "have I already acted on this subject?" lookups, but it must **not**
351    /// be used to suppress an append — a phase that completed `Failed` and then,
352    /// after a resume, completes `Ok` shares this key yet is a distinct fact that
353    /// must be recorded. Replay idempotency is provided by [`Self::seq`] (the
354    /// high-water mark), not by this key.
355    pub idempotency_key: String,
356    /// The event payload, flattened into this envelope.
357    #[serde(flatten)]
358    pub kind: EventKind,
359}
360
361impl EventKind {
362    /// The stable idempotency key for this event — its natural semantic identity,
363    /// so a retried step (re-publishing an already-published target, re-entering a
364    /// phase) resolves to the same key.
365    ///
366    /// This is **metadata only**: it is deliberately *not* used to suppress an
367    /// append (see [`JournalEvent::idempotency_key`]). Two events can share a key
368    /// yet be distinct facts that must both be recorded — a `phase_completed`
369    /// `Failed` and, after a resume, a `phase_completed` `Ok` for the same phase.
370    /// Replay idempotency comes from [`JournalEvent::seq`] (the watermark), never
371    /// from this key.
372    #[must_use]
373    pub fn idempotency_key(&self) -> String {
374        match self {
375            Self::RunCreated { .. } => "run_created".to_string(),
376            Self::PhaseEntered { phase } => format!("phase_entered:{}", phase.as_str()),
377            Self::PhaseCompleted { phase, .. } => {
378                format!("phase_completed:{}", phase.as_str())
379            }
380            Self::TargetDryRun { target } => format!("dry_run:{target}"),
381            Self::TargetBuilt { target } => format!("built:{target}"),
382            Self::TargetPublished { target, .. } => format!("published:{target}"),
383            Self::TargetCancelled { target, .. } => format!("cancelled:{target}"),
384            Self::TargetDelegated { target, .. } => format!("delegated:{target}"),
385            Self::TagCreatedLocal { tag } => format!("tag_created_local:{tag}"),
386            Self::TagPushedRemote { tag } => format!("tag_pushed_remote:{tag}"),
387            Self::GithubReleaseCreated { tag, .. } => format!("github_release_created:{tag}"),
388            Self::GithubReleaseDelegated { tag, .. } => format!("github_release_delegated:{tag}"),
389            Self::RunAbandoned { .. } => "run_abandoned".to_string(),
390        }
391    }
392}
393
394/// The materialized run state — the projection reduced from the event log and
395/// cached in `manifest.json`.
396///
397/// Every collection is a `BTree*`/sorted `Vec`, so the serialized manifest is
398/// **byte-deterministic** for a given event stream: the same events always
399/// produce the same JSON, which is what makes the manifest a trustworthy cache
400/// of the log. It is disposable — rebuild it any time with
401/// [`crate::release::journal::reduce`].
402#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
403pub struct RunState {
404    /// Durable schema version of this state document.
405    pub schema_version: u32,
406    /// The run's unique id (empty only before the `RunCreated` event).
407    pub run_id: String,
408    /// The sealed plan id this run executes.
409    pub plan_id: String,
410    /// The chosen release version this run publishes (from the `RunCreated`
411    /// event) — the input `resume` reconstructs the plan against. Populated from
412    /// the required event field; the manifest is disposable and always rebuilt
413    /// from the log, so no cross-version default is needed here.
414    pub version: String,
415    /// The ordered target set, as declared at creation.
416    pub targets: Vec<String>,
417    /// The high-water sequence number folded into this state — the append-then-
418    /// apply watermark (ADR-0003 §2).
419    pub applied_seq: u64,
420    /// Derived run status.
421    pub status: RunStatus,
422    /// The phase currently in progress, if any.
423    pub current_phase: Option<Phase>,
424    /// Completed phases with their outcomes, sorted by phase order.
425    pub phases: Vec<PhaseRecord>,
426    /// Targets that cleared dry-run.
427    pub dry_run: BTreeSet<String>,
428    /// Targets whose artifact was built.
429    pub built: BTreeSet<String>,
430    /// Published targets → their receipts.
431    pub published: BTreeMap<String, PublishReceipt>,
432    /// Cancelled targets → their reasons.
433    pub cancelled: BTreeMap<String, String>,
434    /// CI-delegated targets (their ids): skipped in publish because a
435    /// tag-triggered CI job produces their artifact, not the engine. Neither
436    /// engine-published nor missing/failed (`release-engine-cut-cargo-dist-flow`).
437    /// `#[serde(default)]` so a v1 manifest that predates the field still
438    /// deserializes (the manifest is disposable and rebuilt from the log anyway).
439    #[serde(default)]
440    pub delegated: BTreeSet<String>,
441    /// Release tags → their landing progress.
442    pub tags: BTreeMap<String, TagState>,
443    /// The reason recorded by a `run_abandoned` event, if any.
444    pub abandon_reason: Option<String>,
445    /// Timestamp of the `RunCreated` event.
446    pub created_ts: u64,
447    /// Timestamp of the most recently applied event.
448    pub updated_ts: u64,
449}
450
451impl RunState {
452    /// The empty pre-`RunCreated` state the reducer folds events into. Carries
453    /// the current [`JOURNAL_SCHEMA_VERSION`] and [`RunStatus::InProgress`];
454    /// identity fields are filled by the first (`RunCreated`) event.
455    #[must_use]
456    pub fn empty() -> Self {
457        Self {
458            schema_version: JOURNAL_SCHEMA_VERSION,
459            run_id: String::new(),
460            plan_id: String::new(),
461            version: String::new(),
462            targets: Vec::new(),
463            applied_seq: 0,
464            status: RunStatus::InProgress,
465            current_phase: None,
466            phases: Vec::new(),
467            dry_run: BTreeSet::new(),
468            built: BTreeSet::new(),
469            published: BTreeMap::new(),
470            cancelled: BTreeMap::new(),
471            delegated: BTreeSet::new(),
472            tags: BTreeMap::new(),
473            abandon_reason: None,
474            created_ts: 0,
475            updated_ts: 0,
476        }
477    }
478}
479
480impl Default for RunState {
481    fn default() -> Self {
482        Self::empty()
483    }
484}