envseal 0.3.11

Write-only secret vault with process-level access control — post-agent secret management
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
//! Security-signal taxonomy — the organizational backbone for every
//! threat detection in envseal.
//!
//! # The problem this solves
//!
//! Without a uniform signal model, every new heuristic forces three
//! changes in three places:
//!
//! 1. A field on [`super::GuiSecurityReport`] (or some sibling struct).
//! 2. A flag on [`crate::security_config::SecurityConfig`].
//! 3. A new branch in [`crate::gui::request_approval`].
//!
//! That doesn't scale past a few dozen detectors. With 100+
//! heuristics across screen recording, GUI threats, environment
//! injection, binary integrity, sandbox state, network posture, and
//! disk permissions, the approval logic becomes a tangle of
//! one-off `if` statements.
//!
//! # The model
//!
//! - Every detector emits zero or more [`Signal`]s.
//! - Every [`Signal`] is identified by a stable [`SignalId`]
//!   (`category.specific.modifier`, e.g. `gui.input_injector.xdotool`),
//!   carries a [`Category`] and a [`Severity`], and ships with
//!   human-readable label / description / mitigation strings.
//! - The [`Policy`] is a stable mapping from `(severity, security
//!   tier) → ` [`Action`]. The same Hostile signal blocks under
//!   Lockdown but only warns under Standard — that's a policy
//!   choice, not a detector choice.
//! - [`Action`] is what the approval pipeline consumes:
//!   ignore / log / warn (with optional friction) / block.
//!
//! # Adding a new detector
//!
//! 1. Append a new [`Category`] variant if needed (rare).
//! 2. Pick a stable `SignalId` like `disk.master_key.world_readable`.
//! 3. Implement detection in `core/src/guard/detectors/<category>.rs`
//!    (or an existing file), pushing [`Signal`]s into the assessor's
//!    accumulator.
//! 4. Declare the signal's default [`Severity`].
//!
//! That's it. No `request_approval` change, no `SecurityConfig`
//! field, no new branch in the `match` ladders. The policy decides
//! what to do — and the policy is a table, not code.

use crate::security_config::SecurityTier;

/// Stable, machine-readable identifier for a security signal.
///
/// Format: `<source>.<class>.<specific>` — for example
/// `gui.input_injector.xdotool`, `env.preload.ld_audit`,
/// `disk.master_key.world_readable`. Stability is part of the
/// contract: `SignalId`s appear in audit logs and external policy
/// configs, so renaming one is a breaking change.
///
/// Holds a `Cow` so most ids stay zero-allocation static literals
/// while detectors that interpolate a discovered tool/process name
/// (`gui.input_injector.{name}`) can build per-detection ids
/// without forcing every signal to allocate.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SignalId(std::borrow::Cow<'static, str>);

impl SignalId {
    /// Construct a signal id from a `'static` literal — zero-cost.
    #[must_use]
    pub const fn new(id: &'static str) -> Self {
        Self(std::borrow::Cow::Borrowed(id))
    }

    /// Construct a signal id from a fully-qualified runtime string —
    /// used when loading user-authored policy overrides from
    /// `security.toml` where the id is read as a `String` rather
    /// than a literal. The string is taken verbatim; no
    /// sanitization is applied because the user is the trust
    /// boundary for their own config.
    #[must_use]
    pub fn from_runtime_string(id: &str) -> Self {
        Self(std::borrow::Cow::Owned(id.to_string()))
    }

    /// Construct a signal id by interpolating a runtime value into a
    /// taxonomic prefix, e.g. `SignalId::scoped("gui.input_injector",
    /// process_name)`. The id format remains `<prefix>.<scope>` so
    /// audit-log queries continue to work via prefix match.
    #[must_use]
    pub fn scoped(prefix: &'static str, scope: &str) -> Self {
        // Sanitize: scope must only contain `[a-z0-9_-]` so it
        // remains a valid taxonomic suffix and can't smuggle dots
        // (which would break `category.specific.modifier` parsers).
        let mut sanitized = String::with_capacity(scope.len());
        for ch in scope.chars() {
            if ch.is_ascii_alphanumeric() || ch == '_' || ch == '-' {
                sanitized.push(ch.to_ascii_lowercase());
            } else {
                sanitized.push('_');
            }
        }
        Self(std::borrow::Cow::Owned(format!("{prefix}.{sanitized}")))
    }

    /// The string form used in audit logs and external configs.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for SignalId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// What flavor of attack vector a signal represents. Categories are
/// stable: changing one breaks downstream consumers (audit log
/// analytics, external policy files). Adding a new variant is fine.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Category {
    /// A process can synthesize keyboard / mouse events on the same
    /// session (`xdotool`, `ydotool`, `xte`, `wtype`, `AppleScript`
    /// `system events`, Windows `SendInput` automation tools).
    InputInjection,
    /// A process is recording the screen (OBS, ffmpeg + x11grab,
    /// `screencapture`, `Screen Recording` in Privacy & Security).
    ScreenRecording,
    /// Where the user is — local console, SSH session, X11
    /// forwarding, RDP/VNC. Changes whether GUI-only auth is even
    /// reachable.
    GuiPresence,
    /// Hostile dynamic-loader or interpreter env vars (`LD_PRELOAD`,
    /// `LD_AUDIT`, `LD_LIBRARY_PATH`, `DYLD_INSERT_LIBRARIES`,
    /// `PYTHONPATH`, `NODE_OPTIONS`).
    EnvironmentInjection,
    /// The target binary's hash doesn't match the policy entry — it
    /// has been replaced or modified since approval.
    BinaryIntegrity,
    /// A vault file has lax permissions (world-readable
    /// `master.key`, group-writable `policy.toml`, etc.).
    DiskPermissions,
    /// The vault was sealed by a different hardware backend than the
    /// one this device exposes. Cross-machine vault transfer attempt.
    DeviceMismatch,
    /// The append-only audit log could not be written.
    AuditFailure,
    /// The requested sandbox tier is unsupported / not applicable on
    /// this host (e.g. Lockdown on macOS without `sandbox_init`).
    SandboxUnavailable,
    /// Accessibility automation framework that could click approval
    /// buttons (AT-SPI bridge, macOS Accessibility API consumers).
    AccessibilityBridge,
    /// The target binary's *behavior* is risky regardless of integrity:
    /// it's a script interpreter (executes attacker-controlled scripts),
    /// or it lives in a user-writable / world-writable / Downloads-style
    /// directory where any process or social-engineered file drop could
    /// have planted it. Distinct from [`Self::BinaryIntegrity`] (which is
    /// hash-based) — a binary can pass integrity and still be risky.
    BinaryRisk,
    /// I/O context — how this process was launched. Stdin redirected
    /// from an actual pipe (FIFO), stdout going to a file an attacker
    /// can read, etc. Distinct from environment vars
    /// ([`Self::EnvironmentInjection`]) and binary identity
    /// ([`Self::BinaryIntegrity`] / [`Self::BinaryRisk`]).
    IoContext,
    /// The secret being stored fails an entropy check (looks like a
    /// dictionary word, has trivial structure, looks like a known
    /// test/demo placeholder, etc.).
    SecretQuality,
    /// The supervisor that wraps a child process saw the secret
    /// appear in the child's stdout/stderr. Indicates the secret was
    /// exfiltrated past envseal's control surface and had to be
    /// redacted.
    SupervisorLeak,
    /// Catch-all for signals that don't fit a defined category.
    Other,
}

impl Category {
    /// Stable string identifier used in audit logs and external
    /// policy configs.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::InputInjection => "input_injection",
            Self::ScreenRecording => "screen_recording",
            Self::GuiPresence => "gui_presence",
            Self::EnvironmentInjection => "environment_injection",
            Self::BinaryIntegrity => "binary_integrity",
            Self::DiskPermissions => "disk_permissions",
            Self::DeviceMismatch => "device_mismatch",
            Self::AuditFailure => "audit_failure",
            Self::SandboxUnavailable => "sandbox_unavailable",
            Self::AccessibilityBridge => "accessibility_bridge",
            Self::BinaryRisk => "binary_risk",
            Self::IoContext => "io_context",
            Self::SecretQuality => "secret_quality",
            Self::SupervisorLeak => "supervisor_leak",
            Self::Other => "other",
        }
    }
}

/// Severity of a signal — the *intrinsic* threat level, before any
/// policy is applied. `Critical` always blocks; everything else is
/// policy-decided.
///
/// Severities have a total order: `Info < Warn < Degraded < Hostile
/// < Critical`. A policy that blocks `Hostile` implicitly blocks
/// `Critical`; a policy that warns on `Warn` does not warn on `Info`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Severity {
    /// Reportable but never blocks. Always logged at the audit
    /// layer, never surfaces a popup warning.
    Info,
    /// Surfaces a friction-free warning to the user (e.g., "screen
    /// recorder detected"). Approval can proceed.
    Warn,
    /// Tier policy may block. Standard tier proceeds with friction;
    /// Hardened/Lockdown block.
    Degraded,
    /// Strong block signal at Hardened+. Standard tier may still
    /// allow with explicit confirmation.
    Hostile,
    /// Always blocks regardless of tier — there is no scenario where
    /// proceeding is acceptable. Examples: `master.key` is a symlink
    /// pointing outside the vault root, audit log write failed.
    Critical,
}

impl Severity {
    /// Stable string identifier used in audit logs and external
    /// policy configs.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Info => "info",
            Self::Warn => "warn",
            Self::Degraded => "degraded",
            Self::Hostile => "hostile",
            Self::Critical => "critical",
        }
    }
}

/// One detected security signal at a point in time.
///
/// `Signal` is the unit of communication between detectors and the
/// approval pipeline. Detectors push signals; the policy layer
/// decides what to do with them; the approval pipeline acts on the
/// resulting [`Action`]s.
#[derive(Debug, Clone)]
pub struct Signal {
    /// Stable taxonomic id.
    pub id: SignalId,
    /// Category this signal belongs to.
    pub category: Category,
    /// Intrinsic severity (before policy is applied).
    pub severity: Severity,
    /// Short human-readable label for UI surfaces.
    pub label: &'static str,
    /// Per-detection contextual detail (process name, file path,
    /// hash mismatch values). Free-form so each detector can pass
    /// what's relevant.
    pub detail: String,
    /// One-sentence mitigation hint shown alongside the warning.
    pub mitigation: &'static str,
}

impl Signal {
    /// Construct a new signal.
    #[must_use]
    pub fn new(
        id: SignalId,
        category: Category,
        severity: Severity,
        label: &'static str,
        detail: impl Into<String>,
        mitigation: &'static str,
    ) -> Self {
        Self {
            id,
            category,
            severity,
            label,
            detail: detail.into(),
            mitigation,
        }
    }
}

/// What the policy layer decides for one signal under a given tier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    /// Take no action. The signal is not even logged.
    Ignore,
    /// Log the signal to the audit trail. No user-facing surface.
    Log,
    /// Surface as a warning in the approval popup. If `friction` is
    /// `true`, require an additional challenge (e.g. typing a
    /// 4-digit code) before approval can complete.
    Warn {
        /// Whether the user must clear an additional challenge gate
        /// (numeric code) before the approval can proceed.
        friction: bool,
    },
    /// Block the operation outright. Approval cannot succeed; the
    /// caller receives an `Error::EnvironmentCompromised` (or
    /// equivalent) with the signal's `label` and `mitigation`.
    Block,
}

impl Action {
    /// Stable string identifier used in audit logs.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Ignore => "ignore",
            Self::Log => "log",
            Self::Warn { friction: false } => "warn",
            Self::Warn { friction: true } => "warn_with_challenge",
            Self::Block => "block",
        }
    }

    /// True if this action prevents the approval from completing.
    #[must_use]
    pub const fn blocks(&self) -> bool {
        matches!(self, Self::Block)
    }
}

/// The default policy: how each (severity, tier) pair maps to an
/// action.
///
/// The table is small, declarative, and deliberately conservative.
/// It can be overridden at runtime by [`Policy::override_action`]
/// for site-specific tightening (e.g., a corporate deployment that
/// wants `Warn` severity to block under Hardened).
///
/// # Default table
///
/// | Severity / Tier | Standard | Hardened | Lockdown |
/// |---|---|---|---|
/// | `Info`          | log      | log      | log      |
/// | `Warn`          | warn     | warn     | warn(F)  |
/// | `Degraded`      | warn(F)  | block    | block    |
/// | `Hostile`       | warn(F)  | block    | block    |
/// | `Critical`      | block    | block    | block    |
///
/// `warn(F)` = warn with friction (challenge gate).
#[derive(Debug, Clone, Default)]
pub struct Policy {
    /// Per-(severity, tier) overrides. Anything not in this map
    /// uses the default table baked into [`Policy::decide`].
    overrides: std::collections::HashMap<(Severity, SecurityTier), Action>,
    /// Per-signal-id overrides — strongest level of customization.
    /// A site that wants to mute a specific noisy detector (e.g.,
    /// `accessibility_bridge.at_spi_only`) does it here.
    per_signal: std::collections::HashMap<SignalId, Action>,
}

impl Policy {
    /// Construct an empty policy that uses defaults for every
    /// `(severity, tier)` pair.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Override the default action for one severity at one tier.
    pub fn override_action(&mut self, severity: Severity, tier: SecurityTier, action: Action) {
        self.overrides.insert((severity, tier), action);
    }

    /// Override the action for one specific signal id, regardless
    /// of tier or severity. Highest-priority override.
    pub fn override_signal(&mut self, id: SignalId, action: Action) {
        self.per_signal.insert(id, action);
    }

    /// Decide what to do about `signal` under the active `tier`.
    ///
    /// Order of resolution:
    /// 1. Per-signal-id override (strongest).
    /// 2. (severity, tier) override.
    /// 3. Default table.
    #[must_use]
    pub fn decide(&self, signal: &Signal, tier: SecurityTier) -> Action {
        let action = if let Some(action) = self.per_signal.get(&signal.id).copied() {
            action
        } else if let Some(action) = self.overrides.get(&(signal.severity, tier)).copied() {
            action
        } else {
            Self::default_action(signal.severity, tier)
        };
        // SECURITY: Critical-severity signals can never be silently
        // ignored, even if a user-authored override requests it.
        // This prevents a compromised config from disabling
        // always-block protections (e.g. master-key world-readable).
        if signal.severity == Severity::Critical && action == Action::Ignore {
            Action::Log
        } else {
            action
        }
    }

    /// The hard-coded default table — no overrides applied.
    ///
    /// Each `(severity, tier)` pair is listed explicitly even when
    /// distinct rows happen to produce the same [`Action`] today.
    /// That makes the policy auditable as a 5×3 matrix at a glance
    /// — see the table in this module's documentation. Future tier
    /// or severity additions land as new rows here, not as
    /// catch-all wildcards spread across the body.
    #[must_use]
    #[allow(clippy::match_same_arms)] // matrix readability beats DRY here
    pub const fn default_action(severity: Severity, tier: SecurityTier) -> Action {
        match (severity, tier) {
            (Severity::Info, _) => Action::Log,
            (Severity::Warn, SecurityTier::Standard | SecurityTier::Hardened) => {
                Action::Warn { friction: false }
            }
            (Severity::Warn, SecurityTier::Lockdown) => Action::Warn { friction: true },
            (Severity::Degraded, SecurityTier::Standard) => Action::Warn { friction: true },
            (Severity::Degraded, SecurityTier::Hardened | SecurityTier::Lockdown) => Action::Block,
            (Severity::Hostile, SecurityTier::Standard) => Action::Warn { friction: true },
            (Severity::Hostile, SecurityTier::Hardened | SecurityTier::Lockdown) => Action::Block,
            (Severity::Critical, _) => Action::Block,
        }
    }
}

/// Aggregate decision over a set of signals. Returned by
/// [`evaluate`] so the approval pipeline gets a single summary
/// rather than re-iterating over signals.
#[derive(Debug, Clone, Default)]
pub struct Decision {
    /// Whether any signal blocked.
    pub blocked: bool,
    /// Whether any signal demanded a challenge gate.
    pub needs_friction: bool,
    /// Human-facing warnings to surface in the approval popup. One
    /// entry per signal with `Action::Warn`.
    pub warnings: Vec<String>,
    /// First blocking signal, if any. Used to populate the error
    /// returned to the caller.
    pub blocking_signal: Option<Signal>,
    /// Every signal that was logged. Caller appends to audit.
    pub log_entries: Vec<Signal>,
}

/// Evaluate a slice of signals against the policy at a given tier
/// and produce a single decision.
#[must_use]
pub fn evaluate(signals: &[Signal], policy: &Policy, tier: SecurityTier) -> Decision {
    let mut decision = Decision::default();
    for signal in signals {
        match policy.decide(signal, tier) {
            Action::Ignore => {}
            Action::Log => decision.log_entries.push(signal.clone()),
            Action::Warn { friction } => {
                decision.warnings.push(format!(
                    "{}: {}{}",
                    signal.label, signal.detail, signal.mitigation
                ));
                if friction {
                    decision.needs_friction = true;
                }
                decision.log_entries.push(signal.clone());
            }
            Action::Block => {
                decision.blocked = true;
                if decision.blocking_signal.is_none() {
                    decision.blocking_signal = Some(signal.clone());
                }
                decision.log_entries.push(signal.clone());
            }
        }
    }
    decision
}

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

    fn sig(severity: Severity) -> Signal {
        Signal::new(
            SignalId::new("test.signal.x"),
            Category::Other,
            severity,
            "test signal",
            "detail goes here",
            "fix it",
        )
    }

    #[test]
    fn default_policy_info_is_logged_at_every_tier() {
        for tier in [
            SecurityTier::Standard,
            SecurityTier::Hardened,
            SecurityTier::Lockdown,
        ] {
            assert_eq!(Policy::default_action(Severity::Info, tier), Action::Log);
        }
    }

    #[test]
    fn default_policy_critical_always_blocks() {
        for tier in [
            SecurityTier::Standard,
            SecurityTier::Hardened,
            SecurityTier::Lockdown,
        ] {
            assert_eq!(
                Policy::default_action(Severity::Critical, tier),
                Action::Block
            );
        }
    }

    #[test]
    fn default_policy_hostile_blocks_at_hardened_and_above() {
        assert_eq!(
            Policy::default_action(Severity::Hostile, SecurityTier::Hardened),
            Action::Block
        );
        assert_eq!(
            Policy::default_action(Severity::Hostile, SecurityTier::Lockdown),
            Action::Block
        );
        // Standard surfaces friction but does not block.
        match Policy::default_action(Severity::Hostile, SecurityTier::Standard) {
            Action::Warn { friction: true } => {}
            other => panic!("expected warn-with-friction, got {other:?}"),
        }
    }

    #[test]
    fn policy_per_signal_override_beats_severity_table() {
        let mut policy = Policy::new();
        let id = SignalId::new("specific.signal");
        policy.override_signal(id.clone(), Action::Ignore);
        // Hostile signals can be overridden to Ignore.
        let s = Signal::new(
            id.clone(),
            Category::Other,
            Severity::Hostile,
            "would-be-blocking signal",
            "",
            "",
        );
        assert_eq!(policy.decide(&s, SecurityTier::Lockdown), Action::Ignore);

        // Critical signals can NEVER be silently ignored, even with
        // a per-signal override — this prevents a compromised config
        // from disabling always-block protections.
        let crit = Signal::new(
            id,
            Category::Other,
            Severity::Critical,
            "would-be-blocking signal",
            "",
            "",
        );
        assert_eq!(policy.decide(&crit, SecurityTier::Lockdown), Action::Log);
    }

    #[test]
    fn policy_severity_tier_override_works() {
        let mut policy = Policy::new();
        // A site that wants to ignore Warn under Standard.
        policy.override_action(Severity::Warn, SecurityTier::Standard, Action::Ignore);
        let s = sig(Severity::Warn);
        assert_eq!(policy.decide(&s, SecurityTier::Standard), Action::Ignore);
        // Under Hardened the override doesn't apply.
        assert_eq!(
            policy.decide(&s, SecurityTier::Hardened),
            Action::Warn { friction: false }
        );
    }

    #[test]
    fn evaluate_aggregates_warnings_and_blocking() {
        let signals = [
            sig(Severity::Warn),
            sig(Severity::Hostile),
            sig(Severity::Info),
        ];
        let policy = Policy::new();
        let d = evaluate(&signals, &policy, SecurityTier::Lockdown);
        assert!(d.blocked, "Hostile under Lockdown must block");
        assert!(!d.warnings.is_empty(), "Warn must produce a user warning");
        assert_eq!(d.log_entries.len(), 3, "all 3 signals should be logged");
        assert!(d.blocking_signal.is_some());
    }

    #[test]
    fn scoped_signal_id_sanitizes_unsafe_chars() {
        // Tool names from /proc/<pid>/comm can contain anything;
        // SignalId must produce a clean taxonomic suffix.
        let id = SignalId::scoped("gui.input_injector", "xdotool");
        assert_eq!(id.as_str(), "gui.input_injector.xdotool");

        // Dots in scope must be replaced so the taxonomy doesn't
        // get extra levels we can't predict.
        let id = SignalId::scoped("env.preload", "LD_PRELOAD.evil.so");
        assert_eq!(id.as_str(), "env.preload.ld_preload_evil_so");

        // Spaces / slashes / unicode become `_`.
        let id = SignalId::scoped("gui.screen_recorder", "OBS Studio");
        assert_eq!(id.as_str(), "gui.screen_recorder.obs_studio");
    }

    #[test]
    fn scoped_signal_id_is_lowercased() {
        // Audit-log analytics rely on case-stable IDs.
        let id = SignalId::scoped("env.preload", "LD_PRELOAD");
        assert_eq!(id.as_str(), "env.preload.ld_preload");
    }

    #[test]
    fn per_signal_override_can_target_a_scoped_id() {
        // The whole point of granular ids: site can mute one
        // specific tool without muting the category.
        let mut policy = Policy::new();
        let xdotool_id = SignalId::scoped("gui.input_injector", "xdotool");
        let ydotool_id = SignalId::scoped("gui.input_injector", "ydotool");

        policy.override_signal(xdotool_id.clone(), Action::Ignore);

        let xdotool_signal = Signal::new(
            xdotool_id,
            Category::InputInjection,
            Severity::Hostile,
            "xdotool",
            "running",
            "stop it",
        );
        let ydotool_signal = Signal::new(
            ydotool_id,
            Category::InputInjection,
            Severity::Hostile,
            "ydotool",
            "running",
            "stop it",
        );

        // xdotool is muted; ydotool still hits the default action.
        assert_eq!(
            policy.decide(&xdotool_signal, SecurityTier::Lockdown),
            Action::Ignore
        );
        assert_eq!(
            policy.decide(&ydotool_signal, SecurityTier::Lockdown),
            Action::Block
        );
    }

    #[test]
    fn category_str_is_stable() {
        // A regression test for the stability contract — these
        // strings appear in audit logs.
        assert_eq!(Category::InputInjection.as_str(), "input_injection");
        assert_eq!(Category::ScreenRecording.as_str(), "screen_recording");
        assert_eq!(Category::DeviceMismatch.as_str(), "device_mismatch");
    }

    #[test]
    fn severity_ordering() {
        assert!(Severity::Info < Severity::Warn);
        assert!(Severity::Warn < Severity::Degraded);
        assert!(Severity::Degraded < Severity::Hostile);
        assert!(Severity::Hostile < Severity::Critical);
    }

    #[test]
    fn action_blocks_helper() {
        assert!(Action::Block.blocks());
        assert!(!Action::Warn { friction: true }.blocks());
        assert!(!Action::Log.blocks());
        assert!(!Action::Ignore.blocks());
    }

    #[test]
    fn empty_signals_yield_empty_decision() {
        let policy = Policy::new();
        let d = evaluate(&[], &policy, SecurityTier::Lockdown);
        assert!(!d.blocked);
        assert!(!d.needs_friction);
        assert!(d.warnings.is_empty());
        assert!(d.blocking_signal.is_none());
        assert!(d.log_entries.is_empty());
    }
}