assay-cli 6.26.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
use crate::exit_codes::{ReasonCode, RunOutcome};
use std::path::{Path, PathBuf};

fn reason_code_from_run_error_kind(kind: assay_core::errors::RunErrorKind) -> Option<ReasonCode> {
    use assay_core::errors::RunErrorKind;

    match kind {
        RunErrorKind::TraceNotFound => Some(ReasonCode::ETraceNotFound),
        RunErrorKind::MissingConfig => Some(ReasonCode::EMissingConfig),
        RunErrorKind::ConfigParse => Some(ReasonCode::ECfgParse),
        RunErrorKind::InvalidArgs => Some(ReasonCode::EInvalidArgs),
        RunErrorKind::ProviderRateLimit => Some(ReasonCode::ERateLimit),
        RunErrorKind::ProviderTimeout => Some(ReasonCode::ETimeout),
        RunErrorKind::ProviderServer => Some(ReasonCode::EProvider5xx),
        RunErrorKind::Network => Some(ReasonCode::ENetworkError),
        RunErrorKind::JudgeUnavailable => Some(ReasonCode::EJudgeUnavailable),
        RunErrorKind::Other => None,
    }
}

pub(crate) fn reason_code_from_run_error(err: &assay_core::errors::RunError) -> Option<ReasonCode> {
    reason_code_from_run_error_kind(err.kind.clone())
}

fn run_error_kind_from_details(
    details: &serde_json::Value,
) -> Option<assay_core::errors::RunErrorKind> {
    use assay_core::errors::RunErrorKind;

    let kind = details.get("run_error_kind")?.as_str()?;
    match kind {
        "trace_not_found" => Some(RunErrorKind::TraceNotFound),
        "missing_config" => Some(RunErrorKind::MissingConfig),
        "config_parse" => Some(RunErrorKind::ConfigParse),
        "invalid_args" => Some(RunErrorKind::InvalidArgs),
        "provider_rate_limit" => Some(RunErrorKind::ProviderRateLimit),
        "provider_timeout" => Some(RunErrorKind::ProviderTimeout),
        "provider_server" => Some(RunErrorKind::ProviderServer),
        "network" => Some(RunErrorKind::Network),
        "judge_unavailable" => Some(RunErrorKind::JudgeUnavailable),
        "other" => Some(RunErrorKind::Other),
        _ => None,
    }
}

/// The not-evaluated episode code for a row, read from the typed companion
/// 6.6.3 already emits — never from the message text.
fn reason_code_from_not_evaluated(details: &serde_json::Value) -> Option<ReasonCode> {
    use assay_core::report::exercised::{
        ASSERTIONS_NOT_EVALUATED, EPISODE_AMBIGUOUS, EPISODE_MISSING,
    };

    let kind = details
        .get(ASSERTIONS_NOT_EVALUATED)?
        .get("kind")?
        .as_str()?;
    if kind == EPISODE_MISSING {
        Some(ReasonCode::ETraceEpisodeMissing)
    } else if kind == EPISODE_AMBIGUOUS {
        Some(ReasonCode::ETraceEpisodeAmbiguous)
    } else {
        None
    }
}

/// True when the row carries the typed not-evaluated companion, regardless of
/// which lookup kind it names.
fn is_not_evaluated_row(row: &assay_core::model::TestResultRow) -> bool {
    use assay_core::report::exercised::ASSERTIONS_NOT_EVALUATED;

    row.details.get(ASSERTIONS_NOT_EVALUATED).is_some()
}

fn reason_code_from_result_row(row: &assay_core::model::TestResultRow) -> Option<ReasonCode> {
    // Typed-first mapping in hot path; message classification remains explicit legacy fallback.
    // The not-evaluated companion is read before everything else: these rows
    // are `Error` like infra rows, and the legacy classifier must never decide
    // them.
    if let Some(reason) = reason_code_from_not_evaluated(&row.details) {
        return Some(reason);
    }
    if let Some(kind) = run_error_kind_from_details(&row.details) {
        return reason_code_from_run_error_kind(kind);
    }
    reason_code_from_error_message(&row.message)
}

pub(crate) fn reason_code_from_error_message(message: &str) -> Option<ReasonCode> {
    use assay_core::errors::RunError;

    // Legacy-only fallback for untyped paths.
    let classified = RunError::legacy_classify_message(message.to_string());
    reason_code_from_run_error(&classified)
}

/// Decide the run's outcome, then attach the observations that do not decide it.
///
/// A wrapper rather than a line at the end of the body below, because that body has six early
/// returns. An observation appended on one of them would be missing from the other five, and the
/// path it would be missing from most often is the one that matters here: success. A metric that
/// evaluated nothing shows up on a green run by definition.
///
/// Both `assay run` and `assay ci` reach this through `execute_pipeline`, so the two commands
/// cannot report different coverage.
pub(crate) fn decide_run_outcome(
    results: &[assay_core::model::TestResultRow],
    strict: bool,
    version: crate::exit_codes::ExitCodeVersion,
) -> crate::exit_codes::RunOutcome {
    let mut outcome = decide_run_outcome_impl(results, strict, version);
    // Appended, never assigned: `warnings` already carries report-writing failures, and this must
    // not displace them. It does not participate in `exit_code` — that is what makes it a review
    // signal instead of a gate (#1949 layer 2, slice 4).
    outcome
        .warnings
        .extend(assay_core::report::exercised::warnings(results));
    outcome
}

fn decide_run_outcome_impl(
    results: &[assay_core::model::TestResultRow],
    strict: bool,
    version: crate::exit_codes::ExitCodeVersion,
) -> crate::exit_codes::RunOutcome {
    use assay_core::model::TestStatus;

    // Helper to ensure exit code matches requested version
    let make_outcome = |reason: ReasonCode, msg: Option<String>, context: Option<&str>| {
        let mut o = RunOutcome::from_reason(reason, msg, context);
        o.exit_code = reason.exit_code_for(version);
        o
    };

    // Priority 1: Config/Argument Errors (Exit 2)
    for r in results {
        if let Some(reason) = reason_code_from_result_row(r) {
            if matches!(
                reason,
                ReasonCode::ETraceNotFound
                    | ReasonCode::EMissingConfig
                    | ReasonCode::ECfgParse
                    | ReasonCode::EInvalidArgs
            ) {
                return make_outcome(reason, Some(r.message.clone()), None);
            }
        }
    }

    // Priority 2: Infrastructure Failures (Refined Heuristics)
    //
    // Not-evaluated episode rows are `Error` too, but they are decided below,
    // never here: without the exclusion they would fall to
    // `E_JUDGE_UNAVAILABLE` / exit 3.
    let infra_errors: Vec<&assay_core::model::TestResultRow> = results
        .iter()
        .filter(|r| matches!(r.status, TestStatus::Error) && !is_not_evaluated_row(r))
        .collect();

    if !infra_errors.is_empty() {
        let reason = pick_infra_reason(&infra_errors);
        return make_outcome(
            reason,
            Some("Infrastructure failures detected".into()),
            None,
        );
    }

    // Priority 3: Judge uncertain (abstain) — exit 1, E_JUDGE_UNCERTAIN
    let abstain_count = results
        .iter()
        .filter(|r| has_judge_verdict_abstain(&r.details))
        .count();
    if abstain_count > 0 {
        let mut o = RunOutcome::judge_uncertain(abstain_count);
        o.exit_code = ReasonCode::EJudgeUncertain.exit_code_for(version);
        return o;
    }

    // Priority 4: Test Failures
    let fails = results
        .iter()
        .filter(|r| matches!(r.status, TestStatus::Fail))
        .count();
    if fails > 0 {
        let mut o = RunOutcome::test_failure(fails);
        o.exit_code = ReasonCode::ETestFailed.exit_code_for(version);
        return o;
    }

    // Priority 4b: Assertions never evaluated (exit 1 under variant B1).
    //
    // After failures, so a mixed run with an evaluated failure reports
    // `E_TEST_FAILED` first; before strict, which only constrains evaluated
    // rows. Missing outranks ambiguous regardless of result order.
    let missing = results
        .iter()
        .filter(|r| {
            reason_code_from_not_evaluated(&r.details) == Some(ReasonCode::ETraceEpisodeMissing)
        })
        .count();
    let ambiguous = results
        .iter()
        .filter(|r| {
            reason_code_from_not_evaluated(&r.details) == Some(ReasonCode::ETraceEpisodeAmbiguous)
        })
        .count();
    if missing + ambiguous > 0 {
        let reason = if missing > 0 {
            ReasonCode::ETraceEpisodeMissing
        } else {
            ReasonCode::ETraceEpisodeAmbiguous
        };
        let msg = format!(
            "assertions not evaluated for {} test(s): {} missing, {} ambiguous",
            missing + ambiguous,
            missing,
            ambiguous
        );
        return make_outcome(reason, Some(msg), None);
    }

    // Priority 5: Strict Mode Violations
    if strict {
        let violations = results
            .iter()
            .filter(|r| {
                matches!(
                    r.status,
                    TestStatus::Warn | TestStatus::Flaky | TestStatus::Unstable
                )
            })
            .count();
        if violations > 0 {
            return make_outcome(
                ReasonCode::EPolicyViolation,
                Some(format!("Strict mode: {} policy violations", violations)),
                None,
            );
        }
    }

    // Priority 6: Success (ensure version compliance though Success is usually 0 in all versions)
    let mut o = RunOutcome::success();
    o.exit_code = ReasonCode::Success.exit_code_for(version);
    o
}

/// True if this result row has any judge metric with verdict "Abstain" (E7.5).
pub(crate) fn has_judge_verdict_abstain(details: &serde_json::Value) -> bool {
    let Some(metrics) = details.get("metrics").and_then(|m| m.as_object()) else {
        return false;
    };
    for (_name, metric_val) in metrics {
        if let Some(inner) = metric_val.get("details").and_then(|d| d.get("verdict")) {
            if inner.as_str() == Some("Abstain") {
                return true;
            }
        }
    }
    false
}

fn pick_infra_reason(
    errors: &[&assay_core::model::TestResultRow],
) -> crate::exit_codes::ReasonCode {
    for r in errors {
        if let Some(reason) = reason_code_from_result_row(r) {
            if matches!(
                reason,
                ReasonCode::ERateLimit
                    | ReasonCode::ETimeout
                    | ReasonCode::EProvider5xx
                    | ReasonCode::ENetworkError
                    | ReasonCode::EJudgeUnavailable
            ) {
                return reason;
            }
        }
    }
    ReasonCode::EJudgeUnavailable
}

/// Compatibility facade for existing run/replay callers.
pub(crate) use crate::cli_failure::summary_from_outcome;

pub(crate) fn write_extended_run_json(
    artifacts: &assay_core::report::RunArtifacts,
    outcome: &crate::exit_codes::RunOutcome,
    path: &Path,
    sarif_omitted: Option<u64>,
) -> anyhow::Result<()> {
    // Manually construct the JSON to inject outcome fields
    let mut v = serde_json::to_value(artifacts)?;
    if let Some(obj) = v.as_object_mut() {
        // Inject top-level outcome fields for machine-readability (Canonical Contract)
        obj.insert(
            "exit_code".to_string(),
            serde_json::json!(outcome.exit_code),
        );
        obj.insert(
            "reason_code".to_string(),
            serde_json::json!(outcome.reason_code),
        );
        obj.insert(
            "reason_code_version".to_string(),
            serde_json::json!(assay_core::report::summary::REASON_CODE_VERSION),
        );

        // E7.2: seeds always present; order_seed/judge_seed as string or null (SPEC: avoid JSON number precision loss)
        obj.insert(
            "seed_version".to_string(),
            serde_json::json!(assay_core::report::summary::SEED_VERSION),
        );
        let order_seed_json = match artifacts.order_seed {
            Some(n) => serde_json::Value::String(n.to_string()),
            None => serde_json::Value::Null,
        };
        obj.insert("order_seed".to_string(), order_seed_json);
        obj.insert("judge_seed".to_string(), serde_json::Value::Null);

        // E7.3: judge metrics when present
        if let Some(metrics) =
            assay_core::report::summary::judge_metrics_from_results(&artifacts.results)
        {
            obj.insert("judge_metrics".to_string(), serde_json::to_value(metrics)?);
        }

        // E2.3: SARIF truncation metadata when SARIF was truncated
        if let Some(n) = sarif_omitted {
            if n > 0 {
                obj.insert("sarif".to_string(), serde_json::json!({ "omitted": n }));
            }
        }

        // Conflict avoidance: Move full details to 'resolution' object
        // Do NOT inject 'message' or 'next_step' top-level to avoid collisions with artifact fields.
        obj.insert("resolution".to_string(), serde_json::to_value(outcome)?);

        if !outcome.warnings.is_empty() {
            obj.insert("warnings".into(), serde_json::json!(outcome.warnings));
        }
    }

    write_sanitized_run_json(path, v)
}

/// Sanitize a run.json document and write it. Render-safety (MCP01a-5): EVERY run.json writer routes
/// its assembled value through the same `render_details_safe` walk as the `--format json` stdout
/// renderer (`assay_core::report::json::render_json`), so the untrusted result `message` /
/// `details.*` / `resolution.message` content is redacted on disk too — the file-writers used to
/// serialize raw artifacts and bypass redaction. As a record sink it redacts and control-strips but
/// does not truncate (`usize::MAX`); assay-owned keys (ids, status, reason_code, exit_code, digests,
/// seeds) stay byte-stable. Shared by both the extended and minimal (early-error) writers so neither
/// path can drift back to raw.
fn write_sanitized_run_json(path: &Path, v: serde_json::Value) -> anyhow::Result<()> {
    let v = assay_core::render_safety::render_details_safe(
        assay_core::render_safety::Sink::Json,
        &v,
        usize::MAX,
    );
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(path, serde_json::to_string_pretty(&v)?)?;
    Ok(())
}

pub(crate) fn write_run_json_minimal(
    outcome: &crate::exit_codes::RunOutcome,
    path: &Path,
) -> anyhow::Result<()> {
    // Minimal JSON for early exits (no artifacts available). E7.2: seed fields present for schema stability (null when unknown).
    // `resolution` carries the outcome (incl. its `message`, which on config/arg errors echoes
    // external path/parse text), so this goes through the shared sanitizer like the extended writer.
    let v = serde_json::json!({
        "exit_code": outcome.exit_code,
        "reason_code": outcome.reason_code,
        "reason_code_version": assay_core::report::summary::REASON_CODE_VERSION,
        "seed_version": assay_core::report::summary::SEED_VERSION,
        "order_seed": null,
        "judge_seed": null,
        "resolution": outcome
    });
    write_sanitized_run_json(path, v)
}

pub(crate) fn export_baseline(
    path: &PathBuf,
    config_path: &Path,
    cfg: &assay_core::model::EvalConfig,
    results: &[assay_core::model::TestResultRow],
) -> anyhow::Result<()> {
    let mut entries = Vec::new();

    for r in results {
        if let Some(metrics) = r.details.get("metrics").and_then(|v| v.as_object()) {
            for (metric_name, m_val) in metrics {
                if let Some(score) = m_val.get("score").and_then(|s| s.as_f64()) {
                    entries.push(assay_core::baseline::BaselineEntry {
                        test_id: r.test_id.clone(),
                        metric: metric_name.clone(),
                        score,
                        // Carried so a later run can tell "this metric scored worse" from "this
                        // metric stopped being evaluated". Without it the two are the same row.
                        // `meta` is an existing optional field, so an older baseline still loads
                        // and simply reports no prior coverage.
                        meta: m_val
                            .get("exercised")
                            .map(|e| serde_json::json!({ "exercised": e })),
                    });
                }
            }
        }
    }

    let b = assay_core::baseline::Baseline {
        schema_version: 1,
        suite: cfg.suite.clone(),
        assay_version: env!("CARGO_PKG_VERSION").to_string(),
        created_at: chrono::Utc::now().to_rfc3339(),
        config_fingerprint: assay_core::baseline::compute_config_fingerprint(config_path),
        git_info: None,
        entries,
    };

    b.save(path)?;
    eprintln!("exported baseline to {}", path.display());
    Ok(())
}

#[cfg(test)]
mod tests;