agentstategraph-taint 1.3.0

Taint / quarantine / watch substrate for AgentStateGraph
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
//! Core data types for the taint substrate.

use std::collections::HashMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// A taint record. Persisted to the `taints` table in storage and
/// round-tripped across the MCP / FFI / binding surfaces.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Taint {
    /// UUID string generated at creation.
    pub id: String,
    /// Path the taint applies to (e.g. `/cluster/nodes/picoup2`).
    pub path: String,
    /// Human-readable taint name (e.g. `disk-pressure`,
    /// `crash-loop`, `security-review`).
    pub name: String,
    /// Discriminator between taint / quarantine / watch.
    pub kind: TaintKind,
    /// How the pre-commit hook should behave when this taint
    /// matches an incoming write.
    pub effect: TaintEffect,
    /// Advisory severity (does not change pre-commit semantics).
    pub severity: TaintSeverity,
    /// Why the taint was applied. Free-form.
    pub reason: String,
    /// Agent that applied the taint.
    pub agent_id: String,
    /// Commit id of the `Taint` / `Quarantine` / `Watch` intent
    /// commit that created this record. Empty until the commit is
    /// written (the repository patches it post-commit).
    #[serde(default)]
    pub commit_id: String,
    /// When the taint was created.
    pub created_at: DateTime<Utc>,
    /// Optional auto-expiry.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,
    /// Set when resolved via `untaint` / `unquarantine` / `unwatch`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved_at: Option<DateTime<Utc>>,
    /// Agent that resolved the taint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved_by: Option<String>,
    /// Reason given at resolution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved_reason: Option<String>,
    /// Optional evidence (e.g. a remediation commit id) proving
    /// the issue is resolved.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved_proof: Option<String>,
    /// When true, the taint applies to all descendant paths of
    /// `path`.
    pub propagate: bool,
    /// Kind-specific metadata: `authorized_agents` for quarantines,
    /// `metric` / `threshold` / `direction` for watches, etc.
    #[serde(default)]
    pub metadata: TaintMetadata,
}

impl Taint {
    /// `true` when the taint is currently active against `now`:
    /// not resolved and not yet expired.
    pub fn is_active(&self, now: DateTime<Utc>) -> bool {
        if self.resolved_at.is_some() {
            return false;
        }
        match self.expires_at {
            Some(exp) => exp > now,
            None => true,
        }
    }

    /// Authorized-agents allowlist parsed from `metadata`. Applies
    /// to `Quarantine` kind; empty for others.
    pub fn authorized_agents(&self) -> Vec<String> {
        self.metadata
            .0
            .get("authorized_agents")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(str::to_string))
                    .collect()
            })
            .unwrap_or_default()
    }
}

/// Discriminator between the three taint kinds.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum TaintKind {
    Taint,
    Quarantine,
    Watch,
}

/// Pre-commit-hook behavior for this taint.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum TaintEffect {
    /// Attach a warning to the commit metadata but allow the write.
    Warn,
    /// Reject the write with [`TaintError::Blocked`].
    Block,
    /// Require confidence >= 0.9; reject lower-confidence writes.
    Review,
    /// Allow the write; flag the path for query / search filtering.
    Isolate,
    /// Watch kind only — purely advisory.
    Advisory,
}

/// Advisory severity. Does not change pre-commit semantics; used
/// by consumers for triage ordering.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum TaintSeverity {
    Low,
    #[default]
    Medium,
    High,
    Critical,
}

/// Flat string-to-JSON map for kind-specific metadata. Wrapped so
/// we can control the on-disk shape without bleeding
/// `HashMap<String, serde_json::Value>` through every API.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(transparent)]
pub struct TaintMetadata(pub HashMap<String, serde_json::Value>);

impl TaintMetadata {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn insert(
        &mut self,
        key: impl Into<String>,
        value: impl Into<serde_json::Value>,
    ) -> &mut Self {
        self.0.insert(key.into(), value.into());
        self
    }

    pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
        self.0.get(key)
    }
}

/// Result of [`crate::evaluate_access`]. Consumed by the pre-commit
/// hook + `policy_evaluate_change` integration.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TaintCheck {
    pub tainted: bool,
    pub quarantined: bool,
    pub watched: bool,
    pub taints: Vec<Taint>,
    pub quarantines: Vec<Taint>,
    pub watches: Vec<Taint>,
    /// Given the current taints + quarantines + supplied
    /// `agent_id` + `confidence`, is writing allowed?
    pub can_write: bool,
    /// Minimum confidence the caller must supply to pass the
    /// pre-commit hook. `0.0` when no review-effect taint applies.
    pub required_confidence: f64,
    /// Union of `authorized_agents` across all active quarantines
    /// on this path. Empty when no quarantine applies.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub authorized_agents: Vec<String>,
    /// When any `Isolate`-effect taint applies, the path should be
    /// omitted from search / query / `get_tree` unless the caller
    /// explicitly opts in.
    pub isolated: bool,
}

impl TaintCheck {
    pub fn clear() -> Self {
        Self {
            tainted: false,
            quarantined: false,
            watched: false,
            taints: Vec::new(),
            quarantines: Vec::new(),
            watches: Vec::new(),
            can_write: true,
            required_confidence: 0.0,
            authorized_agents: Vec::new(),
            isolated: false,
        }
    }
}

// ---------------------------------------------------------------------------
// Parameter bundles for the Repository surface (§4).
// ---------------------------------------------------------------------------

/// Parameters for `Repository::taint`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TaintParams {
    pub name: String,
    pub effect: TaintEffect,
    pub reason: String,
    #[serde(default)]
    pub severity: TaintSeverity,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,
    #[serde(default = "default_true")]
    pub propagate: bool,
    #[serde(default)]
    pub metadata: TaintMetadata,
    pub agent_id: String,
}

/// Parameters for `Repository::untaint`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct UntaintParams {
    pub reason: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proof: Option<String>,
    pub agent_id: String,
}

/// Parameters for `Repository::quarantine`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct QuarantineParams {
    pub name: String,
    pub reason: String,
    #[serde(default)]
    pub severity: TaintSeverity,
    pub authorized_agents: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,
    #[serde(default = "default_true")]
    pub propagate: bool,
    pub agent_id: String,
}

/// Parameters for `Repository::unquarantine`. Same shape as untaint.
pub type UnquarantineParams = UntaintParams;

/// Parameters for `Repository::watch`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct WatchParams {
    pub name: String,
    pub reason: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metric: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub threshold: Option<f64>,
    #[serde(default = "default_watch_direction")]
    pub direction: WatchDirection,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub check_interval_secs: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,
    #[serde(default)]
    pub severity: TaintSeverity,
    #[serde(default = "default_true")]
    pub propagate: bool,
    pub agent_id: String,
}

/// Parameters for `Repository::unwatch`. Watches are lightweight so
/// reason is optional.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct UnwatchParams {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    pub agent_id: String,
}

/// Direction a watch threshold fires in.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum WatchDirection {
    #[default]
    Above,
    Below,
}

fn default_true() -> bool {
    true
}

fn default_watch_direction() -> WatchDirection {
    WatchDirection::Above
}

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

    #[test]
    fn taint_kind_serializes_snake_case() {
        assert_eq!(
            serde_json::to_string(&TaintKind::Taint).unwrap(),
            "\"taint\""
        );
        assert_eq!(
            serde_json::to_string(&TaintKind::Quarantine).unwrap(),
            "\"quarantine\""
        );
        assert_eq!(
            serde_json::to_string(&TaintKind::Watch).unwrap(),
            "\"watch\""
        );
    }

    #[test]
    fn taint_effect_round_trips() {
        for e in [
            TaintEffect::Warn,
            TaintEffect::Block,
            TaintEffect::Review,
            TaintEffect::Isolate,
            TaintEffect::Advisory,
        ] {
            let j = serde_json::to_value(e).unwrap();
            let back: TaintEffect = serde_json::from_value(j).unwrap();
            assert_eq!(e, back);
        }
    }

    #[test]
    fn is_active_honors_resolved_and_expired() {
        let base = Taint {
            id: "t1".into(),
            path: "/x".into(),
            name: "n".into(),
            kind: TaintKind::Taint,
            effect: TaintEffect::Warn,
            severity: TaintSeverity::Low,
            reason: "r".into(),
            agent_id: "a".into(),
            commit_id: String::new(),
            created_at: Utc::now(),
            expires_at: None,
            resolved_at: None,
            resolved_by: None,
            resolved_reason: None,
            resolved_proof: None,
            propagate: true,
            metadata: TaintMetadata::new(),
        };
        assert!(base.is_active(Utc::now()));

        let mut expired = base.clone();
        expired.expires_at = Some(Utc::now() - chrono::Duration::seconds(10));
        assert!(!expired.is_active(Utc::now()));

        let mut resolved = base.clone();
        resolved.resolved_at = Some(Utc::now() - chrono::Duration::seconds(1));
        assert!(!resolved.is_active(Utc::now()));
    }

    #[test]
    fn authorized_agents_parses_metadata() {
        let mut t = Taint {
            id: "q1".into(),
            path: "/x".into(),
            name: "sec".into(),
            kind: TaintKind::Quarantine,
            effect: TaintEffect::Block,
            severity: TaintSeverity::High,
            reason: "r".into(),
            agent_id: "a".into(),
            commit_id: String::new(),
            created_at: Utc::now(),
            expires_at: None,
            resolved_at: None,
            resolved_by: None,
            resolved_reason: None,
            resolved_proof: None,
            propagate: true,
            metadata: TaintMetadata::new(),
        };
        t.metadata.insert(
            "authorized_agents",
            serde_json::json!(["agent/security", "human/sre-lead"]),
        );
        assert_eq!(
            t.authorized_agents(),
            vec!["agent/security".to_string(), "human/sre-lead".to_string()]
        );
    }

    fn base_taint() -> Taint {
        Taint {
            id: "t1".into(),
            path: "/x".into(),
            name: "n".into(),
            kind: TaintKind::Taint,
            effect: TaintEffect::Warn,
            severity: TaintSeverity::Low,
            reason: "r".into(),
            agent_id: "a".into(),
            commit_id: String::new(),
            created_at: Utc::now(),
            expires_at: None,
            resolved_at: None,
            resolved_by: None,
            resolved_reason: None,
            resolved_proof: None,
            propagate: true,
            metadata: TaintMetadata::new(),
        }
    }

    // --- is_active edge cases ---

    #[test]
    fn is_active_future_expiry_still_active() {
        let mut t = base_taint();
        t.expires_at = Some(Utc::now() + chrono::Duration::hours(1));
        assert!(t.is_active(Utc::now()));
    }

    #[test]
    fn is_active_resolved_overrides_non_expired() {
        let mut t = base_taint();
        t.expires_at = Some(Utc::now() + chrono::Duration::hours(1)); // not expired
        t.resolved_at = Some(Utc::now() - chrono::Duration::seconds(1)); // but resolved
        assert!(!t.is_active(Utc::now()));
    }

    #[test]
    fn is_active_no_expiry_no_resolution_always_active() {
        let t = base_taint();
        assert!(t.is_active(Utc::now()));
    }

    // --- authorized_agents edge cases ---

    #[test]
    fn authorized_agents_empty_when_key_absent() {
        let t = base_taint();
        assert!(t.authorized_agents().is_empty());
    }

    #[test]
    fn authorized_agents_empty_when_value_not_array() {
        let mut t = base_taint();
        t.metadata.insert("authorized_agents", "not-an-array");
        assert!(t.authorized_agents().is_empty());
    }

    #[test]
    fn authorized_agents_filters_non_string_entries() {
        let mut t = base_taint();
        // Mixed array: string + number; only strings should survive
        t.metadata.insert(
            "authorized_agents",
            serde_json::json!(["agent/ok", 42, "human/ok"]),
        );
        let agents = t.authorized_agents();
        assert_eq!(agents, vec!["agent/ok", "human/ok"]);
    }

    // --- TaintMetadata ---

    #[test]
    fn taint_metadata_insert_get_roundtrip() {
        let mut m = TaintMetadata::new();
        m.insert("key1", serde_json::json!("value1"));
        m.insert("key2", serde_json::json!(42));
        assert_eq!(m.get("key1"), Some(&serde_json::json!("value1")));
        assert_eq!(m.get("key2"), Some(&serde_json::json!(42)));
        assert_eq!(m.get("missing"), None);
    }

    #[test]
    fn taint_metadata_insert_returns_self_for_chaining() {
        let mut m = TaintMetadata::new();
        m.insert("a", "1").insert("b", "2");
        assert!(m.get("a").is_some());
        assert!(m.get("b").is_some());
    }

    #[test]
    fn taint_metadata_default_is_empty() {
        let m = TaintMetadata::default();
        assert!(m.0.is_empty());
    }

    // --- Default values ---

    #[test]
    fn taint_severity_default_is_medium() {
        assert_eq!(TaintSeverity::default(), TaintSeverity::Medium);
    }

    #[test]
    fn watch_direction_default_is_above() {
        assert_eq!(WatchDirection::default(), WatchDirection::Above);
    }

    // --- TaintCheck::clear ---

    #[test]
    fn taint_check_clear_is_all_clear() {
        let c = TaintCheck::clear();
        assert!(!c.tainted);
        assert!(!c.quarantined);
        assert!(!c.watched);
        assert!(c.taints.is_empty());
        assert!(c.quarantines.is_empty());
        assert!(c.watches.is_empty());
        assert!(c.can_write);
        assert_eq!(c.required_confidence, 0.0);
        assert!(c.authorized_agents.is_empty());
        assert!(!c.isolated);
    }

    // --- Serialization round-trips ---

    #[test]
    fn taint_severity_round_trips_all_variants() {
        for s in [
            TaintSeverity::Low,
            TaintSeverity::Medium,
            TaintSeverity::High,
            TaintSeverity::Critical,
        ] {
            let j = serde_json::to_value(s).unwrap();
            let back: TaintSeverity = serde_json::from_value(j).unwrap();
            assert_eq!(s, back);
        }
    }

    #[test]
    fn taint_kind_deserializes_snake_case() {
        assert_eq!(
            serde_json::from_str::<TaintKind>("\"quarantine\"").unwrap(),
            TaintKind::Quarantine
        );
        assert_eq!(
            serde_json::from_str::<TaintKind>("\"watch\"").unwrap(),
            TaintKind::Watch
        );
    }

    #[test]
    fn taint_full_round_trip_serialization() {
        let t = Taint {
            id: "uuid-123".into(),
            path: "/nodes/pico1".into(),
            name: "disk-pressure".into(),
            kind: TaintKind::Quarantine,
            effect: TaintEffect::Block,
            severity: TaintSeverity::Critical,
            reason: "disk full".into(),
            agent_id: "monitor/disk".into(),
            commit_id: "abc123".into(),
            created_at: Utc::now(),
            expires_at: Some(Utc::now() + chrono::Duration::hours(24)),
            resolved_at: None,
            resolved_by: None,
            resolved_reason: None,
            resolved_proof: None,
            propagate: false,
            metadata: {
                let mut m = TaintMetadata::new();
                m.insert("authorized_agents", serde_json::json!(["agent/ops"]));
                m
            },
        };

        let json = serde_json::to_string(&t).unwrap();
        let restored: Taint = serde_json::from_str(&json).unwrap();

        assert_eq!(restored.id, t.id);
        assert_eq!(restored.kind, TaintKind::Quarantine);
        assert_eq!(restored.effect, TaintEffect::Block);
        assert_eq!(restored.severity, TaintSeverity::Critical);
        assert!(!restored.propagate);
        assert_eq!(restored.authorized_agents(), vec!["agent/ops"]);
    }

    #[test]
    fn taint_resolved_fields_round_trip() {
        let mut t = base_taint();
        t.resolved_at = Some(Utc::now());
        t.resolved_by = Some("human/sre".into());
        t.resolved_reason = Some("disk replaced".into());
        t.resolved_proof = Some("commit-xyz".into());

        let json = serde_json::to_string(&t).unwrap();
        let restored: Taint = serde_json::from_str(&json).unwrap();

        assert!(restored.resolved_at.is_some());
        assert_eq!(restored.resolved_by.as_deref(), Some("human/sre"));
        assert_eq!(restored.resolved_reason.as_deref(), Some("disk replaced"));
        assert_eq!(restored.resolved_proof.as_deref(), Some("commit-xyz"));
        assert!(!restored.is_active(Utc::now()));
    }

    #[test]
    fn taint_optional_fields_omitted_from_serialization() {
        let t = base_taint();
        let json = serde_json::to_string(&t).unwrap();
        // Fields with skip_serializing_if should be absent
        assert!(!json.contains("expires_at"));
        assert!(!json.contains("resolved_at"));
        assert!(!json.contains("resolved_by"));
    }

    #[test]
    fn watch_direction_round_trips() {
        for d in [WatchDirection::Above, WatchDirection::Below] {
            let j = serde_json::to_value(d).unwrap();
            let back: WatchDirection = serde_json::from_value(j).unwrap();
            assert_eq!(d, back);
        }
    }
}