From b6f0ac79f36861148973dae389900aa9ef81e533 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 15 Oct 2026 15:40:02 +0000 Subject: [PATCH 1/2] feat(qa): replay the Aravath slice as one required hash Scripted and goal policies call run_aravath_slice once and must share a trace. The failure artifact and ddmin stay off pull requests. The new gameplay_qa_aravath_slice case joins the existing replay set. Co-authored-by: Andrew Brown --- .github/workflows/determinism-replay.yml | 15 +- Cargo.lock | 3 + astraweave-weaving/Cargo.toml | 3 + astraweave-weaving/examples/aravath_slice.rs | 33 +- .../scenarios/aravath_slice_sword.ron | 18 + astraweave-weaving/src/aravath.rs | 7 +- astraweave-weaving/src/gameplay_qa.rs | 979 ++++++++++++++++++ astraweave-weaving/src/lib.rs | 4 +- docs/architecture/weaving.md | 26 +- docs/current/AUTONOMOUS_GAMEPLAY_QA.md | 64 +- docs/current/CI_ARCHITECTURE.md | 4 +- scripts/ci/test_workflow_policy.py | 8 +- 12 files changed, 1111 insertions(+), 53 deletions(-) create mode 100644 astraweave-weaving/scenarios/aravath_slice_sword.ron create mode 100644 astraweave-weaving/src/gameplay_qa.rs diff --git a/.github/workflows/determinism-replay.yml b/.github/workflows/determinism-replay.yml index 2a3f1b88de..fabdab56a8 100644 --- a/.github/workflows/determinism-replay.yml +++ b/.github/workflows/determinism-replay.yml @@ -1,9 +1,9 @@ # Required status check on pull requests: `determinism-replay / compare`. # Branch protection is a repository setting. This workflow is the check it must require. # `planner_pure` (WS-D0), `perception_world` (WS-D1), `gameplay_rng` (WS-D2), -# `fixed64`, `combat_resolve`, and `destruction` fail the compare job on any -# mismatch or if the case is missing. No path filter. cargo test has no retry -# loop (no-retry). Do not switch this job to nextest. +# `fixed64`, `combat_resolve`, `destruction`, and `gameplay_qa_aravath_slice` +# fail the compare job on any mismatch or if the case is missing. No path +# filter. cargo test has no retry loop (no-retry). Do not switch this job to nextest. name: determinism-replay @@ -66,6 +66,7 @@ jobs: run: | cargo test -p astraweave-core --test replay_hash -- --nocapture cargo test -p astraweave-combat --test replay_hash -- --nocapture + cargo test -p astraweave-weaving --lib gameplay_qa::tests::replay_aravath_slice_scenario -- --exact --nocapture - name: Merge replay hashes run: | @@ -75,16 +76,18 @@ jobs: const root = process.env.CARGO_TARGET_DIR || "target"; const core = JSON.parse(fs.readFileSync(path.join(root, "replay-hash.json"), "utf8")); const combat = JSON.parse(fs.readFileSync(path.join(root, "replay-hash-combat.json"), "utf8")); + const gameplay = JSON.parse(fs.readFileSync(path.join(root, "replay-hash-gameplay-qa.json"), "utf8")); const seen = new Set(core.map((row) => row.case)); const merged = core.slice(); - for (const row of combat) { + for (const row of combat.concat(gameplay)) { if (seen.has(row.case)) { console.error(`duplicate replay case ${row.case}`); process.exit(1); } + seen.add(row.case); merged.push(row); } - const required = ["planner_pure", "perception_world", "gameplay_rng", "fixed64", "combat_resolve", "destruction"]; + const required = ["planner_pure", "perception_world", "gameplay_rng", "fixed64", "combat_resolve", "destruction", "gameplay_qa_aravath_slice"]; const names = new Set(merged.map((row) => row.case)); for (const name of required) { if (!names.has(name)) { @@ -123,7 +126,7 @@ jobs: import sys from pathlib import Path - required = {"planner_pure", "perception_world", "gameplay_rng", "fixed64", "combat_resolve", "destruction"} + required = {"planner_pure", "perception_world", "gameplay_rng", "fixed64", "combat_resolve", "destruction", "gameplay_qa_aravath_slice"} root = Path("replay-artifacts") files = sorted(root.glob("*/replay-hash.json")) print(f"artifacts: {[str(p) for p in files]}") diff --git a/Cargo.lock b/Cargo.lock index af90cdddd8..6993a55dd7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1640,7 +1640,10 @@ dependencies = [ "criterion 0.7.0", "glam", "rand 0.9.2", + "ron 0.8.1", "serde", + "serde_json", + "sha2", "toml 0.9.8", ] diff --git a/astraweave-weaving/Cargo.toml b/astraweave-weaving/Cargo.toml index 8d01a0c213..9d1371c999 100644 --- a/astraweave-weaving/Cargo.toml +++ b/astraweave-weaving/Cargo.toml @@ -12,7 +12,10 @@ weaving = [] [dependencies] # Core dependencies anyhow = { workspace = true } +ron = "0.8" serde = { workspace = true } +serde_json = { workspace = true } +sha2 = { workspace = true } toml = { workspace = true } rand = { workspace = true } diff --git a/astraweave-weaving/examples/aravath_slice.rs b/astraweave-weaving/examples/aravath_slice.rs index e21b222d97..09003ff01e 100644 --- a/astraweave-weaving/examples/aravath_slice.rs +++ b/astraweave-weaving/examples/aravath_slice.rs @@ -1,10 +1,25 @@ -fn main() { - let slice = astraweave_weaving::run_aravath_slice(); - println!( - "aravath sword hp {} weave hp {} cover intact {} cover damage {}", - slice.sword_hp, slice.weave_hp, slice.cover_intact, slice.cover_damage - ); - assert_eq!(slice.sword_hp, 15); - assert_eq!(slice.weave_hp, 25); - assert!(!slice.cover_intact); +fn main() -> anyhow::Result<()> { + let scenario = astraweave_weaving::load_bundled_scenario()?; + match astraweave_weaving::run_scenario(&scenario) { + astraweave_weaving::RunOutcome::Pass(report) => { + println!( + "aravath sword hp {} weave hp {} cover intact {} cover damage {}", + report.slice.sword_hp, + report.slice.weave_hp, + report.slice.cover_intact, + report.slice.cover_damage + ); + println!("gameplay_qa_aravath_slice {}", report.trace_sha256); + Ok(()) + } + astraweave_weaving::RunOutcome::Fail(artifact) => { + let json = astraweave_weaving::gameplay_qa::failure_json(&artifact)?; + eprintln!("{json}"); + anyhow::bail!( + "scenario {} failed: {}", + artifact.scenario_id, + artifact.failure.kind + ); + } + } } diff --git a/astraweave-weaving/scenarios/aravath_slice_sword.ron b/astraweave-weaving/scenarios/aravath_slice_sword.ron new file mode 100644 index 0000000000..95095a9faa --- /dev/null +++ b/astraweave-weaving/scenarios/aravath_slice_sword.ron @@ -0,0 +1,18 @@ +Scenario( + schema: 1, + id: "aravath_slice_sword", + seed: 0xA11CE5EE, + max_ticks: 1, + setup: Slice, + bot: Script(steps: [ + (edges: [ + Hit(attack_id: 1, defender: Cover, seq: 0, heal: false), + Hit(attack_id: 3, defender: Woven, seq: 1, heal: false), + WeaveDecay, + ]), + ]), + goal: (objective: "cover_broken", policy: "slice_sword_then_weave"), + checks: [ + Reach(by_tick: 1, sword_hp: 15, weave_hp: 25, cover_intact: false, min_cover_damage: 25), + ], +) diff --git a/astraweave-weaving/src/aravath.rs b/astraweave-weaving/src/aravath.rs index 27c2e9893a..88f026b4ec 100644 --- a/astraweave-weaving/src/aravath.rs +++ b/astraweave-weaving/src/aravath.rs @@ -72,6 +72,9 @@ pub struct AravathSlice { pub cover_damage: i64, } +/// World seed and destruction seed used by [`run_aravath_slice`]. +pub const ARAVATH_SLICE_SEED: u64 = 0xA11C_E5EE; + /// Sword for 25, a data-driven weave school for 15, and a cover bond that breaks. pub fn run_aravath_slice() -> AravathSlice { let mut app = App::new().add_plugin(CombatPlugin); @@ -81,11 +84,11 @@ pub fn run_aravath_slice() -> AravathSlice { ) .expect("install table"); app.world.insert_resource(CombatClock { - world_seed: 0xA11C_E5EE, + world_seed: ARAVATH_SLICE_SEED, tick: 0, }); - let mut destruction = DestructionWorld::new(0xA11C_E5EE, 0); + let mut destruction = DestructionWorld::new(ARAVATH_SLICE_SEED, 0); let half = [Fixed64::from_int(1); 3]; let post = [Fixed64::from_int(0), Fixed64::from_int(1), Fixed64::ZERO]; destruction diff --git a/astraweave-weaving/src/gameplay_qa.rs b/astraweave-weaving/src/gameplay_qa.rs new file mode 100644 index 0000000000..6b8d26941f --- /dev/null +++ b/astraweave-weaving/src/gameplay_qa.rs @@ -0,0 +1,979 @@ +//! Headless gameplay QA for the one-tick Aravath slice. +//! +//! Scenario 1 calls [`crate::run_aravath_slice`] once. The scripted policy and +//! the goal policy each record the edges that call performs. Both traces must +//! match. The function is not split into a tick loop. + +use std::path::{Path, PathBuf}; + +use anyhow::{bail, Context, Result}; +use serde::Deserialize; +use serde::Serialize; +use sha2::{Digest, Sha256}; + +use crate::{run_aravath_slice, AravathSlice, ARAVATH_SLICE_SEED}; + +const SCHEMA: u32 = 1; +const MINIMIZE_BUDGET: u32 = 64; +const CASE_NAME: &str = "gameplay_qa_aravath_slice"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Scenario { + pub id: String, + pub seed: u64, + pub max_ticks: u64, + pub steps: Vec, + pub objective: String, + pub policy: String, + pub reach: Reach, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TickActions { + pub edges: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Edge { + Hit { + attack_id: u32, + defender: Defender, + seq: u32, + heal: bool, + }, + WeaveDecay, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Defender { + Cover, + Woven, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Reach { + pub by_tick: u64, + pub sword_hp: i64, + pub weave_hp: i64, + pub cover_intact: bool, + pub min_cover_damage: i64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum FailureKind { + TerminalMismatch, + GoalBotDiverged, + UnstablePredicate, +} + +impl FailureKind { + fn as_str(self) -> &'static str { + match self { + Self::TerminalMismatch => "terminal_mismatch", + Self::GoalBotDiverged => "goal_bot_diverged", + Self::UnstablePredicate => "unstable_predicate", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ScenarioReport { + pub trace_sha256: String, + pub state_sha256: String, + pub slice: AravathSlice, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct FailureArtifact { + pub schema: u32, + pub scenario_id: String, + pub seed: String, + pub setup: String, + pub inputs: Vec, + pub hashes: Vec, + pub failure: FailureBody, + pub original_len: usize, + pub minimized_len: usize, + /// `skipped` on the pull-request path, `full` when ddmin finished, `partial` at the budget. + pub minimized: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct TickRecord { + pub tick: u64, + pub edges: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum EdgeRecord { + Hit { + attack_id: u32, + defender: String, + seq: u32, + heal: bool, + }, + WeaveDecay {}, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct HashRow { + pub tick: u64, + pub sha256: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct FailureBody { + pub kind: String, + pub tick: u64, + pub detail: String, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MinimizeMode { + Off, + On, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RunOutcome { + Pass(ScenarioReport), + Fail(FailureArtifact), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MinimizeResult { + pub ticks: Vec, + pub calls: u32, + pub partial: bool, +} + +#[derive(Debug, Deserialize)] +#[serde(rename = "Scenario", deny_unknown_fields)] +struct ScenarioFile { + schema: u32, + id: String, + seed: u64, + max_ticks: u64, + setup: SetupFile, + bot: BotFile, + goal: GoalFile, + checks: Vec, +} + +#[derive(Debug, Deserialize)] +enum SetupFile { + Slice, +} + +#[derive(Debug, Deserialize)] +enum BotFile { + Script { steps: Vec }, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct StepFile { + edges: Vec, +} + +#[derive(Debug, Deserialize)] +enum EdgeFile { + Hit { + attack_id: u32, + defender: DefenderFile, + seq: u32, + heal: bool, + }, + WeaveDecay, +} + +#[derive(Debug, Deserialize)] +enum DefenderFile { + Cover, + Woven, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct GoalFile { + objective: String, + policy: String, +} + +#[derive(Debug, Deserialize)] +enum CheckFile { + Reach { + by_tick: u64, + sword_hp: i64, + weave_hp: i64, + cover_intact: bool, + min_cover_damage: i64, + }, +} + +/// `QA_MINIMIZE=1` and the GitHub event is not `pull_request`. +#[must_use] +pub fn minimize_enabled() -> bool { + minimize_enabled_from( + std::env::var("QA_MINIMIZE").ok().as_deref(), + std::env::var("GITHUB_EVENT_NAME").ok().as_deref(), + ) +} + +#[must_use] +pub fn minimize_enabled_from(qa_minimize: Option<&str>, github_event: Option<&str>) -> bool { + qa_minimize == Some("1") && github_event != Some("pull_request") +} + +pub fn load_scenario(text: &str) -> Result { + let file: ScenarioFile = ron::from_str(text).context("parse gameplay scenario")?; + if file.schema != SCHEMA { + bail!("scenario schema {} is not {SCHEMA}", file.schema); + } + if file.seed != ARAVATH_SLICE_SEED { + bail!( + "scenario seed {seed:#x} does not match the slice seed {ARAVATH_SLICE_SEED:#x}", + seed = file.seed + ); + } + let SetupFile::Slice = file.setup; + let BotFile::Script { steps } = file.bot; + if steps.is_empty() { + bail!("scenario {} has no scripted ticks", file.id); + } + if steps.len() as u64 > file.max_ticks { + bail!( + "scenario {} has {} ticks and max_ticks {}", + file.id, + steps.len(), + file.max_ticks + ); + } + let mut reach = None; + for check in file.checks { + match check { + CheckFile::Reach { + by_tick, + sword_hp, + weave_hp, + cover_intact, + min_cover_damage, + } => { + if reach.is_some() { + bail!("scenario {} has two Reach checks", file.id); + } + if by_tick < 1 { + bail!("Reach.by_tick starts at 1"); + } + reach = Some(Reach { + by_tick, + sword_hp, + weave_hp, + cover_intact, + min_cover_damage, + }); + } + } + } + let Some(reach) = reach else { + bail!("scenario {} has no Reach check", file.id); + }; + Ok(Scenario { + id: file.id, + seed: file.seed, + max_ticks: file.max_ticks, + steps: steps + .into_iter() + .map(|step| TickActions { + edges: step.edges.into_iter().map(Edge::from).collect(), + }) + .collect(), + objective: file.goal.objective, + policy: file.goal.policy, + reach, + }) +} + +pub fn load_bundled_scenario() -> Result { + let path = bundled_scenario_path(); + let text = std::fs::read_to_string(&path) + .with_context(|| format!("read scenario {}", path.display()))?; + load_scenario(&text) +} + +#[must_use] +pub fn bundled_scenario_path() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("scenarios/aravath_slice_sword.ron") +} + +pub fn run_scenario(scenario: &Scenario) -> RunOutcome { + let mode = if minimize_enabled() { + MinimizeMode::On + } else { + MinimizeMode::Off + }; + run_scenario_with(scenario, mode) +} + +pub fn run_scenario_with(scenario: &Scenario, minimize: MinimizeMode) -> RunOutcome { + let scripted = scenario.steps.clone(); + let goal = match goal_edges(&scenario.objective, &scenario.policy) { + Ok(edges) => edges, + Err(detail) => { + return fail_outcome( + scenario, + &scripted, + FailureKind::GoalBotDiverged, + detail.to_string(), + minimize, + ); + } + }; + let scripted_trace = execute(&scripted); + let goal_trace = execute(&goal); + if scripted_trace.trace_sha256 != goal_trace.trace_sha256 { + return fail_outcome( + scenario, + &scripted, + FailureKind::GoalBotDiverged, + format!( + "scripted {} goal {}", + scripted_trace.trace_sha256, goal_trace.trace_sha256 + ), + minimize, + ); + } + if let Some(detail) = reach_detail(&scripted_trace.slice, &scenario.reach) { + return fail_outcome( + scenario, + &scripted, + FailureKind::TerminalMismatch, + detail, + minimize, + ); + } + RunOutcome::Pass(scripted_trace) +} + +pub fn failure_json(artifact: &FailureArtifact) -> Result { + let mut body = serde_json::to_string_pretty(artifact).context("encode failure artifact")?; + body.push('\n'); + Ok(body) +} + +pub fn write_failure_artifact(path: &Path, artifact: &FailureArtifact) -> Result<()> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?; + } + let body = failure_json(artifact)?; + std::fs::write(path, body).with_context(|| format!("write {}", path.display()))?; + Ok(()) +} + +#[must_use] +pub fn replay_case_path() -> PathBuf { + if let Ok(dir) = std::env::var("CARGO_TARGET_DIR") { + return PathBuf::from(dir).join("replay-hash-gameplay-qa.json"); + } + let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + path.pop(); + path.push("target"); + path.push("replay-hash-gameplay-qa.json"); + path +} + +pub fn write_replay_case(trace_sha256: &str) -> Result { + let path = replay_case_path(); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?; + } + let body = format!("[\n {{ \"case\": \"{CASE_NAME}\", \"sha256\": \"{trace_sha256}\" }}\n]\n"); + std::fs::write(&path, body).with_context(|| format!("write {}", path.display()))?; + Ok(path) +} + +pub fn minimize( + input: &[TickActions], + mut pred: impl FnMut(&[TickActions]) -> bool, +) -> MinimizeResult { + let mut session = Session { + calls: 0, + partial: false, + best: input.to_vec(), + pred: &mut pred, + }; + match session.probe(input) { + Some(true) => {} + _ => { + return MinimizeResult { + ticks: input.to_vec(), + calls: session.calls, + partial: session.partial, + }; + } + } + let reduced = session.reduce_ticks(input.to_vec()); + let reduced = session.reduce_edges(reduced); + let reduced = session.drop_empty_ticks(reduced); + MinimizeResult { + ticks: reduced, + calls: session.calls, + partial: session.partial, + } +} + +fn goal_edges(objective: &str, policy: &str) -> Result> { + if objective == "cover_broken" && policy == "slice_sword_then_weave" { + return Ok(vec![TickActions { + edges: slice_program(), + }]); + } + bail!("unknown goal objective {objective} policy {policy}"); +} + +fn slice_program() -> Vec { + vec![ + Edge::Hit { + attack_id: 1, + defender: Defender::Cover, + seq: 0, + heal: false, + }, + Edge::Hit { + attack_id: 3, + defender: Defender::Woven, + seq: 1, + heal: false, + }, + Edge::WeaveDecay, + ] +} + +fn execute(steps: &[TickActions]) -> ScenarioReport { + let slice = run_aravath_slice(); + let state_sha256 = sha256_hex(&state_bytes(&slice)); + let trace_sha256 = sha256_hex(&trace_bytes(steps, &slice)); + ScenarioReport { + trace_sha256, + state_sha256, + slice, + } +} + +fn reach_detail(slice: &AravathSlice, reach: &Reach) -> Option { + if slice.sword_hp != reach.sword_hp { + return Some(format!( + "sword_hp {} expected, got {}", + reach.sword_hp, slice.sword_hp + )); + } + if slice.weave_hp != reach.weave_hp { + return Some(format!( + "weave_hp {} expected, got {}", + reach.weave_hp, slice.weave_hp + )); + } + if slice.cover_intact != reach.cover_intact { + return Some(format!( + "cover_intact {} expected, got {}", + reach.cover_intact, slice.cover_intact + )); + } + if slice.cover_damage < reach.min_cover_damage { + return Some(format!( + "cover_damage {} is below {}", + slice.cover_damage, reach.min_cover_damage + )); + } + None +} + +fn fail_outcome( + scenario: &Scenario, + inputs: &[TickActions], + kind: FailureKind, + detail: String, + mode: MinimizeMode, +) -> RunOutcome { + let original_len = inputs.len(); + let (chosen, minimized) = match mode { + MinimizeMode::Off => (inputs.to_vec(), "skipped".to_string()), + MinimizeMode::On => { + let reduced = minimize(inputs, |candidate| { + failure_kind(scenario, candidate) == Some(kind) + }); + let label = if reduced.partial { "partial" } else { "full" }; + (reduced.ticks, label.to_string()) + } + }; + let mut chosen = chosen; + let mut kind = kind; + let mut detail = detail; + let mut minimized = minimized; + if minimized != "skipped" { + let once = execute(&chosen); + let twice = execute(&chosen); + if once.trace_sha256 != twice.trace_sha256 { + chosen = inputs.to_vec(); + kind = FailureKind::UnstablePredicate; + detail = format!( + "minimized trace {} then {}", + once.trace_sha256, twice.trace_sha256 + ); + minimized = "skipped".to_string(); + } + } + let report = execute(&chosen); + RunOutcome::Fail(FailureArtifact { + schema: SCHEMA, + scenario_id: scenario.id.clone(), + seed: format!("0x{:X}", scenario.seed), + setup: "slice".to_string(), + inputs: records(&chosen), + hashes: vec![HashRow { + tick: 0, + sha256: report.state_sha256, + }], + failure: FailureBody { + kind: kind.as_str().to_string(), + tick: 0, + detail, + }, + original_len, + minimized_len: chosen.len(), + minimized, + }) +} + +fn failure_kind(scenario: &Scenario, steps: &[TickActions]) -> Option { + let goal = goal_edges(&scenario.objective, &scenario.policy).ok()?; + let scripted = execute(steps); + let goal_trace = execute(&goal); + if scripted.trace_sha256 != goal_trace.trace_sha256 { + return Some(FailureKind::GoalBotDiverged); + } + if reach_detail(&scripted.slice, &scenario.reach).is_some() { + return Some(FailureKind::TerminalMismatch); + } + None +} + +fn records(steps: &[TickActions]) -> Vec { + steps + .iter() + .enumerate() + .map(|(tick, step)| TickRecord { + tick: tick as u64, + edges: step.edges.iter().map(Edge::record).collect(), + }) + .collect() +} + +fn state_bytes(slice: &AravathSlice) -> Vec { + let mut out = Vec::with_capacity(8 * 3 + 1); + push_i64(&mut out, slice.sword_hp); + push_i64(&mut out, slice.weave_hp); + out.push(u8::from(slice.cover_intact)); + push_i64(&mut out, slice.cover_damage); + out +} + +fn trace_bytes(steps: &[TickActions], slice: &AravathSlice) -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(b"AWQA"); + push_u32(&mut out, SCHEMA); + push_u64(&mut out, ARAVATH_SLICE_SEED); + push_u32(&mut out, steps.len() as u32); + for step in steps { + push_u32(&mut out, step.edges.len() as u32); + for edge in &step.edges { + encode_edge(&mut out, edge); + } + } + out.extend_from_slice(&state_bytes(slice)); + out +} + +fn encode_edge(out: &mut Vec, edge: &Edge) { + match edge { + Edge::Hit { + attack_id, + defender, + seq, + heal, + } => { + out.push(1); + push_u32(out, *attack_id); + out.push(match defender { + Defender::Cover => 1, + Defender::Woven => 2, + }); + push_u32(out, *seq); + out.push(u8::from(*heal)); + } + Edge::WeaveDecay => out.push(2), + } +} + +fn sha256_hex(bytes: &[u8]) -> String { + let digest = Sha256::digest(bytes); + let mut hex = String::with_capacity(digest.len() * 2); + for byte in digest { + hex.push_str(&format!("{byte:02x}")); + } + hex +} + +fn push_u32(out: &mut Vec, value: u32) { + out.extend_from_slice(&value.to_le_bytes()); +} + +fn push_u64(out: &mut Vec, value: u64) { + out.extend_from_slice(&value.to_le_bytes()); +} + +fn push_i64(out: &mut Vec, value: i64) { + out.extend_from_slice(&value.to_le_bytes()); +} + +struct Session<'a> { + calls: u32, + partial: bool, + best: Vec, + pred: &'a mut dyn FnMut(&[TickActions]) -> bool, +} + +impl Session<'_> { + fn probe(&mut self, candidate: &[TickActions]) -> Option { + if self.calls >= MINIMIZE_BUDGET { + self.partial = true; + return None; + } + self.calls += 1; + let ok = (self.pred)(candidate); + if ok && tighter(candidate, &self.best) { + self.best = candidate.to_vec(); + } + Some(ok) + } + + fn reduce_ticks(&mut self, mut items: Vec) -> Vec { + let mut parts = 2usize; + while items.len() >= 2 && !self.partial { + let mut start = 0usize; + let chunk = (items.len() / parts).max(1); + let mut reduced = false; + while start < items.len() { + let end = (start + chunk).min(items.len()); + let mut complement = Vec::with_capacity(items.len() - (end - start)); + complement.extend_from_slice(&items[..start]); + complement.extend_from_slice(&items[end..]); + match self.probe(&complement) { + Some(true) => { + items = complement; + parts = parts.saturating_sub(1).max(2); + reduced = true; + break; + } + None => return self.best.clone(), + Some(false) => start = end, + } + } + if !reduced { + if parts >= items.len() { + break; + } + parts = (parts * 2).min(items.len()); + } + } + items + } + + fn reduce_edges(&mut self, mut items: Vec) -> Vec { + for index in 0..items.len() { + if self.partial { + break; + } + let edges = items[index].edges.clone(); + if edges.len() < 2 { + continue; + } + let kept = self.ddmin_edges(&items, index, edges); + items[index].edges = kept; + } + items + } + + fn ddmin_edges( + &mut self, + items: &[TickActions], + index: usize, + mut edges: Vec, + ) -> Vec { + let mut parts = 2usize; + while edges.len() >= 2 && !self.partial { + let mut start = 0usize; + let chunk = (edges.len() / parts).max(1); + let mut reduced = false; + while start < edges.len() { + let end = (start + chunk).min(edges.len()); + let mut complement = Vec::with_capacity(edges.len() - (end - start)); + complement.extend_from_slice(&edges[..start]); + complement.extend_from_slice(&edges[end..]); + let candidate = splice(items, index, &complement); + match self.probe(&candidate) { + Some(true) => { + edges = complement; + parts = parts.saturating_sub(1).max(2); + reduced = true; + break; + } + None => return edges, + Some(false) => start = end, + } + } + if !reduced { + if parts >= edges.len() { + break; + } + parts = (parts * 2).min(edges.len()); + } + } + edges + } + + fn drop_empty_ticks(&mut self, mut items: Vec) -> Vec { + let mut index = 0usize; + while index < items.len() && !self.partial { + if !items[index].edges.is_empty() { + index += 1; + continue; + } + let mut candidate = items.clone(); + candidate.remove(index); + match self.probe(&candidate) { + Some(true) => items = candidate, + None => break, + Some(false) => index += 1, + } + } + if tighter(&self.best, &items) { + self.best.clone() + } else { + items + } + } +} + +fn splice(items: &[TickActions], index: usize, edges: &[Edge]) -> Vec { + let mut candidate = items.to_vec(); + candidate[index].edges = edges.to_vec(); + candidate +} + +fn tighter(candidate: &[TickActions], best: &[TickActions]) -> bool { + let candidate_edges: usize = candidate.iter().map(|tick| tick.edges.len()).sum(); + let best_edges: usize = best.iter().map(|tick| tick.edges.len()).sum(); + candidate_edges < best_edges || (candidate_edges == best_edges && candidate.len() < best.len()) +} + +impl From for Edge { + fn from(edge: EdgeFile) -> Self { + match edge { + EdgeFile::Hit { + attack_id, + defender, + seq, + heal, + } => Self::Hit { + attack_id, + defender: match defender { + DefenderFile::Cover => Defender::Cover, + DefenderFile::Woven => Defender::Woven, + }, + seq, + heal, + }, + EdgeFile::WeaveDecay => Self::WeaveDecay, + } + } +} + +impl Edge { + fn record(&self) -> EdgeRecord { + match self { + Self::Hit { + attack_id, + defender, + seq, + heal, + } => EdgeRecord::Hit { + attack_id: *attack_id, + defender: match defender { + Defender::Cover => "cover", + Defender::Woven => "woven", + } + .to_string(), + seq: *seq, + heal: *heal, + }, + Self::WeaveDecay => EdgeRecord::WeaveDecay {}, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hit(seq: u32) -> TickActions { + TickActions { + edges: vec![Edge::Hit { + attack_id: 1, + defender: Defender::Cover, + seq, + heal: false, + }], + } + } + + #[test] + fn replay_aravath_slice_scenario() { + let scenario = load_bundled_scenario().expect("scenario"); + let first = run_scenario(&scenario); + let second = run_scenario(&scenario); + let RunOutcome::Pass(first) = first else { + panic!("scripted and goal traces diverged or Reach failed"); + }; + let RunOutcome::Pass(second) = second else { + panic!("second run failed"); + }; + assert_eq!(first.trace_sha256, second.trace_sha256); + assert_eq!( + first.trace_sha256, "ef7e38b580f2d157041d2d58bc0cac41dcf1442ac0ff6064d6ba52039adfc089", + "gameplay_qa_aravath_slice digest drifted" + ); + assert_eq!(first.slice.sword_hp, 15); + assert_eq!(first.slice.weave_hp, 25); + assert!(!first.slice.cover_intact); + assert!(first.slice.cover_damage >= 25); + let path = write_replay_case(&first.trace_sha256).expect("write case"); + let body = std::fs::read_to_string(&path).expect("read case"); + assert!(body.contains(CASE_NAME)); + assert!(body.contains(&first.trace_sha256)); + println!("{CASE_NAME} {}", first.trace_sha256); + } + + #[test] + fn minimizer_is_off_for_pull_requests() { + assert!(!minimize_enabled_from(Some("1"), Some("pull_request"))); + assert!(minimize_enabled_from(Some("1"), Some("push"))); + assert!(minimize_enabled_from(Some("1"), None)); + assert!(!minimize_enabled_from(None, Some("push"))); + assert!(!minimize_enabled_from(Some("0"), None)); + } + + #[test] + fn ddmin_keeps_the_marked_tick() { + let input = vec![hit(1), hit(2), hit(7), hit(4)]; + let result = minimize(&input, |candidate| { + candidate.iter().any(|tick| { + tick.edges + .iter() + .any(|edge| matches!(edge, Edge::Hit { seq: 7, .. })) + }) + }); + assert!(!result.partial); + assert_eq!(result.ticks, vec![hit(7)]); + assert!(result.calls <= MINIMIZE_BUDGET); + } + + #[test] + fn ddmin_keeps_the_marked_edge_inside_one_tick() { + let input = vec![TickActions { + edges: vec![ + Edge::WeaveDecay, + Edge::Hit { + attack_id: 1, + defender: Defender::Cover, + seq: 7, + heal: false, + }, + Edge::WeaveDecay, + ], + }]; + let result = minimize(&input, |candidate| { + candidate.iter().any(|tick| { + tick.edges + .iter() + .any(|edge| matches!(edge, Edge::Hit { seq: 7, .. })) + }) + }); + assert!(!result.partial); + assert_eq!(result.ticks.len(), 1); + assert_eq!( + result.ticks[0].edges, + vec![Edge::Hit { + attack_id: 1, + defender: Defender::Cover, + seq: 7, + heal: false, + }] + ); + } + + #[test] + fn ddmin_stops_at_the_budget() { + let input: Vec<_> = (0..70).map(hit).collect(); + let full = input.clone(); + let result = minimize(&input, |candidate| candidate == full.as_slice()); + assert!(result.partial); + assert_eq!(result.calls, MINIMIZE_BUDGET); + assert_eq!(result.ticks, full); + } + + #[test] + fn a_goal_mismatch_writes_a_minimized_artifact_only_when_asked() { + let scenario = Scenario { + id: "aravath_slice_sword".to_string(), + seed: ARAVATH_SLICE_SEED, + max_ticks: 2, + steps: vec![ + TickActions { + edges: vec![Edge::WeaveDecay], + }, + TickActions { + edges: vec![Edge::WeaveDecay], + }, + ], + objective: "cover_broken".to_string(), + policy: "slice_sword_then_weave".to_string(), + reach: Reach { + by_tick: 1, + sword_hp: 15, + weave_hp: 25, + cover_intact: false, + min_cover_damage: 25, + }, + }; + let RunOutcome::Fail(skipped) = run_scenario_with(&scenario, MinimizeMode::Off) else { + panic!("expected a goal divergence"); + }; + assert_eq!(skipped.failure.kind, "goal_bot_diverged"); + assert_eq!(skipped.minimized, "skipped"); + assert_eq!(skipped.original_len, skipped.minimized_len); + + let RunOutcome::Fail(reduced) = run_scenario_with(&scenario, MinimizeMode::On) else { + panic!("expected a goal divergence"); + }; + assert_eq!(reduced.failure.kind, "goal_bot_diverged"); + assert_eq!(reduced.minimized, "full"); + assert!(reduced.minimized_len < reduced.original_len); + let json = failure_json(&reduced).expect("json"); + let parsed: serde_json::Value = serde_json::from_str(&json).expect("parse"); + assert_eq!(parsed["setup"], "slice"); + assert_eq!(parsed["seed"], "0xA11CE5EE"); + assert_eq!(parsed["failure"]["kind"], "goal_bot_diverged"); + } +} diff --git a/astraweave-weaving/src/lib.rs b/astraweave-weaving/src/lib.rs index 17b4cffe32..790109557b 100644 --- a/astraweave-weaving/src/lib.rs +++ b/astraweave-weaving/src/lib.rs @@ -19,6 +19,7 @@ pub mod damage; pub mod echo_currency; pub mod enemy; pub mod enemy_types; +pub mod gameplay_qa; pub mod intents; pub mod level; pub mod particles; @@ -38,12 +39,13 @@ mod mutation_tests; pub use adjudicator::{WeaveAdjudicator, WeaveConfig}; pub use anchor::{AbilityType, Anchor, AnchorVfxState}; -pub use aravath::{run_aravath_slice, AravathSlice}; +pub use aravath::{run_aravath_slice, AravathSlice, ARAVATH_SLICE_SEED}; pub use audio::{echo_pickup_audio_command, AnchorAudioState, AnchorAudioSystem, AudioCommand}; pub use combat::{CombatEvent, CombatSystem, Killer}; pub use damage::{apply_element_schools, ElementSchool}; pub use echo_currency::{EchoCurrency, Transaction, TransactionReason}; pub use enemy::{AttackTarget, Enemy, EnemyBehavior, EnemyState}; +pub use gameplay_qa::{load_bundled_scenario, run_scenario, FailureArtifact, RunOutcome}; pub use intents::{IntentProposer, WeaveIntent}; pub use level::{Camera, LevelStats, Player, VeilweaverLevel}; pub use particles::{AnchorParticleEmitter, AnchorParticleSystem, Particle, ParticleType}; diff --git a/docs/architecture/weaving.md b/docs/architecture/weaving.md index 66d9d1b449..56f4517637 100644 --- a/docs/architecture/weaving.md +++ b/docs/architecture/weaving.md @@ -9,7 +9,7 @@ lifecycle_status: in_design integration_status: example_only summary: "Zero library consumers (only examples/advanced_content_demo + veilweaver_quest_demo); systems/* take Vec/slice params, not Query/Res — not registerable as ECS systems as written. weaving.md §1,§8" owns: [astraweave-weaving] -doc_version: "1.2" +doc_version: "1.3" last_verified_commit: 7c29b8182 --- @@ -21,7 +21,7 @@ last_verified_commit: 7c29b8182 |---|---| | **System name** | Weaving / Fate-Weaving System (the Veilweaver signature mechanic) | | **Primary crates** | `astraweave-weaving` | -| **Document version** | 1.2 | +| **Document version** | 1.3 | | **Last verified against commit** | `7c29b8182` | | **Last verified date** | 2026-06-25 | | **Status** | In-Design-but-tested (heavily unit-tested; consumed only by two non-runtime examples) | @@ -230,7 +230,10 @@ This crate hosts **two distinct pipelines** that do not call each other. Both ar | File | Role | Status | Notes | |---|---|---|---| -| [`lib.rs`](../../astraweave-weaving/src/lib.rs) | Module roots, re-exports, `CWeaveAgent`/`CWeaveSignal`/`WeaveIntentEvent` ECS-style components | Active | `#![forbid(unsafe_code)]`. The three components have no in-crate consumer (no ECS in this crate). | +| [`lib.rs`](../../astraweave-weaving/src/lib.rs) | Module roots, re-exports, `CWeaveAgent`/`CWeaveSignal`/`WeaveIntentEvent` ECS-style components | Active | `#![forbid(unsafe_code)]`. | +| [`aravath.rs`](../../astraweave-weaving/src/aravath.rs) | `run_aravath_slice`, `ARAVATH_SLICE_SEED` (`0xA11C_E5EE`) | Active | One combat resolve plus one destruction tick. Sword hp 15, weave hp 25, cover bond broken. | +| [`gameplay_qa.rs`](../../astraweave-weaving/src/gameplay_qa.rs) | Scenario loader, scripted and goal policies, failure artifact, ddmin | Active | Scenario 1 calls `run_aravath_slice` once per trace. It does not split the function. | +| [`scenarios/aravath_slice_sword.ron`](../../astraweave-weaving/scenarios/aravath_slice_sword.ron) | Scenario 1 | Active | Reach check only. `SaveReload` and `SameSeqTwice` are not in this file. | | [`patterns.rs`](../../astraweave-weaving/src/patterns.rs) | Emergent pattern detection (4 detectors) | Active | Pure functions over `WorldMetrics`. | | [`intents.rs`](../../astraweave-weaving/src/intents.rs) | `WeaveIntent` + 4 proposers | Active | Builder-style intent. | | [`adjudicator.rs`](../../astraweave-weaving/src/adjudicator.rs) | `WeaveAdjudicator` + `WeaveConfig` (TOML) | Active | Budget/cooldown/priority gate. | @@ -337,6 +340,15 @@ This crate hosts **two distinct pipelines** that do not call each other. Both ar - **Alternatives considered:** [Reasoning not recovered]. - **Consequences:** The crate is portable and testable but is dormant scaffolding from a runtime-wiring standpoint (zero library consumers). +### Decision: Scenario 1 calls `run_aravath_slice` once + +- **Date:** 2026-10-15 +- **Status:** Accepted +- **Context:** Gameplay QA needs a headless trace. The slice function is one resolve. +- **Decision:** The RON scenario records the sword hit, the weave hit, and weave decay. Scripted and goal policies must hash equal. ddmin stays off pull requests (`QA_MINIMIZE=1` and the event is not `pull_request`). +- **Alternatives considered:** Splitting the function into a tick loop before the first scenario. Rejected for scenario 1. +- **Consequences:** Save and double-hit checks are not in the first scenario. The trace is integer fields, so the three-OS compare does not hash Rapier `f32`. + --- ## 8. Known Invariants @@ -353,6 +365,7 @@ This crate hosts **two distinct pipelines** that do not call each other. Both ar | 8 | An anchor repair only reports an ability unlock when the anchor's pre-repair stability was `< 0.7`. | Yes | `anchor_repair_system.rs:91-99`; `test_ability_not_unlocked_if_stable`. | | 9 | Anchor particle positions and velocities are a function of `(world_seed, tick, SIM_SYSTEM_ANCHOR_PARTICLES)` via `SimRng`. Draws are dyadic `f32`s plus IEEE `sqrt`; no `rand::random` and no `sin`/`cos`. | Yes | `sim_rng.rs`, `particles/anchor_particle.rs`; test `particle_spawn_state_is_bit_identical_for_the_same_seed`. | | 10 | Enemy patrol targets and wave spawn positions are a function of `(world_seed, draw_index, SIM_SYSTEM_ENEMY_PATROL \| SIM_SYSTEM_SPAWNER)`. Offsets are rejection samples in the disk (`disk_xz`); no `thread_rng` and no `sin`/`cos`. Active spawn ids are sorted before round-robin. | Yes | `enemy.rs`, `spawner.rs`; tests `patrol_target_is_bit_identical_for_the_same_seed`, `spawn_positions_are_bit_identical_for_the_same_seed`. | +| 11 | `run_aravath_slice` is one resolve at `ARAVATH_SLICE_SEED`. The scripted and goal policies of `aravath_slice_sword` finish on the same SHA-256 trace. That digest is required case `gameplay_qa_aravath_slice`. | Yes | `gameplay_qa.rs` test `replay_aravath_slice_scenario`. `determinism-replay.yml` merges `replay-hash-gameplay-qa.json`. | --- @@ -392,11 +405,18 @@ This is a pure-CPU logic crate; performance is benchmark-tracked but not a runti - **Relationship to `veilweaver_slice_runtime`:** A separate `veilweaver_slice_runtime` crate exists and references "veilweaver"/anchor/echo concepts but does **not** depend on `astraweave-weaving` (verified: no `astraweave_weaving` import). Is `astraweave-weaving` superseded by the slice runtime, or are they parallel tracks? This determines whether this crate is in-design or effectively legacy. - **`CWeaveAgent`/`CWeaveSignal`/`WeaveIntentEvent`** (declared in `lib.rs:56-94`) have no in-crate consumer. Are these intended ECS components for a future host integration? - **`astraweave-pcg` usage scope:** `astraweave-pcg` is a declared-but-unused Cargo dep — zero `use`/`pcg` references in `astraweave-weaving/src` (verified 2026-06-24). Whether to wire it or drop the dep remains parked. Spawn positions, archetypes, and patrol targets are seed-driven as of WS-D2 (`SimRng` + `disk_xz`, system ids `SIM_SYSTEM_SPAWNER` / `SIM_SYSTEM_ENEMY_PATROL`). Default `world_seed` is 0. Callers that want a world-specific stream call `set_world_seed` before `update`. +- **Tickable slice session.** Scenario 1 records edges and calls `run_aravath_slice` once. `SaveReload` and `SameSeqTwice` wait until a later change returns the world from that function. Do not add a second resolver beside it. --- ## 12. Maintenance Notes +**Revision history** + +| Version | Date | Notes | +|---|---|---| +| 1.3 | 2026-10-15 | Scenario 1 gameplay QA. File map rows for `aravath.rs`, `gameplay_qa.rs`, and the RON. Invariant 11. | + **Update this doc when:** - A consumer beyond the two examples adopts `astraweave-weaving` (this would flip its wired status — update §1 and §4). - Either of the duplicate repair/currency paths in §6 is unified, or a duplicate enum (`AbilityType`/`CombatEvent`) is reconciled. diff --git a/docs/current/AUTONOMOUS_GAMEPLAY_QA.md b/docs/current/AUTONOMOUS_GAMEPLAY_QA.md index c05e1784ae..8320110a63 100644 --- a/docs/current/AUTONOMOUS_GAMEPLAY_QA.md +++ b/docs/current/AUTONOMOUS_GAMEPLAY_QA.md @@ -1,11 +1,22 @@ # Autonomous gameplay QA -> **Status**: design for review. Nothing in this document is implemented. +> **Status**: scenario 1 is implemented. Later scenarios are still design. > **Date**: 2026-10-15 -> **Branch**: `cursor/gameplay-qa-design-0073` (draft, not for merge) -> **Read against**: `main` at `b7ffb358`, plus the open pull requests named below +> **Branch**: `cursor/gameplay-qa-slice-0073` (rebased onto current `main`, draft, not for merge) +> **Read against**: `main` after #212, #243, #277, and #290 -Synthetic players will attempt objectives in headless, fixed-tick runs and report softlocks, unreachable objectives, save/reload breakage, and simple exploits. Every failure writes one artifact that replays to the same hash trace on Linux, Windows, and macOS. This pass maps the code those runs have to sit on, and stops before any runner, scenario file, or workflow is added. +## Recorded decisions + +Approved 2026-10-15, with two answers applied as written: + +1. Scenario 1 stays the one-tick slice resolve. `run_scenario` calls `run_aravath_slice` once per trace. The scripted policy is the RON edge list. The goal policy `slice_sword_then_weave` emits the same edges from code. The trace hash covers those edges plus the slice fields (`sword_hp`, `weave_hp`, `cover_intact`, `cover_damage`). The function is not split into a tick loop. +2. `run_aravath_slice` is on `main`. #243 has landed, and `destruction` stays a required replay case next to `gameplay_qa_aravath_slice`. + +`SaveReload` and `SameSeqTwice` stay specified below and are not in `scenarios/aravath_slice_sword.ron`. Both need the world the one-tick function does not return. + +The minimizer runs only when `QA_MINIMIZE=1` and `GITHUB_EVENT_NAME` is not `pull_request`. The Linux test and `determinism-replay.yml` do not set `QA_MINIMIZE`. The required case `gameplay_qa_aravath_slice` is the SHA-256 of the passing scripted trace, `ef7e38b580f2d157041d2d58bc0cac41dcf1442ac0ff6064d6ba52039adfc089`, emitted by `replay_aravath_slice_scenario`. Required cases are `planner_pure`, `perception_world`, `gameplay_rng`, `fixed64`, `combat_resolve`, `destruction`, and `gameplay_qa_aravath_slice`. + +Synthetic players will attempt objectives in headless, fixed-tick runs and report softlocks, unreachable objectives, save/reload breakage, and simple exploits. Every failure writes one artifact that replays to the same hash trace on Linux, Windows, and macOS. Scenario 1 is the runner. Later scenarios are still design. Learning-based exploit search is out of scope. The first bots are scripted and goal-driven. @@ -156,9 +167,9 @@ pub enum Bot { The runner: -1. Builds the world with the scenario seed by running the same table install and spawns as `run_aravath_slice`. The function stays the reference for the unsplit end state. The tickable session is that function's steps pulled apart, still calling `install`, `combat_resolve_system`, `enqueue_weave`, and `DestructionWorld::tick`. It is not a new resolver. -2. For each tick, takes `decide`, applies actions in `seq` order, runs the existing systems once, appends the state hash. -3. Evaluates predicates. On failure, writes the artifact and, off the pull-request path, minimizes. +1. Scenario 1 does not rebuild the world. It calls `run_aravath_slice` once for the scripted trace and once for the goal trace. The edges are recorded in the trace. They are not applied as a second resolver. +2. The trace hash is the canonical bytes of those edges plus the slice fields. +3. On failure, the runner builds the JSON artifact. ddmin runs only when `minimize_enabled` is true. `Greybox` adapter, when it exists, maps `Motor` onto `TickInput` and calls `Greybox::step`. `Hit` is not remapped onto the greybox sword: #275 already does that inside `Combat::tick` by calling the whole slice. A greybox scenario that also emits `Hit` would resolve the slice twice. Greybox scenarios use `Motor` only. @@ -173,26 +184,23 @@ Scenario( schema: 1, id: "aravath_slice_sword", seed: 0xA11C_E5EE, - max_ticks: 4, + max_ticks: 1, setup: Slice, bot: Script(steps: [ (edges: [ Hit(attack_id: 1, defender: Cover, seq: 0, heal: false), Hit(attack_id: 3, defender: Woven, seq: 1, heal: false), - WeaveDecay(), + WeaveDecay, ]), ]), + goal: (objective: "cover_broken", policy: "slice_sword_then_weave"), checks: [ Reach(by_tick: 1, sword_hp: 15, weave_hp: 25, cover_intact: false, min_cover_damage: 25), - SaveReload(at_tick: 1, during: Combat), - SameSeqTwice(attack_id: 1, defender: Cover, seq: 0), ], ) ``` -`setup: Slice` is the only setup the first implementation accepts. `setup: Greybox` is reserved and fails load until the greybox adapter exists. `setup: CoreWorld` is not a value: the core replay cases already cover that world. - -`Goal` uses the same file with `bot: Goal(objective: "cover_broken", policy: "slice_sword_then_weave")`. +`setup: Slice` is the only setup the loader accepts. The checked-in file is `astraweave-weaving/scenarios/aravath_slice_sword.ron`. The goal block is required. Its policy emits `slice_program()` in code, and the script above must hash to the same trace. Checks, and the failure condition each one writes: @@ -264,26 +272,24 @@ No new required workflow. No LFS checkout. No renderer. No minimizer on pull req After the slice is on the branch under test: -1. **Pull request, Linux, inside the crate test that already compiles weaving.** One scenario, one seed, `max_ticks: 4`. Test name contains `replay` so profile `ci-pr` does not retry it. Expected time is the combat resolve, well under a second once the crate is built. This is the fast signal. It does not by itself prove macOS. -2. **Three OS, inside `determinism-replay.yml`, one extra case.** Name: `gameplay_qa_aravath_slice`. Value: SHA-256 of the canonical hash trace of the successful scripted run (a passing run still writes the trace; the artifact file is for failures). Emit it the way #212 emits `combat_resolve`: a small JSON file merged into `replay-hash.json` before upload, duplicate case names are an error. The case joins the required set. It does not add a job, a runner, or a path filter. The Windows hash job is already the slow required replay (10.7 minutes on `7512c86a`, compile included). A Q32.32 resolve on top of the combat test #212 already runs is noise next to that compile. +1. **Pull request, Linux, inside the weaving lib tests.** `replay_aravath_slice_scenario` loads the RON, checks Reach, and requires the scripted and goal traces to match. The name contains `replay`, so profile `ci-pr` does not retry it. This is the fast signal. It does not by itself prove macOS. +2. **Three OS, inside `determinism-replay.yml`, one extra case.** Name: `gameplay_qa_aravath_slice`. Value: SHA-256 of the canonical hash trace of the successful scripted run. Emit it the way `combat_resolve` is emitted: `target/replay-hash-gameplay-qa.json` is merged into `replay-hash.json` before upload. Duplicate case names are an error. The required set also keeps `destruction`. 3. **Nightly / `main`, not `pull_request`.** The scenario directory, the goal-bot twin, save/reload twins, and the minimizer when a predicate fails. Hang it on the same schedule as `integration-tests.yml` (push and 04:00 UTC), timeout 30 minutes, `retries = 0`. Three OS compare of those traces. This is where softlock windows of 600 ticks and quest scripts are allowed to live. -Docs-only pulls, including this one, stay docs-only. Determinism on `main` keeps running the four current cases and does not look for `gameplay_qa_aravath_slice` until the implementation PR adds it. Adding the case to the required set before the test exists would fail every pull request. +`replay_aravath_slice_scenario` writes `target/replay-hash-gameplay-qa.json`. The merge step appends that file next to the combat file. Core's replay test still emits `destruction`. The greybox workflow on #205 stays as it is. QA does not call `aravath_greybox`, does not fetch KayKit blobs, and does not take its 90 minute budget. ## First scenario -File, when implementation is allowed: `astraweave-weaving/scenarios/aravath_slice_sword.ron`. +Shipped file: `astraweave-weaving/scenarios/aravath_slice_sword.ron`. Seed `0xA11C_E5EE` (`ARAVATH_SLICE_SEED`). -- Seed `0xA11C_E5EE`, the seed already in `run_aravath_slice`. -- Scripted bot emits the two `HitEvent`s the function already pushes (`sword_light` id 1 at the cover, `weave_bolt` id 3 at the woven target) and the weave-decay command, in one tick, seq order 0 then 1. -- `Reach` matches the unit test: sword hp 15, weave hp 25, cover not intact, cover damage at least 25. -- `SaveReload` at that tick writes `combat_vitals` plus `DestructionWorld::state_hash` through the combat and destruction helpers, loads them into a new app with the same seed and table, and requires the twin hash. It does not call `SaveManager::save`, so `Uuid` and the clock stay out of the trace. -- `SameSeqTwice` replays the sword hit with seq 0 a second time in that tick. The predicate fails if vitals or the destruction hash move. If today's resolver applies the hit twice, the run fails and the artifact is the finding. The design does not pre-decide a resolver change. -- A goal-bot twin of the same file must finish on the same hash trace. A difference is `TerminalMismatch` with detail `goal_bot_diverged`, which means the policy is wrong. It is not a game defect until the scripted run also fails. +- One scripted tick: sword hit id 1, weave hit id 3, then weave decay. `max_ticks` is 1. +- `Reach`: sword hp 15, weave hp 25, cover not intact, cover damage at least 25. +- The goal policy emits that same edge list. A difference writes `goal_bot_diverged`. +- `examples/aravath_slice.rs` calls `load_bundled_scenario` and `run_scenario`. -What this scenario does not claim: a softlock search, a quest, a dialogue, or a greybox fight. Those need a world that can fail to make progress. The slice cannot. +`SaveReload` and `SameSeqTwice` are not in this file. What this scenario does not claim: a softlock search, a quest, a dialogue, a greybox fight, or a save round-trip. Those need a world the one-tick function does not return. ## Later scenarios (specified, not built) @@ -301,8 +307,8 @@ Player-facing strings in those scenarios say Aravath, never the retired product This pull request is the design. It does not merge as part of the work that wrote it. 1. **#223 is already on `main`.** QA fits its tiers. Do not add a required job, and do not cancel `main` pushes. -2. **#243 lands destruction**, including required case `destruction`, only after its workflow is rebased onto current `determinism-replay.yml`. The rebase keeps `gameplay_rng` and `fixed64`, keeps `cancel-in-progress` limited to `pull_request`, and keeps `rust-ci-setup`. #212's destruction crate is a copy waiting to be deleted when that happens. -3. **#212 then keeps combat, `run_aravath_slice`, and `combat_resolve`**, and drops the vendored destruction crate. Head inspected: `5bc00302`. `astraweave-weaving/src/aravath.rs` matches #275 byte for byte. The branch name `cursor/combat-damage-design` is not on the remote; the pull ref is the source of truth. +2. **#243 and #212 are on `main`.** `destruction` and `combat_resolve` stay required. This rebase keeps both and adds `gameplay_qa_aravath_slice`. +3. **#290 is on `main`.** It does not own the slice replay case. 4. **Scenario 1 is implemented on top of that main-line slice**, in a new branch, still not merged from this design. It adds `gameplay_qa_aravath_slice` to the required set in the same commit as the test that emits it. 5. **#205 stays the greybox.** #275 should shrink to the `Combat::tick` call site once #212 and #243 own the crates on `main`. Until then, #275 vendors those crates onto #205 and will conflict with both. Do not start the QA runner on #275 and on #212 at once. 6. **#244, #263, and #264** sit on #205 and change traversal, bridge collapse, and the local field. Greybox goal bots wait until that stack is quiet. A hash recorded against a moving motor is not a regression test. @@ -322,12 +328,12 @@ These block a claim that "gameplay replay" is already cross-OS. They are not fix | Greybox checkpoint omits enemies, motor mode, attack phase, lock, tick, and `cover_broken` | PR #275 / #205 | `greybox_combat_save` is expected to fail until the checkpoint stores those fields. Implement the fields with the scenario, or accept the deferred issue and skip the check | | `auto_save_system` is empty and `replay_system` does not apply events | `astraweave-persistence-ecs` | QA does not call `PersistencePlugin` | | `astraweave-quests` stamps `Utc::now()` and `Instant::now()` | quests trace, crate `astraweave-quests` | Quest scenarios use `astraweave-weaving::QuestManager` and tick counts. The LLM quest layer stays out of the hashed sim until its clocks are tick fields | -| #243's workflow head drops `gameplay_rng` and sets `cancel-in-progress: true` unconditionally | PR #243 | Rebase the workflow as in the merge order before that PR lands. Do not take its required-set as the new baseline | +| The audio rapid-volume test shared `tests/assets` with cleanup | this branch, same fix as #289 | The beep is written in a private temp directory | | Two dialogue graphs (crate runner and editor panel) and two quest crates | quests trace | Bots bind the crate types named above. No third graph and no third quest type | ## Non-goals -- Implementing the runner, the RON loader, the workflow case, or a bot in this pull request. +- Splitting `run_aravath_slice` into a tick loop. Scenario 1 calls it once. - A learned or fuzzing exploit hunter. - Driving the legacy slice game loop, the editor play mode, or the net headless example. - Replacing `recorded_script` or moving the golden hash. diff --git a/docs/current/CI_ARCHITECTURE.md b/docs/current/CI_ARCHITECTURE.md index 0ccac9ec73..e5d829edcd 100644 --- a/docs/current/CI_ARCHITECTURE.md +++ b/docs/current/CI_ARCHITECTURE.md @@ -45,7 +45,7 @@ A new push cancels the previous pull-request run. Pushes to main, tags, and sche | Windows archive, then 3 partitions | `Test (windows, build archive)`, then `Test (windows, 1/3)`, `Test (windows, 2/3)`, `Test (windows, 3/3)` | | MSRV (`rust-version` in the workspace manifest, 1.89.0) | `Minimum Supported Rust Version` | | Rollup of the rows above | `PR Rust checks` | -| Replay hash, Ubuntu / Windows / macOS, then compare. Required cases: `planner_pure`, `perception_world`, `gameplay_rng`. No path filter. | `hash (ubuntu-latest)`, `hash (windows-latest)`, `hash (macos-latest)`, `compare` | +| Replay hash, Ubuntu / Windows / macOS, then compare. Required cases: `planner_pure`, `perception_world`, `gameplay_rng`, `fixed64`, `combat_resolve`, `destruction`, `gameplay_qa_aravath_slice`. No path filter. | `hash (ubuntu-latest)`, `hash (windows-latest)`, `hash (macos-latest)`, `compare` | | cargo-deny, cargo-audit | `Cargo Deny Check`, `Security Audit (cargo-audit)` | These also run on a non-docs pull request when their paths match, and are not in the required set because a path filter would skip them: `net-tests`, trace sync, doc-truth lint, docs. Pack guard and OpenSSF Scorecard run on every pull request. PBR, Editor CI, and AW Editor tests do not run on pull requests. @@ -69,7 +69,7 @@ These also run on a non-docs pull request when their paths match, and are not in ## Determinism -`determinism-replay.yml` runs on every pull request and on push to `main`. It has no path filter. Each OS runs `cargo test -p astraweave-core --test replay_hash` with the baseline CPU pinned (`target-cpu=x86-64` on x86_64; aarch64 stays on the default baseline). `cargo test` has no retry loop. The `compare` job requires `planner_pure`, `perception_world`, and `gameplay_rng` to be present and byte-identical across the three artifacts. +`determinism-replay.yml` runs on every pull request and on push to `main`. It has no path filter. Each OS runs the core replay test, the combat replay test, and `replay_aravath_slice_scenario` with the baseline CPU pinned (`target-cpu=x86-64` on x86_64; aarch64 stays on the default baseline). `cargo test` has no retry loop. The `compare` job requires `planner_pure`, `perception_world`, `gameplay_rng`, `fixed64`, `combat_resolve`, `destruction`, and `gameplay_qa_aravath_slice` to be present and byte-identical across the three artifacts. When the same tests also run under nextest (an affected crate on a pull request, or the full nightly matrix), `.config/nextest.toml` profile `ci` sets `retries = 2` for ordinary tests and `retries = 0` for test names matching `determinism`, `replay`, or `deterministic`. The determinism workflow does not call nextest. diff --git a/scripts/ci/test_workflow_policy.py b/scripts/ci/test_workflow_policy.py index 17c03c5162..47bfee0360 100644 --- a/scripts/ci/test_workflow_policy.py +++ b/scripts/ci/test_workflow_policy.py @@ -164,7 +164,13 @@ def test_deferred_pr_filter_matches_the_list_and_skips_replay(self) -> None: self.assertIn(f"test(={test})", profile) if binary == package: self.fail(f"lib binary should be the underscore target name, got {binary}") - for replay in ("planner_pure", "perception_world", "gameplay_rng", "replay_hash"): + for replay in ( + "planner_pure", + "perception_world", + "gameplay_rng", + "replay_hash", + "gameplay_qa_aravath_slice", + ): self.assertNotIn(replay, profile) self.assertNotIn(replay, (ROOT / "scripts" / "ci" / "deferred_pr_tests.txt").read_text(encoding="utf-8")) From e5640375c3a9bc0723ac08d2e3930b07523717fa Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 15 Oct 2026 16:34:56 +0000 Subject: [PATCH 2/2] test(audio): keep rapid volume changes off the shared asset dir The Windows archive deleted tests/assets while this test still had a wav there. Write the beep in a private temp directory instead. Co-authored-by: Andrew Brown --- astraweave-audio/tests/advanced_edge_cases.rs | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/astraweave-audio/tests/advanced_edge_cases.rs b/astraweave-audio/tests/advanced_edge_cases.rs index 3691677f51..5c97b4dd86 100644 --- a/astraweave-audio/tests/advanced_edge_cases.rs +++ b/astraweave-audio/tests/advanced_edge_cases.rs @@ -335,18 +335,18 @@ n0 = "tests/assets/override_test/NONEXISTENT.wav" #[serial] fn test_rapid_master_volume_changes() -> Result<()> { let mut engine = AudioEngine::new()?; + // Private directory. A shared `tests/assets` path races with + // `cleanup_test_assets`, which deletes that tree from another test. + let dir = tempfile::tempdir()?; + let wav = dir.path().join("rapid.wav"); + let wav_str = wav + .to_str() + .ok_or_else(|| anyhow::anyhow!("temp wav path is not utf-8"))?; - test_asset_generator::generate_test_beep( - "tests/assets/test_beep_rapid.wav", - 440.0, - 1.0, - 22050, - )?; + test_asset_generator::generate_test_beep(wav_str, 440.0, 1.0, 22050)?; - // Play a long sound - engine.play_sfx_file("tests/assets/test_beep_rapid.wav")?; + engine.play_sfx_file(wav_str)?; - // Rapidly change master volume for i in 0..20 { let volume = (i as f32 / 20.0).clamp(0.0, 1.0); engine.set_master_volume(volume); @@ -354,8 +354,5 @@ fn test_rapid_master_volume_changes() -> Result<()> { thread::sleep(Duration::from_millis(10)); } - // Cleanup - fs::remove_file("tests/assets/test_beep_rapid.wav")?; - Ok(()) }