rusty_agent_runtime/artifact.rs
1//! The run artifact plane (R0.12 Operations Plane, wave 1): the records
2//! that make a run's binary outputs operable — content-addressed,
3//! lineage-carrying, retainable — plus the journaled commitment that
4//! binds each one back into the run's evidence.
5//!
6//! Two artifact concepts share one word in this codebase, and the type
7//! system keeps them apart. Registry artifacts
8//! ([`crate::registry::ArtifactRecord`]) are human-authored *configuration*:
9//! a commit is a candidate, governance is the learn pipeline, the bytes
10//! are small and diffed. [`RunArtifact`] records are run-produced
11//! *outputs*: generated files, images, audio, exported datasets. A run
12//! artifact is not a candidate, has no promotion lifecycle, and is never
13//! diffed; its governance is lineage, permissions, and retention. The
14//! server surface is `/artifacts`, deliberately distinct from
15//! `/registry/artifacts`, so the route grammar itself says which concept
16//! a caller addresses.
17//!
18//! The record is deliberately thin because the bytes and the evidence
19//! already have homes:
20//!
21//! - **Identity is integrity.** `artifact_id` is the lowercase hex
22//! SHA-256 of the bytes — exactly the [`crate::record::ArtifactRef`]
23//! rule, so a run artifact's address is the same digest the journal
24//! already stamps for spilled payloads. Two runs producing
25//! byte-identical outputs share one object, and a read re-hashes
26//! before it serves: a store that cannot prove its bytes is
27//! corruption, not data.
28//! - **Lineage is what makes the plane evidence.** The journal already
29//! records the producing effect with its class, latency, and causal
30//! parentage, but nothing connected that effect to the file that
31//! outlived the run. [`ArtifactLineage`] is that join: the producing
32//! run id, the deterministic [`EffectId`] of the producing effect
33//! (re-derivable at audit through
34//! [`derive_effect_id`](crate::effects::derive_effect_id) — no new
35//! identity minting), and the journal event id whose output carried
36//! the reference. Recorded at commit, never edited.
37//! - **The journal carries commitments, never bytes.** One additive
38//! [`RunEventKind::ArtifactCommitted`](crate::record::RunEventKind::ArtifactCommitted)
39//! event, payload [`ArtifactCommitment`], sits in the run's own
40//! journal, so the signed receipt's head covers it transitively: the
41//! audit walk is signed receipt → journal head → `ArtifactCommitted` →
42//! `EffectId` → the effect's journaled record → the bytes behind the
43//! address. Run artifacts are arbitrary bytes, potentially hundreds of
44//! megabytes; they do not belong in snapshots, so the journal records
45//! the reference and the commitment and the plane carries the rest.
46//!
47//! Wave 1 shipped the base record and the commit path; wave 2 grows the
48//! plane's governance, all additively:
49//!
50//! - **Version accumulation** ([`append_artifact_version`]): a commit
51//! naming an already-taken name joins its sequence — the `versions`
52//! slot the wire shape carried from the first record, so accumulation
53//! is an append, never a shape change. Each version stays its own
54//! record under its own address; older versions serve by address with
55//! the sequence prefix they were committed under.
56//! - **Previews** ([`derive_preview`]): derived on read, *never* stored
57//! — the `RegistryDiff` precedent. A stored preview is a second,
58//! divergent account of the same bytes; a kind that cannot be derived
59//! is an honest empty answer, not a placeholder.
60//! - **The retention acts** ([`ArtifactPrune`], [`ArtifactRelease`],
61//! [`ArtifactUnavailability`]): the sweeper's journaled intention
62//! (before any byte moves — a crash mid-sweep leaves intentions
63//! auditable), the operator's release — the *only* path that prunes a
64//! receipt-pinned or `pinned` address, because shortening evidence
65//! retention is a governance decision with a name on it, never
66//! housekeeping — and the typed miss, journaled so "the record exists,
67//! the bytes do not" reads differently from "no such artifact" in
68//! exactly the way a retention audit needs.
69
70use chrono::{DateTime, Utc};
71use serde::{Deserialize, Serialize};
72use thiserror::Error;
73
74use crate::effects::EffectId;
75use crate::record::ArtifactRef;
76use crate::registry::MAX_ARTIFACT_NAME_LEN;
77
78// --------------------------------------------------------------------- //
79// Media and retention — the closed enums
80// --------------------------------------------------------------------- //
81
82/// The artifact's media class: a closed, additively-evolved enum that
83/// drives preview eligibility (Wave 2). The producer's declared media
84/// *type* string travels beside it
85/// ([`RunArtifact::media_type`]), preserved verbatim because the runtime
86/// cannot certify a producer's claim, only record it.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
88#[serde(rename_all = "snake_case")]
89pub enum MediaKind {
90 /// A generic file (text, JSON, binary without a richer class).
91 File,
92 /// A still image.
93 Image,
94 /// An audio recording.
95 Audio,
96 /// An exported dataset (rows, tables, archives of records).
97 Data,
98}
99
100/// How long the bytes behind an artifact live. Declared at commit and
101/// journaled with it; a change that would shorten live retention is a
102/// governance act (Wave 2's journaled release), never housekeeping.
103///
104/// The default is [`RetentionPolicy::ReceiptBound`]: a signed receipt
105/// commits to a journal head whose events name content addresses, and
106/// pruning bytes an unexpired receipt still names would falsify the
107/// receipt's *usefulness* — the chain verifies over events and survives,
108/// but "the run produced `sha256:abc…`" is cold comfort when `abc…` was
109/// swept. Retain-at-least-as-long-as-the-receipt is the stance that
110/// keeps evidence whole.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
112#[serde(tag = "policy", rename_all = "snake_case")]
113pub enum RetentionPolicy {
114 /// Retain until an operator explicitly releases the pin (a journaled
115 /// act, Wave 2).
116 Pinned,
117 /// Retain for at least this many days from commit.
118 Days {
119 /// The retention window, in whole days.
120 days: u32,
121 },
122 /// Retain at least as long as any signed receipt whose journal
123 /// references the address (the default).
124 #[default]
125 ReceiptBound,
126}
127
128// --------------------------------------------------------------------- //
129// Versions and lineage
130// --------------------------------------------------------------------- //
131
132/// One entry in a named artifact's version sequence: the
133/// [`crate::registry::ArtifactCommit`] discipline (append-only,
134/// content-addressed) applied to bytes. The current version is the
135/// last; older versions are addresses, retained under the same policy.
136///
137/// Wave 1 commits write exactly one entry — the committed object itself
138/// — so the slot exists on the wire from the first record and version
139/// accumulation (Wave 2) lands as appends, not a shape change.
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141pub struct ArtifactVersion {
142 /// The version's content address (lowercase hex SHA-256 of its
143 /// bytes).
144 pub sha256: String,
145
146 /// The version's size in bytes.
147 pub bytes: u64,
148
149 /// When this version joined the sequence.
150 pub committed_at: DateTime<Utc>,
151}
152
153/// The join that makes the plane evidence: where these bytes came from.
154/// Recorded at commit, never edited — a later act (a retention release,
155/// a sweep) journals its own event rather than rewriting the lineage.
156#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
157pub struct ArtifactLineage {
158 /// The run that produced the artifact.
159 pub run_id: String,
160
161 /// The deterministic [`EffectId`] of the producing effect —
162 /// re-derivable at audit from the journaled scope, kind, input hash,
163 /// and key, so the lineage anchor needs no new identity minting.
164 pub effect_id: EffectId,
165
166 /// The journal event id whose output carried the reference to these
167 /// bytes (the node output that spilled, or the event the declaring
168 /// node parents its commitment to).
169 pub event_id: String,
170}
171
172// --------------------------------------------------------------------- //
173// The record
174// --------------------------------------------------------------------- //
175
176/// A run-produced output made operable: the plane's only persisted
177/// entity.
178///
179/// Keyed by content address (`artifact_id`), tenant-scoped at the
180/// metadata layer. Bytes are deliberately *not* tenant-namespaced —
181/// content addressing makes byte storage global (two tenants producing
182/// identical bytes share one object) — and the metadata layer is the
183/// only path that lists or resolves, so a shared address grants no
184/// cross-tenant read path.
185#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
186pub struct RunArtifact {
187 /// The content address: lowercase hex SHA-256 of the bytes, exactly
188 /// the [`ArtifactRef`] rule. Identity is integrity.
189 pub artifact_id: String,
190
191 /// The logical name (`weekly-report`) versions accumulate under, or
192 /// `None` for an address-only artifact: produced, referenced,
193 /// retained, expired. The naming rules are the registry's
194 /// ([`MAX_ARTIFACT_NAME_LEN`], no `@`, no `/`, no control
195 /// characters), for the same reason: names ride in keys that tenant
196 /// prefixes and environment tags already punctuate. Absent from the
197 /// wire when unnamed — an address-only artifact carries no
198 /// placeholder.
199 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub name: Option<String>,
201
202 /// The media class (drives preview eligibility, Wave 2).
203 pub media_kind: MediaKind,
204
205 /// The producer-declared media type (`image/png`,
206 /// `text/csv`), preserved verbatim: the runtime records the claim,
207 /// it cannot certify it. Absent when the producer declared none.
208 #[serde(default, skip_serializing_if = "Option::is_none")]
209 pub media_type: Option<String>,
210
211 /// Where these bytes came from (run, effect, event). Recorded at
212 /// commit, never edited.
213 pub lineage: ArtifactLineage,
214
215 /// The name's version sequence, oldest first, append-only — present
216 /// exactly for named artifacts. Wave 1 writes one entry (the
217 /// committed object itself); Wave 2's accumulation appends.
218 #[serde(default, skip_serializing_if = "Vec::is_empty")]
219 pub versions: Vec<ArtifactVersion>,
220
221 /// The declared retention. Journaled with the commit; shortening it
222 /// later is a governance act, not housekeeping.
223 pub retention: RetentionPolicy,
224
225 /// When the artifact was committed.
226 pub created_at: DateTime<Utc>,
227}
228
229/// The journaled half of a commit: the output payload of one
230/// [`RunEventKind::ArtifactCommitted`](crate::record::RunEventKind::ArtifactCommitted)
231/// event in the producing run's own journal.
232///
233/// The event is the commitment, and it is what the signed receipt's head
234/// covers — the bytes never enter the journal, so the payload names
235/// everything an auditor needs to walk from the receipt to the bytes:
236/// the address, the name and version index when named, the media kind,
237/// the byte count, the producing [`EffectId`], and the declared
238/// retention. Built together with the [`RunArtifact`] record by
239/// [`commit_artifact`]: one derivation, two homes, so the journaled
240/// commitment and the stored record can never diverge.
241#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
242pub struct ArtifactCommitment {
243 /// The content address (the record's `artifact_id`).
244 pub artifact_id: String,
245
246 /// The logical name, when the artifact is named.
247 #[serde(default, skip_serializing_if = "Option::is_none")]
248 pub name: Option<String>,
249
250 /// The version index this commit appended — present exactly when
251 /// the artifact is named (the sequence position of the new head; `0`
252 /// for the first version).
253 #[serde(default, skip_serializing_if = "Option::is_none")]
254 pub version: Option<u64>,
255
256 /// The media class.
257 pub media_kind: MediaKind,
258
259 /// The byte count (the [`ArtifactRef::bytes`] rule).
260 pub bytes: u64,
261
262 /// The producing effect's deterministic id.
263 pub effect_id: EffectId,
264
265 /// The retention declared at commit.
266 pub retention: RetentionPolicy,
267}
268
269// --------------------------------------------------------------------- //
270// The commit constructor
271// --------------------------------------------------------------------- //
272
273/// What a commit declares: everything the record and the journaled
274/// commitment need, from whichever source the bytes arrived (an
275/// SDK-declared output, or a journaled [`crate::record::PayloadRef::Artifact`]
276/// the producing node opted into). Both paths build through
277/// [`commit_artifact`], which is what makes "both write the same record
278/// shape and journal the same event" structural rather than
279/// conventional.
280#[derive(Debug, Clone)]
281pub struct CommitDeclaration {
282 /// The content address and size of the committed bytes, as the byte
283 /// store minted them.
284 pub reference: ArtifactRef,
285
286 /// The logical name versions accumulate under, when named.
287 pub name: Option<String>,
288
289 /// The media class.
290 pub media_kind: MediaKind,
291
292 /// The producer-declared media type string, when asserted.
293 pub media_type: Option<String>,
294
295 /// The producing run, effect, and journal event.
296 pub lineage: ArtifactLineage,
297
298 /// The declared retention (defaults to
299 /// [`RetentionPolicy::ReceiptBound`] at the call sites, which is why
300 /// this is not an `Option`).
301 pub retention: RetentionPolicy,
302
303 /// When the commit happened.
304 pub committed_at: DateTime<Utc>,
305}
306
307/// Build the record and the journaled commitment for one commit — the
308/// single constructor both commit paths share. Wave 1 writes the base
309/// version sequence (one entry, index `0`); the append path that grows
310/// it is Wave 2's.
311///
312/// Refusals are typed ([`ArtifactError`]) and change nothing: the
313/// naming rules keep names route-addressable and unambiguous under
314/// tagging and tenant prefixing, and the address rule keeps identity
315/// honest — a commit over a malformed address would mint a record the
316/// byte store can never verify.
317pub fn commit_artifact(
318 declaration: CommitDeclaration,
319) -> Result<(RunArtifact, ArtifactCommitment), ArtifactError> {
320 validate_artifact_address(&declaration.reference.sha256)?;
321 if let Some(name) = &declaration.name {
322 validate_artifact_name(name)?;
323 }
324 let version = declaration.name.as_ref().map(|_| ArtifactVersion {
325 sha256: declaration.reference.sha256.clone(),
326 bytes: declaration.reference.bytes,
327 committed_at: declaration.committed_at,
328 });
329 let record = RunArtifact {
330 artifact_id: declaration.reference.sha256.clone(),
331 name: declaration.name.clone(),
332 media_kind: declaration.media_kind,
333 media_type: declaration.media_type.clone(),
334 lineage: declaration.lineage,
335 versions: version.into_iter().collect(),
336 retention: declaration.retention,
337 created_at: declaration.committed_at,
338 };
339 let commitment = ArtifactCommitment {
340 artifact_id: declaration.reference.sha256,
341 name: declaration.name,
342 version: record
343 .versions
344 .len()
345 .checked_sub(1)
346 .map(|index| index as u64),
347 media_kind: declaration.media_kind,
348 bytes: declaration.reference.bytes,
349 effect_id: record.lineage.effect_id.clone(),
350 retention: declaration.retention,
351 };
352 Ok((record, commitment))
353}
354
355/// Build the record and the journaled commitment for a commit that
356/// joins an existing name's version sequence (wave 2): the new head
357/// record carries the prior sequence plus the new entry, and the
358/// commitment names the appended index. Wave 1 answered this commit
359/// with `409`; the sequence the wire shape carried from the first
360/// record is what makes accumulation an append, not a migration.
361///
362/// Each version remains its own record under its own address — the
363/// prior head's file is never edited (records are written once), so an
364/// older version keeps serving by address with the sequence prefix it
365/// was committed under. The name index re-points at the new head; the
366/// history route reads the head's full sequence.
367///
368/// The same refusals as [`commit_artifact`] apply, plus
369/// [`ArtifactError::VersionMismatch`] when the declaration does not
370/// belong to `head`'s sequence — a version joins the sequence its name
371/// owns, never another's.
372pub fn append_artifact_version(
373 head: &RunArtifact,
374 declaration: CommitDeclaration,
375) -> Result<(RunArtifact, ArtifactCommitment), ArtifactError> {
376 validate_artifact_address(&declaration.reference.sha256)?;
377 let Some(head_name) = &head.name else {
378 return Err(ArtifactError::VersionMismatch {
379 reason: "the sequence head is unnamed — versions accumulate under a name; an \
380 address-only artifact has no sequence to join",
381 });
382 };
383 match &declaration.name {
384 Some(name) if name == head_name => validate_artifact_name(name)?,
385 _ => {
386 return Err(ArtifactError::VersionMismatch {
387 reason: "the declaration's name is not the sequence head's — a version \
388 joins the sequence its name owns",
389 })
390 }
391 }
392 let mut versions = head.versions.clone();
393 versions.push(ArtifactVersion {
394 sha256: declaration.reference.sha256.clone(),
395 bytes: declaration.reference.bytes,
396 committed_at: declaration.committed_at,
397 });
398 let record = RunArtifact {
399 artifact_id: declaration.reference.sha256.clone(),
400 name: head.name.clone(),
401 media_kind: declaration.media_kind,
402 media_type: declaration.media_type.clone(),
403 lineage: declaration.lineage,
404 versions,
405 retention: declaration.retention,
406 created_at: declaration.committed_at,
407 };
408 let commitment = ArtifactCommitment {
409 artifact_id: declaration.reference.sha256,
410 name: head.name.clone(),
411 version: record
412 .versions
413 .len()
414 .checked_sub(1)
415 .map(|index| index as u64),
416 media_kind: declaration.media_kind,
417 bytes: declaration.reference.bytes,
418 effect_id: record.lineage.effect_id.clone(),
419 retention: declaration.retention,
420 };
421 Ok((record, commitment))
422}
423
424/// The artifact naming rules, enforced at commit: non-empty, bounded
425/// ([`MAX_ARTIFACT_NAME_LEN`]), no leading or trailing whitespace, no
426/// control characters, no `@` (the environment-tag separator), and no
427/// `/` (the tenant id-prefix separator). The registry's rules verbatim
428/// ([`crate::registry::ArtifactRecord::new`]), re-stated here because a
429/// run artifact's name rides the same keys: tenant prefixes and
430/// environment tags punctuate both, and a name that escapes one grammar
431/// escapes the other.
432fn validate_artifact_name(name: &str) -> Result<(), ArtifactError> {
433 let refuse = |reason: &'static str| ArtifactError::InvalidName {
434 name: name.to_owned(),
435 reason,
436 };
437 if name.is_empty() {
438 return Err(refuse("empty — an artifact exists to be named"));
439 }
440 if name.len() > MAX_ARTIFACT_NAME_LEN {
441 return Err(refuse("over 128 bytes"));
442 }
443 if name != name.trim() {
444 return Err(refuse(
445 "leading or trailing whitespace — visually identical names would be distinct \
446 artifacts, which is a misreview waiting to happen",
447 ));
448 }
449 if name.chars().any(|c| c.is_control() || c == '@' || c == '/') {
450 return Err(refuse(
451 "carries a control character, `@`, or `/` — the tag separator and the tenant \
452 separator are structural, and control characters have no business in a key",
453 ));
454 }
455 Ok(())
456}
457
458/// The address rule: 64 lowercase hex characters — the exact shape
459/// [`crate::record::sha256_hex`] mints. Anything else is not a content
460/// address this plane can verify, so it is refused at commit rather than
461/// discovered at read.
462fn validate_artifact_address(address: &str) -> Result<(), ArtifactError> {
463 if address.len() == 64
464 && address
465 .chars()
466 .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
467 {
468 return Ok(());
469 }
470 Err(ArtifactError::InvalidAddress {
471 address: address.to_owned(),
472 reason: "not 64 lowercase hex characters — the `sha256_hex` shape; identity is \
473 integrity, and an address outside the rule can never re-hash to itself",
474 })
475}
476
477// --------------------------------------------------------------------- //
478// The retention acts (wave 2): the payloads the deployment's artifact
479// evidence chain journals
480// --------------------------------------------------------------------- //
481
482/// Why the sweeper pruned an address. The cause is part of the evidence:
483/// a retention audit reads *which* rule fired, not just that bytes left.
484#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
485#[serde(rename_all = "snake_case")]
486pub enum PruneCause {
487 /// A `days(n)` policy elapsed and no verified signed receipt covered
488 /// the address.
489 Expired,
490 /// A `receipt_bound` policy found no receipt to be bound to.
491 Unbound,
492 /// Every remaining pin on the address was a released one.
493 Released,
494}
495
496/// The journaled half of a sweep prune: the output payload of one
497/// [`RunEventKind::ArtifactPruned`](crate::record::RunEventKind::ArtifactPruned)
498/// event on the deployment's artifact evidence chain. Journaled *before*
499/// the bytes are deleted, so a crash mid-sweep leaves the intention
500/// auditable and the bytes recoverable — the scan-and-prune step can
501/// never leave a deletion nothing recorded.
502#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
503pub struct ArtifactPrune {
504 /// The pruned content address.
505 pub artifact_id: String,
506
507 /// The logical name, when the pruned record was named.
508 #[serde(default, skip_serializing_if = "Option::is_none")]
509 pub name: Option<String>,
510
511 /// Which retention rule fired.
512 pub cause: PruneCause,
513
514 /// When the sweep journaled the intention.
515 pub swept_at: DateTime<Utc>,
516}
517
518/// The journaled half of the retention-release act: the output payload
519/// of one
520/// [`RunEventKind::ArtifactRetentionReleased`](crate::record::RunEventKind::ArtifactRetentionReleased)
521/// event on the deployment's artifact evidence chain. The release is the
522/// *only* path that prunes an address a live signed receipt covers or a
523/// `pinned` policy holds — shortening evidence retention is a governance
524/// decision with a name on it, so the act carries the operator's
525/// identity and journals before any byte moves.
526#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
527pub struct ArtifactRelease {
528 /// The released content address.
529 pub artifact_id: String,
530
531 /// The tenant whose record held the pin (the chain is
532 /// deployment-wide; the tenant is audit metadata, not scoping).
533 pub tenant: String,
534
535 /// The logical name, when the released record was named.
536 #[serde(default, skip_serializing_if = "Option::is_none")]
537 pub name: Option<String>,
538
539 /// The operator identity that released the pin (`human:{id}`, the
540 /// registry commit discipline).
541 pub released_by: String,
542
543 /// The operator's stated reason, when given.
544 #[serde(default, skip_serializing_if = "Option::is_none")]
545 pub reason: Option<String>,
546
547 /// When the release journaled.
548 pub released_at: DateTime<Utc>,
549}
550
551/// Which read surface observed the miss — the audit reads whether the
552/// bytes themselves were asked for or a derivation was attempted.
553#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
554#[serde(rename_all = "snake_case")]
555pub enum UnavailabilitySurface {
556 /// The byte read (`GET /artifacts/{id}/bytes`) — the surface an
557 /// exact replay's byte fetch fails closed on.
558 Bytes,
559 /// The preview derivation (`GET /artifacts/{id}/preview`).
560 Preview,
561}
562
563/// The journaled half of the typed miss: the output payload of one
564/// [`RunEventKind::ArtifactUnavailable`](crate::record::RunEventKind::ArtifactUnavailable)
565/// event on the deployment's artifact evidence chain. The record exists,
566/// the bytes do not — that difference is exactly what a retention audit
567/// needs, so the miss is typed (`410 artifact_unavailable`, never 404)
568/// and journaled. Journaling lands on the deployment chain rather than
569/// the producing run's journal so the miss evidence never rewrites a
570/// journal a signed receipt already covers.
571#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
572pub struct ArtifactUnavailability {
573 /// The missed content address.
574 pub artifact_id: String,
575
576 /// The tenant whose record was read.
577 pub tenant: String,
578
579 /// The logical name, when the record was named.
580 #[serde(default, skip_serializing_if = "Option::is_none")]
581 pub name: Option<String>,
582
583 /// The read surface that observed the miss.
584 pub surface: UnavailabilitySurface,
585
586 /// When the miss was observed.
587 pub observed_at: DateTime<Utc>,
588}
589
590// --------------------------------------------------------------------- //
591// Previews (wave 2): derived on read, never stored
592// --------------------------------------------------------------------- //
593
594/// The byte bound on a text or JSON preview's source window (4 KB — the
595/// journal's `INLINE_PAYLOAD_MAX_BYTES` discipline: a preview is an
596/// operator-scale read, so its derivation is bounded the same way the
597/// journal bounds inline payloads).
598pub const PREVIEW_TEXT_MAX_BYTES: usize = 4096;
599
600/// The longest edge a derived thumbnail may have. Integer-factor nearest
601/// sampling keeps the derivation cheap and exact — a thumbnail is an
602/// operator's glance, not a rendering pipeline.
603pub const PREVIEW_THUMBNAIL_MAX_EDGE: u32 = 64;
604
605/// The bucket count of a derived waveform's peak envelope.
606pub const PREVIEW_WAVEFORM_BUCKETS: usize = 64;
607
608/// What a read derived from the bytes — the `RegistryDiff` precedent
609/// applied to media: computed on read, *never* stored. A stored preview
610/// would be a second, divergent account of the same bytes; derivation
611/// keeps one source of truth, and a kind that cannot be derived answers
612/// [`ArtifactPreview::Empty`] — an honest empty, not a placeholder.
613///
614/// The derivations are deliberately dependency-free, which bounds what
615/// they cover, stated per kind:
616///
617/// - `file` / `data`: a bounded UTF-8 window ([`ArtifactPreview::Text`]),
618/// or the parsed document when the whole payload fits the window and
619/// is JSON ([`ArtifactPreview::Json`]). Binary bytes are not text —
620/// they answer `Empty`.
621/// - `image`: a real downscaled thumbnail ([`ArtifactPreview::Image`])
622/// for the formats decodable without a codec dependency — uncompressed
623/// BMP (24/32-bit `BI_RGB`) and binary PNM (P6/P5). Compressed formats
624/// (PNG, JPEG, GIF, …) answer `Empty`: a codec dependency is the
625/// measured-need seam the design's preview question reserves, not
626/// something to half-parse.
627/// - `audio`: waveform metadata ([`ArtifactPreview::Audio`]) for RIFF/WAVE
628/// PCM (8/16-bit) — duration, rate, channels, and a bounded peak
629/// envelope. Anything else answers `Empty`.
630#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
631#[serde(tag = "kind", rename_all = "snake_case")]
632pub enum ArtifactPreview {
633 /// A bounded UTF-8 window over the source bytes.
634 Text {
635 /// The window's text (lossless: only whole characters).
636 text: String,
637 /// Whether the source extends past the window.
638 truncated: bool,
639 /// The source size in bytes.
640 source_bytes: u64,
641 },
642
643 /// The parsed JSON document (only when it fits the window whole — a
644 /// preview is bounded, so a larger document degrades to `Text`,
645 /// never to a partial parse).
646 Json {
647 /// The parsed document.
648 value: serde_json::Value,
649 /// The source size in bytes.
650 source_bytes: u64,
651 },
652
653 /// A downscaled thumbnail, re-encoded as a binary PPM (P6) and
654 /// carried hex-encoded (the repo's dependency-free byte-on-JSON
655 /// codec — the commit path's `bytes_hex` convention).
656 Image {
657 /// The decoded source format (`bmp` or `pnm`).
658 format: String,
659 /// The source dimensions.
660 width: u32,
661 /// The source dimensions.
662 height: u32,
663 /// The thumbnail dimensions (integer-factor downscale, nearest
664 /// sampling).
665 thumb_width: u32,
666 /// The thumbnail dimensions.
667 thumb_height: u32,
668 /// The thumbnail as a P6 PPM, hex-encoded.
669 pixels_ppm_hex: String,
670 },
671
672 /// Waveform metadata for RIFF/WAVE PCM: the envelope an operator
673 /// glances at, derived — the audio bytes themselves are never
674 /// re-encoded.
675 Audio {
676 /// The decoded container (`wav`).
677 format: String,
678 /// The clip length in whole milliseconds.
679 duration_ms: u64,
680 /// The sample rate in Hz.
681 sample_rate: u32,
682 /// The channel count.
683 channels: u16,
684 /// The frame count (samples per channel).
685 frames: u64,
686 /// The peak envelope: [`PREVIEW_WAVEFORM_BUCKETS`] buckets, each
687 /// the loudest absolute sample in its window on the 16-bit scale
688 /// (`0..=65535`), max across channels.
689 peaks: Vec<u16>,
690 },
691
692 /// The honest empty answer: this media kind (or these bytes, under
693 /// the dependency-free derivations above) yields no preview. Carries
694 /// the reason so the answer is attributable, never a placeholder.
695 Empty {
696 /// Why nothing was derivable.
697 reason: String,
698 },
699}
700
701/// Derive the preview for `media_kind` over `bytes` — the single
702/// derivation the preview route serves, so the answer is a pure function
703/// of the bytes and can never drift from them.
704pub fn derive_preview(media_kind: MediaKind, bytes: &[u8]) -> ArtifactPreview {
705 let source_bytes = bytes.len() as u64;
706 match media_kind {
707 MediaKind::File | MediaKind::Data => derive_text_preview(bytes, source_bytes),
708 MediaKind::Image => derive_image_preview(bytes),
709 MediaKind::Audio => derive_audio_preview(bytes),
710 }
711}
712
713/// The text/JSON rule: a whole document that fits the window and parses
714/// as JSON is `Json`; any valid UTF-8 window is `Text`; interior-invalid
715/// bytes are binary, and binary is not text.
716fn derive_text_preview(bytes: &[u8], source_bytes: u64) -> ArtifactPreview {
717 if bytes.len() <= PREVIEW_TEXT_MAX_BYTES {
718 if let Ok(value) = serde_json::from_slice::<serde_json::Value>(bytes) {
719 return ArtifactPreview::Json {
720 value,
721 source_bytes,
722 };
723 }
724 }
725 let window = &bytes[..bytes.len().min(PREVIEW_TEXT_MAX_BYTES)];
726 let truncated = bytes.len() > PREVIEW_TEXT_MAX_BYTES;
727 match std::str::from_utf8(window) {
728 Ok(text) => ArtifactPreview::Text {
729 text: text.to_owned(),
730 truncated,
731 source_bytes,
732 },
733 Err(error) if truncated && error.error_len().is_none() => {
734 // The window clipped a multi-byte character at its end: serve
735 // up to the boundary — the window stays lossless.
736 let text = std::str::from_utf8(&window[..error.valid_up_to()])
737 .expect("valid_up_to is a char boundary");
738 ArtifactPreview::Text {
739 text: text.to_owned(),
740 truncated: true,
741 source_bytes,
742 }
743 }
744 Err(_) => ArtifactPreview::Empty {
745 reason: "the bytes are not valid UTF-8 — binary content yields no text \
746 preview, and a placeholder would pretend otherwise"
747 .to_owned(),
748 },
749 }
750}
751
752/// The image rule: decode what is decodable without a codec dependency,
753/// downscale by an integer factor with nearest sampling, re-encode as
754/// P6. Anything else is the honest empty.
755fn derive_image_preview(bytes: &[u8]) -> ArtifactPreview {
756 let decoded = decode_bmp(bytes)
757 .map(|(width, height, rgb)| ("bmp", width, height, rgb))
758 .or_else(|| decode_pnm(bytes).map(|(width, height, rgb)| ("pnm", width, height, rgb)));
759 let Some((format, width, height, rgb)) = decoded else {
760 return ArtifactPreview::Empty {
761 reason: "only uncompressed BMP (24/32-bit) and binary PNM (P6/P5) decode \
762 without a codec dependency — a compressed format is the measured-need \
763 seam, not something to half-parse"
764 .to_owned(),
765 };
766 };
767 let factor = (width.max(height))
768 .div_ceil(PREVIEW_THUMBNAIL_MAX_EDGE)
769 .max(1);
770 let thumb_width = (width / factor).max(1);
771 let thumb_height = (height / factor).max(1);
772 let mut ppm = format!("P6\n{thumb_width} {thumb_height}\n255\n").into_bytes();
773 for y in 0..thumb_height {
774 for x in 0..thumb_width {
775 let source = ((y * factor) * width + (x * factor)) as usize * 3;
776 ppm.extend_from_slice(&rgb[source..source + 3]);
777 }
778 }
779 ArtifactPreview::Image {
780 format: format.to_owned(),
781 width,
782 height,
783 thumb_width,
784 thumb_height,
785 pixels_ppm_hex: crate::broker::hex_encode(&ppm),
786 }
787}
788
789/// A decoded raster: width, height, and tightly packed RGB bytes.
790type Raster = (u32, u32, Vec<u8>);
791
792fn read_u16_le(bytes: &[u8], at: usize) -> Option<u16> {
793 Some(u16::from_le_bytes(bytes.get(at..at + 2)?.try_into().ok()?))
794}
795
796fn read_u32_le(bytes: &[u8], at: usize) -> Option<u32> {
797 Some(u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?))
798}
799
800/// Decode an uncompressed Windows BMP (`BM`, `BI_RGB`, 24 or 32 bits per
801/// pixel) into RGB. Rows are bottom-up unless the height is negative;
802/// 24-bit rows pad to a 4-byte boundary. Anything richer (compression,
803/// palettes, bitfields) answers `None` — partial decoding guesses, and
804/// guessing is not derivation.
805fn decode_bmp(bytes: &[u8]) -> Option<Raster> {
806 if bytes.len() < 54 || &bytes[0..2] != b"BM" {
807 return None;
808 }
809 let data_offset = read_u32_le(bytes, 10)? as usize;
810 let dib_size = read_u32_le(bytes, 14)? as usize;
811 if dib_size < 40 {
812 return None;
813 }
814 let width = read_u32_le(bytes, 18)?;
815 let raw_height = i32::from_le_bytes(bytes.get(22..26)?.try_into().ok()?);
816 let top_down = raw_height < 0;
817 let height = raw_height.unsigned_abs();
818 let bpp = read_u16_le(bytes, 28)?;
819 let compression = read_u32_le(bytes, 30)?;
820 if compression != 0 || width == 0 || height == 0 || !matches!(bpp, 24 | 32) {
821 return None;
822 }
823 let pixel_bytes = (bpp / 8) as usize;
824 let stride = if bpp == 24 {
825 (width as usize * 3).div_ceil(4) * 4
826 } else {
827 width as usize * 4
828 };
829 let needed = data_offset.checked_add(stride.checked_mul(height as usize)?)?;
830 if bytes.len() < needed {
831 return None;
832 }
833 let mut rgb = Vec::with_capacity(width as usize * height as usize * 3);
834 for row in 0..height as usize {
835 let source_row = if top_down {
836 row
837 } else {
838 height as usize - 1 - row
839 };
840 let base = data_offset + source_row * stride;
841 for x in 0..width as usize {
842 let at = base + x * pixel_bytes;
843 // BMP stores BGR(A); the preview speaks RGB.
844 rgb.push(bytes[at + 2]);
845 rgb.push(bytes[at + 1]);
846 rgb.push(bytes[at]);
847 }
848 }
849 Some((width, height, rgb))
850}
851
852/// Decode a binary PNM (P6 color, P5 grayscale; maxval 255) into RGB.
853/// The header is whitespace-separated ASCII; exactly one whitespace byte
854/// follows the maxval. Comments (`# …`) are honored between tokens, per
855/// the format. Anything else (ASCII PNM, 16-bit maxval) answers `None`.
856fn decode_pnm(bytes: &[u8]) -> Option<Raster> {
857 let color = match bytes.first()? {
858 b'P' => match bytes.get(1)? {
859 b'6' => true,
860 b'5' => false,
861 _ => return None,
862 },
863 _ => return None,
864 };
865 let mut cursor = 2;
866 let mut tokens = [0u32; 3];
867 for token in &mut tokens {
868 // Skip whitespace and comments before each token.
869 loop {
870 match bytes.get(cursor)? {
871 b'#' => {
872 while bytes.get(cursor).is_some_and(|b| *b != b'\n') {
873 cursor += 1;
874 }
875 }
876 b if b.is_ascii_whitespace() => cursor += 1,
877 _ => break,
878 }
879 }
880 let start = cursor;
881 while bytes.get(cursor).is_some_and(|b| b.is_ascii_digit()) {
882 cursor += 1;
883 }
884 *token = std::str::from_utf8(bytes.get(start..cursor)?)
885 .ok()?
886 .parse()
887 .ok()?;
888 }
889 let [width, height, maxval] = tokens;
890 if width == 0 || height == 0 || maxval != 255 {
891 return None;
892 }
893 // Exactly one whitespace byte separates the header from the raster.
894 if !bytes.get(cursor)?.is_ascii_whitespace() {
895 return None;
896 }
897 cursor += 1;
898 let pixels = width as usize * height as usize;
899 let mut rgb = Vec::with_capacity(pixels * 3);
900 if color {
901 let data = bytes.get(cursor..cursor + pixels * 3)?;
902 rgb.extend_from_slice(data);
903 } else {
904 let data = bytes.get(cursor..cursor + pixels)?;
905 for gray in data {
906 rgb.extend_from_slice(&[*gray, *gray, *gray]);
907 }
908 }
909 Some((width, height, rgb))
910}
911
912/// The audio rule: RIFF/WAVE PCM (8 or 16 bits) yields duration, rate,
913/// channels, frames, and a bounded peak envelope. Any other container or
914/// encoding is the honest empty.
915fn derive_audio_preview(bytes: &[u8]) -> ArtifactPreview {
916 match decode_wav(bytes) {
917 Some((sample_rate, channels, frames, peaks)) => ArtifactPreview::Audio {
918 format: "wav".to_owned(),
919 duration_ms: frames.saturating_mul(1000) / u64::from(sample_rate.max(1)),
920 sample_rate,
921 channels,
922 frames,
923 peaks,
924 },
925 None => ArtifactPreview::Empty {
926 reason: "only RIFF/WAVE PCM (8/16-bit) decodes without a codec dependency — \
927 a compressed or foreign container yields no waveform metadata"
928 .to_owned(),
929 },
930 }
931}
932
933/// Parse a RIFF/WAVE PCM stream into its format fields and a peak
934/// envelope of [`PREVIEW_WAVEFORM_BUCKETS`] buckets (the loudest absolute
935/// sample per window, max across channels, on the 16-bit scale).
936/// Chunked layout is honored (unknown chunks are skipped on their padded
937/// length); non-PCM encodings, unusual bit depths, and truncated bodies
938/// answer `None`.
939fn decode_wav(bytes: &[u8]) -> Option<(u32, u16, u64, Vec<u16>)> {
940 if bytes.len() < 12 || &bytes[0..4] != b"RIFF" || &bytes[8..12] != b"WAVE" {
941 return None;
942 }
943 let mut cursor = 12;
944 let mut format: Option<(u16, u32, u16, u16)> = None; // (channels, rate, bits, align)
945 let mut data: Option<&[u8]> = None;
946 while cursor + 8 <= bytes.len() {
947 let id = &bytes[cursor..cursor + 4];
948 let size = read_u32_le(bytes, cursor + 4)? as usize;
949 let body = bytes.get(cursor + 8..cursor + 8 + size)?;
950 match id {
951 b"fmt " => {
952 if size < 16 {
953 return None;
954 }
955 let audio_format = read_u16_le(body, 0)?;
956 let channels = read_u16_le(body, 2)?;
957 let sample_rate = read_u32_le(body, 4)?;
958 let block_align = read_u16_le(body, 12)?;
959 let bits = read_u16_le(body, 14)?;
960 if audio_format != 1 || channels == 0 || !matches!(bits, 8 | 16) {
961 return None;
962 }
963 format = Some((channels, sample_rate, bits, block_align));
964 }
965 b"data" => data = Some(body),
966 _ => {}
967 }
968 // Chunks pad to an even length.
969 cursor += 8 + size + (size % 2);
970 }
971 let (channels, sample_rate, bits, block_align) = format?;
972 let data = data?;
973 let align = usize::from(block_align).max(usize::from(channels) * usize::from(bits / 8));
974 let frames = (data.len() / align) as u64;
975 if frames == 0 {
976 return None;
977 }
978 let mut peaks = vec![0u16; PREVIEW_WAVEFORM_BUCKETS];
979 for frame in 0..frames {
980 let bucket = ((frame * PREVIEW_WAVEFORM_BUCKETS as u64) / frames) as usize;
981 let base = frame as usize * align;
982 for channel in 0..usize::from(channels) {
983 let at = base + channel * usize::from(bits / 8);
984 let magnitude = match bits {
985 // 8-bit PCM is unsigned, midpoint 128: the magnitude is
986 // the absolute offset from the midpoint, on the 16-bit
987 // scale.
988 8 => u16::from(data[at].abs_diff(128)) * 256,
989 _ => {
990 let sample = i16::from_le_bytes([data[at], data[at + 1]]);
991 (sample as i32).unsigned_abs().min(u16::MAX as u32) as u16
992 }
993 };
994 peaks[bucket] = peaks[bucket].max(magnitude);
995 }
996 }
997 Some((sample_rate, channels, frames, peaks))
998}
999
1000/// The artifact plane's typed refusals. A refused commit changes
1001/// nothing — the [`crate::registry::RegistryError`] discipline: refused
1002/// operations are contract outcomes surfaced to the caller, never
1003/// silent no-ops.
1004#[derive(Debug, Clone, PartialEq, Error)]
1005pub enum ArtifactError {
1006 /// An artifact name outside the naming rules (see
1007 /// [`commit_artifact`]).
1008 #[error("invalid artifact name {name:?}: {reason}")]
1009 InvalidName {
1010 /// The refused name.
1011 name: String,
1012 /// The rule it broke.
1013 reason: &'static str,
1014 },
1015
1016 /// A content address outside the `sha256_hex` shape.
1017 #[error("invalid artifact address {address:?}: {reason}")]
1018 InvalidAddress {
1019 /// The refused address.
1020 address: String,
1021 /// The rule it broke.
1022 reason: &'static str,
1023 },
1024
1025 /// A version append against a sequence the declaration does not
1026 /// belong to (see [`append_artifact_version`]) — an unnamed head, or
1027 /// a name that is not the head's. Refused, never redirected: a
1028 /// version joins the sequence its name owns.
1029 #[error("version append refused: {reason}")]
1030 VersionMismatch {
1031 /// The rule the append broke.
1032 reason: &'static str,
1033 },
1034}
1035
1036#[cfg(test)]
1037mod tests {
1038 use super::*;
1039 use crate::journal::{Clock, EventDraft, Journal};
1040 use crate::record::{sha256_hex, Effect, RunEventKind};
1041 use serde::Serialize;
1042 use serde_json::json;
1043 use std::path::PathBuf;
1044
1045 // ---------- golden-file machinery (the tests/registry.rs discipline) ----------
1046 //
1047 // Asserted here (unit tests beside the contracts) so the golden
1048 // fixtures under `tests/golden/` pin the new wire shapes without the
1049 // wave touching another test file. `UPDATE_GOLDEN=1` blesses an
1050 // intentional change — the diff is then the contract change under
1051 // review.
1052
1053 fn golden_path(name: &str) -> PathBuf {
1054 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1055 .join("tests")
1056 .join("golden")
1057 .join(name)
1058 }
1059
1060 fn assert_golden(name: &str, value: &impl Serialize) {
1061 let rendered = format!("{}\n", serde_json::to_string_pretty(value).unwrap());
1062 let path = golden_path(name);
1063 if std::env::var_os("UPDATE_GOLDEN").is_some() {
1064 std::fs::write(&path, &rendered).unwrap();
1065 return;
1066 }
1067 let expected = std::fs::read_to_string(&path)
1068 .unwrap_or_else(|e| panic!("missing golden file `{}`: {e}", path.display()));
1069 assert_eq!(
1070 rendered,
1071 expected,
1072 "contract drift in `{}` — if intentional, re-run with UPDATE_GOLDEN=1 \
1073 and review the diff",
1074 path.display()
1075 );
1076 }
1077
1078 fn ts(millis: i64) -> DateTime<Utc> {
1079 DateTime::<Utc>::from_timestamp_millis(millis).unwrap()
1080 }
1081
1082 fn effect_id() -> EffectId {
1083 crate::effects::derive_effect_id(
1084 "run-9",
1085 "render_report",
1086 &sha256_hex(b"weekly"),
1087 Some("render:9"),
1088 )
1089 }
1090
1091 fn lineage() -> ArtifactLineage {
1092 ArtifactLineage {
1093 run_id: "run-9".into(),
1094 effect_id: effect_id(),
1095 event_id: "run-9:7".into(),
1096 }
1097 }
1098
1099 fn named_commitment_pair() -> (RunArtifact, ArtifactCommitment) {
1100 commit_artifact(CommitDeclaration {
1101 reference: ArtifactRef {
1102 sha256: "a".repeat(64),
1103 bytes: 41_312,
1104 },
1105 name: Some("weekly-report".into()),
1106 media_kind: MediaKind::Image,
1107 media_type: Some("image/png".into()),
1108 lineage: lineage(),
1109 retention: RetentionPolicy::Days { days: 30 },
1110 committed_at: ts(1_760_000_000_000),
1111 })
1112 .unwrap()
1113 }
1114
1115 // ---------- goldens ----------
1116
1117 #[test]
1118 fn golden_artifact_event_kinds_shape() {
1119 // The plane's additive RunEventKind wire names (the
1120 // `registry_event_kinds.json` discipline): pinned so no wire
1121 // shape lands unpinned. Wave 2 appends the retention acts after
1122 // `artifact_committed`, per the additive evolution rule every
1123 // variant since R0.6 followed — declared in wire order.
1124 assert_golden(
1125 "artifact_event_kinds.json",
1126 &vec![
1127 RunEventKind::ArtifactCommitted,
1128 RunEventKind::ArtifactPruned,
1129 RunEventKind::ArtifactRetentionReleased,
1130 RunEventKind::ArtifactUnavailable,
1131 ],
1132 );
1133 }
1134
1135 #[test]
1136 fn golden_run_artifact_shape() {
1137 // The full record: named, media-typed, day-retained, one base
1138 // version, lineage attached.
1139 let (record, _) = named_commitment_pair();
1140 assert_golden("run_artifact.json", &record);
1141 }
1142
1143 #[test]
1144 fn golden_run_artifact_unnamed_shape() {
1145 // The sparse wire: unnamed, no declared media type, the default
1146 // retention — `name`, `media_type`, and `versions` are absent
1147 // (not null), so the address-only artifact carries no
1148 // placeholders.
1149 let (record, _) = commit_artifact(CommitDeclaration {
1150 reference: ArtifactRef {
1151 sha256: "b".repeat(64),
1152 bytes: 973,
1153 },
1154 name: None,
1155 media_kind: MediaKind::File,
1156 media_type: None,
1157 lineage: lineage(),
1158 retention: RetentionPolicy::default(),
1159 committed_at: ts(1_760_000_000_000),
1160 })
1161 .unwrap();
1162 assert_golden("run_artifact_unnamed.json", &record);
1163 }
1164
1165 #[test]
1166 fn golden_artifact_commitment_shape() {
1167 // The journaled payload the `artifact_committed` event carries.
1168 let (_, commitment) = named_commitment_pair();
1169 assert_golden("artifact_commitment.json", &commitment);
1170 }
1171
1172 #[test]
1173 fn golden_retention_policy_shape() {
1174 // All three variants in declaration order: the policy names and
1175 // the `days` payload are the contract.
1176 assert_golden(
1177 "retention_policy.json",
1178 &vec![
1179 RetentionPolicy::Pinned,
1180 RetentionPolicy::Days { days: 30 },
1181 RetentionPolicy::ReceiptBound,
1182 ],
1183 );
1184 }
1185
1186 // ---------- the commit constructor ----------
1187
1188 #[test]
1189 fn commit_builds_record_and_payload_from_one_derivation() {
1190 let (record, commitment) = named_commitment_pair();
1191 // Two homes, one derivation: the journaled commitment and the
1192 // stored record agree on every shared field by construction.
1193 assert_eq!(record.artifact_id, commitment.artifact_id);
1194 assert_eq!(record.name, commitment.name);
1195 assert_eq!(record.media_kind, commitment.media_kind);
1196 assert_eq!(record.retention, commitment.retention);
1197 assert_eq!(record.lineage.effect_id, commitment.effect_id);
1198 assert_eq!(record.versions.len(), 1);
1199 assert_eq!(record.versions[0].sha256, record.artifact_id);
1200 assert_eq!(record.versions[0].bytes, commitment.bytes);
1201 assert_eq!(commitment.version, Some(0));
1202 }
1203
1204 #[test]
1205 fn commit_refuses_the_naming_rules() {
1206 for name in ["", " padded", "has@tag", "tenant/escape", "ctl\tchar"] {
1207 let declaration = CommitDeclaration {
1208 reference: ArtifactRef {
1209 sha256: "a".repeat(64),
1210 bytes: 1,
1211 },
1212 name: Some(name.into()),
1213 media_kind: MediaKind::File,
1214 media_type: None,
1215 lineage: lineage(),
1216 retention: RetentionPolicy::default(),
1217 committed_at: ts(1_760_000_000_000),
1218 };
1219 assert!(
1220 matches!(
1221 commit_artifact(declaration),
1222 Err(ArtifactError::InvalidName { .. })
1223 ),
1224 "name {name:?} must be refused"
1225 );
1226 }
1227 }
1228
1229 #[test]
1230 fn commit_refuses_a_malformed_address() {
1231 for address in ["", "abc", &"A".repeat(64), &"z".repeat(64)] {
1232 let declaration = CommitDeclaration {
1233 reference: ArtifactRef {
1234 sha256: address.to_string(),
1235 bytes: 1,
1236 },
1237 name: None,
1238 media_kind: MediaKind::File,
1239 media_type: None,
1240 lineage: lineage(),
1241 retention: RetentionPolicy::default(),
1242 committed_at: ts(1_760_000_000_000),
1243 };
1244 assert!(
1245 matches!(
1246 commit_artifact(declaration),
1247 Err(ArtifactError::InvalidAddress { .. })
1248 ),
1249 "address {address:?} must be refused"
1250 );
1251 }
1252 }
1253
1254 #[test]
1255 fn sparse_wire_omits_absent_slots() {
1256 // Additive-evolution insurance: the unnamed record's optional
1257 // slots are absent on the wire (not null), and a payload without
1258 // them deserializes with the defaults the record was built from.
1259 let (record, _) = commit_artifact(CommitDeclaration {
1260 reference: ArtifactRef {
1261 sha256: "c".repeat(64),
1262 bytes: 7,
1263 },
1264 name: None,
1265 media_kind: MediaKind::Data,
1266 media_type: None,
1267 lineage: lineage(),
1268 retention: RetentionPolicy::Pinned,
1269 committed_at: ts(1_760_000_000_000),
1270 })
1271 .unwrap();
1272 let wire = serde_json::to_value(&record).unwrap();
1273 assert!(wire.get("name").is_none());
1274 assert!(wire.get("media_type").is_none());
1275 assert!(wire.get("versions").is_none());
1276 let back: RunArtifact = serde_json::from_value(wire).unwrap();
1277 assert_eq!(back, record);
1278 }
1279
1280 // ---------- the journaled half ----------
1281
1282 #[test]
1283 fn artifact_committed_journals_and_reverifies() {
1284 // The commitment event sits in the run's journal under the head
1285 // hash: snapshot, re-verify, and the payload resolves back into
1286 // the typed commitment — the audit walk's first hop.
1287 let (_, commitment) = named_commitment_pair();
1288 let journal = Journal::new("run-9", "thread-1", Clock::System);
1289 journal.record(
1290 EventDraft::new(RunEventKind::ArtifactCommitted, Effect::Pure)
1291 .output(serde_json::to_value(&commitment).unwrap())
1292 .parent("run-9:7"),
1293 );
1294 let snapshot = journal.snapshot();
1295 let bytes = serde_json::to_vec(&snapshot).unwrap();
1296 let parsed = serde_json::from_slice(&bytes).unwrap();
1297 let rebuilt = Journal::from_snapshot(parsed, Clock::System).unwrap();
1298 let event = &rebuilt.events()[0];
1299 assert_eq!(event.kind, RunEventKind::ArtifactCommitted);
1300 assert_eq!(event.parent.as_deref(), Some("run-9:7"));
1301 let resolved: ArtifactCommitment =
1302 serde_json::from_value(rebuilt.resolve(event.output.as_ref().unwrap()).unwrap())
1303 .unwrap();
1304 assert_eq!(resolved, commitment);
1305 }
1306
1307 #[test]
1308 fn artifact_committed_payload_survives_a_mixed_journal() {
1309 // A journal holding pre-R0.12 events beside the new variant
1310 // round-trips whole: the additive variant changes nothing the
1311 // older events deserialize from.
1312 let (_, commitment) = named_commitment_pair();
1313 let journal = Journal::new("run-9", "thread-1", Clock::System);
1314 journal.record(EventDraft::new(RunEventKind::SuperStepStart, Effect::Pure));
1315 journal.record(
1316 EventDraft::new(RunEventKind::NodeOutput, Effect::Pure)
1317 .node("render")
1318 .output(json!({"report": "weekly"})),
1319 );
1320 journal.record(
1321 EventDraft::new(RunEventKind::ArtifactCommitted, Effect::Pure)
1322 .output(serde_json::to_value(&commitment).unwrap()),
1323 );
1324 let snapshot = journal.snapshot();
1325 let rebuilt = Journal::from_snapshot(
1326 serde_json::from_str(&serde_json::to_string(&snapshot).unwrap()).unwrap(),
1327 Clock::System,
1328 )
1329 .unwrap();
1330 assert_eq!(rebuilt.len(), 3);
1331 assert_eq!(rebuilt.events()[2].kind, RunEventKind::ArtifactCommitted);
1332 }
1333
1334 // ---------- wave 2: version accumulation ----------
1335
1336 /// Build a three-version sequence by appending twice onto the named
1337 /// base commit; returns the newest head and its commitment.
1338 fn versioned_head() -> (RunArtifact, ArtifactCommitment) {
1339 let (base, _) = named_commitment_pair();
1340 let (v2, _) = append_artifact_version(
1341 &base,
1342 CommitDeclaration {
1343 reference: ArtifactRef {
1344 sha256: "d".repeat(64),
1345 bytes: 41_990,
1346 },
1347 name: Some("weekly-report".into()),
1348 media_kind: MediaKind::Image,
1349 media_type: Some("image/png".into()),
1350 lineage: lineage(),
1351 retention: RetentionPolicy::Days { days: 30 },
1352 committed_at: ts(1_760_100_000_000),
1353 },
1354 )
1355 .unwrap();
1356 append_artifact_version(
1357 &v2,
1358 CommitDeclaration {
1359 reference: ArtifactRef {
1360 sha256: "e".repeat(64),
1361 bytes: 42_104,
1362 },
1363 name: Some("weekly-report".into()),
1364 media_kind: MediaKind::Image,
1365 media_type: Some("image/png".into()),
1366 lineage: lineage(),
1367 retention: RetentionPolicy::Days { days: 30 },
1368 committed_at: ts(1_760_200_000_000),
1369 },
1370 )
1371 .unwrap()
1372 }
1373
1374 #[test]
1375 fn golden_run_artifact_versioned_shape() {
1376 // The accumulated record: three entries, oldest first, each its
1377 // own address — the append-only `ArtifactCommit` discipline over
1378 // bytes, pinned on the wire.
1379 let (head, _) = versioned_head();
1380 assert_golden("run_artifact_versioned.json", &head);
1381 }
1382
1383 #[test]
1384 fn golden_artifact_prune_shape() {
1385 // The sweeper's journaled intention: address, name, cause,
1386 // instant — all three causes in declaration order.
1387 assert_golden(
1388 "artifact_prune.json",
1389 &vec![
1390 ArtifactPrune {
1391 artifact_id: "a".repeat(64),
1392 name: Some("weekly-report".into()),
1393 cause: PruneCause::Expired,
1394 swept_at: ts(1_760_300_000_000),
1395 },
1396 ArtifactPrune {
1397 artifact_id: "b".repeat(64),
1398 name: None,
1399 cause: PruneCause::Unbound,
1400 swept_at: ts(1_760_300_000_000),
1401 },
1402 ArtifactPrune {
1403 artifact_id: "c".repeat(64),
1404 name: None,
1405 cause: PruneCause::Released,
1406 swept_at: ts(1_760_300_000_000),
1407 },
1408 ],
1409 );
1410 }
1411
1412 #[test]
1413 fn golden_artifact_release_shape() {
1414 // The operator's journaled release: attributed, optional reason
1415 // present here; the sparse wire (no reason, unnamed) is covered
1416 // by `retention_acts_omit_absent_slots`.
1417 assert_golden(
1418 "artifact_release.json",
1419 &ArtifactRelease {
1420 artifact_id: "a".repeat(64),
1421 tenant: "acme".into(),
1422 name: Some("weekly-report".into()),
1423 released_by: "human:amjad".into(),
1424 reason: Some("evidence window closed by counsel".into()),
1425 released_at: ts(1_760_300_000_000),
1426 },
1427 );
1428 }
1429
1430 #[test]
1431 fn golden_artifact_unavailability_shape() {
1432 // The journaled miss: both surfaces, so the audit reads which
1433 // read failed closed.
1434 assert_golden(
1435 "artifact_unavailability.json",
1436 &vec![
1437 ArtifactUnavailability {
1438 artifact_id: "a".repeat(64),
1439 tenant: "acme".into(),
1440 name: Some("weekly-report".into()),
1441 surface: UnavailabilitySurface::Bytes,
1442 observed_at: ts(1_760_300_000_000),
1443 },
1444 ArtifactUnavailability {
1445 artifact_id: "a".repeat(64),
1446 tenant: "acme".into(),
1447 name: Some("weekly-report".into()),
1448 surface: UnavailabilitySurface::Preview,
1449 observed_at: ts(1_760_300_100_000),
1450 },
1451 ],
1452 );
1453 }
1454
1455 #[test]
1456 fn version_append_accumulates_and_indexes_the_new_head() {
1457 let (head, commitment) = versioned_head();
1458 assert_eq!(head.versions.len(), 3);
1459 assert_eq!(head.versions[0].sha256, "a".repeat(64));
1460 assert_eq!(head.versions[1].sha256, "d".repeat(64));
1461 assert_eq!(head.versions[2].sha256, "e".repeat(64));
1462 // The current version is the last, and it is the record itself.
1463 assert_eq!(head.artifact_id, head.versions[2].sha256);
1464 assert_eq!(commitment.version, Some(2));
1465 assert_eq!(commitment.name.as_deref(), Some("weekly-report"));
1466 // The append keeps the name, mints fresh lineage/retention from
1467 // the declaration, and never edits the base record.
1468 assert_eq!(head.name.as_deref(), Some("weekly-report"));
1469 }
1470
1471 #[test]
1472 fn version_append_refuses_a_foreign_or_unnamed_sequence() {
1473 let (base, _) = named_commitment_pair();
1474 let declaration = |name: Option<&str>| CommitDeclaration {
1475 reference: ArtifactRef {
1476 sha256: "d".repeat(64),
1477 bytes: 1,
1478 },
1479 name: name.map(str::to_owned),
1480 media_kind: MediaKind::File,
1481 media_type: None,
1482 lineage: lineage(),
1483 retention: RetentionPolicy::default(),
1484 committed_at: ts(1_760_100_000_000),
1485 };
1486 // A different name does not join this sequence.
1487 assert!(matches!(
1488 append_artifact_version(&base, declaration(Some("monthly-report"))),
1489 Err(ArtifactError::VersionMismatch { .. })
1490 ));
1491 // An unnamed declaration has no sequence to join.
1492 assert!(matches!(
1493 append_artifact_version(&base, declaration(None)),
1494 Err(ArtifactError::VersionMismatch { .. })
1495 ));
1496 // An unnamed head has no sequence at all.
1497 let (unnamed, _) = commit_artifact(CommitDeclaration {
1498 reference: ArtifactRef {
1499 sha256: "b".repeat(64),
1500 bytes: 1,
1501 },
1502 name: None,
1503 media_kind: MediaKind::File,
1504 media_type: None,
1505 lineage: lineage(),
1506 retention: RetentionPolicy::default(),
1507 committed_at: ts(1_760_000_000_000),
1508 })
1509 .unwrap();
1510 assert!(matches!(
1511 append_artifact_version(&unnamed, declaration(Some("weekly-report"))),
1512 Err(ArtifactError::VersionMismatch { .. })
1513 ));
1514 // The naming and address rules still hold on the append path.
1515 assert!(matches!(
1516 append_artifact_version(&base, declaration(Some("tenant/escape"))),
1517 Err(ArtifactError::VersionMismatch { .. })
1518 ));
1519 }
1520
1521 #[test]
1522 fn retention_acts_omit_absent_slots() {
1523 // The sparse wire: unnamed, reasonless acts carry no
1524 // placeholders, and round-trip whole.
1525 let release = ArtifactRelease {
1526 artifact_id: "f".repeat(64),
1527 tenant: "default".into(),
1528 name: None,
1529 released_by: "human:amjad".into(),
1530 reason: None,
1531 released_at: ts(1_760_300_000_000),
1532 };
1533 let wire = serde_json::to_value(&release).unwrap();
1534 assert!(wire.get("name").is_none());
1535 assert!(wire.get("reason").is_none());
1536 let back: ArtifactRelease = serde_json::from_value(wire).unwrap();
1537 assert_eq!(back, release);
1538 }
1539
1540 // ---------- wave 2: previews ----------
1541
1542 /// A 4×2 uncompressed 24-bit BMP, rows bottom-up: the top row red,
1543 /// the bottom row blue (in display order).
1544 fn tiny_bmp() -> Vec<u8> {
1545 let stride = 12; // (4 px * 3 B) padded to a 4-byte boundary
1546 let mut bmp = Vec::new();
1547 bmp.extend_from_slice(b"BM");
1548 bmp.extend_from_slice(&(54u32 + 2 * stride as u32).to_le_bytes()); // file size
1549 bmp.extend_from_slice(&0u32.to_le_bytes()); // reserved
1550 bmp.extend_from_slice(&54u32.to_le_bytes()); // data offset
1551 bmp.extend_from_slice(&40u32.to_le_bytes()); // DIB size
1552 bmp.extend_from_slice(&4u32.to_le_bytes()); // width
1553 bmp.extend_from_slice(&2i32.to_le_bytes()); // height (bottom-up)
1554 bmp.extend_from_slice(&1u16.to_le_bytes()); // planes
1555 bmp.extend_from_slice(&24u16.to_le_bytes()); // bpp
1556 bmp.extend_from_slice(&0u32.to_le_bytes()); // BI_RGB
1557 bmp.extend_from_slice(&(2 * stride as u32).to_le_bytes()); // image size
1558 bmp.extend_from_slice(&0u32.to_le_bytes()); // x ppm
1559 bmp.extend_from_slice(&0u32.to_le_bytes()); // y ppm
1560 bmp.extend_from_slice(&0u32.to_le_bytes()); // palette colors
1561 bmp.extend_from_slice(&0u32.to_le_bytes()); // important colors
1562 // Stored bottom row first: blue (BGR).
1563 for _ in 0..4 {
1564 bmp.extend_from_slice(&[255, 0, 0]);
1565 }
1566 bmp.extend_from_slice(&[0; 0]); // stride is exactly 12 here
1567 // Stored top row: red (BGR).
1568 for _ in 0..4 {
1569 bmp.extend_from_slice(&[0, 0, 255]);
1570 }
1571 bmp
1572 }
1573
1574 /// A 16-sample mono 8-bit PCM WAV at 8000 Hz, ramping 0..255.
1575 fn tiny_wav() -> Vec<u8> {
1576 let samples: Vec<u8> = (0..16).map(|i| i * 16).collect();
1577 let mut wav = Vec::new();
1578 wav.extend_from_slice(b"RIFF");
1579 wav.extend_from_slice(&(36u32 + samples.len() as u32).to_le_bytes());
1580 wav.extend_from_slice(b"WAVE");
1581 wav.extend_from_slice(b"fmt ");
1582 wav.extend_from_slice(&16u32.to_le_bytes());
1583 wav.extend_from_slice(&1u16.to_le_bytes()); // PCM
1584 wav.extend_from_slice(&1u16.to_le_bytes()); // mono
1585 wav.extend_from_slice(&8000u32.to_le_bytes()); // rate
1586 wav.extend_from_slice(&8000u32.to_le_bytes()); // byte rate
1587 wav.extend_from_slice(&1u16.to_le_bytes()); // block align
1588 wav.extend_from_slice(&8u16.to_le_bytes()); // bits
1589 wav.extend_from_slice(b"data");
1590 wav.extend_from_slice(&(samples.len() as u32).to_le_bytes());
1591 wav.extend_from_slice(&samples);
1592 wav
1593 }
1594
1595 #[test]
1596 fn golden_artifact_preview_shapes() {
1597 // Every derivable variant plus the honest empty, built from real
1598 // fixtures so the pinned shapes are derivations, not inventions.
1599 let text = derive_preview(MediaKind::File, b"plain export, no structure");
1600 let json_preview = derive_preview(MediaKind::Data, br#"{"rows":[1,2,3]}"#);
1601 let image = derive_preview(MediaKind::Image, &tiny_bmp());
1602 let audio = derive_preview(MediaKind::Audio, &tiny_wav());
1603 let empty = derive_preview(MediaKind::File, &[0xff, 0x00, 0xfe, 0x01]);
1604 assert_golden(
1605 "artifact_preview.json",
1606 &vec![text, json_preview, image, audio, empty],
1607 );
1608 }
1609
1610 #[test]
1611 fn text_preview_bounds_the_window_and_json_stays_whole() {
1612 // A small JSON document derives as parsed JSON.
1613 let preview = derive_preview(MediaKind::Data, br#"{"ok":true}"#);
1614 assert!(matches!(preview, ArtifactPreview::Json { .. }));
1615 // A document past the window degrades to truncated text, never a
1616 // partial parse.
1617 let big = format!("{{\"data\":\"{}\"}}", "x".repeat(PREVIEW_TEXT_MAX_BYTES));
1618 let preview = derive_preview(MediaKind::Data, big.as_bytes());
1619 match preview {
1620 ArtifactPreview::Text {
1621 truncated,
1622 text,
1623 source_bytes,
1624 } => {
1625 assert!(truncated);
1626 assert!(text.len() <= PREVIEW_TEXT_MAX_BYTES);
1627 assert_eq!(source_bytes, big.len() as u64);
1628 }
1629 other => panic!("expected truncated text, got {other:?}"),
1630 }
1631 // A window that would clip a multi-byte character serves up to
1632 // the boundary, lossless.
1633 let mut bytes = vec![b'a'; PREVIEW_TEXT_MAX_BYTES - 1];
1634 bytes.extend_from_slice("é".as_bytes()); // 2 bytes, straddles the cap
1635 let preview = derive_preview(MediaKind::File, &bytes);
1636 match preview {
1637 ArtifactPreview::Text {
1638 truncated, text, ..
1639 } => {
1640 assert!(truncated);
1641 assert_eq!(text.len(), PREVIEW_TEXT_MAX_BYTES - 1);
1642 }
1643 other => panic!("expected boundary-clipped text, got {other:?}"),
1644 }
1645 // Interior-invalid bytes are binary: the honest empty.
1646 assert!(matches!(
1647 derive_preview(MediaKind::File, &[b'a', 0xff, b'b']),
1648 ArtifactPreview::Empty { .. }
1649 ));
1650 }
1651
1652 #[test]
1653 fn image_preview_decodes_downscales_and_refuses_the_undecodable() {
1654 let preview = derive_preview(MediaKind::Image, &tiny_bmp());
1655 match preview {
1656 ArtifactPreview::Image {
1657 format,
1658 width,
1659 height,
1660 thumb_width,
1661 thumb_height,
1662 pixels_ppm_hex,
1663 } => {
1664 assert_eq!(format, "bmp");
1665 assert_eq!((width, height), (4, 2));
1666 assert_eq!((thumb_width, thumb_height), (4, 2)); // under the cap: factor 1
1667 let ppm = crate::broker::hex_decode(&pixels_ppm_hex).unwrap();
1668 assert_eq!(&ppm[0..2], b"P6");
1669 // The display-order top row is red (RGB), the bottom blue.
1670 let header_len = "P6\n4 2\n255\n".len();
1671 assert_eq!(&ppm[header_len..header_len + 3], &[255, 0, 0]);
1672 assert_eq!(&ppm[ppm.len() - 3..], &[0, 0, 255]);
1673 }
1674 other => panic!("expected a derived thumbnail, got {other:?}"),
1675 }
1676 // A P5 grayscale PNM derives too (channels replicate).
1677 let mut pnm = b"P5\n2 1\n255\n".to_vec();
1678 pnm.extend_from_slice(&[17, 240]);
1679 match derive_preview(MediaKind::Image, &pnm) {
1680 ArtifactPreview::Image {
1681 format,
1682 pixels_ppm_hex,
1683 ..
1684 } => {
1685 assert_eq!(format, "pnm");
1686 let ppm = crate::broker::hex_decode(&pixels_ppm_hex).unwrap();
1687 assert!(ppm.windows(3).any(|w| w == [17, 17, 17]));
1688 }
1689 other => panic!("expected a derived pnm thumbnail, got {other:?}"),
1690 }
1691 // A PNG is the honest empty: compressed formats need a codec the
1692 // runtime deliberately does not carry.
1693 let png = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0];
1694 assert!(matches!(
1695 derive_preview(MediaKind::Image, &png),
1696 ArtifactPreview::Empty { .. }
1697 ));
1698 }
1699
1700 #[test]
1701 fn audio_preview_derives_waveform_metadata_for_pcm_only() {
1702 let preview = derive_preview(MediaKind::Audio, &tiny_wav());
1703 match preview {
1704 ArtifactPreview::Audio {
1705 format,
1706 duration_ms,
1707 sample_rate,
1708 channels,
1709 frames,
1710 peaks,
1711 } => {
1712 assert_eq!(format, "wav");
1713 assert_eq!(duration_ms, 2); // 16 frames at 8000 Hz
1714 assert_eq!(sample_rate, 8000);
1715 assert_eq!(channels, 1);
1716 assert_eq!(frames, 16);
1717 assert_eq!(peaks.len(), PREVIEW_WAVEFORM_BUCKETS);
1718 // Sixteen frames over sixty-four buckets touch every
1719 // fourth bucket. The 8-bit magnitude is the absolute
1720 // offset from midpoint 128, so the ramp's ends are the
1721 // loudest: frame 0 (sample 0, offset 128) at bucket 0.
1722 assert_eq!(peaks[0], 128 * 256);
1723 assert_eq!(peaks.iter().max().unwrap(), &(128 * 256));
1724 // The quiet middle (sample 128, offset 0) lands at
1725 // frame 8 → bucket 32.
1726 assert_eq!(peaks[32], 0);
1727 }
1728 other => panic!("expected waveform metadata, got {other:?}"),
1729 }
1730 // A truncated header and a foreign container are the honest empty.
1731 assert!(matches!(
1732 derive_preview(MediaKind::Audio, b"RIFF"),
1733 ArtifactPreview::Empty { .. }
1734 ));
1735 assert!(matches!(
1736 derive_preview(MediaKind::Audio, b"OggS........"),
1737 ArtifactPreview::Empty { .. }
1738 ));
1739 }
1740}