1use serde::{Deserialize, Serialize};
18
19use crate::action::Action;
20use crate::state::State;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
24pub enum Gate {
25 #[serde(rename = "inv5")]
27 Inv5StutterBudget,
28 #[serde(rename = "inv6")]
30 Inv6ResidualProductivity,
31 #[serde(rename = "inv7")]
33 Inv7MergeAcyclicity,
34 #[serde(rename = "inv8")]
36 Inv8JepaWindowTrend,
37 #[serde(rename = "inv9")]
39 Inv9EnergyEveryAction,
40 #[serde(rename = "inv10")]
42 Inv10MatchWellTyped,
43 #[serde(rename = "inv11")]
45 Inv11FairProductivity,
46}
47
48impl Gate {
49 pub const ALL: [Gate; 7] = [
50 Gate::Inv5StutterBudget,
51 Gate::Inv6ResidualProductivity,
52 Gate::Inv7MergeAcyclicity,
53 Gate::Inv8JepaWindowTrend,
54 Gate::Inv9EnergyEveryAction,
55 Gate::Inv10MatchWellTyped,
56 Gate::Inv11FairProductivity,
57 ];
58
59 pub fn name(&self) -> &'static str {
60 match self {
61 Gate::Inv5StutterBudget => "inv5",
62 Gate::Inv6ResidualProductivity => "inv6",
63 Gate::Inv7MergeAcyclicity => "inv7",
64 Gate::Inv8JepaWindowTrend => "inv8",
65 Gate::Inv9EnergyEveryAction => "inv9",
66 Gate::Inv10MatchWellTyped => "inv10",
67 Gate::Inv11FairProductivity => "inv11",
68 }
69 }
70
71 pub fn parse(s: &str) -> Option<Gate> {
72 match s.trim().to_lowercase().as_str() {
73 "inv5" => Some(Gate::Inv5StutterBudget),
74 "inv6" => Some(Gate::Inv6ResidualProductivity),
75 "inv7" => Some(Gate::Inv7MergeAcyclicity),
76 "inv8" => Some(Gate::Inv8JepaWindowTrend),
77 "inv9" => Some(Gate::Inv9EnergyEveryAction),
78 "inv10" => Some(Gate::Inv10MatchWellTyped),
79 "inv11" => Some(Gate::Inv11FairProductivity),
80 _ => None,
81 }
82 }
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct GateConfig {
88 #[serde(default)]
90 pub enabled: Vec<Gate>,
91 #[serde(default = "default_stutter_k")]
93 pub stutter_k: u64,
94 #[serde(default = "default_window")]
96 pub window: usize,
97 #[serde(default = "default_horizon")]
99 pub horizon: usize,
100 #[serde(default = "default_trend_tol")]
108 pub trend_tol: f64,
109 #[serde(default = "default_energy_tol")]
111 pub energy_tol: f64,
112}
113
114fn default_stutter_k() -> u64 {
115 2
116}
117fn default_window() -> usize {
118 8
119}
120fn default_horizon() -> usize {
121 32
122}
123fn default_trend_tol() -> f64 {
124 0.25
125}
126fn default_energy_tol() -> f64 {
127 1e-10
128}
129
130impl Default for GateConfig {
131 fn default() -> Self {
132 GateConfig {
133 enabled: Vec::new(),
134 stutter_k: default_stutter_k(),
135 window: default_window(),
136 horizon: default_horizon(),
137 trend_tol: default_trend_tol(),
138 energy_tol: default_energy_tol(),
139 }
140 }
141}
142
143impl GateConfig {
144 pub fn parse_list(s: &str) -> Result<Vec<Gate>, String> {
146 let s = s.trim();
147 if s.is_empty() || s.eq_ignore_ascii_case("none") {
148 return Ok(Vec::new());
149 }
150 if s.eq_ignore_ascii_case("all") {
151 return Ok(Gate::ALL.to_vec());
152 }
153 s.split(',')
154 .map(|part| Gate::parse(part).ok_or_else(|| format!("unknown gate '{}'", part.trim())))
155 .collect()
156 }
157
158 pub fn is_enabled(&self, g: Gate) -> bool {
159 self.enabled.contains(&g)
160 }
161}
162
163#[derive(Debug, Clone, Serialize, Deserialize)]
165pub struct GateBreach {
166 pub gate: String,
167 pub step: u64,
168 pub detail: String,
169}
170
171#[derive(Debug, Clone, Default, Serialize, Deserialize)]
173pub struct GateReport {
174 pub enabled: Vec<String>,
175 pub breaches: Vec<GateBreach>,
176}
177
178impl GateReport {
179 pub fn all_ok(&self) -> bool {
180 self.breaches.is_empty()
181 }
182}
183
184#[derive(Debug)]
190pub struct GateMonitor {
191 config: GateConfig,
192 step: u64,
193 consecutive_stutters: u64,
194 hot_residual_age: Option<usize>,
196 unproductive_run: usize,
198 residuals: Vec<f64>,
200 breaches: Vec<GateBreach>,
201}
202
203impl GateMonitor {
204 pub fn new(config: GateConfig) -> Self {
205 GateMonitor {
206 config,
207 step: 0,
208 consecutive_stutters: 0,
209 hot_residual_age: None,
210 unproductive_run: 0,
211 residuals: Vec::new(),
212 breaches: Vec::new(),
213 }
214 }
215
216 #[allow(clippy::too_many_lines)]
220 pub fn observe(&mut self, action: Action, state: &State, residual: f64, eps: f64) {
221 let productive = action != Action::Stutter;
222
223 if action == Action::Stutter {
225 self.consecutive_stutters += 1;
226 } else {
227 self.consecutive_stutters = 0;
228 }
229 if self.config.is_enabled(Gate::Inv5StutterBudget)
230 && self.consecutive_stutters > self.config.stutter_k
231 {
232 self.breach(
233 Gate::Inv5StutterBudget,
234 format!(
235 "{} consecutive Stutters exceeds K = {}",
236 self.consecutive_stutters, self.config.stutter_k
237 ),
238 );
239 }
240
241 let answers_residual = matches!(action, Action::Predict | Action::Match | Action::Diffuse);
243 if answers_residual {
244 self.hot_residual_age = None;
245 } else if let Some(age) = self.hot_residual_age.as_mut() {
246 *age += 1;
247 }
248 if residual > eps && self.hot_residual_age.is_none() && !answers_residual {
249 self.hot_residual_age = Some(0);
250 }
251 if self.config.is_enabled(Gate::Inv6ResidualProductivity) {
252 if let Some(age) = self.hot_residual_age {
253 if age >= self.config.window {
254 self.breach(
255 Gate::Inv6ResidualProductivity,
256 format!(
257 "Res = {residual:.6} > ε = {eps:.6} for {age} steps with no Predict/Match/Diffuse"
258 ),
259 );
260 self.hot_residual_age = None;
261 }
262 }
263 }
264
265 if self.config.is_enabled(Gate::Inv7MergeAcyclicity)
267 && action == Action::Match
268 && !state.g.is_acyclic()
269 {
270 self.breach(
271 Gate::Inv7MergeAcyclicity,
272 format!(
273 "Match produced a cyclic graph (|V| = {})",
274 state.g.node_count()
275 ),
276 );
277 }
278
279 self.residuals.push(residual);
281 if self.residuals.len() > self.config.horizon {
282 self.residuals.remove(0);
283 }
284 if self.config.is_enabled(Gate::Inv8JepaWindowTrend)
285 && self.residuals.len() == self.config.horizon
286 {
287 let half = self.config.horizon / 2;
288 let early: f64 = self.residuals[..half].iter().sum::<f64>() / half as f64;
289 let late: f64 =
290 self.residuals[half..].iter().sum::<f64>() / (self.config.horizon - half) as f64;
291 let allowed = early * (1.0 + self.config.trend_tol) + 1e-12;
294 if late > allowed {
295 self.breach(
296 Gate::Inv8JepaWindowTrend,
297 format!(
298 "mean residual rose {:.6} → {:.6} (+{:.1}%) over horizon {}, tol {:.0}%",
299 early,
300 late,
301 100.0 * (late - early) / early.max(f64::MIN_POSITIVE),
302 self.config.horizon,
303 100.0 * self.config.trend_tol
304 ),
305 );
306 self.residuals.clear();
307 }
308 }
309
310 if self.config.is_enabled(Gate::Inv9EnergyEveryAction) {
312 let drift = (state.energy() - state.energy_0).abs();
313 if drift > self.config.energy_tol {
314 self.breach(
315 Gate::Inv9EnergyEveryAction,
316 format!("{action:?} drifted energy by {drift:.3e}"),
317 );
318 }
319 }
320
321 if self.config.is_enabled(Gate::Inv10MatchWellTyped) && action == Action::Match {
323 let dim = state.z.len();
324 if !state.g.ok(dim) {
325 self.breach(
326 Gate::Inv10MatchWellTyped,
327 "Match produced a graph failing GraphOK".into(),
328 );
329 }
330 }
331
332 if productive {
334 self.unproductive_run = 0;
335 } else {
336 self.unproductive_run += 1;
337 }
338 if self.config.is_enabled(Gate::Inv11FairProductivity)
339 && self.unproductive_run >= self.config.window
340 {
341 self.breach(
342 Gate::Inv11FairProductivity,
343 format!(
344 "{} consecutive non-productive steps (window {})",
345 self.unproductive_run, self.config.window
346 ),
347 );
348 self.unproductive_run = 0;
349 }
350
351 self.step += 1;
352 }
353
354 fn breach(&mut self, gate: Gate, detail: String) {
355 self.breaches.push(GateBreach {
356 gate: gate.name().to_string(),
357 step: self.step,
358 detail,
359 });
360 }
361
362 pub fn finish(self) -> GateReport {
364 GateReport {
365 enabled: self
366 .config
367 .enabled
368 .iter()
369 .map(|g| g.name().into())
370 .collect(),
371 breaches: self.breaches,
372 }
373 }
374}
375
376#[cfg(test)]
377mod tests {
378 use super::*;
379 use crate::graph::{EdgeType, Graph, GraphOp, NodeId, NodeType};
380 use num_complex::Complex64;
381
382 fn add_test_node(g: &mut Graph, id: NodeId, emb_dim: usize) {
388 g.apply(
389 &GraphOp::AddNode {
390 id,
391 ntype: NodeType::Observation,
392 emb: vec![0.0; emb_dim],
393 ts: 0,
394 },
395 emb_dim,
396 )
397 .expect("fixture node must apply");
398 }
399
400 fn add_test_edge(g: &mut Graph, from: NodeId, to: NodeId) {
401 g.apply(
402 &GraphOp::AddEdge {
403 from,
404 to,
405 etype: EdgeType::CausallyPrecedes,
406 },
407 0,
408 )
409 .expect("fixture edge must apply");
410 }
411
412 fn state(latent_dim: usize) -> State {
413 State {
414 psi: vec![Complex64::new(1.0, 0.0)],
415 z: vec![0.0; latent_dim],
416 g: Graph::empty(),
417 t: 0,
418 prev_res: 0.0,
419 energy_0: 1.0,
420 }
421 }
422
423 fn monitor(gates: &[Gate]) -> GateMonitor {
424 GateMonitor::new(GateConfig {
425 enabled: gates.to_vec(),
426 window: 4,
427 horizon: 8,
428 ..GateConfig::default()
429 })
430 }
431
432 #[test]
433 fn no_gates_means_no_breaches() {
434 let mut m = monitor(&[]);
435 let s = state(4);
436 for _ in 0..50 {
437 m.observe(Action::Stutter, &s, 99.0, 1.0);
438 }
439 assert!(m.finish().all_ok(), "gates must be off by default");
440 }
441
442 #[test]
443 fn inv5_flags_an_over_budget_stutter_run() {
444 let mut m = monitor(&[Gate::Inv5StutterBudget]);
445 let s = state(4);
446 for _ in 0..5 {
447 m.observe(Action::Stutter, &s, 0.0, 1.0);
448 }
449 let r = m.finish();
450 assert!(!r.all_ok());
451 assert!(r.breaches.iter().all(|b| b.gate == "inv5"));
452 }
453
454 #[test]
455 fn inv5_accepts_a_bounded_stutter_run() {
456 let mut m = monitor(&[Gate::Inv5StutterBudget]);
457 let s = state(4);
458 for _ in 0..10 {
459 m.observe(Action::Stutter, &s, 0.0, 1.0);
460 m.observe(Action::Stutter, &s, 0.0, 1.0);
461 m.observe(Action::OpticalStep, &s, 0.0, 1.0);
462 }
463 assert!(m.finish().all_ok());
464 }
465
466 #[test]
467 fn inv6_flags_a_hot_residual_left_unanswered() {
468 let mut m = monitor(&[Gate::Inv6ResidualProductivity]);
469 let s = state(4);
470 for _ in 0..10 {
471 m.observe(Action::OpticalStep, &s, 5.0, 1.0);
472 }
473 let r = m.finish();
474 assert!(r.breaches.iter().any(|b| b.gate == "inv6"), "{r:?}");
475 }
476
477 #[test]
478 fn inv6_accepts_a_hot_residual_answered_by_predict() {
479 let mut m = monitor(&[Gate::Inv6ResidualProductivity]);
480 let s = state(4);
481 for _ in 0..10 {
482 m.observe(Action::OpticalStep, &s, 5.0, 1.0);
483 m.observe(Action::Predict, &s, 0.0, 1.0);
484 }
485 assert!(m.finish().all_ok());
486 }
487
488 #[test]
489 fn inv7_flags_a_cyclic_match_result() {
490 let mut m = monitor(&[Gate::Inv7MergeAcyclicity]);
491 let mut s = state(2);
492 add_test_node(&mut s.g, 1, 2);
493 add_test_node(&mut s.g, 2, 2);
494 add_test_edge(&mut s.g, 1, 2);
495 add_test_edge(&mut s.g, 2, 1);
496 m.observe(Action::Match, &s, 0.0, 1.0);
497 assert!(m.finish().breaches.iter().any(|b| b.gate == "inv7"));
498 }
499
500 #[test]
501 fn inv8_ignores_stationary_noise() {
502 let mut m = monitor(&[Gate::Inv8JepaWindowTrend]);
503 let s = state(4);
504 for i in 0..200 {
506 let r = 1.0 + 0.1 * (f64::from(i) * 0.7).sin();
507 m.observe(Action::OpticalStep, &s, r, 1.0);
508 }
509 assert!(
510 m.finish().all_ok(),
511 "Inv8 must not fire on stationary noise"
512 );
513 }
514
515 #[test]
516 fn inv8_flags_a_diverging_residual() {
517 let mut m = monitor(&[Gate::Inv8JepaWindowTrend]);
518 let s = state(4);
519 for i in 0..64 {
520 m.observe(Action::OpticalStep, &s, 1.0 + f64::from(i), 1.0);
521 }
522 assert!(m.finish().breaches.iter().any(|b| b.gate == "inv8"));
523 }
524
525 #[test]
526 fn inv8_accepts_a_falling_residual() {
527 let mut m = monitor(&[Gate::Inv8JepaWindowTrend]);
528 let s = state(4);
529 for i in 0..64 {
530 m.observe(Action::OpticalStep, &s, 10.0 / (1.0 + f64::from(i)), 1.0);
531 }
532 assert!(m.finish().all_ok());
533 }
534
535 #[test]
536 fn inv9_flags_energy_drift() {
537 let mut m = monitor(&[Gate::Inv9EnergyEveryAction]);
538 let mut s = state(4);
539 s.energy_0 = 2.0; m.observe(Action::Stutter, &s, 0.0, 1.0);
541 assert!(m.finish().breaches.iter().any(|b| b.gate == "inv9"));
542 }
543
544 #[test]
545 fn inv10_flags_a_match_to_a_bad_graph() {
546 let mut m = monitor(&[Gate::Inv10MatchWellTyped]);
547 let mut s = state(4);
548 add_test_node(&mut s.g, 1, 2);
550 m.observe(Action::Match, &s, 0.0, 1.0);
551 assert!(m.finish().breaches.iter().any(|b| b.gate == "inv10"));
552 }
553
554 #[test]
555 fn inv11_flags_starved_productivity() {
556 let mut m = monitor(&[Gate::Inv11FairProductivity]);
557 let s = state(4);
558 for _ in 0..12 {
559 m.observe(Action::Stutter, &s, 0.0, 1.0);
560 }
561 assert!(m.finish().breaches.iter().any(|b| b.gate == "inv11"));
562 }
563
564 #[test]
565 fn parse_list_handles_names_all_and_none() {
566 assert_eq!(GateConfig::parse_list("").unwrap(), vec![]);
567 assert_eq!(GateConfig::parse_list("none").unwrap(), vec![]);
568 assert_eq!(GateConfig::parse_list("all").unwrap(), Gate::ALL.to_vec());
569 assert_eq!(
570 GateConfig::parse_list("inv5, inv9").unwrap(),
571 vec![Gate::Inv5StutterBudget, Gate::Inv9EnergyEveryAction]
572 );
573 assert!(GateConfig::parse_list("inv12").is_err());
574 }
575}