Skip to main content

rusty_agent_runtime/
deploy.rs

1//! The deployment control plane's core contracts (R0.12 Operations
2//! Plane, wave 3): revisions, environments, and the per-environment
3//! deployment pointer, plus the journaled payloads of every control-plane
4//! act and the environment-scoped secret records.
5//!
6//! The governing decision, from the design: the heavy machinery is
7//! reused, so the new entities stay small. A [`DeploymentRevision`] is
8//! the [`crate::learn::Candidate`] discipline turned toward deployments —
9//! immutable, content-addressed ([`derive_revision_id`], the
10//! [`crate::learn::derive_candidate_id`] rule), authored (`human:{id}`
11//! attribution) — carrying the graph/assistant identity, the
12//! `graph_hash` the checkpoint header already computes, and a **frozen
13//! pin set**: the registry surfaces the revision binds, resolved to
14//! candidate ids at revision *creation* from a declared source
15//! environment. The freeze is deliberate and priced in the design's
16//! honest edges: a revision evaluated against a recorded dataset must be
17//! the same thing the gate evaluated when it canaries, and pins resolved
18//! at admission would make that evidence a moving target. The weight —
19//! every registry promotion that should reach prod requires a new
20//! revision — is the price of evaluable deployments, paid knowingly.
21//!
22//! An [`Environment`] is R0.11's tag promoted to a first-class record:
23//! a name (the `dev` / `staging` / `prod` convention, deployment-declared
24//! rather than enumerated), the gate and approval declarations that will
25//! govern promotions into it (wired in wave 4; declared here so the rule
26//! in force is data, not code), and creation metadata. What an
27//! environment is *not* — the R0.11 tag discipline applied one level up:
28//! not a separate process, not an isolated store, not a trust boundary.
29//! Environments are logical surfaces over one deployment's stores and one
30//! binary's admission path.
31//!
32//! The [`DeploymentPointer`] is the R0.8
33//! [`crate::learn::VersionPointer`] shape applied to revisions: one
34//! pointer per environment under the surface key `deployment:{env}`, an
35//! `active` full-traffic revision, and a `canary` binding one revision to
36//! a declared fraction of new runs. Promotion moves `active` and clears
37//! any canary — a full promotion supersedes the experiment it graduated
38//! from. Rollback re-points `active` to the previously serving revision:
39//! byte-exact, because the restored revision is the immutable record that
40//! served before, not a reconstruction. Canary admission is the seeded
41//! draw ([`deployment_admission`]) over the pointer surface — the draw
42//! machinery reused verbatim; only the surface it draws over is new.
43//!
44//! Environment-scoped secrets are custody, not brokerage (R0.11's line,
45//! re-argued by the environment dimension): named, tenant-scoped,
46//! environment-tagged values stored as ciphertext envelopes on both
47//! backends (the broker's construction — the store side only ever holds
48//! [`StoredEnvSecret`]), journaled as metadata — never bytes — on the
49//! deployment evidence chain. A request outside the holder's environment
50//! is a typed, journaled [`EnvSecretDenial`]: scoping is enforcement, not
51//! convention.
52//!
53//! Wave 4 turns the declared rules into enforced ones. The gate an
54//! [`Environment`] declares is evaluated through the
55//! [`RevisionGateEvaluator`] seam — core owns the contract, never the
56//! evaluator, so the runtime keeps its distance from `rusty-eval` (the
57//! workspace's dependency direction) — and the decision journals as a
58//! [`GateDecisionRecord`] *before* the pointer move it governs, allowed
59//! or refused: a gate whose refusals leave no evidence is a gate an
60//! audit cannot tell apart from never having run. Approval-required
61//! environments gate promotion behind a token scoped to the revision's
62//! own promotion effect id ([`revision_promotion_effect_id`]) — a token
63//! minted for one revision admits no other, so an approval is a fact
64//! about a specific deploy, not a standing permission. Canary declare
65//! and clear are journaled acts ([`CanaryDeclaration`],
66//! [`CanaryClearance`]) on the same chain, so the experiment's whole
67//! lifecycle — declared, drawn against, graduated or cleared — reads
68//! from one evidence trail. And a shadow run replays a recorded run's
69//! twin against a candidate revision behind the shadow admission
70//! boundary, journaling its start ([`ShadowRunStarted`]), every refusal
71//! the boundary served or not, and its [`ShadowVerdict`]: divergence as
72//! evidence, with no path to the world.
73
74use async_trait::async_trait;
75use chrono::{DateTime, Utc};
76use serde::{Deserialize, Serialize};
77use serde_json::Value;
78use thiserror::Error;
79
80use crate::broker::SealedCredential;
81use crate::effects::{derive_effect_id, EffectId, ShadowRefusal};
82use crate::error::Result;
83use crate::learn::{canary_admits, CanaryBinding, CandidateId, EnvironmentTag, SurfaceKey};
84use crate::memory::ProvenanceAuthor;
85use crate::record::{sha256_hex, DecisionRole};
86use crate::registry::PointerBinding;
87
88// --------------------------------------------------------------------- //
89// The deployment revision
90// --------------------------------------------------------------------- //
91
92/// A content-addressed revision identity: lowercase hex SHA-256 over the
93/// revision's canonical content ([`derive_revision_id`]). Transparent
94/// newtype so the type system — not convention — keeps revision ids
95/// distinct from candidate ids, memory addresses, and other digest
96/// strings (the [`CandidateId`] precedent).
97#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
98#[serde(transparent)]
99pub struct RevisionId(String);
100
101impl RevisionId {
102    /// The hex digest.
103    pub fn as_str(&self) -> &str {
104        &self.0
105    }
106}
107
108impl std::fmt::Display for RevisionId {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        f.write_str(&self.0)
111    }
112}
113
114impl From<String> for RevisionId {
115    /// Wrap a digest the caller already trusts — rehydration from storage,
116    /// a rollback's `to`. Minting ids from content is
117    /// [`derive_revision_id`]'s job alone; nothing here re-verifies.
118    fn from(digest: String) -> Self {
119        Self(digest)
120    }
121}
122
123/// One frozen pin: a registry surface bound to the candidate id that
124/// served it in the revision's source environment at creation. The pin
125/// names a *candidate* — content-addressed, immutable — so the pin set
126/// can never drift beneath a recorded revision: what the gate evaluated
127/// is what canaries, byte for byte.
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
129pub struct RegistryPin {
130    /// The untagged registry surface (`prompt:system`,
131    /// `model_settings:primary`, …). The environment the pin was resolved
132    /// from travels once on the revision (`source_environment`), not on
133    /// every pin.
134    pub surface: SurfaceKey,
135
136    /// The candidate the source environment's pointer served at creation.
137    pub candidate_id: CandidateId,
138}
139
140/// What a revision binds: the content the address covers.
141///
142/// Struct serialization is field-ordered, so the canonical form is stable
143/// across map backends — the same discipline
144/// [`crate::learn::derive_candidate_id`] relies on. Attribution is not
145/// identity (the [`crate::learn::Candidate`] rule): the author and the
146/// creation instant travel on the record, outside the address, so two
147/// registrations of the same declaration converge on one id.
148#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
149pub struct RevisionContent {
150    /// The registered graph this revision serves (the `GraphRegistry`
151    /// name — the run's admission target).
152    pub graph: String,
153
154    /// The graph's topology hash — exactly what
155    /// [`crate::graph::Graph::topology_hash`] computes and the checkpoint
156    /// header stamps. Code identity is the R0.7/R0.11 story, unchanged;
157    /// the revision records it so admission can refuse a build the
158    /// revision no longer describes.
159    pub graph_hash: String,
160
161    /// The assistant identity the revision binds, when the deployment
162    /// serves through one. Absent when the revision binds the graph
163    /// directly.
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub assistant: Option<String>,
166
167    /// The environment the pin set was resolved from at creation. A
168    /// revision-refresh is a new revision resolved again from its source
169    /// — the staleness of the freeze becomes a journaled act, never
170    /// silent drift.
171    pub source_environment: EnvironmentTag,
172
173    /// The frozen pin set, sorted by surface (the canonical order — a
174    /// set, so order is derivation, not declaration). May be empty: a
175    /// graph that binds no registry artifacts pins nothing.
176    pub pins: Vec<RegistryPin>,
177}
178
179/// The content address of a revision: `sha256` over the canonical
180/// serialization of its content — the [`crate::learn::derive_candidate_id`]
181/// discipline, so two registrations of the same declaration converge on
182/// one id and a tampered revision fails its own address.
183pub fn derive_revision_id(content: &RevisionContent) -> Result<RevisionId> {
184    Ok(RevisionId(sha256_hex(&serde_json::to_vec(content)?)))
185}
186
187/// The digest a journaled [`DeploymentResolved`] names for the bound
188/// revision's pin set: `sha256` over the canonical pin list. The
189/// revision's own address already covers the pins — one derivation, two
190/// homes — so the audit walk reads the pin-set commitment out of the
191/// resolution event without fetching the revision.
192pub fn pin_set_digest(pins: &[RegistryPin]) -> String {
193    // Struct serialization is field-ordered (see `RevisionContent`), so
194    // this digest is stable across map backends.
195    let bytes = serde_json::to_vec(pins).expect("a pin list always serializes");
196    sha256_hex(&bytes)
197}
198
199/// An immutable, content-addressed declaration of what may serve.
200///
201/// Immutable by construction: a changed declaration is a new id, and
202/// there is no in-place update anywhere in the control plane. A registry
203/// prompt promotion does not flow into an existing revision — the
204/// revision-refresh path mints a new one addressing the delta, a
205/// journaled act like any other.
206#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
207pub struct DeploymentRevision {
208    /// The content address ([`derive_revision_id`]).
209    pub revision_id: RevisionId,
210
211    /// What the revision binds.
212    pub content: RevisionContent,
213
214    /// Who registered the revision (`human:{id}`, the registry commit
215    /// discipline). Mandatory — journaled with registration, because a
216    /// deployment act that cannot name its author is indistinguishable
217    /// from an untracked edit.
218    pub author: ProvenanceAuthor,
219
220    /// When the revision was registered.
221    pub created_at: DateTime<Utc>,
222}
223
224impl DeploymentRevision {
225    /// Mint a revision over `content`, attributed to `author`. The pin
226    /// set is canonicalized here — sorted by surface, duplicate surfaces
227    /// refused — so equal declarations converge on one address however
228    /// the caller ordered them.
229    pub fn new(
230        mut content: RevisionContent,
231        author: ProvenanceAuthor,
232        created_at: DateTime<Utc>,
233    ) -> std::result::Result<Self, DeployError> {
234        if content.graph.is_empty() {
235            return Err(DeployError::InvalidRevision {
236                reason: "empty graph identity — a revision exists to name what serves",
237            });
238        }
239        content.pins.sort_by(|a, b| a.surface.cmp(&b.surface));
240        for pair in content.pins.windows(2) {
241            if pair[0].surface == pair[1].surface {
242                return Err(DeployError::DuplicatePin {
243                    surface: pair[0].surface.clone(),
244                });
245            }
246        }
247        let revision_id = derive_revision_id(&content)
248            .map_err(|e| DeployError::UnaddressableContent(e.to_string()))?;
249        Ok(Self {
250            revision_id,
251            content,
252            author,
253            created_at,
254        })
255    }
256
257    /// Re-derive the content address and compare. The integrity check the
258    /// store read path and admission run before anything serves or pins —
259    /// a revision failing its own address is tampered evidence, refused
260    /// rather than journaled.
261    pub fn verify_address(&self) -> std::result::Result<(), DeployError> {
262        let derived = derive_revision_id(&self.content)
263            .map_err(|e| DeployError::UnaddressableContent(e.to_string()))?;
264        if derived != self.revision_id {
265            return Err(DeployError::AddressMismatch {
266                declared: self.revision_id.clone(),
267                derived,
268            });
269        }
270        Ok(())
271    }
272}
273
274// --------------------------------------------------------------------- //
275// The environment record
276// --------------------------------------------------------------------- //
277
278/// The gate declaration governing promotions into an environment: the
279/// gate policy's name and the dataset version the gate replays. Names
280/// only — the declaration, not the evaluator: the rule in force when a
281/// promotion happens is data an audit reads, not code it infers. Wave 4
282/// evaluates it through the [`RevisionGateEvaluator`] seam before any
283/// pointer moves.
284#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
285pub struct GateDeclaration {
286    /// The gate policy's name (the `rusty-eval` `GatePolicy` the control
287    /// plane will evaluate through the core seam, wave 4).
288    pub policy: String,
289
290    /// The recorded dataset version the gate replays the revision
291    /// against. Versioned because datasets are immutable per version:
292    /// re-running the gate must mean re-reading the same evidence.
293    pub dataset_version: String,
294}
295
296/// An environment: R0.11's promotion tag as a first-class record.
297///
298/// Logical, not physical — one deployment serves every environment from
299/// one store and one binary's admission path; the record exists so the
300/// control plane can name the surface, declare its promotion rule, and
301/// answer "which revision serves here" from journaled data.
302#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
303pub struct Environment {
304    /// The environment's name — `dev` / `staging` / `prod` by
305    /// deployment-declared convention, not an enum: the R0.11 tag set,
306    /// promoted. Validated by [`EnvironmentTag`], so the pointer surface
307    /// key (`deployment:{name}`) is always well-formed.
308    pub name: EnvironmentTag,
309
310    /// The gate declaration promotions into this environment must clear,
311    /// when one is declared (enforced by the control plane since wave 4;
312    /// recorded from the start). Absent: promotion is an operator act
313    /// with no gate — the `dev` floor.
314    #[serde(default, skip_serializing_if = "Option::is_none")]
315    pub gate: Option<GateDeclaration>,
316
317    /// Whether promotions into this environment require a human approval
318    /// token scoped to the revision's promotion effect id (enforced
319    /// since wave 4; the `prod` stance). Recorded as data so the
320    /// declaration is auditable before it is enforced.
321    #[serde(default)]
322    pub approval_required: bool,
323
324    /// Who declared the environment (`human:{id}`).
325    pub created_by: ProvenanceAuthor,
326
327    /// When the environment was declared.
328    pub created_at: DateTime<Utc>,
329}
330
331/// The pointer surface key for one environment: `deployment:{env}`. One
332/// prefix for every deployment pointer, so pointer listings and the
333/// canary draw's seed material read without string surgery.
334pub fn deployment_surface(environment: &EnvironmentTag) -> SurfaceKey {
335    SurfaceKey::new(format!("deployment:{environment}"))
336}
337
338// --------------------------------------------------------------------- //
339// The deployment pointer
340// --------------------------------------------------------------------- //
341
342/// A canary binding on a deployment pointer: one revision bound to a
343/// declared fraction of new runs while `active` serves the rest — the
344/// [`crate::learn::CanaryBinding`] shape with a revision in the slot.
345#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
346pub struct CanaryDeployment {
347    /// The canaried revision.
348    pub revision_id: RevisionId,
349
350    /// The fraction of new runs the revision serves, in `(0, 1]`.
351    pub fraction: f64,
352}
353
354impl CanaryDeployment {
355    /// Declare a canary. Fractions outside `(0, 1]` are refused: zero
356    /// binds nothing (a cleared slot says that), and above one is not a
357    /// fraction.
358    pub fn new(revision_id: RevisionId, fraction: f64) -> std::result::Result<Self, DeployError> {
359        if !(fraction > 0.0 && fraction <= 1.0) {
360            return Err(DeployError::InvalidFraction { fraction });
361        }
362        Ok(Self {
363            revision_id,
364            fraction,
365        })
366    }
367}
368
369/// The serving revision of one environment: an immutable-pointer move
370/// away from any revision that ever served — the R0.8
371/// [`crate::learn::VersionPointer`] shape applied to revisions.
372///
373/// New runs bind the pointer at admission (the canary by seeded draw —
374/// [`deployment_admission`]); in-flight runs keep the revision their
375/// journaled resolution names, the same conservatism as checkpoint
376/// pinning. There is no hot reload: a hot-reloaded deployment is a
377/// silent behavioral rewrite, forbidden since R0.8.
378#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
379pub struct DeploymentPointer {
380    /// The surface this pointer governs (`deployment:{env}`).
381    pub surface: SurfaceKey,
382
383    /// The full-traffic revision (`None`: the environment serves
384    /// nothing — there is no implicit "latest", because latest is a
385    /// guess with a deploy's blast radius).
386    #[serde(default, skip_serializing_if = "Option::is_none")]
387    pub active: Option<RevisionId>,
388
389    /// The canary binding, when one is declared.
390    #[serde(default, skip_serializing_if = "Option::is_none")]
391    pub canary: Option<CanaryDeployment>,
392}
393
394impl DeploymentPointer {
395    /// A pointer with nothing serving.
396    pub fn new(surface: SurfaceKey) -> Self {
397        Self {
398            surface,
399            active: None,
400            canary: None,
401        }
402    }
403
404    /// The pointer after a promotion: `active` moves to the promoted
405    /// revision and any canary clears — a full promotion supersedes the
406    /// experiment it graduated from (the
407    /// [`crate::learn::VersionPointer::promoted`] semantics).
408    pub fn promoted(&self, promotion: &RevisionPromotion) -> DeploymentPointer {
409        let mut next = self.clone();
410        next.active = Some(promotion.revision_id.clone());
411        next.canary = None;
412        next
413    }
414
415    /// The pointer after a rollback: `active` re-points to the
416    /// revision that served before — byte-exact, because revisions are
417    /// content-addressed and immutable, so the restored revision is the
418    /// one that served, not a reconstruction. A canary naming the rolled
419    /// revision clears with it. The caller derives `to` from the
420    /// journaled transition history before building the rollback — this
421    /// is the move, not the check.
422    pub fn rolled_back(&self, rollback: &RevisionRollback) -> DeploymentPointer {
423        let mut next = self.clone();
424        if self.active.as_ref() == Some(&rollback.from) {
425            next.active = rollback.to.clone();
426        }
427        if self
428            .canary
429            .as_ref()
430            .is_some_and(|canary| canary.revision_id == rollback.from)
431        {
432            next.canary = None;
433        }
434        next
435    }
436}
437
438/// The revision an environment's pointer binds for `run_id`: the canary
439/// when this run's seeded draw admits, else the full-traffic revision.
440/// `None` when the pointer serves nothing — a pointer serving nothing
441/// binds nothing, and admission refuses the run rather than guessing.
442///
443/// The draw reuses [`canary_admits`] verbatim: its seed material is the
444/// bound id's string form, so wrapping the revision id as a one-off
445/// [`CanaryBinding`] draws the identical seeded value the learn plane
446/// would — a canary at staging and a canary at prod are independent
447/// draws over the same run id (the surface is part of the seed), and a
448/// recorded run re-derives its assignment from the journaled resolution
449/// alone.
450pub fn deployment_admission(
451    pointer: &DeploymentPointer,
452    run_id: &str,
453) -> Option<(RevisionId, PointerBinding)> {
454    if let Some(canary) = &pointer.canary {
455        let binding = CanaryBinding {
456            candidate_id: CandidateId::from(canary.revision_id.as_str().to_owned()),
457            fraction: canary.fraction,
458        };
459        if canary_admits(&binding, &pointer.surface, run_id) {
460            return Some((canary.revision_id.clone(), PointerBinding::Canary));
461        }
462    }
463    pointer
464        .active
465        .clone()
466        .map(|revision_id| (revision_id, PointerBinding::Active))
467}
468
469// --------------------------------------------------------------------- //
470// The journaled control-plane acts
471// --------------------------------------------------------------------- //
472
473/// A revision was registered: the journaled payload of a
474/// [`crate::record::RunEventKind::RevisionRegistered`] event on the
475/// deployment evidence chain. The revision carries its own author and
476/// content address; the tenant rides alongside because the chain is
477/// deployment-wide (the [`crate::artifact::ArtifactRelease`] precedent —
478/// audit metadata, not scoping).
479#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
480pub struct RevisionRegistration {
481    /// The tenant the revision registered under.
482    pub tenant: String,
483
484    /// The registered revision.
485    pub revision: DeploymentRevision,
486}
487
488/// An environment was declared: the journaled payload of a
489/// [`crate::record::RunEventKind::EnvironmentDeclared`] event. The rule
490/// in force journals with the declaration, so an audit reads the
491/// declaration that governed a promotion, not a later edit.
492#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
493pub struct EnvironmentDeclaration {
494    /// The tenant the environment was declared under.
495    pub tenant: String,
496
497    /// The declared environment.
498    pub environment: Environment,
499}
500
501/// A revision was promoted into an environment: the journaled payload of
502/// a [`crate::record::RunEventKind::RevisionPromoted`] event, and the
503/// move [`DeploymentPointer::promoted`] applies. `previous` is recorded
504/// because it is the rollback path's whole story: the transition history
505/// on the chain is what a byte-exact rollback re-derives, never a
506/// reconstruction.
507#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
508pub struct RevisionPromotion {
509    /// The tenant the promotion governs.
510    pub tenant: String,
511
512    /// The environment promoted into.
513    pub environment: EnvironmentTag,
514
515    /// The revision that now serves full traffic.
516    pub revision_id: RevisionId,
517
518    /// The revision the promotion displaced (`None` when the environment
519    /// served nothing before).
520    #[serde(default, skip_serializing_if = "Option::is_none")]
521    pub previous: Option<RevisionId>,
522
523    /// Who promoted (`human:{id}` — a deployment act with a name on it).
524    pub author: ProvenanceAuthor,
525
526    /// When the promotion journaled.
527    pub promoted_at: DateTime<Utc>,
528}
529
530/// A serving revision was rolled back: the journaled payload of a
531/// [`crate::record::RunEventKind::RevisionRolledBack`] event, and the
532/// move [`DeploymentPointer::rolled_back`] applies. Byte-exact by
533/// construction: `to` is derived from the chain's transition history —
534/// the immutable revision that served before — so the restored serving
535/// state is a fact about what happened, not a guess at what should.
536#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
537pub struct RevisionRollback {
538    /// The tenant the rollback governs.
539    pub tenant: String,
540
541    /// The environment rolling back.
542    pub environment: EnvironmentTag,
543
544    /// The revision that was serving.
545    pub from: RevisionId,
546
547    /// The previously serving revision, re-derived from the journaled
548    /// transition history (`None`: the environment returns to serving
549    /// nothing — the state before its first promotion).
550    #[serde(default, skip_serializing_if = "Option::is_none")]
551    pub to: Option<RevisionId>,
552
553    /// Why the rollback happened — the operator's note, the incident id.
554    pub cause: String,
555
556    /// Who rolled back (`human:{id}`).
557    pub author: ProvenanceAuthor,
558
559    /// When the rollback journaled.
560    pub rolled_back_at: DateTime<Utc>,
561}
562
563/// The journaled admission resolution (R0.12 wave 3): the output of a
564/// [`crate::record::RunEventKind::DeploymentResolved`] event, journaled
565/// at admission into the run's own journal — the
566/// [`crate::registry::ConfigResolution`] precedent lifted from
567/// configuration to deployments.
568///
569/// The walk it closes: the run's signed receipt commits the journal head;
570/// this event names the environment, the bound `revision_id`, and the
571/// pointer slot; the revision addresses the frozen pin set; the pins name
572/// candidates; the candidates carry their authors and promotions. Every
573/// hop is signature-covered — this event sits inside the journal the
574/// receipt's head signs.
575#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
576pub struct DeploymentResolved {
577    /// The environment the run was admitted to.
578    pub environment: EnvironmentTag,
579
580    /// The revision the environment's pointer bound — reproducible at
581    /// audit from this id alone (revisions are content-addressed: the id
582    /// *is* the integrity check).
583    pub revision_id: RevisionId,
584
585    /// Which pointer slot admitted the revision (the full-traffic
586    /// `active`, or the `canary` when this run's seeded draw admitted).
587    pub pointer: PointerBinding,
588
589    /// The digest of the bound revision's frozen pin set
590    /// ([`pin_set_digest`]) — the pin-set commitment, readable without
591    /// fetching the revision.
592    pub pin_set_digest: String,
593}
594
595// --------------------------------------------------------------------- //
596// Environment-scoped secrets
597// --------------------------------------------------------------------- //
598
599/// The longest an environment-secret name may be. Names ride in scoped
600/// keys (`{name}@{environment}`), journal payloads, and store primary
601/// keys, so a bound keeps a configuration typo from minting an unbounded
602/// key.
603pub const MAX_SECRET_NAME_LEN: usize = 128;
604
605/// The scoped id of an environment secret: `{name}@{environment}` — the
606/// scope is part of the secret's identity, so the staging database URL
607/// and the prod database URL are two secrets that can never be
608/// interchangeable. The sealed envelope authenticates this id as
609/// associated data, so a ciphertext transplanted between scopes fails to
610/// open.
611pub fn scoped_secret_name(name: &str, environment: &EnvironmentTag) -> String {
612    format!("{name}@{environment}")
613}
614
615/// The secret naming rules, enforced at set time: non-empty, bounded
616/// ([`MAX_SECRET_NAME_LEN`]), no leading or trailing whitespace, no
617/// control characters, no `@` (the scope separator — a name carrying it
618/// would make scoped ids ambiguous), and no `/` (the tenant id-prefix
619/// separator). The registry artifact naming rule, applied to secrets.
620pub fn validate_secret_name(name: &str) -> std::result::Result<(), DeployError> {
621    let refuse = |reason: &'static str| DeployError::InvalidSecretName {
622        name: name.to_owned(),
623        reason,
624    };
625    if name.is_empty() {
626        return Err(refuse("empty — a secret exists to be named"));
627    }
628    if name.len() > MAX_SECRET_NAME_LEN {
629        return Err(refuse("over 128 bytes"));
630    }
631    if name != name.trim() {
632        return Err(refuse(
633            "leading or trailing whitespace — visually identical names would be distinct \
634             secrets, which is a misreview waiting to happen",
635        ));
636    }
637    if name.chars().any(|c| c.is_control() || c == '@' || c == '/') {
638        return Err(refuse(
639            "carries a control character, `@`, or `/` — the scope separator and the tenant \
640             separator are structural, and control characters have no business in a key",
641        ));
642    }
643    Ok(())
644}
645
646/// The public record of one environment secret: metadata by
647/// construction, safe to serve and journal. Rotation is replacement
648/// beneath the stable scoped name — what a run's evidence pins is the
649/// scoped name, not the value of the moment (the broker's "rotate a
650/// credential without redeploying" argument applied to static material).
651#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
652pub struct EnvSecretRecord {
653    /// The secret's name within its scope.
654    pub name: String,
655
656    /// The environment the secret is scoped to. Enforcement, not
657    /// convention: resolution serves `name@{environment}` and nothing
658    /// else.
659    pub environment: EnvironmentTag,
660
661    /// Who set (or last rotated) the secret (`human:{id}`).
662    pub set_by: ProvenanceAuthor,
663
664    /// When the secret was first set.
665    pub created_at: DateTime<Utc>,
666
667    /// When the secret was last rotated beneath the stable scoped name.
668    /// Absent when never rotated.
669    #[serde(default, skip_serializing_if = "Option::is_none")]
670    pub rotated_at: Option<DateTime<Utc>>,
671}
672
673/// What both store backends hold for one environment secret: the
674/// metadata record plus the sealed value. Plaintext on neither backend,
675/// ever — a Postgres dump of this row contains no secret (the broker's
676/// custody shape, verbatim).
677#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
678pub struct StoredEnvSecret {
679    /// The metadata record (safe to serve and journal).
680    pub record: EnvSecretRecord,
681
682    /// The sealed value — the broker's envelope construction with the
683    /// scoped secret id as associated data.
684    pub envelope: SealedCredential,
685}
686
687/// A secret was set or rotated: the journaled payload of an
688/// [`crate::record::RunEventKind::EnvSecretSet`] event on the deployment
689/// evidence chain. Metadata only — the bytes live only in the sealed
690/// envelope and can never appear here.
691#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
692pub struct EnvSecretAct {
693    /// The tenant the secret serves.
694    pub tenant: String,
695
696    /// The secret's metadata after the act (`rotated_at` marks a
697    /// rotation beneath the stable scoped name).
698    pub record: EnvSecretRecord,
699}
700
701/// A secret was revoked by deletion: the journaled payload of an
702/// [`crate::record::RunEventKind::EnvSecretRevoked`] event. Deletion is
703/// the only revocation path — there is no disable flag to forget, and
704/// the tombstone is the evidence the scope once held a value.
705#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
706pub struct EnvSecretRevocation {
707    /// The tenant the secret served.
708    pub tenant: String,
709
710    /// The revoked secret's name.
711    pub name: String,
712
713    /// The environment the secret was scoped to.
714    pub environment: EnvironmentTag,
715
716    /// Who revoked it (`human:{id}`).
717    pub revoked_by: ProvenanceAuthor,
718
719    /// When the revocation journaled.
720    pub revoked_at: DateTime<Utc>,
721}
722
723/// A secret resolution was refused on scope: the journaled payload of an
724/// [`crate::record::RunEventKind::EnvSecretDenied`] event — the
725/// [`crate::capsule::CapsuleDenial`] discipline (attributable to a
726/// declaration, not a stack trace) applied to environment scope. Names
727/// the scope requested and the scope the holder holds, because the
728/// difference between the two is exactly what a scope audit reads.
729#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
730pub struct EnvSecretDenial {
731    /// The tenant the request ran under.
732    pub tenant: String,
733
734    /// The secret's name.
735    pub name: String,
736
737    /// The environment scope the request asked for.
738    pub requested_environment: EnvironmentTag,
739
740    /// The environment scope the requester holds — the admission
741    /// environment the resolution runs under.
742    pub held_environment: EnvironmentTag,
743
744    /// When the refusal journaled.
745    pub denied_at: DateTime<Utc>,
746}
747
748// --------------------------------------------------------------------- //
749// Errors
750// --------------------------------------------------------------------- //
751
752/// The deployment plane's typed refusals. A refused declaration, move,
753/// or resolution changes nothing — the [`crate::learn::LearnError`]
754/// discipline: refused operations are contract outcomes surfaced to the
755/// caller, never silent no-ops.
756#[derive(Debug, Clone, PartialEq, Error)]
757pub enum DeployError {
758    /// A revision declaration outside the construction rules.
759    #[error("invalid revision: {reason}")]
760    InvalidRevision {
761        /// The rule it broke.
762        reason: &'static str,
763    },
764
765    /// A pin set naming one surface twice — a set, not a bag.
766    #[error(
767        "pin set names surface `{surface}` twice — a revision pins one candidate per surface; \
768         a second naming is a configuration error, not a second pin"
769    )]
770    DuplicatePin {
771        /// The doubly pinned surface.
772        surface: SurfaceKey,
773    },
774
775    /// A revision's content could not be serialized for addressing —
776    /// unreachable for well-formed content, surfaced rather than
777    /// panicked (the `UndiffableContent` precedent).
778    #[error("revision content could not be addressed: {0}")]
779    UnaddressableContent(String),
780
781    /// A stored revision fails its own content address.
782    #[error(
783        "revision declares id `{declared}` but its content addresses to `{derived}` — \
784         tampered evidence; refused, never served"
785    )]
786    AddressMismatch {
787        /// The id the record carried.
788        declared: RevisionId,
789        /// The id its content derives.
790        derived: RevisionId,
791    },
792
793    /// A canary fraction outside `(0, 1]`.
794    #[error(
795        "canary fraction {fraction} is outside (0, 1] — zero binds nothing (a cleared slot \
796         says that), and above one is not a fraction"
797    )]
798    InvalidFraction {
799        /// The refused fraction.
800        fraction: f64,
801    },
802
803    /// A secret name outside the naming rules (see
804    /// [`validate_secret_name`]).
805    #[error("invalid secret name {name:?}: {reason}")]
806    InvalidSecretName {
807        /// The refused name.
808        name: String,
809        /// The rule it broke.
810        reason: &'static str,
811    },
812}
813
814// --------------------------------------------------------------------- //
815// Wave 4: the release gate
816// --------------------------------------------------------------------- //
817
818/// One gate check, journaled: the core mirror of `rusty-eval`'s
819/// `GateCheck`, serde-mapped at the seam so the runtime never links the
820/// eval crate (the workspace's dependency direction is `rusty-eval` →
821/// runtime, never the reverse — the
822/// [`crate::learn::EvaluationThresholds`] precedent). `metric` is the
823/// eval metric's own serde form (`snake_case`-tagged), carried as a
824/// string so a new eval metric needs no core release to journal.
825#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
826pub struct GateCheckRecord {
827    /// The check's metric, in `rusty-eval`'s serde form.
828    pub metric: String,
829
830    /// Whether the check passed.
831    pub passed: bool,
832
833    /// What the candidate measured.
834    pub observed: Value,
835
836    /// What the policy required.
837    pub required: Value,
838
839    /// The check's explanation — the journaled why, so an audit reads
840    /// the refusal without re-running the gate.
841    pub detail: String,
842}
843
844/// A gate's verdict. Two states and no third: a gate that cannot say
845/// `allow` says `block` — unevaluable comparisons fail closed (the
846/// `ComparisonAvailable` precedent in `rusty-eval`).
847#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
848#[serde(rename_all = "snake_case")]
849pub enum GateVerdict {
850    /// Every check passed; the promotion may proceed.
851    Allow,
852
853    /// At least one check failed — or the gate could not be evaluated;
854    /// the promotion is refused.
855    Block,
856}
857
858/// The gate evaluation the [`RevisionGateEvaluator`] seam returns: the
859/// verdict and every check behind it, naming the policy and dataset
860/// version it ran under. The seam's contract requires the evaluator to
861/// name back the declaration it was handed — an evaluation that cannot
862/// say what it evaluated is not evidence about this promotion.
863#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
864pub struct GateEvaluation {
865    /// The policy the evaluation ran (must equal the declaration's).
866    pub policy: String,
867
868    /// The dataset version the evaluation replayed (must equal the
869    /// declaration's).
870    pub dataset_version: String,
871
872    /// The verdict.
873    pub outcome: GateVerdict,
874
875    /// Every check the verdict stands on.
876    pub checks: Vec<GateCheckRecord>,
877}
878
879impl GateEvaluation {
880    /// Whether the promotion may proceed: the verdict allows **and**
881    /// every check passed. The conjunction is deliberate — a verdict
882    /// and its checks disagreeing is a broken evaluator, and a broken
883    /// evaluator fails closed.
884    pub fn allowed(&self) -> bool {
885        self.outcome == GateVerdict::Allow && self.checks.iter().all(|check| check.passed)
886    }
887}
888
889/// A gate decision, journaled: the payload of a
890/// [`crate::record::RunEventKind::GateDecisionRecorded`] event on the
891/// deployment evidence chain. The decision journals before the pointer
892/// move it governs — and journals when it *refuses*, so the chain holds
893/// the gate's refusals, not only its permissions.
894#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
895pub struct GateDecisionRecord {
896    /// The tenant the decision governs.
897    pub tenant: String,
898
899    /// The gated environment.
900    pub environment: EnvironmentTag,
901
902    /// The revision the gate evaluated.
903    pub revision_id: RevisionId,
904
905    /// The revision the gate compared against — the environment's
906    /// serving revision at decision time (`None`: nothing served, so
907    /// comparative checks ran baseline-less and failed closed where the
908    /// policy needed a comparison).
909    #[serde(default, skip_serializing_if = "Option::is_none")]
910    pub baseline_revision_id: Option<RevisionId>,
911
912    /// The policy the gate ran — the declaration's, echoed.
913    pub policy: String,
914
915    /// The dataset version the gate replayed — the declaration's,
916    /// echoed.
917    pub dataset_version: String,
918
919    /// The verdict.
920    pub outcome: GateVerdict,
921
922    /// Every check the verdict stands on.
923    pub checks: Vec<GateCheckRecord>,
924
925    /// When the gate decided.
926    pub decided_at: DateTime<Utc>,
927}
928
929/// The release-gate seam: core owns the contract, the server composes
930/// the evaluator over `rusty-eval` (the [`crate::learn::CandidateEvaluator`]
931/// precedent — the runtime declares what a gate must answer; the
932/// composition that answers it lives one crate out, where the eval
933/// dependency is allowed).
934///
935/// The contract: `baseline` is the environment's serving revision at
936/// decision time (`None` when nothing serves); the returned evaluation
937/// **must** name `gate.policy` and `gate.dataset_version` back — the
938/// control plane refuses an evaluation that cannot say what it
939/// evaluated. Errors are refusals of the evaluation itself (the dataset
940/// is unreadable, the policy unknown); the control plane fails closed
941/// on one — a gate that could not run is a gate that did not pass.
942#[async_trait]
943pub trait RevisionGateEvaluator: Send + Sync + std::fmt::Debug {
944    /// Evaluate `revision` against `gate`, comparing against `baseline`
945    /// when one serves.
946    async fn evaluate(
947        &self,
948        revision: &DeploymentRevision,
949        baseline: Option<&DeploymentRevision>,
950        gate: &GateDeclaration,
951    ) -> Result<GateEvaluation>;
952}
953
954/// The effect kind a revision promotion is admitted under: distinct
955/// from the learn plane's `candidate_promotion`, because the acts are
956/// distinct — promoting a candidate changes what the registry *points
957/// at*; promoting a revision changes what an environment *serves*.
958pub const REVISION_PROMOTION_EFFECT_KIND: &str = "revision_promotion";
959
960/// The promotion effect id for a revision into an environment: the
961/// approval-token scope for approval-required environments, derived by
962/// the [`crate::learn::promotion_effect_id`] rule over the deployment
963/// surface. Scoped to the revision's own content address, so a token
964/// minted for one revision admits no other — an approval is a fact
965/// about a specific deploy, not a standing permission.
966pub fn revision_promotion_effect_id(
967    environment: &EnvironmentTag,
968    revision: &DeploymentRevision,
969) -> EffectId {
970    derive_effect_id(
971        deployment_surface(environment).as_str(),
972        REVISION_PROMOTION_EFFECT_KIND,
973        revision.revision_id.as_str(),
974        Some(&format!("promotion:{}", revision.revision_id.as_str())),
975    )
976}
977
978// --------------------------------------------------------------------- //
979// Wave 4: canary acts
980// --------------------------------------------------------------------- //
981
982/// A canary was declared on an environment's pointer: the journaled
983/// payload of a [`crate::record::RunEventKind::CanaryDeclared`] event,
984/// and the move [`DeploymentPointer::canaried`] applies. The binding
985/// journals whole — revision and fraction — because the seeded draw an
986/// audit replays is a function of exactly these fields.
987#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
988pub struct CanaryDeclaration {
989    /// The tenant the canary governs.
990    pub tenant: String,
991
992    /// The environment canarying.
993    pub environment: EnvironmentTag,
994
995    /// The canaried revision.
996    pub revision_id: RevisionId,
997
998    /// The fraction of new runs the revision serves.
999    pub fraction: f64,
1000
1001    /// Who declared the canary (`human:{id}`).
1002    pub author: ProvenanceAuthor,
1003
1004    /// When the canary journaled.
1005    pub declared_at: DateTime<Utc>,
1006}
1007
1008/// A canary was cleared without graduating: the journaled payload of a
1009/// [`crate::record::RunEventKind::CanaryCleared`] event, and the move
1010/// [`DeploymentPointer::cleared_canary`] applies. Naming the cleared
1011/// revision is the point — a bare "slot emptied" would leave the
1012/// experiment's end unattributable.
1013#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1014pub struct CanaryClearance {
1015    /// The tenant the clearance governs.
1016    pub tenant: String,
1017
1018    /// The environment clearing its canary.
1019    pub environment: EnvironmentTag,
1020
1021    /// The revision the canary slot held.
1022    pub cleared_revision_id: RevisionId,
1023
1024    /// Who cleared the canary (`human:{id}`).
1025    pub author: ProvenanceAuthor,
1026
1027    /// When the clearance journaled.
1028    pub cleared_at: DateTime<Utc>,
1029}
1030
1031impl DeploymentPointer {
1032    /// The pointer after a canary declaration: the canary slot binds the
1033    /// revision and `active` keeps serving the rest — a canary is an
1034    /// experiment alongside the serving revision, not a move of it.
1035    pub fn canaried(&self, declaration: &CanaryDeclaration) -> DeploymentPointer {
1036        let mut next = self.clone();
1037        next.canary = Some(CanaryDeployment {
1038            revision_id: declaration.revision_id.clone(),
1039            fraction: declaration.fraction,
1040        });
1041        next
1042    }
1043
1044    /// The pointer after a canary clearance: the slot empties and
1045    /// `active` serves everything again.
1046    pub fn cleared_canary(&self) -> DeploymentPointer {
1047        let mut next = self.clone();
1048        next.canary = None;
1049        next
1050    }
1051}
1052
1053// --------------------------------------------------------------------- //
1054// Wave 4: shadow runs
1055// --------------------------------------------------------------------- //
1056
1057/// A shadow run started: the journaled payload of a
1058/// [`crate::record::RunEventKind::ShadowRunStarted`] event in the shadow
1059/// run's own journal. Naming the source run and pinning
1060/// `role: shadow` makes the twin-pair discipline data the journal
1061/// carries: the shadow's evidence names what it shadows, and its role
1062/// can never be confused with the acting twin's.
1063#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1064pub struct ShadowRunStarted {
1065    /// The tenant the shadow runs under.
1066    pub tenant: String,
1067
1068    /// The shadow run's id.
1069    pub shadow_run_id: String,
1070
1071    /// The recorded run this shadow replays.
1072    pub source_run_id: String,
1073
1074    /// The candidate revision under test.
1075    pub revision_id: RevisionId,
1076
1077    /// The decision role — always [`DecisionRole::Shadow`]; pinned in
1078    /// the payload so the discipline survives any caller.
1079    pub role: DecisionRole,
1080
1081    /// Who launched the shadow (`human:{id}`).
1082    pub author: ProvenanceAuthor,
1083
1084    /// When the shadow started.
1085    pub started_at: DateTime<Utc>,
1086}
1087
1088/// How a shadow run ended.
1089#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1090#[serde(rename_all = "snake_case")]
1091pub enum ShadowRunOutcome {
1092    /// The graph ran to completion behind the shadow boundary.
1093    Completed,
1094
1095    /// The run failed — a graph error, not an admission refusal
1096    /// (refusals are the shadow's normal path, journaled as they
1097    /// happen). The verdict still journals: a failed shadow is evidence
1098    /// about the candidate, not a run to sweep away.
1099    Failed {
1100        /// The executor's error, surfaced verbatim.
1101        error: String,
1102    },
1103}
1104
1105/// A shadow run's verdict: the journaled payload of a
1106/// [`crate::record::RunEventKind::ShadowVerdict`] event, and the answer
1107/// the shadow exists to give — what the candidate tried to do to the
1108/// world, what the recorded world served back, and where the candidate
1109/// diverged from the run it shadows.
1110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1111pub struct ShadowVerdict {
1112    /// The tenant the shadow ran under.
1113    pub tenant: String,
1114
1115    /// The shadow run's id.
1116    pub shadow_run_id: String,
1117
1118    /// The recorded run this shadow replayed.
1119    pub source_run_id: String,
1120
1121    /// The candidate revision under test.
1122    pub revision_id: RevisionId,
1123
1124    /// Every effect the boundary refused, journaled served-or-not as it
1125    /// happened — the shadow's reason to exist, verbatim.
1126    pub refusals: Vec<ShadowRefusal>,
1127
1128    /// How many refused calls were served from the recorded world.
1129    pub matched: usize,
1130
1131    /// How many refused calls the recorded world could not serve — the
1132    /// candidate asked for something its source never did.
1133    pub unserved: usize,
1134
1135    /// Recorded effect kinds with calls the candidate never requested —
1136    /// divergence in the other direction, evidence the candidate does
1137    /// *less* than the run it shadows.
1138    pub unrequested: Vec<String>,
1139
1140    /// How the run ended.
1141    pub outcome: ShadowRunOutcome,
1142
1143    /// When the verdict journaled.
1144    pub completed_at: DateTime<Utc>,
1145}
1146
1147// --------------------------------------------------------------------- //
1148// Tests
1149// --------------------------------------------------------------------- //
1150
1151#[cfg(test)]
1152mod tests {
1153    use super::*;
1154    use serde::Serialize;
1155    use std::path::PathBuf;
1156
1157    // ---------- golden-file machinery (the artifact.rs discipline) ----------
1158    //
1159    // Asserted here (unit tests beside the contracts) so the golden
1160    // fixtures under `tests/golden/` pin the new wire shapes without the
1161    // wave touching another test file. `UPDATE_GOLDEN=1` blesses an
1162    // intentional change — the diff is then the contract change under
1163    // review.
1164
1165    fn golden_path(name: &str) -> PathBuf {
1166        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1167            .join("tests")
1168            .join("golden")
1169            .join(name)
1170    }
1171
1172    fn assert_golden(name: &str, value: &impl Serialize) {
1173        let rendered = format!("{}\n", serde_json::to_string_pretty(value).unwrap());
1174        let path = golden_path(name);
1175        if std::env::var_os("UPDATE_GOLDEN").is_some() {
1176            std::fs::write(&path, &rendered).unwrap();
1177            return;
1178        }
1179        let expected = std::fs::read_to_string(&path)
1180            .unwrap_or_else(|e| panic!("missing golden file `{}`: {e}", path.display()));
1181        assert_eq!(
1182            rendered,
1183            expected,
1184            "contract drift in `{}` — if intentional, re-run with UPDATE_GOLDEN=1 \
1185             and review the diff",
1186            path.display()
1187        );
1188    }
1189
1190    fn ts(millis: i64) -> DateTime<Utc> {
1191        DateTime::<Utc>::from_timestamp_millis(millis).unwrap()
1192    }
1193
1194    fn author() -> ProvenanceAuthor {
1195        ProvenanceAuthor::Human {
1196            human_id: "amjad".into(),
1197        }
1198    }
1199
1200    fn tag(name: &str) -> EnvironmentTag {
1201        EnvironmentTag::new(name).unwrap()
1202    }
1203
1204    fn candidate_id(seed: char) -> CandidateId {
1205        CandidateId::from(seed.to_string().repeat(64))
1206    }
1207
1208    fn revision(seed: char) -> DeploymentRevision {
1209        DeploymentRevision::new(
1210            RevisionContent {
1211                graph: "pipeline".into(),
1212                graph_hash: "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
1213                    .into(),
1214                assistant: Some("support-agent".into()),
1215                source_environment: tag("staging"),
1216                pins: vec![
1217                    RegistryPin {
1218                        surface: SurfaceKey::new("model_settings:primary"),
1219                        candidate_id: candidate_id(seed),
1220                    },
1221                    RegistryPin {
1222                        surface: SurfaceKey::new("prompt:system"),
1223                        candidate_id: candidate_id('p'),
1224                    },
1225                ],
1226            },
1227            author(),
1228            ts(1_760_000_000_000),
1229        )
1230        .unwrap()
1231    }
1232
1233    // ---------- construction and identity ----------
1234
1235    #[test]
1236    fn content_addressing_converges_and_ignores_attribution() {
1237        // Identity is integrity: equal declarations converge on one id,
1238        // however they are ordered and whoever registers them — the pin
1239        // set sorts at construction, and the author lives outside the
1240        // address.
1241        let first = revision('a');
1242        let mut shuffled = first.content.clone();
1243        shuffled.pins.reverse();
1244        let second = DeploymentRevision::new(
1245            shuffled,
1246            ProvenanceAuthor::Human {
1247                human_id: "someone-else".into(),
1248            },
1249            ts(1_760_000_999_000),
1250        )
1251        .unwrap();
1252        assert_eq!(first.revision_id, second.revision_id);
1253        assert_ne!(first.author, second.author, "attribution is not identity");
1254        first.verify_address().unwrap();
1255    }
1256
1257    #[test]
1258    fn a_changed_declaration_is_a_new_id() {
1259        let changed = DeploymentRevision::new(
1260            RevisionContent {
1261                graph_hash: "0".repeat(64),
1262                ..revision('a').content
1263            },
1264            author(),
1265            ts(1_760_000_000_000),
1266        )
1267        .unwrap();
1268        assert_ne!(changed.revision_id, revision('a').revision_id);
1269    }
1270
1271    #[test]
1272    fn duplicate_pins_and_empty_graphs_are_refused() {
1273        let dup = DeploymentRevision::new(
1274            RevisionContent {
1275                pins: vec![
1276                    RegistryPin {
1277                        surface: SurfaceKey::new("prompt:system"),
1278                        candidate_id: candidate_id('a'),
1279                    },
1280                    RegistryPin {
1281                        surface: SurfaceKey::new("prompt:system"),
1282                        candidate_id: candidate_id('b'),
1283                    },
1284                ],
1285                ..revision('a').content
1286            },
1287            author(),
1288            ts(1_760_000_000_000),
1289        );
1290        assert!(
1291            matches!(dup, Err(DeployError::DuplicatePin { .. })),
1292            "one surface pins one candidate"
1293        );
1294        let empty = DeploymentRevision::new(
1295            RevisionContent {
1296                graph: String::new(),
1297                ..revision('a').content
1298            },
1299            author(),
1300            ts(1_760_000_000_000),
1301        );
1302        assert!(matches!(empty, Err(DeployError::InvalidRevision { .. })));
1303    }
1304
1305    #[test]
1306    fn verify_address_refuses_tampering() {
1307        let mut tampered = revision('a');
1308        tampered.content.graph_hash = "f".repeat(64);
1309        assert!(matches!(
1310            tampered.verify_address(),
1311            Err(DeployError::AddressMismatch { .. })
1312        ));
1313    }
1314
1315    // ---------- the pointer moves ----------
1316
1317    #[test]
1318    fn promotion_moves_active_and_clears_the_canary() {
1319        let surface = deployment_surface(&tag("prod"));
1320        let mut pointer = DeploymentPointer::new(surface.clone());
1321        pointer.active = Some(RevisionId::from("a".repeat(64)));
1322        pointer.canary =
1323            Some(CanaryDeployment::new(RevisionId::from("b".repeat(64)), 0.1).unwrap());
1324        let promotion = RevisionPromotion {
1325            tenant: "default".into(),
1326            environment: tag("prod"),
1327            revision_id: RevisionId::from("b".repeat(64)),
1328            previous: pointer.active.clone(),
1329            author: author(),
1330            promoted_at: ts(1_760_000_100_000),
1331        };
1332        let moved = pointer.promoted(&promotion);
1333        assert_eq!(moved.active, Some(RevisionId::from("b".repeat(64))));
1334        assert_eq!(
1335            moved.canary, None,
1336            "a full promotion supersedes its experiment"
1337        );
1338    }
1339
1340    #[test]
1341    fn rollback_repoints_byte_exact() {
1342        let surface = deployment_surface(&tag("prod"));
1343        let mut pointer = DeploymentPointer::new(surface);
1344        pointer.active = Some(RevisionId::from("b".repeat(64)));
1345        let rollback = RevisionRollback {
1346            tenant: "default".into(),
1347            environment: tag("prod"),
1348            from: RevisionId::from("b".repeat(64)),
1349            to: Some(RevisionId::from("a".repeat(64))),
1350            cause: "error rate".into(),
1351            author: author(),
1352            rolled_back_at: ts(1_760_000_200_000),
1353        };
1354        let moved = pointer.rolled_back(&rollback);
1355        assert_eq!(
1356            moved.active,
1357            Some(RevisionId::from("a".repeat(64))),
1358            "the restored revision is the one that served, not a reconstruction"
1359        );
1360        // Rolling back a revision the pointer does not serve moves nothing.
1361        let stray = pointer.rolled_back(&RevisionRollback {
1362            from: RevisionId::from("c".repeat(64)),
1363            ..rollback
1364        });
1365        assert_eq!(stray, pointer);
1366    }
1367
1368    #[test]
1369    fn canary_fraction_bounds_are_enforced() {
1370        assert!(CanaryDeployment::new(RevisionId::from("a".repeat(64)), 0.0).is_err());
1371        assert!(CanaryDeployment::new(RevisionId::from("a".repeat(64)), 1.0).is_ok());
1372        assert!(CanaryDeployment::new(RevisionId::from("a".repeat(64)), 1.1).is_err());
1373    }
1374
1375    #[test]
1376    fn the_canary_draw_is_seeded_and_reproducible() {
1377        // A recorded run re-derives its assignment from the pointer alone:
1378        // one draw over the same (surface, revision, run) triple, every
1379        // time; a different surface (staging vs prod) is an independent
1380        // draw.
1381        let revision = RevisionId::from("a".repeat(64));
1382        let mut pointer = DeploymentPointer::new(deployment_surface(&tag("staging")));
1383        pointer.active = Some(RevisionId::from("f".repeat(64)));
1384        pointer.canary = Some(CanaryDeployment::new(revision.clone(), 0.5).unwrap());
1385        let first = deployment_admission(&pointer, "run-1");
1386        let second = deployment_admission(&pointer, "run-1");
1387        assert_eq!(
1388            first, second,
1389            "the draw is a pure function of journaled facts"
1390        );
1391        let prod_pointer =
1392            DeploymentPointer::new(deployment_surface(&tag("prod"))).promoted(&RevisionPromotion {
1393                tenant: "default".into(),
1394                environment: tag("prod"),
1395                revision_id: RevisionId::from("f".repeat(64)),
1396                previous: None,
1397                author: author(),
1398                promoted_at: ts(1_760_000_000_000),
1399            });
1400        let mut prod_with_canary = prod_pointer;
1401        prod_with_canary.canary = Some(CanaryDeployment::new(revision, 0.5).unwrap());
1402        // Not asserting inequality (the draws could coincide); asserting
1403        // the mechanism: both answers come from their own surface's seed.
1404        assert!(deployment_admission(&prod_with_canary, "run-1").is_some());
1405        // A pointer serving nothing binds nothing.
1406        let empty = DeploymentPointer::new(deployment_surface(&tag("dev")));
1407        assert_eq!(deployment_admission(&empty, "run-1"), None);
1408    }
1409
1410    #[test]
1411    fn secret_names_follow_the_registry_naming_rule() {
1412        assert!(validate_secret_name("database-url").is_ok());
1413        assert!(validate_secret_name("").is_err());
1414        assert!(
1415            validate_secret_name("db@prod").is_err(),
1416            "the scope separator is structural"
1417        );
1418        assert!(
1419            validate_secret_name("a/b").is_err(),
1420            "the tenant separator is structural"
1421        );
1422        assert_eq!(
1423            scoped_secret_name("database-url", &tag("staging")),
1424            "database-url@staging"
1425        );
1426    }
1427
1428    // ---------- goldens ----------
1429
1430    #[test]
1431    fn golden_deployment_event_kinds_shape() {
1432        // The plane's additive RunEventKind wire names (the
1433        // `artifact_event_kinds.json` discipline): pinned so no wire
1434        // shape lands unpinned — declared in wire order, appended after
1435        // wave 2's retention acts.
1436        use crate::record::RunEventKind;
1437        assert_golden(
1438            "deployment_event_kinds.json",
1439            &vec![
1440                RunEventKind::DeploymentResolved,
1441                RunEventKind::RevisionRegistered,
1442                RunEventKind::RevisionPromoted,
1443                RunEventKind::RevisionRolledBack,
1444                RunEventKind::EnvironmentDeclared,
1445                RunEventKind::EnvSecretSet,
1446                RunEventKind::EnvSecretRevoked,
1447                RunEventKind::EnvSecretDenied,
1448            ],
1449        );
1450    }
1451
1452    #[test]
1453    fn golden_deployment_revision_shape() {
1454        assert_golden("deployment_revision.json", &revision('a'));
1455    }
1456
1457    #[test]
1458    fn golden_environment_shape() {
1459        let environment = Environment {
1460            name: tag("prod"),
1461            gate: Some(GateDeclaration {
1462                policy: "r0.12-default".into(),
1463                dataset_version: "support-v3".into(),
1464            }),
1465            approval_required: true,
1466            created_by: author(),
1467            created_at: ts(1_760_000_000_000),
1468        };
1469        assert_golden("environment.json", &environment);
1470    }
1471
1472    #[test]
1473    fn golden_deployment_pointer_shape() {
1474        // The full shape: both slots bound — active plus a 10% canary.
1475        let mut pointer = DeploymentPointer::new(deployment_surface(&tag("staging")));
1476        pointer.active = Some(RevisionId::from("a".repeat(64)));
1477        pointer.canary =
1478            Some(CanaryDeployment::new(RevisionId::from("b".repeat(64)), 0.1).unwrap());
1479        assert_golden("deployment_pointer.json", &pointer);
1480    }
1481
1482    #[test]
1483    fn golden_deployment_resolved_shape() {
1484        // The journaled resolution: a run admitted to staging under the
1485        // canary slot, naming the bound revision and the pin-set digest.
1486        let resolved = DeploymentResolved {
1487            environment: tag("staging"),
1488            revision_id: revision('a').revision_id,
1489            pointer: PointerBinding::Canary,
1490            pin_set_digest: pin_set_digest(&revision('a').content.pins),
1491        };
1492        assert_golden("deployment_resolved.json", &resolved);
1493    }
1494
1495    #[test]
1496    fn golden_revision_registration_shape() {
1497        assert_golden(
1498            "revision_registration.json",
1499            &RevisionRegistration {
1500                tenant: "default".into(),
1501                revision: revision('a'),
1502            },
1503        );
1504    }
1505
1506    #[test]
1507    fn golden_environment_declaration_shape() {
1508        assert_golden(
1509            "environment_declaration.json",
1510            &EnvironmentDeclaration {
1511                tenant: "default".into(),
1512                environment: Environment {
1513                    name: tag("dev"),
1514                    gate: None,
1515                    approval_required: false,
1516                    created_by: author(),
1517                    created_at: ts(1_760_000_000_000),
1518                },
1519            },
1520        );
1521    }
1522
1523    #[test]
1524    fn golden_revision_promotion_shape() {
1525        assert_golden(
1526            "revision_promotion.json",
1527            &RevisionPromotion {
1528                tenant: "default".into(),
1529                environment: tag("prod"),
1530                revision_id: revision('a').revision_id,
1531                previous: Some(RevisionId::from("f".repeat(64))),
1532                author: author(),
1533                promoted_at: ts(1_760_000_100_000),
1534            },
1535        );
1536    }
1537
1538    #[test]
1539    fn golden_revision_rollback_shape() {
1540        assert_golden(
1541            "revision_rollback.json",
1542            &RevisionRollback {
1543                tenant: "default".into(),
1544                environment: tag("prod"),
1545                from: revision('a').revision_id,
1546                to: Some(RevisionId::from("f".repeat(64))),
1547                cause: "canary regression".into(),
1548                author: author(),
1549                rolled_back_at: ts(1_760_000_200_000),
1550            },
1551        );
1552    }
1553
1554    #[test]
1555    fn golden_env_secret_record_shape() {
1556        assert_golden(
1557            "env_secret_record.json",
1558            &EnvSecretRecord {
1559                name: "database-url".into(),
1560                environment: tag("staging"),
1561                set_by: author(),
1562                created_at: ts(1_760_000_000_000),
1563                rotated_at: Some(ts(1_760_000_500_000)),
1564            },
1565        );
1566    }
1567
1568    #[test]
1569    fn golden_stored_env_secret_shape() {
1570        // The custody shape: metadata plus the sealed envelope — hex
1571        // ciphertext fields, never bytes (fixed vectors pin the wire).
1572        assert_golden(
1573            "stored_env_secret.json",
1574            &StoredEnvSecret {
1575                record: EnvSecretRecord {
1576                    name: "database-url".into(),
1577                    environment: tag("prod"),
1578                    set_by: author(),
1579                    created_at: ts(1_760_000_000_000),
1580                    rotated_at: None,
1581                },
1582                envelope: SealedCredential {
1583                    format_version: 1,
1584                    key_id: "esk-0123456789abcdef".into(),
1585                    wrapped_data_key: "aa".repeat(48),
1586                    wrap_nonce: "bb".repeat(24),
1587                    nonce: "cc".repeat(24),
1588                    ciphertext: "dd".repeat(80),
1589                    sealed_at: ts(1_760_000_000_000),
1590                },
1591            },
1592        );
1593    }
1594
1595    #[test]
1596    fn golden_env_secret_denial_shape() {
1597        assert_golden(
1598            "env_secret_denial.json",
1599            &EnvSecretDenial {
1600                tenant: "default".into(),
1601                name: "database-url".into(),
1602                requested_environment: tag("prod"),
1603                held_environment: tag("staging"),
1604                denied_at: ts(1_760_000_300_000),
1605            },
1606        );
1607    }
1608
1609    // ---------- wave 4: gates, canary acts, shadows ----------
1610
1611    fn gate_evaluation(outcome: GateVerdict, checks: Vec<GateCheckRecord>) -> GateEvaluation {
1612        GateEvaluation {
1613            policy: "r0.12-default".into(),
1614            dataset_version: "support-v3".into(),
1615            outcome,
1616            checks,
1617        }
1618    }
1619
1620    fn passing_check() -> GateCheckRecord {
1621        GateCheckRecord {
1622            metric: "\"pass_rate\"".into(),
1623            passed: true,
1624            observed: serde_json::json!(0.91),
1625            required: serde_json::json!(0.85),
1626            detail: "pass rate clears the floor".into(),
1627        }
1628    }
1629
1630    #[test]
1631    fn the_gate_allows_only_when_verdict_and_every_check_agree() {
1632        // Fail-closed twice over: a blocked verdict refuses however the
1633        // checks read, and an allow verdict with one failing check
1634        // refuses too — a verdict and its checks disagreeing is a broken
1635        // evaluator, and a broken evaluator does not ship revisions.
1636        assert!(gate_evaluation(GateVerdict::Allow, vec![passing_check()]).allowed());
1637        assert!(!gate_evaluation(GateVerdict::Block, vec![passing_check()]).allowed());
1638        let mut failing = passing_check();
1639        failing.passed = false;
1640        assert!(!gate_evaluation(GateVerdict::Allow, vec![passing_check(), failing]).allowed());
1641    }
1642
1643    #[test]
1644    fn canary_moves_keep_the_active_revision_serving() {
1645        // Declare: the canary slot binds, active keeps serving the rest.
1646        // Clear: the slot empties, active is untouched. Promotion still
1647        // supersedes the experiment it graduated from (wave 3 semantics,
1648        // unchanged).
1649        let pointer = DeploymentPointer {
1650            canary: None,
1651            ..DeploymentPointer::new(deployment_surface(&tag("staging")))
1652        };
1653        let declaration = CanaryDeclaration {
1654            tenant: "default".into(),
1655            environment: tag("staging"),
1656            revision_id: revision('b').revision_id.clone(),
1657            fraction: 0.1,
1658            author: author(),
1659            declared_at: ts(1_760_000_100_000),
1660        };
1661        let canaried = pointer.canaried(&declaration);
1662        assert_eq!(
1663            canaried.canary,
1664            Some(CanaryDeployment {
1665                revision_id: revision('b').revision_id.clone(),
1666                fraction: 0.1,
1667            })
1668        );
1669        assert_eq!(
1670            canaried.active, pointer.active,
1671            "a canary moves nothing serving"
1672        );
1673        let cleared = canaried.cleared_canary();
1674        assert_eq!(cleared, pointer, "clearing restores the pre-canary pointer");
1675    }
1676
1677    #[test]
1678    fn the_revision_promotion_effect_id_is_scoped_to_the_revision() {
1679        // Deterministic for one revision into one environment; different
1680        // for any other revision or any other environment — a token
1681        // minted for this deploy admits no other.
1682        let rev = revision('a');
1683        let staging = tag("staging");
1684        let id = revision_promotion_effect_id(&staging, &rev);
1685        assert_eq!(id, revision_promotion_effect_id(&staging, &rev));
1686        assert_ne!(
1687            id,
1688            revision_promotion_effect_id(&staging, &revision('b')),
1689            "another revision is another approval"
1690        );
1691        assert_ne!(
1692            id,
1693            revision_promotion_effect_id(&tag("prod"), &rev),
1694            "another environment is another approval"
1695        );
1696    }
1697
1698    fn gate_decision_record() -> GateDecisionRecord {
1699        GateDecisionRecord {
1700            tenant: "default".into(),
1701            environment: tag("staging"),
1702            revision_id: revision('b').revision_id.clone(),
1703            baseline_revision_id: Some(revision('a').revision_id.clone()),
1704            policy: "r0.12-default".into(),
1705            dataset_version: "support-v3".into(),
1706            outcome: GateVerdict::Allow,
1707            checks: vec![passing_check()],
1708            decided_at: ts(1_760_000_200_000),
1709        }
1710    }
1711
1712    fn shadow_refusal() -> ShadowRefusal {
1713        ShadowRefusal {
1714            kind: "charge".into(),
1715            effect: crate::record::Effect::NonIdempotent,
1716            effect_id: derive_effect_id(
1717                "shadow-run-1",
1718                "charge",
1719                &sha256_hex(b"{\"tool\":\"charge\"}"),
1720                Some("shadow-run-1:7"),
1721            ),
1722            input_hash: sha256_hex(b"{\"tool\":\"charge\"}"),
1723            served: true,
1724        }
1725    }
1726
1727    #[test]
1728    fn golden_gate_event_kinds_shape() {
1729        // Wave 4's additive RunEventKind wire names, pinned beside wave
1730        // 3's (`deployment_event_kinds.json`) — appended after
1731        // `EnvSecretDenied`, in wire order.
1732        use crate::record::RunEventKind;
1733        assert_golden(
1734            "deployment_gate_event_kinds.json",
1735            &vec![
1736                RunEventKind::GateDecisionRecorded,
1737                RunEventKind::CanaryDeclared,
1738                RunEventKind::CanaryCleared,
1739                RunEventKind::ShadowRunStarted,
1740                RunEventKind::ShadowEffectRefused,
1741                RunEventKind::ShadowVerdict,
1742            ],
1743        );
1744    }
1745
1746    #[test]
1747    fn golden_gate_decision_record_shape() {
1748        assert_golden("gate_decision_record.json", &gate_decision_record());
1749    }
1750
1751    #[test]
1752    fn golden_canary_declaration_shape() {
1753        assert_golden(
1754            "canary_declaration.json",
1755            &CanaryDeclaration {
1756                tenant: "default".into(),
1757                environment: tag("staging"),
1758                revision_id: revision('b').revision_id.clone(),
1759                fraction: 0.1,
1760                author: author(),
1761                declared_at: ts(1_760_000_100_000),
1762            },
1763        );
1764    }
1765
1766    #[test]
1767    fn golden_canary_clearance_shape() {
1768        assert_golden(
1769            "canary_clearance.json",
1770            &CanaryClearance {
1771                tenant: "default".into(),
1772                environment: tag("staging"),
1773                cleared_revision_id: revision('b').revision_id.clone(),
1774                author: author(),
1775                cleared_at: ts(1_760_000_400_000),
1776            },
1777        );
1778    }
1779
1780    #[test]
1781    fn golden_shadow_run_started_shape() {
1782        assert_golden(
1783            "shadow_run_started.json",
1784            &ShadowRunStarted {
1785                tenant: "default".into(),
1786                shadow_run_id: "shadow-run-1-abcdef123456-7f3a".into(),
1787                source_run_id: "run-1".into(),
1788                revision_id: revision('b').revision_id.clone(),
1789                role: DecisionRole::Shadow,
1790                author: author(),
1791                started_at: ts(1_760_000_500_000),
1792            },
1793        );
1794    }
1795
1796    #[test]
1797    fn golden_shadow_effect_refusal_shape() {
1798        assert_golden("shadow_effect_refusal.json", &shadow_refusal());
1799    }
1800
1801    #[test]
1802    fn golden_shadow_verdict_shape() {
1803        assert_golden(
1804            "shadow_verdict.json",
1805            &ShadowVerdict {
1806                tenant: "default".into(),
1807                shadow_run_id: "shadow-run-1-abcdef123456-7f3a".into(),
1808                source_run_id: "run-1".into(),
1809                revision_id: revision('b').revision_id.clone(),
1810                refusals: vec![shadow_refusal()],
1811                matched: 1,
1812                unserved: 0,
1813                unrequested: vec!["lookup".into()],
1814                outcome: ShadowRunOutcome::Completed,
1815                completed_at: ts(1_760_000_600_000),
1816            },
1817        );
1818    }
1819}