1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
//! Policy engine: Silent | Watch | Review | Escalate.
//!
//! The policy engine is the final stage in the deterministic pipeline:
//!
//! IQ Residual → Sign → Syntax → Grammar → Semantics → Policy
//!
//! It maps (grammar_state, semantic_disposition, dsa_score, corroboration)
//! → PolicyDecision, subject to persistence and fragmentation constraints.
//!
//! ## Policy Rules (paper §VIII, §B.5)
//!
//! - Silent: grammar Admissible, DSA < τ, or persistence gate failed
//! - Watch: motif active, DSA < τ or persistence < K
//! - Review: persistence ≥ K AND motif class = Review-grade
//! - Escalate: persistence ≥ K AND Violation-class motif or Violation grammar
use crate::grammar::GrammarState;
use crate::heuristics::SemanticDisposition;
use crate::dsa::DsaScore;
/// The operator-facing policy decision.
///
/// This is the terminal output of the DSFB pipeline. It is the single
/// value the integration layer presents to the operator or upstream
/// alerting system.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PolicyDecision {
/// No structural activity detected. Nominal operation.
Silent,
/// Structural activity below escalation threshold. Continue monitoring.
Watch,
/// Persistent structural episode. Operator review warranted.
Review,
/// Violation-class episode. Immediate operator attention required.
Escalate,
}
impl PolicyDecision {
/// Returns true if this decision requires operator action.
#[inline]
pub fn requires_action(&self) -> bool {
matches!(self, PolicyDecision::Review | PolicyDecision::Escalate)
}
/// Numeric level for metric computation (0–3).
#[inline]
pub fn level(&self) -> u8 {
*self as u8
}
}
/// Policy configuration — the Stage III fixed protocol parameters.
#[derive(Debug, Clone, Copy)]
pub struct PolicyConfig {
/// DSA score threshold τ. Default 2.0 (paper Stage III).
pub tau: f32,
/// Persistence count K. Default 4 (paper Stage III).
pub k: u8,
/// Minimum corroboration count m. Default 1 (paper Stage III).
pub m: u8,
/// When `true`, a [`GrammarState::Violation`] causes an immediate
/// [`PolicyDecision::Escalate`] without waiting for K persistence
/// observations. This is the **magnitude-gated bypass** described in
/// paper §L item 9 (hypersonic detection latency defence): an extreme
/// violation (residual norm >> ρ, triggering `Violation` directly) must
/// not be delayed by the hysteresis confirmation window.
///
/// Default: `true`. Set to `false` only if false-escalation suppression
/// is more important than latency (e.g., benign laboratory environments
/// with high transient artefact rates).
pub extreme_bypass: bool,
}
impl Default for PolicyConfig {
fn default() -> Self {
Self { tau: 2.0, k: 4, m: 1, extreme_bypass: true }
}
}
impl PolicyConfig {
/// Paper Stage III fixed configuration.
pub const STAGE_III: Self = Self { tau: 2.0, k: 4, m: 1, extreme_bypass: true };
}
/// Policy evaluator with persistence tracking.
///
/// Maintains a consecutive-observation persistence counter.
/// Fires Review/Escalate only when DSA ≥ τ for ≥ K consecutive observations
/// with ≥ m corroborating channels.
pub struct PolicyEvaluator {
config: PolicyConfig,
/// Consecutive observations with DSA ≥ τ.
persistence: u8,
/// Whether last-committed decision was Review or Escalate (for fragmentation guard).
episode_open: bool,
}
impl PolicyEvaluator {
/// Create a new evaluator with Stage III defaults.
pub const fn new() -> Self {
Self {
config: PolicyConfig::STAGE_III,
persistence: 0,
episode_open: false,
}
}
/// Create with custom configuration.
pub const fn with_config(config: PolicyConfig) -> Self {
Self { config, persistence: 0, episode_open: false }
}
/// Evaluate policy for one observation.
///
/// The integration contract: this method has `&mut self` (the evaluator
/// maintains persistence state), but accepts the upstream observables
/// as immutable references. There is no write path into upstream data.
pub fn evaluate(
&mut self,
grammar: GrammarState,
disposition: SemanticDisposition,
dsa: DsaScore,
corroboration_count: u8,
) -> PolicyDecision {
// DSA threshold and corroboration gate
let dsa_active = dsa.meets_threshold(self.config.tau);
let corroborated = corroboration_count >= self.config.m;
// Magnitude-gated extreme bypass (paper §L item 9, hypersonic defence):
// An immediate Violation grammar state bypasses the K-persistence
// hysteresis gate and escalates on the first observation. This
// prevents multi-window confirmation delay when the residual norm
// far exceeds ρ (the grammar only assigns Violation for |r| ≫ ρ_eff).
if self.config.extreme_bypass && grammar.is_violation() && corroborated {
self.persistence = self.persistence.saturating_add(1);
self.episode_open = true;
return PolicyDecision::Escalate;
}
// Update persistence counter
if dsa_active && corroborated && grammar.requires_attention() {
self.persistence = self.persistence.saturating_add(1);
} else {
self.persistence = 0;
self.episode_open = false;
}
// Decision logic
if !grammar.requires_attention() || !corroborated {
PolicyDecision::Silent
} else if !dsa_active || self.persistence < self.config.k {
PolicyDecision::Watch
} else if grammar.is_violation()
|| matches!(disposition,
SemanticDisposition::AbruptOnsetEvent
| SemanticDisposition::PreTransitionCluster)
{
self.episode_open = true;
PolicyDecision::Escalate
} else {
self.episode_open = true;
PolicyDecision::Review
}
}
/// Reset the evaluator (e.g., after a post-transition guard window).
pub fn reset(&mut self) {
self.persistence = 0;
self.episode_open = false;
}
/// Returns true if an episode is currently open.
#[inline]
pub fn episode_open(&self) -> bool {
self.episode_open
}
/// Current persistence count.
#[inline]
pub fn persistence(&self) -> u8 {
self.persistence
}
}
impl Default for PolicyEvaluator {
fn default() -> Self {
Self::new()
}
}
// ---------------------------------------------------------------
// Tests
// ---------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use crate::grammar::{GrammarState, ReasonCode};
use crate::heuristics::SemanticDisposition;
use crate::dsa::DsaScore;
fn boundary() -> GrammarState {
GrammarState::Boundary(ReasonCode::SustainedOutwardDrift)
}
#[test]
fn clean_signal_is_silent() {
let mut p = PolicyEvaluator::new();
let d = p.evaluate(
GrammarState::Admissible,
SemanticDisposition::Unknown,
DsaScore(0.1),
0,
);
assert_eq!(d, PolicyDecision::Silent);
}
#[test]
fn watch_before_persistence_threshold() {
let mut p = PolicyEvaluator::new();
// K=4, so first 3 should be Watch
for _ in 0..3 {
let d = p.evaluate(boundary(), SemanticDisposition::PreTransitionCluster,
DsaScore(3.0), 1);
assert_eq!(d, PolicyDecision::Watch,
"should be Watch before K=4 persistence");
}
}
#[test]
fn escalate_after_k_consecutive_with_pre_transition() {
let mut p = PolicyEvaluator::new();
let mut last = PolicyDecision::Silent;
for _ in 0..5 {
last = p.evaluate(boundary(), SemanticDisposition::PreTransitionCluster,
DsaScore(3.0), 1);
}
assert_eq!(last, PolicyDecision::Escalate);
}
#[test]
fn review_for_corroborating_drift() {
let mut p = PolicyEvaluator::new();
let mut last = PolicyDecision::Silent;
for _ in 0..5 {
last = p.evaluate(boundary(), SemanticDisposition::CorroboratingDrift,
DsaScore(3.0), 1);
}
assert_eq!(last, PolicyDecision::Review);
}
#[test]
fn violation_always_escalates_after_persistence() {
let mut p = PolicyEvaluator::new();
let mut last = PolicyDecision::Silent;
for _ in 0..5 {
last = p.evaluate(GrammarState::Violation,
SemanticDisposition::Unknown, DsaScore(3.0), 1);
}
assert_eq!(last, PolicyDecision::Escalate);
}
#[test]
fn policy_resets_on_clean_window() {
let mut p = PolicyEvaluator::new();
// Build up persistence
for _ in 0..5 {
p.evaluate(boundary(), SemanticDisposition::PreTransitionCluster,
DsaScore(3.0), 1);
}
// Clean observation resets
p.evaluate(GrammarState::Admissible, SemanticDisposition::Unknown,
DsaScore(0.1), 0);
assert_eq!(p.persistence(), 0);
assert!(!p.episode_open());
}
#[test]
fn requires_action_only_for_review_escalate() {
assert!(!PolicyDecision::Silent.requires_action());
assert!(!PolicyDecision::Watch.requires_action());
assert!(PolicyDecision::Review.requires_action());
assert!(PolicyDecision::Escalate.requires_action());
}
}