assay-cli 6.20.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
pub mod adapt_skill_scan;
pub mod attest;
pub mod cyclonedx_mlbom_model;
pub mod diff;
mod diff_render;
pub mod effect_refutation;
pub mod export_incident_package;
mod incident_input;
pub mod index;
pub mod lint;
pub mod list;
pub mod livekit_tool_action;
pub mod mapping;
pub mod mastra_score_event;
pub mod mcp_execution_records;
pub mod mcp_supersession;
pub mod mcp_tunnel_observed;
pub mod openfeature_details;
pub mod privileged_mcp_action;
pub mod project_skill_bom;
pub mod promptfoo_jsonl;
pub mod pull;
pub mod push;
pub mod pydantic_case_result;
pub mod schema;
pub mod skill_supply_chain;
pub mod skill_supply_chain_capture;
mod source_artifact_ref;
pub mod store_status;
pub mod tool_decision_truth;
pub mod verify_attestation;
pub mod verify_coverage_attestation;
pub mod verify_incident_package;
pub mod verify_privileged_mcp_action;
pub mod verify_side_effects;
pub mod verify_skill_supply_chain;
pub mod verify_tool_decision_truth;

use anyhow::{Context, Result};
use clap::{Args, Subcommand};
use mapping::{DetailLevel, EvidenceMapper};
use std::fs::File;
use std::io;

/// Manage tamper-evident bundles (audit/compliance)
#[derive(Debug, Subcommand, Clone)]
pub enum EvidenceCmd {
    /// Export an evidence bundle from a Profile
    Export(EvidenceExportArgs),
    /// Verify a bundle's integrity and provenance
    Verify(EvidenceVerifyArgs),
    /// Verify a signed v1 attestation against the complete evidence archive
    #[command(name = "verify-attestation")]
    VerifyAttestation(verify_attestation::VerifyAttestationArgs),
    /// Verify a local CAP-1 coverage attestation document
    #[command(name = "verify-coverage-attestation")]
    VerifyCoverageAttestation(verify_coverage_attestation::VerifyCoverageAttestationArgs),
    /// Verify an incident package v1 outer archive offline
    #[command(name = "verify-incident-package")]
    VerifyIncidentPackage(verify_incident_package::VerifyIncidentPackageArgs),
    /// Export supplied local incident-package documents and objects (Unix)
    #[command(name = "export-incident-package")]
    ExportIncidentPackage(export_incident_package::ExportIncidentPackageArgs),
    /// Verify SEP-2787/server execution-record fixture pairing
    #[command(name = "verify-mcp-records")]
    VerifyMcpRecords(mcp_execution_records::McpExecutionRecordArgs),
    /// Evaluate decision-record supersession (latest decidedAt wins; equal time is ambiguous)
    #[command(name = "verify-mcp-supersession")]
    VerifyMcpSupersession(mcp_supersession::McpSupersessionArgs),
    /// Verify MCP tunnel observed-facts fixture boundaries and join classification
    #[command(name = "verify-mcp-tunnel-observed")]
    VerifyMcpTunnelObserved(mcp_tunnel_observed::McpTunnelObservedArgs),
    /// Verify experimental tool-decision-truth recipe rows against their carriers in a bundle
    #[command(name = "verify-tool-decision-truth")]
    VerifyToolDecisionTruth(verify_tool_decision_truth::VerifyToolDecisionTruthArgs),
    /// Promote side-effect levels against imported provider audit records (import + recompute, never a query)
    #[command(name = "verify-side-effects")]
    VerifySideEffects(verify_side_effects::VerifySideEffectsArgs),
    /// Verify a bundle against privileged-mcp-action v0 or v1 (explicit --profile-version, default v0)
    #[command(name = "verify-privileged-mcp-action")]
    VerifyPrivilegedMcpAction(verify_privileged_mcp_action::VerifyPrivilegedMcpActionArgs),
    /// Verify experimental skill supply-chain carriers against the pinned contract in a bundle
    #[command(name = "verify-skill-supply-chain")]
    VerifySkillSupplyChain(verify_skill_supply_chain::VerifySkillSupplyChainArgs),
    /// Capture a skill root into an experimental skill supply-chain carrier (declarative, not a scanner)
    #[command(name = "capture-skill-supply-chain")]
    CaptureSkillSupplyChain(skill_supply_chain_capture::CaptureSkillSupplyChainArgs),
    /// Project a verified skill supply-chain bundle into a CycloneDX 1.6 AI-BOM
    #[command(name = "project-skill-bom")]
    ProjectSkillBom(project_skill_bom::ProjectSkillBomArgs),
    /// Attach SARIF scanner findings to a skill supply-chain carrier as occurrence signals
    #[command(name = "adapt-skill-scan")]
    AdaptSkillScan(adapt_skill_scan::AdaptSkillScanArgs),
    /// Inspect a bundle's contents (verify + show table)
    Show(EvidenceShowArgs),
    /// Import external evidence into an Assay evidence bundle
    Import(EvidenceImportArgs),
    /// Inspect and validate supported receipt/input schemas
    Schema(schema::SchemaArgs),
    /// Lint a bundle for quality and security issues
    Lint(lint::LintArgs),
    /// Diff two bundles and report changes
    Diff(diff::DiffArgs),
    /// Sign a complete evidence archive as an in-toto/DSSE attestation
    Attest(attest::AttestArgs),
    /// Upload a bundle to remote storage (BYOS)
    Push(push::PushArgs),
    /// Download a bundle from remote storage (BYOS)
    Pull(pull::PullArgs),
    /// List bundles in remote storage (BYOS)
    List(list::ListArgs),
    /// Check evidence store connectivity and status (BYOS)
    StoreStatus(store_status::StoreStatusArgs),
    /// Manage the evidence run index (BYOS)
    #[command(subcommand)]
    Index(index::EvidenceIndexCmd),
    /// Interactive TUI explorer for evidence bundles
    #[cfg(feature = "tui")]
    Explore(explore::ExploreArgs),
}

#[derive(Debug, Args, Clone)]
pub struct EvidenceExportArgs {
    /// Input profile (multi-run profile or sandbox evidence sidecar, YAML/JSON)
    #[arg(long, alias = "input")]
    pub profile: std::path::PathBuf,

    /// Output bundle path (.tar.gz). Defaults to assay_evidence_{run_id}.tar.gz
    #[arg(long, short = 'o')]
    pub out: Option<std::path::PathBuf>,

    /// Level of detail to include (summary, observed, full)
    #[arg(long, value_enum, default_value_t = DetailLevel::Observed)]
    pub detail: DetailLevel,
}

#[derive(Debug, Args, Clone)]
pub struct EvidenceVerifyArgs {
    /// Bundle path, or "-" for stdin
    #[arg(value_name = "BUNDLE", default_value = "-")]
    pub bundle: std::path::PathBuf,
}

#[derive(Debug, Args, Clone)]
pub struct EvidenceShowArgs {
    /// Bundle path
    #[arg(value_name = "BUNDLE")]
    pub bundle: std::path::PathBuf,

    /// Skip verification (show even if corrupt/untrusted)
    #[arg(long)]
    pub no_verify: bool,

    /// Output format for the bundle listing.
    #[arg(long, value_enum, default_value_t = crate::cli::args::common::ShowFormat::Table)]
    pub format: crate::cli::args::common::ShowFormat,
}

#[derive(Debug, Args, Clone)]
pub struct EvidenceImportArgs {
    #[command(subcommand)]
    pub cmd: EvidenceImportCmd,
}

#[derive(Debug, Subcommand, Clone)]
pub enum EvidenceImportCmd {
    /// Import one CycloneDX ML-BOM machine-learning-model component receipt
    #[command(name = "cyclonedx-mlbom-model")]
    CycloneDxMlBomModel(cyclonedx_mlbom_model::CycloneDxMlBomModelArgs),
    /// Import bounded OpenFeature boolean EvaluationDetails decision artifacts
    #[command(name = "openfeature-details")]
    OpenFeatureDetails(openfeature_details::OpenFeatureDetailsArgs),
    /// Import bounded Mastra ScoreEvent-derived score artifacts
    #[command(name = "mastra-score-event")]
    MastraScoreEvent(mastra_score_event::MastraScoreEventArgs),
    /// Import bounded Pydantic Evals reduced case-result artifacts
    #[command(name = "pydantic-case-result")]
    PydanticCaseResult(pydantic_case_result::PydanticCaseResultArgs),
    /// Import bounded LiveKit function tool action artifacts
    #[command(name = "livekit-tool-action")]
    LiveKitToolAction(livekit_tool_action::LiveKitToolActionArgs),
    /// Import Promptfoo CLI JSONL assertion component results
    #[command(name = "promptfoo-jsonl")]
    PromptfooJsonl(promptfoo_jsonl::PromptfooJsonlArgs),
    /// Import privileged-mcp-action producer NDJSON records (decisions, observations, establish)
    #[command(name = "privileged-mcp-action")]
    PrivilegedMcpAction(privileged_mcp_action::PrivilegedMcpActionArgs),
    /// Import an experimental tool-decision-truth carrier as a bound recipe row
    #[command(name = "tool-decision-truth")]
    ToolDecisionTruth(tool_decision_truth::ToolDecisionTruthArgs),
    /// Import an experimental skill supply-chain carrier (retained skill record)
    #[command(name = "skill-supply-chain")]
    SkillSupplyChain(skill_supply_chain::SkillSupplyChainArgs),
}

pub async fn run(args: crate::cli::args::EvidenceArgs) -> Result<i32> {
    match args.cmd {
        EvidenceCmd::Export(a) => cmd_export(a),
        EvidenceCmd::Verify(a) => cmd_verify(a),
        EvidenceCmd::VerifyMcpRecords(a) => mcp_execution_records::cmd_verify_mcp_records(a),
        EvidenceCmd::VerifyMcpSupersession(a) => mcp_supersession::cmd_verify_mcp_supersession(a),
        EvidenceCmd::VerifyMcpTunnelObserved(a) => {
            mcp_tunnel_observed::cmd_verify_mcp_tunnel_observed(a)
        }
        EvidenceCmd::VerifyToolDecisionTruth(a) => {
            verify_tool_decision_truth::cmd_verify_tool_decision_truth(a)
        }
        EvidenceCmd::VerifySideEffects(a) => verify_side_effects::cmd_verify_side_effects(&a),
        EvidenceCmd::VerifyPrivilegedMcpAction(a) => {
            verify_privileged_mcp_action::cmd_verify_privileged_mcp_action(a)
        }
        EvidenceCmd::VerifySkillSupplyChain(a) => {
            verify_skill_supply_chain::cmd_verify_skill_supply_chain(a)
        }
        EvidenceCmd::CaptureSkillSupplyChain(a) => {
            skill_supply_chain_capture::cmd_capture_skill_supply_chain(a)
        }
        EvidenceCmd::ProjectSkillBom(a) => project_skill_bom::cmd_project_skill_bom(a),
        EvidenceCmd::AdaptSkillScan(a) => adapt_skill_scan::cmd_adapt_skill_scan(a),
        EvidenceCmd::Show(a) => cmd_show(a),
        EvidenceCmd::Import(a) => cmd_import(a),
        EvidenceCmd::Schema(a) => schema::cmd_schema(a),
        EvidenceCmd::Lint(a) => lint::cmd_lint(a),
        EvidenceCmd::Diff(a) => diff::cmd_diff(a),
        EvidenceCmd::Attest(a) => attest::cmd_attest(a),
        EvidenceCmd::VerifyAttestation(a) => verify_attestation::cmd_verify_attestation(a),
        EvidenceCmd::VerifyCoverageAttestation(a) => {
            verify_coverage_attestation::cmd_verify_coverage_attestation(a)
        }
        EvidenceCmd::ExportIncidentPackage(a) => {
            export_incident_package::cmd_export_incident_package(a)
        }
        EvidenceCmd::VerifyIncidentPackage(a) => {
            verify_incident_package::cmd_verify_incident_package(a)
        }
        EvidenceCmd::Push(a) => push::cmd_push(a).await,
        EvidenceCmd::Pull(a) => pull::cmd_pull(a).await,
        EvidenceCmd::List(a) => list::cmd_list(a).await,
        EvidenceCmd::StoreStatus(a) => store_status::cmd_store_status(a).await,
        EvidenceCmd::Index(a) => index::cmd_evidence_index(a).await,
        #[cfg(feature = "tui")]
        EvidenceCmd::Explore(a) => explore::cmd_explore(a),
    }
}

fn cmd_import(args: EvidenceImportArgs) -> Result<i32> {
    match args.cmd {
        EvidenceImportCmd::CycloneDxMlBomModel(a) => {
            cyclonedx_mlbom_model::cmd_cyclonedx_mlbom_model(a)
        }
        EvidenceImportCmd::OpenFeatureDetails(a) => openfeature_details::cmd_openfeature_details(a),
        EvidenceImportCmd::MastraScoreEvent(a) => mastra_score_event::cmd_mastra_score_event(a),
        EvidenceImportCmd::PydanticCaseResult(a) => {
            pydantic_case_result::cmd_pydantic_case_result(a)
        }
        EvidenceImportCmd::LiveKitToolAction(a) => livekit_tool_action::cmd_livekit_tool_action(a),
        EvidenceImportCmd::PromptfooJsonl(a) => promptfoo_jsonl::cmd_promptfoo_jsonl(a),
        EvidenceImportCmd::PrivilegedMcpAction(a) => {
            privileged_mcp_action::cmd_privileged_mcp_action(a)
        }
        EvidenceImportCmd::ToolDecisionTruth(a) => tool_decision_truth::cmd_tool_decision_truth(a),
        EvidenceImportCmd::SkillSupplyChain(a) => skill_supply_chain::cmd_skill_supply_chain(a),
    }
}

fn cmd_export(args: EvidenceExportArgs) -> Result<i32> {
    // 1. Load Profile
    let profile = crate::cli::commands::profile_types::load_profile(&args.profile)
        .with_context(|| format!("failed to load profile from {}", args.profile.display()))?;

    // 2. Map Profile -> EvidenceEvents
    let run_id_opt = profile.run_ids.back().cloned();

    let mut mapper = EvidenceMapper::new(run_id_opt, &profile.name);
    let events = mapper.map_profile(&profile, args.detail)?;
    let run_id = mapper.run_id().to_string();

    // 3. Write Bundle
    let out_path = args
        .out
        .unwrap_or_else(|| std::path::PathBuf::from(format!("assay_evidence_{}.tar.gz", run_id)));

    let out_file = File::create(&out_path)
        .with_context(|| format!("failed to create output file {}", out_path.display()))?;

    let mut bw = assay_evidence::bundle::BundleWriter::new(out_file);
    for ev in events {
        bw.add_event(ev);
    }

    bw.finish().context("failed to finalize evidence bundle")?;

    eprintln!("Exported evidence bundle to {}", out_path.display());
    Ok(0)
}

fn cmd_verify(args: EvidenceVerifyArgs) -> Result<i32> {
    if args.bundle.to_string_lossy() == "-" {
        // ADR-043 section 1: the ceiling applies to the stream. Reading stdin to the end first
        // and verifying a `Cursor` over the result meant an untrusted pipe sized the allocation
        // before any limit was consulted, and stdin is the one source whose length nothing can
        // be checked against beforehand. `verify_bundle` bounds the reader it is given, so hand
        // it the pipe rather than a buffer already filled from it.
        let stdin = io::stdin();
        assay_evidence::bundle::verify_bundle(stdin.lock())
            .context("bundle verification failed")?;
        eprintln!("Bundle verified (stdin): OK");
        return Ok(0);
    }

    let f = File::open(&args.bundle)
        .with_context(|| format!("failed to open bundle {}", args.bundle.display()))?;

    // Same verifier the stdin arm uses, for the same reason it uses it. `BundleReader::open`
    // verifies too, but it also retains the whole decompressed events stream so a caller can
    // iterate it — and this caller iterates nothing, it discards the reader. That retention is
    // bounded by `max_events_bytes` (500 MiB), five times the bundle ceiling, so a small,
    // compressible bundle made `verify` hold hundreds of megabytes to answer yes or no: 530 MB
    // against this path's 33 MB on the same 5.7 MB file. Verification never needed the buffer.
    assay_evidence::bundle::verify_bundle(f).context("bundle verification failed")?;

    eprintln!("Bundle verified ({}): OK", args.bundle.display());
    Ok(0)
}

fn cmd_show(args: EvidenceShowArgs) -> Result<i32> {
    let f = File::open(&args.bundle).map_err(|error| {
        classify_show_error(
            &args.bundle,
            error.into(),
            &format!("failed to open bundle {}", args.bundle.display()),
        )
    })?;

    let limits = assay_evidence::VerifyLimits::for_retained_events();
    let reader = if args.no_verify {
        assay_evidence::bundle::BundleReader::open_unverified_with_limits(f, limits)
    } else {
        assay_evidence::bundle::BundleReader::open_with_limits(f, limits)
    };
    let br = reader.map_err(|error| {
        classify_show_error(&args.bundle, error, "failed to open bundle reader")
    })?;

    let verified = !args.no_verify; // If open() succeeded above, it IS verified.
    let manifest = br.manifest();

    if args.format == crate::cli::args::common::ShowFormat::Json {
        // Output complete bundle as JSON: manifest + events + additive content-hash scope.
        // Embed `content_hash_scope()` unchanged — do not rebuild fields from CLI literals.
        let events = br.events().collect::<Result<Vec<_>>>()?;
        let bundle_json = serde_json::json!({
            "manifest": manifest,
            "events": events,
            "verify_mode": assay_core::report::summary::verification_mode(verified),
            "content_hash_scope": assay_evidence::crypto::id::content_hash_scope(),
        });
        println!("{}", serde_json::to_string_pretty(&bundle_json)?);
        return Ok(0);
    }

    // Table view
    println!("Evidence Bundle Inspector");
    println!("=========================");
    if !args.no_verify {
        if verified {
            println!("Verified:    ✅ OK");
        } else {
            println!("Verified:    ❌ FAILED (Integrity compromised)");
        }
    } else {
        println!("Verified:    ⚠️  SKIPPED");
    }
    println!("Bundle ID:   {}", manifest.bundle_id);
    println!(
        "Producer:    {} v{}",
        manifest.producer.name, manifest.producer.version
    );
    println!("Run ID:      {}", manifest.run_id);
    println!("Events:      {}", manifest.event_count);
    let run_root_display: String = manifest.run_root.chars().take(16).collect();
    println!("Run Root:    {}...", run_root_display);
    println!();
    println!("{:<4} {:<25} {:<30} SUBJECT", "SEQ", "TIME", "TYPE");
    println!("{:-<4} {:-<25} {:-<30} {:-<20}", "", "", "", "");

    for ev_res in br.events() {
        let ev = ev_res?;
        let subject = ev.subject.as_deref().unwrap_or("-");
        let time_str = ev.time.to_rfc3339();
        let time_short = if time_str.len() > 19 {
            time_str.chars().skip(11).take(8).collect::<String>()
        } else {
            time_str.clone()
        };

        println!(
            "{:<4} {:<25} {:<30} {}",
            ev.seq, time_short, ev.type_, subject
        );
    }

    if !args.no_verify {
        println!("\n✅ Verified Integrity");
    } else {
        println!("\n⚠️  Verification Skipped");
    }

    Ok(0)
}

fn classify_show_error(
    path: &std::path::Path,
    error: anyhow::Error,
    fallback_context: &str,
) -> anyhow::Error {
    // Show publishes only the three already-live identities. LIMIT / PATH /
    // PROFILE stay on the untyped fallback; they are not this command's emit.
    let failure = match crate::evidence_verify_reason::reason_code_for_evidence_error(&error) {
        Some(crate::exit_codes::ReasonCode::EEvidenceIntegrity) => {
            crate::cli_failure::CliFailure::evidence_integrity(path, &error)
        }
        Some(crate::exit_codes::ReasonCode::EEvidenceUnreadable) => {
            crate::cli_failure::CliFailure::evidence_unreadable(path, &error)
        }
        Some(crate::exit_codes::ReasonCode::EEvidenceContract) => {
            crate::cli_failure::CliFailure::evidence_contract(path, &error)
        }
        Some(_) | None => None,
    };
    match failure {
        Some(failure) => failure.into(),
        None => error.context(fallback_context.to_string()),
    }
}

// TUI explore module (conditional compilation)
#[cfg(feature = "tui")]
pub mod explore;