lex_vcs/attestation.rs
1//! Persistent evidence about a stage (#132).
2//!
3//! [`Operation`](crate::Operation) records *what* changed.
4//! [`Intent`](crate::Intent) records *why*. An [`Attestation`] records
5//! *what we know about the result*: did this stage typecheck, did its
6//! examples pass, did a spec prove it, did `lex agent-tool` run it
7//! cleanly under a sandbox.
8//!
9//! Today every verification (`lex check`, `lex agent-tool --spec ...`,
10//! `lex audit --effect ...`) runs, prints a verdict, and exits. The
11//! evidence is ephemeral — there's no persistent answer to "has this
12//! stage ever been spec-checked?" beyond rerunning. That makes
13//! attestations useless as a CI gate and useless as a trust signal
14//! across sessions.
15//!
16//! This module is the foundational data layer for tier-2's evidence
17//! story. Producers (`lex check` emits `TypeCheck`, `lex agent-tool`
18//! emits `Spec` / `Examples` / `DiffBody` / `SandboxRun`) and
19//! consumers (`lex blame --with-evidence`, `GET /v1/stage/<id>/
20//! attestations`) wire to it in subsequent slices.
21//!
22//! # Identity
23//!
24//! [`AttestationId`] is the lowercase-hex SHA-256 of the canonical
25//! form of `(stage_id, op_id, intent_id, kind, result, produced_by)`.
26//! `cost`, `timestamp`, and `signature` are deliberately *not* in the
27//! hash so two independent runs of the same logical verification —
28//! same stage, same kind, same producer, same outcome — produce the
29//! same `attestation_id`. This is the dedup property the issue calls
30//! out: harnesses can ask "has this exact verification been done?"
31//! by checking for the id without rerunning.
32//!
33//! # Storage
34//!
35//! ```text
36//! <root>/attestations/<AttestationId>.json
37//! <root>/attestations/by-stage/<StageId>/<AttestationId>
38//! ```
39//!
40//! The primary file under `attestations/` is the source of truth.
41//! `by-stage/` is a per-stage index — empty marker files whose names
42//! point at the primary record. Rebuildable from primary records on
43//! demand; we write it eagerly so `lex stage <id> --attestations` is
44//! a directory listing rather than a full scan.
45//!
46//! `by-spec/` (mentioned in the issue) is deferred until a producer
47//! actually emits `Spec` attestations against persisted spec ids.
48//!
49//! # Trust model
50//!
51//! Attestations are claims, not proofs. The store doesn't trust
52//! attestations from outside — it just stores them. A maintainer
53//! choosing to skip CI for a stage that already has a passing spec
54//! attestation from a known producer is a *policy* decision, not a
55//! guarantee the store enforces. The optional Ed25519 signature
56//! field exists so an attestation can be cryptographically tied to
57//! a producer (e.g. a CI runner's public key) and the policy
58//! decision auditable. Verifying signatures is out of scope for the
59//! data layer.
60
61use serde::{Deserialize, Serialize};
62use std::collections::BTreeSet;
63use std::fs;
64use std::io::{self, Write};
65use std::path::{Path, PathBuf};
66use std::time::{SystemTime, UNIX_EPOCH};
67
68use crate::canonical;
69use crate::intent::IntentId;
70use crate::operation::{OpId, StageId};
71
72/// Content-addressed identity of an attestation. Lowercase-hex
73/// SHA-256 of the canonical form of
74/// `(stage_id, op_id, intent_id, kind, result, produced_by)`.
75pub type AttestationId = String;
76
77/// Reference to a spec file. Free-form string so callers can use
78/// either a content hash or a logical name; the data layer doesn't
79/// care which. Producers should pick one and stick with it for
80/// dedup to work as expected.
81pub type SpecId = String;
82
83/// Content hash of a file (examples list, body source, etc.). Kept
84/// as a string for the same reason as [`OpId`]: we want this crate
85/// to have no view into the hash function used by callers.
86pub type ContentHash = String;
87
88/// The decision a [`AttestationKind::Review`] carries (#836 G4).
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90#[serde(rename_all = "snake_case")]
91pub enum ReviewVerdict {
92 /// This candidate should win / this stage is good to promote.
93 Approve,
94 /// This candidate should not win / this stage should not advance.
95 Reject,
96 /// Not a veto, but changes are wanted before it advances.
97 RequestChanges,
98}
99
100/// What was verified. The variants mirror the verdict surfaces
101/// `lex agent-tool` and the store-write gate already produce.
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103#[serde(tag = "kind", rename_all = "snake_case")]
104pub enum AttestationKind {
105 /// `lex agent-tool --examples FILE` — body was run against
106 /// `{input, expected}` pairs.
107 Examples {
108 file_hash: ContentHash,
109 count: usize,
110 },
111 /// `lex spec check` or `lex agent-tool --spec FILE` — a
112 /// behavioral contract was checked against the body.
113 Spec {
114 spec_id: SpecId,
115 method: SpecMethod,
116 #[serde(default, skip_serializing_if = "Option::is_none")]
117 trials: Option<usize>,
118 },
119 /// `lex agent-tool --diff-body 'src'` — a second body was run on
120 /// the same inputs and the outputs compared.
121 DiffBody {
122 other_body_hash: ContentHash,
123 input_count: usize,
124 },
125 /// A structured review verdict on a stage — closes the
126 /// Candidate->Promote gap (#836 G4): the path from a `Candidate`
127 /// to a `Promote` otherwise carries no recorded reason. An agent
128 /// or human records why a candidate should (or shouldn't) win the
129 /// bake-off, addressable at the candidate's stage like any other
130 /// attestation. `Approve`/`Reject`/`RequestChanges` also map onto
131 /// the `result` field (Passed/Failed/Inconclusive) so existing
132 /// result-based tooling reads it sensibly.
133 Review {
134 reviewer: String,
135 verdict: ReviewVerdict,
136 #[serde(default, skip_serializing_if = "Option::is_none")]
137 notes: Option<String>,
138 },
139 /// Emitted by the store-write gate (#130) on every accepted op.
140 /// The store can answer "the HEAD typechecks" as a queryable
141 /// fact rather than an implicit invariant.
142 TypeCheck,
143 /// Emitted by `lex audit --effect K` when no violations are
144 /// found. Useful as a trust signal that a stage was checked
145 /// against a specific effect-policy revision.
146 EffectAudit,
147 /// Emitted by `lex agent-tool` on a successful sandboxed run.
148 /// `effects` is the set the sandbox actually allowed; useful for
149 /// answering "did this code run under fs_write?" after the fact.
150 SandboxRun {
151 effects: BTreeSet<String>,
152 },
153 /// Human-issued override (lex-tea v3, #172). Records that a
154 /// human took an action that bypassed an automatic verdict
155 /// — e.g. activating a stage despite a `Spec::Failed` or
156 /// `TypeCheck::Failed` attestation. Subject to the same
157 /// trust trail as agent attestations: the audit fact lives
158 /// in the log alongside what it overrode.
159 ///
160 /// `actor` is the human's identifier (today: `LEX_TEA_USER`
161 /// env var or `--actor` flag; v3b adds session auth).
162 /// `target_attestation_id` points at the attestation being
163 /// overridden, when one exists; for unconditional pins
164 /// (e.g. activate-by-default) it can be `None`.
165 Override {
166 actor: String,
167 reason: String,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
169 target_attestation_id: Option<AttestationId>,
170 },
171 /// `lex stage defer` (lex-tea v3b, #172). Records that a human
172 /// looked at the stage and chose to revisit it later. No state
173 /// change — purely an audit/triage signal so dashboards and AI
174 /// reviewers can see "this isn't abandoned, it's snoozed."
175 Defer {
176 actor: String,
177 reason: String,
178 },
179 /// `lex stage block` (lex-tea v3b, #172). Records that a human
180 /// has decided this stage should not activate. `lex stage pin`
181 /// and any other activation path consults the attestation log
182 /// and refuses while a Block is the latest decision for the
183 /// stage. Reversed by [`AttestationKind::Unblock`].
184 Block {
185 actor: String,
186 reason: String,
187 },
188 /// `lex stage unblock` (lex-tea v3b, #172). Counterpart to
189 /// [`AttestationKind::Block`]. The attestation log is append-
190 /// only, so we encode "block lifted" as a separate, later fact
191 /// rather than mutating the original block.
192 Unblock {
193 actor: String,
194 reason: String,
195 },
196 /// `lex run --trace` finalized a [`lex_trace::TraceTree`] (#246).
197 /// Links the trace blob to the stage that was the run's entry
198 /// point. The trace itself stays at
199 /// `<store>/traces/<run_id>/trace.json` (per
200 /// `docs/design/trace-vs-vcs.md`); this attestation is the
201 /// audit-side hook so `lex attest filter --kind trace` and
202 /// cross-store sync can reason about runs without copying the
203 /// trace bytes.
204 ///
205 /// `root_target` is the entry function's `SigId` — the call site
206 /// the user (or agent) typed on the command line. Distinct from
207 /// `Attestation::stage_id`, which records the *content-addressed*
208 /// stage the entry function resolved to; the same `root_target`
209 /// across multiple body edits surfaces as multiple
210 /// `(stage_id, root_target)` rows in the attestation log.
211 Trace {
212 run_id: TraceRunId,
213 root_target: super::operation::SigId,
214 },
215 /// Retroactive producer quarantine (#248). Declares "as of
216 /// `blocked_at`, attestations produced by `tool_id` are no
217 /// longer trusted; the branch advance gate must refuse to move
218 /// past any op whose attestations were produced by this tool
219 /// at or after `blocked_at`."
220 ///
221 /// Distinct from `policy.json`'s `blocked_producers` (#181):
222 /// that is a *forward-going* read-time tag for the activity
223 /// feed; this is a write-time gate on branch advance, retro-
224 /// active to a specific timestamp. The two compose cleanly —
225 /// `blocked_producers` filters what reviewers see; `ProducerBlock`
226 /// stops a compromised tool's history from being promoted past
227 /// a known-bad point.
228 ///
229 /// Stored at the attestation log under `stage_id == tool_id`
230 /// so the by-stage index doubles as a by-tool lookup for these
231 /// records — no schema break, no separate index needed.
232 /// `Attestation::stage_id` carries the `tool_id` for these
233 /// records; the variant payload duplicates it for clarity in
234 /// the JSON.
235 ProducerBlock {
236 tool_id: String,
237 reason: String,
238 blocked_at: u64,
239 },
240 /// Counterpart to [`AttestationKind::ProducerBlock`] (#248). The
241 /// attestation log is append-only, so revoking a producer block
242 /// is a separate, later fact rather than a delete. The branch
243 /// advance gate honors the most recent verdict for each
244 /// `tool_id` by timestamp.
245 ProducerUnblock {
246 tool_id: String,
247 reason: String,
248 unblocked_at: u64,
249 },
250 /// Auto-emitted by `Store::apply_operation_checked` when an op
251 /// is rejected for `TypeError` (#281). Records the failed op's
252 /// id, the structured type-error envelope, and an optional
253 /// suggested-transform payload (left empty by the gate; the
254 /// `lex repair --apply` flow populates it via LLM call). The
255 /// hint is attached to the candidate stage that didn't
256 /// typecheck, so `lex_vcs::AttestationLog::list_for_stage`
257 /// surfaces it on the next read.
258 ///
259 /// Schema: `errors` and `suggested_transform` are
260 /// `serde_json::Value` to keep this crate independent of
261 /// `lex-types::TypeError` (which lives downstream) and to let
262 /// the slice-2 LLM integration ship without a schema bump.
263 RepairHint {
264 failed_op_id: super::operation::OpId,
265 errors: serde_json::Value,
266 #[serde(default, skip_serializing_if = "Option::is_none")]
267 suggested_transform: Option<serde_json::Value>,
268 },
269 /// Records one iteration of `lex repair --apply` (#281). The
270 /// repair loop emits a chain of `RepairAttempt`s — one per
271 /// applied transform — so the audit trail walks the agent's
272 /// fix progression.
273 RepairAttempt {
274 hint_id: super::operation::OpId,
275 /// Outcome tag: `passed` / `failed` / `skipped`.
276 outcome: String,
277 #[serde(default, skip_serializing_if = "Option::is_none")]
278 applied_op_id: Option<super::operation::OpId>,
279 },
280 /// Positive trust signal for a producer (#293). Complement to
281 /// [`Self::ProducerBlock`]. Computed from a producer's recent
282 /// history of (passed, failed, inconclusive) attestations;
283 /// not manually set. `score_thousandths` is in `[0, 1000]`
284 /// (representing `0.0 .. 1.0`); fixed-point because
285 /// `AttestationKind` is `Eq` for content-addressed hashing,
286 /// which `f64` doesn't implement. Consumers (the
287 /// `required_attestations` gate) may waive a requirement
288 /// when the latest score for a tool exceeds a configured
289 /// threshold in `policy.required_attestations[].skip_if_producer_trust_thousandths_above`.
290 ///
291 /// Refuses to grant trust to a tool with an active
292 /// `ProducerBlock` (the hard veto wins).
293 ///
294 /// Stored under `stage_id == tool_id` so the by-stage index
295 /// doubles as a per-tool lookup — same trick `ProducerBlock`
296 /// uses.
297 ProducerTrust {
298 tool_id: String,
299 /// Score × 1000, clamped to `[0, 1000]`. Derived from
300 /// `passed / (passed + failed + inconclusive)` over the
301 /// last `window` attestations from this tool.
302 score_thousandths: u32,
303 /// Free-form reference to the evidence corpus the score
304 /// was derived from — e.g. "window=1000 as of <head_op>".
305 evidence: String,
306 granted_by: String,
307 },
308 /// Records that the `required_attestations` gate waived a
309 /// requirement because the producer's `ProducerTrust` score
310 /// exceeded the configured threshold (#293). Audit signal —
311 /// not load-bearing for gate decisions, but ensures every
312 /// skip is recoverable from the attestation log.
313 TrustWaived {
314 /// Tool whose trust score caused the waiver.
315 producer: String,
316 /// Latest score (× 1000) consulted at gate time.
317 score_thousandths: u32,
318 /// Threshold (× 1000) from the policy rule.
319 threshold_thousandths: u32,
320 /// Which required-attestation kind tag was skipped
321 /// (e.g. `spec`, `type_check`).
322 kind_tag: String,
323 },
324 /// A capsule installed cleanly under lex-os (lex-os#36 / #38).
325 /// Promotes the tamper-evident `CapsuleInstalled` record from a
326 /// `lex-os capsule install --audit-out` log into a durable,
327 /// content-addressed attestation, via `lex attest import-install`.
328 ///
329 /// In the capsule distribution model the publisher's signing key
330 /// *is* the producer identity, so these records are stored under
331 /// `stage_id == signer` **and** carry `produced_by.tool == signer`
332 /// — the same convention `ProducerBlock` / `ProducerTrust` use.
333 /// That makes a publisher's install track record feed
334 /// `recompute_producer_trust` (which scores `produced_by.tool`)
335 /// and, through it, the trusted-keys keyring that `capsule install
336 /// --trusted-keys` consumes. The loop closes: install → attestation
337 /// → earned trust → keyring → next install.
338 CapsuleInstall {
339 /// `name@version` label of the installed artifact.
340 artifact: String,
341 /// Hex SHA-256 of the published archive bytes — the
342 /// publish-time identity of exactly which bytes installed.
343 /// Empty when imported from a pre-content-hash audit log.
344 content_hash: ContentHash,
345 /// The publisher's Ed25519 public key (hex): the verified
346 /// signer of the capability contract. Duplicated from
347 /// `stage_id` / `produced_by.tool` for clarity in the JSON.
348 signer: String,
349 /// The grant the box actually ran at — `meet(consumer,
350 /// requires)`, pretty-printed.
351 effective_grant: String,
352 },
353 /// A plan-shaped decision a capability gate reached, promoted into
354 /// durable evidence by `lex attest import-apply` (#790).
355 ///
356 /// Two gates emit this fact today — `lex-iac` between `terraform
357 /// plan` and `terraform apply`, and `lex-k8s` at Kubernetes
358 /// admission — and both emit the *same* fact: a plan-shaped
359 /// artifact, checked against a manifest, decided under a signer.
360 /// The name is deliberately generic. An `InfraApply` variant would
361 /// have pushed the Kubernetes gate into minting a near-duplicate,
362 /// and a duplicate discriminant splits one producer's track record
363 /// across two kinds. Whatever differs between the gates lives in
364 /// the `gate` and `subject` fields, which are payload rather than
365 /// identity-by-variant.
366 ///
367 /// Stored under `stage_id == signer` **and** `produced_by.tool ==
368 /// signer`, the convention [`Self::CapsuleInstall`] /
369 /// [`Self::ProducerBlock`] / [`Self::ProducerTrust`] use — get it
370 /// wrong and `recompute_producer_trust`, which scores
371 /// `produced_by.tool`, silently never sees these records.
372 ///
373 /// # Refusals are part of the record
374 ///
375 /// [`AttestationResult`] carries the verdict, so a refused decision
376 /// is this same kind with `Failed { detail }`. That is not an
377 /// afterthought: producer trust is `passed / (passed + failed)`, so
378 /// a corpus of acceptances only would score every submitter 1.0 and
379 /// mean nothing. A submitter loses trust by having its refusals on
380 /// the record next to its acceptances.
381 PlanApply {
382 /// Which gate decided — `terraform`, `kubernetes`, … Free-form,
383 /// and in the payload rather than the discriminant so a third
384 /// gate needs no schema change here.
385 gate: String,
386 /// What was decided about, in the gate's own vocabulary: a
387 /// workspace, a namespaced pod name. Human-facing; may be empty
388 /// when the gate names nothing.
389 subject: String,
390 /// Hex SHA-256 of the artifact's bytes — the plan or spec the
391 /// decision was actually reached about. Load-bearing: an
392 /// acceptance authorises *these* bytes, so a substituted plan
393 /// must not match. Never empty; the importer refuses an event
394 /// without it rather than minting evidence that matches
395 /// anything.
396 artifact_sha256: ContentHash,
397 /// The identity the decision was made under — a CI pipeline
398 /// key, a ServiceAccount, an agent key. Duplicated from
399 /// `stage_id` / `produced_by.tool` for clarity in the JSON.
400 signer: String,
401 /// The manifest the artifact was checked against: the ceiling
402 /// in force at decision time.
403 manifest: String,
404 },
405 /// Replay-as-verification (#836 G3): the recorded [`Intent`] behind
406 /// an op was re-run against the op's parent state, and the
407 /// regenerated stage compared to the recorded one. Makes the
408 /// reproducibility claim concrete — "can this change be regenerated
409 /// from its recorded cause". Addressed to the op's recorded stage;
410 /// `result` maps `reproduced` onto Passed/Failed so result-based
411 /// tooling reads it. The model call itself is external (the agent
412 /// harness regenerates and hands back a candidate); this attestation
413 /// records the deterministic comparison lex performed.
414 ///
415 /// [`Intent`]: crate::Intent
416 Replay {
417 /// The stage id the op recorded producing — what a faithful
418 /// regeneration should reproduce.
419 expected_stage_id: super::operation::StageId,
420 /// The stage id the regeneration actually produced, or `None`
421 /// when the regenerator returned nothing / a non-matching sig.
422 #[serde(default, skip_serializing_if = "Option::is_none")]
423 produced_stage_id: Option<super::operation::StageId>,
424 /// Whether `produced_stage_id == expected_stage_id`.
425 reproduced: bool,
426 /// The model the recorded intent named, for audit (`None` when
427 /// the op carried no intent or the intent no model).
428 #[serde(default, skip_serializing_if = "Option::is_none")]
429 model: Option<String>,
430 },
431}
432
433/// Walk a tool's `ProducerBlock` / `ProducerUnblock` attestations
434/// and return the active block timestamp, if any (#248). The
435/// attestation log is append-only, so a tool's state is whichever
436/// `ProducerBlock` / `ProducerUnblock` record has the latest
437/// `timestamp`. Returns `Some(blocked_at)` when the latest verdict
438/// is a `ProducerBlock` and `None` when the latest is an unblock or
439/// no verdict exists.
440///
441/// Ties: a `ProducerUnblock` at the same wall-clock second as a
442/// `ProducerBlock` wins, so re-running an unblock immediately after
443/// a block leaves the tool unblocked. Mirrors the tie-breaking in
444/// [`is_stage_blocked`].
445pub fn active_producer_block(
446 attestations: &[Attestation],
447 tool_id: &str,
448) -> Option<u64> {
449 let mut latest: Option<&Attestation> = None;
450 for a in attestations {
451 let matches = match &a.kind {
452 AttestationKind::ProducerBlock { tool_id: tid, .. }
453 | AttestationKind::ProducerUnblock { tool_id: tid, .. } => tid == tool_id,
454 _ => false,
455 };
456 if !matches {
457 continue;
458 }
459 match latest {
460 None => latest = Some(a),
461 Some(prev) if a.timestamp > prev.timestamp => latest = Some(a),
462 Some(prev) if a.timestamp == prev.timestamp
463 && matches!(a.kind, AttestationKind::ProducerUnblock { .. }) =>
464 {
465 latest = Some(a);
466 }
467 _ => {}
468 }
469 }
470 match latest.map(|a| &a.kind) {
471 Some(AttestationKind::ProducerBlock { blocked_at, .. }) => Some(*blocked_at),
472 _ => None,
473 }
474}
475
476/// Stable identifier for a [`lex_trace::TraceTree`]. Mirrors the
477/// `run_id` field on the trace JSON; kept as a `String` so this
478/// crate doesn't pull `lex-trace` in.
479pub type TraceRunId = String;
480
481/// Walk a stage's attestations and return whether the latest
482/// Block/Unblock decision is currently a Block. Used by
483/// activation paths (e.g. `lex stage pin`) to refuse when a
484/// human has signalled the stage shouldn't ship.
485///
486/// "Latest" is defined by `timestamp`, which matches what users
487/// see in `lex stage <id> --attestations`. Ties go to Unblock so
488/// retrying an unblock right after a block (same wall-clock
489/// second) doesn't leave the stage stuck.
490pub fn is_stage_blocked(attestations: &[Attestation]) -> bool {
491 let mut latest: Option<&Attestation> = None;
492 for a in attestations {
493 if !matches!(a.kind, AttestationKind::Block { .. } | AttestationKind::Unblock { .. }) {
494 continue;
495 }
496 match latest {
497 None => latest = Some(a),
498 Some(prev) if a.timestamp > prev.timestamp => latest = Some(a),
499 Some(prev) if a.timestamp == prev.timestamp
500 && matches!(a.kind, AttestationKind::Unblock { .. }) =>
501 {
502 latest = Some(a);
503 }
504 _ => {}
505 }
506 }
507 matches!(latest.map(|a| &a.kind), Some(AttestationKind::Block { .. }))
508}
509
510/// Verification method for [`AttestationKind::Spec`]. Mirrors the
511/// tag the spec checker already uses — kept as a string so the
512/// vcs crate doesn't have to pull `spec-checker` in.
513#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
514#[serde(rename_all = "snake_case")]
515pub enum SpecMethod {
516 /// Exhaustive search; `trials` is unset.
517 Exhaustive,
518 /// Random sampling; `trials` carries the sample count.
519 Random,
520 /// Symbolic execution.
521 Symbolic,
522}
523
524/// Whether the verification succeeded. `Inconclusive` is its own
525/// state because some checkers (e.g. random-sampling spec checks
526/// over an unbounded input space) can pass within their budget
527/// without proving the contract holds in general.
528#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
529#[serde(tag = "result", rename_all = "snake_case")]
530pub enum AttestationResult {
531 Passed,
532 Failed { detail: String },
533 Inconclusive { detail: String },
534}
535
536/// Who produced this attestation. `tool` is the CLI / harness name
537/// (`"lex check"`, `"lex agent-tool"`, `"ci-runner@v3"`). `version`
538/// pins the tool revision so a regression in the producer is
539/// distinguishable from a regression in the code being verified.
540/// `model` is set when an LLM was the proximate producer — for
541/// `--spec`-style runs the harness is the producer; for `lex
542/// agent-tool` the model is, and we want both recorded.
543#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
544pub struct ProducerDescriptor {
545 pub tool: String,
546 pub version: String,
547 #[serde(default, skip_serializing_if = "Option::is_none")]
548 pub model: Option<String>,
549}
550
551/// Optional cost record. Excluded from the attestation hash so
552/// rerunning a verification on a different machine (different
553/// wall-clock, different token pricing) doesn't break dedup.
554#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
555pub struct Cost {
556 #[serde(default, skip_serializing_if = "Option::is_none")]
557 pub tokens_in: Option<u64>,
558 #[serde(default, skip_serializing_if = "Option::is_none")]
559 pub tokens_out: Option<u64>,
560 /// USD cents (avoid floating-point in persisted form).
561 #[serde(default, skip_serializing_if = "Option::is_none")]
562 pub usd_cents: Option<u64>,
563 #[serde(default, skip_serializing_if = "Option::is_none")]
564 pub wall_time_ms: Option<u64>,
565}
566
567/// Optional Ed25519 signature over the attestation hash. Verifying
568/// it is the consumer's job; the data layer just stores the bytes.
569#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
570pub struct Signature {
571 /// Hex-encoded Ed25519 public key.
572 pub public_key: String,
573 /// Hex-encoded signature over the lowercase-hex `attestation_id`.
574 pub signature: String,
575}
576
577/// The persisted attestation. See module docs for what each field
578/// is, what's in the hash, and what isn't.
579#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
580pub struct Attestation {
581 pub attestation_id: AttestationId,
582 pub stage_id: StageId,
583 #[serde(default, skip_serializing_if = "Option::is_none")]
584 pub op_id: Option<OpId>,
585 #[serde(default, skip_serializing_if = "Option::is_none")]
586 pub intent_id: Option<IntentId>,
587 pub kind: AttestationKind,
588 pub result: AttestationResult,
589 pub produced_by: ProducerDescriptor,
590 #[serde(default, skip_serializing_if = "Option::is_none")]
591 pub cost: Option<Cost>,
592 /// Wall-clock seconds since epoch when this attestation was
593 /// produced. Excluded from `attestation_id` so the dedup
594 /// property holds across runs.
595 pub timestamp: u64,
596 #[serde(default, skip_serializing_if = "Option::is_none")]
597 pub signature: Option<Signature>,
598}
599
600impl Attestation {
601 /// Build an attestation against a stage, computing its
602 /// content-addressed id. `timestamp` defaults to the current
603 /// wall clock; pass to [`Attestation::with_timestamp`] in tests.
604 #[allow(clippy::too_many_arguments)]
605 pub fn new(
606 stage_id: impl Into<StageId>,
607 op_id: Option<OpId>,
608 intent_id: Option<IntentId>,
609 kind: AttestationKind,
610 result: AttestationResult,
611 produced_by: ProducerDescriptor,
612 cost: Option<Cost>,
613 ) -> Self {
614 let now = SystemTime::now()
615 .duration_since(UNIX_EPOCH)
616 .map(|d| d.as_secs())
617 .unwrap_or(0);
618 Self::with_timestamp(stage_id, op_id, intent_id, kind, result, produced_by, cost, now)
619 }
620
621 /// Build an attestation with a caller-controlled `timestamp`.
622 /// Used in tests to keep golden hashes stable.
623 #[allow(clippy::too_many_arguments)]
624 pub fn with_timestamp(
625 stage_id: impl Into<StageId>,
626 op_id: Option<OpId>,
627 intent_id: Option<IntentId>,
628 kind: AttestationKind,
629 result: AttestationResult,
630 produced_by: ProducerDescriptor,
631 cost: Option<Cost>,
632 timestamp: u64,
633 ) -> Self {
634 let stage_id = stage_id.into();
635 let attestation_id = compute_attestation_id(
636 &stage_id,
637 op_id.as_deref(),
638 intent_id.as_deref(),
639 &kind,
640 &result,
641 &produced_by,
642 );
643 Self {
644 attestation_id,
645 stage_id,
646 op_id,
647 intent_id,
648 kind,
649 result,
650 produced_by,
651 cost,
652 timestamp,
653 signature: None,
654 }
655 }
656
657 /// Attach a signature. The signature is not part of the hash;
658 /// the same logical attestation produced by an unsigned harness
659 /// dedupes against a signed one. Callers who *want* signature
660 /// to be part of identity should hash signature into the
661 /// `produced_by.tool` string explicitly.
662 pub fn with_signature(mut self, signature: Signature) -> Self {
663 self.signature = Some(signature);
664 self
665 }
666}
667
668fn compute_attestation_id(
669 stage_id: &str,
670 op_id: Option<&str>,
671 intent_id: Option<&str>,
672 kind: &AttestationKind,
673 result: &AttestationResult,
674 produced_by: &ProducerDescriptor,
675) -> AttestationId {
676 let view = CanonicalAttestationView {
677 stage_id,
678 op_id,
679 intent_id,
680 kind,
681 result,
682 produced_by,
683 };
684 canonical::hash(&view)
685}
686
687/// Hashable shadow of [`Attestation`] omitting the fields we
688/// deliberately exclude from identity (`attestation_id`, `cost`,
689/// `timestamp`, `signature`). Lives only as a transient.
690#[derive(Serialize)]
691struct CanonicalAttestationView<'a> {
692 stage_id: &'a str,
693 #[serde(skip_serializing_if = "Option::is_none")]
694 op_id: Option<&'a str>,
695 #[serde(skip_serializing_if = "Option::is_none")]
696 intent_id: Option<&'a str>,
697 kind: &'a AttestationKind,
698 result: &'a AttestationResult,
699 produced_by: &'a ProducerDescriptor,
700}
701
702// ---- Persistence -------------------------------------------------
703
704/// Persistent log of [`Attestation`] records.
705///
706/// Mirrors [`crate::OpLog`] / [`crate::IntentLog`] in shape: one
707/// canonical-JSON file per attestation, atomic writes via tempfile +
708/// rename, idempotent on re-puts. Maintains two secondary indices
709/// for cheap reverse lookups:
710///
711/// * `by-stage/<StageId>/<AttestationId>` — every attestation,
712/// indexed by the stage it records evidence for.
713/// * `by-run/<TraceRunId>/<AttestationId>` (#246) — only
714/// `AttestationKind::Trace` entries are indexed here, so
715/// `list_for_run` is `O(traces of that run)` rather than scanning
716/// the whole log.
717pub struct AttestationLog {
718 dir: PathBuf,
719 by_stage: PathBuf,
720 by_run: PathBuf,
721}
722
723impl AttestationLog {
724 pub fn open(root: &Path) -> io::Result<Self> {
725 let dir = root.join("attestations");
726 let by_stage = dir.join("by-stage");
727 let by_run = dir.join("by-run");
728 fs::create_dir_all(&by_stage)?;
729 fs::create_dir_all(&by_run)?;
730 Ok(Self { dir, by_stage, by_run })
731 }
732
733 fn primary_path(&self, id: &AttestationId) -> PathBuf {
734 self.dir.join(format!("{id}.json"))
735 }
736
737 /// Persist an attestation. Idempotent on existing ids — content
738 /// addressing guarantees the same logical attestation produces
739 /// the same id, so re-putting is a no-op for the primary file.
740 /// The by-stage index is also re-written idempotently.
741 pub fn put(&self, attestation: &Attestation) -> io::Result<()> {
742 let primary = self.primary_path(&attestation.attestation_id);
743 if !primary.exists() {
744 let bytes = serde_json::to_vec(attestation)
745 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
746 let tmp = primary.with_extension("json.tmp");
747 let mut f = fs::File::create(&tmp)?;
748 f.write_all(&bytes)?;
749 f.sync_all()?;
750 fs::rename(&tmp, &primary)?;
751 }
752 // Index entry: empty marker file. Reading the index is a
753 // directory listing; resolving each entry is a primary-file
754 // read by id.
755 let stage_dir = self.by_stage.join(&attestation.stage_id);
756 fs::create_dir_all(&stage_dir)?;
757 let idx = stage_dir.join(&attestation.attestation_id);
758 if !idx.exists() {
759 fs::File::create(&idx)?;
760 }
761 // by-run secondary index for Trace attestations (#246) —
762 // only the variants that carry a `run_id` are indexed; every
763 // other kind skips this directory entirely.
764 if let AttestationKind::Trace { run_id, .. } = &attestation.kind {
765 let run_dir = self.by_run.join(run_id);
766 fs::create_dir_all(&run_dir)?;
767 let idx = run_dir.join(&attestation.attestation_id);
768 if !idx.exists() {
769 fs::File::create(&idx)?;
770 }
771 }
772 Ok(())
773 }
774
775 /// Remove an attestation from the log along with both index
776 /// entries (#258). Idempotent on missing files.
777 ///
778 /// **Not** part of the day-to-day API — the attestation log is
779 /// append-only by design (#132). The only legitimate caller is
780 /// the migration tool, which supervises a destructive,
781 /// `--confirm`-gated batch.
782 pub fn delete(&self, attestation: &Attestation) -> io::Result<()> {
783 let primary = self.primary_path(&attestation.attestation_id);
784 match fs::remove_file(&primary) {
785 Ok(()) | Err(_) => {} // best-effort; missing is fine
786 }
787 let stage_idx = self.by_stage
788 .join(&attestation.stage_id)
789 .join(&attestation.attestation_id);
790 let _ = fs::remove_file(&stage_idx);
791 if let AttestationKind::Trace { run_id, .. } = &attestation.kind {
792 let run_idx = self.by_run.join(run_id).join(&attestation.attestation_id);
793 let _ = fs::remove_file(&run_idx);
794 }
795 Ok(())
796 }
797
798 pub fn get(&self, id: &AttestationId) -> io::Result<Option<Attestation>> {
799 let path = self.primary_path(id);
800 if !path.exists() {
801 return Ok(None);
802 }
803 let bytes = fs::read(&path)?;
804 let attestation: Attestation = serde_json::from_slice(&bytes)
805 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
806 Ok(Some(attestation))
807 }
808
809 /// Enumerate every attestation in the log. Walks
810 /// `<root>/attestations/*.json` directly — no per-stage index
811 /// — so cost is `O(total attestations)`. Used by `lex attest
812 /// filter` for CI / dashboard queries that span stages.
813 /// Order is not stable; callers that need stable ordering
814 /// should sort by `timestamp` or `attestation_id`.
815 pub fn list_all(&self) -> io::Result<Vec<Attestation>> {
816 let mut out = Vec::new();
817 if !self.dir.exists() {
818 return Ok(out);
819 }
820 for entry in fs::read_dir(&self.dir)? {
821 let entry = entry?;
822 let p = entry.path();
823 // Skip the by-stage/ subdir and the .tmp staging files
824 // a crashed put might have left behind.
825 if p.is_dir() {
826 continue;
827 }
828 if p.extension().is_none_or(|e| e != "json") {
829 continue;
830 }
831 let bytes = fs::read(&p)?;
832 // A corrupt primary file shouldn't take down a filter
833 // query — log to stderr and skip.
834 match serde_json::from_slice::<Attestation>(&bytes) {
835 Ok(att) => out.push(att),
836 Err(e) => eprintln!(
837 "warning: skipping unreadable attestation {}: {e}",
838 p.display()
839 ),
840 }
841 }
842 Ok(out)
843 }
844
845 /// Enumerate attestations for a given stage. Order is not
846 /// stable across calls (it follows directory iteration order).
847 /// Callers that need a stable ordering should sort by
848 /// `timestamp` or `attestation_id`.
849 pub fn list_for_stage(&self, stage_id: &StageId) -> io::Result<Vec<Attestation>> {
850 let stage_dir = self.by_stage.join(stage_id);
851 if !stage_dir.exists() {
852 return Ok(Vec::new());
853 }
854 let mut out = Vec::new();
855 for entry in fs::read_dir(&stage_dir)? {
856 let entry = entry?;
857 let id = match entry.file_name().into_string() {
858 Ok(s) => s,
859 Err(_) => continue,
860 };
861 if let Some(att) = self.get(&id)? {
862 out.push(att);
863 }
864 }
865 Ok(out)
866 }
867
868 /// Enumerate `AttestationKind::Trace` entries for a given
869 /// `run_id` (#246). Walks the `by-run/<run_id>/` directory; cost
870 /// is `O(trace attestations for that run)`, typically 1.
871 /// Returns an empty vec if the run has no Trace attestations.
872 /// Order is not stable.
873 pub fn list_for_run(&self, run_id: &TraceRunId) -> io::Result<Vec<Attestation>> {
874 let run_dir = self.by_run.join(run_id);
875 if !run_dir.exists() {
876 return Ok(Vec::new());
877 }
878 let mut out = Vec::new();
879 for entry in fs::read_dir(&run_dir)? {
880 let entry = entry?;
881 let id = match entry.file_name().into_string() {
882 Ok(s) => s,
883 Err(_) => continue,
884 };
885 if let Some(att) = self.get(&id)? {
886 out.push(att);
887 }
888 }
889 Ok(out)
890 }
891}
892
893// ---- Tests --------------------------------------------------------
894
895#[cfg(test)]
896mod tests {
897 use super::*;
898
899 fn ci_runner() -> ProducerDescriptor {
900 ProducerDescriptor {
901 tool: "lex check".into(),
902 version: "0.1.0".into(),
903 model: None,
904 }
905 }
906
907 fn typecheck_passed() -> Attestation {
908 Attestation::with_timestamp(
909 "stage-abc",
910 Some("op-123".into()),
911 None,
912 AttestationKind::TypeCheck,
913 AttestationResult::Passed,
914 ci_runner(),
915 None,
916 1000,
917 )
918 }
919
920 #[test]
921 fn same_logical_verification_hashes_equal() {
922 // Dedup invariant: same stage, same kind, same producer,
923 // same outcome → same `attestation_id` regardless of
924 // wall-clock or cost.
925 let a = typecheck_passed();
926 let b = Attestation::with_timestamp(
927 "stage-abc",
928 Some("op-123".into()),
929 None,
930 AttestationKind::TypeCheck,
931 AttestationResult::Passed,
932 ci_runner(),
933 Some(Cost {
934 tokens_in: Some(0),
935 tokens_out: Some(0),
936 usd_cents: Some(0),
937 wall_time_ms: Some(42),
938 }),
939 99999,
940 );
941 assert_eq!(a.attestation_id, b.attestation_id);
942 }
943
944 #[test]
945 fn different_stages_hash_differently() {
946 let a = typecheck_passed();
947 let b = Attestation::with_timestamp(
948 "stage-XYZ",
949 Some("op-123".into()),
950 None,
951 AttestationKind::TypeCheck,
952 AttestationResult::Passed,
953 ci_runner(),
954 None,
955 1000,
956 );
957 assert_ne!(a.attestation_id, b.attestation_id);
958 }
959
960 #[test]
961 fn different_op_ids_hash_differently() {
962 let a = typecheck_passed();
963 let b = Attestation::with_timestamp(
964 "stage-abc",
965 Some("op-XYZ".into()),
966 None,
967 AttestationKind::TypeCheck,
968 AttestationResult::Passed,
969 ci_runner(),
970 None,
971 1000,
972 );
973 assert_ne!(a.attestation_id, b.attestation_id);
974 }
975
976 #[test]
977 fn different_intents_hash_differently() {
978 let a = Attestation::with_timestamp(
979 "stage-abc", None,
980 Some("intent-A".into()),
981 AttestationKind::TypeCheck, AttestationResult::Passed,
982 ci_runner(), None, 1000,
983 );
984 let b = Attestation::with_timestamp(
985 "stage-abc", None,
986 Some("intent-B".into()),
987 AttestationKind::TypeCheck, AttestationResult::Passed,
988 ci_runner(), None, 1000,
989 );
990 assert_ne!(a.attestation_id, b.attestation_id);
991 }
992
993 #[test]
994 fn different_kinds_hash_differently() {
995 let a = typecheck_passed();
996 let b = Attestation::with_timestamp(
997 "stage-abc",
998 Some("op-123".into()),
999 None,
1000 AttestationKind::EffectAudit,
1001 AttestationResult::Passed,
1002 ci_runner(),
1003 None,
1004 1000,
1005 );
1006 assert_ne!(a.attestation_id, b.attestation_id);
1007 }
1008
1009 #[test]
1010 fn passed_vs_failed_hash_differently() {
1011 // Critical: a Failed attestation must not collide with a
1012 // Passed one for the same logical verification. Otherwise
1013 // a flaky producer could overwrite the negative evidence
1014 // by re-running and getting Passed.
1015 let a = typecheck_passed();
1016 let b = Attestation::with_timestamp(
1017 "stage-abc",
1018 Some("op-123".into()),
1019 None,
1020 AttestationKind::TypeCheck,
1021 AttestationResult::Failed { detail: "arity mismatch".into() },
1022 ci_runner(),
1023 None,
1024 1000,
1025 );
1026 assert_ne!(a.attestation_id, b.attestation_id);
1027 }
1028
1029 #[test]
1030 fn different_producers_hash_differently() {
1031 let a = typecheck_passed();
1032 let mut other = ci_runner();
1033 other.tool = "third-party-runner".into();
1034 let b = Attestation::with_timestamp(
1035 "stage-abc",
1036 Some("op-123".into()),
1037 None,
1038 AttestationKind::TypeCheck,
1039 AttestationResult::Passed,
1040 other,
1041 None,
1042 1000,
1043 );
1044 assert_ne!(
1045 a.attestation_id, b.attestation_id,
1046 "an attestation from a different producer is a different fact",
1047 );
1048 }
1049
1050 #[test]
1051 fn signature_is_excluded_from_hash() {
1052 // A signed and unsigned attestation of the same logical
1053 // fact must dedupe. Otherwise late-signing a record would
1054 // create two attestations that say the same thing.
1055 let a = typecheck_passed();
1056 let b = typecheck_passed().with_signature(Signature {
1057 public_key: "ed25519:fffe".into(),
1058 signature: "0xabcd".into(),
1059 });
1060 assert_eq!(a.attestation_id, b.attestation_id);
1061 }
1062
1063 #[test]
1064 fn attestation_id_is_64_char_lowercase_hex() {
1065 let a = typecheck_passed();
1066 assert_eq!(a.attestation_id.len(), 64);
1067 assert!(a
1068 .attestation_id
1069 .chars()
1070 .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)));
1071 }
1072
1073 #[test]
1074 fn round_trip_through_serde_json() {
1075 let a = Attestation::with_timestamp(
1076 "stage-abc",
1077 Some("op-123".into()),
1078 Some("intent-A".into()),
1079 AttestationKind::Spec {
1080 spec_id: "clamp.spec".into(),
1081 method: SpecMethod::Random,
1082 trials: Some(1000),
1083 },
1084 AttestationResult::Passed,
1085 ProducerDescriptor {
1086 tool: "lex agent-tool".into(),
1087 version: "0.1.0".into(),
1088 model: Some("claude-opus-4-7".into()),
1089 },
1090 Some(Cost {
1091 tokens_in: Some(1234),
1092 tokens_out: Some(567),
1093 usd_cents: Some(2),
1094 wall_time_ms: Some(3400),
1095 }),
1096 99,
1097 )
1098 .with_signature(Signature {
1099 public_key: "ed25519:abc".into(),
1100 signature: "0x1234".into(),
1101 });
1102 let json = serde_json::to_string(&a).unwrap();
1103 let back: Attestation = serde_json::from_str(&json).unwrap();
1104 assert_eq!(a, back);
1105 }
1106
1107 /// Golden hash. If this changes, the canonical form has shifted
1108 /// — every `AttestationId` in every existing store has changed
1109 /// too. Update with care; same protective shape as the
1110 /// `Operation` and `Intent` golden tests.
1111 #[test]
1112 fn canonical_form_is_stable_for_a_known_input() {
1113 let a = Attestation::with_timestamp(
1114 "stage-abc",
1115 Some("op-123".into()),
1116 None,
1117 AttestationKind::TypeCheck,
1118 AttestationResult::Passed,
1119 ProducerDescriptor {
1120 tool: "lex check".into(),
1121 version: "0.1.0".into(),
1122 model: None,
1123 },
1124 None,
1125 0,
1126 );
1127 assert_eq!(
1128 a.attestation_id,
1129 "a4ef921f7bb0db70779c5b698cda1744d49165a4a56aa8414bdbafc85bcbc16b",
1130 "canonical-form regression: the AttestationId for a known input changed",
1131 );
1132 }
1133
1134 // ---- AttestationLog ----
1135
1136 #[test]
1137 fn log_round_trips_through_disk() {
1138 let tmp = tempfile::tempdir().unwrap();
1139 let log = AttestationLog::open(tmp.path()).unwrap();
1140 let a = typecheck_passed();
1141 log.put(&a).unwrap();
1142 let read_back = log.get(&a.attestation_id).unwrap().unwrap();
1143 assert_eq!(a, read_back);
1144 }
1145
1146 #[test]
1147 fn log_get_unknown_returns_none() {
1148 let tmp = tempfile::tempdir().unwrap();
1149 let log = AttestationLog::open(tmp.path()).unwrap();
1150 assert!(log
1151 .get(&"nonexistent".to_string())
1152 .unwrap()
1153 .is_none());
1154 }
1155
1156 #[test]
1157 fn log_put_is_idempotent() {
1158 let tmp = tempfile::tempdir().unwrap();
1159 let log = AttestationLog::open(tmp.path()).unwrap();
1160 let a = typecheck_passed();
1161 log.put(&a).unwrap();
1162 log.put(&a).unwrap();
1163 let read_back = log.get(&a.attestation_id).unwrap().unwrap();
1164 assert_eq!(a, read_back);
1165 }
1166
1167 #[test]
1168 fn list_for_stage_returns_only_that_stage() {
1169 let tmp = tempfile::tempdir().unwrap();
1170 let log = AttestationLog::open(tmp.path()).unwrap();
1171
1172 let on_abc_1 = typecheck_passed();
1173 let on_abc_2 = Attestation::with_timestamp(
1174 "stage-abc",
1175 Some("op-123".into()),
1176 None,
1177 AttestationKind::EffectAudit,
1178 AttestationResult::Passed,
1179 ci_runner(),
1180 None,
1181 2000,
1182 );
1183 let on_xyz = Attestation::with_timestamp(
1184 "stage-xyz",
1185 Some("op-456".into()),
1186 None,
1187 AttestationKind::TypeCheck,
1188 AttestationResult::Passed,
1189 ci_runner(),
1190 None,
1191 1000,
1192 );
1193
1194 log.put(&on_abc_1).unwrap();
1195 log.put(&on_abc_2).unwrap();
1196 log.put(&on_xyz).unwrap();
1197
1198 let mut on_abc = log.list_for_stage(&"stage-abc".to_string()).unwrap();
1199 on_abc.sort_by_key(|a| a.timestamp);
1200 assert_eq!(on_abc.len(), 2);
1201 assert_eq!(on_abc[0], on_abc_1);
1202 assert_eq!(on_abc[1], on_abc_2);
1203
1204 let on_xyz_listed = log.list_for_stage(&"stage-xyz".to_string()).unwrap();
1205 assert_eq!(on_xyz_listed.len(), 1);
1206 assert_eq!(on_xyz_listed[0], on_xyz);
1207 }
1208
1209 #[test]
1210 fn list_for_unknown_stage_is_empty() {
1211 let tmp = tempfile::tempdir().unwrap();
1212 let log = AttestationLog::open(tmp.path()).unwrap();
1213 let v = log.list_for_stage(&"never-attested".to_string()).unwrap();
1214 assert!(v.is_empty());
1215 }
1216
1217 #[test]
1218 fn list_all_returns_every_persisted_attestation() {
1219 // Cross-stage enumeration: `list_all` walks the primary
1220 // directory regardless of stage, so a CI / dashboard query
1221 // can filter across the whole log without iterating the
1222 // by-stage index.
1223 let tmp = tempfile::tempdir().unwrap();
1224 let log = AttestationLog::open(tmp.path()).unwrap();
1225 let on_abc = typecheck_passed();
1226 let on_xyz = Attestation::with_timestamp(
1227 "stage-xyz",
1228 Some("op-456".into()),
1229 None,
1230 AttestationKind::TypeCheck,
1231 AttestationResult::Passed,
1232 ci_runner(),
1233 None,
1234 2000,
1235 );
1236 log.put(&on_abc).unwrap();
1237 log.put(&on_xyz).unwrap();
1238 let mut all = log.list_all().unwrap();
1239 all.sort_by_key(|a| a.attestation_id.clone());
1240 assert_eq!(all.len(), 2);
1241 let ids: BTreeSet<_> = all.iter().map(|a| a.attestation_id.clone()).collect();
1242 assert!(ids.contains(&on_abc.attestation_id));
1243 assert!(ids.contains(&on_xyz.attestation_id));
1244 }
1245
1246 #[test]
1247 fn list_all_on_empty_log_is_empty() {
1248 let tmp = tempfile::tempdir().unwrap();
1249 let log = AttestationLog::open(tmp.path()).unwrap();
1250 let v = log.list_all().unwrap();
1251 assert!(v.is_empty());
1252 }
1253
1254 #[test]
1255 fn passed_and_failed_for_same_stage_both_persist() {
1256 // Failure attestations are evidence too; they must not be
1257 // overwritten by a later passing attestation. The hash
1258 // distinction (tested above) plus the by-stage listing
1259 // should keep both visible.
1260 let tmp = tempfile::tempdir().unwrap();
1261 let log = AttestationLog::open(tmp.path()).unwrap();
1262
1263 let passed = typecheck_passed();
1264 let failed = Attestation::with_timestamp(
1265 "stage-abc",
1266 Some("op-123".into()),
1267 None,
1268 AttestationKind::TypeCheck,
1269 AttestationResult::Failed { detail: "arity mismatch".into() },
1270 ci_runner(),
1271 None,
1272 500,
1273 );
1274
1275 log.put(&failed).unwrap();
1276 log.put(&passed).unwrap();
1277
1278 let listing = log.list_for_stage(&"stage-abc".to_string()).unwrap();
1279 assert_eq!(listing.len(), 2, "both passing and failing evidence must persist");
1280 }
1281
1282 fn human_decision(kind: AttestationKind, ts: u64) -> Attestation {
1283 Attestation::with_timestamp(
1284 "stage-abc",
1285 None, None,
1286 kind,
1287 AttestationResult::Passed,
1288 ProducerDescriptor {
1289 tool: "lex stage".into(),
1290 version: "0.1.0".into(),
1291 model: None,
1292 },
1293 None,
1294 ts,
1295 )
1296 }
1297
1298 #[test]
1299 fn is_stage_blocked_empty_log_is_false() {
1300 assert!(!is_stage_blocked(&[]));
1301 }
1302
1303 #[test]
1304 fn is_stage_blocked_only_unrelated_attestations() {
1305 // TypeCheck/Override attestations don't gate activation —
1306 // only Block/Unblock do.
1307 let attestations = vec![
1308 typecheck_passed(),
1309 human_decision(
1310 AttestationKind::Override {
1311 actor: "alice".into(),
1312 reason: "ship".into(),
1313 target_attestation_id: None,
1314 },
1315 500,
1316 ),
1317 ];
1318 assert!(!is_stage_blocked(&attestations));
1319 }
1320
1321 #[test]
1322 fn is_stage_blocked_block_alone_blocks() {
1323 let attestations = vec![human_decision(
1324 AttestationKind::Block { actor: "alice".into(), reason: "x".into() },
1325 500,
1326 )];
1327 assert!(is_stage_blocked(&attestations));
1328 }
1329
1330 #[test]
1331 fn is_stage_blocked_later_unblock_clears_block() {
1332 let attestations = vec![
1333 human_decision(
1334 AttestationKind::Block { actor: "alice".into(), reason: "x".into() },
1335 500,
1336 ),
1337 human_decision(
1338 AttestationKind::Unblock { actor: "alice".into(), reason: "ok".into() },
1339 600,
1340 ),
1341 ];
1342 assert!(!is_stage_blocked(&attestations));
1343 }
1344
1345 #[test]
1346 fn is_stage_blocked_later_block_re_blocks() {
1347 let attestations = vec![
1348 human_decision(
1349 AttestationKind::Block { actor: "a".into(), reason: "1".into() },
1350 500,
1351 ),
1352 human_decision(
1353 AttestationKind::Unblock { actor: "a".into(), reason: "2".into() },
1354 600,
1355 ),
1356 human_decision(
1357 AttestationKind::Block { actor: "a".into(), reason: "3".into() },
1358 700,
1359 ),
1360 ];
1361 assert!(is_stage_blocked(&attestations));
1362 }
1363
1364 #[test]
1365 fn is_stage_blocked_unblock_wins_at_same_timestamp() {
1366 // Tie-break favours Unblock so a hasty re-attempt at the
1367 // same wall-clock second can't strand the stage.
1368 let attestations = vec![
1369 human_decision(
1370 AttestationKind::Block { actor: "a".into(), reason: "1".into() },
1371 500,
1372 ),
1373 human_decision(
1374 AttestationKind::Unblock { actor: "a".into(), reason: "2".into() },
1375 500,
1376 ),
1377 ];
1378 assert!(!is_stage_blocked(&attestations));
1379 }
1380}