heartbit-core 2026.507.3

The Rust agentic framework — agents, tools, LLM providers, memory, evaluation.
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
//! PII detection guardrail.
//!
//! Scans LLM responses and tool outputs for personally identifiable
//! information (email, phone, SSN, credit card) and can redact, warn, or deny.

#![allow(missing_docs)]
use std::future::Future;
use std::pin::Pin;
use std::sync::LazyLock;

use regex::Regex;

use crate::agent::guardrail::{GuardAction, Guardrail};
use crate::error::Error;
use crate::llm::types::{CompletionResponse, ContentBlock, ToolCall};
use crate::tool::ToolOutput;

// Static compiled regexes for built-in PII detectors.
static EMAIL_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}").unwrap());
// SECURITY (F-AGENT-15): broaden the phone-number pattern beyond US/CA
// (NANP). Covers E.164 international (`+33 6 12 34 56 78`,
// `+44 20 7946 0958`, etc.) plus the original NANP (US/CA `(555)
// 123-4567`). Best-effort: a serious deployment should swap in a
// `phonenumber`-crate detector. Kept as a single regex so the existing
// match-replace loop continues to work unchanged.
static PHONE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(concat!(
        // Group 1: international E.164 (+CC NN NN NN NN, 7-15 digits total)
        r"(?:\+\d{1,3}[-.\s]?(?:\(?\d{1,4}\)?[-.\s]?){2,5}\d{2,4})",
        r"|",
        // Group 2: NANP / generic US-style
        r"(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}",
    ))
    .unwrap()
});
static SSN_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\b\d{3}-\d{2}-\d{4}\b").unwrap());
static CC_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{1,7}\b").unwrap());

/// What to do when PII is detected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PiiAction {
    /// Replace matched PII with `[REDACTED:type]` in both `post_tool` (tool
    /// outputs) and `post_llm` (LLM response text blocks). Returns
    /// `GuardAction::Warn` so the redaction is surfaced via audit and
    /// `GuardrailWarned` events without blocking the response.
    #[default]
    Redact,
    /// Issue a warning but allow the content through unmodified.
    Warn,
    /// Deny the operation entirely.
    Deny,
}

/// Built-in and custom PII detector types.
#[derive(Debug, Clone)]
pub enum PiiDetector {
    Email,
    Phone,
    Ssn,
    CreditCard,
    Custom { name: String, pattern: Regex },
}

impl PiiDetector {
    fn label(&self) -> &str {
        match self {
            PiiDetector::Email => "email",
            PiiDetector::Phone => "phone",
            PiiDetector::Ssn => "ssn",
            PiiDetector::CreditCard => "credit_card",
            PiiDetector::Custom { name, .. } => name,
        }
    }

    /// Find all matches in text, returning (start, end, label) tuples.
    fn find_matches(&self, text: &str) -> Vec<(usize, usize, String)> {
        let re: &Regex = match self {
            PiiDetector::Email => &EMAIL_RE,
            PiiDetector::Phone => &PHONE_RE,
            PiiDetector::Ssn => &SSN_RE,
            PiiDetector::CreditCard => &CC_RE,
            PiiDetector::Custom { pattern, .. } => pattern,
        };
        let label = self.label().to_string();
        re.find_iter(text)
            .filter(|m| {
                // Luhn validation for credit cards
                if matches!(self, PiiDetector::CreditCard) {
                    let digits: String =
                        m.as_str().chars().filter(|c| c.is_ascii_digit()).collect();
                    return luhn_check(&digits);
                }
                true
            })
            .map(|m| (m.start(), m.end(), label.clone()))
            .collect()
    }
}

/// PII detection guardrail.
pub struct PiiGuardrail {
    detectors: Vec<PiiDetector>,
    action: PiiAction,
}

impl PiiGuardrail {
    pub fn new(detectors: Vec<PiiDetector>, action: PiiAction) -> Self {
        Self { detectors, action }
    }

    /// Create with all built-in detectors (email, phone, SSN, credit card).
    pub fn all_builtin(action: PiiAction) -> Self {
        Self::new(
            vec![
                PiiDetector::Email,
                PiiDetector::Phone,
                PiiDetector::Ssn,
                PiiDetector::CreditCard,
            ],
            action,
        )
    }

    /// Scan text for PII, returning all matches sorted by position.
    fn scan(&self, text: &str) -> Vec<(usize, usize, String)> {
        let mut matches = Vec::new();
        for det in &self.detectors {
            matches.extend(det.find_matches(text));
        }
        matches.sort_by_key(|m| m.0);
        matches
    }

    /// Redact PII in text, replacing matches with `[REDACTED:type]`.
    fn redact(&self, text: &str) -> String {
        let matches = self.scan(text);
        if matches.is_empty() {
            return text.to_string();
        }
        let mut result = String::with_capacity(text.len());
        let mut last = 0;
        for (start, end, label) in &matches {
            if *start < last {
                continue; // Skip overlapping matches
            }
            result.push_str(&text[last..*start]);
            result.push_str(&format!("[REDACTED:{label}]"));
            last = *end;
        }
        result.push_str(&text[last..]);
        result
    }

    /// Determine the guard action for detected PII matches. Used after the
    /// (possibly mutating) scan has already run.
    fn handle_pii(&self, matches: &[(usize, usize, String)]) -> GuardAction {
        if matches.is_empty() {
            return GuardAction::Allow;
        }
        let labels: Vec<&str> = matches.iter().map(|(_, _, l)| l.as_str()).collect();
        let reason = format!("PII detected: {}", labels.join(", "));
        match self.action {
            PiiAction::Redact => GuardAction::warn(reason),
            PiiAction::Warn => GuardAction::warn(reason),
            PiiAction::Deny => GuardAction::deny(reason),
        }
    }
}

impl Guardrail for PiiGuardrail {
    fn name(&self) -> &str {
        "pii"
    }

    fn post_llm(
        &self,
        response: &mut CompletionResponse,
    ) -> Pin<Box<dyn Future<Output = Result<GuardAction, Error>> + Send + '_>> {
        // Scan every text block once. In Redact mode, replace each block's
        // text with the redacted version in place — the trait now hands us
        // `&mut CompletionResponse`, so the mutation actually reaches the
        // caller (Issue #7).
        let mut all_matches = Vec::new();
        let redact = matches!(self.action, PiiAction::Redact);
        for block in &mut response.content {
            if let ContentBlock::Text { text } = block {
                let scanned = self.scan(text);
                if !scanned.is_empty() {
                    if redact {
                        *text = self.redact(text);
                    }
                    all_matches.extend(scanned);
                }
            }
        }
        let action = self.handle_pii(&all_matches);
        Box::pin(async move { Ok(action) })
    }

    fn post_tool(
        &self,
        _call: &ToolCall,
        output: &mut ToolOutput,
    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + '_>> {
        if output.is_error {
            return Box::pin(async { Ok(()) });
        }
        let matches = self.scan(&output.content);
        if matches.is_empty() {
            return Box::pin(async { Ok(()) });
        }
        match self.action {
            PiiAction::Redact => {
                output.content = self.redact(&output.content);
                Box::pin(async { Ok(()) })
            }
            PiiAction::Warn => Box::pin(async { Ok(()) }),
            PiiAction::Deny => {
                let labels: Vec<&str> = matches.iter().map(|(_, _, l)| l.as_str()).collect();
                let reason = format!("PII detected in tool output: {}", labels.join(", "));
                Box::pin(async move { Err(Error::Guardrail(reason)) })
            }
        }
    }
}

/// Luhn algorithm for credit card validation.
fn luhn_check(digits: &str) -> bool {
    if digits.len() < 13 || digits.len() > 19 {
        return false;
    }
    let mut sum = 0u32;
    let mut double = false;
    for c in digits.chars().rev() {
        let Some(d) = c.to_digit(10) else {
            return false;
        };
        let val = if double {
            let doubled = d * 2;
            if doubled > 9 { doubled - 9 } else { doubled }
        } else {
            d
        };
        sum += val;
        double = !double;
    }
    sum.is_multiple_of(10)
}

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

    fn make_guard(action: PiiAction) -> PiiGuardrail {
        PiiGuardrail::all_builtin(action)
    }

    #[test]
    fn detects_email_address() {
        let g = make_guard(PiiAction::Deny);
        let matches = g.scan("Contact john@example.com for details");
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].2, "email");
    }

    #[test]
    fn detects_phone_number() {
        let g = make_guard(PiiAction::Deny);
        let matches = g.scan("Call me at (555) 123-4567");
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].2, "phone");
    }

    #[test]
    fn detects_ssn() {
        let g = make_guard(PiiAction::Deny);
        let matches = g.scan("SSN: 123-45-6789");
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].2, "ssn");
    }

    #[test]
    fn detects_credit_card_with_luhn() {
        let g = make_guard(PiiAction::Deny);
        // 4532015112830366 is a valid Luhn number
        let matches = g.scan("Card: 4532 0151 1283 0366");
        assert_eq!(matches.len(), 1, "matches: {matches:?}");
        assert_eq!(matches[0].2, "credit_card");
    }

    #[test]
    fn rejects_invalid_luhn() {
        let g = make_guard(PiiAction::Deny);
        let matches = g.scan("Card: 1234 5678 9012 3456");
        assert!(
            matches.iter().all(|m| m.2 != "credit_card"),
            "should reject invalid Luhn: {matches:?}"
        );
    }

    #[test]
    fn redact_mode_replaces_pii() {
        let g = make_guard(PiiAction::Redact);
        let result = g.redact("Email: john@example.com, SSN: 123-45-6789");
        assert!(result.contains("[REDACTED:email]"), "result: {result}");
        assert!(result.contains("[REDACTED:ssn]"), "result: {result}");
        assert!(!result.contains("john@example.com"), "result: {result}");
        assert!(!result.contains("123-45-6789"), "result: {result}");
    }

    #[test]
    fn redact_mode_warns_on_detection() {
        // handle_pii returns Warn for Redact mode (actual redaction happens
        // inline in post_tool; post_llm can't mutate so it warns).
        let g = make_guard(PiiAction::Redact);
        let scan_matches = g.scan("Contact john@example.com");
        let action = g.handle_pii(&scan_matches);
        assert!(matches!(action, GuardAction::Warn { .. }));
    }

    #[test]
    fn warn_mode_warns() {
        let g = make_guard(PiiAction::Warn);
        let scan_matches = g.scan("Contact john@example.com");
        let action = g.handle_pii(&scan_matches);
        assert!(matches!(action, GuardAction::Warn { .. }));
    }

    #[test]
    fn deny_mode_denies() {
        let g = make_guard(PiiAction::Deny);
        let scan_matches = g.scan("Contact john@example.com");
        let action = g.handle_pii(&scan_matches);
        assert!(action.is_denied());
    }

    #[test]
    fn custom_detector_works() {
        let custom = PiiDetector::Custom {
            name: "api_key".into(),
            pattern: Regex::new(r"tok-[a-zA-Z0-9]{32,}").unwrap(),
        };
        let g = PiiGuardrail::new(vec![custom], PiiAction::Deny);
        let matches = g.scan("Key: tok-AAAAAAAAAAAABBBBBBBBBBBBCCCCCCCCCCCC");
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].2, "api_key");
    }

    #[test]
    fn no_false_positive_on_clean_text() {
        let g = make_guard(PiiAction::Deny);
        let matches = g.scan("The weather in Paris is nice today. Temperature: 22C.");
        assert!(matches.is_empty(), "false positives: {matches:?}");
    }

    #[test]
    fn multiple_pii_types_in_one_string() {
        let g = make_guard(PiiAction::Redact);
        let text = "Name: John, email: john@example.com, SSN: 123-45-6789, phone: (555) 123-4567";
        let matches = g.scan(text);
        let labels: Vec<&str> = matches.iter().map(|m| m.2.as_str()).collect();
        assert!(labels.contains(&"email"), "labels: {labels:?}");
        assert!(labels.contains(&"ssn"), "labels: {labels:?}");
        assert!(labels.contains(&"phone"), "labels: {labels:?}");
    }

    #[tokio::test]
    async fn post_tool_redacts_pii() {
        let g = make_guard(PiiAction::Redact);
        let call = ToolCall {
            id: "c1".into(),
            name: "test".into(),
            input: serde_json::json!({}),
        };
        let mut output = ToolOutput::success("Email: john@example.com".to_string());
        g.post_tool(&call, &mut output).await.unwrap();
        assert!(output.content.contains("[REDACTED:email]"));
        assert!(!output.content.contains("john@example.com"));
    }

    #[tokio::test]
    async fn post_tool_deny_returns_error() {
        let g = make_guard(PiiAction::Deny);
        let call = ToolCall {
            id: "c1".into(),
            name: "test".into(),
            input: serde_json::json!({}),
        };
        let mut output = ToolOutput::success("SSN: 123-45-6789".to_string());
        let result = g.post_tool(&call, &mut output).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn post_tool_skips_error_outputs() {
        let g = make_guard(PiiAction::Deny);
        let call = ToolCall {
            id: "c1".into(),
            name: "test".into(),
            input: serde_json::json!({}),
        };
        let mut output = ToolOutput::error("john@example.com");
        let result = g.post_tool(&call, &mut output).await;
        assert!(result.is_ok());
    }

    #[test]
    fn luhn_valid() {
        assert!(luhn_check("4532015112830366")); // 16 digits, valid Visa
        assert!(luhn_check("5425233430109903")); // 16 digits, valid Mastercard
    }

    #[test]
    fn luhn_invalid() {
        assert!(!luhn_check("1234567890123456"));
        assert!(!luhn_check("123")); // too short
    }

    #[tokio::test]
    async fn post_llm_redact_mode_actually_redacts_response() {
        // Issue #7: Redact must mutate the LLM response in place, not just
        // return a Warn while leaving raw PII in the user-visible output.
        use crate::llm::types::{StopReason, TokenUsage};

        let g = make_guard(PiiAction::Redact);
        let mut response = CompletionResponse {
            content: vec![ContentBlock::Text {
                text: "Contact john@example.com or 415-555-0142 for help".into(),
            }],
            stop_reason: StopReason::EndTurn,
            usage: TokenUsage::default(),
            model: None,
        };
        let action = g.post_llm(&mut response).await.unwrap();

        // Audit signal preserved.
        assert!(
            matches!(action, GuardAction::Warn { .. }),
            "expected Warn after redaction so the detection is auditable, got: {action:?}"
        );

        // The raw PII must be gone from the response the caller sees.
        let ContentBlock::Text { text } = &response.content[0] else {
            panic!("expected text block");
        };
        assert!(!text.contains("john@example.com"), "email survived: {text}");
        assert!(!text.contains("415-555-0142"), "phone survived: {text}");
        assert!(
            text.contains("[REDACTED:email]"),
            "missing email tag: {text}"
        );
        assert!(
            text.contains("[REDACTED:phone]"),
            "missing phone tag: {text}"
        );
    }

    #[tokio::test]
    async fn post_llm_warn_mode_leaves_response_unchanged() {
        use crate::llm::types::{StopReason, TokenUsage};

        let g = make_guard(PiiAction::Warn);
        let original = "Contact john@example.com for help".to_string();
        let mut response = CompletionResponse {
            content: vec![ContentBlock::Text {
                text: original.clone(),
            }],
            stop_reason: StopReason::EndTurn,
            usage: TokenUsage::default(),
            model: None,
        };
        let action = g.post_llm(&mut response).await.unwrap();
        assert!(matches!(action, GuardAction::Warn { .. }));
        let ContentBlock::Text { text } = &response.content[0] else {
            panic!("expected text block");
        };
        assert_eq!(text, &original, "Warn mode must not mutate text");
    }

    #[tokio::test]
    async fn post_llm_deny_mode_denies_on_pii() {
        use crate::llm::types::{StopReason, TokenUsage};

        let g = make_guard(PiiAction::Deny);
        let mut response = CompletionResponse {
            content: vec![ContentBlock::Text {
                text: "SSN: 123-45-6789".into(),
            }],
            stop_reason: StopReason::EndTurn,
            usage: TokenUsage::default(),
            model: None,
        };
        let action = g.post_llm(&mut response).await.unwrap();
        assert!(action.is_denied());
    }

    #[test]
    fn meta_name() {
        let g = make_guard(PiiAction::Redact);
        assert_eq!(g.name(), "pii");
    }
}