omega-cognitive-kernel 0.15.1

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
#[allow(unused_imports)]
use crate::prelude::*;

#[cfg(feature = "ureq")]
use crate::audit::AuditEvent;
#[cfg(feature = "std")]
use crate::audit::AuditLog;
#[cfg(feature = "std")]
use crate::audit::DEFAULT_MAX_AUDIT_BYTES;
use crate::error::{OmegaError, Result};
use crate::types::Action;
use hashbrown::HashSet;
#[cfg(all(feature = "std", feature = "async"))]
use std::future::Future;
#[cfg(feature = "std")]
use std::io::Write;
#[cfg(feature = "std")]
use std::path::{Path, PathBuf};
#[cfg(all(feature = "std", feature = "async"))]
use std::sync::{Arc, Mutex};
#[cfg(feature = "ureq")]
use std::time::Duration;

#[cfg(all(feature = "std", feature = "async"))]
use tokio::io::AsyncWriteExt;

/// External world execution interface (synchronous).
///
/// Implement this trait to apply kernel decisions to the real world.
/// The default `SandboxedExecutor` only allows a fixed whitelist and returns
/// synthetic success payloads (no side effects).
pub trait Executor {
    /// Performs actions for this type.
    fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>>;
}

/// External world execution interface (asynchronous).
///
/// Async version of [`Executor`] for use with async runtimes (tokio).
/// Requires the `async` feature (which implies `std`).
#[cfg(all(feature = "std", feature = "async"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
pub trait AsyncExecutor {
    /// Performs item for this type.
    fn execute_async(
        &mut self,
        actions: &[Action],
    ) -> impl Future<Output = Result<Vec<serde_json::Value>>> + Send;
}

/// Adapter to use a synchronous [`Executor`] as an [`AsyncExecutor`] by running
/// the blocking call on a thread pool (tokio).
/// Completed calls return the wrapped executor so this adapter can be called
/// again. If a blocking task fails before returning it, later calls return an
/// error instead of panicking.
#[cfg(all(feature = "std", feature = "async"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
pub struct AsyncExecutorAdapter<E> {
    inner: Arc<Mutex<Option<E>>>,
}

#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
impl<E> AsyncExecutorAdapter<E> {
    /// Creates a new value of this type.
    pub fn new(executor: E) -> Self {
        Self {
            inner: Arc::new(Mutex::new(Some(executor))),
        }
    }

    /// Attempt to unwrap the inner executor without panicking.
    ///
    /// Returns `None` if another clone or in-flight task still holds the adapter.
    pub fn try_into_inner(self) -> Option<E> {
        Arc::try_unwrap(self.inner)
            .ok()
            .and_then(|mutex| mutex.into_inner().ok())
            .and_then(Option::from)
    }

    /// Unwrap the inner executor.
    ///
    /// # Panics
    ///
    /// Panics if another clone or in-flight task still holds the adapter.
    /// Prefer [`Self::try_into_inner`] when exclusive ownership is not guaranteed.
    pub fn into_inner(self) -> E {
        self.try_into_inner()
            .expect("AsyncExecutorAdapter is still in use")
    }
}

#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
impl<E: Executor + Send + 'static> AsyncExecutor for AsyncExecutorAdapter<E> {
    fn execute_async(
        &mut self,
        actions: &[Action],
    ) -> impl Future<Output = Result<Vec<serde_json::Value>>> + Send {
        let inner = Arc::clone(&self.inner);
        let actions = actions.to_vec();
        async move {
            tokio::task::spawn_blocking(move || {
                let mut guard = inner.lock().map_err(|_| {
                    OmegaError::ExecutionBlocked("executor adapter lock poisoned".into())
                })?;
                let mut executor = guard.take().ok_or_else(|| {
                    OmegaError::ExecutionBlocked(
                        "AsyncExecutorAdapter executor is unavailable after a failed invocation"
                            .into(),
                    )
                })?;
                let result = executor.execute(&actions);
                *guard = Some(executor);
                result
            })
            .await
            .map_err(|e| OmegaError::Other(anyhow::anyhow!(e)))?
        }
    }
}

/// Blanket implementation: any sync `Executor` can be used as an `AsyncExecutor`
/// by wrapping it in `AsyncExecutorAdapter`.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
impl<E: Executor + Send + 'static> From<E> for AsyncExecutorAdapter<E> {
    fn from(executor: E) -> Self {
        Self::new(executor)
    }
}

/// Data structure representing sandboxed executor.
pub struct SandboxedExecutor {
    allowed: HashSet<String>,
}

impl SandboxedExecutor {
    /// Creates a new value of this type.
    pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
        Self {
            allowed: allowed.into_iter().collect(),
        }
    }
}

impl Executor for SandboxedExecutor {
    fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>> {
        let mut results = Vec::new();
        for act in actions {
            if !act.constraints_checked {
                return Err(OmegaError::ExecutionBlocked(format!(
                    "{} (constraints not checked)",
                    act.name
                )));
            }
            if !self.allowed.contains(&act.name) {
                return Err(OmegaError::ExecutionBlocked(act.name.clone()));
            }
            results.push(serde_json::json!({
                "status": "ok",
                "action": act.name,
                "params": act.params
            }));
        }
        Ok(results)
    }
}

/// Records intended actions to a log file (and optionally stdout).
#[cfg(feature = "std")]
pub struct LoggingExecutor {
    allowed: HashSet<String>,
    log_path: Option<PathBuf>,
    echo_stdout: bool,
}

#[cfg(feature = "std")]
impl LoggingExecutor {
    /// Creates a new value of this type.
    pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
        Self {
            allowed: allowed.into_iter().collect(),
            log_path: None,
            echo_stdout: true,
        }
    }

    /// Creates or updates a value with log file.
    pub fn with_log_file(mut self, path: impl AsRef<Path>) -> Self {
        self.log_path = Some(path.as_ref().to_path_buf());
        self
    }

    /// Performs echo stdout for this type.
    pub fn echo_stdout(mut self, enabled: bool) -> Self {
        self.echo_stdout = enabled;
        self
    }
}

#[cfg(feature = "std")]
impl Executor for LoggingExecutor {
    fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>> {
        let mut results = Vec::new();
        for act in actions {
            if !act.constraints_checked {
                return Err(OmegaError::ExecutionBlocked(format!(
                    "{} (constraints not checked)",
                    act.name
                )));
            }
            if !self.allowed.contains(&act.name) {
                return Err(OmegaError::ExecutionBlocked(act.name.clone()));
            }

            let entry = serde_json::json!({
                "status": "logged",
                "action": act.name,
                "params": act.params,
                "ts": crate::now_utc_string()
            });

            if self.echo_stdout {
                println!("[LoggingExecutor] {}", entry);
            }
            if let Some(path) = &self.log_path {
                let mut file = std::fs::OpenOptions::new()
                    .create(true)
                    .append(true)
                    .open(path)
                    .map_err(|e| OmegaError::ExecutionBlocked(format!("log open: {e}")))?;
                writeln!(file, "{entry}")
                    .map_err(|e| OmegaError::ExecutionBlocked(format!("log write: {e}")))?;
            }

            results.push(entry);
        }
        Ok(results)
    }
}

/// Max response body bytes kept for `http_get` (truncate after this).
#[cfg(feature = "ureq")]
const HTTP_GET_BODY_LIMIT: usize = 2048;

/// Safe GET-only fetch for tool-gate. Only public HTTP(S) targets are allowed;
/// redirect targets are revalidated and response previews are capped at 2 KiB.
#[cfg(feature = "ureq")]
fn safe_http_get(url: &str) -> Result<serde_json::Value> {
    let input_url = url.trim();
    let parsed = crate::l0::observer::parse_http_url(input_url)?;
    let (status, bytes, truncated) = crate::l0::observer::fetch_http_sync_preview(
        parsed,
        Duration::from_secs(10),
        Duration::from_secs(5),
        HTTP_GET_BODY_LIMIT,
    )?;
    let preview = String::from_utf8_lossy(&bytes).into_owned();
    Ok(serde_json::json!({
        "status": "ok",
        "action": "http_get",
        "http_status": status,
        "url": input_url,
        "body_preview": preview,
        "truncated": truncated,
        "effect": "network_get",
    }))
}

/// Tool-call gate: allow-list + deny-list, optional audit, optional real `http_get`.
///
/// Denied tools never touch the network. When `enable_http_get` is true and the
/// tool name is `http_get` on the allow-list, a GET is performed (response truncated).
#[cfg(feature = "std")]
pub struct ToolGateExecutor {
    #[cfg_attr(not(feature = "ureq"), allow(dead_code))]
    allowed: HashSet<String>,
    #[cfg_attr(not(feature = "ureq"), allow(dead_code))]
    denied: HashSet<String>,
    audit: Option<AuditLog>,
    audit_max_bytes: u64,
    echo: bool,
    fail_closed: bool,
    /// If true, ALLOW + name `http_get` performs a real GET (`params.url`).
    enable_http_get: bool,
}

#[cfg(feature = "std")]
impl ToolGateExecutor {
    /// Creates a new value of this type.
    pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
        Self {
            allowed: allowed.into_iter().collect(),
            denied: HashSet::new(),
            audit: None,
            audit_max_bytes: DEFAULT_MAX_AUDIT_BYTES,
            echo: true,
            fail_closed: true,
            enable_http_get: false,
        }
    }

    /// Performs deny for this type.
    pub fn deny(mut self, names: impl IntoIterator<Item = String>) -> Self {
        self.denied.extend(names);
        self
    }

    /// Creates or updates a value with audit.
    pub fn with_audit(mut self, log: AuditLog) -> Self {
        self.audit = Some(log);
        self
    }

    /// Set the maximum audit JSONL file size in bytes for tool events.
    pub fn audit_max_bytes(mut self, max_bytes: u64) -> Self {
        self.audit_max_bytes = max_bytes;
        self
    }

    /// Performs echo for this type.
    pub fn echo(mut self, on: bool) -> Self {
        self.echo = on;
        self
    }

    /// Performs fail closed for this type.
    pub fn fail_closed(mut self, on: bool) -> Self {
        self.fail_closed = on;
        self
    }

    /// Enable real HTTP GET for tool name `http_get` after allow-list pass.
    pub fn enable_http_get(mut self, on: bool) -> Self {
        self.enable_http_get = on;
        self
    }

    #[cfg_attr(not(feature = "ureq"), allow(dead_code))]
    fn is_denied(&self, name: &str) -> bool {
        self.denied.contains(name) || !self.allowed.contains(name)
    }
}

#[cfg(feature = "ureq")]
impl Executor for ToolGateExecutor {
    fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>> {
        let mut results = Vec::new();
        for act in actions {
            if !act.constraints_checked {
                return Err(OmegaError::ExecutionBlocked(format!(
                    "{} (constraints not checked)",
                    act.name
                )));
            }

            if self.is_denied(&act.name) {
                let reason = if self.denied.contains(&act.name) {
                    "deny_list"
                } else {
                    "not_on_allow_list"
                };
                if let Some(log) = &self.audit {
                    log.append_with_max_bytes(
                        AuditEvent::ToolDenied {
                            tool: act.name.clone(),
                            reason: reason.into(),
                        },
                        self.audit_max_bytes,
                    )?;
                }
                if self.echo {
                    println!("[tool-gate] DENY  {} ({reason})", act.name);
                }
                if self.fail_closed {
                    return Err(OmegaError::ExecutionBlocked(format!(
                        "tool denied: {} ({reason})",
                        act.name
                    )));
                }
                results.push(serde_json::json!({
                    "status": "denied",
                    "action": act.name,
                    "reason": reason,
                }));
                continue;
            }

            if let Some(log) = &self.audit {
                log.append_with_max_bytes(
                    AuditEvent::ToolAllowed {
                        tool: act.name.clone(),
                    },
                    self.audit_max_bytes,
                )?;
            }
            if self.echo {
                println!("[tool-gate] ALLOW {}", act.name);
            }

            // Real side effect only for http_get when explicitly enabled.
            if self.enable_http_get && act.name == "http_get" {
                let url = act.params.get("url").and_then(|v| v.as_str()).unwrap_or("");
                if url.is_empty() {
                    return Err(OmegaError::ExecutionBlocked(
                        "http_get requires params.url".into(),
                    ));
                }
                if self.echo {
                    println!("[tool-gate] GET   {url}");
                }
                results.push(safe_http_get(url)?);
                continue;
            }

            results.push(serde_json::json!({
                "status": "ok",
                "action": act.name,
                "params": act.params,
                "effect": "simulated",
            }));
        }
        Ok(results)
    }
}

/// Async logging executor using tokio's async filesystem.
#[cfg(all(feature = "std", feature = "async"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
pub struct AsyncLoggingExecutor {
    allowed: HashSet<String>,
    log_path: Option<PathBuf>,
    echo_stdout: bool,
}

#[cfg(all(feature = "std", feature = "async"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
impl AsyncLoggingExecutor {
    /// Creates a new value of this type.
    pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
        Self {
            allowed: allowed.into_iter().collect(),
            log_path: None,
            echo_stdout: true,
        }
    }

    /// Creates or updates a value with log file.
    pub fn with_log_file(mut self, path: impl AsRef<Path>) -> Self {
        self.log_path = Some(path.as_ref().to_path_buf());
        self
    }

    /// Performs echo stdout for this type.
    pub fn echo_stdout(mut self, enabled: bool) -> Self {
        self.echo_stdout = enabled;
        self
    }
}

#[cfg(all(feature = "std", feature = "async"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
impl AsyncExecutor for AsyncLoggingExecutor {
    fn execute_async(
        &mut self,
        actions: &[Action],
    ) -> impl Future<Output = Result<Vec<serde_json::Value>>> + Send {
        let allowed = self.allowed.clone();
        let log_path = self.log_path.clone();
        let echo_stdout = self.echo_stdout;
        let actions = actions.to_vec();
        async move {
            let mut results = Vec::new();
            for act in actions {
                if !act.constraints_checked {
                    return Err(OmegaError::ExecutionBlocked(format!(
                        "{} (constraints not checked)",
                        act.name
                    )));
                }
                if !allowed.contains(&act.name) {
                    return Err(OmegaError::ExecutionBlocked(act.name.clone()));
                }

                let entry = serde_json::json!({
                    "status": "logged",
                    "action": act.name,
                    "params": act.params,
                    "ts": crate::now_utc_string()
                });

                if echo_stdout {
                    println!("[AsyncLoggingExecutor] {}", entry);
                }

                if let Some(path) = &log_path {
                    let mut file = tokio::fs::OpenOptions::new()
                        .create(true)
                        .append(true)
                        .open(path)
                        .await
                        .map_err(|e| OmegaError::ExecutionBlocked(format!("log open: {e}")))?;
                    let line = format!("{}\n", entry);
                    file.write_all(line.as_bytes())
                        .await
                        .map_err(|e| OmegaError::ExecutionBlocked(format!("log write: {e}")))?;
                }

                results.push(entry);
            }
            Ok(results)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::Action;
    use alloc::collections::BTreeMap;

    fn action(name: &str, checked: bool) -> Action {
        Action {
            name: name.into(),
            params: BTreeMap::new(),
            constraints_checked: checked,
        }
    }

    #[test]
    fn allows_whitelisted_checked_action() {
        let mut ex = SandboxedExecutor::new(vec!["observe".into()]);
        let res = ex.execute(&[action("observe", true)]);
        assert!(res.is_ok());
        assert_eq!(res.unwrap().len(), 1);
    }

    #[test]
    fn blocks_unchecked_action() {
        let mut ex = SandboxedExecutor::new(vec!["observe".into()]);
        let res = ex.execute(&[action("observe", false)]);
        assert!(res.is_err());
    }

    #[test]
    fn blocks_non_whitelisted_action() {
        let mut ex = SandboxedExecutor::new(vec!["observe".into()]);
        let res = ex.execute(&[action("delete_everything", true)]);
        assert!(res.is_err());
    }

    #[cfg(feature = "async")]
    struct CountingExecutor {
        calls: usize,
    }

    #[cfg(feature = "async")]
    impl Executor for CountingExecutor {
        fn execute(&mut self, _actions: &[Action]) -> Result<Vec<serde_json::Value>> {
            self.calls += 1;
            Ok(vec![serde_json::json!({"call": self.calls})])
        }
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_executor_adapter_supports_consecutive_calls() {
        let mut adapter = AsyncExecutorAdapter::new(CountingExecutor { calls: 0 });
        let actions = [action("observe", true)];

        let first = adapter.execute_async(&actions).await.unwrap();
        let second = adapter.execute_async(&actions).await.unwrap();

        assert_eq!(first[0]["call"], 1);
        assert_eq!(second[0]["call"], 2);
        assert_eq!(adapter.into_inner().calls, 2);
    }

    #[test]
    fn logging_executor_records_action() {
        let mut ex = LoggingExecutor::new(vec!["observe".into()]).echo_stdout(false);
        let res = ex.execute(&[action("observe", true)]).unwrap();
        assert_eq!(res[0]["status"], "logged");
        assert_eq!(res[0]["action"], "observe");
    }

    #[test]
    #[cfg(all(feature = "std", feature = "async"))]
    fn async_adapter_can_execute_repeatedly() {
        let runtime = tokio::runtime::Runtime::new().unwrap();
        runtime.block_on(async {
            let mut executor =
                AsyncExecutorAdapter::new(SandboxedExecutor::new(vec!["observe".into()]));
            for _ in 0..2 {
                let results = executor
                    .execute_async(&[action("observe", true)])
                    .await
                    .unwrap();
                assert_eq!(results.len(), 1);
            }
            let _ = executor.into_inner();
        });
    }

    #[test]
    #[cfg(all(feature = "std", feature = "async"))]
    fn async_logging_propagates_open_failure() {
        let blocker =
            std::env::temp_dir().join(format!("omega-async-log-blocker-{}", crate::new_uuid()));
        std::fs::write(&blocker, b"not a directory").unwrap();
        let mut executor = AsyncLoggingExecutor::new(vec!["observe".into()])
            .with_log_file(blocker.join("actions.jsonl"))
            .echo_stdout(false);
        let runtime = tokio::runtime::Runtime::new().unwrap();
        let error = runtime
            .block_on(executor.execute_async(&[action("observe", true)]))
            .unwrap_err();
        assert!(error.to_string().contains("log open"), "{error}");
        let _ = std::fs::remove_file(blocker);
    }

    #[test]
    #[cfg(feature = "ureq")]
    fn tool_gate_denies_dangerous_tool() {
        use crate::audit::AuditLog;
        use std::env::temp_dir;
        let dir = temp_dir().join(format!(
            "omega-gate-{}-{}",
            std::process::id(),
            crate::new_uuid()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("state.json");
        let audit = AuditLog::beside_state(&path);
        let mut gate = ToolGateExecutor::new(["search_docs".into(), "http_get".into()])
            .deny(["delete_database".into(), "shell_exec".into()])
            .with_audit(audit)
            .echo(false)
            .fail_closed(true);
        assert!(gate.execute(&[action("search_docs", true)]).is_ok());
        assert!(gate.execute(&[action("delete_database", true)]).is_err());
        let rows = AuditLog::beside_state(&path).read_all().unwrap();
        assert!(rows.len() >= 2);
        let _ = std::fs::remove_file(AuditLog::beside_state(&path).path);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    #[cfg(feature = "ureq")]
    fn tool_gate_propagates_audit_size_limit_errors_for_allowed_and_denied_tools() {
        use crate::audit::AuditLog;
        use std::env::temp_dir;

        let dir = temp_dir().join(format!(
            "omega-gate-limit-{}-{}",
            std::process::id(),
            crate::new_uuid()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let state_path = dir.join("state.json");
        let audit = AuditLog::beside_state(&state_path);
        let mut gate = ToolGateExecutor::new(["safe_tool".into()])
            .deny(["blocked_tool".into()])
            .with_audit(audit)
            .audit_max_bytes(0)
            .echo(false)
            .fail_closed(false);

        let allowed_error = gate.execute(&[action("safe_tool", true)]).unwrap_err();
        assert!(
            allowed_error
                .to_string()
                .contains("audit log size limit exceeded"),
            "{allowed_error}"
        );
        let denied_error = gate.execute(&[action("blocked_tool", true)]).unwrap_err();
        assert!(
            denied_error
                .to_string()
                .contains("audit log size limit exceeded"),
            "{denied_error}"
        );
        assert!(!dir.join("audit.jsonl").exists());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    #[cfg(feature = "ureq")]
    fn http_get_bounds_large_response_preview() {
        use std::io::Write;
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let server = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let mut request = [0_u8; 1024];
            let _ = std::io::Read::read(&mut stream, &mut request);
            stream
                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 8192\r\nConnection: close\r\n\r\n")
                .unwrap();
            stream.write_all(&[b'x'; 8192]).unwrap();
        });

        let url = crate::l0::observer::parse_http_url(&format!("http://{address}/large")).unwrap();
        let (status, body, truncated) = crate::l0::observer::fetch_http_sync_preview_with_resolver(
            url,
            Duration::from_secs(2),
            Duration::from_millis(300),
            HTTP_GET_BODY_LIMIT,
            move |_, _| Ok(vec![address]),
        )
        .unwrap();
        server.join().unwrap();
        assert_eq!(status, 200);
        assert_eq!(body.len(), HTTP_GET_BODY_LIMIT);
        assert!(truncated);
    }

    #[test]
    #[cfg(feature = "ureq")]
    fn http_get_rejects_private_and_metadata_ip_literals() {
        for url in [
            "http://127.0.0.1/",
            "http://10.0.0.1/",
            "http://169.254.169.254/latest/meta-data/",
            "http://[::1]/",
        ] {
            assert!(safe_http_get(url).is_err(), "accepted unsafe target {url}");
        }
    }

    #[test]
    #[cfg(feature = "ureq")]
    fn http_get_rejects_credentialed_urls() {
        assert!(safe_http_get("http://user:password@example.com/").is_err());
    }

    #[test]
    #[cfg(feature = "ureq")]
    fn http_get_rejects_non_http_scheme() {
        let mut gate = ToolGateExecutor::new(["http_get".into()])
            .enable_http_get(true)
            .echo(false);
        let mut params = BTreeMap::new();
        params.insert("url".into(), serde_json::json!("file:///etc/passwd"));
        let act = Action {
            name: "http_get".into(),
            params,
            constraints_checked: true,
        };
        assert!(gate.execute(&[act]).is_err());
    }
}