use chrono::{TimeZone, Utc};
use kranz_engine::events::{Event, EventKind};
use kranz_engine::reducer;
use kranz_engine::report_render::render_mission_report;
use kranz_engine::types::{
Assertion, AssertionCheck, MissionConfig, Plan, PlanFeature, PlanMilestone,
};
fn ev(seq: u64, kind: EventKind) -> Event {
Event {
seq,
ts: Utc.with_ymd_and_hms(2026, 7, 24, 12, 0, 0).unwrap(),
mission_id: "m-test".into(),
kind,
}
}
fn plan() -> Plan {
Plan {
goal: "add the widget and prove it works".into(),
validation_contract: vec![
Assertion {
id: "a-1".into(),
statement: "the build succeeds".into(),
check: AssertionCheck::Command,
command: Some("cargo test --workspace".into()),
negative_control: None,
pty_script: None,
},
Assertion {
id: "a-2".into(),
statement: "the widget reads honestly".into(),
check: AssertionCheck::AgentJudgement,
command: None,
negative_control: None,
pty_script: None,
},
],
milestones: vec![PlanMilestone {
title: "Ship the widget".into(),
features: vec![
PlanFeature {
title: "build the widget".into(),
spec: "Add a Widget struct that renders the count. It must not allocate."
.into(),
validation_criteria: vec!["cargo test widget passes".into()],
},
PlanFeature {
title: "document the widget".into(),
spec: "One paragraph in the README.".into(),
validation_criteria: vec!["README mentions the widget".into()],
},
],
}],
considered_alternatives: None,
command_grants: vec![],
touch_set: vec![],
standards_manifest: None,
reviewer_independence: None,
}
}
fn completed_state() -> kranz_engine::types::MissionState {
let p = plan();
let events = vec![
ev(
1,
EventKind::MissionCreated {
goal: p.goal.clone(),
base_branch: "main".into(),
mission_branch: "kranz/mission-m-test".into(),
config: MissionConfig::default(),
},
),
ev(
2,
EventKind::PlanApproved {
plan: p,
base_sha: None,
},
),
ev(
3,
EventKind::MilestoneStarted {
milestone_id: "ms-1".into(),
start_sha: "abc".into(),
},
),
ev(
4,
EventKind::FeatureStarted {
feature_id: "f-1-1".into(),
},
),
ev(
5,
EventKind::FeatureCompleted {
feature_id: "f-1-1".into(),
commits: vec!["0123456789abcdef [f-1-1] add Widget struct".into()],
},
),
ev(
6,
EventKind::FeatureStarted {
feature_id: "f-1-2".into(),
},
),
ev(
7,
EventKind::FeatureCompleted {
feature_id: "f-1-2".into(),
commits: vec!["1123456789abcdef [f-1-2] document the widget".into()],
},
),
ev(
8,
EventKind::MilestoneCompleted {
milestone_id: "ms-1".into(),
tag: None,
},
),
ev(9, EventKind::MissionCompleted {}),
];
reducer::fold(&events).unwrap()
}
fn estimate() -> kranz_engine::cost::CostEstimate {
kranz_engine::cost::CostEstimate {
worker_runs: 2.0,
validator_runs: 2.0,
low_usd: 1.0,
expected_usd: 2.0,
high_usd: 5.0,
shape: kranz_engine::cost::MissionShape::Unknown,
confidence: kranz_engine::cost::Confidence::High,
}
}
#[test]
fn report_opens_with_goal_and_plan_summary_before_statistics() {
let state = completed_state();
let report = render_mission_report(
&state,
&[],
&plan(),
&estimate(),
std::path::Path::new("/tmp"),
None,
);
let ordered = [
"**Goal:**",
"## The plan",
"**Elapsed:**",
"## What shipped",
"## Validation history",
"## Contract outcomes",
];
let mut cursor = 0;
for marker in ordered {
let at = report
.find(marker)
.unwrap_or_else(|| panic!("missing section {marker:?}:\n{report}"));
assert!(at >= cursor, "{marker:?} out of order:\n{report}");
cursor = at;
}
assert!(
report.contains(
"1 milestone, 2 features, gated by 2 contract assertions (1 command, 1 judgement)"
),
"plan summary line:\n{report}"
);
}
#[test]
fn report_narrates_features_with_intent_and_evidence_inline() {
let state = completed_state();
let report = render_mission_report(
&state,
&[],
&plan(),
&estimate(),
std::path::Path::new("/tmp"),
None,
);
assert!(
report.contains("Add a Widget struct that renders the count."),
"intent line present:\n{report}"
);
assert!(
report.contains("`0123456` [f-1-1] add Widget struct"),
"{report}"
);
assert!(report.contains("- ✓ cargo test widget passes"), "{report}");
assert!(
report.contains("- ✅ **[a-1]** the build succeeds *(command: `cargo test --workspace`)*"),
"{report}"
);
}
#[test]
fn report_workspace_section_states_contract_presence() {
let state = completed_state();
let without = render_mission_report(
&state,
&[],
&plan(),
&estimate(),
std::path::Path::new("/tmp"),
None,
);
assert!(
without.contains("- **Workspace contract:** no workspace contract (source isolation only)"),
"{without}"
);
assert!(
!without.contains("- **Bootstrap:**") && !without.contains("- **Readiness:**"),
"no contract ⇒ no gate outcome lines (never imply a runnable environment): {without}"
);
let contract = kranz_engine::workspace_contract::parse_workspace_contract(
br#"{
"schemaVersion": 1,
"services": [
{"name": "api", "start": "cargo run", "port": {"policy": "dynamic"}},
{"name": "db", "start": "docker compose up db", "port": {"policy": {"fixed": 5432}}}
],
"previews": [{"name": "app", "urlTemplate": "http://localhost:{port}/"}]
}"#,
)
.expect("valid contract");
let with = render_mission_report(
&state,
&[],
&plan(),
&estimate(),
std::path::Path::new("/tmp"),
Some(&contract),
);
assert!(
with.contains("- **Workspace contract:** present (2 services, 1 previews)"),
"{with}"
);
assert!(with.contains("- **Bootstrap:** not run yet"), "{with}");
assert!(with.contains("- **Readiness:** not run yet"), "{with}");
}
#[test]
fn report_workspace_section_renders_bootstrap_readiness_outcomes() {
let state = completed_state();
let contract = kranz_engine::workspace_contract::parse_workspace_contract(
br#"{"schemaVersion": 1, "bootstrap": ["cargo fetch"], "readiness": ["pg_isready"]}"#,
)
.expect("valid contract");
let decision = |seq, summary: &str| {
ev(
seq,
EventKind::OrchestratorDecision {
summary: summary.into(),
detail: None,
},
)
};
let events = vec![
decision(10, "workspace bootstrap: running 1 commands"),
decision(11, "workspace bootstrap: 1/1 commands ok"),
decision(12, "workspace readiness: running 1 checks"),
decision(13, "workspace readiness: 1/1 checks ok"),
];
let report = render_mission_report(
&state,
&events,
&plan(),
&estimate(),
std::path::Path::new("/tmp"),
Some(&contract),
);
assert!(
report.contains("- **Bootstrap:** 1/1 commands ok"),
"{report}"
);
assert!(
report.contains("- **Readiness:** 1/1 checks ok"),
"{report}"
);
let events = vec![
decision(10, "workspace bootstrap: 1/1 commands ok"),
decision(
20,
"workspace bootstrap: FAILED at command 1/1 — blocking mission (owner: repo-setup)",
),
decision(21, "workspace readiness: 1/1 checks ok"),
];
let report = render_mission_report(
&state,
&events,
&plan(),
&estimate(),
std::path::Path::new("/tmp"),
Some(&contract),
);
assert!(
report.contains(
"- **Bootstrap:** FAILED at command 1/1 — blocking mission (owner: repo-setup)"
),
"{report}"
);
assert!(
report.contains("- **Readiness:** 1/1 checks ok"),
"{report}"
);
}
#[test]
fn report_workspace_section_renders_provider_pin() {
use kranz_engine::types::WorkspacePin;
let mut state = completed_state();
state.workspace_pin = Some(WorkspacePin {
provider: "local-worktree".into(),
template: "worktree".into(),
version: "1".into(),
});
let report = render_mission_report(
&state,
&[],
&plan(),
&estimate(),
std::path::Path::new("/tmp"),
None,
);
assert!(
report.contains(
"- **Provider:** local-worktree (source isolation) · template: worktree · contract schema v1"
),
"{report}"
);
let mut state = completed_state();
state.workspace_pin = Some(WorkspacePin {
provider: "local-worktree".into(),
template: "checkout".into(),
version: "none".into(),
});
let report = render_mission_report(
&state,
&[],
&plan(),
&estimate(),
std::path::Path::new("/tmp"),
None,
);
assert!(
report.contains(
"- **Provider:** local-worktree (source isolation) · template: checkout · no workspace contract"
),
"{report}"
);
let state = completed_state();
assert_eq!(state.workspace_pin, None);
let report = render_mission_report(
&state,
&[],
&plan(),
&estimate(),
std::path::Path::new("/tmp"),
None,
);
assert!(
!report.contains("- **Provider:**"),
"absent pin ⇒ no Provider line: {report}"
);
}
fn pinned_plan() -> Plan {
let rule =
|id: &str, revision: u64, status: &str, level: &str| kranz_engine::types::PinnedRule {
id: id.into(),
revision,
rfc: "RFC-001".into(),
level: level.into(),
effective_status: status.into(),
statement: format!("statement for {id}"),
domains: vec![],
stages: vec!["validation".into()],
when_paths: vec![],
task_classes: vec![],
checker: Some("gate:zz-gate".into()),
waivable: false,
};
Plan {
standards_manifest: Some(Box::new(kranz_engine::types::StandardsPin {
pack_name: "zz-pack".into(),
pack_dir: "vendor/pack".into(),
standards_root: "standards".into(),
digest: "ab".repeat(32),
source: kranz_engine::types::StandardsPinSource::RepoTracked,
task_class: None,
touch_set: vec!["crates/**".into()],
context_paths: Vec::new(),
gates: Vec::new(),
rules: vec![
rule("ZZ-FAIL-001", 2, "enforced", "must"),
rule("ZZ-QUIET-001", 1, "enforced", "must"),
],
})),
..plan()
}
}
fn pinned_events() -> (Vec<kranz_engine::events::Event>, Plan) {
let p = pinned_plan();
let events = vec![
ev(
1,
EventKind::MissionCreated {
goal: p.goal.clone(),
base_branch: "main".into(),
mission_branch: "kranz/mission-m-test".into(),
config: MissionConfig::default(),
},
),
ev(
2,
EventKind::PlanApproved {
plan: p.clone(),
base_sha: Some("deadbeef".into()),
},
),
ev(
3,
EventKind::StandardsResolved {
source: "repo-tracked".into(),
pack_name: "zz-pack".into(),
standards_root: "standards".into(),
digest: "ab".repeat(32),
stage: "approval".into(),
task_class: None,
touch_set: vec!["crates/**".into()],
context_paths: Vec::new(),
rules: vec![
kranz_engine::types::StandardsRuleRef {
id: "ZZ-FAIL-001".into(),
revision: 2,
effective_status: "enforced".into(),
},
kranz_engine::types::StandardsRuleRef {
id: "ZZ-QUIET-001".into(),
revision: 1,
effective_status: "enforced".into(),
},
],
approval_seq: 2,
},
),
ev(
4,
EventKind::MilestoneStarted {
milestone_id: "ms-1".into(),
start_sha: "abc".into(),
},
),
ev(
5,
EventKind::MilestoneValidating {
milestone_id: "ms-1".into(),
},
),
ev(
6,
EventKind::GateResult {
gate: "zz-gate".into(),
surface: kranz_engine::gate::GateSurface::FinalGate,
kind: kranz_engine::gate::GateKind::Deterministic,
index: 0,
verdict: kranz_engine::gate::GateVerdict::Pass,
artefact_ref: "file:runs/gate-zz.jsonl".into(),
artefact_detail: None,
score: None,
threshold: None,
rule_ids: vec!["ZZ-QUIET-001".into()],
},
),
ev(
7,
EventKind::ValidationFinding {
milestone_id: "ms-1".into(),
run_id: kranz_engine::reducer::ENGINE_RUN_ID.into(),
finding: kranz_engine::types::Finding {
subject: "a-1".into(),
severity: "major".into(),
evidence: "the rule's gate failed".into(),
suggested_fix: String::new(),
class: String::new(),
rule: Some(kranz_engine::types::RuleCitation {
id: "ZZ-FAIL-001".into(),
revision: 2,
source: "zz-pack standards".into(),
digest: "ab".repeat(32),
lifecycle: "enforced".into(),
level: "must".into(),
checker: Some("gate:zz-gate".into()),
}),
},
},
),
ev(8, EventKind::MissionCompleted {}),
];
(events, p)
}
#[test]
fn flight_rules_provenance_report_renders_the_coverage_matrix() {
let (events, p) = pinned_events();
let state = reducer::fold(&events).unwrap();
let report = render_mission_report(
&state,
&events,
&p,
&estimate(),
std::path::Path::new("/tmp"),
None,
);
assert!(
report.contains("## Flight Rules standards coverage"),
"{report}"
);
assert!(
report.contains(&format!(
"Pack `zz-pack` (`vendor/pack`, source repo-tracked) — standards root \
`standards`, digest `sha256:{}`.",
"ab".repeat(32)
)),
"{report}"
);
assert!(
report.contains("Pinned at plan approval (seq 2)"),
"{report}"
);
assert!(
report.contains(
"| ZZ-FAIL-001 | r2 | enforced | must | gate:zz-gate | failed | validation.finding \
seq 7 engine fail `a-1` |"
),
"{report}"
);
assert!(
report.contains(
"| ZZ-QUIET-001 | r1 | enforced | must | gate:zz-gate | passed | gate.result seq 6 \
zz-gate pass `file:runs/gate-zz.jsonl` |"
),
"{report}"
);
assert!(
report.contains("Absence of evidence is never rendered as pass"),
"{report}"
);
let history = report.find("## Validation history").unwrap();
let coverage = report.find("## Flight Rules standards coverage").unwrap();
let outcomes = report.find("## Contract outcomes").unwrap();
assert!(history < coverage && coverage < outcomes, "{report}");
}
#[test]
fn flight_rules_provenance_pre_flight_rules_report_is_unchanged() {
let state = completed_state();
let report = render_mission_report(
&state,
&[],
&plan(),
&estimate(),
std::path::Path::new("/tmp"),
None,
);
assert!(
!report.contains("Flight Rules standards coverage"),
"no pin, no matrix: {report}"
);
assert!(!report.contains("not-evaluated"), "{report}");
}