From d0c1c24946a14b9607f17d9593e65f334781fa0e Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 15 Oct 2026 15:58:55 +0000 Subject: [PATCH 1/3] feat(ai): add a zero-cost decision ring and headless inspector decision-trace stays off by default, so the record sites compile out and the six required replay cases are unchanged. With the feature on, a preallocated ring records the plan and a null sink hashes to the same plan bytes. aw_decision prints one Aravath bridge tick and a sealed-cell counterfactual. Co-authored-by: Andrew Brown --- Cargo.lock | 10 + Cargo.toml | 1 + astraweave-ai/Cargo.toml | 3 + astraweave-ai/benches/htn_budget.rs | 4 + astraweave-ai/src/decision_trace.rs | 1122 +++++++++++++++++ astraweave-ai/src/ecs_ai_plugin.rs | 60 + astraweave-ai/src/htn.rs | 250 +++- astraweave-ai/src/lib.rs | 13 + astraweave-ai/tests/decision_trace_alloc.rs | 59 + astraweave-ai/tests/decision_trace_hash.rs | 146 +++ astraweave-ai/tests/zero_alloc_tick.rs | 24 +- astraweave-ecs/src/lib.rs | 32 + docs/architecture/ai_pipeline.md | 9 +- docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md | 13 +- examples/hello_companion/Cargo.toml | 1 + examples/hello_companion/src/main.rs | 47 +- tools/aw_decision/Cargo.toml | 16 + tools/aw_decision/src/lib.rs | 166 +++ tools/aw_decision/src/main.rs | 123 ++ 19 files changed, 2070 insertions(+), 29 deletions(-) create mode 100644 astraweave-ai/src/decision_trace.rs create mode 100644 astraweave-ai/tests/decision_trace_alloc.rs create mode 100644 astraweave-ai/tests/decision_trace_hash.rs create mode 100644 tools/aw_decision/Cargo.toml create mode 100644 tools/aw_decision/src/lib.rs create mode 100644 tools/aw_decision/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 68a50dc4a8..87aca7ec89 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -586,6 +586,7 @@ dependencies = [ "serde", "serde_json", "serial_test", + "sha2", "tempfile", "tokio", "toml 0.8.23", @@ -2159,6 +2160,15 @@ dependencies = [ "wgpu", ] +[[package]] +name = "aw_decision" +version = "0.1.0" +dependencies = [ + "astraweave-ai", + "astraweave-nav", + "clap", +] + [[package]] name = "aw_demo_builder" version = "0.4.0" diff --git a/Cargo.toml b/Cargo.toml index 0ed490111f..5054db5fcf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -92,6 +92,7 @@ members = [ "astraweave-pcg", "astraweave-weaving", "tools/aw_debug", + "tools/aw_decision", "tools/aw_build", "tools/aw_texture_gen", "tools/aw_headless", diff --git a/astraweave-ai/Cargo.toml b/astraweave-ai/Cargo.toml index 687571ad07..8cf28feaf1 100644 --- a/astraweave-ai/Cargo.toml +++ b/astraweave-ai/Cargo.toml @@ -42,6 +42,8 @@ alloc-counter = ["dep:astraweave-profiling", "astraweave-profiling/alloc-counter # Bench-only allocator swap for the mimalloc experiment. fast-alloc = ["dep:astraweave-alloc", "astraweave-alloc/fast-alloc"] veilweaver_slice = ["dep:astraweave-behavior", "dep:astraweave-observability"] +# Decision ring. Off by default: call sites compile out. +decision-trace = [] [dependencies.astraweave-llm] workspace = true @@ -54,6 +56,7 @@ criterion = { workspace = true } tokio = { workspace = true, features = ["rt", "sync", "time", "macros"] } tempfile = "3.8" serial_test = "3" +sha2 = { workspace = true } [[bench]] name = "ai_core_loop" diff --git a/astraweave-ai/benches/htn_budget.rs b/astraweave-ai/benches/htn_budget.rs index 75ecfa7839..f22a72d7fd 100644 --- a/astraweave-ai/benches/htn_budget.rs +++ b/astraweave-ai/benches/htn_budget.rs @@ -24,6 +24,10 @@ fn bench_htn_expansions(c: &mut Criterion) { 1, &mut plan, &mut budget, + #[cfg(feature = "decision-trace")] + &mut astraweave_ai::decision_trace::NullSink, + #[cfg(feature = "decision-trace")] + 1u64, ); if budget == before { break; diff --git a/astraweave-ai/src/decision_trace.rs b/astraweave-ai/src/decision_trace.rs new file mode 100644 index 0000000000..f8b9c933bd --- /dev/null +++ b/astraweave-ai/src/decision_trace.rs @@ -0,0 +1,1122 @@ +//! Decision ring for one agent at one tick. +//! +//! Compiled only with `decision-trace`. Shipping builds omit this module. +//! [`DecisionTrace::new`] allocates the rings once. [`DecisionTrace::push`] +//! writes a slot and does not allocate. + +#![forbid(unsafe_code)] + +use astraweave_core::{ActionStep, EngineError, IVec2, WorldSnapshot}; + +use crate::htn::{self, plan_route, AgentPlan, SpatialHooks}; +use crate::orchestrator::Orchestrator; + +pub const ALT_CAP: usize = 4; +pub const RECORD_CAP: usize = 128; +pub const AGENT_CAP: usize = 32; +const WALK_CAP: usize = 8; + +#[repr(u8)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PlannerId { + None = 0, + Rule = 1, + BehaviorTree = 2, + GoapHeuristic = 3, + Utility = 4, + Htn = 5, +} + +#[repr(u16)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GoalId { + None = 0, + Cross = 1, + Engage = 2, + Hold = 3, + Extract = 4, +} + +#[repr(u16)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ActionCode { + Empty = 0, + MoveTo = 1, + UseBreach = 2, + TakeCover = 3, + Wait = 4, + ThrowSmoke = 5, + CoverFire = 6, +} + +#[repr(u16)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RejectCode { + Selected = 0, + LowerScore = 1, + Cooldown = 2, + SealedCell = 3, + OutOfBand = 4, + BudgetExhausted = 5, + NoPath = 6, + TieLostToLowerId = 7, +} + +#[repr(u16)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FailCode { + Ok = 0, + InvalidAction = 1, + Cooldown = 2, + LosBlocked = 3, + NoPath = 4, + Resource = 5, + Pending = 6, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AltScore { + pub action: u16, + pub reject: u16, + pub score: i32, + pub a: i32, + pub b: i32, +} + +impl AltScore { + pub const EMPTY: Self = Self { + action: 0, + reject: 0, + score: 0, + a: 0, + b: 0, + }; +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PerceivedView { + pub self_x: i32, + pub self_y: i32, + pub ammo: i32, + pub morale_milli: i32, + pub smoke_cd_milli: i32, + pub enemy_count: u8, + pub nearest_x: i32, + pub nearest_y: i32, + pub nearest_hp: i32, + pub obstacle_count: u16, + pub breach_len: u8, + pub breach_portal: u32, + pub breach_x: i32, + pub breach_y: i32, + pub lost_cover_len: u8, + pub lost_cover_id: u32, +} + +impl PerceivedView { + pub const EMPTY: Self = Self { + self_x: 0, + self_y: 0, + ammo: 0, + morale_milli: 0, + smoke_cd_milli: 0, + enemy_count: 0, + nearest_x: 0, + nearest_y: 0, + nearest_hp: 0, + obstacle_count: 0, + breach_len: 0, + breach_portal: 0, + breach_x: 0, + breach_y: 0, + lost_cover_len: 0, + lost_cover_id: 0, + }; +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BeliefView { + pub fact_hash: u64, + pub strength_milli: i32, + pub source: u8, + pub stat_mask: u16, +} + +impl BeliefView { + pub const EMPTY: Self = Self { + fact_hash: 0, + strength_milli: 0, + source: 0, + stat_mask: 0, + }; +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DecisionRecord { + pub tick: u64, + pub entity_id: u64, + pub planner: u8, + pub band: u8, + pub goal: u16, + pub selected: u16, + pub selected_score: i32, + pub param0: i32, + pub param1: i32, + pub outcome: u8, + pub fail: u16, + pub alt_len: u8, + pub alts: [AltScore; ALT_CAP], + pub perceived: PerceivedView, + pub belief: BeliefView, +} + +impl DecisionRecord { + pub const EMPTY: Self = Self { + tick: 0, + entity_id: 0, + planner: 0, + band: 0, + goal: 0, + selected: 0, + selected_score: 0, + param0: 0, + param1: 0, + outcome: 0, + fail: FailCode::Pending as u16, + alt_len: 0, + alts: [AltScore::EMPTY; ALT_CAP], + perceived: PerceivedView::EMPTY, + belief: BeliefView::EMPTY, + }; +} + +#[derive(Clone, Copy, Debug)] +pub struct TickSample { + pub record: DecisionRecord, + /// Milli-unit position the spatial planner started from. + pub pos_milli: [i32; 3], + /// Milli-unit goal the spatial planner walked toward. + pub goal_milli: [i32; 3], +} + +impl TickSample { + #[must_use] + pub const fn from_record(record: DecisionRecord) -> Self { + Self { + record, + pos_milli: [0; 3], + goal_milli: [0; 3], + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Patch { + NearestEnemy { x: i32, y: i32 }, + SmokeCooldownMilli(i32), + Ammo(i32), + SealCell { x: i32, y: i32 }, + GoalMilli { x: i32, y: i32, z: i32 }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DecisionDiff { + pub tick: u64, + pub entity_id: u64, + pub before: u16, + pub after: u16, + pub before_score: i32, + pub after_score: i32, + pub alt_len: u8, + pub alts: [AltScore; ALT_CAP], +} + +pub struct PlannerView<'a> { + pub tiles: &'a astraweave_nav::NavTiles, + pub scratch: &'a mut astraweave_nav::NavScratch, + pub hooks: SpatialHooks<'a>, +} + +#[derive(Clone, Copy, Debug)] +pub struct AltList { + items: [AltScore; WALK_CAP], + len: u8, +} + +impl AltList { + #[must_use] + pub const fn new() -> Self { + Self { + items: [AltScore::EMPTY; WALK_CAP], + len: 0, + } + } + + pub fn clear(&mut self) { + self.len = 0; + } + + pub fn push(&mut self, alt: AltScore) { + if (self.len as usize) < WALK_CAP { + self.items[self.len as usize] = alt; + self.len += 1; + return; + } + for i in 1..WALK_CAP { + self.items[i - 1] = self.items[i]; + } + self.items[WALK_CAP - 1] = alt; + } + + /// Keep up to four rejects. The chosen `(action, a)` pair is left out. + #[must_use] + pub fn rejects(&self, winner_action: u16, winner_a: i32) -> ([AltScore; ALT_CAP], u8) { + let mut out = [AltScore::EMPTY; ALT_CAP]; + let mut n = 0u8; + for alt in self.items.iter().take(self.len as usize) { + if alt.action == winner_action && alt.a == winner_a { + continue; + } + if n == ALT_CAP as u8 { + for i in 1..ALT_CAP { + out[i - 1] = out[i]; + } + out[ALT_CAP - 1] = *alt; + } else { + out[n as usize] = *alt; + n += 1; + } + } + (out, n) + } +} + +impl Default for AltList { + fn default() -> Self { + Self::new() + } +} + +struct AgentRing { + entity_id: u64, + records: [DecisionRecord; RECORD_CAP], + head: u16, + count: u16, +} + +impl AgentRing { + const fn empty() -> Self { + Self { + entity_id: 0, + records: [DecisionRecord::EMPTY; RECORD_CAP], + head: 0, + count: 0, + } + } +} + +/// Preallocated rings for [`AGENT_CAP`] agents. +pub struct DecisionTrace { + agents: Box<[AgentRing]>, + len: u16, +} + +impl DecisionTrace { + #[must_use] + pub fn new() -> Self { + let mut agents = Vec::with_capacity(AGENT_CAP); + for _ in 0..AGENT_CAP { + agents.push(AgentRing::empty()); + } + Self { + agents: agents.into_boxed_slice(), + len: 0, + } + } + + /// Bind `entity_id`. A second bind of the same id is a no-op success. + /// Entity id 0 and a 33rd distinct id are refused. + pub fn bind(&mut self, entity_id: u64) -> bool { + if entity_id == 0 { + return false; + } + if self.index_of(entity_id).is_some() { + return true; + } + if self.len as usize >= AGENT_CAP { + return false; + } + let slot = &mut self.agents[self.len as usize]; + slot.entity_id = entity_id; + slot.head = 0; + slot.count = 0; + self.len += 1; + true + } + + #[must_use] + pub fn agent_count(&self) -> u16 { + self.len + } + + pub fn push(&mut self, record: &DecisionRecord) -> bool { + let Some(index) = self.index_of(record.entity_id) else { + return false; + }; + let slot = &mut self.agents[index]; + let write_at = (slot.head as usize) & (RECORD_CAP - 1); + slot.records[write_at] = *record; + slot.head = slot.head.wrapping_add(1); + if (slot.count as usize) < RECORD_CAP { + slot.count += 1; + } + true + } + + #[must_use] + pub fn count_of(&self, entity_id: u64) -> u16 { + self.index_of(entity_id) + .map(|index| self.agents[index].count) + .unwrap_or(0) + } + + #[must_use] + pub fn find_tick(&self, entity_id: u64, tick: u64) -> Option<&DecisionRecord> { + let index = self.index_of(entity_id)?; + let slot = &self.agents[index]; + let n = slot.count as usize; + for age in 0..n { + let idx = newest_index(slot.head, age); + let record = &slot.records[idx]; + if record.tick == tick { + return Some(record); + } + } + None + } + + pub fn store_outcome(&mut self, entity_id: u64, tick: u64, code: FailCode) -> bool { + let Some(index) = self.index_of(entity_id) else { + return false; + }; + let slot = &mut self.agents[index]; + let n = slot.count as usize; + for age in 0..n { + let idx = newest_index(slot.head, age); + if slot.records[idx].tick == tick { + slot.records[idx].fail = code as u16; + slot.records[idx].outcome = outcome_byte(code); + return true; + } + } + false + } + + pub fn amend_band(&mut self, entity_id: u64, tick: u64, band: u8) { + let Some(index) = self.index_of(entity_id) else { + return; + }; + let slot = &mut self.agents[index]; + if slot.count == 0 { + return; + } + let idx = newest_index(slot.head, 0); + if slot.records[idx].tick == tick { + slot.records[idx].band = band; + } + } + + fn index_of(&self, entity_id: u64) -> Option { + self.agents[..self.len as usize] + .iter() + .position(|slot| slot.entity_id == entity_id) + } +} + +impl Default for DecisionTrace { + fn default() -> Self { + Self::new() + } +} + +fn newest_index(head: u16, age: usize) -> usize { + (head.wrapping_sub(1).wrapping_sub(age as u16) as usize) & (RECORD_CAP - 1) +} + +fn outcome_byte(code: FailCode) -> u8 { + match code { + FailCode::Pending => 0, + FailCode::Ok => 1, + _ => 2, + } +} + +pub trait DecisionSink { + fn record(&mut self, record: &DecisionRecord); + fn amend_band(&mut self, entity_id: u64, tick: u64, band: u8) { + let _ = (entity_id, tick, band); + } +} + +/// Sink that drops the record. The planner result does not read it. +pub struct NullSink; + +impl DecisionSink for NullSink { + #[inline(always)] + fn record(&mut self, _record: &DecisionRecord) {} +} + +impl DecisionSink for DecisionTrace { + fn record(&mut self, record: &DecisionRecord) { + let _ = self.push(record); + } + + fn amend_band(&mut self, entity_id: u64, tick: u64, band: u8) { + DecisionTrace::amend_band(self, entity_id, tick, band); + } +} + +/// One-record sink used by [`rerun`] so the live ring stays put. +pub struct CaptureSink { + pub record: DecisionRecord, + pub wrote: bool, +} + +impl DecisionSink for CaptureSink { + fn record(&mut self, record: &DecisionRecord) { + self.record = *record; + self.wrote = true; + } +} + +impl Default for CaptureSink { + fn default() -> Self { + Self { + record: DecisionRecord::EMPTY, + wrote: false, + } + } +} + +impl CaptureSink { + #[must_use] + pub const fn new() -> Self { + Self { + record: DecisionRecord::EMPTY, + wrote: false, + } + } +} + +#[must_use] +pub fn tick_from_time(t: f32) -> u64 { + if t.is_finite() && t >= 0.0 { + (t * 1000.0) as u64 + } else { + 0 + } +} + +#[must_use] +pub fn goal_from_objective(objective: Option<&str>) -> u16 { + match objective { + Some("cross") => GoalId::Cross as u16, + Some("engage") => GoalId::Engage as u16, + Some("hold") => GoalId::Hold as u16, + Some("extract") => GoalId::Extract as u16, + _ => GoalId::None as u16, + } +} + +#[must_use] +pub fn perceived_from_snap(snap: &WorldSnapshot) -> PerceivedView { + let enemy = snap.enemies.first(); + let cd = snap.me.cooldowns.get("throw:smoke").copied().unwrap_or(0.0); + let breach = snap.pois.iter().find(|poi| poi.k == "breach"); + let lost = snap.pois.iter().find(|poi| poi.k == "cover_lost"); + PerceivedView { + self_x: snap.me.pos.x, + self_y: snap.me.pos.y, + ammo: snap.me.ammo, + morale_milli: (snap.me.morale * 1000.0) as i32, + smoke_cd_milli: if cd.is_finite() { + (cd * 1000.0) as i32 + } else { + 0 + }, + enemy_count: u8::try_from(snap.enemies.len()).unwrap_or(u8::MAX), + nearest_x: enemy.map(|enemy| enemy.pos.x).unwrap_or(0), + nearest_y: enemy.map(|enemy| enemy.pos.y).unwrap_or(0), + nearest_hp: enemy.map(|enemy| enemy.hp).unwrap_or(0), + obstacle_count: u16::try_from(snap.obstacles.len()).unwrap_or(u16::MAX), + breach_len: u8::from(breach.is_some()), + breach_portal: 0, + breach_x: breach.map(|poi| poi.pos.x).unwrap_or(0), + breach_y: breach.map(|poi| poi.pos.y).unwrap_or(0), + lost_cover_len: u8::from(lost.is_some()), + lost_cover_id: 0, + } +} + +pub fn record_rule( + trace: &mut DecisionTrace, + entity_id: u64, + tick: u64, + snap: &WorldSnapshot, + plan: &astraweave_core::PlanIntent, +) { + let _ = trace.bind(entity_id); + trace.record(&grid_record( + entity_id, + tick, + PlannerId::Rule as u8, + snap, + plan, + 0, + [], + )); +} + +pub fn record_utility(trace: &mut DecisionTrace, entity_id: u64, tick: u64, snap: &WorldSnapshot) { + let _ = trace.bind(entity_id); + trace.record(&utility_decision(entity_id, tick, snap)); +} + +fn grid_record( + entity_id: u64, + tick: u64, + planner: u8, + snap: &WorldSnapshot, + plan: &astraweave_core::PlanIntent, + score: i32, + alts: impl IntoIterator, +) -> DecisionRecord { + let (selected, param0, param1) = + plan.steps + .first() + .map(action_of_step) + .unwrap_or((ActionCode::Empty as u16, 0, 0)); + let mut record = DecisionRecord::EMPTY; + record.tick = tick; + record.entity_id = entity_id; + record.planner = planner; + record.goal = goal_from_objective(snap.objective.as_deref()); + record.selected = selected; + record.selected_score = score; + record.param0 = param0; + record.param1 = param1; + record.outcome = outcome_byte(FailCode::Pending); + record.fail = FailCode::Pending as u16; + record.perceived = perceived_from_snap(snap); + record.belief = BeliefView::EMPTY; + for alt in alts { + if record.alt_len == ALT_CAP as u8 { + break; + } + record.alts[record.alt_len as usize] = alt; + record.alt_len += 1; + } + record +} + +#[must_use] +pub fn utility_decision(entity_id: u64, tick: u64, snap: &WorldSnapshot) -> DecisionRecord { + let Some(pair) = htn::utility_pair(snap) else { + let plan = astraweave_core::PlanIntent { + plan_id: String::new(), + steps: Vec::new(), + }; + return grid_record( + entity_id, + tick, + PlannerId::Utility as u8, + snap, + &plan, + 0, + [], + ); + }; + let choose_smoke = pair.smoke >= pair.advance; + let (selected, score, param0, param1, reject, other_score) = if choose_smoke { + let mid_x = (pair.me_x + pair.enemy_x) / 2; + let mid_y = (pair.me_y + pair.enemy_y) / 2; + ( + ActionCode::ThrowSmoke as u16, + pair.smoke, + mid_x, + mid_y, + if pair.smoke == pair.advance { + RejectCode::TieLostToLowerId + } else { + RejectCode::LowerScore + }, + pair.advance, + ) + } else { + ( + ActionCode::MoveTo as u16, + pair.advance, + pair.me_x + (pair.enemy_x - pair.me_x).signum(), + pair.me_y + (pair.enemy_y - pair.me_y).signum(), + if pair.smoke == i32::MIN { + RejectCode::Cooldown + } else { + RejectCode::LowerScore + }, + pair.smoke, + ) + }; + let other_action = if choose_smoke { + ActionCode::MoveTo as u16 + } else { + ActionCode::ThrowSmoke as u16 + }; + let mut record = DecisionRecord::EMPTY; + record.tick = tick; + record.entity_id = entity_id; + record.planner = PlannerId::Utility as u8; + record.goal = goal_from_objective(snap.objective.as_deref()); + record.selected = selected; + record.selected_score = score; + record.param0 = param0; + record.param1 = param1; + record.outcome = outcome_byte(FailCode::Pending); + record.fail = FailCode::Pending as u16; + record.alt_len = 1; + record.alts[0] = AltScore { + action: other_action, + reject: reject as u16, + score: other_score, + a: pair.enemy_x, + b: pair.enemy_y, + }; + record.perceived = perceived_from_snap(snap); + record +} + +#[must_use] +pub fn action_of_step(step: &ActionStep) -> (u16, i32, i32) { + match step { + ActionStep::MoveTo { x, y, .. } => (ActionCode::MoveTo as u16, *x, *y), + ActionStep::Throw { x, y, .. } => (ActionCode::ThrowSmoke as u16, *x, *y), + ActionStep::CoverFire { target_id, .. } => { + (ActionCode::CoverFire as u16, *target_id as i32, 0) + } + ActionStep::TakeCover { position } => { + let (x, y) = position.map(|pos| (pos.x, pos.y)).unwrap_or((0, 0)); + (ActionCode::TakeCover as u16, x, y) + } + ActionStep::Wait { duration } => (ActionCode::Wait as u16, (*duration * 1000.0) as i32, 0), + _ => (ActionCode::Empty as u16, 0, 0), + } +} + +pub fn store_result( + trace: &mut DecisionTrace, + entity_id: u64, + tick: u64, + result: &Result<(), EngineError>, +) -> bool { + let code = match result { + Ok(()) => FailCode::Ok, + Err(err) => fail_of(err), + }; + trace.store_outcome(entity_id, tick, code) +} + +fn fail_of(err: &EngineError) -> FailCode { + match err { + EngineError::InvalidAction(_) => FailCode::InvalidAction, + EngineError::Cooldown(_) => FailCode::Cooldown, + EngineError::LosBlocked => FailCode::LosBlocked, + EngineError::NoPath => FailCode::NoPath, + EngineError::Resource(_) => FailCode::Resource, + _ => FailCode::InvalidAction, + } +} + +/// Rerun one recorded tick with a single patch. The live plan and the live +/// tiles are not written. `view.scratch` is a caller-owned buffer. +pub fn rerun(sample: TickSample, patch: Patch, view: &mut PlannerView<'_>) -> DecisionDiff { + let mut perceived = sample.record.perceived; + let mut goal = sample.goal_milli; + let pos = sample.pos_milli; + let mut seal: Option<(i32, i32)> = None; + match patch { + Patch::NearestEnemy { x, y } => { + perceived.nearest_x = x; + perceived.nearest_y = y; + perceived.enemy_count = perceived.enemy_count.max(1); + } + Patch::SmokeCooldownMilli(cd) => perceived.smoke_cd_milli = cd, + Patch::Ammo(ammo) => perceived.ammo = ammo, + Patch::SealCell { x, y } => seal = Some((x, y)), + Patch::GoalMilli { x, y, z } => goal = [x, y, z], + } + let planner = sample.record.planner; + let after = if planner == PlannerId::Htn as u8 { + rerun_htn(&sample, pos, goal, seal, view) + } else if planner == PlannerId::Utility as u8 { + let snap = snapshot_from_perceived(sample.record.tick, &perceived, sample.record.goal); + utility_decision(sample.record.entity_id, sample.record.tick, &snap) + } else { + let snap = snapshot_from_perceived(sample.record.tick, &perceived, sample.record.goal); + let plan = crate::RuleOrchestrator.propose_plan(&snap); + grid_record( + sample.record.entity_id, + sample.record.tick, + PlannerId::Rule as u8, + &snap, + &plan, + 0, + [], + ) + }; + let _ = pos; + DecisionDiff { + tick: sample.record.tick, + entity_id: sample.record.entity_id, + before: sample.record.selected, + after: after.selected, + before_score: sample.record.selected_score, + after_score: after.selected_score, + alt_len: after.alt_len, + alts: after.alts, + } +} + +fn rerun_htn( + sample: &TickSample, + pos: [i32; 3], + goal: [i32; 3], + seal: Option<(i32, i32)>, + view: &mut PlannerView<'_>, +) -> DecisionRecord { + let mut hazard_buf = [astraweave_core::LocalHazardHook { + hazard_id: 0, + x: 0, + y: 0, + kind: 0, + }; 8]; + let mut hazard_len = view.hooks.hazards.len().min(8); + hazard_buf[..hazard_len].copy_from_slice(&view.hooks.hazards[..hazard_len]); + if let Some((x, y)) = seal { + if hazard_len < 8 { + hazard_buf[hazard_len] = astraweave_core::LocalHazardHook { + hazard_id: 1, + x, + y, + kind: 1, + }; + hazard_len += 1; + } + } + let hooks = SpatialHooks { + weaving: view.hooks.weaving, + hazards: &hazard_buf[..hazard_len], + }; + let mut plan = AgentPlan::empty(); + let mut budget = htn::HTN_EXPANSIONS_PER_TICK as u32; + let mut capture = CaptureSink::default(); + plan_route( + view.tiles, + view.scratch, + pos, + goal, + &hooks, + sample.record.tick, + &mut plan, + &mut budget, + &mut capture, + sample.record.entity_id, + ); + if capture.wrote { + capture.record + } else { + DecisionRecord::EMPTY + } +} + +fn snapshot_from_perceived(tick: u64, perceived: &PerceivedView, goal: u16) -> WorldSnapshot { + use astraweave_core::{CompanionState, CoverType, EnemyState, PlayerState}; + use std::collections::BTreeMap; + let mut cooldowns = BTreeMap::new(); + if perceived.smoke_cd_milli > 0 { + cooldowns.insert( + "throw:smoke".to_string(), + perceived.smoke_cd_milli as f32 / 1000.0, + ); + } + let enemies = if perceived.enemy_count == 0 { + Vec::new() + } else { + vec![EnemyState { + id: 1, + pos: IVec2 { + x: perceived.nearest_x, + y: perceived.nearest_y, + }, + hp: perceived.nearest_hp, + cover: CoverType::Low, + last_seen: 0.0, + }] + }; + let objective = match goal { + g if g == GoalId::Cross as u16 => Some("cross".to_string()), + g if g == GoalId::Engage as u16 => Some("engage".to_string()), + g if g == GoalId::Hold as u16 => Some("hold".to_string()), + g if g == GoalId::Extract as u16 => Some("extract".to_string()), + _ => None, + }; + WorldSnapshot { + t: tick as f32 / 1000.0, + player: PlayerState { + hp: 100, + pos: IVec2 { x: 0, y: 0 }, + stance: "stand".into(), + orders: Vec::new(), + }, + me: CompanionState { + ammo: perceived.ammo, + cooldowns, + morale: perceived.morale_milli as f32 / 1000.0, + pos: IVec2 { + x: perceived.self_x, + y: perceived.self_y, + }, + }, + enemies, + pois: Vec::new(), + obstacles: Vec::new(), + objective, + } +} + +#[must_use] +pub fn planner_name(id: u8) -> &'static str { + match id { + x if x == PlannerId::Rule as u8 => "rule", + x if x == PlannerId::BehaviorTree as u8 => "behavior", + x if x == PlannerId::GoapHeuristic as u8 => "goap", + x if x == PlannerId::Utility as u8 => "utility", + x if x == PlannerId::Htn as u8 => "htn", + _ => "none", + } +} + +#[must_use] +pub fn action_name(code: u16) -> &'static str { + match code { + x if x == ActionCode::MoveTo as u16 => "move", + x if x == ActionCode::UseBreach as u16 => "use breach", + x if x == ActionCode::TakeCover as u16 => "take cover", + x if x == ActionCode::Wait as u16 => "wait", + x if x == ActionCode::ThrowSmoke as u16 => "throw smoke", + x if x == ActionCode::CoverFire as u16 => "cover fire", + _ => "empty", + } +} + +#[must_use] +pub fn reject_name(code: u16) -> &'static str { + match code { + x if x == RejectCode::Selected as u16 => "selected", + x if x == RejectCode::LowerScore as u16 => "lower score", + x if x == RejectCode::Cooldown as u16 => "cooldown", + x if x == RejectCode::SealedCell as u16 => "sealed cell", + x if x == RejectCode::OutOfBand as u16 => "out of band", + x if x == RejectCode::BudgetExhausted as u16 => "budget exhausted", + x if x == RejectCode::NoPath as u16 => "no path", + x if x == RejectCode::TieLostToLowerId as u16 => "tie lost to lower id", + _ => "unknown", + } +} + +#[must_use] +pub fn goal_name(code: u16) -> &'static str { + match code { + x if x == GoalId::Cross as u16 => "cross", + x if x == GoalId::Engage as u16 => "engage", + x if x == GoalId::Hold as u16 => "hold", + x if x == GoalId::Extract as u16 => "extract", + _ => "none", + } +} + +#[must_use] +pub fn outcome_name(outcome: u8, fail: u16) -> &'static str { + match outcome { + 1 => "ok", + 2 => match fail { + x if x == FailCode::InvalidAction as u16 => "invalid action", + x if x == FailCode::Cooldown as u16 => "cooldown", + x if x == FailCode::LosBlocked as u16 => "line of sight blocked", + x if x == FailCode::NoPath as u16 => "no path", + x if x == FailCode::Resource as u16 => "resource missing", + _ => "failed", + }, + _ => "pending", + } +} + +pub fn format_record(record: &DecisionRecord) -> String { + let mut text = format!( + "tick {tick}\nentity {entity}\nplanner {planner}\nband {band}\ngoal {goal}\nperceived self ({sx}, {sy}) enemies {enemies} breaches {breaches}\nbelief {belief}\nselected {action} {p0} {p1} score {score}\n", + tick = record.tick, + entity = record.entity_id, + planner = planner_name(record.planner), + band = record.band, + goal = goal_name(record.goal), + sx = record.perceived.self_x, + sy = record.perceived.self_y, + enemies = record.perceived.enemy_count, + breaches = record.perceived.breach_len, + belief = if record.belief.fact_hash == 0 { "none" } else { "recorded" }, + action = action_name(record.selected), + p0 = record.param0, + p1 = record.param1, + score = record.selected_score, + ); + for alt in record.alts.iter().take(record.alt_len as usize) { + text.push_str(&format!( + "rejected {action} {a} {b} score {score} {why}\n", + action = action_name(alt.action), + a = alt.a, + b = alt.b, + score = alt.score, + why = reject_name(alt.reject), + )); + } + text.push_str(&format!( + "outcome {outcome}\n", + outcome = outcome_name(record.outcome, record.fail) + )); + text +} + +/// Build the route record from the plan the tick just wrote and the rejects +/// collected while scoring. +#[allow(clippy::too_many_arguments)] +pub fn route_record( + entity_id: u64, + tick: u64, + band: u8, + pos_milli: [i32; 3], + plan: &AgentPlan, + perceived: PerceivedView, + alts: &AltList, + selected_score: i32, +) -> DecisionRecord { + let (selected, param0, param1) = first_slot(plan); + let (rejected, alt_len) = alts.rejects(selected, param0); + let mut record = DecisionRecord::EMPTY; + record.tick = tick; + record.entity_id = entity_id; + record.planner = PlannerId::Htn as u8; + record.band = band; + record.goal = GoalId::Cross as u16; + record.selected = selected; + record.selected_score = selected_score; + record.param0 = param0; + record.param1 = param1; + record.outcome = outcome_byte(FailCode::Pending); + record.fail = FailCode::Pending as u16; + record.alt_len = alt_len; + record.alts = rejected; + record.perceived = perceived; + record.perceived.self_x = pos_milli[0] / 1000; + record.perceived.self_y = pos_milli[2] / 1000; + record +} + +fn first_slot(plan: &AgentPlan) -> (u16, i32, i32) { + for slot in plan.slots.iter().take(plan.len as usize) { + match slot { + htn::ActionSlot::MoveTo { x, y } => return (ActionCode::MoveTo as u16, *x, *y), + htn::ActionSlot::UseBreach { portal_id } => { + return (ActionCode::UseBreach as u16, *portal_id as i32, 0); + } + htn::ActionSlot::TakeCover { cover_id } => { + return (ActionCode::TakeCover as u16, *cover_id as i32, 0); + } + htn::ActionSlot::Wait { duration_milli } => { + return (ActionCode::Wait as u16, *duration_milli as i32, 0); + } + htn::ActionSlot::Empty => {} + } + } + (ActionCode::Empty as u16, 0, 0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ring_wraps_at_one_hundred_twenty_eight() { + let mut trace = DecisionTrace::new(); + assert!(trace.bind(1)); + for tick in 0..129u64 { + let mut record = DecisionRecord::EMPTY; + record.tick = tick; + record.entity_id = 1; + assert!(trace.push(&record)); + } + assert_eq!(trace.count_of(1), RECORD_CAP as u16); + assert!(trace.find_tick(1, 0).is_none()); + assert!(trace.find_tick(1, 1).is_some()); + assert_eq!(trace.find_tick(1, 128).map(|record| record.tick), Some(128)); + } + + #[test] + fn a_thirty_third_agent_is_refused() { + let mut trace = DecisionTrace::new(); + for id in 1..=AGENT_CAP as u64 { + assert!(trace.bind(id), "bind {id}"); + } + assert!(!trace.bind((AGENT_CAP as u64) + 1)); + assert_eq!(trace.agent_count(), AGENT_CAP as u16); + assert!(trace.bind(1)); + assert!(!trace.bind(0)); + } + + #[test] + fn utility_records_the_lower_score_as_rejected() { + use astraweave_core::{CompanionState, EnemyState, IVec2, PlayerState}; + use std::collections::BTreeMap; + let snap = WorldSnapshot { + t: 0.0, + player: PlayerState { + hp: 100, + pos: IVec2 { x: 0, y: 0 }, + stance: "stand".into(), + orders: Vec::new(), + }, + me: CompanionState { + ammo: 10, + cooldowns: BTreeMap::new(), + morale: 1.0, + pos: IVec2 { x: 0, y: 0 }, + }, + enemies: vec![EnemyState { + id: 2, + pos: IVec2 { x: 1, y: 0 }, + hp: 10, + cover: astraweave_core::CoverType::Low, + last_seen: 0.0, + }], + pois: Vec::new(), + obstacles: Vec::new(), + objective: Some("engage".into()), + }; + let record = utility_decision(4, 3, &snap); + assert_eq!(record.planner, PlannerId::Utility as u8); + assert_eq!(record.goal, GoalId::Engage as u16); + assert!(record.alt_len >= 1); + assert_ne!(record.alts[0].action, record.selected); + } +} diff --git a/astraweave-ai/src/ecs_ai_plugin.rs b/astraweave-ai/src/ecs_ai_plugin.rs index cbca1501bf..155c342b7d 100644 --- a/astraweave-ai/src/ecs_ai_plugin.rs +++ b/astraweave-ai/src/ecs_ai_plugin.rs @@ -70,6 +70,8 @@ fn record_plan_outcome( } fn sys_ai_planning(world: &mut ecs::World) { + #[cfg(feature = "decision-trace")] + let mut held = world.take_resource::(); // One planner tick for every companion. Legacy `World` companions and // ECS-only companions are both covered. A missing component or a plan // without MoveTo records `AiPlanningFailedEvent` and does not abort. @@ -152,6 +154,9 @@ fn sys_ai_planning(world: &mut ecs::World) { &mut planned_events, &mut failed_events, ); + crate::decision_record!({ + trace_grid(&mut held, u64::from(comp), &snap, &plan); + }); } } } @@ -243,6 +248,9 @@ fn sys_ai_planning(world: &mut ecs::World) { &mut planned_events, &mut failed_events, ); + crate::decision_record!({ + trace_grid(&mut held, ecs_entity_key(entity), &snap, &plan); + }); } for (entity, desired) in updates { @@ -260,17 +268,69 @@ fn sys_ai_planning(world: &mut ecs::World) { writer.send(event); } } + #[cfg(feature = "decision-trace")] + if let Some(held) = held { + world.restore_resource(held); + } +} + +#[cfg(feature = "decision-trace")] +fn ecs_entity_key(entity: ecs::Entity) -> u64 { + (u64::from(entity.generation()) << 32) | u64::from(entity.id()) +} + +#[cfg(feature = "decision-trace")] +fn trace_grid( + held: &mut Option>, + entity_id: u64, + snap: &WorldSnapshot, + plan: &PlanIntent, +) { + let Some(trace) = held.as_mut() else { + return; + }; + let tick = crate::decision_trace::tick_from_time(snap.t); + if !trace.bind(entity_id) { + return; + } + crate::decision_trace::record_rule(trace, entity_id, tick, snap, plan); + let code = if move_target(plan).is_some() { + crate::decision_trace::FailCode::Pending + } else { + crate::decision_trace::FailCode::InvalidAction + }; + let _ = trace.store_outcome(entity_id, tick, code); } /// Spatial HTN tick. No work unless [`crate::htn::SpatialTick`] was inserted. fn sys_spatial_tick(world: &mut ecs::World) { + #[cfg(feature = "decision-trace")] + let mut held = world.take_resource::(); let Some(tick) = world.get_resource_mut::() else { + #[cfg(feature = "decision-trace")] + if let Some(held) = held { + world.restore_resource(held); + } return; }; let mut scratch = astraweave_nav::NavScratch::new(); let sim_tick = tick.clock; tick.clock = tick.clock.saturating_add(1); + #[cfg(not(feature = "decision-trace"))] crate::htn::tick_agents(tick, &mut scratch, sim_tick); + #[cfg(feature = "decision-trace")] + { + if let Some(ref mut trace) = held { + crate::htn::tick_agents(tick, &mut scratch, sim_tick, trace.as_mut()); + } else { + let mut null = crate::decision_trace::NullSink; + crate::htn::tick_agents(tick, &mut scratch, sim_tick, &mut null); + } + } + #[cfg(feature = "decision-trace")] + if let Some(held) = held { + world.restore_resource(held); + } } impl ecs::Plugin for AiPlanningPlugin { diff --git a/astraweave-ai/src/htn.rs b/astraweave-ai/src/htn.rs index 62deb38700..d0efe9dff6 100644 --- a/astraweave-ai/src/htn.rs +++ b/astraweave-ai/src/htn.rs @@ -213,7 +213,12 @@ pub fn fill_observation(tiles: &NavTiles, buf: &mut ObservationBuf) { /// Advance every agent. Sort key is `(band, entity_id)`. #[allow(clippy::needless_range_loop)] -pub fn tick_agents(tick: &mut SpatialTick, scratch: &mut NavScratch, sim_tick: u64) { +pub fn tick_agents( + tick: &mut SpatialTick, + scratch: &mut NavScratch, + sim_tick: u64, + #[cfg(feature = "decision-trace")] sink: &mut dyn crate::decision_trace::DecisionSink, +) { let wlen = tick.weaving_len as usize; let hlen = tick.hazard_len as usize; let mut weave_buf = [WeaveEffectHook { @@ -285,9 +290,15 @@ pub fn tick_agents(tick: &mut SpatialTick, scratch: &mut NavScratch, sim_tick: u sim_tick, &mut agent.plan, &mut budget, + #[cfg(feature = "decision-trace")] + sink, + #[cfg(feature = "decision-trace")] + agent.entity_id, ); agent.plan.band = 0; agent.ticks_since_plan = 0; + #[cfg(feature = "decision-trace")] + sink.amend_band(agent.entity_id, sim_tick, 0); } 1 => { plan_route( @@ -299,9 +310,15 @@ pub fn tick_agents(tick: &mut SpatialTick, scratch: &mut NavScratch, sim_tick: u sim_tick, &mut agent.plan, &mut budget, + #[cfg(feature = "decision-trace")] + sink, + #[cfg(feature = "decision-trace")] + agent.entity_id, ); agent.plan.band = 1; agent.ticks_since_plan = 0; + #[cfg(feature = "decision-trace")] + sink.amend_band(agent.entity_id, sim_tick, 1); } 2 if agent.plan.len == 0 => { agent.plan.slots[0] = ActionSlot::MoveTo { @@ -312,6 +329,20 @@ pub fn tick_agents(tick: &mut SpatialTick, scratch: &mut NavScratch, sim_tick: u agent.plan.band = 2; agent.plan.tick = sim_tick; budget = budget.saturating_sub(1); + #[cfg(feature = "decision-trace")] + { + let record = crate::decision_trace::route_record( + agent.entity_id, + sim_tick, + 2, + agent.pos_milli, + &agent.plan, + crate::decision_trace::PerceivedView::EMPTY, + &crate::decision_trace::AltList::new(), + 0, + ); + sink.record(&record); + } } _ => { agent.plan.band = band; @@ -332,7 +363,11 @@ pub fn plan_route( sim_tick: u64, out: &mut AgentPlan, budget: &mut u32, + #[cfg(feature = "decision-trace")] sink: &mut dyn crate::decision_trace::DecisionSink, + #[cfg(feature = "decision-trace")] entity_id: u64, ) { + #[cfg(feature = "decision-trace")] + clear_alts(); if *budget == 0 { return; } @@ -387,6 +422,16 @@ pub fn plan_route( } } } + #[cfg(feature = "decision-trace")] + { + let perceived = perceived_for_route(tiles, pos_milli); + let alts = copy_alts(); + let score = route_score(tiles, out); + let record = crate::decision_trace::route_record( + entity_id, sim_tick, 0, pos_milli, out, perceived, &alts, score, + ); + sink.record(&record); + } } fn best_breach(tiles: &NavTiles, scratch: &NavScratch, hooks: &SpatialHooks<'_>) -> Option { @@ -399,6 +444,14 @@ fn best_breach(tiles: &NavTiles, scratch: &NavScratch, hooks: &SpatialHooks<'_>) let cell_x = site.x_milli / 1000; let cell_y = site.z_milli / 1000; if sealed(hooks, cell_x, cell_y) { + #[cfg(feature = "decision-trace")] + push_alt(crate::decision_trace::AltScore { + action: crate::decision_trace::ActionCode::UseBreach as u16, + reject: crate::decision_trace::RejectCode::SealedCell as u16, + score: i32::MIN, + a: id as i32, + b: 0, + }); continue; } let score = -site.x_milli; @@ -409,7 +462,39 @@ fn best_breach(tiles: &NavTiles, scratch: &NavScratch, hooks: &SpatialHooks<'_>) } }; if take { + #[cfg(feature = "decision-trace")] + if let Some((old_id, old_score)) = best { + let reject = if score == old_score { + crate::decision_trace::RejectCode::TieLostToLowerId + } else { + crate::decision_trace::RejectCode::LowerScore + }; + push_alt(crate::decision_trace::AltScore { + action: crate::decision_trace::ActionCode::UseBreach as u16, + reject: reject as u16, + score: old_score, + a: old_id as i32, + b: 0, + }); + } best = Some((id, score)); + } else { + #[cfg(feature = "decision-trace")] + { + let best_score = best.map(|(_, best_score)| best_score).unwrap_or(score); + let reject = if score == best_score { + crate::decision_trace::RejectCode::TieLostToLowerId + } else { + crate::decision_trace::RejectCode::LowerScore + }; + push_alt(crate::decision_trace::AltScore { + action: crate::decision_trace::ActionCode::UseBreach as u16, + reject: reject as u16, + score, + a: id as i32, + b: 0, + }); + } } } best.map(|(id, _)| id) @@ -445,12 +530,99 @@ fn best_cover(tiles: &NavTiles, pos_milli: [i32; 3]) -> Option { Some((id, best_dist)) => dist < best_dist || (dist == best_dist && cover.id < id), }; if take { + #[cfg(feature = "decision-trace")] + if let Some((old_id, old_dist)) = best { + push_alt(crate::decision_trace::AltScore { + action: crate::decision_trace::ActionCode::TakeCover as u16, + reject: crate::decision_trace::RejectCode::LowerScore as u16, + score: -old_dist, + a: old_id as i32, + b: 0, + }); + } best = Some((cover.id, dist)); + } else { + #[cfg(feature = "decision-trace")] + push_alt(crate::decision_trace::AltScore { + action: crate::decision_trace::ActionCode::TakeCover as u16, + reject: crate::decision_trace::RejectCode::LowerScore as u16, + score: -dist, + a: cover.id as i32, + b: 0, + }); } } best.map(|(id, _)| id) } +#[cfg(feature = "decision-trace")] +std::thread_local! { + static ROUTE_ALTS: std::cell::RefCell = + const { std::cell::RefCell::new(crate::decision_trace::AltList::new()) }; +} + +#[cfg(feature = "decision-trace")] +fn clear_alts() { + ROUTE_ALTS.with(|cell| { + if let Ok(mut alts) = cell.try_borrow_mut() { + alts.clear(); + } + }); +} + +#[cfg(feature = "decision-trace")] +fn push_alt(alt: crate::decision_trace::AltScore) { + ROUTE_ALTS.with(|cell| { + if let Ok(mut alts) = cell.try_borrow_mut() { + alts.push(alt); + } + }); +} + +#[cfg(feature = "decision-trace")] +fn copy_alts() -> crate::decision_trace::AltList { + ROUTE_ALTS.with(|cell| { + cell.try_borrow() + .map(|alts| *alts) + .unwrap_or_else(|_| crate::decision_trace::AltList::new()) + }) +} + +#[cfg(feature = "decision-trace")] +fn perceived_for_route( + tiles: &NavTiles, + pos_milli: [i32; 3], +) -> crate::decision_trace::PerceivedView { + let mut perceived = crate::decision_trace::PerceivedView::EMPTY; + perceived.self_x = pos_milli[0] / 1000; + perceived.self_y = pos_milli[2] / 1000; + perceived.breach_len = u8::try_from(tiles.breach_count).unwrap_or(u8::MAX); + if let Some(site) = tiles.breaches.first() { + if tiles.breach_count > 0 { + perceived.breach_portal = site.portal_id; + perceived.breach_x = site.x_milli / 1000; + perceived.breach_y = site.z_milli / 1000; + } + } + perceived.lost_cover_len = u8::try_from(tiles.lost_cover_count).unwrap_or(u8::MAX); + if tiles.lost_cover_count > 0 { + perceived.lost_cover_id = tiles.lost_cover[0].id; + } + perceived +} + +#[cfg(feature = "decision-trace")] +fn route_score(tiles: &NavTiles, plan: &AgentPlan) -> i32 { + for slot in plan.slots.iter().take(plan.len as usize) { + if let ActionSlot::UseBreach { portal_id } = slot { + if let Some(site) = find_breach(tiles, *portal_id) { + return -site.x_milli; + } + } + } + 0 +} + fn band_of(pos: [i32; 3], player: [i32; 3]) -> u8 { let dist = (pos[0] - player[0]).abs() + (pos[2] - player[2]).abs(); if dist <= BAND0_MILLI { @@ -479,31 +651,59 @@ fn plan_from_snapshot(snap: &WorldSnapshot) -> PlanIntent { legacy_steps(snap, plan_id) } -fn legacy_steps(snap: &WorldSnapshot, plan_id: String) -> PlanIntent { - let Some(enemy) = snap.enemies.first() else { - return PlanIntent { - plan_id, - steps: vec![], - }; - }; +pub(crate) struct UtilityPair { + pub smoke: i32, + pub advance: i32, + pub dist: i32, + pub me_x: i32, + pub me_y: i32, + pub enemy_x: i32, + pub enemy_y: i32, + pub enemy_id: u32, +} + +/// Integer smoke-versus-advance scores. Equal scores keep smoke. +pub(crate) fn utility_pair(snap: &WorldSnapshot) -> Option { + let enemy = snap.enemies.first()?; let me = &snap.me; let cd = me.cooldowns.get("throw:smoke").copied().unwrap_or(0.0); let dx = (enemy.pos.x - me.pos.x).abs(); let dy = (enemy.pos.y - me.pos.y).abs(); let dist = dx + dy; - // Integer form of the old scores: smoke 1000 + hp*10, advance 800 + close bonus. - // Higher wins. Equal scores take the lower method id (smoke is 0). - let smoke_score = if cd <= 0.0 { + let smoke = if cd <= 0.0 { 1000 + enemy.hp.saturating_mul(10) } else { i32::MIN }; let close_bonus = (3 - dist).max(0) * 50; - let advance_score = 800 + close_bonus; + Some(UtilityPair { + smoke, + advance: 800 + close_bonus, + dist, + me_x: me.pos.x, + me_y: me.pos.y, + enemy_x: enemy.pos.x, + enemy_y: enemy.pos.y, + enemy_id: enemy.id, + }) +} + +fn legacy_steps(snap: &WorldSnapshot, plan_id: String) -> PlanIntent { + let Some(pair) = utility_pair(snap) else { + return PlanIntent { + plan_id, + steps: vec![], + }; + }; + // Integer form of the old scores: smoke 1000 + hp*10, advance 800 + close bonus. + // Higher wins. Equal scores take the lower method id (smoke is 0). + let smoke_score = pair.smoke; + let advance_score = pair.advance; + let dist = pair.dist; if smoke_score >= advance_score { let mid = IVec2 { - x: (me.pos.x + enemy.pos.x) / 2, - y: (me.pos.y + enemy.pos.y) / 2, + x: (pair.me_x + pair.enemy_x) / 2, + y: (pair.me_y + pair.enemy_y) / 2, }; PlanIntent { plan_id, @@ -515,20 +715,20 @@ fn legacy_steps(snap: &WorldSnapshot, plan_id: String) -> PlanIntent { }, ActionStep::MoveTo { speed: None, - x: me.pos.x + (enemy.pos.x - me.pos.x).signum() * 2, - y: me.pos.y + (enemy.pos.y - me.pos.y).signum() * 2, + x: pair.me_x + (pair.enemy_x - pair.me_x).signum() * 2, + y: pair.me_y + (pair.enemy_y - pair.me_y).signum() * 2, }, ], } } else { let mut steps = vec![ActionStep::MoveTo { speed: None, - x: me.pos.x + (enemy.pos.x - me.pos.x).signum(), - y: me.pos.y + (enemy.pos.y - me.pos.y).signum(), + x: pair.me_x + (pair.enemy_x - pair.me_x).signum(), + y: pair.me_y + (pair.enemy_y - pair.me_y).signum(), }]; if dist <= 3 { steps.push(ActionStep::CoverFire { - target_id: enemy.id, + target_id: pair.enemy_id, duration: 1.0, }); } @@ -624,6 +824,10 @@ mod tests { 1, &mut plan, &mut budget, + #[cfg(feature = "decision-trace")] + &mut crate::decision_trace::NullSink, + #[cfg(feature = "decision-trace")] + 1u64, ); if budget == before { break; @@ -653,6 +857,10 @@ mod tests { 1, &mut plan, &mut budget, + #[cfg(feature = "decision-trace")] + &mut crate::decision_trace::NullSink, + #[cfg(feature = "decision-trace")] + 1u64, ); let before = move_cell(&plan); tiles.mark(astraweave_nav::nav_change_from_kind( @@ -672,6 +880,10 @@ mod tests { 31, &mut plan, &mut budget, + #[cfg(feature = "decision-trace")] + &mut crate::decision_trace::NullSink, + #[cfg(feature = "decision-trace")] + 1u64, ); let after = move_cell(&plan); assert!(before < 8, "bridge path cell {before}"); diff --git a/astraweave-ai/src/lib.rs b/astraweave-ai/src/lib.rs index 29406f8782..b9fc261469 100644 --- a/astraweave-ai/src/lib.rs +++ b/astraweave-ai/src/lib.rs @@ -27,11 +27,24 @@ //! - Validated capacity: 12,700+ agents @ 60 FPS pub mod core_loop; +#[cfg(feature = "decision-trace")] +pub mod decision_trace; pub mod ecs_ai_plugin; pub mod htn; pub mod orchestrator; pub mod tool_sandbox; +/// Record a decision. With `decision-trace` off, the tokens are discarded. +#[macro_export] +macro_rules! decision_record { + ($($tokens:tt)*) => { + #[cfg(feature = "decision-trace")] + { + $($tokens)* + } + }; +} + #[cfg(test)] mod mutation_tests; diff --git a/astraweave-ai/tests/decision_trace_alloc.rs b/astraweave-ai/tests/decision_trace_alloc.rs new file mode 100644 index 0000000000..42b04fcbd8 --- /dev/null +++ b/astraweave-ai/tests/decision_trace_alloc.rs @@ -0,0 +1,59 @@ +//! The traced spatial tick does not allocate after the rings exist. +//! +//! ```text +//! cargo test -p astraweave-ai --features decision-trace,alloc-counter --test decision_trace_alloc -- --test-threads=1 +//! ``` + +#![cfg(all(feature = "decision-trace", feature = "alloc-counter"))] + +use astraweave_ai::decision_trace::DecisionTrace; +use astraweave_ai::htn::{plan_route, AgentPlan, SpatialHooks}; +use astraweave_ecs::counting_alloc::{allocs, reset_allocs}; +use astraweave_nav::{bridge_and_ford, NavScratch}; + +#[global_allocator] +static ALLOC: astraweave_ecs::counting_alloc::CountingAlloc = + astraweave_ecs::counting_alloc::CountingAlloc; + +#[test] +fn traced_plan_route_allocates_nothing_after_warmup() { + let tiles = bridge_and_ford(); + let mut scratch = NavScratch::new(); + let hooks = SpatialHooks::none(); + let mut trace = DecisionTrace::new(); + assert!(trace.bind(1)); + for tick in 0..4u64 { + let mut budget = 64u32; + let mut plan = AgentPlan::empty(); + plan_route( + &tiles, + &mut scratch, + [1_000, 0, 1_000], + [1_000, 0, 46_000], + &hooks, + tick, + &mut plan, + &mut budget, + &mut trace, + 1, + ); + } + + reset_allocs(); + let mut budget = 64u32; + let mut plan = AgentPlan::empty(); + plan_route( + &tiles, + &mut scratch, + [1_000, 0, 1_000], + [1_000, 0, 46_000], + &hooks, + 4, + &mut plan, + &mut budget, + &mut trace, + 1, + ); + assert_eq!(allocs(), 0, "traced plan_route allocated"); + assert!(trace.count_of(1) > 4); +} diff --git a/astraweave-ai/tests/decision_trace_hash.rs b/astraweave-ai/tests/decision_trace_hash.rs new file mode 100644 index 0000000000..90126594eb --- /dev/null +++ b/astraweave-ai/tests/decision_trace_hash.rs @@ -0,0 +1,146 @@ +//! Plan bytes stay identical when the decision ring records them. +//! +//! ```text +//! cargo test -p astraweave-ai --features decision-trace --test decision_trace_hash +//! ``` + +#![cfg(feature = "decision-trace")] + +use astraweave_ai::decision_trace::{DecisionSink, DecisionTrace, NullSink, Patch, PlannerView}; +use astraweave_ai::htn::{plan_route, AgentPlan, SpatialHooks}; +use astraweave_nav::{bridge_and_ford, nav_change_from_kind, NavChangeKind, NavScratch}; +use sha2::{Digest, Sha256}; + +struct RingSink { + trace: DecisionTrace, +} + +impl DecisionSink for RingSink { + fn record(&mut self, record: &astraweave_ai::decision_trace::DecisionRecord) { + let _ = self.trace.push(record); + } +} + +fn script_bytes(sink: &mut S) -> Vec { + let mut tiles = bridge_and_ford(); + let mut scratch = NavScratch::new(); + let hooks = SpatialHooks::none(); + let mut out = Vec::new(); + for tick in 0..40u64 { + if tick == 30 { + tiles.mark(nav_change_from_kind( + NavChangeKind::Detach, + tick, + 0, + [-1_000, -1_000, 17_000], + [5_000, 1_000, 31_999], + )); + } + let committed = tiles.commit_tick() as u32; + let mut budget = 64u32; + let mut plan = AgentPlan::empty(); + plan_route( + &tiles, + &mut scratch, + [1_000, 0, 1_000], + [1_000, 0, 46_000], + &hooks, + tick, + &mut plan, + &mut budget, + sink, + 1, + ); + out.extend_from_slice(&tick.to_le_bytes()); + out.extend_from_slice(&committed.to_le_bytes()); + out.push(plan.len); + for slot in plan.slots.iter().take(plan.len as usize) { + match slot { + astraweave_ai::htn::ActionSlot::Empty => out.push(0), + astraweave_ai::htn::ActionSlot::MoveTo { x, y } => { + out.push(1); + out.extend_from_slice(&x.to_le_bytes()); + out.extend_from_slice(&y.to_le_bytes()); + } + astraweave_ai::htn::ActionSlot::UseBreach { portal_id } => { + out.push(2); + out.extend_from_slice(&portal_id.to_le_bytes()); + } + astraweave_ai::htn::ActionSlot::TakeCover { cover_id } => { + out.push(3); + out.extend_from_slice(&cover_id.to_le_bytes()); + } + astraweave_ai::htn::ActionSlot::Wait { duration_milli } => { + out.push(4); + out.extend_from_slice(&duration_milli.to_le_bytes()); + } + } + } + } + out +} + +fn sha256(bytes: &[u8]) -> [u8; 32] { + Sha256::digest(bytes).into() +} + +#[test] +fn decision_trace_hash_matches_when_the_ring_is_off() { + let mut null_sink = NullSink; + let silent = script_bytes(&mut null_sink); + + let mut ring = RingSink { + trace: DecisionTrace::new(), + }; + assert!(ring.trace.bind(1)); + let traced = script_bytes(&mut ring); + + assert_eq!(sha256(&silent), sha256(&traced)); + assert_eq!(silent, traced); + assert!(ring.trace.count_of(1) > 0); +} + +#[test] +fn decision_trace_rerun_leaves_the_script_hash() { + let mut ring = RingSink { + trace: DecisionTrace::new(), + }; + assert!(ring.trace.bind(1)); + let before = script_bytes(&mut ring); + let digest = sha256(&before); + + let mut tiles = bridge_and_ford(); + let mut scratch = NavScratch::new(); + let record = ring + .trace + .find_tick(1, 1) + .copied() + .expect("tick 1 was recorded"); + let mut sample = astraweave_ai::decision_trace::TickSample::from_record(record); + sample.pos_milli = [1_000, 0, 1_000]; + sample.goal_milli = [1_000, 0, 46_000]; + let hooks = SpatialHooks::none(); + let mut view = PlannerView { + tiles: &tiles, + scratch: &mut scratch, + hooks, + }; + let diff = astraweave_ai::decision_trace::rerun( + sample, + Patch::SealCell { + x: record.perceived.breach_x, + y: record.perceived.breach_y, + }, + &mut view, + ); + let _ = diff; + let _ = tiles.commit_tick(); + + let mut again = RingSink { + trace: DecisionTrace::new(), + }; + assert!(again.trace.bind(1)); + let after = script_bytes(&mut again); + assert_eq!(sha256(&before), digest); + assert_eq!(sha256(&after), digest); +} diff --git a/astraweave-ai/tests/zero_alloc_tick.rs b/astraweave-ai/tests/zero_alloc_tick.rs index 62faefcae5..f1e39f010d 100644 --- a/astraweave-ai/tests/zero_alloc_tick.rs +++ b/astraweave-ai/tests/zero_alloc_tick.rs @@ -24,7 +24,13 @@ fn htn_tick_and_tile_commit_allocate_nothing_after_warmup() { let mut scratch = NavScratch::new(); for step in 0..4u64 { let _ = tick.nav.commit_tick(); - tick_agents(&mut tick, &mut scratch, step); + tick_agents( + &mut tick, + &mut scratch, + step, + #[cfg(feature = "decision-trace")] + &mut astraweave_ai::decision_trace::NullSink, + ); } let collapse = GeometryNotice { tick: 8, @@ -39,7 +45,13 @@ fn htn_tick_and_tile_commit_allocate_nothing_after_warmup() { let warmup = nav_change_from_geometry_notice(&collapse, 0).expect("notice"); tick.nav.mark(warmup); let _ = tick.nav.commit_tick(); - tick_agents(&mut tick, &mut scratch, 8); + tick_agents( + &mut tick, + &mut scratch, + 8, + #[cfg(feature = "decision-trace")] + &mut astraweave_ai::decision_trace::NullSink, + ); reset_allocs(); let again = nav_change_from_geometry_notice(&collapse, 1).expect("notice"); @@ -48,7 +60,13 @@ fn htn_tick_and_tile_commit_allocate_nothing_after_warmup() { let commit_allocs = allocs(); reset_allocs(); - tick_agents(&mut tick, &mut scratch, 9); + tick_agents( + &mut tick, + &mut scratch, + 9, + #[cfg(feature = "decision-trace")] + &mut astraweave_ai::decision_trace::NullSink, + ); let tick_allocs = allocs(); assert!(committed >= 1, "warmup left a dirty tile to commit"); diff --git a/astraweave-ecs/src/lib.rs b/astraweave-ecs/src/lib.rs index bba3c5cc85..fb8482bbf9 100644 --- a/astraweave-ecs/src/lib.rs +++ b/astraweave-ecs/src/lib.rs @@ -487,6 +487,25 @@ impl World { self.resources.get_mut(&TypeId::of::())?.downcast_mut() } + /// Remove a resource and hand back its box. Putting the same box back + /// with [`restore_resource`] does not allocate. + pub fn take_resource(&mut self) -> Option> { + let boxed = self.resources.remove(&TypeId::of::())?; + match boxed.downcast::() { + Ok(value) => Some(value), + Err(boxed) => { + self.resources.insert(TypeId::of::(), boxed); + None + } + } + } + + /// Return a box previously taken with [`take_resource`]. + pub fn restore_resource(&mut self, value: Box) { + let erased: Box = value; + self.resources.insert(TypeId::of::(), erased); + } + /// Iterates all entities with component `T`, giving mutable access. /// /// # Examples @@ -959,6 +978,19 @@ mod tests { #[derive(Debug, PartialEq)] struct TestResource(i32); + #[test] + fn take_resource_round_trips_without_dropping_the_value() { + let mut world = World::new(); + world.insert_resource(TestResource(7)); + let taken = world.take_resource::(); + assert!(taken.is_some()); + let taken = taken.unwrap_or_else(|| Box::new(TestResource(0))); + assert!(world.get_resource::().is_none()); + assert_eq!(taken.0, 7); + world.restore_resource(taken); + assert_eq!(world.get_resource::().map(|r| r.0), Some(7)); + } + #[test] fn test_spawn_and_insert() { let mut world = World::new(); diff --git a/docs/architecture/ai_pipeline.md b/docs/architecture/ai_pipeline.md index 8410606b95..031bf5e10a 100644 --- a/docs/architecture/ai_pipeline.md +++ b/docs/architecture/ai_pipeline.md @@ -8,7 +8,7 @@ domain: ai lifecycle_status: active integration_status: wired owns: [astraweave-ai, astraweave-behavior, astraweave-context, astraweave-coordination, astraweave-dialogue, astraweave-director, astraweave-embeddings, astraweave-llm, astraweave-memory, astraweave-npc, astraweave-persona, astraweave-prompts, astraweave-rag] -doc_version: "1.13" +doc_version: "1.14" last_verified_commit: 32afac52f --- @@ -20,9 +20,9 @@ last_verified_commit: 32afac52f |---|---| | **System name** | AI Pipeline (Perception → Reasoning → Planning → Action) — foundational AI-first substrate | | **Primary crates** | `astraweave-ai` (39 files / 30.5K LoC), `astraweave-behavior` (6 / 5K), `astraweave-llm` (29 / 23.5K), `astraweave-memory` (17 / 11.5K), `astraweave-director` (6 / 3.3K), `astraweave-npc` (6 / 1.7K), `astraweave-dialogue` (4 / 5K), `astraweave-coordination` (5 / 5.3K) — **8 crates, 112 files, ~85K LoC total** | -| **Document version** | 1.13 | +| **Document version** | 1.14 | | **Last verified against commit** | `32afac52f` | -| **Last verified date** | 2026-05-12 | +| **Last verified date** | 2026-10-15 | | **Status** | **Active foundation — AI-first citizen of the engine.** The canonical loop is stable and validated for 12,700+ agents @ 60 FPS (per `astraweave-ai/src/lib.rs:27`). The Arbiter / dual-executor / LLM fallback chain has shipped multiple iterations and is hardening continuously. Subsystems like Memory, Director, NPC, Dialogue, Coordination are each large enough to warrant per-system follow-up traces. | | **Owner notes** | This trace is a **navigational map + load-bearing detail**, not an exhaustive per-file enumeration. Scale: 85K LoC across 8 crates. The canonical loop (`astraweave-ai/src/core_loop.rs` + `orchestrator.rs` + `tool_sandbox.rs` + `ai_arbiter.rs` + `llm_executor.rs` + `astraweave-behavior/src/goap.rs` + `astraweave-llm/src/{plan_parser,fallback_system,tool_guard,production_hardening}.rs`) is documented in detail. **Subsystem trace for Memory added 2026-05-12 (see §13.1)** — surfaced dormancy of the main memory pipeline w.r.t. the runtime AI loop. **Subsystem trace for Director added 2026-05-12 (see §13.2)** — confirmed Director is a parallel sibling AI subsystem (boss/encounter authoring) with its own validation gate `apply_director_plan`; the Companion-AI loop and Director loop share `WorldSnapshot` but otherwise do not interact. **Subsystem trace for NPC added 2026-05-12 (see §13.3)** — confirmed NPC is a fully isolated AI subsystem with its own parallel vocabulary (`NpcAction`/`NpcPlan`/`NpcWorldView`/`LlmAdapter`/`CommandSink`), zero imports of canonical AI types, and direct physics/audio integration rather than ECS-loop participation. **Subsystem trace for Dialogue added 2026-05-12 (see §13.4)** — confirmed Dialogue has a **two-layer architecture**: the basic `DialogueGraph`/`DialogueRunner`/`toml_loader` path is actively production-wired into `veilweaver_slice_runtime` and the editor; the LLM-enhanced `llm_dialogue.rs` (2941 LoC / 60% of crate) is dormant with zero external consumers. **Subsystem trace for Coordination added 2026-05-12 (see §13.5)** — most aggressively dormant subsystem traced: zero workspace consumers of any kind (no examples, no tools, no game-loop crates), explicit `#[allow(dead_code)]` "reserved for future…" markers on 7+ struct/field locations, three commented-out module declarations whose source files were never created. The entire `AgentCoordinator`/`WorldEventGenerator`/`NarrativeCoherenceEngine` surface is in-design. **Subsystem trace for Advanced GOAP added 2026-05-12 (see §13.6)** — largest subsystem traced (22 files / 16.7K LoC) and most architecturally mature among the dormant subsystems: feature-gated on `planner_advanced`, structured across 6 phases (0-5) of explicit phase-numbered development, integrates with the canonical loop via the `Orchestrator` trait, includes built-in shadow-mode infrastructure for safe rollout, but currently has zero production constructors outside tests/benches and three disabled CLI bins. **Subsystem trace for LLM Production Hardening added 2026-05-12 (see §13.7)** — second-deepest LoC dormancy reservoir at ~15K LoC across 16 files. Confirmed only one primitive (`parse_llm_response`) is actively wired in production (via `FallbackOrchestrator` Tier-1/Tier-2), but `FallbackOrchestrator::new` itself is doc-comment-only with zero non-test constructors. The runtime `AIArbiter`/`LlmExecutor` path bypasses the entire hardening surface — no rate limiting, no circuit breaking, no backpressure, no A/B routing, no retry, no telemetry, no ToolGuard, no 4-tier fallback. The 4096-char prompt limit and `safe_llm_invoke` stub are unreachable code. **Subsystem trace for RAG added 2026-05-12 (see §13.8)** — closes the original §11 follow-up list. Three-crate stack (`astraweave-rag` + `astraweave-embeddings` + `astraweave-context`, ~12.3K LoC total). Foundation primitives are active (`TokenCounter::new` is the most actively-wired primitive — instantiated by `RagPipeline::new` AND `ConversationHistory::new`), but the `RagPipeline` composite is dormant for the runtime AI loop: held as a field in 5 LLM-enhanced consumer crates (Director, Quests, Persona, Dialogue, Coordination), all of which are themselves dormant per §13.2/§13.4/§13.5. Surfaced two parallel-implementation anti-patterns (matching the CLAUDE.md "Architecture Drift" warning): (a) a SECOND orphaned `RagPipeline` struct in `astraweave-ai/src/rag/pipeline.rs:115` that never compiles because `pub mod rag` is not declared in lib.rs; (b) internal `astraweave-rag` crate duplication of `InjectionConfig` + `InjectionResult` types (different field sets, same names, two modules). Also surfaced "vocabulary-only" enum drift: `RetrievalMethod` 4 unused variants, `DiversityStrategy` 4 unused variants, `InjectionStrategy` 4 unused variants, plus `VectorStoreWrapper::get_all_memories` returns empty Vec making consolidation a no-op, plus HNSW indexing advertised but linear-scan implemented. **All originally enumerated per-subsystem follow-up traces are now complete.** **Verification pass 2026-05-12 (version 1.9):** resolved 22 markers across §1 / §3 / §5 / §6 / §8 / §10 / §11 / §13.2 / §13.3 / §13.4 / §13.5 / §13.6 / §13.7 / §13.8 with file:line evidence. Three factual corrections surfaced: (a) `GOAPOrchestrator` (Advanced GOAP) does NOT implement the `Orchestrator` trait despite earlier trace claim; (b) `plan_to_intent` emits `tracing::warn!` on unknown actions (not silent drop as previously hedged); (c) `BatchInferenceExecutor` IS actively wired via `FallbackOrchestrator` (not "[NEEDS VERIFICATION]"). One bug-class confirmation: `ProductionHardeningLayer` has no `Drop` impl, confirming runtime resource leak risk without explicit `shutdown().await`. **Deep investigation pass 2026-05-12 (version 1.10):** closed 2 factual §11 Open Questions (`*_stub` grep result, `AIArbiter` non-Send violation check) by moving resolutions into §8 Invariants 19 and 20. Enriched 4 decisional §11 questions with deeper factual context: `AIControlMode` vs `PlannerMode` (variant-set diff), Hermes2Pro/Qwen3/Phi3 (3-client coexistence + phi3:medium runtime default contradiction), `astraweave-ai` forbid_unsafe (grep verified absent crate-wide), `VectorStoreWrapper` consolidation no-op (verified no test catches the bug). Surfaced one new cognitive trap in §6: runtime LLM default is phi3:medium despite doc-comment Qwen3 claims. **Verification pass 2026-05-12 (version 1.11):** resolved 5 additional markers in §7 (Interner test isolation — no `serial_test` in astraweave-behavior), §13.2 (Director context/prompts deps enrichment), §13.3 (`PhysicsWorld::control_character` confirmed to use dt internally), §13.4 (D12 LlmDialogueSystem Send+Sync fields audited, TOML speaker field NOT retained, RunnerState Idle/Finished externally observable only via `is_finished()`). Verified git log searches for "Phase 7" + "WorldState" + "fallback" returned no relevant AI-pipeline commits — §7 Decision Log "[Reasoning not recovered]" markers remain unrecoverable per Default 3 (honest acknowledgment of missing rationale). | @@ -372,6 +372,7 @@ This section enumerates the load-bearing files. Per-file enumeration of all 112 | `astraweave-ai/src/lib.rs` | Module declarations + re-exports; performance summary at lines 22-27 | Active | 70 LoC | | `astraweave-ai/src/core_loop.rs` | `PlannerMode`, `CAiController`, `dispatch_planner`; the canonical loop dispatcher | Active | `PlannerMode::Htn` is always available (2026-10-15). With `ai-bt`, policy `default` ticks a behavior graph and other policies return `BehaviorDispatchError`. `ai-goap` / `ai-bt` enable the behavior crate | | `astraweave-ai/src/htn.rs` | HTN decomposition, utility-scored breaches and cover, LOD bands, `SpatialTick` | Active | Tick writes `[ActionSlot; 8]` and does not allocate. Caps at `HTN_EXPANSIONS_PER_TICK` (64). Weaving and hazard hooks are read and empty until those owners write them | +| `astraweave-ai/src/decision_trace.rs` | Decision ring, counterfactual `rerun`, static name table | Active (feature `decision-trace`, default off) | `DecisionTrace::new` allocates the rings once. `push` does not. With the feature off the module is absent and `decision_record!` compiles out. Belief stays empty until PR #213 publishes a `Copy` summary | | `astraweave-ai/src/orchestrator.rs` | `Orchestrator` trait, `OrchestratorAsync` trait, `RuleOrchestrator` | Active | The trait surface is the single contract every planner implements | | `astraweave-ai/src/tool_sandbox.rs` | `ToolVerb` enum (10 verbs), `ValidationCategory`, sandbox helpers | Active | Re-exported via `lib.rs:57` | | `astraweave-ai/src/ecs_ai_plugin.rs` | `AiPlanningPlugin`, `build_app_with_ai()`, `sys_ai_planning` system | Active | Plans every team-1 companion on the tick (legacy ids sorted, then ECS companions not already handled). A plan without `MoveTo`, or `try_build_snapshot`'s `SnapshotError`, records `AiPlanningFailedEvent` | @@ -659,6 +660,7 @@ This section enumerates the load-bearing files. Per-file enumeration of all 112 | 19 | `AIArbiter` is `!Send + !Sync` — must be used per-agent, never shared across threads | Yes (compile-time via auto-traits + doc-comment at `ai_arbiter.rs:194-195`) | **Closed from §11 via deep investigation 2026-05-12:** workspace grep for `Arc` or bare type name `AIArbiter` outside `astraweave-ai/src/ai_arbiter.rs`, tests, and benches returned zero matches. No external production consumers exist today, so the non-`Send` constraint is not currently violated anywhere. | | 20 | No production code stubs in AI surface (no `*_stub` naming convention) | Yes (workspace grep) | **Closed from §11 via deep investigation 2026-05-12:** workspace grep for `_stub` across `astraweave-ai/src`, `astraweave-llm/src`, `astraweave-behavior/src`, `astraweave-memory/src` returned exactly one match: `test_phi3_stub_without_feature` at `astraweave-llm/src/phi3.rs:494` — a test function name, NOT a production stub. (Note: `astraweave-llm/src/llm_adapter.rs` is itself described as a "stub" in its file-header comment per §13.7.7, but does not use the `_stub` naming convention.) | | 21 | The AI tick records an outcome for every team-1 companion. A* node order is a total order (`f32::total_cmp`), not `partial_cmp` collapsing NaN to `Equal` | Yes | `sys_ai_planning` loops legacy companions sorted by id, then ECS companions not already handled. `astraweave-behavior` `PlanNode::cmp` and `astraweave-ai` `goap/planner.rs` `PlanNode::cmp`. `ecs_integration_tests` `test_multi_agent_100_agents` and `test_multi_agent_determinism` | +| 22 | Decision tracing is absent from the default build. A traced run and an untraced run hash to the same plan bytes | Yes | Feature `decision-trace` is default off. `astraweave-ai/tests/decision_trace_hash.rs` compares SHA-256 of the plan encoding with `NullSink` and with the ring. The required replay cases do not include trace bytes | --- @@ -730,6 +732,7 @@ This section enumerates the load-bearing files. Per-file enumeration of all 112 ## 11. Open Questions / Parked Decisions +- **Decision-ring belief slot.** [Decisional, opened 2026-10-15.] The ring's `BeliefView` stays zero until PR #213 publishes a `Copy` summary from the depth tick. `StatKnowledge` is an optional mask the caller can pass. The tracer does not call `resolve_hit` and does not edit the depth tick. - **Two GOAP implementations — consolidation roadmap?** [Decisional, enriched by §13.6 investigation 2026-05-12.] Factual state: canonical `astraweave-behavior::goap` and advanced `astraweave-ai::goap` (22 files / 16,736 LoC, feature `planner_advanced`) coexist with no shared types. The Advanced GOAP layer adds: learning (EWMA + Bayesian smoothing), persistence, shadow mode (`ShadowModeRunner` + `PlanComparison` for side-by-side rollout), plan_analyzer (`PlanMetrics` + `Suggestion`), plan_stitcher (multi-plan merging with `Conflict` + `StitchError`), plan_visualizer (multiple `VisualizationFormat`s), goal_authoring (`GoalLibrary` + `GoalDefinition`), goal_scheduler, goal_validator (`Severity` + `ValidationError`), and a richer `StateValue` enum (Bool/Int/Float/String/IntRange/FloatApprox) vs canonical's `BTreeMap`. Verified 2026-05-12: Advanced GOAP has **zero production constructors** outside tests + benches + three disabled CLI bins (`astraweave-ai/src/bin.disabled/{analyze-plan,validate-goals,visualize-plan}.rs`). The integration adapter `GOAPOrchestrator` (`orchestrator.rs:11-…`) implements the canonical `Orchestrator` trait, so it's plug-compatible with `AIArbiter`, but no production code instantiates it. The Advanced GOAP is phase-numbered (Phase 0 discovery through Phase 5 tooling, per `mod.rs` and archive phase reports). Whether the advanced features eventually fold back into the canonical implementation, or whether they remain distinct (e.g. canonical for in-engine + advanced for editor authoring + offline analysis CLI), is the directional question. - **`AIControlMode` vs `PlannerMode` — unify or keep separate?** [Decisional, **enriched by deep investigation 2026-05-12**.] **Verified variant sets (2026-05-12) — they are NOT the same.** `PlannerMode` (`astraweave-ai/src/core_loop.rs:22-32`): `#[non_exhaustive]` 3-variant enum `Rule / BehaviorTree / GOAP`. Each variant carries no data. Has feature-flag helpers (`requires_bt_feature`, `requires_goap_feature`, `is_always_available`). Used as per-entity dispatch in `CAiController.mode` (see benches `ai_core_loop.rs:196,212,...`). `AIControlMode` (`astraweave-ai/src/ai_arbiter.rs:93-110`): `#[non_exhaustive]` 3-variant enum `GOAP / ExecutingLLM { step_index } / BehaviorTree`. Has data-carrying `ExecutingLLM` variant; has helper methods `is_goap()`, `is_executing_llm()`, `is_behavior_tree()`, `is_fallback()`, `step_index()`. Used only as the runtime state field of the arbiter. **Structural diff:** `PlannerMode` has `Rule` (no LLM); `AIControlMode` has `ExecutingLLM { step_index }` (data-carrying LLM step). They share only the `GOAP` and `BehaviorTree` *names*. A unification would need to subsume both `Rule` and `ExecutingLLM` semantics — likely a 4-variant enum or a richer hierarchy. Whether to unify (single enum with broader semantics) or to keep separate with clearer naming is undecided. - **`llm_adapter.rs` — stub vs production?** [Decisional / factual, **enriched by §13.7 investigation 2026-05-12**.] Factual state (verified 2026-05-12): the file header at `astraweave-llm/src/llm_adapter.rs:1` explicitly says "stub". `safe_llm_invoke` has **zero workspace callers** outside the file's own tests. `mock_llm_call` placeholder (`llm_adapter.rs:21-27`) just echoes the prompt back. The stub remains pure stub. The actual validation lives in `plan_parser.rs` (output-side, active via FallbackOrchestrator) + `tool_guard.rs` (output-side, dormant) + `validate_and_execute` (engine-side, active via tool sandbox). Three resolution options surfaced in §13.7.7: (a) promote — wire `safe_llm_invoke` ahead of every `LlmClient::complete`; (b) delete — rely on the existing three-layer defense; (c) keep as test fixture under a `mock_` rename. Suggested: option (b). Decision pending Andrew confirmation. diff --git a/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md b/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md index a93acc9470..c6214c5816 100644 --- a/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md +++ b/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md @@ -1,8 +1,17 @@ # Semantic AI decision debugger -Design for review. This document is the whole change. No runtime code, no editor panel, and no asset lands with it. +Approved 2026-10-15. Every question in §14 was accepted as proposed. The implementation is stacked on PR #251 at `ea8ec329`, which keeps all six required replay cases (`planner_pure`, `perception_world`, `gameplay_rng`, `fixed64`, `combat_resolve`, `nav_reroute`). `NavChangeKind` on that head matches PR #263. -Surveyed `main` at `f1109340` (2026-10-15), plus the open drafts that already own the pieces this tool has to read. Implementation waits on the review questions in §14. +The survey below was taken at `main` `f1109340` and on the #251 draft before that rebase. It stays as the map. The code that landed from this approval is `astraweave-ai/src/decision_trace.rs` (feature `decision-trace`, default off), the record sites in the hierarchical tick and the grid planners, and the headless `tools/aw_decision` binary. No editor panel. No new asset. + +## Approved answers + +1. Feature-off is the zero-cost mode. `decision_record!` compiles to nothing unless `decision-trace` is on. The default replay build leaves the feature off. +2. The determinism proof is the in-process null-sink versus ring-sink plan digest (`decision_trace_hash_matches_when_the_ring_is_off`). Trace bytes are not a required replay case. +3. `tools/aw_decision` is the inspector. The editor panel stays later, after issues #265 and #273 close. +4. The #251 rebase rule stands. This branch starts at `ea8ec329` and does not drop a required case. + +`rerun` takes `&mut PlannerView` so the caller-owned nav scratch can be borrowed mutably. `DecisionTrace::new` allocates the agent rings once; `push` does not. The `aravath-bridge` script uses `bridge_and_ford` and a detach at tick 30. It does not call `BridgeAgent`, which still lives on PR #263. ## 1. What a user can select diff --git a/examples/hello_companion/Cargo.toml b/examples/hello_companion/Cargo.toml index 943a29f1cc..46e9b7df88 100644 --- a/examples/hello_companion/Cargo.toml +++ b/examples/hello_companion/Cargo.toml @@ -50,6 +50,7 @@ llm = ["astraweave-llm", "astraweave-llm/llm_cache", "tokio"] ollama = ["llm", "astraweave-llm/ollama", "reqwest", "serde_json"] metrics = ["serde", "serde_json", "chrono"] llm_orchestrator = ["astraweave-ai/llm_orchestrator", "ollama"] +decision-trace = ["astraweave-ai/decision-trace"] # Visual demo with full rendering + LLM support visual = [ "astraweave-render", diff --git a/examples/hello_companion/src/main.rs b/examples/hello_companion/src/main.rs index 202644a413..d438f3ca7b 100644 --- a/examples/hello_companion/src/main.rs +++ b/examples/hello_companion/src/main.rs @@ -380,7 +380,9 @@ fn run_single_demo(mode: AIMode) -> Result { { let w = app.world.get_resource_mut::().unwrap(); println!("\n--- Executing Plan @ t={:.2} ---", w.t); - if let Err(e) = validate_and_execute(&mut *w, comp, &plan, &v_cfg, &mut log) { + let exec_result = validate_and_execute(&mut *w, comp, &plan, &v_cfg, &mut log); + note_decision(&snap, comp, &plan, mode, &exec_result); + if let Err(e) = exec_result { println!("⚠️ Execution failed: {}. Continuing...", e); } } @@ -452,7 +454,9 @@ fn run_single_demo(mode: AIMode) -> Result<()> { { let w = app.world.get_resource_mut::().unwrap(); println!("\n--- Executing Plan @ t={:.2} ---", w.t); - if let Err(e) = validate_and_execute(&mut *w, comp, &plan, &v_cfg, &mut log) { + let exec_result = validate_and_execute(&mut *w, comp, &plan, &v_cfg, &mut log); + note_decision(&snap, comp, &plan, mode, &exec_result); + if let Err(e) = exec_result { println!("⚠️ Execution failed: {}. Continuing...", e); } } @@ -611,6 +615,45 @@ fn select_ai_mode(args: &[String]) -> AIMode { // PLAN GENERATION ROUTER // ============================================================================ +fn planner_code(mode: AIMode) -> u8 { + match mode { + AIMode::Classical => 1, + #[cfg(feature = "llm")] + AIMode::BehaviorTree => 2, + #[cfg(feature = "llm")] + AIMode::Utility => 4, + #[cfg(feature = "ollama")] + AIMode::LLM | AIMode::Hybrid => 0, + #[cfg(feature = "llm")] + AIMode::Ensemble => 0, + #[cfg(feature = "llm_orchestrator")] + AIMode::Arbiter => 0, + } +} + +fn note_decision( + snap: &WorldSnapshot, + comp: astraweave_core::Entity, + plan: &PlanIntent, + mode: AIMode, + result: &Result<(), astraweave_core::EngineError>, +) { + let _ = planner_code(mode); + astraweave_ai::decision_record!({ + let mut trace = astraweave_ai::decision_trace::DecisionTrace::new(); + let entity = u64::from(comp); + let tick = astraweave_ai::decision_trace::tick_from_time(snap.t); + if trace.bind(entity) { + if planner_code(mode) == 4 { + astraweave_ai::decision_trace::record_utility(&mut trace, entity, tick, snap); + } else { + astraweave_ai::decision_trace::record_rule(&mut trace, entity, tick, snap, plan); + } + let _ = astraweave_ai::decision_trace::store_result(&mut trace, entity, tick, result); + } + }); +} + fn generate_plan(snap: &WorldSnapshot, mode: AIMode) -> Result { match mode { AIMode::Classical => generate_classical_plan(snap), diff --git a/tools/aw_decision/Cargo.toml b/tools/aw_decision/Cargo.toml new file mode 100644 index 0000000000..afc52a55e0 --- /dev/null +++ b/tools/aw_decision/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "aw_decision" +version = "0.1.0" +license.workspace = true +edition = "2021" +publish = false +description = "Headless inspector for one agent decision at one tick." + +[dependencies] +astraweave-ai = { path = "../../astraweave-ai", features = ["decision-trace"] } +astraweave-nav = { path = "../../astraweave-nav" } +clap = { version = "4.4", features = ["derive"] } + +[lib] +name = "aw_decision" +path = "src/lib.rs" diff --git a/tools/aw_decision/src/lib.rs b/tools/aw_decision/src/lib.rs new file mode 100644 index 0000000000..894565c9a9 --- /dev/null +++ b/tools/aw_decision/src/lib.rs @@ -0,0 +1,166 @@ +//! Headless inspector for the Aravath bridge companion. +//! +//! The script uses the same span as the nav reroute case. It does not call +//! the greybox `BridgeAgent` type, which lives on another branch. + +use std::fs; +use std::path::Path; + +use astraweave_ai::decision_trace::{ + format_record, rerun, DecisionTrace, Patch, PlannerView, TickSample, +}; +use astraweave_ai::htn::{plan_route, AgentPlan, SpatialHooks}; +use astraweave_nav::{bridge_and_ford, nav_change_from_kind, NavChangeKind, NavScratch, NavTiles}; + +/// Player-facing scene name. +pub const SCENE_LABEL: &str = "Aravath"; + +const ENTITY: u64 = 1; +const POS: [i32; 3] = [1_000, 0, 1_000]; +const GOAL: [i32; 3] = [1_000, 0, 46_000]; + +pub fn show(tick: u64, entity: u64) -> Result { + let (trace, _tiles) = simulate_through(tick.max(31)); + let record = trace.find_tick(entity, tick).ok_or_else(|| { + format!( + "no record for entity {entity} at tick {tick} (held {})", + trace.count_of(entity) + ) + })?; + Ok(format!("{SCENE_LABEL}\n{}", format_record(record))) +} + +pub fn diff_seal(tick: u64, entity: u64, x: i32, y: i32) -> Result { + let (trace, tiles) = simulate_through(tick); + let record = trace + .find_tick(entity, tick) + .ok_or_else(|| format!("no record for entity {entity} at tick {tick}"))?; + let mut sample = TickSample::from_record(*record); + sample.pos_milli = POS; + sample.goal_milli = GOAL; + let mut scratch = NavScratch::new(); + let hooks = SpatialHooks::none(); + let mut view = PlannerView { + tiles: &tiles, + scratch: &mut scratch, + hooks, + }; + let diff = rerun(sample, Patch::SealCell { x, y }, &mut view); + let mut text = format!( + "{SCENE_LABEL}\ntick {tick}\nentity {entity}\nbefore {before} score {before_score}\nafter {after} score {after_score}\n", + before = astraweave_ai::decision_trace::action_name(diff.before), + before_score = diff.before_score, + after = astraweave_ai::decision_trace::action_name(diff.after), + after_score = diff.after_score, + ); + for alt in diff.alts.iter().take(diff.alt_len as usize) { + text.push_str(&format!( + "rejected {} {} {} score {} {}\n", + astraweave_ai::decision_trace::action_name(alt.action), + alt.a, + alt.b, + alt.score, + astraweave_ai::decision_trace::reject_name(alt.reject), + )); + } + Ok(text) +} + +pub fn dump_record(path: &Path, tick: u64, entity: u64) -> Result<(), String> { + let (trace, _tiles) = simulate_through(tick); + let record = trace + .find_tick(entity, tick) + .ok_or_else(|| format!("no record for entity {entity} at tick {tick}"))?; + let bytes = record_bytes(record); + fs::write(path, bytes).map_err(|err| format!("writing {}: {err}", path.display())) +} + +fn record_bytes(record: &astraweave_ai::decision_trace::DecisionRecord) -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(b"AWDT"); + out.extend_from_slice(&1u32.to_le_bytes()); + out.extend_from_slice(&record.tick.to_le_bytes()); + out.extend_from_slice(&record.entity_id.to_le_bytes()); + out.push(record.planner); + out.push(record.band); + out.extend_from_slice(&record.goal.to_le_bytes()); + out.extend_from_slice(&record.selected.to_le_bytes()); + out.extend_from_slice(&record.selected_score.to_le_bytes()); + out.extend_from_slice(&record.param0.to_le_bytes()); + out.extend_from_slice(&record.param1.to_le_bytes()); + out.push(record.outcome); + out.extend_from_slice(&record.fail.to_le_bytes()); + out.push(record.alt_len); + for alt in &record.alts { + out.extend_from_slice(&alt.action.to_le_bytes()); + out.extend_from_slice(&alt.reject.to_le_bytes()); + out.extend_from_slice(&alt.score.to_le_bytes()); + out.extend_from_slice(&alt.a.to_le_bytes()); + out.extend_from_slice(&alt.b.to_le_bytes()); + } + out +} + +fn simulate_through(last_tick: u64) -> (DecisionTrace, NavTiles) { + let mut tiles = bridge_and_ford(); + let mut scratch = NavScratch::new(); + let hooks = SpatialHooks::none(); + let mut trace = DecisionTrace::new(); + let _ = trace.bind(ENTITY); + for tick in 0..=last_tick { + if tick == 30 { + tiles.mark(nav_change_from_kind( + NavChangeKind::Detach, + tick, + 0, + [-1_000, -1_000, 17_000], + [5_000, 1_000, 31_999], + )); + } + let _ = tiles.commit_tick(); + let mut budget = 64u32; + let mut plan = AgentPlan::empty(); + plan_route( + &tiles, + &mut scratch, + POS, + GOAL, + &hooks, + tick, + &mut plan, + &mut budget, + &mut trace, + ENTITY, + ); + } + (trace, tiles) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn show_prints_the_bridge_decision() { + let text = show(31, 1).expect("record"); + assert!(text.starts_with("Aravath\n"), "{text}"); + assert!(text.contains("planner htn"), "{text}"); + assert!(text.contains("selected "), "{text}"); + assert!(text.contains("outcome "), "{text}"); + assert!(text.contains("rejected "), "{text}"); + } + + #[test] + fn diff_seal_prints_both_actions() { + let shown = show(1, 1).expect("tick 1"); + let breach_line = shown + .lines() + .find(|line| line.starts_with("perceived ")) + .expect("perceived"); + let _ = breach_line; + let text = diff_seal(1, 1, 0, 0).expect("diff"); + assert!(text.starts_with("Aravath\n"), "{text}"); + assert!(text.contains("before "), "{text}"); + assert!(text.contains("after "), "{text}"); + } +} diff --git a/tools/aw_decision/src/main.rs b/tools/aw_decision/src/main.rs new file mode 100644 index 0000000000..b9c2197c0e --- /dev/null +++ b/tools/aw_decision/src/main.rs @@ -0,0 +1,123 @@ +//! Headless decision inspector. +//! +//! ```text +//! aw_decision show --script aravath-bridge --tick 31 --entity 1 +//! aw_decision diff --script aravath-bridge --tick 31 --entity 1 --seal 1,17 +//! ``` + +use std::path::PathBuf; +use std::process::ExitCode; + +use aw_decision::{diff_seal, dump_record, show, SCENE_LABEL}; +use clap::{Parser, Subcommand}; + +#[derive(Parser)] +#[command(name = "aw_decision")] +struct Cli { + #[command(subcommand)] + cmd: Cmd, +} + +#[derive(Subcommand)] +enum Cmd { + /// Print one recorded decision. + Show { + #[arg(long, default_value = "aravath-bridge")] + script: String, + #[arg(long)] + tick: u64, + #[arg(long)] + entity: u64, + #[arg(long)] + dump: Option, + }, + /// Rerun one tick with a single sealed cell. + Diff { + #[arg(long, default_value = "aravath-bridge")] + script: String, + #[arg(long)] + tick: u64, + #[arg(long)] + entity: u64, + /// Cell to seal, written as `x,y`. + #[arg(long)] + seal: String, + }, +} + +fn main() -> ExitCode { + let cli = Cli::parse(); + let result = match cli.cmd { + Cmd::Show { + script, + tick, + entity, + dump, + } => show_cmd(&script, tick, entity, dump.as_deref()), + Cmd::Diff { + script, + tick, + entity, + seal, + } => diff_cmd(&script, tick, entity, &seal), + }; + match result { + Ok(text) => { + print!("{text}"); + if !text.ends_with('\n') { + println!(); + } + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("{err}"); + ExitCode::from(1) + } + } +} + +fn show_cmd( + script: &str, + tick: u64, + entity: u64, + dump: Option<&std::path::Path>, +) -> Result { + require_script(script)?; + if let Some(path) = dump { + dump_record(path, tick, entity)?; + } + let mut text = show(tick, entity)?; + if !text.contains(SCENE_LABEL) { + text = format!("{SCENE_LABEL}\n{text}"); + } + Ok(text) +} + +fn diff_cmd(script: &str, tick: u64, entity: u64, seal: &str) -> Result { + require_script(script)?; + let (x, y) = parse_cell(seal)?; + diff_seal(tick, entity, x, y) +} + +fn require_script(script: &str) -> Result<(), String> { + if script == "aravath-bridge" { + Ok(()) + } else { + Err(format!("unknown script {script}")) + } +} + +fn parse_cell(text: &str) -> Result<(i32, i32), String> { + let (x, y) = text + .split_once(',') + .ok_or_else(|| format!("seal must be x,y, got {text}"))?; + let x = x + .trim() + .parse::() + .map_err(|_| format!("seal x is not an integer: {x}"))?; + let y = y + .trim() + .parse::() + .map_err(|_| format!("seal y is not an integer: {y}"))?; + Ok((x, y)) +} From 6ef72e75d50e82c28087f37dd19f3b300d6eabd5 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 15 Oct 2026 16:16:39 +0000 Subject: [PATCH 2/3] fix(ai): keep plan_route's signature stable when tracing is on The replay harness calls plan_route with eight arguments. A feature-only extra parameter made that test fail to compile when decision-trace was unified on, so the sink now lives in thread-local storage. perception_world stays 6e52e721 with the feature off and on. Co-authored-by: Andrew Brown --- astraweave-ai/benches/htn_budget.rs | 4 - astraweave-ai/src/decision_trace.rs | 76 ++-------- astraweave-ai/src/ecs_ai_plugin.rs | 14 +- astraweave-ai/src/htn.rs | 136 +++++++++++++----- astraweave-ai/tests/decision_trace_alloc.rs | 6 +- astraweave-ai/tests/decision_trace_hash.rs | 52 ++----- astraweave-ai/tests/zero_alloc_tick.rs | 24 +--- docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md | 4 +- tools/aw_decision/src/lib.rs | 3 +- 9 files changed, 141 insertions(+), 178 deletions(-) diff --git a/astraweave-ai/benches/htn_budget.rs b/astraweave-ai/benches/htn_budget.rs index f22a72d7fd..75ecfa7839 100644 --- a/astraweave-ai/benches/htn_budget.rs +++ b/astraweave-ai/benches/htn_budget.rs @@ -24,10 +24,6 @@ fn bench_htn_expansions(c: &mut Criterion) { 1, &mut plan, &mut budget, - #[cfg(feature = "decision-trace")] - &mut astraweave_ai::decision_trace::NullSink, - #[cfg(feature = "decision-trace")] - 1u64, ); if budget == before { break; diff --git a/astraweave-ai/src/decision_trace.rs b/astraweave-ai/src/decision_trace.rs index f8b9c933bd..9f007c7cad 100644 --- a/astraweave-ai/src/decision_trace.rs +++ b/astraweave-ai/src/decision_trace.rs @@ -455,63 +455,6 @@ fn outcome_byte(code: FailCode) -> u8 { } } -pub trait DecisionSink { - fn record(&mut self, record: &DecisionRecord); - fn amend_band(&mut self, entity_id: u64, tick: u64, band: u8) { - let _ = (entity_id, tick, band); - } -} - -/// Sink that drops the record. The planner result does not read it. -pub struct NullSink; - -impl DecisionSink for NullSink { - #[inline(always)] - fn record(&mut self, _record: &DecisionRecord) {} -} - -impl DecisionSink for DecisionTrace { - fn record(&mut self, record: &DecisionRecord) { - let _ = self.push(record); - } - - fn amend_band(&mut self, entity_id: u64, tick: u64, band: u8) { - DecisionTrace::amend_band(self, entity_id, tick, band); - } -} - -/// One-record sink used by [`rerun`] so the live ring stays put. -pub struct CaptureSink { - pub record: DecisionRecord, - pub wrote: bool, -} - -impl DecisionSink for CaptureSink { - fn record(&mut self, record: &DecisionRecord) { - self.record = *record; - self.wrote = true; - } -} - -impl Default for CaptureSink { - fn default() -> Self { - Self { - record: DecisionRecord::EMPTY, - wrote: false, - } - } -} - -impl CaptureSink { - #[must_use] - pub const fn new() -> Self { - Self { - record: DecisionRecord::EMPTY, - wrote: false, - } - } -} - #[must_use] pub fn tick_from_time(t: f32) -> u64 { if t.is_finite() && t >= 0.0 { @@ -570,7 +513,7 @@ pub fn record_rule( plan: &astraweave_core::PlanIntent, ) { let _ = trace.bind(entity_id); - trace.record(&grid_record( + let _ = trace.push(&grid_record( entity_id, tick, PlannerId::Rule as u8, @@ -583,7 +526,7 @@ pub fn record_rule( pub fn record_utility(trace: &mut DecisionTrace, entity_id: u64, tick: u64, snap: &WorldSnapshot) { let _ = trace.bind(entity_id); - trace.record(&utility_decision(entity_id, tick, snap)); + let _ = trace.push(&utility_decision(entity_id, tick, snap)); } fn grid_record( @@ -821,7 +764,9 @@ fn rerun_htn( }; let mut plan = AgentPlan::empty(); let mut budget = htn::HTN_EXPANSIONS_PER_TICK as u32; - let mut capture = CaptureSink::default(); + let mut capture = DecisionTrace::new(); + let _ = capture.bind(sample.record.entity_id); + let _guard = htn::attach_trace(&mut capture, sample.record.entity_id); plan_route( view.tiles, view.scratch, @@ -831,14 +776,11 @@ fn rerun_htn( sample.record.tick, &mut plan, &mut budget, - &mut capture, - sample.record.entity_id, ); - if capture.wrote { - capture.record - } else { - DecisionRecord::EMPTY - } + capture + .find_tick(sample.record.entity_id, sample.record.tick) + .copied() + .unwrap_or(DecisionRecord::EMPTY) } fn snapshot_from_perceived(tick: u64, perceived: &PerceivedView, goal: u16) -> WorldSnapshot { diff --git a/astraweave-ai/src/ecs_ai_plugin.rs b/astraweave-ai/src/ecs_ai_plugin.rs index 155c342b7d..8293e8aa8d 100644 --- a/astraweave-ai/src/ecs_ai_plugin.rs +++ b/astraweave-ai/src/ecs_ai_plugin.rs @@ -316,16 +316,12 @@ fn sys_spatial_tick(world: &mut ecs::World) { let mut scratch = astraweave_nav::NavScratch::new(); let sim_tick = tick.clock; tick.clock = tick.clock.saturating_add(1); - #[cfg(not(feature = "decision-trace"))] - crate::htn::tick_agents(tick, &mut scratch, sim_tick); - #[cfg(feature = "decision-trace")] { - if let Some(ref mut trace) = held { - crate::htn::tick_agents(tick, &mut scratch, sim_tick, trace.as_mut()); - } else { - let mut null = crate::decision_trace::NullSink; - crate::htn::tick_agents(tick, &mut scratch, sim_tick, &mut null); - } + #[cfg(feature = "decision-trace")] + let _guard = held + .as_mut() + .map(|trace| crate::htn::attach_trace(trace.as_mut(), 0)); + crate::htn::tick_agents(tick, &mut scratch, sim_tick); } #[cfg(feature = "decision-trace")] if let Some(held) = held { diff --git a/astraweave-ai/src/htn.rs b/astraweave-ai/src/htn.rs index d0efe9dff6..8752f55b95 100644 --- a/astraweave-ai/src/htn.rs +++ b/astraweave-ai/src/htn.rs @@ -211,14 +211,103 @@ pub fn fill_observation(tiles: &NavTiles, buf: &mut ObservationBuf) { } } +#[cfg(feature = "decision-trace")] +std::thread_local! { + static TRACE_ACTIVE: std::cell::Cell = const { std::cell::Cell::new(false) }; + static TRACE_ENTITY: std::cell::Cell = const { std::cell::Cell::new(0) }; + static TRACE_HOLDER: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +/// Swaps `trace` into thread-local storage until the guard drops. +/// +/// `plan_route` keeps the same eight arguments with the feature on or off, +/// so the replay harness compiles either way and writes the same plan bytes. +/// With the feature off this function does not exist, and `plan_route` does +/// not touch the thread local. +#[cfg(feature = "decision-trace")] +pub struct TraceGuard { + trace: *mut crate::decision_trace::DecisionTrace, + prev_active: bool, + prev_entity: u64, +} + +#[cfg(feature = "decision-trace")] +#[must_use] +pub fn attach_trace( + trace: &mut crate::decision_trace::DecisionTrace, + entity_id: u64, +) -> TraceGuard { + let prev_active = TRACE_ACTIVE.with(|cell| cell.replace(true)); + let prev_entity = TRACE_ENTITY.with(|cell| cell.replace(entity_id)); + let trace_ptr = trace as *mut crate::decision_trace::DecisionTrace; + swap_holder(trace); + TraceGuard { + trace: trace_ptr, + prev_active, + prev_entity, + } +} + +#[cfg(feature = "decision-trace")] +fn swap_holder(trace: &mut crate::decision_trace::DecisionTrace) { + TRACE_HOLDER.with(|cell| { + let mut slot = cell.borrow_mut(); + if slot.is_none() { + *slot = Some(crate::decision_trace::DecisionTrace::new()); + } + if let Some(held) = slot.as_mut() { + std::mem::swap(trace, held); + } + }); +} + +#[cfg(feature = "decision-trace")] +impl Drop for TraceGuard { + fn drop(&mut self) { + if !self.trace.is_null() { + // SAFETY: `attach_trace` created this pointer from the caller's + // `&mut DecisionTrace`, and this guard is dropped before that + // borrow ends. The swap returns the caller's rings. + unsafe { swap_holder(&mut *self.trace) } + } + TRACE_ACTIVE.with(|cell| cell.set(self.prev_active)); + TRACE_ENTITY.with(|cell| cell.set(self.prev_entity)); + } +} + +#[cfg(feature = "decision-trace")] +fn set_trace_entity(entity_id: u64) { + TRACE_ENTITY.with(|cell| cell.set(entity_id)); +} + +#[cfg(feature = "decision-trace")] +fn emit_record(record: &crate::decision_trace::DecisionRecord) { + if !TRACE_ACTIVE.with(|cell| cell.get()) { + return; + } + TRACE_HOLDER.with(|cell| { + if let Some(trace) = cell.borrow_mut().as_mut() { + let _ = trace.push(record); + } + }); +} + +#[cfg(feature = "decision-trace")] +fn emit_band(entity_id: u64, tick: u64, band: u8) { + if !TRACE_ACTIVE.with(|cell| cell.get()) { + return; + } + TRACE_HOLDER.with(|cell| { + if let Some(trace) = cell.borrow_mut().as_mut() { + trace.amend_band(entity_id, tick, band); + } + }); +} + /// Advance every agent. Sort key is `(band, entity_id)`. #[allow(clippy::needless_range_loop)] -pub fn tick_agents( - tick: &mut SpatialTick, - scratch: &mut NavScratch, - sim_tick: u64, - #[cfg(feature = "decision-trace")] sink: &mut dyn crate::decision_trace::DecisionSink, -) { +pub fn tick_agents(tick: &mut SpatialTick, scratch: &mut NavScratch, sim_tick: u64) { let wlen = tick.weaving_len as usize; let hlen = tick.hazard_len as usize; let mut weave_buf = [WeaveEffectHook { @@ -281,6 +370,8 @@ pub fn tick_agents( agent.ticks_since_plan = agent.ticks_since_plan.saturating_add(1); match band { 0 if agent.ticks_since_plan >= REPLAN_TICKS || agent.plan.len == 0 => { + #[cfg(feature = "decision-trace")] + set_trace_entity(agent.entity_id); plan_route( nav, scratch, @@ -290,17 +381,15 @@ pub fn tick_agents( sim_tick, &mut agent.plan, &mut budget, - #[cfg(feature = "decision-trace")] - sink, - #[cfg(feature = "decision-trace")] - agent.entity_id, ); agent.plan.band = 0; agent.ticks_since_plan = 0; #[cfg(feature = "decision-trace")] - sink.amend_band(agent.entity_id, sim_tick, 0); + emit_band(agent.entity_id, sim_tick, 0); } 1 => { + #[cfg(feature = "decision-trace")] + set_trace_entity(agent.entity_id); plan_route( nav, scratch, @@ -310,15 +399,11 @@ pub fn tick_agents( sim_tick, &mut agent.plan, &mut budget, - #[cfg(feature = "decision-trace")] - sink, - #[cfg(feature = "decision-trace")] - agent.entity_id, ); agent.plan.band = 1; agent.ticks_since_plan = 0; #[cfg(feature = "decision-trace")] - sink.amend_band(agent.entity_id, sim_tick, 1); + emit_band(agent.entity_id, sim_tick, 1); } 2 if agent.plan.len == 0 => { agent.plan.slots[0] = ActionSlot::MoveTo { @@ -341,7 +426,7 @@ pub fn tick_agents( &crate::decision_trace::AltList::new(), 0, ); - sink.record(&record); + emit_record(&record); } } _ => { @@ -363,8 +448,6 @@ pub fn plan_route( sim_tick: u64, out: &mut AgentPlan, budget: &mut u32, - #[cfg(feature = "decision-trace")] sink: &mut dyn crate::decision_trace::DecisionSink, - #[cfg(feature = "decision-trace")] entity_id: u64, ) { #[cfg(feature = "decision-trace")] clear_alts(); @@ -427,10 +510,11 @@ pub fn plan_route( let perceived = perceived_for_route(tiles, pos_milli); let alts = copy_alts(); let score = route_score(tiles, out); + let entity_id = TRACE_ENTITY.with(|cell| cell.get()); let record = crate::decision_trace::route_record( entity_id, sim_tick, 0, pos_milli, out, perceived, &alts, score, ); - sink.record(&record); + emit_record(&record); } } @@ -824,10 +908,6 @@ mod tests { 1, &mut plan, &mut budget, - #[cfg(feature = "decision-trace")] - &mut crate::decision_trace::NullSink, - #[cfg(feature = "decision-trace")] - 1u64, ); if budget == before { break; @@ -857,10 +937,6 @@ mod tests { 1, &mut plan, &mut budget, - #[cfg(feature = "decision-trace")] - &mut crate::decision_trace::NullSink, - #[cfg(feature = "decision-trace")] - 1u64, ); let before = move_cell(&plan); tiles.mark(astraweave_nav::nav_change_from_kind( @@ -880,10 +956,6 @@ mod tests { 31, &mut plan, &mut budget, - #[cfg(feature = "decision-trace")] - &mut crate::decision_trace::NullSink, - #[cfg(feature = "decision-trace")] - 1u64, ); let after = move_cell(&plan); assert!(before < 8, "bridge path cell {before}"); diff --git a/astraweave-ai/tests/decision_trace_alloc.rs b/astraweave-ai/tests/decision_trace_alloc.rs index 42b04fcbd8..90d7a21d9c 100644 --- a/astraweave-ai/tests/decision_trace_alloc.rs +++ b/astraweave-ai/tests/decision_trace_alloc.rs @@ -25,6 +25,7 @@ fn traced_plan_route_allocates_nothing_after_warmup() { for tick in 0..4u64 { let mut budget = 64u32; let mut plan = AgentPlan::empty(); + let _guard = astraweave_ai::htn::attach_trace(&mut trace, 1); plan_route( &tiles, &mut scratch, @@ -34,14 +35,13 @@ fn traced_plan_route_allocates_nothing_after_warmup() { tick, &mut plan, &mut budget, - &mut trace, - 1, ); } reset_allocs(); let mut budget = 64u32; let mut plan = AgentPlan::empty(); + let _guard = astraweave_ai::htn::attach_trace(&mut trace, 1); plan_route( &tiles, &mut scratch, @@ -51,8 +51,6 @@ fn traced_plan_route_allocates_nothing_after_warmup() { 4, &mut plan, &mut budget, - &mut trace, - 1, ); assert_eq!(allocs(), 0, "traced plan_route allocated"); assert!(trace.count_of(1) > 4); diff --git a/astraweave-ai/tests/decision_trace_hash.rs b/astraweave-ai/tests/decision_trace_hash.rs index 90126594eb..e88db5a964 100644 --- a/astraweave-ai/tests/decision_trace_hash.rs +++ b/astraweave-ai/tests/decision_trace_hash.rs @@ -6,22 +6,13 @@ #![cfg(feature = "decision-trace")] -use astraweave_ai::decision_trace::{DecisionSink, DecisionTrace, NullSink, Patch, PlannerView}; +use astraweave_ai::decision_trace::{DecisionTrace, Patch, PlannerView}; use astraweave_ai::htn::{plan_route, AgentPlan, SpatialHooks}; use astraweave_nav::{bridge_and_ford, nav_change_from_kind, NavChangeKind, NavScratch}; use sha2::{Digest, Sha256}; -struct RingSink { - trace: DecisionTrace, -} - -impl DecisionSink for RingSink { - fn record(&mut self, record: &astraweave_ai::decision_trace::DecisionRecord) { - let _ = self.trace.push(record); - } -} - -fn script_bytes(sink: &mut S) -> Vec { +fn script_bytes(trace: Option<&mut DecisionTrace>) -> Vec { + let _guard = trace.map(|trace| astraweave_ai::htn::attach_trace(trace, 1)); let mut tiles = bridge_and_ford(); let mut scratch = NavScratch::new(); let hooks = SpatialHooks::none(); @@ -48,8 +39,6 @@ fn script_bytes(sink: &mut S) -> Vec { tick, &mut plan, &mut budget, - sink, - 1, ); out.extend_from_slice(&tick.to_le_bytes()); out.extend_from_slice(&committed.to_le_bytes()); @@ -86,36 +75,27 @@ fn sha256(bytes: &[u8]) -> [u8; 32] { #[test] fn decision_trace_hash_matches_when_the_ring_is_off() { - let mut null_sink = NullSink; - let silent = script_bytes(&mut null_sink); + let silent = script_bytes(None); - let mut ring = RingSink { - trace: DecisionTrace::new(), - }; - assert!(ring.trace.bind(1)); - let traced = script_bytes(&mut ring); + let mut ring = DecisionTrace::new(); + assert!(ring.bind(1)); + let traced = script_bytes(Some(&mut ring)); assert_eq!(sha256(&silent), sha256(&traced)); assert_eq!(silent, traced); - assert!(ring.trace.count_of(1) > 0); + assert!(ring.count_of(1) > 0); } #[test] fn decision_trace_rerun_leaves_the_script_hash() { - let mut ring = RingSink { - trace: DecisionTrace::new(), - }; - assert!(ring.trace.bind(1)); - let before = script_bytes(&mut ring); + let mut ring = DecisionTrace::new(); + assert!(ring.bind(1)); + let before = script_bytes(Some(&mut ring)); let digest = sha256(&before); let mut tiles = bridge_and_ford(); let mut scratch = NavScratch::new(); - let record = ring - .trace - .find_tick(1, 1) - .copied() - .expect("tick 1 was recorded"); + let record = ring.find_tick(1, 1).copied().expect("tick 1 was recorded"); let mut sample = astraweave_ai::decision_trace::TickSample::from_record(record); sample.pos_milli = [1_000, 0, 1_000]; sample.goal_milli = [1_000, 0, 46_000]; @@ -136,11 +116,9 @@ fn decision_trace_rerun_leaves_the_script_hash() { let _ = diff; let _ = tiles.commit_tick(); - let mut again = RingSink { - trace: DecisionTrace::new(), - }; - assert!(again.trace.bind(1)); - let after = script_bytes(&mut again); + let mut again = DecisionTrace::new(); + assert!(again.bind(1)); + let after = script_bytes(Some(&mut again)); assert_eq!(sha256(&before), digest); assert_eq!(sha256(&after), digest); } diff --git a/astraweave-ai/tests/zero_alloc_tick.rs b/astraweave-ai/tests/zero_alloc_tick.rs index f1e39f010d..62faefcae5 100644 --- a/astraweave-ai/tests/zero_alloc_tick.rs +++ b/astraweave-ai/tests/zero_alloc_tick.rs @@ -24,13 +24,7 @@ fn htn_tick_and_tile_commit_allocate_nothing_after_warmup() { let mut scratch = NavScratch::new(); for step in 0..4u64 { let _ = tick.nav.commit_tick(); - tick_agents( - &mut tick, - &mut scratch, - step, - #[cfg(feature = "decision-trace")] - &mut astraweave_ai::decision_trace::NullSink, - ); + tick_agents(&mut tick, &mut scratch, step); } let collapse = GeometryNotice { tick: 8, @@ -45,13 +39,7 @@ fn htn_tick_and_tile_commit_allocate_nothing_after_warmup() { let warmup = nav_change_from_geometry_notice(&collapse, 0).expect("notice"); tick.nav.mark(warmup); let _ = tick.nav.commit_tick(); - tick_agents( - &mut tick, - &mut scratch, - 8, - #[cfg(feature = "decision-trace")] - &mut astraweave_ai::decision_trace::NullSink, - ); + tick_agents(&mut tick, &mut scratch, 8); reset_allocs(); let again = nav_change_from_geometry_notice(&collapse, 1).expect("notice"); @@ -60,13 +48,7 @@ fn htn_tick_and_tile_commit_allocate_nothing_after_warmup() { let commit_allocs = allocs(); reset_allocs(); - tick_agents( - &mut tick, - &mut scratch, - 9, - #[cfg(feature = "decision-trace")] - &mut astraweave_ai::decision_trace::NullSink, - ); + tick_agents(&mut tick, &mut scratch, 9); let tick_allocs = allocs(); assert!(committed >= 1, "warmup left a dirty tile to commit"); diff --git a/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md b/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md index c6214c5816..bb553966b8 100644 --- a/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md +++ b/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md @@ -1,6 +1,6 @@ # Semantic AI decision debugger -Approved 2026-10-15. Every question in §14 was accepted as proposed. The implementation is stacked on PR #251 at `ea8ec329`, which keeps all six required replay cases (`planner_pure`, `perception_world`, `gameplay_rng`, `fixed64`, `combat_resolve`, `nav_reroute`). `NavChangeKind` on that head matches PR #263. +Approved 2026-10-15. Every question in §14 was accepted as proposed. The implementation is stacked on PR #251 at `fe349aa0`, which keeps all six required replay cases (`planner_pure`, `perception_world`, `gameplay_rng`, `fixed64`, `combat_resolve`, `nav_reroute`). `NavChangeKind` on that head matches PR #263. `perception_world` on that head is `6e52e721ceb8a96413a7ae0ba1ad3f88adaeb37c56ba520c3a3cb9f6f0bf7ebb` because `4172ed01` stopped `build_snapshot` from inserting a breach POI. Tracing does not change that digest. The survey below was taken at `main` `f1109340` and on the #251 draft before that rebase. It stays as the map. The code that landed from this approval is `astraweave-ai/src/decision_trace.rs` (feature `decision-trace`, default off), the record sites in the hierarchical tick and the grid planners, and the headless `tools/aw_decision` binary. No editor panel. No new asset. @@ -9,7 +9,7 @@ The survey below was taken at `main` `f1109340` and on the #251 draft before tha 1. Feature-off is the zero-cost mode. `decision_record!` compiles to nothing unless `decision-trace` is on. The default replay build leaves the feature off. 2. The determinism proof is the in-process null-sink versus ring-sink plan digest (`decision_trace_hash_matches_when_the_ring_is_off`). Trace bytes are not a required replay case. 3. `tools/aw_decision` is the inspector. The editor panel stays later, after issues #265 and #273 close. -4. The #251 rebase rule stands. This branch starts at `ea8ec329` and does not drop a required case. +4. The #251 rebase rule stands. This branch starts at `fe349aa0` and does not drop a required case. `rerun` takes `&mut PlannerView` so the caller-owned nav scratch can be borrowed mutably. `DecisionTrace::new` allocates the agent rings once; `push` does not. The `aravath-bridge` script uses `bridge_and_ford` and a detach at tick 30. It does not call `BridgeAgent`, which still lives on PR #263. diff --git a/tools/aw_decision/src/lib.rs b/tools/aw_decision/src/lib.rs index 894565c9a9..b2c374c8c6 100644 --- a/tools/aw_decision/src/lib.rs +++ b/tools/aw_decision/src/lib.rs @@ -120,6 +120,7 @@ fn simulate_through(last_tick: u64) -> (DecisionTrace, NavTiles) { let _ = tiles.commit_tick(); let mut budget = 64u32; let mut plan = AgentPlan::empty(); + let _guard = astraweave_ai::htn::attach_trace(&mut trace, ENTITY); plan_route( &tiles, &mut scratch, @@ -129,8 +130,6 @@ fn simulate_through(last_tick: u64) -> (DecisionTrace, NavTiles) { tick, &mut plan, &mut budget, - &mut trace, - ENTITY, ); } (trace, tiles) From b0fa24de6ede04aca7d6d3af870878e18b7846b9 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 15 Oct 2026 20:48:06 +0000 Subject: [PATCH 3/3] docs: restack the decision debugger onto main at e894d019 The required replay set is the eight cases on main. The allocation test reads the ring after the trace guard returns it. Co-authored-by: Andrew Brown --- astraweave-ai/tests/decision_trace_alloc.rs | 30 ++++++++++--------- docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md | 6 ++-- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/astraweave-ai/tests/decision_trace_alloc.rs b/astraweave-ai/tests/decision_trace_alloc.rs index 90d7a21d9c..7131b18137 100644 --- a/astraweave-ai/tests/decision_trace_alloc.rs +++ b/astraweave-ai/tests/decision_trace_alloc.rs @@ -39,19 +39,21 @@ fn traced_plan_route_allocates_nothing_after_warmup() { } reset_allocs(); - let mut budget = 64u32; - let mut plan = AgentPlan::empty(); - let _guard = astraweave_ai::htn::attach_trace(&mut trace, 1); - plan_route( - &tiles, - &mut scratch, - [1_000, 0, 1_000], - [1_000, 0, 46_000], - &hooks, - 4, - &mut plan, - &mut budget, - ); - assert_eq!(allocs(), 0, "traced plan_route allocated"); + { + let mut budget = 64u32; + let mut plan = AgentPlan::empty(); + let _guard = astraweave_ai::htn::attach_trace(&mut trace, 1); + plan_route( + &tiles, + &mut scratch, + [1_000, 0, 1_000], + [1_000, 0, 46_000], + &hooks, + 4, + &mut plan, + &mut budget, + ); + assert_eq!(allocs(), 0, "traced plan_route allocated"); + } assert!(trace.count_of(1) > 4); } diff --git a/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md b/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md index bb553966b8..69c03750b7 100644 --- a/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md +++ b/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md @@ -1,6 +1,6 @@ # Semantic AI decision debugger -Approved 2026-10-15. Every question in §14 was accepted as proposed. The implementation is stacked on PR #251 at `fe349aa0`, which keeps all six required replay cases (`planner_pure`, `perception_world`, `gameplay_rng`, `fixed64`, `combat_resolve`, `nav_reroute`). `NavChangeKind` on that head matches PR #263. `perception_world` on that head is `6e52e721ceb8a96413a7ae0ba1ad3f88adaeb37c56ba520c3a3cb9f6f0bf7ebb` because `4172ed01` stopped `build_snapshot` from inserting a breach POI. Tracing does not change that digest. +Approved 2026-10-15. Every question in §14 was accepted as proposed. The implementation is restacked on `main` at `e894d019` after PR #251 and PR #263 merged. The required replay set is eight cases: `planner_pure`, `perception_world`, `gameplay_rng`, `fixed64`, `combat_resolve`, `destruction`, `gameplay_qa_aravath_slice`, and `nav_reroute`. `perception_world` is `6e52e721ceb8a96413a7ae0ba1ad3f88adaeb37c56ba520c3a3cb9f6f0bf7ebb` because `4172ed01` stopped `build_snapshot` from inserting a breach POI. Tracing does not change that digest. The survey below was taken at `main` `f1109340` and on the #251 draft before that rebase. It stays as the map. The code that landed from this approval is `astraweave-ai/src/decision_trace.rs` (feature `decision-trace`, default off), the record sites in the hierarchical tick and the grid planners, and the headless `tools/aw_decision` binary. No editor panel. No new asset. @@ -9,9 +9,9 @@ The survey below was taken at `main` `f1109340` and on the #251 draft before tha 1. Feature-off is the zero-cost mode. `decision_record!` compiles to nothing unless `decision-trace` is on. The default replay build leaves the feature off. 2. The determinism proof is the in-process null-sink versus ring-sink plan digest (`decision_trace_hash_matches_when_the_ring_is_off`). Trace bytes are not a required replay case. 3. `tools/aw_decision` is the inspector. The editor panel stays later, after issues #265 and #273 close. -4. The #251 rebase rule stands. This branch starts at `fe349aa0` and does not drop a required case. +4. The #251 rebase rule stands. This branch is on `main` at `e894d019` and keeps all eight required cases. -`rerun` takes `&mut PlannerView` so the caller-owned nav scratch can be borrowed mutably. `DecisionTrace::new` allocates the agent rings once; `push` does not. The `aravath-bridge` script uses `bridge_and_ford` and a detach at tick 30. It does not call `BridgeAgent`, which still lives on PR #263. +`rerun` takes `&mut PlannerView` so the caller-owned nav scratch can be borrowed mutably. `DecisionTrace::new` allocates the agent rings once; `push` does not. The `aravath-bridge` script uses `bridge_and_ford` and a detach at tick 30. `BridgeAgent` is now on `main` in `aravath_runtime`; the inspector still does not call it. ## 1. What a user can select