heartbit-core 2026.613.1

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
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
//! Built-in agent tool implementations — filesystem I/O, web, code execution, search, and more.

mod bash;
mod edit;
mod fetch_full_output;
mod file_tracker;
mod glob;
mod grep;
pub mod handoff;
mod image_generate;
mod list;
mod patch;
mod question;
mod read;
mod recall_context;
mod skill;
mod todo;
mod tts;
#[cfg(feature = "ghost-domain-config")]
pub(crate) mod twitter_post;
mod webfetch;
mod websearch;
mod write;

use std::path::PathBuf;
use std::sync::Arc;

use crate::tool::Tool;

/// Check if a path matches any protected pattern.
///
/// SECURITY (F-FS-11): the input path is normalised first
/// (`crate::workspace::normalize_path`) so trivial variants like
/// `/home/user//.ssh/key` or `/home/user/./.ssh/key` cannot bypass a
/// `~/.ssh` protection. Extension match is case-insensitive (ASCII)
/// since `secret.ENV` and `secret.env` are the same file on
/// HFS+/APFS/NTFS.
fn is_protected(path: &std::path::Path, protected: &[PathBuf]) -> bool {
    let normalized = crate::workspace::normalize_path(path);
    for pp in protected {
        if normalized.starts_with(pp) || normalized == *pp {
            return true;
        }
        if let Some(pattern) = pp.to_str()
            && let Some(pat_ext) = pattern.strip_prefix("*.")
            && let Some(ext) = normalized.extension().and_then(|e| e.to_str())
            && ext.eq_ignore_ascii_case(pat_ext)
        {
            return true;
        }
    }
    false
}

/// Like [`is_protected`], but also screens the symlink-resolved target.
///
/// SECURITY (F-FS-12): `is_protected` matches the *lexical* path only, so a
/// symlink with an innocuous name (`config.txt -> .env`, or
/// `notes.txt -> ~/.aws/credentials`) evades the denylist while still reading
/// the real secret. Canonicalizing the path resolves the symlink so the actual
/// target is screened too. Non-existent paths (new-file creates) don't
/// canonicalize — they fall back to the lexical check, which is sufficient
/// since there is no existing target to alias.
fn is_protected_resolved(path: &std::path::Path, protected: &[PathBuf]) -> bool {
    if is_protected(path, protected) {
        return true;
    }
    if let Ok(canonical) = path.canonicalize()
        && canonical != path
        && is_protected(&canonical, protected)
    {
        return true;
    }
    false
}

/// Write `bytes` to `path`, refusing to follow symlinks at the final
/// component (Unix). On non-Unix platforms, falls back to plain `tokio::fs::write`.
///
/// SECURITY (F-FS-1): combined with `CorePathPolicy::check_path_for_create`,
/// this eliminates the TOCTOU window where a parallel tool call could have
/// replaced the target path with a symlink between the policy check and the
/// open syscall.
pub(crate) async fn write_no_follow(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        let path_owned = path.to_path_buf();
        let bytes = bytes.to_vec();
        tokio::task::spawn_blocking(move || -> std::io::Result<()> {
            let mut file = std::fs::OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .custom_flags(libc::O_NOFOLLOW)
                .open(&path_owned)?;
            file.write_all(&bytes)?;
            file.sync_all()?;
            Ok(())
        })
        .await
        .map_err(|e| std::io::Error::other(format!("spawn_blocking failed: {e}")))?
    }
    #[cfg(not(unix))]
    {
        // No equivalent of O_NOFOLLOW in the std/tokio stable API on Windows.
        // The `CorePathPolicy::check_path_for_create` parent-canonicalize check
        // still applies; combined with the absence of inotify-style TOCTOU
        // primitives this is the best we can do portably here.
        tokio::fs::write(path, bytes).await
    }
}

/// Write `bytes` to `target` by walking down from the trusted, canonical
/// `root` one path component at a time, opening EACH component with
/// `O_NOFOLLOW`. No component — intermediate directory OR final file — may be
/// a symlink; the first that is fails the write.
///
/// SECURITY (F-FS-1): `write_no_follow` only guards the *trailing* component,
/// so a parallel tool call (e.g. bash dispatched alongside write via
/// `tokio::JoinSet`) could swap an *intermediate* directory for a symlink
/// after the policy check and the write would follow it outside the
/// workspace. This walk closes that window: each directory is opened
/// relative to a pinned parent fd (`openat`), so even a swap landing between
/// two steps cannot redirect us — the previously-opened fd still refers to
/// the real inode, and a freshly-swapped symlink component is rejected by
/// `O_NOFOLLOW`. The write becomes self-protecting; no check→write gap
/// remains. `target` must be a canonical path beneath `root` (the value from
/// [`crate::sandbox::CorePathPolicy::check_path_for_create`]); its
/// intermediate directories must already exist (they do, since the parent was
/// just canonicalized). On non-Unix this falls back to [`write_no_follow`].
#[cfg(unix)]
pub(crate) async fn write_beneath_root(
    root: &std::path::Path,
    target: &std::path::Path,
    bytes: &[u8],
) -> std::io::Result<()> {
    use std::ffi::CString;
    use std::io::{Error, ErrorKind, Write};
    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
    use std::os::unix::ffi::OsStrExt;
    use std::path::Component;

    let rel = target
        .strip_prefix(root)
        .map_err(|_| Error::new(ErrorKind::InvalidInput, "target is not beneath the root"))?;
    // Only plain `Normal` components are allowed — no `..`, `.`, root or
    // prefix components may sneak through.
    let mut comps: Vec<CString> = Vec::new();
    for c in rel.components() {
        match c {
            Component::Normal(p) => comps.push(
                CString::new(p.as_bytes())
                    .map_err(|_| Error::new(ErrorKind::InvalidInput, "NUL in path component"))?,
            ),
            _ => {
                return Err(Error::new(
                    ErrorKind::InvalidInput,
                    "target has a non-normal path component",
                ));
            }
        }
    }
    if comps.is_empty() {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            "target equals the root (no file component)",
        ));
    }

    let root_c = CString::new(root.as_os_str().as_bytes())
        .map_err(|_| Error::new(ErrorKind::InvalidInput, "NUL in root path"))?;
    let bytes = bytes.to_vec();

    tokio::task::spawn_blocking(move || -> std::io::Result<()> {
        // Open the trusted root directory itself. Its own ancestry is
        // operator-configured and canonical, so it is trusted; O_NOFOLLOW
        // still guards the root's final component.
        let fd = unsafe {
            libc::open(
                root_c.as_ptr(),
                libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
            )
        };
        if fd < 0 {
            return Err(Error::last_os_error());
        }
        let mut parent = unsafe { OwnedFd::from_raw_fd(fd) };

        let last = comps.len() - 1;
        for (i, comp) in comps.iter().enumerate() {
            if i == last {
                // Final component: the file itself. O_NOFOLLOW rejects an
                // existing symlink here (ELOOP); O_CREAT|O_TRUNC otherwise.
                let ffd = unsafe {
                    libc::openat(
                        parent.as_raw_fd(),
                        comp.as_ptr(),
                        libc::O_WRONLY
                            | libc::O_CREAT
                            | libc::O_TRUNC
                            | libc::O_NOFOLLOW
                            | libc::O_CLOEXEC,
                        0o644 as libc::c_uint,
                    )
                };
                if ffd < 0 {
                    return Err(Error::last_os_error());
                }
                let mut file = unsafe { std::fs::File::from_raw_fd(ffd) };
                file.write_all(&bytes)?;
                file.sync_all()?;
                return Ok(());
            }
            // Intermediate component: must be a real directory, never a
            // symlink. O_NOFOLLOW makes a swapped symlink fail (ELOOP).
            let dfd = unsafe {
                libc::openat(
                    parent.as_raw_fd(),
                    comp.as_ptr(),
                    libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
                )
            };
            if dfd < 0 {
                return Err(Error::last_os_error());
            }
            parent = unsafe { OwnedFd::from_raw_fd(dfd) };
        }
        unreachable!("loop returns on the final component");
    })
    .await
    .map_err(|e| std::io::Error::other(format!("spawn_blocking failed: {e}")))?
}

/// Non-Unix fallback: no `O_NOFOLLOW`/`openat` walk available; delegate to the
/// plain writer (the policy parent-canonicalize check still applies).
#[cfg(not(unix))]
pub(crate) async fn write_beneath_root(
    _root: &std::path::Path,
    target: &std::path::Path,
    bytes: &[u8],
) -> std::io::Result<()> {
    write_no_follow(target, bytes).await
}

/// Schema description for a `file_path` parameter, accurate to the policy
/// `resolve_path` actually enforces. The old wording ("Absolute path, or
/// relative to workspace") actively invited rejected absolute paths — a live
/// `/analyze` diagnosis caught an agent burning 7 tool errors on exactly that.
pub(crate) fn path_param_description(workspace: Option<&std::path::Path>) -> &'static str {
    if workspace.is_some() {
        "Path relative to the workspace root (absolute paths are accepted only \
         inside the workspace; outside paths are rejected — keep scratch files \
         in the workspace, not /tmp)"
    } else {
        "Absolute path, or relative to the current directory"
    }
}

/// Resolve a file path with workspace jail enforcement and protected path checks.
pub(crate) fn resolve_path(
    path: &str,
    workspace: Option<&std::path::Path>,
    protected_paths: &[PathBuf],
) -> Result<PathBuf, String> {
    let p = std::path::Path::new(path);

    match workspace {
        Some(ws) => {
            // Absolute paths are accepted ONLY when they already point inside
            // the workspace — models naturally emit the absolute form of
            // workspace paths (live finding), and the containment checks
            // below enforce exactly the same jail either way. Anything
            // outside is rejected with the actionable hint.
            let candidate = if p.is_absolute() {
                p.to_path_buf()
            } else {
                ws.join(p)
            };
            let normalized = crate::workspace::normalize_path(&candidate);
            if !normalized.starts_with(ws) {
                return Err(format!(
                    "Path '{path}' escapes the workspace root ({}). The file tools can only \
                     access paths INSIDE the workspace. Use a path inside it; for temporary \
                     or scratch work, create a subdirectory like ./scratch — that is your \
                     temporary directory (keep it out of tracked files).",
                    ws.display()
                ));
            }
            match normalized.canonicalize() {
                Ok(canonical) => {
                    if !canonical.starts_with(ws) {
                        return Err(format!(
                            "Path '{path}' resolves to {} which is outside the workspace. Use a \
                             path inside the workspace; for temporary/scratch work, a \
                             subdirectory like ./scratch is your temporary directory.",
                            canonical.display()
                        ));
                    }
                }
                Err(_) => {
                    // The target does not exist yet (a new-file create), so the
                    // whole-path canonicalize above has nothing to resolve. The
                    // lexical `starts_with` check does NOT resolve symlinks, so a
                    // symlinked INTERMEDIATE directory inside the workspace (e.g.
                    // `data -> ~/.ssh`, which a cloned repo can ship) would let
                    // the create escape the jail. Canonicalize the DEEPEST
                    // EXISTING ancestor and require it inside the workspace
                    // before allowing creation.
                    for ancestor in normalized.ancestors() {
                        if ancestor.symlink_metadata().is_err() {
                            continue; // not created yet — keep walking up
                        }
                        match ancestor.canonicalize() {
                            Ok(canonical) if canonical.starts_with(ws) => break,
                            Ok(canonical) => {
                                return Err(format!(
                                    "Path '{path}' resolves to {} which is outside the \
                                     workspace. Use a path inside the workspace; for \
                                     temporary/scratch work, a subdirectory like ./scratch is \
                                     your temporary directory.",
                                    canonical.display()
                                ));
                            }
                            Err(_) => {
                                // Exists (e.g. a dangling symlink) but cannot be
                                // resolved: containment is unprovable — fail closed.
                                return Err(format!(
                                    "Path '{path}' resolves through '{}' which cannot be \
                                     verified inside the workspace. Use a path inside the \
                                     workspace; for temporary/scratch work, a subdirectory \
                                     like ./scratch is your temporary directory.",
                                    ancestor.display()
                                ));
                            }
                        }
                    }
                }
            }
            if is_protected_resolved(&normalized, protected_paths) {
                return Err(format!("Access to '{path}' is denied (protected path)."));
            }
            Ok(normalized)
        }
        None => {
            let result = p.to_path_buf();
            if is_protected_resolved(&result, protected_paths) {
                return Err(format!("Access to '{path}' is denied (protected path)."));
            }
            Ok(result)
        }
    }
}

/// Directories that file-traversal builtins (`grep`, `glob`) skip by default.
///
/// These are gitignored build / dependency / VCS directories that can be huge
/// (a single `.d` dep file under `target/` can be ~100KB on one line) and would
/// otherwise blow up tool output and walk time. `list.rs` keeps its own richer
/// `DEFAULT_IGNORES`; this is the shared minimal set for the search builtins.
pub(crate) const SKIP_DIRS: &[&str] = &[
    "target",
    "node_modules",
    "dist",
    "build",
    ".git",
    "__pycache__",
];

/// Round `target` down to the nearest UTF-8 character boundary in `text`.
///
/// Returns the largest position `≤ target.min(text.len())` that lies on a char
/// boundary, so `&text[..pos]` is always a valid UTF-8 slice.
pub fn floor_char_boundary(text: &str, target: usize) -> usize {
    let mut pos = target.min(text.len());
    while pos > 0 && !text.is_char_boundary(pos) {
        pos -= 1;
    }
    pos
}

pub use file_tracker::FileTracker;
pub use image_generate::ImageGenerateTool;
pub use question::{
    OnQuestion, Question, QuestionOption, QuestionRequest, QuestionResponse, QuestionTool,
};
pub(crate) use todo::recite_open_todos;
pub use todo::{TodoPriority, TodoStatus, TodoStore, todo_tools};
#[cfg(feature = "ghost-domain-config")]
pub use twitter_post::TwitterCredentials;
pub use webfetch::WebFetchTool;
pub use websearch::{WebSearchTool, search_provider_label};

/// Risk classification for builtin tools.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolRisk {
    /// Safe tools: always available.
    Safe,
    /// Dangerous tools: bash. Disabled by default in daemon mode.
    Dangerous,
}

/// Configuration for creating built-in tools.
#[non_exhaustive]
pub struct BuiltinToolsConfig {
    /// Shared mtime-based read-before-write tracker.
    pub file_tracker: Arc<FileTracker>,
    /// Shared todo-list store for the `todo` tool.
    pub todo_store: Arc<TodoStore>,
    /// Optional callback that resolves structured questions raised by the agent.
    pub on_question: Option<Arc<OnQuestion>>,
    /// Optional workspace root; tools restrict path access to descendants when set.
    pub workspace: Option<PathBuf>,
    /// Enable dangerous tools (e.g. bash). Default: false.
    pub dangerous_tools: bool,
    /// Environment variable policy for bash subprocesses.
    pub env_policy: crate::workspace::EnvPolicy,
    /// File path patterns to deny access to (e.g., `*.env`, `*.pem`).
    pub protected_paths: Vec<PathBuf>,
    /// Landlock filesystem sandbox policy for bash (Linux only).
    #[cfg(all(target_os = "linux", feature = "sandbox"))]
    pub sandbox_policy: Option<crate::sandbox::SandboxPolicy>,
    /// X/Twitter credentials for the `twitter_post` builtin tool (per-tenant).
    #[cfg(feature = "ghost-domain-config")]
    pub twitter_credentials: Option<TwitterCredentials>,
    /// Optional allowlist of builtin tool names. When `Some`, only tools whose
    /// name appears in this list are returned. When `None`, all builtins are
    /// returned (backward compatible).
    pub allowlist: Option<Vec<String>>,
    /// Application-layer path policy applied to all filesystem builtins
    /// (bash, read, write, edit, patch). When set, `check_path` is called
    /// before any I/O, complementing the existing workspace + protected_paths
    /// mechanism and the Linux-only Landlock sandbox.
    pub path_policy: Option<Arc<crate::sandbox::CorePathPolicy>>,
    /// Explicit, highest-precedence skill directories given to the `skill` tool
    /// (each holding `<name>/SKILL.md`). These are searched before the
    /// conventional `.opencode/.claude/skills` walk and are the SAME dirs the
    /// Level-1 catalog is built from, so the catalog never advertises a skill the
    /// tool cannot load. Empty (default) = conventional discovery only.
    pub skill_dirs: Vec<PathBuf>,
    /// When present, registers the `fetch_full_output` / `recall_context` tools
    /// and is shared with the runner for indexing. `None` = feature off (zero
    /// overhead: tools not registered, no indexing).
    pub context_recall_store: Option<Arc<crate::agent::context_recall::ContextRecallStore>>,
}

/// Sensible default `protected_paths` patterns for filesystem builtins.
///
/// SECURITY (F-FS-9): when no workspace is configured, file builtins
/// otherwise accept arbitrary absolute paths under the process's identity.
/// The default `protected_paths` is now populated with widely-recognised
/// secret-bearing files and directories. Operators can override via
/// `BuiltinToolsConfig::protected_paths` (replaces the default).
pub fn default_protected_paths() -> Vec<PathBuf> {
    let mut v: Vec<PathBuf> = vec![
        // Patterns (matched by glob in is_protected). The leading `*.` form
        // is recognised by the existing matcher.
        PathBuf::from("*.env"),
        PathBuf::from("*.pem"),
        PathBuf::from("*.key"),
        PathBuf::from("*.p12"),
        PathBuf::from("*.pfx"),
        PathBuf::from("*.kdbx"),
        // Common system / process secret containers.
        PathBuf::from("/etc/shadow"),
        PathBuf::from("/etc/sudoers"),
        PathBuf::from("/proc/self/environ"),
    ];
    if let Some(home) = std::env::var_os("HOME") {
        let h = PathBuf::from(home);
        v.push(h.join(".ssh"));
        v.push(h.join(".aws"));
        v.push(h.join(".gnupg"));
        v.push(h.join(".config").join("heartbit"));
        v.push(h.join(".docker").join("config.json"));
        v.push(h.join(".netrc"));
    }
    v
}

impl Default for BuiltinToolsConfig {
    fn default() -> Self {
        Self {
            file_tracker: Arc::new(FileTracker::new()),
            todo_store: Arc::new(TodoStore::new()),
            on_question: None,
            workspace: None,
            dangerous_tools: false,
            // SECURITY (F-FS-2): default to the no-secrets allowlist, NOT Inherit —
            // otherwise a caller using `BuiltinToolsConfig::default()` + dangerous
            // bash (e.g. the CLI) silently leaks ANTHROPIC_API_KEY/AWS_*/GITHUB_TOKEN
            // into the agent's shell. Opt into Inherit explicitly if truly needed.
            env_policy: crate::workspace::EnvPolicy::default(),
            // SECURITY (F-FS-9): default protected paths populated.
            protected_paths: default_protected_paths(),
            #[cfg(all(target_os = "linux", feature = "sandbox"))]
            sandbox_policy: None,
            #[cfg(feature = "ghost-domain-config")]
            twitter_credentials: None,
            allowlist: None,
            path_policy: None,
            skill_dirs: Vec::new(),
            context_recall_store: None,
        }
    }
}

/// Create all built-in tools with shared state.
pub fn builtin_tools(config: BuiltinToolsConfig) -> Vec<Arc<dyn Tool>> {
    let ws = config.workspace.map(|w| w.canonicalize().unwrap_or(w));
    let pp = Arc::new(config.protected_paths);
    let path_policy = config.path_policy;
    let mut tools: Vec<Arc<dyn Tool>> = Vec::new();

    macro_rules! maybe_policy {
        ($tool:expr) => {
            if let Some(ref pp) = path_policy {
                $tool.with_path_policy(Arc::clone(pp))
            } else {
                $tool
            }
        };
    }

    if config.dangerous_tools {
        let bash_tool: Arc<dyn Tool> = match &ws {
            Some(path) => {
                let tool = bash::BashTool::with_sandbox(path.clone(), config.env_policy);
                #[cfg(all(target_os = "linux", feature = "sandbox"))]
                let tool = if let Some(policy) = config.sandbox_policy {
                    tool.with_sandbox_policy(policy)
                } else {
                    tool
                };
                Arc::new(maybe_policy!(tool))
            }
            None => Arc::new(maybe_policy!(bash::BashTool::new())),
        };
        tools.push(bash_tool);
    }

    tools.extend([
        Arc::new(maybe_policy!(read::ReadTool::new(
            config.file_tracker.clone(),
            ws.clone(),
            Arc::clone(&pp),
        ))) as Arc<dyn Tool>,
        Arc::new(maybe_policy!(write::WriteTool::new(
            config.file_tracker.clone(),
            ws.clone(),
            Arc::clone(&pp),
        ))),
        Arc::new(maybe_policy!(edit::EditTool::new(
            config.file_tracker.clone(),
            ws.clone(),
            Arc::clone(&pp),
        ))),
        // SECURITY (F-FS-4): apply the same `path_policy` to grep/glob/list
        // that read/write/edit/patch already use. Without this, an LLM with
        // no workspace configured can enumerate `/home` or grep `/etc` for
        // secrets while the path policy blocks the file builtins.
        Arc::new(maybe_policy!(grep::GrepTool::new(
            ws.clone(),
            Arc::clone(&pp)
        ))),
        Arc::new(maybe_policy!(glob::GlobTool::new(
            ws.clone(),
            Arc::clone(&pp)
        ))),
        Arc::new(maybe_policy!(list::ListTool::new(
            ws.clone(),
            Arc::clone(&pp)
        ))),
        Arc::new(maybe_policy!(patch::PatchTool::new(
            config.file_tracker.clone(),
            ws,
            Arc::clone(&pp),
        ))),
        Arc::new(webfetch::WebFetchTool::new()),
        Arc::new(websearch::WebSearchTool::new()),
        Arc::new(image_generate::ImageGenerateTool::new()),
        Arc::new(tts::TtsTool::new()),
        Arc::new(skill::SkillTool::with_dirs(config.skill_dirs.clone())),
    ]);

    let todo_tools = todo::todo_tools(config.todo_store);
    tools.extend(todo_tools);

    if let Some(on_question) = config.on_question {
        tools.push(Arc::new(question::QuestionTool::new(on_question)));
    }

    #[cfg(feature = "ghost-domain-config")]
    if let Some(creds) = config.twitter_credentials {
        tools.push(Arc::new(twitter_post::TwitterPostTool::new(creds)));
    }

    if let Some(store) = &config.context_recall_store {
        tools.push(Arc::new(fetch_full_output::FetchFullOutputTool {
            store: store.clone(),
        }));
        tools.push(Arc::new(recall_context::RecallContextTool {
            store: store.clone(),
        }));
    }

    if let Some(ref allowed) = config.allowlist {
        let set: std::collections::HashSet<&str> = allowed.iter().map(|s| s.as_str()).collect();
        tools.retain(|t| set.contains(t.definition().name.as_str()));
    }

    tools
}

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

    #[cfg(unix)]
    #[tokio::test]
    async fn write_beneath_root_writes_into_real_subdir() {
        let root = tempfile::tempdir().unwrap();
        let root_c = root.path().canonicalize().unwrap();
        std::fs::create_dir(root_c.join("sub")).unwrap();
        write_beneath_root(&root_c, &root_c.join("sub/ok.txt"), b"hi")
            .await
            .unwrap();
        assert_eq!(std::fs::read(root_c.join("sub/ok.txt")).unwrap(), b"hi");
    }

    // SECURITY (F-FS-1): the heart of the fix. An INTERMEDIATE directory
    // component swapped for a symlink (the classic TOCTOU that O_NOFOLLOW on
    // the final component alone does NOT catch) must make the write fail, with
    // nothing written outside the root.
    #[cfg(unix)]
    #[tokio::test]
    async fn write_beneath_root_refuses_symlinked_intermediate_component() {
        let root = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let root_c = root.path().canonicalize().unwrap();
        let outside_c = outside.path().canonicalize().unwrap();

        // Real intermediate dir, then swap it for a symlink pointing outside.
        std::fs::create_dir(root_c.join("sub")).unwrap();
        std::fs::remove_dir(root_c.join("sub")).unwrap();
        std::os::unix::fs::symlink(&outside_c, root_c.join("sub")).unwrap();

        let result = write_beneath_root(&root_c, &root_c.join("sub/evil.txt"), b"pwn").await;
        assert!(
            result.is_err(),
            "write through a symlinked intermediate component must be refused"
        );
        assert!(
            !outside_c.join("evil.txt").exists(),
            "write escaped the root into the symlink target"
        );
    }

    // A symlink at the FINAL component must also be refused (no overwrite of
    // whatever it points to).
    #[cfg(unix)]
    #[tokio::test]
    async fn write_beneath_root_refuses_symlinked_final_component() {
        let root = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let root_c = root.path().canonicalize().unwrap();
        let outside_c = outside.path().canonicalize().unwrap();
        let victim = outside_c.join("victim.txt");
        std::fs::write(&victim, b"original").unwrap();

        std::os::unix::fs::symlink(&victim, root_c.join("link.txt")).unwrap();
        let result = write_beneath_root(&root_c, &root_c.join("link.txt"), b"pwn").await;
        assert!(result.is_err(), "write onto a symlink must be refused");
        assert_eq!(
            std::fs::read(&victim).unwrap(),
            b"original",
            "symlink target was overwritten"
        );
    }

    #[test]
    fn floor_char_boundary_ascii() {
        assert_eq!(floor_char_boundary("hello", 3), 3);
        assert_eq!(floor_char_boundary("hello", 10), 5);
        assert_eq!(floor_char_boundary("hello", 0), 0);
    }

    #[test]
    fn floor_char_boundary_multibyte() {
        let s = "café";
        assert_eq!(s.len(), 5);
        assert_eq!(floor_char_boundary(s, 4), 3);
        assert_eq!(floor_char_boundary(s, 3), 3);
        assert_eq!(floor_char_boundary(s, 5), 5);
    }

    // Live finding (squad session): models naturally emit the ABSOLUTE form
    // of workspace paths (`/repo/landpage-crm-temp/...`) — rejecting those
    // wholesale created a recurring error class. Absolute paths are accepted
    // when they point INSIDE the workspace (same containment checks as the
    // relative form); anything outside stays rejected.
    #[test]
    fn resolve_path_absolute_inside_workspace_accepted() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        let abs = ws.join("sub").join("notes.md");
        let result = resolve_path(abs.to_str().unwrap(), Some(&ws), &[]);
        assert_eq!(result.unwrap(), abs);
    }

    #[test]
    fn resolve_path_absolute_outside_workspace_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        let result = resolve_path("/etc/passwd", Some(&ws), &[]);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("escapes the workspace"));
    }

    #[test]
    fn resolve_path_rejection_redirects_to_in_workspace_scratch() {
        // Live finding 6a265efd: models follow "a temporary directory" → /tmp,
        // the jail rejects it, and (trace seq 38→43) they REACT to the rejection
        // by relocating — but with no destination they pick wrong (repo root,
        // a symlink, tmp_crm_project…). The rejection must carry the destination:
        // a scratch subdirectory INSIDE the workspace.
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        let err = resolve_path("/tmp/crm-project/main.rs", Some(&ws), &[]).unwrap_err();
        assert!(
            err.contains("scratch"),
            "the outside-workspace rejection must name an in-workspace scratch \
             destination, not just refuse: {err}"
        );
    }

    #[test]
    fn resolve_path_absolute_sneaky_traversal_still_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        // Absolute, workspace-prefixed, but escaping via `..`.
        let sneaky = format!("{}/sub/../../etc/passwd", ws.display());
        let result = resolve_path(&sneaky, Some(&ws), &[]);
        assert!(result.is_err(), "got: {result:?}");
        assert!(result.unwrap_err().contains("escapes the workspace"));
    }

    #[test]
    fn resolve_path_absolute_passthrough_without_workspace() {
        let result = resolve_path("/absolute/path", None, &[]);
        assert_eq!(result.unwrap(), PathBuf::from("/absolute/path"));
    }

    #[cfg(unix)]
    #[test]
    fn resolve_path_symlink_to_protected_target_denied_in_workspace() {
        // S1: a workspace-internal symlink with an innocuous name (`config.txt`)
        // pointing at a protected file (`secret.env`) must be denied. The lexical
        // denylist (`*.env`) only sees `config.txt`; the fix resolves the symlink
        // target before screening.
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        std::fs::write(ws.join("secret.env"), "API_KEY=xxx").unwrap();
        std::os::unix::fs::symlink(ws.join("secret.env"), ws.join("config.txt")).unwrap();
        let protected = vec![PathBuf::from("*.env")];
        let result = resolve_path("config.txt", Some(&ws), &protected);
        assert!(
            result.is_err(),
            "symlink to a protected target must be denied, got {result:?}"
        );
        assert!(result.unwrap_err().contains("protected"));
    }

    #[cfg(unix)]
    #[test]
    fn resolve_path_symlink_to_protected_target_denied_no_workspace() {
        // S1 (no-workspace path): an innocuously-named symlink pointing at a
        // protected target must be denied even when no workspace jail is set.
        let dir = tempfile::tempdir().unwrap();
        let base = dir.path().canonicalize().unwrap();
        std::fs::write(base.join("creds.pem"), "-----BEGIN KEY-----").unwrap();
        let link = base.join("notes.txt");
        std::os::unix::fs::symlink(base.join("creds.pem"), &link).unwrap();
        let protected = vec![PathBuf::from("*.pem")];
        let result = resolve_path(link.to_str().unwrap(), None, &protected);
        assert!(
            result.is_err(),
            "symlink to a protected target must be denied without a workspace, got {result:?}"
        );
        assert!(result.unwrap_err().contains("protected"));
    }

    #[test]
    fn resolve_path_relative_with_workspace() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        let result = resolve_path("notes.md", Some(&ws), &[]);
        assert_eq!(result.unwrap(), ws.join("notes.md"));
    }

    #[test]
    fn resolve_path_relative_without_workspace() {
        let result = resolve_path("notes.md", None, &[]);
        assert_eq!(result.unwrap(), PathBuf::from("notes.md"));
    }

    #[test]
    fn resolve_path_traversal_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        let result = resolve_path("../../etc/passwd", Some(&ws), &[]);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("escapes the workspace"));
    }

    #[test]
    fn resolve_path_internal_dotdot_allowed() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        let result = resolve_path("sub/../file.txt", Some(&ws), &[]);
        assert_eq!(result.unwrap(), ws.join("file.txt"));
    }

    #[test]
    fn resolve_path_boundary_dotdot_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        let result = resolve_path("../escape", Some(&ws), &[]);
        assert!(result.is_err());
    }

    // Jail escape (audit 2026-06-09): a NEW-file write through a symlinked
    // INTERMEDIATE directory must be rejected. The whole-path canonicalize
    // check is skipped when the final component does not exist, and the
    // lexical normalize does not resolve symlinks — so `data -> /outside`
    // plus a write to `data/evil.txt` used to pass the jail.
    #[cfg(unix)]
    #[test]
    fn resolve_path_new_file_through_symlinked_intermediate_dir_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let outside_c = outside.path().canonicalize().unwrap();
        std::os::unix::fs::symlink(&outside_c, ws.join("data")).unwrap();

        let result = resolve_path("data/evil.txt", Some(&ws), &[]);
        assert!(
            result.is_err(),
            "new-file create through a symlinked intermediate dir must be rejected: {result:?}"
        );
        assert!(
            result.unwrap_err().contains("outside the workspace"),
            "rejection should use the jail wording"
        );
    }

    // Same escape, one level deeper: only an ANCESTOR of the parent exists.
    #[cfg(unix)]
    #[test]
    fn resolve_path_new_file_deep_under_symlinked_dir_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let outside_c = outside.path().canonicalize().unwrap();
        std::fs::create_dir(outside_c.join("sub")).unwrap();
        std::os::unix::fs::symlink(&outside_c, ws.join("data")).unwrap();

        let result = resolve_path("data/sub/evil.txt", Some(&ws), &[]);
        assert!(
            result.is_err(),
            "deep new-file create through a symlinked dir must be rejected: {result:?}"
        );
    }

    // A DANGLING symlink ancestor cannot be canonicalized; containment cannot
    // be proven, so creation must fail closed (create_dir_all would otherwise
    // materialize the link target outside the jail).
    #[cfg(unix)]
    #[test]
    fn resolve_path_new_file_through_dangling_symlink_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        std::os::unix::fs::symlink("/nonexistent_heartbit_jail_test", ws.join("data")).unwrap();

        let result = resolve_path("data/evil.txt", Some(&ws), &[]);
        assert!(
            result.is_err(),
            "new-file create through a dangling symlink must fail closed: {result:?}"
        );
    }

    // Regression guard: creating a new file under a NOT-YET-EXISTING real
    // subdirectory stays allowed (the deepest existing ancestor is the
    // workspace root itself).
    #[test]
    fn resolve_path_new_file_in_nonexistent_real_subdir_allowed() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        let result = resolve_path("newdir/sub/file.txt", Some(&ws), &[]);
        assert_eq!(result.unwrap(), ws.join("newdir/sub/file.txt"));
    }

    #[test]
    fn resolve_path_symlink_escape_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        let target = tempfile::tempdir().unwrap();
        std::fs::write(target.path().join("secret.txt"), "secret").unwrap();
        let link_path = ws.join("escape_link");
        #[cfg(unix)]
        std::os::unix::fs::symlink(target.path(), &link_path).unwrap();
        #[cfg(not(unix))]
        {
            return;
        }
        let result = resolve_path("escape_link/secret.txt", Some(&ws), &[]);
        assert!(
            result.is_err(),
            "symlink escape should be rejected: {:?}",
            result
        );
    }

    #[test]
    fn resolve_path_rejects_protected_extension() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        std::fs::write(ws.join("secret.env"), "SECRET=value").unwrap();
        let protected = vec![PathBuf::from("*.env")];
        let result = resolve_path("secret.env", Some(&ws), &protected);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("protected"));
    }

    #[test]
    fn resolve_path_allows_non_protected() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().canonicalize().unwrap();
        let protected = vec![PathBuf::from("*.env")];
        let result = resolve_path("notes.md", Some(&ws), &protected);
        assert!(result.is_ok());
    }

    #[test]
    fn builtin_tools_excludes_bash_by_default() {
        let tools = builtin_tools(BuiltinToolsConfig::default());
        assert!(!tools.iter().any(|t| t.definition().name == "bash"));
        assert_eq!(tools.len(), 14);
    }

    #[test]
    fn builtin_tools_includes_bash_when_dangerous() {
        let config = BuiltinToolsConfig {
            dangerous_tools: true,
            ..Default::default()
        };
        let tools = builtin_tools(config);
        assert!(tools.iter().any(|t| t.definition().name == "bash"));
        assert_eq!(tools.len(), 15);
    }

    #[test]
    fn builtin_tools_with_question_callback() {
        let config = BuiltinToolsConfig {
            dangerous_tools: true,
            on_question: Some(Arc::new(|_| {
                Box::pin(async { Ok(QuestionResponse { answers: vec![] }) })
            })),
            ..Default::default()
        };
        let tools = builtin_tools(config);
        assert_eq!(tools.len(), 16);
    }

    #[cfg(feature = "ghost-domain-config")]
    #[test]
    fn builtin_tools_includes_twitter_when_credentials_present() {
        let config = BuiltinToolsConfig {
            twitter_credentials: Some(TwitterCredentials {
                consumer_key: "ck".into(),
                consumer_secret: "cs".into(),
                access_token: "at".into(),
                access_token_secret: "ats".into(),
            }),
            ..Default::default()
        };
        let tools = builtin_tools(config);
        assert_eq!(tools.len(), 15); // 14 base + twitter_post
        assert!(tools.iter().any(|t| t.definition().name == "twitter_post"));
    }

    #[cfg(feature = "ghost-domain-config")]
    #[test]
    fn builtin_tools_excludes_twitter_when_no_credentials() {
        let tools = builtin_tools(BuiltinToolsConfig::default());
        assert!(!tools.iter().any(|t| t.definition().name == "twitter_post"));
    }

    #[test]
    fn builtin_tools_with_allowlist() {
        let config = BuiltinToolsConfig {
            allowlist: Some(vec!["websearch".into(), "webfetch".into()]),
            ..Default::default()
        };
        let tools = builtin_tools(config);
        assert_eq!(tools.len(), 2);
        let names: Vec<String> = tools.iter().map(|t| t.definition().name.clone()).collect();
        assert!(names.contains(&"websearch".to_string()));
        assert!(names.contains(&"webfetch".to_string()));
    }

    #[test]
    fn builtin_tools_empty_allowlist() {
        let config = BuiltinToolsConfig {
            allowlist: Some(vec![]),
            ..Default::default()
        };
        let tools = builtin_tools(config);
        assert_eq!(tools.len(), 0);
    }

    #[test]
    fn builtin_tools_allowlist_none_returns_all() {
        let config = BuiltinToolsConfig {
            allowlist: None,
            ..Default::default()
        };
        let tools = builtin_tools(config);
        assert_eq!(tools.len(), 14);
    }

    #[test]
    fn builtin_tools_allowlist_bash_gated() {
        // Even if allowlist includes bash, dangerous_tools=false prevents it
        let config = BuiltinToolsConfig {
            dangerous_tools: false,
            allowlist: Some(vec!["bash".into()]),
            ..Default::default()
        };
        let tools = builtin_tools(config);
        assert_eq!(tools.len(), 0);
    }

    #[test]
    fn context_recall_tools_registered_only_when_store_present() {
        use std::sync::Arc;
        // Off: no store -> tools absent.
        let off = builtin_tools(BuiltinToolsConfig::default());
        assert!(
            !off.iter()
                .any(|t| t.definition().name == "fetch_full_output")
        );
        assert!(!off.iter().any(|t| t.definition().name == "recall_context"));

        // On: store present -> both tools registered.
        let cfg = BuiltinToolsConfig {
            context_recall_store: Some(Arc::new(
                crate::agent::context_recall::ContextRecallStore::new(),
            )),
            ..Default::default()
        };
        let on = builtin_tools(cfg);
        assert!(
            on.iter()
                .any(|t| t.definition().name == "fetch_full_output")
        );
        assert!(on.iter().any(|t| t.definition().name == "recall_context"));
    }
}