assay-cli 6.1.0

Policy-as-code gate for MCP agent tool calls, with verifiable evidence and Linux kernel enforcement.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use std::io;
use std::path::Path;

use assay_core::errors::Diagnostic;
use assay_core::report::summary::Summary;

use crate::cli::commands::pipeline_error::emit_operator_diagnostic;
use crate::exit_codes::{ReasonCode, RunOutcome, EXIT_SUCCESS};
use crate::output_write::{map_write_result, write_stdout_json};

fn evidence_reason(error: &anyhow::Error) -> Option<ReasonCode> {
    crate::evidence_verify_reason::reason_code_for_evidence_error(error)
}

/// A classified command failure that the top-level CLI funnel can render.
///
/// Untyped `anyhow::Error` values deliberately do not enter this path: assigning a
/// reason code is a command-level decision, not something the funnel can infer from
/// prose without silently misclassifying failures.
#[derive(Debug)]
pub(crate) struct CliFailure {
    outcome: RunOutcome,
    source: &'static str,
    context: serde_json::Value,
}

impl CliFailure {
    pub(crate) fn coverage_invalid_args(message: impl Into<String>) -> Self {
        let outcome = RunOutcome::from_reason(ReasonCode::EInvalidArgs, Some(message.into()), None);
        Self {
            outcome,
            source: "coverage",
            context: serde_json::json!({}),
        }
    }

    pub(crate) fn policy_parse(path: &Path, error: impl std::fmt::Display) -> Self {
        let path = path.display().to_string();
        let message = format!("failed to parse policy {path}: {error}");
        let outcome =
            RunOutcome::from_reason(ReasonCode::EPolicyParse, Some(message), Some(path.as_str()));
        Self {
            outcome,
            source: "policy",
            context: serde_json::json!({ "path": path }),
        }
    }

    /// Classify only verifier outcomes that establish a recorded-value mismatch.
    ///
    /// `ErrorClass::Integrity` is intentionally too broad: the evidence crate also assigns it to
    /// I/O, gzip, and tar failures, none of which establish anything about the content that was
    /// successfully read. The shared verifier-code mapping is pinned to the normative boundary by
    /// a mutation-sensitive test below.
    pub(crate) fn evidence_integrity(path: &Path, error: &anyhow::Error) -> Option<Self> {
        if evidence_reason(error) != Some(ReasonCode::EEvidenceIntegrity) {
            return None;
        }
        let verifier = error
            .chain()
            .find_map(|cause| cause.downcast_ref::<assay_evidence::VerifyError>())?;

        let path = path.display().to_string();
        let verifier_code = verifier.code.to_string();
        let message = format!("evidence bundle {path} failed content verification: {error}");
        let outcome = RunOutcome::from_reason(
            ReasonCode::EEvidenceIntegrity,
            Some(message),
            Some(path.as_str()),
        );
        Some(Self {
            outcome,
            source: "evidence",
            context: serde_json::json!({
                "path": path,
                "verifier_code": verifier_code,
            }),
        })
    }

    /// Classify failures where the bundle could not be opened or read to completion.
    ///
    /// If the evidence verifier supplied a typed code, that code is authoritative. Searching the
    /// rest of its source chain for an I/O error would misclassify a contract or content finding
    /// that merely carries an I/O source.
    pub(crate) fn evidence_unreadable(path: &Path, error: &anyhow::Error) -> Option<Self> {
        if evidence_reason(error) != Some(ReasonCode::EEvidenceUnreadable) {
            return None;
        }

        let path = path.display().to_string();
        let message = format!("evidence bundle {path} could not be opened or read: {error}");
        let outcome = RunOutcome::from_reason(
            ReasonCode::EEvidenceUnreadable,
            Some(message),
            Some(path.as_str()),
        );
        Some(Self {
            outcome,
            source: "evidence",
            context: serde_json::json!({ "path": path }),
        })
    }

    /// Typed `Contract*` format-contract failure for `evidence show`.
    pub(crate) fn evidence_contract(path: &Path, error: &anyhow::Error) -> Option<Self> {
        if evidence_reason(error) != Some(ReasonCode::EEvidenceContract) {
            return None;
        }

        let path = path.display().to_string();
        let message =
            format!("evidence bundle {path} violates its declared format contract: {error:#}");
        let outcome = RunOutcome::from_reason(
            ReasonCode::EEvidenceContract,
            Some(message),
            Some(path.as_str()),
        );
        Some(Self {
            outcome,
            source: "evidence",
            context: serde_json::json!({ "path": path }),
        })
    }

    pub(crate) fn emit(self, machine_output_verify_enabled: Option<bool>) -> i32 {
        emit_operator_diagnostic(&self.diagnostic());
        if let Some(verify_enabled) = machine_output_verify_enabled {
            let summary = summary_from_outcome(&self.outcome, verify_enabled);
            let write_code = write_summary_stdout(&summary);
            if write_code != EXIT_SUCCESS {
                return write_code;
            }
        }
        self.outcome.exit_code
    }

    fn diagnostic(&self) -> Diagnostic {
        let mut diagnostic = Diagnostic::new(
            self.outcome.reason_code.clone(),
            self.outcome.message.clone().unwrap_or_default(),
        )
        .with_source(self.source)
        .with_context(self.context.clone());
        if let Some(next_step) = &self.outcome.next_step {
            diagnostic = diagnostic.with_fix_step(next_step.clone());
        }
        diagnostic
    }
}

impl std::fmt::Display for CliFailure {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.outcome.message.as_deref().unwrap_or("CLI failure"))
    }
}

impl std::error::Error for CliFailure {}

/// Build the one summary shape shared by run artifacts and top-level CLI failures.
pub(crate) fn summary_from_outcome(outcome: &RunOutcome, verify_enabled: bool) -> Summary {
    let assay_version = env!("CARGO_PKG_VERSION");
    if outcome.exit_code == 0 {
        Summary::success(assay_version, verify_enabled)
    } else {
        Summary::failure(
            outcome.exit_code,
            &outcome.reason_code,
            outcome.message.as_deref().unwrap_or(""),
            outcome.next_step.as_deref().unwrap_or(""),
            assay_version,
            verify_enabled,
        )
    }
}

/// Render and deliver the one machine-summary shape used by command failures and policy validation.
/// A render, write, or flush failure means the requested document was not delivered, so the shared
/// output policy returns `EXIT_INFRA_ERROR` rather than preserving the semantic command result.
pub(crate) fn write_summary_stdout(summary: &Summary) -> i32 {
    let rendered = match assay_core::report::summary::render_summary_json(summary) {
        Ok(rendered) => rendered,
        Err(error) => {
            return map_write_result(
                "stdout",
                Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("failed to render machine summary: {error}"),
                )),
            )
        }
    };
    write_stdout_json(&rendered)
}

#[cfg(test)]
mod tests {
    use super::CliFailure;
    use crate::evidence_verify_reason::reason_code_for_verify_error;
    use crate::exit_codes::ReasonCode;
    use assay_evidence::{ErrorClass, ErrorCode, VerifyError};
    use std::collections::BTreeSet;
    use std::path::Path;

    const INTEGRITY_CODES: &[ErrorCode] = &[
        ErrorCode::IntegrityManifestHash,
        ErrorCode::IntegrityEventHash,
        ErrorCode::IntegrityFileSizeMismatch,
        ErrorCode::IntegrityRunRootMismatch,
    ];
    const UNREADABLE_CODES: &[ErrorCode] = &[
        ErrorCode::IntegrityIo,
        ErrorCode::IntegrityGzip,
        ErrorCode::IntegrityTar,
    ];

    fn verifier_error(class: ErrorClass, code: ErrorCode) -> anyhow::Error {
        anyhow::Error::new(VerifyError::new(class, code, "measured failure"))
            .context("bundle reader failed")
    }

    #[test]
    fn evidence_integrity_code_set_matches_the_normative_boundary() {
        let boundary = include_str!("exit_codes/evidence_integrity_boundary.md");
        let required = boundary
            .split_once("An emitter MUST key on")
            .and_then(|(_, rest)| rest.split_once("and MUST NOT map"))
            .map(|(required, _)| required)
            .expect("normative boundary must retain its required/forbidden code clauses");
        let normative: BTreeSet<&str> = required
            .split('`')
            .filter(|token| token.starts_with("Integrity"))
            .collect();
        assert!(
            !normative.is_empty(),
            "the normative integrity boundary parser must find verifier codes"
        );
        let implemented: BTreeSet<String> = INTEGRITY_CODES
            .iter()
            .copied()
            .filter(|code| {
                reason_code_for_verify_error(&VerifyError::new(
                    ErrorClass::Integrity,
                    *code,
                    "boundary",
                )) == Some(ReasonCode::EEvidenceIntegrity)
            })
            .map(|code| code.to_string())
            .collect();
        assert_eq!(
            implemented,
            normative.into_iter().map(str::to_string).collect(),
            "the executable integrity classifier drifted from the one normative boundary"
        );
    }

    #[test]
    fn evidence_unreadable_code_set_matches_the_normative_registry() {
        let spec = include_str!("../../../docs/architecture/SPEC-PR-Gate-Outputs-v1.md");
        let row = spec
            .lines()
            .find(|line| line.starts_with("| E_EVIDENCE_UNREADABLE |"))
            .expect("reason registry must retain E_EVIDENCE_UNREADABLE");
        let normative: BTreeSet<&str> = row
            .split('`')
            .filter(|token| token.starts_with("Integrity"))
            .collect();
        assert!(
            !normative.is_empty(),
            "the unreadable reason registry parser must find verifier codes"
        );
        let implemented: BTreeSet<String> = UNREADABLE_CODES
            .iter()
            .copied()
            .filter(|code| {
                reason_code_for_verify_error(&VerifyError::new(
                    ErrorClass::Integrity,
                    *code,
                    "registry",
                )) == Some(ReasonCode::EEvidenceUnreadable)
            })
            .map(|code| code.to_string())
            .collect();
        assert_eq!(
            implemented,
            normative.into_iter().map(str::to_string).collect(),
            "the executable unreadable classifier drifted from the normative registry"
        );
    }

    #[test]
    fn evidence_integrity_classification_matches_the_normative_code_boundary() {
        for &code in INTEGRITY_CODES {
            let failure = CliFailure::evidence_integrity(
                Path::new("bundle.tar.gz"),
                &verifier_error(ErrorClass::Integrity, code),
            )
            .unwrap_or_else(|| panic!("{code} must classify as an evidence mismatch"));
            assert_eq!(failure.outcome.reason_code, "E_EVIDENCE_INTEGRITY");
            assert_eq!(failure.outcome.exit_code, 2);
            assert!(
                failure
                    .outcome
                    .next_step
                    .as_deref()
                    .is_some_and(|step| !step.is_empty()),
                "{code} must carry remediation"
            );
        }

        for (class, code) in [
            (ErrorClass::Integrity, ErrorCode::IntegrityIo),
            (ErrorClass::Integrity, ErrorCode::IntegrityGzip),
            (ErrorClass::Integrity, ErrorCode::IntegrityTar),
            (ErrorClass::Contract, ErrorCode::ContractInvalidJson),
            (ErrorClass::Limits, ErrorCode::LimitBundleBytes),
            (ErrorClass::Security, ErrorCode::SecurityPathTraversal),
        ] {
            assert!(
                CliFailure::evidence_integrity(
                    Path::new("bundle.tar.gz"),
                    &verifier_error(class, code),
                )
                .is_none(),
                "{code} establishes no recorded-value mismatch"
            );
        }
    }

    #[test]
    fn evidence_unreadable_classification_excludes_content_and_contract_findings() {
        let direct_io = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::NotFound));
        let failure = CliFailure::evidence_unreadable(Path::new("missing.bundle"), &direct_io)
            .expect("a direct open failure must classify as unreadable");
        assert_eq!(failure.outcome.reason_code, "E_EVIDENCE_UNREADABLE");

        for &code in UNREADABLE_CODES {
            assert!(
                CliFailure::evidence_unreadable(
                    Path::new("bundle.tar.gz"),
                    &verifier_error(ErrorClass::Integrity, code),
                )
                .is_some(),
                "{code} must classify as unreadable"
            );
        }

        for (class, code) in [
            (ErrorClass::Integrity, ErrorCode::IntegrityManifestHash),
            (ErrorClass::Contract, ErrorCode::ContractInvalidJson),
            (ErrorClass::Limits, ErrorCode::LimitBundleBytes),
            (ErrorClass::Security, ErrorCode::SecurityPathTraversal),
        ] {
            assert!(
                CliFailure::evidence_unreadable(
                    Path::new("bundle.tar.gz"),
                    &verifier_error(class, code),
                )
                .is_none(),
                "{code} is not an unreadable-bundle finding"
            );
        }

        let contract_with_io_source = anyhow::Error::new(
            VerifyError::new(
                ErrorClass::Contract,
                ErrorCode::ContractInvalidJson,
                "invalid event",
            )
            .with_source(std::io::Error::from(std::io::ErrorKind::UnexpectedEof)),
        );
        assert!(
            CliFailure::evidence_unreadable(Path::new("bundle.tar.gz"), &contract_with_io_source,)
                .is_none(),
            "a typed contract code must not be reclassified from its nested I/O source"
        );
    }

    #[test]
    fn evidence_contract_cannot_stamp_contract_on_a_non_contract_verifier() {
        for (class, code) in [
            (ErrorClass::Limits, ErrorCode::LimitBundleBytes),
            (ErrorClass::Security, ErrorCode::SecurityPathTraversal),
            (ErrorClass::Integrity, ErrorCode::IntegrityEventHash),
        ] {
            assert!(
                CliFailure::evidence_contract(
                    Path::new("bundle.tar.gz"),
                    &verifier_error(class, code),
                )
                .is_none(),
                "{code} must not be stampable as E_EVIDENCE_CONTRACT"
            );
        }
    }

    #[test]
    fn evidence_contract_constructs_for_typed_contract_invalid_json() {
        let failure = CliFailure::evidence_contract(
            Path::new("bundle.tar.gz"),
            &verifier_error(ErrorClass::Contract, ErrorCode::ContractInvalidJson),
        )
        .expect("ContractInvalidJson must construct as E_EVIDENCE_CONTRACT");
        assert_eq!(failure.outcome.reason_code, "E_EVIDENCE_CONTRACT");
        assert_eq!(failure.outcome.exit_code, 2);
    }
}