Skip to main content

g8_obligations/
lib.rs

1//! `g8-obligations` — typed obligation-checker backends for `g8 check`.
2//!
3//! Executes the 27-obligation self-audit (`specs/obligations-v0.1.json`)
4//! against g8's own repository. Every obligation resolves to a member of a
5//! **closed Rust enum** of checker backends with structured, typed arguments
6//! — see [`backend::CheckerBackend`]. There is no `shell_command: String`
7//! field anywhere in this crate (`specs/obligation-checker-contract.md` §0).
8//!
9//! # Deterministic zone
10//!
11//! No LLM calls, no network, no unseeded randomness. Subprocess calls to
12//! `cargo`/`ast-grep`/`rg`/`current_exe()` are the same class of dependency
13//! `g8-extractor` already has on `ast-grep`.
14//!
15//! # `G8CheckContract` design note (contract §8)
16//!
17//! §8 describes this backend's implementation in terms of
18//! `g8_core::contract::CheckPayload`/`CheckError` — types that do not exist
19//! yet. Their relocation from `crates/g8/src/render/json.rs` into
20//! `g8-core` is explicitly T5's job ("a small, precisely-scoped refactor for
21//! T5... not something I am doing here" — contract §8 point 1), and
22//! `g8-core`/`g8` are both outside this crate's writable (and, for
23//! `g8`, even dependency-able) scope. Since T3 runs before T5 in the
24//! plan's dependency order, those types cannot exist yet when this code is
25//! written.
26//!
27//! This crate's [`exec::check_contract`] therefore validates against a
28//! `serde_json::Value` shape seam instead of the not-yet-relocated concrete
29//! types: it builds the check-contract envelope directly (mirroring exactly
30//! what `render_check`/`render_check_enforcement_disabled` in
31//! `crates/g8/src/render/json.rs` produce today, and what
32//! `CLAUDE.md`'s locked "Output contract" section documents), using the
33//! REAL `g8_store::{PairingError, PairingErrorReason}` types (already
34//! `Serialize`, already living in the allowed `g8-store` dependency — no
35//! relocation needed for those) for the `errors[]` array. This keeps the
36//! backend's trust tier honestly `Verified` (it runs `g8-store`'s real
37//! `pairing_check` against a real in-memory `RusqliteStore`, not a hollow
38//! shape assertion) while depending on nothing that doesn't exist today.
39//! Once T5 relocates `CheckPayload`/`CheckError`, this seam continues to
40//! work unchanged — it was never coupled to their Rust type identity, only
41//! to the JSON shape they serialize to.
42//!
43//! # Receipt mode (contract addendum, o-g8-receipts-20260721)
44//!
45//! `Signal.wiring == "action_receipt"` declares an obligation's subject is a
46//! parsed *action receipt*, not the repository. [`run_obligations`]'s
47//! `receipt` parameter selects the choke point:
48//!
49//! - `receipt = None` (repo mode): receipt-wired obligations are **not
50//!   executed** — they surface as `status = Unknown` with
51//!   `evidence.detail.scope = "action_receipt"` and are exempt from gate
52//!   classification (their choke point is elsewhere; a green repo stays
53//!   green). Repo-wired obligations run exactly as before this addendum.
54//! - `receipt = Some(subject)` (receipt mode): *only* receipt-wired
55//!   obligations run, against `subject`; repo-wired obligations are skipped
56//!   entirely (excluded from the returned `Vec`, not represented).
57//!
58//! Subject binding is validated either way: a receipt-wired obligation may
59//! only contain `receipt_query` checks, and `receipt_query` may not appear
60//! in a repo-wired obligation. A violation is `ObligationStatus::Error`
61//! (loud, gates) rather than a silent skip.
62
63pub mod artifact;
64pub mod backend;
65mod exec;
66pub mod hashing;
67mod proc;
68pub mod result;
69mod scratch;
70
71use std::path::{Path, PathBuf};
72use std::time::Instant;
73
74pub use artifact::{
75    load_artifact, Obligation, ObligationArtifact, ObligationChecker, ObligationsError, Signal,
76};
77pub use backend::*;
78pub use exec::attestation::{
79    attestation_sidecar_path, load_attestation_sidecar, AttestationClaim, AttestationError,
80    AttestationRecord, AttestationSidecar, ATTESTATIONS_RELATIVE_PATH,
81    STALE_ATTESTATION_CLASSIFICATION,
82};
83pub use result::*;
84
85/// The `signal.wiring` value that binds an obligation to the receipt choke
86/// point (contract addendum, o-g8-receipts-20260721 §1). Every other
87/// (or absent/default) wiring value is repo-wired.
88pub const ACTION_RECEIPT_WIRING: &str = "action_receipt";
89
90/// A parsed, content-hashed action receipt — the subject `receipt_query`
91/// checks evaluate against. Built exactly once per `g8 check --receipt`
92/// invocation via [`load_receipt_subject`] and threaded through
93/// [`run_obligations`], never re-parsed per obligation.
94#[derive(Debug, Clone)]
95pub struct ReceiptSubject {
96    /// The path exactly as given to `g8 check --receipt`, for
97    /// self-evidencing JSON output (`render_check`'s `receipt.path`) — not
98    /// necessarily canonicalized.
99    pub display_path: String,
100    /// `sha256:<hex>` of the receipt file's raw bytes (same `sha256:`-prefixed
101    /// form [`hashing::sha256_file`] produces elsewhere in this crate).
102    pub sha256: String,
103    /// The parsed receipt document.
104    pub value: serde_json::Value,
105}
106
107/// Failure to load a receipt file into a [`ReceiptSubject`]. Carries the
108/// SHA-256 when one could still be computed (contract: "even a malformed
109/// receipt's hash is meaningful evidence of exactly what bad input was
110/// rejected") — only a wholly unreadable file has none.
111#[derive(Debug, thiserror::Error)]
112pub enum ReceiptSubjectError {
113    #[error("cannot hash receipt file {path}: {source}")]
114    Hash {
115        path: PathBuf,
116        #[source]
117        source: hashing::HashingError,
118    },
119    #[error("cannot read receipt file {path}: {source}")]
120    Read {
121        path: PathBuf,
122        #[source]
123        source: std::io::Error,
124    },
125    #[error("receipt file {path} is not valid JSON (sha256 {sha256}): {source}")]
126    Json {
127        path: PathBuf,
128        sha256: String,
129        #[source]
130        source: serde_json::Error,
131    },
132}
133
134impl ReceiptSubjectError {
135    /// The receipt's content hash, if loading got far enough to compute one.
136    pub fn sha256(&self) -> Option<&str> {
137        match self {
138            ReceiptSubjectError::Json { sha256, .. } => Some(sha256),
139            ReceiptSubjectError::Hash { .. } | ReceiptSubjectError::Read { .. } => None,
140        }
141    }
142}
143
144/// Parse+hash one receipt file. The file is hashed first (so a merely
145/// malformed-JSON receipt — the file exists and is readable — still yields a
146/// real `sha256` on its `Err`), then parsed as JSON.
147pub fn load_receipt_subject(path: &Path) -> Result<ReceiptSubject, ReceiptSubjectError> {
148    let sha256 = hashing::sha256_file(path).map_err(|source| ReceiptSubjectError::Hash {
149        path: path.to_path_buf(),
150        source,
151    })?;
152    let text = std::fs::read_to_string(path).map_err(|source| ReceiptSubjectError::Read {
153        path: path.to_path_buf(),
154        source,
155    })?;
156    let value: serde_json::Value =
157        serde_json::from_str(&text).map_err(|source| ReceiptSubjectError::Json {
158            path: path.to_path_buf(),
159            sha256: sha256.clone(),
160            source,
161        })?;
162    Ok(ReceiptSubject {
163        display_path: path.display().to_string(),
164        sha256,
165        value,
166    })
167}
168
169/// The one entry point. Never panics; a single backend crashing surfaces as
170/// that one obligation's `status = Error`, not a propagated panic — every
171/// backend invocation is isolated (caught, not just `?`-propagated).
172///
173/// `receipt` selects the choke point (module docs above): `None` runs the
174/// repo-wired obligations (unchanged behavior pre-dating this addendum);
175/// `Some(subject)` runs only the `action_receipt`-wired obligations, against
176/// `subject`.
177///
178/// Opens tracing span `obligations.run_all` (fields: `artifact_version`,
179/// `obligations_count`, `duration_ms`) per SPEC Principle 6 / the P6-01 span
180/// table — flagged in contract §4.1 as a gap in ARCHITECTURE.md §12's
181/// existing 9-span inventory that needs a 10th row; no task in the current
182/// plan has ARCHITECTURE.md in scope to add it, so the span is opened here
183/// (harmless, forward-compatible) but the table itself is not this crate's
184/// to edit.
185#[tracing::instrument(skip(artifact, workspace_root, receipt), fields(obligations_count = artifact.obligations.len()))]
186pub fn run_obligations(
187    artifact: &ObligationArtifact,
188    workspace_root: &Path,
189    receipt: Option<&ReceiptSubject>,
190) -> Vec<ObligationResult> {
191    let run_start = Instant::now();
192    let attestations = exec::attestation::load_for_run(workspace_root);
193    let results: Vec<ObligationResult> = artifact
194        .obligations
195        .iter()
196        .filter_map(|o| run_one_scoped(o, workspace_root, &attestations, receipt))
197        .collect();
198    tracing::debug!(
199        duration_ms = run_start.elapsed().as_millis() as u64,
200        "obligations.run_all"
201    );
202    results
203}
204
205/// Scope-filtering pass (contract addendum §1): decides, per obligation,
206/// whether THIS run (repo mode vs. receipt mode) executes it at all, and if
207/// so, with what wiring/subject. Returns `None` to mean "excluded from this
208/// run's results entirely" (repo-wired obligations in receipt mode) — the
209/// only such case; every other combination produces a real result (either an
210/// executed check or the receipt-scoped `Unknown` placeholder).
211fn run_one_scoped(
212    obligation: &Obligation,
213    workspace_root: &Path,
214    attestations: &exec::attestation::LoadedAttestations,
215    receipt: Option<&ReceiptSubject>,
216) -> Option<ObligationResult> {
217    let wiring_is_receipt = obligation
218        .signal
219        .as_ref()
220        .map(|signal| signal.wiring == ACTION_RECEIPT_WIRING)
221        .unwrap_or(false);
222
223    match (receipt, wiring_is_receipt) {
224        // Repo mode, receipt-wired: different choke point, not executed here.
225        (None, true) => Some(receipt_scoped_unknown_result(&obligation.id)),
226        // Repo mode, repo-wired: unchanged pre-addendum behavior.
227        (None, false) => Some(run_one(
228            obligation,
229            workspace_root,
230            attestations,
231            false,
232            None,
233        )),
234        // Receipt mode, receipt-wired: the whole point of this run.
235        (Some(subject), true) => Some(run_one(
236            obligation,
237            workspace_root,
238            attestations,
239            true,
240            Some(subject),
241        )),
242        // Receipt mode, repo-wired: different choke point, excluded entirely.
243        (Some(_), false) => None,
244    }
245}
246
247/// The repo-mode placeholder for a receipt-wired obligation (contract
248/// addendum §1): `status = Unknown`, `detail.scope = "action_receipt"` — the
249/// literal marker `g8`'s enforcement classifier keys off of to
250/// exempt these from gate classification.
251fn receipt_scoped_unknown_result(id: &str) -> ObligationResult {
252    ObligationResult {
253        id: id.to_string(),
254        status: ObligationStatus::Unknown,
255        trust: None,
256        evidence: Evidence {
257            backend: "none".to_string(),
258            summary: "receipt-wired obligation; run `g8 check --receipt <path>` to evaluate"
259                .to_string(),
260            detail: serde_json::json!({ "scope": ACTION_RECEIPT_WIRING }),
261            duration_ms: 0,
262            checks_run: vec![],
263        },
264    }
265}
266
267fn run_one(
268    obligation: &Obligation,
269    workspace_root: &Path,
270    attestations: &exec::attestation::LoadedAttestations,
271    wiring_is_receipt: bool,
272    receipt: Option<&ReceiptSubject>,
273) -> ObligationResult {
274    match &obligation.checker {
275        None => unknown_result(&obligation.id, "no checker configured for this obligation"),
276        Some(ObligationChecker::ProseOnly) => {
277            unknown_result(&obligation.id, "checker.mode = prose_only")
278        }
279        Some(ObligationChecker::Attestation { attestation_id }) => {
280            exec::attestation::run(&obligation.id, attestation_id, attestations, workspace_root)
281        }
282        Some(ObligationChecker::Typed { checks }) => run_typed(
283            &obligation.id,
284            checks,
285            workspace_root,
286            attestations,
287            wiring_is_receipt,
288            receipt,
289        ),
290    }
291}
292
293fn unknown_result(id: &str, reason: &str) -> ObligationResult {
294    ObligationResult {
295        id: id.to_string(),
296        status: ObligationStatus::Unknown,
297        trust: None,
298        evidence: Evidence {
299            backend: "none".to_string(),
300            summary: reason.to_string(),
301            detail: serde_json::json!({}),
302            duration_ms: 0,
303            checks_run: vec![],
304        },
305    }
306}
307
308fn run_typed(
309    id: &str,
310    checks: &[CheckerBackend],
311    workspace_root: &Path,
312    attestations: &exec::attestation::LoadedAttestations,
313    wiring_is_receipt: bool,
314    receipt: Option<&ReceiptSubject>,
315) -> ObligationResult {
316    let start = Instant::now();
317
318    // Subject-binding validation (contract addendum §1): a receipt-wired
319    // obligation may only use `receipt_query`; `receipt_query` may not
320    // appear in a repo-wired obligation. Checked before dispatching anything
321    // — a violation is a claim about the ARTIFACT's own authoring, not a
322    // per-backend outcome.
323    if let Some(message) = subject_binding_violation(checks, wiring_is_receipt) {
324        return ObligationResult {
325            id: id.to_string(),
326            status: ObligationStatus::Error,
327            trust: Some(TrustLevel::Checked),
328            evidence: Evidence {
329                backend: "none".to_string(),
330                summary: message.clone(),
331                detail: serde_json::json!({ "error": message }),
332                duration_ms: start.elapsed().as_millis() as u64,
333                checks_run: vec![],
334            },
335        };
336    }
337
338    let mut checks_run: Vec<SubCheckResult> = checks
339        .iter()
340        .map(|backend| exec::dispatch(backend, workspace_root, receipt))
341        .collect();
342
343    // Attestations supplement typed checks. Missing is intentionally quiet;
344    // the CLI's rigor floor will classify a Checked-only gate. A present
345    // fresh/stale/error record stays visible as a real sub-check.
346    if let exec::attestation::AttestationEvaluation::Evaluated(attestation) =
347        exec::attestation::evaluate(attestations, id, None, workspace_root)
348    {
349        checks_run.push(attestation);
350    }
351
352    let (status, trust) = result::aggregate(&checks_run);
353
354    // The overall Evidence mirrors the sub-check that determined the
355    // aggregated status (the erroring/failing one if any, else the
356    // highest-trust one) — per Evidence's own doc comment (contract §3).
357    let representative = checks_run
358        .iter()
359        .find(|c| c.status == ObligationStatus::Error)
360        .or_else(|| {
361            checks_run
362                .iter()
363                .find(|c| c.status == ObligationStatus::Failed)
364        })
365        .or_else(|| {
366            checks_run
367                .iter()
368                .find(|c| c.status == ObligationStatus::Unknown)
369        })
370        .or_else(|| {
371            checks_run
372                .iter()
373                .max_by_key(|check| result::backend_tier_rank(&check.backend))
374        });
375
376    let (backend, summary, detail) = match representative {
377        Some(r) => (
378            r.backend.clone(),
379            format!("{:?}: {}", r.status, summarize_detail(&r.detail)),
380            r.detail.clone(),
381        ),
382        None => (
383            "none".to_string(),
384            "no checks configured".to_string(),
385            serde_json::json!({}),
386        ),
387    };
388
389    ObligationResult {
390        id: id.to_string(),
391        status,
392        trust,
393        evidence: Evidence {
394            backend,
395            summary,
396            detail,
397            duration_ms: start.elapsed().as_millis() as u64,
398            checks_run,
399        },
400    }
401}
402
403fn summarize_detail(detail: &serde_json::Value) -> String {
404    if let Some(s) = detail.get("summary").and_then(|v| v.as_str()) {
405        s.to_string()
406    } else {
407        detail.to_string()
408    }
409}
410
411/// `Some(message)` iff `checks` violates subject binding for `wiring_is_receipt`
412/// (contract addendum §1): a receipt-wired obligation's checks must ALL be
413/// `receipt_query`; a repo-wired obligation's checks must contain NONE.
414fn subject_binding_violation(checks: &[CheckerBackend], wiring_is_receipt: bool) -> Option<String> {
415    checks.iter().find_map(|backend| {
416        let is_receipt_backend = backend.name() == "receipt_query";
417        if is_receipt_backend == wiring_is_receipt {
418            return None;
419        }
420        Some(if wiring_is_receipt {
421            format!(
422                "subject-binding violation: obligation is wired to '{ACTION_RECEIPT_WIRING}' but \
423                 its checks include non-receipt backend '{}'; a receipt-wired obligation may only \
424                 use receipt_query",
425                backend.name()
426            )
427        } else {
428            "subject-binding violation: 'receipt_query' backend used in an obligation not wired \
429             to 'action_receipt'; receipt_query may only appear in an action_receipt-wired \
430             obligation"
431                .to_string()
432        })
433    })
434}
435
436#[cfg(test)]
437mod receipt_scope_tests {
438    use super::*;
439
440    fn receipt_wired_obligation(id: &str, checks: Vec<CheckerBackend>) -> Obligation {
441        serde_json::from_value(serde_json::json!({
442            "id": id,
443            "checker": { "mode": "typed", "checks": checks },
444            "signal": { "wiring": "action_receipt", "advisory": false },
445        }))
446        .expect("must deserialize a hand-built obligation")
447    }
448
449    fn repo_wired_obligation(id: &str, checks: Vec<CheckerBackend>) -> Obligation {
450        serde_json::from_value(serde_json::json!({
451            "id": id,
452            "checker": { "mode": "typed", "checks": checks },
453            "signal": { "wiring": "compiled_intent_extension", "advisory": false },
454        }))
455        .expect("must deserialize a hand-built obligation")
456    }
457
458    fn receipt_query_backend() -> CheckerBackend {
459        CheckerBackend::ReceiptQuery(ReceiptQueryArgs {
460            select: "$.actions[*]".to_string(),
461            where_clauses: vec![],
462            aggregate: ReceiptAggregate::Count,
463            expected: ReceiptExpectation::Zero,
464        })
465    }
466
467    fn repo_backend() -> CheckerBackend {
468        CheckerBackend::RgMatchCount(RgArgs {
469            pattern: "ZZZ_NEVER_PRESENT_ZZZ".to_string(),
470            glob: vec!["Cargo.toml".to_string()],
471            expected: CountExpectation::Zero,
472        })
473    }
474
475    fn workspace_root() -> std::path::PathBuf {
476        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
477            .parent()
478            .unwrap()
479            .parent()
480            .unwrap()
481            .to_path_buf()
482    }
483
484    fn subject() -> ReceiptSubject {
485        ReceiptSubject {
486            display_path: "receipts/test.json".to_string(),
487            sha256: "sha256:test".to_string(),
488            value: serde_json::json!({ "actions": [] }),
489        }
490    }
491
492    #[test]
493    fn repo_mode_receipt_wired_obligation_is_unknown_and_scoped_not_executed() {
494        let obligation = receipt_wired_obligation("OBL-RCPT-01", vec![receipt_query_backend()]);
495        let attestations = exec::attestation::load_for_run(&workspace_root());
496        let result = run_one_scoped(&obligation, &workspace_root(), &attestations, None)
497            .expect("repo mode always produces a result for every obligation");
498        assert_eq!(result.status, ObligationStatus::Unknown);
499        assert_eq!(result.trust, None);
500        assert_eq!(
501            result.evidence.detail.get("scope").and_then(|v| v.as_str()),
502            Some(ACTION_RECEIPT_WIRING)
503        );
504    }
505
506    #[test]
507    fn repo_mode_repo_wired_obligation_runs_unaffected() {
508        let obligation = repo_wired_obligation("OBL-REPO-01", vec![repo_backend()]);
509        let attestations = exec::attestation::load_for_run(&workspace_root());
510        let result = run_one_scoped(&obligation, &workspace_root(), &attestations, None)
511            .expect("repo mode always produces a result for every obligation");
512        assert_eq!(result.status, ObligationStatus::Passed);
513    }
514
515    #[test]
516    fn receipt_mode_repo_wired_obligation_is_excluded_entirely() {
517        let obligation = repo_wired_obligation("OBL-REPO-01", vec![repo_backend()]);
518        let attestations = exec::attestation::load_for_run(&workspace_root());
519        let subject = subject();
520        let result = run_one_scoped(
521            &obligation,
522            &workspace_root(),
523            &attestations,
524            Some(&subject),
525        );
526        assert!(result.is_none());
527    }
528
529    #[test]
530    fn receipt_mode_receipt_wired_obligation_runs_against_the_subject() {
531        let obligation = receipt_wired_obligation("OBL-RCPT-01", vec![receipt_query_backend()]);
532        let attestations = exec::attestation::load_for_run(&workspace_root());
533        let subject = subject();
534        let result = run_one_scoped(
535            &obligation,
536            &workspace_root(),
537            &attestations,
538            Some(&subject),
539        )
540        .expect("receipt mode runs receipt-wired obligations");
541        assert_eq!(result.status, ObligationStatus::Passed); // zero actions, expected zero
542    }
543
544    #[test]
545    fn receipt_query_in_a_repo_wired_obligation_is_a_binding_error() {
546        let obligation = repo_wired_obligation("OBL-BAD-01", vec![receipt_query_backend()]);
547        let attestations = exec::attestation::load_for_run(&workspace_root());
548        let result = run_one_scoped(&obligation, &workspace_root(), &attestations, None)
549            .expect("repo mode always produces a result for every obligation");
550        assert_eq!(result.status, ObligationStatus::Error);
551        assert_eq!(result.trust, Some(TrustLevel::Checked));
552    }
553
554    #[test]
555    fn repo_backend_in_a_receipt_wired_obligation_is_a_binding_error() {
556        let obligation = receipt_wired_obligation("OBL-BAD-02", vec![repo_backend()]);
557        let attestations = exec::attestation::load_for_run(&workspace_root());
558        let subject = subject();
559        let result = run_one_scoped(
560            &obligation,
561            &workspace_root(),
562            &attestations,
563            Some(&subject),
564        )
565        .expect("receipt mode runs receipt-wired obligations, including a broken one");
566        assert_eq!(result.status, ObligationStatus::Error);
567    }
568
569    #[test]
570    fn load_receipt_subject_hashes_and_parses_a_real_file() {
571        let dir = tempfile::tempdir().unwrap();
572        let path = dir.path().join("receipt.json");
573        std::fs::write(&path, r#"{"actions": []}"#).unwrap();
574        let subject = load_receipt_subject(&path).expect("must load");
575        assert!(subject.sha256.starts_with("sha256:"));
576        assert_eq!(subject.value, serde_json::json!({"actions": []}));
577    }
578
579    #[test]
580    fn load_receipt_subject_missing_file_has_no_sha256() {
581        let error = load_receipt_subject(std::path::Path::new("/nonexistent/receipt.json"))
582            .expect_err("missing file must error");
583        assert_eq!(error.sha256(), None);
584    }
585
586    #[test]
587    fn load_receipt_subject_malformed_json_still_reports_a_sha256() {
588        let dir = tempfile::tempdir().unwrap();
589        let path = dir.path().join("receipt.json");
590        std::fs::write(&path, "{ not json").unwrap();
591        let error = load_receipt_subject(&path).expect_err("malformed JSON must error");
592        assert!(error.sha256().is_some());
593    }
594}