llmosafe 0.7.3

Safety-critical cognitive safety library for AI agents. 4-tier architecture (Resource Body, Kernel, Working Memory, Sifter) with formal verification primitives, detection layer, and integration primitives.
Documentation
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
//! `CognitivePipeline` — 5-stage sequential safety pipeline.
//!
//! Wires the sifter, working memory, kernel, 5 detectors, dynamic stability
//! monitor, PID controller, and escalation policy into a single cascade that
//! can short-circuit at any stage.
//!
//! # Stage Flow
//!
//! ```text
//! process(text) → SIFT → MEMORY → KERNEL → DETECTION → PID → MONITOR → PipelineResult
//!                    │       │        │         │        │        │
//!                    ▼       ▼        ▼         ▼        ▼        ▼
//!             Halt?   Halt?    Halt?    Gate?    Risk    Advisory
//! ```
//!
//! 1. **SIFT** (Tier 3) — `sift_text_with_score()` classifies text, builds
//!    `SiftedSynapse`. Gate: `EscalationPolicy::decide()`.
//! 2. **MEMORY** (Tier 2) — `WorkingMemory::update()` pushes synapse into ring
//!    buffer. Gate: surprise threshold.
//! 3. **KERNEL** (Tier 1) — `ReasoningLoop::next_step()` advances reasoning.
//!    Gate: depth, bias, entropy stability.
//! 4. **DETECTION** — 5 detectors observe the observation. Flags packed into
//!    synapse reserved bits. Optional detection-gate path bypasses PID.
//! 5. **PID** — `compute_pid_score_pure()` + `apply_safety_overrides()` produce
//!    a risk score mapped to `SafetyDecision` via thresholds.
//! 6. **MONITOR** — `DynamicStabilityMonitor::update()` records entropy envelope.
//!    Advisory only.
//!
//! # Key Types
//!
//! - `CognitivePipeline<'a, MEM_SIZE, MAX_STEPS>` — owns all safety components
//! - `PipelineConfig` — threshold configuration with `validate()` bounds checking
//! - `PipelineResult` — final decision, classified synapse, stage bitmask, diagnostics
//! - `MemoryStats` — snapshot of working-memory mean, variance, trend
//!
//! # Processing Modes
//!
//! - `process(observation)` — standard 5-stage pipeline
//! - `process_with_pressure(observation, body_entropy, pressure)` — adds resource
//!   body pre-gate before SIFT
//! - `process_ctrl(observation, e_body, pressure)` — control-theory composition
//!   path with PID mandatory
//! - `process_safe(text, guard)` — pre-flight resource gate with deadline
#![deny(clippy::cast_lossless)]
// Arithmetic in this module operates on bounded counters and time values
// where wrap/instant arithmetic is the intended behavior.
// DO-178C: these operations are verified safe by value range analysis at
// the module boundary — inputs are always validated before arithmetic.
#![allow(clippy::arithmetic_side_effects)]

use crate::control_types::OverrideFlags;
#[cfg(feature = "std")]
use crate::llmosafe_detection::DetectionResult;
use crate::llmosafe_detection::{
    AdversarialDetector, ConfidenceTracker, CusumDetector, DriftDetector, RepetitionDetector,
};
use crate::llmosafe_integration::EscalationPolicy;
#[cfg(feature = "std")]
use crate::llmosafe_integration::SafetyDecision;
#[cfg(not(feature = "std"))]
use crate::llmosafe_integration::SafetyDecision;
use crate::llmosafe_kernel::{
    DynamicStabilityMonitor, KernelError, KernelOutput, ReasoningLoop, StabilityResult, Synapse,
    ValidatedSynapse, FLAG_ADVERSARIAL, FLAG_ANOMALY, FLAG_DECAYING, FLAG_DRIFTING,
    FLAG_LOW_CONFIDENCE, FLAG_STUCK,
};
use crate::llmosafe_memory::WorkingMemory;
use crate::llmosafe_pid::{PidConfig, PidState};
#[cfg(feature = "std")]
use crate::ResourceGuard;

/// Bitmask constants for `PipelineResult.stages_executed`.
/// Set in `process_ctrl()` during sequential stage execution.
pub const STAGE_SIFT: u8 = 0x01;
/// Bitmask constant 0x02 for the MEMORY stage. Set in `process_ctrl()`.
pub const STAGE_MEMORY: u8 = 0x02;
/// Bitmask constant 0x04 for the KERNEL stage. Set in `process_ctrl()`.
pub const STAGE_KERNEL: u8 = 0x04;
/// Bitmask constant 0x08 for the DETECTION stage. Set in `process_ctrl()`.
pub const STAGE_DETECTION: u8 = 0x08;
/// Bitmask constant 0x10 for the MONITOR stage. Set in `process_ctrl()`.
pub const STAGE_MONITOR: u8 = 0x10;
/// Bitmask constant 0x20 gated behind cfg(feature="std"). Set in
/// `process_with_pressure()` after the body pressure pre-gate executes
/// and `process_ctrl()` returns.
#[cfg(feature = "std")]
pub const STAGE_BODY: u8 = 0x20;

/// Configuration for a CognitivePipeline instance.
///
/// Every threshold has a safe default via `Default::default()`.
/// Fields with `f32` values must be in `[0.0, 1.0]` and finite.
/// Use `validate()` to check bounds before constructing a pipeline.
///
/// Fields:
/// - `policy: EscalationPolicy` — escalation policy thresholds (entropy warn/escalate/halt, surprise, bias).
/// - `pid_config: PidConfig` — PID controller configuration. Must be valid.
/// - `surprise_threshold: i128` — surprise threshold for `WorkingMemory`. Values above this are rejected as `HallucinationDetected`.
/// - `max_repetitions: usize` — maximum repetitions before stuck detection fires.
/// - `drift_threshold: f32` — drift threshold (0.0–1.0). Drift above this triggers `GoalDriftDetected`.
/// - `min_confidence: f32` — minimum confidence threshold (0.0–1.0). Confidence below this is flagged.
/// - `decay_threshold: usize` — decay threshold: consecutive confidence drops before decay warning.
/// - `monitor_k: u8` — `DynamicStabilityMonitor` safety margin k (1–5). Controls envelope sensitivity.
/// - `use_detection_gate: bool` — when true, routes decisions through `decide_from_detection()` instead of the PID weighted summation path.
pub struct PipelineConfig {
    /// Escalation policy thresholds (entropy warn/escalate/halt, surprise, bias).
    pub policy: EscalationPolicy,
    /// PID controller configuration. Must be valid.
    pub pid_config: PidConfig,
    /// Surprise threshold for `WorkingMemory`. Values above this are rejected
    /// as `HallucinationDetected`.
    pub surprise_threshold: i128,
    /// Maximum repetitions before stuck detection fires.
    pub max_repetitions: usize,
    /// Drift threshold (0.0–1.0). Drift above this triggers `GoalDriftDetected`.
    pub drift_threshold: f32,
    /// Minimum confidence threshold (0.0–1.0). Confidence below this is flagged.
    pub min_confidence: f32,
    /// Decay threshold: consecutive confidence drops before decay warning.
    pub decay_threshold: usize,
    /// `DynamicStabilityMonitor` safety margin k (1–5). Controls envelope sensitivity.
    pub monitor_k: u8,
    /// When true, routes decisions through `decide_from_detection()` (first-match-wins
    /// severity ordering: Anomaly > Adversarial > Drifting > Stuck > Confidence) instead
    /// of the PID weighted summation path.  The detection-gate path avoids PID integrator
    /// state entirely — it is simpler and faster but does not remember past observations
    /// beyond what the individual detectors track.  Default: false (PID path).
    pub use_detection_gate: bool,
}

impl Default for PipelineConfig {
    /// Safe defaults calibrated for the classifier entropy range `[0, 65535]`.
    fn default() -> Self {
        Self {
            policy: EscalationPolicy::default(),
            pid_config: PidConfig::default(),
            surprise_threshold: 58000,
            max_repetitions: 3,
            drift_threshold: 0.5,
            min_confidence: 0.3,
            decay_threshold: 3,
            monitor_k: 3,
            use_detection_gate: false,
        }
    }
}

impl PipelineConfig {
    /// Validates all configuration fields are within safe bounds.
    ///
    /// Rejects NaN, out-of-range floats, zero-valued integer parameters,
    /// and the empty memory edge case. `validate()` is called by
    /// `CognitivePipeline::with_config()` before construction.
    ///
    /// # Errors
    ///
    /// Returns `"drift_threshold must be in [0.0, 1.0]"` if out of range or NaN.
    /// Returns `"min_confidence must be in [0.0, 1.0]"` if out of range or NaN.
    /// Returns `"monitor_k must be in [1, 5]"` if out of range.
    /// Returns `"max_repetitions must be > 0"` if zero.
    /// Returns `"decay_threshold must be > 0"` if zero.
    /// Propagates PID config validation errors.
    pub fn validate(&self) -> Result<(), &'static str> {
        if self.drift_threshold.is_nan() || self.drift_threshold < 0.0 || self.drift_threshold > 1.0
        {
            return Err("drift_threshold must be in [0.0, 1.0]");
        }
        if self.min_confidence.is_nan() || self.min_confidence < 0.0 || self.min_confidence > 1.0 {
            return Err("min_confidence must be in [0.0, 1.0]");
        }
        if self.monitor_k < 1 || self.monitor_k > 5 {
            return Err("monitor_k must be in [1, 5]");
        }
        if self.max_repetitions == 0 {
            return Err("max_repetitions must be > 0");
        }
        if self.decay_threshold == 0 {
            return Err("decay_threshold must be > 0");
        }
        self.pid_config.validate()?;
        Ok(())
    }
}

/// Snapshot of working-memory statistics.
///
/// All fields are computed from the ring-buffer state at call time.
/// `is_drifting` compares `trend` against a fixed threshold of 10.0.
///
/// Fields:
/// - `mean: f64` — running mean entropy of the ring buffer [0, 65535].
/// - `variance: f64` — running variance of ring-buffer entropy.
/// - `trend: f64` — linear regression slope over the buffer window.
/// - `is_drifting: bool` — true when `|trend| > 10.0`.
pub struct MemoryStats {
    /// Running mean entropy of the ring buffer `[0, 65535]`.
    pub mean: f64,
    /// Running variance of ring-buffer entropy.
    pub variance: f64,
    /// Linear regression slope over the buffer window.
    pub trend: f64,
    /// `true` when `|trend| > 10.0`.
    pub is_drifting: bool,
}

/// Aggregate output of a single `CognitivePipeline::process()` invocation.
///
/// Carries the final `SafetyDecision`, the classified `Synapse` (with packed
/// detection flags and OOV ratio), a stages-executed bitmask, and diagnostic
/// fields for the C-ABI query functions.
///
/// Fields:
/// - `decision: SafetyDecision` — final safety decision from the pipeline.
/// - `synapse: Synapse` — classified synapse with entropy, surprise, bias, detection flags, OOV ratio.
/// - `stages_executed: u8` — bitmask of stages that executed. `STAGE_SIFT` (0x01) through `STAGE_MONITOR` (0x10).
/// - `detection_flags: u8` — five detection flags packed into 5 bits.
/// - `oov_ratio: u8` — OOV (out-of-vocabulary) ratio. 0=0%, 255=100%.
/// - `entropy: u16` — convenience copy of `synapse.raw_entropy()`. Required by C-ABI query functions.
/// - `surprise: u16` — convenience copy of `synapse.raw_surprise()`. Required by C-ABI query functions.
/// - `monitor_state: StabilityResult` — stability state from the `DynamicStabilityMonitor` after this invocation.
/// - `body_pressure: Option<u8>` — resource body pressure percentage [0, 100] when `process_with_pressure()` was used.
/// - `step_count: usize` — current reasoning step count after this invocation.
/// - `kernel_output: Option<KernelOutput>` — kernel output from the reasoning loop (diagnostic).
/// - `classifier_score: f32` — raw classifier logit (`ClassificationResult.score`) before sigmoid.
pub struct PipelineResult {
    /// Final safety decision from the pipeline.
    pub decision: SafetyDecision,
    /// Classified synapse with entropy, surprise, bias, detection flags, OOV ratio.
    pub synapse: Synapse,
    /// Bitmask of stages that executed. `STAGE_SIFT` (0x01) through `STAGE_MONITOR` (0x10).
    pub stages_executed: u8,
    /// Five detection flags packed into 5 bits.
    pub detection_flags: u8,
    /// OOV (out-of-vocabulary) ratio. 0=0%, 255=100%.
    pub oov_ratio: u8,
    /// Convenience copy of `synapse.raw_entropy()`. Required by C-ABI query functions.
    pub entropy: u16,
    /// Convenience copy of `synapse.raw_surprise()`. Required by C-ABI query functions.
    pub surprise: u16,
    /// Stability state from the `DynamicStabilityMonitor` after this invocation.
    pub monitor_state: StabilityResult,
    /// Resource body pressure percentage [0, 100] when `process_with_pressure()` was used.
    #[cfg(feature = "std")]
    pub body_pressure: Option<u8>,
    /// Current reasoning step count after this invocation.
    pub step_count: usize,
    /// Kernel output from the reasoning loop (diagnostic).
    pub kernel_output: Option<KernelOutput>,
    /// Raw classifier logit (`ClassificationResult.score`) before sigmoid.
    /// Unbounded f32 — negative = safe, positive = manipulation signal.
    /// Set to 0.0 in error-path results where no classification was performed.
    pub classifier_score: f32,
}

impl PipelineResult {
    /// Returns `true` when the pipeline decision allows processing to continue.
    pub fn is_safe(&self) -> bool {
        matches!(self.decision, SafetyDecision::Proceed)
    }

    /// Returns `Some(KernelError)` if the result is a `Halt` or `Exit` decision.
    pub fn halt_reason(&self) -> Option<&KernelError> {
        match &self.decision {
            SafetyDecision::Halt(err, _) | SafetyDecision::Exit(err) => Some(err),
            SafetyDecision::Proceed | SafetyDecision::Warn(_) | SafetyDecision::Escalate { .. } => {
                None
            }
        }
    }

    /// Returns a reference to the kernel output if the reasoning loop ran.
    ///
    /// `None` when the pipeline halted before the kernel stage completed
    /// (SIFT or MEMORY short-circuit, or kernel error).  The kernel output
    /// carries the normalised entropy error `[0.0, 1.0]`, a stability
    /// boolean, and the reasoning step depth at output time.
    pub fn kernel_output(&self) -> Option<&KernelOutput> {
        self.kernel_output.as_ref()
    }

    /// Returns the resource body pressure percentage [0, 100].
    ///
    /// Returns 0 when `process()` was used instead of `process_with_pressure()`
    /// (no resource data available).  Pressure is the RSS memory percentage of
    /// the configured ceiling fed through `process_with_pressure()`.
    #[cfg(feature = "std")]
    pub fn body_pressure(&self) -> u8 {
        self.body_pressure.unwrap_or(0)
    }
}

/// Five-stage cognitive safety pipeline.
///
/// Owns one instance of each safety component and orchestrates them through
/// sequential stages: SIFT → MEMORY → KERNEL → DETECTION → MONITOR.
/// Each stage can short-circuit the pipeline with a `Halt` or `Escalate` decision.
///
/// # Type parameters
///
/// * `MEM_SIZE` — ring-buffer capacity for `WorkingMemory` (default: 64).
/// * `MAX_STEPS` — maximum reasoning steps before `DepthExceeded` (default: 10).
///
/// # Lifetime
///
/// * `'a` — the objective string is borrowed; the caller must keep it alive.
///
/// Fields:
/// - `memory: WorkingMemory<MEM_SIZE>` — surprise-gated ring buffer for entropy history.
/// - `reasoning: ReasoningLoop<MAX_STEPS>` — deterministic reasoning step counter.
/// - `monitor: DynamicStabilityMonitor` — self-calibrating envelope tracker.
/// - `repetition: RepetitionDetector` — loop detection (stuck agent).
/// - `drift: DriftDetector` — goal drift detection.
/// - `confidence: ConfidenceTracker` — confidence decay tracking.
/// - `cusum: CusumDetector` — CUSUM anomaly detection.
/// - `adversarial: AdversarialDetector` — adversarial pattern recognition.
/// - `objective: &'a str` — original objective string for drift detection.
/// - `step_count: usize` — current reasoning step count.
/// - `pid_state: PidState` — PID controller state (dual-rate integrators).
/// - `pid_config: PidConfig` — PID controller configuration.
/// - `esc_policy: EscalationPolicy` — escalation policy thresholds.
/// - `use_detection_gate: bool` — when true, routes through detection-gate path.
/// - `drift_threshold: f32` — drift threshold [0.0, 1.0].
/// - `surprise_threshold: i128` — surprise threshold for WorkingMemory.
pub struct CognitivePipeline<'a, const MEM_SIZE: usize, const MAX_STEPS: usize> {
    memory: WorkingMemory<MEM_SIZE>,
    reasoning: ReasoningLoop<MAX_STEPS>,
    monitor: DynamicStabilityMonitor,
    repetition: RepetitionDetector,
    drift: DriftDetector,
    confidence: ConfidenceTracker,
    cusum: CusumDetector,
    adversarial: AdversarialDetector,
    objective: &'a str,
    step_count: usize,
    pid_state: PidState,
    pid_config: PidConfig,
    pub(crate) esc_policy: EscalationPolicy,
    /// When true, routes decisions through the detection-gate path instead of PID.
    pub(crate) use_detection_gate: bool,
    /// Drift threshold [0.0, 1.0]. Stored for `reset_detectors()` and `reset_full()`.
    drift_threshold: f32,
    /// Surprise threshold for `WorkingMemory` reconstruction in `reset_full()`.
    surprise_threshold: i128,
}

impl<'a, const MEM_SIZE: usize, const MAX_STEPS: usize> CognitivePipeline<'a, MEM_SIZE, MAX_STEPS> {
    /// Creates a pipeline with the given objective and default configuration.
    ///
    /// The objective string is borrowed — it must outlive the pipeline.
    /// Drift detection is initialized with the objective's keyword hashes.
    pub fn new(objective: &'a str) -> Self {
        let config = PipelineConfig::default();
        Self::with_config(objective, config).unwrap_or_else(|_| unreachable!())
    }

    /// Creates a pipeline with a custom `PipelineConfig`.
    ///
    /// Returns `Err` if `config.validate()` fails (NaN, out-of-range, zero
    /// thresholds). All detector instances are constructed from config fields.
    ///
    /// # Errors
    ///
    /// Propagates the same error strings from `PipelineConfig::validate()`.
    pub fn with_config(objective: &'a str, config: PipelineConfig) -> Result<Self, &'static str> {
        config.validate()?;
        Ok(Self {
            memory: WorkingMemory::<MEM_SIZE>::new(config.surprise_threshold),
            reasoning: ReasoningLoop::<MAX_STEPS>::new(),
            monitor: DynamicStabilityMonitor::new(config.monitor_k),
            repetition: RepetitionDetector::new(config.max_repetitions),
            drift: DriftDetector::new(objective, config.drift_threshold),
            confidence: ConfidenceTracker::new(config.min_confidence, config.decay_threshold),
            cusum: CusumDetector::new(0.0, 50.0, 200.0),
            adversarial: AdversarialDetector::new(),
            objective,
            step_count: 0,
            pid_state: PidState::new(),
            pid_config: config.pid_config,
            esc_policy: config.policy,
            use_detection_gate: config.use_detection_gate,
            drift_threshold: config.drift_threshold,
            surprise_threshold: config.surprise_threshold,
        })
    }

    /// Processes an observation through the full 5-stage pipeline.
    ///
    /// # Stages
    ///
    /// 1. **SIFT** — Classifies text via TF-IDF classifier. Builds a `SiftedSynapse`.
    ///    Gate: `EscalationPolicy::decide(entropy, surprise, has_bias)`.
    /// 2. **MEMORY** — Pushes synapse into working-memory ring buffer.
    ///    Gate: `EscalationPolicy::decide_from_stability(stability)`.
    /// 3. **KERNEL** — Advances the reasoning loop. Checked for depth and bias.
    /// 4. **DETECTION** — Runs all 5 detectors. Packs flags into synapse reserved bits.
    ///    Gate: `EscalationPolicy::decide_from_detection()` (std) or inline checks (no_std).
    /// 5. **MONITOR** — Updates the `DynamicStabilityMonitor`. Advisory only.
    ///
    /// # Returns
    ///
    /// A `PipelineResult` with the final decision, classified synapse, and diagnostics.
    pub fn process(&mut self, observation: &str) -> PipelineResult {
        self.process_ctrl(observation, 0.0, 0)
    }

    /// Processes an observation with resource body pressure gating.
    ///
    /// Before the SIFT stage, `body_entropy` and `pressure` (0–100) are mapped
    /// to a `PressureLevel` via `EscalationPolicy` thresholds and gated via
    /// `decide_with_pressure()`. If pressure is `Critical` or `Emergency`, the
    /// pipeline returns an `Escalate` or `Halt` decision before running SIFT.
    ///
    /// `body_entropy` is in `[0, 1000]` (RSS + IO + load weighted score).
    /// `pressure` is a percentage `[0, 100]` of RSS memory ceiling.
    ///
    /// When PID mode is active, the legacy pressure gate is advisory only —
    /// the pressure value is fed directly into `compute_pid_score()` as the P-term.
    ///
    /// Sets `STAGE_BODY` (0x20) in the result's `stages_executed` bitmask.
    #[cfg(feature = "std")]
    pub fn process_with_pressure(
        &mut self,
        observation: &str,
        body_entropy: u16,
        pressure: u8,
    ) -> PipelineResult {
        use crate::llmosafe_integration::PressureLevel;

        // Pre-SIFT pressure gate: map pressure to PressureLevel.
        // If pressure is Critical or Emergency, short-circuit before SIFT
        // via decide_with_pressure(). This is the documented safety
        // requirement from the pipeline doc comment (line 408-412).
        let pressure_level = PressureLevel::from_percentage(pressure);
        if pressure_level.requires_action() {
            // Without SIFT data, use body_entropy as entropy proxy;
            // surprise=0, has_bias=false (not classified yet).
            let decision =
                self.esc_policy
                    .decide_with_pressure(body_entropy, 0, false, pressure_level);
            let mut synapse = Synapse::new();
            synapse.set_raw_entropy(body_entropy);
            return PipelineResult {
                decision,
                synapse,
                stages_executed: STAGE_BODY,
                detection_flags: 0,
                oov_ratio: 0,
                entropy: body_entropy,
                surprise: 0,
                monitor_state: crate::llmosafe_kernel::StabilityResult::Stable,
                #[cfg(feature = "std")]
                body_pressure: Some(pressure),
                step_count: self.step_count,
                kernel_output: None,
                classifier_score: 0.0,
            };
        }

        // Route body pressure through BodyOutput → PidInput.e_body
        let e_body = (f32::from(body_entropy) / 1000.0_f32).clamp(0.0, 1.0);
        let mut result = self.process_ctrl(observation, e_body, pressure);
        result.stages_executed |= STAGE_BODY;
        result.body_pressure = Some(pressure);
        result
    }

    /// Pre-flight resource gate on the cognitive pipeline.
    ///
    /// Calls `ResourceGuard::check_with_deadline()` with a 5-second deadline
    /// before processing. If resources are safe (guard returns `Ok`), the full
    /// pipeline runs via `process()`. If the deadline is exceeded (guard returns
    /// `DeadlineExceeded`), the pipeline still runs but via
    /// `process_with_pressure()` — passing the guard's `raw_entropy()` and
    /// `pressure()` values so resource body state is recorded in the result.
    /// All other guard errors are returned without running the pipeline.
    ///
    /// # Errors
    ///
    /// Propagates `KernelError` from `ResourceGuard::check_with_deadline()` for
    /// all errors except `DeadlineExceeded`, which is handled gracefully.
    #[cfg(feature = "std")]
    pub fn process_safe(
        &mut self,
        text: &str,
        guard: &ResourceGuard,
    ) -> Result<PipelineResult, KernelError> {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        match guard.check_with_deadline(deadline) {
            Ok(_synapse) => Ok(self.process(text)),
            Err(KernelError::DeadlineExceeded) => {
                Ok(self.process_with_pressure(text, guard.raw_entropy(), guard.pressure()))
            }
            Err(e) => Err(e),
        }
    }

    /// Resets all 6 detectors and the `DynamicStabilityMonitor`.
    ///
    /// Preserves `WorkingMemory` ring-buffer state and `ReasoningLoop` step count.
    /// Use `reset_full()` for a complete reset.
    pub fn reset_detectors(&mut self) {
        self.repetition.reset();
        self.confidence.reset();
        self.cusum.reset();
        self.adversarial = AdversarialDetector::new();
        self.monitor.reset();
        self.drift = DriftDetector::new(self.objective, self.drift_threshold);
    }

    /// Full reset to post-construction state.
    ///
    /// Clears detectors, monitor, memory ring buffer (all entropy entries zeroed),
    /// reasoning step count, and PID integrators. Objective string is preserved.
    pub fn reset_full(&mut self) {
        self.memory = WorkingMemory::<MEM_SIZE>::new(self.surprise_threshold);
        self.reasoning = ReasoningLoop::<MAX_STEPS>::new();
        self.monitor.reset();
        self.repetition.reset();
        self.drift = DriftDetector::new(self.objective, self.drift_threshold);
        self.confidence.reset();
        self.cusum.reset();
        self.adversarial = AdversarialDetector::new();
        self.step_count = 0;
        self.pid_state.reset();
    }

    /// Returns a reference to the PID state.
    ///
    /// `PidState` holds the dual-rate leaky integrators (`acute_entropy`,
    /// `chronic_entropy`) and `prev_pressure_norm` for step-change detection.
    /// All fields are `f32` clamped to `[0, 1]`. The state mutates across
    /// `process()` calls; this getter returns the live state for introspection.
    pub fn pid_state(&self) -> &PidState {
        &self.pid_state
    }

    /// Returns a snapshot of working-memory statistics.
    ///
    /// `is_drifting` uses a fixed threshold of 10.0 — positive values
    /// indicate rising entropy, negative values indicate falling entropy.
    pub fn memory_stats(&self) -> MemoryStats {
        let mean = self.memory.mean_entropy();
        let variance = self.memory.entropy_variance();
        let trend = self.memory.trend();
        MemoryStats {
            mean,
            variance,
            trend,
            is_drifting: self.memory.is_drifting(10.0),
        }
    }

    // ── Control Theory Composition Path ────────────────────────────

    /// Processes an observation through the full cascade control pipeline.
    ///
    /// Uses the control theory architecture with typed output structs,
    /// pure PID computation, and safety overrides (infusion pump pattern).
    ///
    /// # Control Flow
    ///
    /// ```text
    /// SifterOutput → MemoryOutput → KernelOutput → Detection → PidInput →
    ///   compute_pid_score_pure → apply_safety_overrides → pid_risk_to_decision
    /// ```
    ///
    /// # DAL A
    ///
    /// Safety overrides (bias, exhaustion, kernel instability) are applied
    /// AFTER pure PID computation, preventing PID bugs from bypassing safety.
    ///
    /// # MC/DC
    ///
    /// Each control signal independently affects its PID term.
    /// Each override flag independently forces Halt.
    ///
    /// Control-theory composition path (cascade control).
    /// PID is now mandatory — see `pid_config` field.
    /// `e_body` is the normalised body pressure error [0.0, 1.0] from BodyOutput.
    /// `pressure` is the resource pressure percentage [0, 100], passed for diagnostics.
    pub fn process_ctrl(&mut self, observation: &str, e_body: f32, pressure: u8) -> PipelineResult {
        let mut stages = 0u8;

        // ── Stage 1: SIFT (Tier 3) ──
        // Single canonical entry point. Keyword-bias (innate layer) OR-s into
        // the classifier result. One synapse, one proof, no duplicate compute.
        stages |= STAGE_SIFT;
        let (sifted, sifted_proof, classifier_score) =
            crate::llmosafe_sifter::sift_text_with_score(observation);
        let entropy = sifted.raw_entropy();
        let surprise_val = sifted.raw_surprise();
        let oov_ratio = sifted.oov_ratio();
        let has_bias = sifted.has_bias();

        // ── Stage 2: MEMORY (Tier 2) ──
        stages |= STAGE_MEMORY;
        let mem_result = self.memory.update(sifted, sifted_proof);
        let validated = match mem_result {
            Ok((v, _p)) => v,
            Err(err) => {
                return self.ctrl_result_from_error(err, stages, oov_ratio, entropy, surprise_val);
            }
        };

        // ── Stage 3: KERNEL (Tier 1) ──
        stages |= STAGE_KERNEL;
        let kernel_synapse = validated.into_inner();
        let kernel_entropy = kernel_synapse.raw_entropy();
        let kernel_validated = ValidatedSynapse::new(kernel_synapse);
        let kernel_result = self
            .reasoning
            .next_step(kernel_validated, crate::llmosafe_kernel::ValidatedProof(()));
        let kernel_synapse_out = match kernel_result {
            Ok(()) => {
                self.step_count += 1;
                validated.into_inner()
            }
            Err(err) => {
                return self.ctrl_result_from_kernel_error(
                    err,
                    stages,
                    oov_ratio,
                    entropy,
                    surprise_val,
                );
            }
        };

        // ── Stage 4: DETECTION (Sidechain) ──
        stages |= STAGE_DETECTION;
        self.repetition.observe(observation);
        self.drift.observe(observation);
        let classifier_prob = f32::from(entropy) / 65535.0_f32;
        self.confidence.observe(classifier_prob);
        let _cusum_anomaly = self.cusum.update(f64::from(entropy));

        let is_stuck = self.repetition.is_stuck();
        let is_drifting = self.drift.is_drifting();
        let is_low_confidence = self.confidence.is_low();
        let is_decaying = self.confidence.is_decaying();
        let anomaly_detected = self.cusum.detected();
        let adversarial_detected = self.adversarial.is_adversarial(observation);

        let mut flags: u8 = 0;
        if is_stuck {
            flags |= FLAG_STUCK;
        }
        if is_drifting {
            flags |= FLAG_DRIFTING;
        }
        if is_low_confidence {
            flags |= FLAG_LOW_CONFIDENCE;
        }
        if is_decaying {
            flags |= FLAG_DECAYING;
        }
        if anomaly_detected {
            flags |= FLAG_ANOMALY;
        }
        if adversarial_detected {
            flags |= FLAG_ADVERSARIAL;
        }

        // ── Stage 5a: DETECTION GATE (optional, non-PID path) ──
        // First-match-wins severity ordering: Anomaly > Adversarial > Drifting > Stuck > Confidence.
        // Avoids PID integrator state entirely. If the gate produces a Halt, return early;
        // otherwise fall through to the PID composition below.
        #[cfg(feature = "std")]
        if self.use_detection_gate {
            let detection_result = DetectionResult {
                is_stuck,
                is_drifting,
                is_low_confidence,
                is_decaying,
                adversarial_patterns: if adversarial_detected {
                    vec!["adversarial"]
                } else {
                    vec![]
                },
                risk_score: if anomaly_detected { 0.9 } else { 0.0 },
            };
            let gate_decision =
                self.esc_policy
                    .decide_from_detection(&detection_result, entropy, surprise_val);
            if gate_decision.must_halt() {
                stages |= STAGE_MONITOR;
                let monitor_state = self.monitor.update(u32::from(entropy));
                let kernel_output = Some(KernelOutput {
                    error_kernel: f32::from(kernel_entropy) / 65535.0_f32,
                    is_stable: u32::from(kernel_entropy)
                        < crate::llmosafe_kernel::STABILITY_THRESHOLD as u32,
                    depth: self.step_count,
                });
                return PipelineResult {
                    decision: gate_decision,
                    synapse: kernel_synapse_out,
                    stages_executed: stages,
                    detection_flags: flags,
                    oov_ratio,
                    entropy,
                    surprise: surprise_val,
                    monitor_state,
                    #[cfg(feature = "std")]
                    body_pressure: Some(pressure),
                    step_count: self.step_count,
                    kernel_output,
                    classifier_score,
                };
            }
        }

        // ── Stage 5: PID COMPOSITION ──
        let pressure_term = (e_body * 100.0_f32) as u8;
        let trend = self.memory.trend();

        // Compute tier error signals for the 4-tier PID cascade.
        // e_mem: memory surprise = |current_entropy − mean_entropy| / 65535
        // e_kernel: kernel stability error = kernel_entropy / 65535
        // Both clamped to [0.0, 1.0].
        let mem_mean = self.memory.mean_entropy();
        let e_mem = ((f64::from(entropy) - mem_mean).abs() as f32 / 65535.0_f32).clamp(0.0, 1.0);
        let e_kernel = (f32::from(kernel_entropy) / 65535.0_f32).clamp(0.0, 1.0);

        let pid_input = crate::control_types::PidInput::new(
            e_body,
            f32::from(entropy) / 65535.0_f32,
            e_mem,
            e_kernel,
            trend,
            classifier_prob,
            has_bias,
            flags,
            pressure_term,
        );
        let pure_risk = crate::llmosafe_pid::compute_pid_score_pure(
            &pid_input,
            &self.pid_config,
            &mut self.pid_state,
        );

        // ── Stage 5bis: MONITOR (before overrides — gates KERNEL_UNSTABLE) ──
        stages |= STAGE_MONITOR;
        let monitor_state = self.monitor.update(u32::from(kernel_entropy));

        let mut override_flags = OverrideFlags::empty();
        if has_bias {
            override_flags = override_flags | OverrideFlags::BIAS;
        }
        if e_body > 0.9 {
            override_flags = override_flags | OverrideFlags::EXHAUSTED;
        }
        // KERNEL_UNSTABLE: set when the dynamic stability monitor detects
        // High, Low, or Both — any non-Stable state triggers the safety gate.
        if monitor_state != crate::llmosafe_kernel::StabilityResult::Stable {
            override_flags = override_flags | OverrideFlags::KERNEL_UNSTABLE;
        }
        let limited_risk = crate::llmosafe_pid::apply_safety_overrides(
            pure_risk,
            override_flags,
            &self.pid_config,
        );
        let decision = crate::llmosafe_pid::pid_risk_to_decision(limited_risk, &self.pid_config);

        let kernel_output = Some(KernelOutput {
            error_kernel: f32::from(kernel_entropy) / 65535.0_f32,
            is_stable: u32::from(kernel_entropy)
                < crate::llmosafe_kernel::STABILITY_THRESHOLD as u32,
            depth: self.step_count,
        });

        PipelineResult {
            decision,
            synapse: kernel_synapse_out,
            stages_executed: stages,
            detection_flags: flags,
            oov_ratio,
            entropy,
            surprise: surprise_val,
            monitor_state,
            #[cfg(feature = "std")]
            body_pressure: Some(pressure),
            step_count: self.step_count,
            kernel_output,
            classifier_score,
        }
    }

    /// Constructs a `PipelineResult` from a `WorkingMemory` error (`KernelError`).
    ///
    /// Maps `HallucinationDetected` → `Escalate` (5000ms cooldown),
    /// `CognitiveInstability` → `Halt` (30000ms),
    /// `BiasHaloDetected` → `Halt` (30000ms),
    /// all other errors → `Halt(error, 30000ms)`.
    /// Constructs a fresh `Synapse` with entropy populated, detection_flags=0,
    /// monitor_state=Stable, kernel_output=None.
    fn ctrl_result_from_error(
        &self,
        err: KernelError,
        stages: u8,
        oov_ratio: u8,
        entropy: u16,
        surprise_val: u16,
    ) -> PipelineResult {
        let (decision, synapse) = match err {
            KernelError::HallucinationDetected => {
                let mut s = Synapse::new();
                s.set_raw_entropy(entropy);
                (
                    SafetyDecision::Escalate {
                        entropy,
                        reason: crate::llmosafe_integration::EscalationReason::Custom(
                            "hallucination",
                        ),
                        cooldown_ms: 5000,
                    },
                    s,
                )
            }
            KernelError::CognitiveInstability => {
                let mut s = Synapse::new();
                s.set_raw_entropy(entropy);
                (
                    SafetyDecision::Halt(KernelError::CognitiveInstability, 30000),
                    s,
                )
            }
            KernelError::BiasHaloDetected => {
                let mut s = Synapse::new();
                s.set_raw_entropy(entropy);
                (
                    SafetyDecision::Halt(KernelError::BiasHaloDetected, 30000),
                    s,
                )
            }
            KernelError::DepthExceeded
            | KernelError::ResourceExhaustion
            | KernelError::SelfMemoryExceeded
            | KernelError::DeadlineExceeded => {
                let mut s = Synapse::new();
                s.set_raw_entropy(entropy);
                (SafetyDecision::Halt(err, 30000), s)
            }
        };
        PipelineResult {
            decision,
            synapse,
            stages_executed: stages,
            detection_flags: 0,
            oov_ratio,
            entropy,
            surprise: surprise_val,
            monitor_state: StabilityResult::Stable,
            #[cfg(feature = "std")]
            body_pressure: None,
            step_count: self.step_count,
            kernel_output: None,
            classifier_score: 0.0,
        }
    }

    /// Constructs a `PipelineResult` from a `ReasoningLoop` error (`KernelError`).
    ///
    /// Maps `DepthExceeded` → `Escalate` (10000ms cooldown),
    /// `BiasHaloDetected` → `Halt` (30000ms),
    /// `CognitiveInstability` → `Halt` (30000ms),
    /// all other errors → `Halt(error, 30000ms)`.
    /// Constructs a fresh `Synapse` with entropy populated, detection_flags=0,
    /// monitor_state=Stable, kernel_output=None.
    fn ctrl_result_from_kernel_error(
        &self,
        err: KernelError,
        stages: u8,
        oov_ratio: u8,
        entropy: u16,
        surprise_val: u16,
    ) -> PipelineResult {
        let decision = match err {
            KernelError::DepthExceeded => SafetyDecision::Escalate {
                entropy,
                reason: crate::llmosafe_integration::EscalationReason::Custom(
                    "reasoning depth exceeded",
                ),
                cooldown_ms: 10000,
            },
            KernelError::BiasHaloDetected => {
                SafetyDecision::Halt(KernelError::BiasHaloDetected, 30000)
            }
            KernelError::CognitiveInstability => {
                SafetyDecision::Halt(KernelError::CognitiveInstability, 30000)
            }
            KernelError::HallucinationDetected
            | KernelError::ResourceExhaustion
            | KernelError::SelfMemoryExceeded
            | KernelError::DeadlineExceeded => SafetyDecision::Halt(err, 30000),
        };
        let mut err_synapse = Synapse::new();
        err_synapse.set_raw_entropy(entropy);
        PipelineResult {
            decision,
            synapse: err_synapse,
            stages_executed: stages,
            detection_flags: 0,
            oov_ratio,
            entropy,
            surprise: surprise_val,
            monitor_state: StabilityResult::Stable,
            #[cfg(feature = "std")]
            body_pressure: None,
            step_count: self.step_count,
            kernel_output: None,
            classifier_score: 0.0,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::llmosafe_kernel::DETECTION_FLAGS_MASK;

    #[test]
    fn test_pipelineconfig_default_validates() {
        let config = PipelineConfig::default();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_pipelineconfig_validate_rejects_nan_drift_threshold() {
        let config = PipelineConfig {
            drift_threshold: f32::NAN,
            ..PipelineConfig::default()
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_pipelineconfig_validate_rejects_out_of_range_confidence() {
        let config = PipelineConfig {
            min_confidence: 2.0,
            ..PipelineConfig::default()
        };
        assert!(config.validate().is_err());

        let config = PipelineConfig {
            min_confidence: -0.1,
            ..PipelineConfig::default()
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_pipelineconfig_validate_rejects_zero_monitor_k() {
        let config = PipelineConfig {
            monitor_k: 0,
            ..PipelineConfig::default()
        };
        assert!(config.validate().is_err());
        let config = PipelineConfig {
            monitor_k: 6,
            ..PipelineConfig::default()
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_pipelineconfig_validate_rejects_zero_max_repetitions() {
        let config = PipelineConfig {
            max_repetitions: 0,
            ..PipelineConfig::default()
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_pipelineconfig_validate_rejects_zero_decay_threshold() {
        let config = PipelineConfig {
            decay_threshold: 0,
            ..PipelineConfig::default()
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_pipelineresult_is_safe() {
        let mut synapse = Synapse::new();
        synapse.set_raw_entropy(100);
        let result = PipelineResult {
            decision: SafetyDecision::Proceed,
            synapse,
            stages_executed: STAGE_SIFT | STAGE_MEMORY,
            detection_flags: 0,
            oov_ratio: 0,
            entropy: 100,
            surprise: 0,
            monitor_state: StabilityResult::Stable,
            #[cfg(feature = "std")]
            body_pressure: None,
            step_count: 1,
            kernel_output: None,
            classifier_score: 0.0,
        };
        assert!(result.is_safe());
        assert!(result.halt_reason().is_none());
    }

    #[test]
    fn test_pipelineresult_halt_reason() {
        let synapse = Synapse::new();
        let result = PipelineResult {
            decision: SafetyDecision::Halt(KernelError::CognitiveInstability, 30000),
            synapse,
            stages_executed: STAGE_SIFT,
            detection_flags: 0,
            oov_ratio: 0,
            entropy: 51000,
            surprise: 0,
            monitor_state: StabilityResult::Stable,
            #[cfg(feature = "std")]
            body_pressure: None,
            step_count: 0,
            kernel_output: None,
            classifier_score: 0.0,
        };
        assert!(!result.is_safe());
        assert_eq!(
            *result.halt_reason().unwrap(),
            KernelError::CognitiveInstability
        );
    }

    #[test]
    fn test_cognitive_pipeline_new_creates_with_defaults() {
        let pipeline = CognitivePipeline::<64, 10>::new("test objective");
        assert_eq!(pipeline.objective, "test objective");
        assert_eq!(pipeline.step_count, 0);
    }

    #[test]
    fn test_cognitive_pipeline_with_config_validates() {
        let config = PipelineConfig::default();
        let pipeline = CognitivePipeline::<64, 10>::with_config("test", config);
        assert!(pipeline.is_ok());
    }

    #[test]
    fn test_cognitive_pipeline_with_config_rejects_invalid() {
        let config = PipelineConfig {
            drift_threshold: f32::NAN,
            ..PipelineConfig::default()
        };
        let pipeline = CognitivePipeline::<64, 10>::with_config("test", config);
        assert!(pipeline.is_err());
    }

    #[test]
    fn test_process_safe_text_returns_proceed() {
        let mut pipeline = CognitivePipeline::<64, 10>::new("test objective");
        let result = pipeline.process("a completely ordinary sentence about everyday topics");
        // Safe text should produce a valid PipelineResult regardless of classifier.
        let _entropy: u16 = result.entropy; // always in [0, 65535] by type
        let _surprise: u16 = result.surprise;
        assert!(result.decision.severity() <= 4);
    }

    #[test]
    fn test_process_returns_pipeline_result_with_synapse() {
        let mut pipeline = CognitivePipeline::<64, 10>::new("test");
        let result = pipeline.process("checking some input text here");
        assert!(result.stages_executed & STAGE_SIFT != 0);
        // entropy is u16 — always in [0, 65535] by type
        let _ = result.entropy;
        let _ = result.surprise;
        assert!(result.detection_flags <= DETECTION_FLAGS_MASK);
    }

    #[test]
    fn test_reset_detectors_preserves_step_count() {
        let mut pipeline = CognitivePipeline::<64, 10>::new("test");
        let _ = pipeline.process("step one");
        let _ = pipeline.process("step two");
        let before = pipeline.step_count;
        pipeline.reset_detectors();
        assert_eq!(pipeline.step_count, before);
    }

    #[test]
    fn test_reset_full_clears_everything() {
        let mut pipeline = CognitivePipeline::<64, 10>::new("test");
        let _ = pipeline.process("this is a normal observation about weather");
        let _ = pipeline.process("another normal sentence for testing");
        pipeline.reset_full();
        assert_eq!(pipeline.step_count, 0);
        let result = pipeline.process("completely normal text after reset");
        // After reset_full + one process, step_count may be 0 or 1 depending
        // on classifier output — verify the pipeline returned a valid result.
        assert!(result.stages_executed & STAGE_SIFT != 0);
    }

    #[test]
    fn test_detection_flags_bitmask_uniqueness() {
        // Verify no overlapping bits
        assert_ne!(FLAG_STUCK, 0);
        assert_ne!(FLAG_DRIFTING, 0);
        assert_ne!(FLAG_LOW_CONFIDENCE, 0);
        assert_ne!(FLAG_DECAYING, 0);
        assert_ne!(FLAG_ANOMALY, 0);
        assert_ne!(FLAG_ADVERSARIAL, 0);
        let combined = FLAG_STUCK
            | FLAG_DRIFTING
            | FLAG_LOW_CONFIDENCE
            | FLAG_DECAYING
            | FLAG_ANOMALY
            | FLAG_ADVERSARIAL;
        assert_eq!(combined, DETECTION_FLAGS_MASK);
    }

    #[test]
    fn test_synapse_detection_flags_roundtrip() {
        let mut synapse = Synapse::new();
        synapse.set_detection_flags(FLAG_STUCK | FLAG_ANOMALY);
        assert_eq!(synapse.detection_flags(), FLAG_STUCK | FLAG_ANOMALY);

        synapse.set_detection_flags(0);
        assert_eq!(synapse.detection_flags(), 0);

        synapse.set_detection_flags(DETECTION_FLAGS_MASK);
        assert_eq!(synapse.detection_flags(), DETECTION_FLAGS_MASK);
    }

    #[test]
    fn test_synapse_oov_ratio_roundtrip() {
        let mut synapse = Synapse::new();
        synapse.set_oov_ratio(128);
        assert_eq!(synapse.oov_ratio(), 128);
        synapse.set_oov_ratio(0);
        assert_eq!(synapse.oov_ratio(), 0);
        synapse.set_oov_ratio(255);
        assert_eq!(synapse.oov_ratio(), 255);
    }

    #[test]
    fn test_synapse_clear_detection() {
        let mut synapse = Synapse::new();
        synapse.set_detection_flags(FLAG_STUCK | FLAG_DRIFTING);
        synapse.set_oov_ratio(200);
        synapse.clear_detection();
        assert_eq!(synapse.detection_flags(), 0);
        assert_eq!(synapse.oov_ratio(), 0);
    }

    #[test]
    fn test_synapse_detection_independent_from_entropy() {
        let mut synapse = Synapse::new();
        synapse.set_raw_entropy(12345);
        synapse.set_detection_flags(FLAG_ANOMALY);
        assert_eq!(synapse.raw_entropy(), 12345);
        assert_eq!(synapse.detection_flags(), FLAG_ANOMALY);

        // Verify entropy field is unchanged by detection operations
        synapse.set_oov_ratio(100);
        assert_eq!(synapse.raw_entropy(), 12345);
        assert_eq!(synapse.oov_ratio(), 100);
    }

    #[test]
    fn test_synapse_detection_does_not_affect_validate() {
        // Detection flags should not affect synapse validation
        let mut synapse = Synapse::new();
        synapse.set_raw_entropy(500);
        synapse.set_has_bias(false);
        synapse.set_detection_flags(DETECTION_FLAGS_MASK);
        synapse.set_oov_ratio(255);
        assert!(synapse.validate().is_ok());

        // But the underlying reserved field roundtrips through from_raw_u128
        let bits = u128::from_le_bytes(synapse.into_bytes());
        let reconstructed = Synapse::from_raw_u128(bits);
        assert_eq!(reconstructed.detection_flags(), DETECTION_FLAGS_MASK);
        assert_eq!(reconstructed.oov_ratio(), 255);
        assert_eq!(reconstructed.raw_entropy(), 500);
    }

    #[test]
    fn test_process_with_same_text_triggers_stuck() {
        let mut pipeline = CognitivePipeline::<64, 10>::new("test");
        let same = "the outdoor temperature readings indicate mild conditions";
        // Feed the same text multiple times — repetition should accumulate.
        // After enough calls, IF the pipeline reaches detection stage,
        // the stuck flag should be set.
        for _ in 0..5 {
            let result = pipeline.process(same);
            // PipelineResult always has valid bitmasks.
            assert!(result.detection_flags <= DETECTION_FLAGS_MASK);
        }
        // If the classifier blocks at SIFT, no detection occurs — that is
        // correct behavior (fail-fast on dangerous input).
    }

    #[test]
    fn test_process_with_drifting_text() {
        let mut pipeline =
            CognitivePipeline::<64, 10>::new("rust safety library performance analysis");
        // Text completely unrelated to objective should drift
        let result = pipeline.process("pizza recipes with extra cheese toppings");
        assert!(result.detection_flags & FLAG_DRIFTING != 0);
    }

    #[test]
    fn test_process_max_steps() {
        let mut pipeline = CognitivePipeline::<64, 2>::new("test");
        // Process until depth is exceeded — use repeated calls.
        let mut last_step = 0usize;
        for _ in 0..5 {
            let result = pipeline.process("checking safety of different input text");
            last_step = result.step_count;
            if result.step_count >= 2 {
                break;
            }
        }
        // Either we hit depth exceeded or ran out of calls.
        // MAX_STEPS=2 means step_count should cap at 2.
        assert!(last_step <= 2);
    }

    #[cfg(feature = "std")]
    #[test]
    fn test_process_with_pressure_nominal_proceeds() {
        let mut pipeline = CognitivePipeline::<64, 10>::new("test");
        let result = pipeline.process_with_pressure(
            "how do i write a function to sort a list in python",
            100,
            10,
        );
        assert!(result.body_pressure.is_some());
    }

    #[cfg(feature = "std")]
    #[test]
    fn test_process_with_pressure_critical_escalates() {
        let mut pipeline = CognitivePipeline::<64, 10>::new("test");
        let result = pipeline.process_with_pressure(
            "how do i write a function to sort a list in python",
            500,
            60,
        );
        assert!(result.decision.is_blocking());
        assert_eq!(result.body_pressure, Some(60));
    }

    #[cfg(feature = "std")]
    #[test]
    fn test_process_with_pressure_emergency_halt() {
        let mut pipeline = CognitivePipeline::<64, 10>::new("test");
        let result = pipeline.process_with_pressure(
            "how do i write a function to sort a list in python",
            800,
            90,
        );
        assert!(result.decision.is_blocking());
        assert_eq!(result.body_pressure, Some(90));
    }

    // ── Control Theory Composition Tests ──

    #[test]
    fn test_process_ctrl_returns_valid_result() {
        let mut pipeline = CognitivePipeline::<64, 10>::new("test objective");
        let result = pipeline.process_ctrl("a completely ordinary sentence", 0.0, 0);
        assert!(result.stages_executed & STAGE_SIFT != 0);
        assert!(result.decision.severity() <= 4);
        // Control loop path should produce bounded entropy
        assert!(
            result.entropy > 0,
            "entropy must be non-zero for valid input"
        );
    }

    #[test]
    fn test_process_ctrl_memory_output_has_bounded_error() {
        let mut pipeline = CognitivePipeline::<64, 10>::new("test");
        let result = pipeline.process_ctrl("safety test input observation", 0.0, 0);
        assert!(result.stages_executed & STAGE_MEMORY != 0);
        // Detection stage always runs
        assert!(result.detection_flags <= DETECTION_FLAGS_MASK);
    }
}