onevcs/event.rs
1//! The NDJSON event envelope this crate writes, and the filter a consumer reads it
2//! through.
3//!
4//! The *shape* of an envelope — a version, a stamp, a stream, a sequence number, a
5//! source, a kind, the labels, the payload, the artifacts — and the filter grammar
6//! over it are `onemessagebus`'s, and `onemessagebus`'s `docs/contract.md` is the
7//! one source of that shape. The **words** are this crate's: `src/vocabulary.rs`
8//! declares the source, the phases, the reserved labels and what a matcher may ask
9//! of them, and the types re-exported below are the bus core's generic ones over
10//! that vocabulary. This crate holds its own bytes to the copy in
11//! `docs/contract.md`, so an envelope that stopped being what this crate always
12//! wrote fails here rather than downstream.
13//!
14//! What stays in this module is the rest of that vocabulary — the closed
15//! [`EventKind`], and the phase each kind belongs to — and how a line of a stream
16//! this crate wrote is read back.
17
18use onemessagebus::Kind;
19use serde::{Deserialize, Serialize};
20
21pub use crate::vocabulary::{
22 ArtifactRef, Dimensions, Envelope, EventFilter, EventMatcher, Labels, MatchFields, Phase,
23 Source, VcsEvents, DIMENSIONS, RESERVED_LABELS, SOURCE_WORD,
24};
25
26/// What an event says happened.
27///
28/// These are the kinds `onevcs` produces. A consumer merging several sources
29/// reads each source's own kinds; nothing here promises to name another
30/// library's.
31///
32/// **A kind is retired by keeping it recognised and inert, never by deleting it.**
33/// A stream is a record, and this enum is what says whether a line of one can be
34/// read at all: delete a variant and every line any earlier build wrote with it
35/// stops parsing, in a build that has no way to know what it lost. That is not
36/// hypothetical — `gate-started` and `gate-verdict` went with the host-run gate in
37/// 0.11.0, and 30% of the streams on the host that consumes this crate turned into
38/// one refusal per line, most expensively in a status read that walks every stream
39/// there is. So a kind nothing emits any more keeps its variant, documented as
40/// retired and produced by nothing, and a reader goes on being able to say what
41/// that line recorded.
42///
43/// The permissive read this crate's stream readers go through is the other half of
44/// that rule rather than a substitute for it. It makes a kind this build has *never
45/// had* — one a later build wrote — cheap to pass over, which is the case no
46/// vocabulary here can cover. It cannot give back the meaning of a kind that was
47/// deleted, which is why the two retired above are a loss this crate carries rather
48/// than one it recovered.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(rename_all = "kebab-case")]
51pub enum EventKind {
52 /// A session was opened over a clone and worktree, on a pool slot or a run root.
53 SessionOpened,
54 /// Objects were fetched, deliberately outside any exclusive section.
55 Fetch,
56 /// Waiting on an identity's lock; carries the identity, elapsed, and queue
57 /// position.
58 LockWait,
59 /// The identity's lock was acquired.
60 LockAcquired,
61 /// Work was committed onto a preserved branch; carries the provenance kind.
62 CommitPreserved,
63 /// A branch was put on its identity's origin under its own name, without being
64 /// published; carries the branch, the identity, the origin URL, the commit, and
65 /// which of the three things `onevcs preserve` found to do.
66 ///
67 /// Deliberately **not** [`Push`](EventKind::Push), and that is the whole reason it
68 /// is its own kind. The one producer of `push` is a publication, so a reader
69 /// counting pushes to find publications must never meet a preservation — and a
70 /// preservation is the opposite of one: no change request is opened, no base is
71 /// touched, and the branch is exactly as recoverable afterwards as it was before.
72 BranchPreserved,
73 /// A branch was pushed.
74 Push,
75 /// A change request was opened; carries its URL and the host kind.
76 ChangeOpened,
77 /// A change request was opened as a **draft**, and this is why it is not ready;
78 /// carries its URL, the host's identifier for it, its base, and the reason — its
79 /// `kind`, and every field of that kind: for `awaiting-release` the repository
80 /// whose release is awaited, which target of it, the reference the change is
81 /// pinned to, and the one line a person reads; for `held` that one line alone.
82 ///
83 /// Beside [`ChangeOpened`](EventKind::ChangeOpened) rather than instead of it: the
84 /// change request *was* opened, and the link from its URL back to the branch is
85 /// what that kind records. This one records the state it was opened in.
86 ChangeDrafted,
87 /// The draft was lifted and the change request is open for review; carries its
88 /// URL and the host's identifier for it.
89 ///
90 /// The reason is not repeated here: it is on the
91 /// [`ChangeDrafted`](EventKind::ChangeDrafted) this answers, and the publication
92 /// that lifts a draft is one carrying none — on green checks, early when they
93 /// never ran on the draft, or at once with the lifecycle off. `onevcs change ready`
94 /// emits the same kind, because it is the same lift asked for as a verb.
95 DraftLifted,
96 /// A draft the publication opened while its required checks ran was lifted
97 /// **before** any of them had run on it, because the grace window elapsed and
98 /// the repository's checks skip drafts; carries its URL, identifier and base,
99 /// the required checks that had not run, the grace window in seconds, and whether
100 /// the warning line was printed. Emitted beside the
101 /// [`DraftLifted`](EventKind::DraftLifted) every lift emits.
102 DraftLiftedEarly,
103 /// Green required checks left a `change-open` change whose approvals are required
104 /// a draft, for its own user's review rather than the team's; carries its URL,
105 /// identifier and base.
106 DraftKeptForReview,
107 /// A publication's watch saw every required check stop blocking; carries the
108 /// change request's URL and identifier, the commit watched, the verdict —
109 /// `passed`, or `passed-with-skipped` where a required check concluded skipped —
110 /// and the skipped required checks by name.
111 ChecksSettled,
112 /// The change request's description was replaced after it was opened; carries
113 /// its URL, the host's identifier for it, its base, the title where the
114 /// description replaced it, and the artifact the body was stored as.
115 ///
116 /// The body is not inlined: it is prose of unbounded size, and the stream bounds
117 /// payload text. The artifact is the record — `onevcs artifact cat ID` reads back
118 /// exactly what was written — and the event references it as every other large
119 /// piece of evidence is referenced.
120 ChangeDescribed,
121 /// A check moved; carries its name, whether it is required, the status
122 /// transition, the conclusion, and its log as an artifact once complete.
123 ChangeCheck,
124 /// The change request merged; carries its URL, the commit it landed at as `sha`
125 /// and as `landing`, and `landed_at`, when the base received it.
126 ChangeMerged,
127 /// One local invocation reached its actual base, carrying base, commit and ordered branches.
128 BaseArrived,
129 /// The change request entered the host's merge queue.
130 MergeQueued,
131 /// The merge the host had queued completed; carries the commit it landed at as
132 /// `sha` and as `landing`, and `landed_at`, when the base received it.
133 MergeCompleted,
134 /// Preserved work that carried an incomplete-step marker was verified and
135 /// attested.
136 RecoveryAttested,
137 /// The base moved under a publication and the bounded resolve-and-requeue did
138 /// not converge.
139 SyncConflict,
140 /// The session's worktree and lease were released.
141 SessionClosed,
142 /// An **automated** release target's probe was run; carries the identity, the
143 /// target, which form of probe it was, what it answered, the version where it
144 /// answered one, and how long it took. A human-step target never produces one,
145 /// and that absence is the observable proof that no probe ran for it.
146 ReleaseProbed,
147 /// Somebody recorded a release of a human-step target; carries the identity,
148 /// the target, the version, the landing commit, the actor, and the version it
149 /// superseded where it replaced one.
150 ReleaseAcknowledged,
151 /// A landing was released, the first time it was: its baseline passed for an
152 /// automated target, its acknowledgement recorded for a human-step one.
153 ReleaseObserved,
154 /// A branch was recorded as superseded by a retry whose landing reached the base;
155 /// carries the identity, the branch, the branch that superseded it, that
156 /// branch's landing — a commit or a change request's URL — and the labels its
157 /// caller stamped.
158 ///
159 /// A record and nothing else: the superseded branch is left exactly where it is.
160 /// What it changes is how the branch is *classified* — `superseded-with-changes`
161 /// where it still differs from the base, which only `onevcs reclaim` acts on.
162 BranchSuperseded,
163 /// A finished branch was deleted everywhere this host holds it; carries the
164 /// identity, the branch, the tip it was deleted at, the class and proof that
165 /// permitted it, which verb or moment acted, and what was deleted and what was
166 /// not — so a partial retirement names the holder a re-run still has to reach.
167 BranchRetired,
168 /// One completed gate run of a publication attempt; carries which gate it was —
169 /// `pre-push` or `required-checks` — the attempt it belongs to, when it started
170 /// and ended, how long that was, its verdict, and for required checks every
171 /// required check with the times and conclusion the host reported.
172 ///
173 /// Recorded from the run the publication makes anyway, never from a second one:
174 /// the push that executed the repository's `pre-push` hook, and the watch of a
175 /// change request's required checks. Its phase is the gate's, so the producer
176 /// stamps it — `integrate` for `pre-push`, `review` for `required-checks`.
177 GateRun,
178 /// A change request's review feedback was read; carries its URL, how many
179 /// comments the read returned, whether nothing was new since the marker it was
180 /// read from, the digest of the marker to read from next (never the marker, which
181 /// grows with the change request), and what the host charged for it —
182 /// `{graphql_points, rest_requests}`, from the responses' own figures.
183 ReviewCommentsRead,
184 /// A reply to one review comment was posted, or found already posted under its
185 /// key; carries the change request's URL, the comment answered, the reply's id
186 /// and URL, whether it sits in the comment's thread, the key, and whether it was
187 /// already there so nothing was posted.
188 ReviewReplyPosted,
189 /// A stack base was assembled: a branch cut from a root and carrying a merge of
190 /// several parent branches, put on its origin with no change request; carries
191 /// the branch, its root, each parent with the head it was merged at or already
192 /// carried, the branch's head, and whether it was `created`, `advanced`,
193 /// `unchanged` or `conflicted`.
194 ///
195 /// Not [`Push`](EventKind::Push), for the reason
196 /// [`BranchPreserved`](EventKind::BranchPreserved) is not: the one producer of
197 /// `push` is a publication, and a stack base publishes nothing.
198 StackBaseAssembled,
199 /// Where a batch of one repository's change requests stand was read; carries the
200 /// repository, how many were read, the change requests whose landing the read
201 /// recorded, and what the host charged, `{graphql_points, rest_requests}`.
202 ChangeStandingsRead,
203 /// A change request was moved onto another base, or found on it already; carries
204 /// its URL, the base it left and the one it targets, whether it moved
205 /// (`retargeted` or `unchanged`), and whether a description was written with it.
206 ChangeRetargeted,
207 /// A closed change request was reopened over its restored base; carries its URL,
208 /// the base branch restored on the origin, and the commit it was restored at.
209 ChangeReopened,
210 /// A publication decided whether to merge its moved base into the branch before
211 /// pushing it; carries the branch, the base, the `decision` (`merged` or
212 /// `skipped`) and `because`.
213 BaseMerge,
214 /// A publication whose wait for the checks elapsed with none of them red left the
215 /// host's own merge armed on its change request, so it lands once the checks pass;
216 /// carries the change request's URL and the head commit armed.
217 MergeArmed,
218}
219
220/// How much attention an event asks of its consumer, stamped by its producer.
221#[derive(
222 Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
223)]
224#[non_exhaustive]
225#[serde(rename_all = "kebab-case")]
226pub enum Significance {
227 /// A change opened, its checks passed, or its landing reached its base.
228 Milestone,
229 /// An attempted action failed, was refused, or needs a person.
230 Blocker,
231 /// Ordinary running or successful detail.
232 Progress,
233}
234
235pub(crate) use crate::significance::{significance, EmissionResult};
236
237impl EventKind {
238 /// The kebab-case string this kind travels as, which is what a filter's
239 /// `kind` glob is matched against and what an envelope's `kind` carries.
240 ///
241 /// The spelling is serde's, and `the_wire_spelling_of_every_kind_is_the_one_a_filter_matches`
242 /// in `tests/contract.rs` holds the two together — a match rather than a
243 /// serialization so that stamping an event cannot fail, and exhaustive so that a
244 /// kind added to the enum cannot reach a stream unnamed.
245 fn wire(self) -> &'static str {
246 match self {
247 EventKind::SessionOpened => "session-opened",
248 EventKind::Fetch => "fetch",
249 EventKind::LockWait => "lock-wait",
250 EventKind::LockAcquired => "lock-acquired",
251 EventKind::CommitPreserved => "commit-preserved",
252 EventKind::BranchPreserved => "branch-preserved",
253 EventKind::Push => "push",
254 EventKind::ChangeOpened => "change-opened",
255 EventKind::ChangeDrafted => "change-drafted",
256 EventKind::DraftLifted => "draft-lifted",
257 EventKind::DraftLiftedEarly => "draft-lifted-early",
258 EventKind::DraftKeptForReview => "draft-kept-for-review",
259 EventKind::ChecksSettled => "checks-settled",
260 EventKind::ChangeDescribed => "change-described",
261 EventKind::ChangeCheck => "change-check",
262 EventKind::ChangeMerged => "change-merged",
263 EventKind::BaseArrived => "base-arrived",
264 EventKind::MergeQueued => "merge-queued",
265 EventKind::MergeCompleted => "merge-completed",
266 EventKind::RecoveryAttested => "recovery-attested",
267 EventKind::SyncConflict => "sync-conflict",
268 EventKind::SessionClosed => "session-closed",
269 EventKind::ReleaseProbed => "release-probed",
270 EventKind::ReleaseAcknowledged => "release-acknowledged",
271 EventKind::ReleaseObserved => "release-observed",
272 EventKind::BranchSuperseded => "branch-superseded",
273 EventKind::BranchRetired => "branch-retired",
274 EventKind::GateRun => "gate-run",
275 EventKind::ReviewCommentsRead => "review-comments-read",
276 EventKind::ReviewReplyPosted => "review-reply-posted",
277 EventKind::StackBaseAssembled => "stack-base-assembled",
278 EventKind::ChangeStandingsRead => "change-standings-read",
279 EventKind::ChangeRetargeted => "change-retargeted",
280 EventKind::ChangeReopened => "change-reopened",
281 EventKind::BaseMerge => "base-merge",
282 EventKind::MergeArmed => "merge-armed",
283 }
284 }
285
286 /// The kind an envelope's wire `kind` names, where this build has a word for it.
287 ///
288 /// Read through serde's own spelling rather than a second table, so the kinds
289 /// this build can read back are exactly the kinds it can write.
290 fn named(kind: &Kind) -> Option<Self> {
291 Self::deserialize(
292 serde::de::value::StrDeserializer::<serde::de::value::Error>::new(kind.as_str()),
293 )
294 .ok()
295 }
296}
297
298/// An envelope's `kind` is open on the wire, and this crate's closed vocabulary is
299/// what it writes into it.
300impl From<EventKind> for Kind {
301 fn from(kind: EventKind) -> Self {
302 Kind::from(kind.wire())
303 }
304}
305
306/// The phase an event of one of this crate's kinds belongs to, where the kind alone
307/// decides it.
308///
309/// A trait rather than an inherent method because the four phases are declared in
310/// `src/vocabulary.rs`, beside the rest of the wire words, and which of them an
311/// `onevcs` kind is in is a fact about the kinds declared here. With it in scope
312/// the call is spelled `Phase::of(kind)`, as it always was.
313pub trait PhaseOf {
314 /// The phase an event of this kind belongs to, where the kind alone decides it.
315 ///
316 /// `None` for exactly two kinds, and neither is an omission: a
317 /// [`Push`](EventKind::Push) of the session's own branch is
318 /// [`Development`](Phase::Development) and a push of anything else — the base a
319 /// `local-direct` squash lands on, the base a merge train advanced — is
320 /// [`Integrate`](Phase::Integrate). Which of the two it was is a fact about the
321 /// push rather than about the kind, so the producer stamps it and this answers
322 /// that it cannot. A [`GateRun`](EventKind::GateRun) is the same: a `pre-push`
323 /// gate is [`Integrate`](Phase::Integrate) and a change request's required checks
324 /// are [`Review`](Phase::Review), which is a fact about the gate.
325 fn of(kind: EventKind) -> Option<Phase>;
326}
327
328impl PhaseOf for Phase {
329 fn of(kind: EventKind) -> Option<Phase> {
330 Some(match kind {
331 EventKind::SessionOpened
332 | EventKind::Fetch
333 | EventKind::LockWait
334 | EventKind::LockAcquired
335 | EventKind::CommitPreserved
336 // The work being made, kept: putting a branch on its origin under its own
337 // name proposes nothing and integrates nothing, and a `local-direct`
338 // identity has no Review phase for it to be in.
339 | EventKind::BranchPreserved
340 // The repair of a preserved branch, and therefore the work being made:
341 // it puts the branch back into a state its merge path can rule on, and
342 // it happens before that branch may enter one at all.
343 | EventKind::RecoveryAttested
344 | EventKind::SessionClosed => Phase::Development,
345 EventKind::MergeQueued | EventKind::MergeCompleted | EventKind::SyncConflict | EventKind::BaseArrived => {
346 Phase::Integrate
347 }
348 // Bringing the base into the branch, or deciding not to, is the step a sync
349 // conflict is met at: the work being brought level with what it lands on.
350 EventKind::BaseMerge => Phase::Integrate,
351 // What became of a branch once its work reached the base, or once a retry
352 // of it did: the base is what decides both, so both are that work being
353 // integrated rather than made or proposed.
354 EventKind::BranchSuperseded | EventKind::BranchRetired => Phase::Integrate,
355 // Several branches brought together onto a root, for the changes based on
356 // them: integration of work that is already made, and proposing nothing.
357 EventKind::StackBaseAssembled => Phase::Integrate,
358 EventKind::ChangeOpened
359 | EventKind::ChangeDrafted
360 | EventKind::DraftLifted
361 | EventKind::DraftLiftedEarly
362 | EventKind::DraftKeptForReview
363 | EventKind::ChecksSettled
364 | EventKind::ChangeDescribed
365 | EventKind::ChangeCheck
366 | EventKind::ChangeMerged
367 // The host's merge of the change request, armed to happen once its checks
368 // pass: the change being ruled on, as `change-merged` is.
369 | EventKind::MergeArmed
370 // Reading what reviewers said and answering it is the change being ruled on.
371 | EventKind::ReviewCommentsRead
372 | EventKind::ReviewReplyPosted
373 // Where each change request under review stands, and the moves that keep a
374 // stack of them true to the host — a base changed, a closed draft reopened:
375 // the change being ruled on, as the host reads and writes it.
376 | EventKind::ChangeStandingsRead
377 | EventKind::ChangeRetargeted
378 | EventKind::ChangeReopened => Phase::Review,
379 EventKind::ReleaseProbed
380 | EventKind::ReleaseAcknowledged
381 | EventKind::ReleaseObserved => Phase::Release,
382 EventKind::Push | EventKind::GateRun => return None,
383 })
384 }
385}
386
387/// The phase an event of this kind is stamped at when its producer names none.
388///
389/// The kinds whose phase their producer decides are a push and a gate run, and
390/// [`Stream::push_result`](crate::stream::Stream::push_result) and
391/// [`Stream::emit_gate_run`](crate::stream::Stream::emit_gate_run) are where every
392/// one in this crate decides it. A push reaching here instead — or a line an older
393/// build wrote before there was a phase — is read at the phase a session's own
394/// stream is in, which is what all but one producer of a push stamps. A gate run
395/// never reaches here unstamped: no build wrote one before there was a phase.
396pub(crate) fn phase_of(kind: EventKind) -> Phase {
397 Phase::of(kind).unwrap_or(Phase::Development)
398}
399
400/// The id of a stored artifact.
401///
402/// This crate's own rather than the bus's: `onemessagebus` 0.4.0 carries an
403/// artifact's id as a plain string on [`ArtifactRef`], and the host seam's
404/// [`check_log`](crate::RemoteHost::check_log) answers a typed one.
405#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
406#[serde(transparent)]
407pub struct ArtifactId(pub String);
408
409/// One line of a stream, read as far as this build's vocabulary reaches.
410///
411/// The distinction the readers of a stream are held to. A line that is *not what a
412/// writer left* — torn, of an envelope version this build does not read, stamped in
413/// a way nothing can order — is a gap, and saying so is not negotiable: reporting
414/// "could not look" as "there is none" is how a report about half a record reads as
415/// a report about all of it. A line that is a perfectly good envelope recording
416/// something this build has no word for is not that. There is nothing to conclude
417/// from it and nothing missing from the read either, so it is passed over rather
418/// than announced — which is what a reader of streams a *later* build wrote needs,
419/// and what a reader of streams an earlier one wrote needed and did not have.
420pub(crate) enum Line {
421 /// An envelope of a kind this build knows, and can therefore act on.
422 ///
423 /// Boxed: an envelope carries three strings, a map and a vector, and the other
424 /// variant is a header — so an unboxed enum would make every line of every
425 /// stream cost the larger of the two.
426 Known(Box<Known>),
427 /// A well-formed envelope of a kind this build has no word for.
428 Unknown(UnknownKind),
429}
430
431/// An envelope whose kind this build has a word for, with that word beside it.
432pub(crate) struct Known {
433 /// The kind the envelope's wire `kind` names.
434 pub kind: EventKind,
435 /// The envelope itself, at the phase its producer stamped — or, for a line an
436 /// older build wrote before there was a phase, the phase its kind decides.
437 pub envelope: Envelope,
438}
439
440/// A line whose kind this build cannot name, as much of it as such a reader can use.
441///
442/// Its header and nothing else, deliberately. Whether the line is a *gap* is
443/// decided by the envelope's own fields — the version it declares, the stamp it is
444/// ordered by, the stream it belongs to — and those mean the same thing whatever
445/// happened, so every check a known kind gets this one gets too. The payload is the
446/// part the kind is the key to, so there is nothing here to offer of it.
447pub(crate) struct UnknownKind {
448 /// The envelope schema version the line declares.
449 pub v: u32,
450 /// When it was stamped, unparsed: ordering it is the reader's own check.
451 pub ts: String,
452 /// The stream it names, so attribution is asked of it as of any other line.
453 pub stream: String,
454 /// The kind it carries, as it was spelled.
455 pub kind: Kind,
456}
457
458impl Line {
459 /// One line of a stream, tolerant of its kind and of nothing else.
460 // llmlint: ignore[boundary_inputs_validated] the envelope's *shape* is validated here,
461 // by the agent profile's envelope: an unknown top-level key, a `seq` that is not a
462 // u64, a source outside the three families, and a missing required field are each
463 // refused. The two semantic checks — that `v` is the version this build reads, and
464 // that `ts` is a stamp it can order — are deliberately not here, for the reason the
465 // envelope has never made them either: what to do about one is the *reader's*, and
466 // the readers disagree. `status` reports each as a gap in its notes rather than
467 // refusing, because it is asked what became of a piece of work and must not answer
468 // "there is none" for "could not look" — and it applies both to a line whose kind has
469 // no word here exactly as to one it knows, which is what `UnknownKind` carries the
470 // header for. Deciding either here would take that choice away from the one caller
471 // that has to report rather than refuse.
472 pub(crate) fn read(line: &str) -> serde_json::Result<Self> {
473 serde_json::from_str(line).map(Self::of)
474 }
475
476 /// An envelope a reader has already parsed, read as far as this build's
477 /// vocabulary reaches.
478 pub(crate) fn of(mut envelope: Envelope) -> Self {
479 let Some(kind) = EventKind::named(&envelope.kind) else {
480 return Line::Unknown(UnknownKind {
481 v: envelope.v,
482 ts: envelope.ts,
483 stream: envelope.stream,
484 kind: envelope.kind,
485 });
486 };
487 // A line an older build wrote carries no phase, and the phase is additive
488 // inside `v: 1`, so it reads at the phase its kind decides. A `push` among
489 // them named no target, so there is nothing to recover the producer's
490 // classification from — it reads as the phase a push of the session's own
491 // branch is, which is a reading of a record rather than a claim about the
492 // push, and why the phase is stamped from here on.
493 envelope
494 .dimensions
495 .phase
496 .get_or_insert_with(|| phase_of(kind));
497 Line::Known(Box::new(Known { kind, envelope }))
498 }
499
500 /// The stream this line names, whether or not its kind has a word here.
501 pub(crate) fn stream(&self) -> &str {
502 match self {
503 Line::Known(known) => &known.envelope.stream,
504 Line::Unknown(header) => &header.stream,
505 }
506 }
507}