heartbit-core 2026.507.2

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
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
//! Composition operators for guardrails.
//!
//! - [`GuardrailChain`]: Ordered pipeline — first `Deny` wins.
//! - [`WarnToDeny`]: Graduated containment — N consecutive `Warn` → `Deny`.
//! - [`ConditionalGuardrail`]: Predicate-gated — only runs when condition is true.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};

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

// ---------------------------------------------------------------------------
// GuardrailChain
// ---------------------------------------------------------------------------

/// Ordered pipeline of guardrails — first `Deny` wins.
///
/// Equivalent to the default `Vec<Arc<dyn Guardrail>>` behavior in the agent
/// loop, but wrapped as a single `Guardrail` for nested composition.
///
/// **Implementation note**: The `Guardrail` trait's lifetime elision ties the
/// returned future to `&self` only (not to reference parameters like `call`
/// or `response`). This means inner guardrails perform their work (including
/// mutations) synchronously during the call, and the returned futures only
/// carry no-op cleanup. We eagerly evaluate all inner guardrails and collect
/// their futures for awaiting.
pub struct GuardrailChain {
    guardrails: Vec<Arc<dyn Guardrail>>,
}

impl GuardrailChain {
    /// Create a new guardrail chain from a list of guardrails.
    pub fn new(guardrails: Vec<Arc<dyn Guardrail>>) -> Self {
        Self { guardrails }
    }
}

impl Guardrail for GuardrailChain {
    fn name(&self) -> &str {
        "chain"
    }

    fn pre_llm(
        &self,
        request: &mut CompletionRequest,
    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + '_>> {
        // Eagerly call each guardrail's pre_llm (synchronous mutations run now).
        let futs: Vec<_> = self.guardrails.iter().map(|g| g.pre_llm(request)).collect();
        Box::pin(async move {
            for fut in futs {
                fut.await?;
            }
            Ok(())
        })
    }

    fn post_llm(
        &self,
        response: &mut CompletionResponse,
    ) -> Pin<Box<dyn Future<Output = Result<GuardAction, Error>> + Send + '_>> {
        // Eagerly call each guardrail's `post_llm`. By contract the synchronous
        // portion of every implementation (including any redaction mutation)
        // runs *before* the returned future is built, so each call here sees
        // the cumulative effect of prior ones — correct semantics for chained
        // redaction. The collected futures only carry the resulting action.
        let futs: Vec<_> = self
            .guardrails
            .iter()
            .map(|g| g.post_llm(response))
            .collect();
        Box::pin(async move {
            let mut worst = GuardAction::Allow;
            for fut in futs {
                let action = fut.await?;
                if action.is_killed() {
                    return Ok(action);
                }
                if action.is_denied() {
                    return Ok(action);
                }
                if matches!(action, GuardAction::Warn { .. }) && matches!(worst, GuardAction::Allow)
                {
                    worst = action;
                }
            }
            Ok(worst)
        })
    }

    fn pre_tool(
        &self,
        call: &ToolCall,
    ) -> Pin<Box<dyn Future<Output = Result<GuardAction, Error>> + Send + '_>> {
        // Eagerly call each guardrail's pre_tool.
        let futs: Vec<_> = self.guardrails.iter().map(|g| g.pre_tool(call)).collect();
        Box::pin(async move {
            let mut worst = GuardAction::Allow;
            for fut in futs {
                let action = fut.await?;
                if action.is_killed() {
                    return Ok(action);
                }
                if action.is_denied() {
                    return Ok(action);
                }
                if matches!(action, GuardAction::Warn { .. }) && matches!(worst, GuardAction::Allow)
                {
                    worst = action;
                }
            }
            Ok(worst)
        })
    }

    fn post_tool(
        &self,
        call: &ToolCall,
        output: &mut ToolOutput,
    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + '_>> {
        // Eagerly call each guardrail's post_tool (mutations run synchronously).
        let futs: Vec<_> = self
            .guardrails
            .iter()
            .map(|g| g.post_tool(call, output))
            .collect();
        Box::pin(async move {
            for fut in futs {
                fut.await?;
            }
            Ok(())
        })
    }
}

// ---------------------------------------------------------------------------
// WarnToDeny
// ---------------------------------------------------------------------------

/// Graduated containment: converts N consecutive `Warn` actions to `Deny`.
///
/// Wraps an inner guardrail. Tracks consecutive `Warn` actions across calls.
/// When the count reaches `threshold`, the `Warn` is escalated to `Deny`.
/// Any `Allow` resets the counter.
pub struct WarnToDeny {
    inner: Arc<dyn Guardrail>,
    threshold: u32,
    consecutive_warns: AtomicU32,
}

impl WarnToDeny {
    /// Create a `WarnToDeny` adaptor that escalates after `threshold` consecutive warnings.
    pub fn new(inner: Arc<dyn Guardrail>, threshold: u32) -> Self {
        Self {
            inner,
            threshold,
            consecutive_warns: AtomicU32::new(0),
        }
    }

    fn escalate_if_needed(&self, action: GuardAction) -> GuardAction {
        match &action {
            GuardAction::Warn { reason } => {
                let prev = self.consecutive_warns.fetch_add(1, Ordering::Relaxed);
                if prev + 1 >= self.threshold {
                    self.consecutive_warns.store(0, Ordering::Relaxed);
                    GuardAction::deny(format!(
                        "Escalated after {} consecutive warnings: {reason}",
                        self.threshold
                    ))
                } else {
                    action
                }
            }
            // Allow/Deny reset warn counter; Kill passes through unchanged
            GuardAction::Kill { .. } => action,
            _ => {
                self.consecutive_warns.store(0, Ordering::Relaxed);
                action
            }
        }
    }
}

impl Guardrail for WarnToDeny {
    fn name(&self) -> &str {
        "warn_to_deny"
    }

    fn pre_llm(
        &self,
        request: &mut CompletionRequest,
    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + '_>> {
        self.inner.pre_llm(request)
    }

    fn post_llm(
        &self,
        response: &mut CompletionResponse,
    ) -> Pin<Box<dyn Future<Output = Result<GuardAction, Error>> + Send + '_>> {
        let fut = self.inner.post_llm(response);
        Box::pin(async move {
            let action = fut.await?;
            Ok(self.escalate_if_needed(action))
        })
    }

    fn pre_tool(
        &self,
        call: &ToolCall,
    ) -> Pin<Box<dyn Future<Output = Result<GuardAction, Error>> + Send + '_>> {
        // Eagerly call inner (doesn't capture `call` per trait elision).
        let fut = self.inner.pre_tool(call);
        Box::pin(async move {
            let action = fut.await?;
            Ok(self.escalate_if_needed(action))
        })
    }

    fn post_tool(
        &self,
        call: &ToolCall,
        output: &mut ToolOutput,
    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + '_>> {
        self.inner.post_tool(call, output)
    }
}

// ---------------------------------------------------------------------------
// ConditionalGuardrail
// ---------------------------------------------------------------------------

/// Predicate-gated guardrail — only runs the inner guardrail when the
/// predicate returns `true` for the tool name.
///
/// Use for patterns like "apply this guardrail only to MCP tools" or
/// "only check bash tool calls".
///
/// The predicate receives the tool name for `pre_tool`/`post_tool` hooks.
/// For `pre_llm`/`post_llm` hooks (no tool name), the inner guardrail
/// always runs.
pub struct ConditionalGuardrail {
    inner: Arc<dyn Guardrail>,
    predicate: Arc<dyn Fn(&str) -> bool + Send + Sync>,
}

impl ConditionalGuardrail {
    /// Create a guardrail that only activates for tool calls matching `predicate`.
    pub fn new(
        inner: Arc<dyn Guardrail>,
        predicate: Arc<dyn Fn(&str) -> bool + Send + Sync>,
    ) -> Self {
        Self { inner, predicate }
    }
}

impl Guardrail for ConditionalGuardrail {
    fn name(&self) -> &str {
        "conditional"
    }

    fn pre_llm(
        &self,
        request: &mut CompletionRequest,
    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + '_>> {
        self.inner.pre_llm(request)
    }

    fn post_llm(
        &self,
        response: &mut CompletionResponse,
    ) -> Pin<Box<dyn Future<Output = Result<GuardAction, Error>> + Send + '_>> {
        self.inner.post_llm(response)
    }

    fn pre_tool(
        &self,
        call: &ToolCall,
    ) -> Pin<Box<dyn Future<Output = Result<GuardAction, Error>> + Send + '_>> {
        if (self.predicate)(&call.name) {
            self.inner.pre_tool(call)
        } else {
            Box::pin(async { Ok(GuardAction::Allow) })
        }
    }

    fn post_tool(
        &self,
        call: &ToolCall,
        output: &mut ToolOutput,
    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + '_>> {
        if (self.predicate)(&call.name) {
            self.inner.post_tool(call, output)
        } else {
            Box::pin(async { Ok(()) })
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::llm::types::{StopReason, TokenUsage};

    /// A guardrail that always denies pre_tool calls.
    struct AlwaysDenyGuardrail;
    impl Guardrail for AlwaysDenyGuardrail {
        fn pre_tool(
            &self,
            _call: &ToolCall,
        ) -> Pin<Box<dyn Future<Output = Result<GuardAction, Error>> + Send + '_>> {
            Box::pin(async { Ok(GuardAction::deny("blocked")) })
        }
        fn post_llm(
            &self,
            _response: &mut CompletionResponse,
        ) -> Pin<Box<dyn Future<Output = Result<GuardAction, Error>> + Send + '_>> {
            Box::pin(async { Ok(GuardAction::deny("blocked")) })
        }
    }

    /// A guardrail that always allows.
    struct AlwaysAllowGuardrail;
    impl Guardrail for AlwaysAllowGuardrail {}

    /// A guardrail that always warns.
    struct AlwaysWarnGuardrail;
    impl Guardrail for AlwaysWarnGuardrail {
        fn pre_tool(
            &self,
            _call: &ToolCall,
        ) -> Pin<Box<dyn Future<Output = Result<GuardAction, Error>> + Send + '_>> {
            Box::pin(async { Ok(GuardAction::warn("suspicious")) })
        }
        fn post_llm(
            &self,
            _response: &mut CompletionResponse,
        ) -> Pin<Box<dyn Future<Output = Result<GuardAction, Error>> + Send + '_>> {
            Box::pin(async { Ok(GuardAction::warn("suspicious")) })
        }
    }

    fn test_call(name: &str) -> ToolCall {
        ToolCall {
            id: "c1".into(),
            name: name.into(),
            input: serde_json::json!({}),
        }
    }

    fn test_response() -> CompletionResponse {
        CompletionResponse {
            content: vec![],
            stop_reason: StopReason::EndTurn,
            usage: TokenUsage::default(),
            model: None,
        }
    }

    // --- GuardrailChain tests ---

    #[tokio::test]
    async fn chain_first_deny_wins() {
        let chain = GuardrailChain::new(vec![
            Arc::new(AlwaysAllowGuardrail) as Arc<dyn Guardrail>,
            Arc::new(AlwaysDenyGuardrail),
            Arc::new(AlwaysAllowGuardrail),
        ]);
        let action = chain.pre_tool(&test_call("bash")).await.unwrap();
        assert!(action.is_denied());
    }

    #[tokio::test]
    async fn chain_all_allow() {
        let chain = GuardrailChain::new(vec![
            Arc::new(AlwaysAllowGuardrail) as Arc<dyn Guardrail>,
            Arc::new(AlwaysAllowGuardrail),
        ]);
        let action = chain.pre_tool(&test_call("read")).await.unwrap();
        assert_eq!(action, GuardAction::Allow);
    }

    #[tokio::test]
    async fn chain_post_llm_first_deny_wins() {
        let chain = GuardrailChain::new(vec![
            Arc::new(AlwaysAllowGuardrail) as Arc<dyn Guardrail>,
            Arc::new(AlwaysDenyGuardrail),
        ]);
        let action = chain.post_llm(&mut test_response()).await.unwrap();
        assert!(action.is_denied());
    }

    #[tokio::test]
    async fn chain_empty_allows() {
        let chain = GuardrailChain::new(vec![]);
        let action = chain.pre_tool(&test_call("bash")).await.unwrap();
        assert_eq!(action, GuardAction::Allow);
    }

    #[tokio::test]
    async fn chain_propagates_warn() {
        let chain = GuardrailChain::new(vec![
            Arc::new(AlwaysAllowGuardrail) as Arc<dyn Guardrail>,
            Arc::new(AlwaysWarnGuardrail),
            Arc::new(AlwaysAllowGuardrail),
        ]);
        let action = chain.pre_tool(&test_call("bash")).await.unwrap();
        assert!(
            matches!(action, GuardAction::Warn { .. }),
            "expected Warn, got: {action:?}"
        );
    }

    #[tokio::test]
    async fn chain_deny_trumps_warn() {
        let chain = GuardrailChain::new(vec![
            Arc::new(AlwaysWarnGuardrail) as Arc<dyn Guardrail>,
            Arc::new(AlwaysDenyGuardrail),
        ]);
        let action = chain.pre_tool(&test_call("bash")).await.unwrap();
        assert!(action.is_denied(), "Deny should win over Warn");
    }

    #[tokio::test]
    async fn chain_post_llm_propagates_warn() {
        let chain = GuardrailChain::new(vec![
            Arc::new(AlwaysWarnGuardrail) as Arc<dyn Guardrail>,
            Arc::new(AlwaysAllowGuardrail),
        ]);
        let action = chain.post_llm(&mut test_response()).await.unwrap();
        assert!(matches!(action, GuardAction::Warn { .. }));
    }

    #[tokio::test]
    async fn chain_post_llm_propagates_pii_redaction() {
        // Issue #7 regression guard: a `PiiGuardrail` wrapped in a chain must
        // still mutate `response` in place. This pins the contract that
        // post_llm impls perform any mutation synchronously, before the
        // chain's collected futures are awaited.
        use crate::agent::guardrails::pii::{PiiAction, PiiGuardrail};
        use crate::llm::types::ContentBlock;

        let chain = GuardrailChain::new(vec![
            Arc::new(AlwaysAllowGuardrail) as Arc<dyn Guardrail>,
            Arc::new(PiiGuardrail::all_builtin(PiiAction::Redact)),
        ]);

        let mut response = CompletionResponse {
            content: vec![ContentBlock::Text {
                text: "Contact john@example.com about it".into(),
            }],
            stop_reason: StopReason::EndTurn,
            usage: TokenUsage::default(),
            model: None,
        };

        let action = chain.post_llm(&mut response).await.unwrap();
        assert!(matches!(action, GuardAction::Warn { .. }));

        let ContentBlock::Text { text } = &response.content[0] else {
            panic!("expected text block");
        };
        assert!(
            !text.contains("john@example.com"),
            "PiiGuardrail mutation didn't propagate through GuardrailChain: {text}"
        );
        assert!(text.contains("[REDACTED:email]"));
    }

    // --- WarnToDeny tests ---

    #[tokio::test]
    async fn warn_to_deny_escalates_after_threshold() {
        let inner = Arc::new(AlwaysWarnGuardrail) as Arc<dyn Guardrail>;
        let g = WarnToDeny::new(inner, 3);
        let call = test_call("bash");

        // First two: still Warn
        let a1 = g.pre_tool(&call).await.unwrap();
        assert!(matches!(a1, GuardAction::Warn { .. }));
        let a2 = g.pre_tool(&call).await.unwrap();
        assert!(matches!(a2, GuardAction::Warn { .. }));

        // Third: escalated to Deny
        let a3 = g.pre_tool(&call).await.unwrap();
        assert!(a3.is_denied());
        if let GuardAction::Deny { reason } = &a3 {
            assert!(reason.contains("3 consecutive warnings"));
        }
    }

    #[tokio::test]
    async fn warn_to_deny_resets_on_allow() {
        let inner = Arc::new(AlwaysWarnGuardrail) as Arc<dyn Guardrail>;
        let g = WarnToDeny::new(inner, 3);
        let call = test_call("bash");

        // Two warns
        g.pre_tool(&call).await.unwrap();
        g.pre_tool(&call).await.unwrap();

        // Reset (simulating an Allow from inner)
        g.consecutive_warns.store(0, Ordering::Relaxed);

        // Two more warns — should not escalate yet
        let a1 = g.pre_tool(&call).await.unwrap();
        assert!(matches!(a1, GuardAction::Warn { .. }));
        let a2 = g.pre_tool(&call).await.unwrap();
        assert!(matches!(a2, GuardAction::Warn { .. }));

        // Third → escalate
        let a3 = g.pre_tool(&call).await.unwrap();
        assert!(a3.is_denied());
    }

    #[tokio::test]
    async fn warn_to_deny_allow_resets_counter() {
        let g = WarnToDeny::new(Arc::new(AlwaysAllowGuardrail) as Arc<dyn Guardrail>, 1);
        let call = test_call("bash");
        // Set counter artificially
        g.consecutive_warns.store(5, Ordering::Relaxed);
        let action = g.pre_tool(&call).await.unwrap();
        assert_eq!(action, GuardAction::Allow);
        assert_eq!(g.consecutive_warns.load(Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn warn_to_deny_post_llm_escalates() {
        let inner = Arc::new(AlwaysWarnGuardrail) as Arc<dyn Guardrail>;
        let g = WarnToDeny::new(inner, 2);
        let mut resp = test_response();

        let a1 = g.post_llm(&mut resp).await.unwrap();
        assert!(matches!(a1, GuardAction::Warn { .. }));

        let a2 = g.post_llm(&mut resp).await.unwrap();
        assert!(a2.is_denied());
    }

    // --- ConditionalGuardrail tests ---

    #[tokio::test]
    async fn conditional_runs_when_predicate_true() {
        let g = ConditionalGuardrail::new(
            Arc::new(AlwaysDenyGuardrail) as Arc<dyn Guardrail>,
            Arc::new(|name: &str| name == "bash"),
        );
        let action = g.pre_tool(&test_call("bash")).await.unwrap();
        assert!(action.is_denied());
    }

    #[tokio::test]
    async fn conditional_skips_when_false() {
        let g = ConditionalGuardrail::new(
            Arc::new(AlwaysDenyGuardrail) as Arc<dyn Guardrail>,
            Arc::new(|name: &str| name == "bash"),
        );
        let action = g.pre_tool(&test_call("read")).await.unwrap();
        assert_eq!(action, GuardAction::Allow);
    }

    #[tokio::test]
    async fn conditional_post_tool_skips_when_false() {
        let g = ConditionalGuardrail::new(
            Arc::new(AlwaysDenyGuardrail) as Arc<dyn Guardrail>,
            Arc::new(|name: &str| name == "bash"),
        );
        let call = test_call("read");
        let mut output = ToolOutput::success("data".to_string());
        g.post_tool(&call, &mut output).await.unwrap();
        assert_eq!(output.content, "data");
    }

    #[tokio::test]
    async fn conditional_llm_hooks_always_run() {
        let g = ConditionalGuardrail::new(
            Arc::new(AlwaysDenyGuardrail) as Arc<dyn Guardrail>,
            Arc::new(|_name: &str| false),
        );
        let action = g.post_llm(&mut test_response()).await.unwrap();
        assert!(action.is_denied());
    }

    // --- Meta tests ---

    #[test]
    fn chain_meta_name() {
        let chain = GuardrailChain::new(vec![]);
        assert_eq!(chain.name(), "chain");
    }

    #[test]
    fn warn_to_deny_meta_name() {
        let g = WarnToDeny::new(Arc::new(AlwaysAllowGuardrail) as Arc<dyn Guardrail>, 3);
        assert_eq!(g.name(), "warn_to_deny");
    }

    #[test]
    fn conditional_meta_name() {
        let g = ConditionalGuardrail::new(
            Arc::new(AlwaysAllowGuardrail) as Arc<dyn Guardrail>,
            Arc::new(|_: &str| true),
        );
        assert_eq!(g.name(), "conditional");
    }
}