supercode-harness 0.4.19

The optional native Supercode agent and tool harness
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
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
//! Tools the agent can call.
//!
//! A [`Tool`] is a named capability with a JSON-Schema input and an async
//! `execute`. The [`ToolRegistry`] holds the set offered to a model; built-ins
//! cover file read/write/edit, directory listing, glob, content search, and
//! shell execution. Every tool can be disabled or re-described per
//! [`crate::Config`], so the capability surface is entirely yours to shape.

pub(crate) mod builtins;
pub mod clock;
pub mod context_budget;
pub mod convert;
pub mod image_gen;
pub mod plan_mode;
pub mod question;
mod skill;
pub(crate) mod tiers;

use std::collections::HashMap;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use async_trait::async_trait;

use crate::config::Config;
use crate::error::Result;
use crate::modules::ModuleId;

pub use builtins::{
    ApplyPatchTool, BashTool, EditFileTool, GlobTool, ListDirTool, PersistentShellTool,
    ReadFileTool, SearchTool, UpdatePlanTool, ViewImageTool, WebFetchTool, WebSearchTool,
    WriteFileTool, DEFAULT_WEB_SEARCH_URL, WEB_CACHE_DIR_ENV, WEB_SEARCH_URL_ENV,
};
// BP-3 (§2 modules 6/8 + the catalog's clock, context-budget and image rows):
// the new core tools. Each is a plain `Tool` registered by
// `ToolRegistry::from_config` under its own preset gate, so `supercode
// harness parity`'s `tool` evidence resolves against the real registry.
pub use clock::{CurrentTimeTool, SleepTool, CURRENT_TIME, MAX_SLEEP_SECS, SLEEP};
pub use context_budget::{
    ContextBudget, GetContextRemainingTool, NewContextRequest, NewContextTool,
    GET_CONTEXT_REMAINING, NEW_CONTEXT,
};
pub use image_gen::{ImageGenTool, IMAGE_GEN};
pub use plan_mode::{
    EnterPlanModeTool, ExitPlanModeTool, PlanModeState, ENTER_PLAN_MODE, EXIT_PLAN_MODE,
};
pub use question::{
    AskUserTool, Question, QuestionOption, UserQuestionHandler, ASK_USER, REQUEST_USER_INPUT,
};
// P5-1 F4: `crate::agent`'s permissions gate needs to check an
// `apply_patch` envelope's write surface against `protected_paths` — not
// part of the crate's public tool-registration API, so `pub(crate)` rather
// than folded into the `pub use` list above.
pub(crate) use builtins::patch_target_paths;
// P5-6 (§2 module 4 `tools.background`): `crate::agent::Agent`'s
// `background_exec` intrinsic reuses `BashTool`'s own sandboxed-spawn
// builder rather than duplicating it — see that function's doc comment.
pub(crate) use builtins::build_sandboxed_sh;
// BP-2 (catalog:32 "+Bash-view exemptions"): the narrow single-file-view
// parser `BashTool` consults, exposed to the crate so the parity tests can
// pin the exemption's edges without spawning a shell per case.
#[cfg(test)]
pub(crate) use builtins::bash_view_target;
pub use skill::{SkillTool, SKILL_TOOL};
pub use tiers::{minify as minify_tool_schema, SchemaTier};
// `SandboxPolicy` and `ToolContext` are defined below in this module.

/// P4c (COMPOSABLE-HARNESS-DESIGN.md S1.2/S3.1 `core.tools.read_file
/// multimodal`, S1.2 `view_image`): the sentinel prefix a tool's plain
/// `String` result carries when it is actually an image data URL rather
/// than ordinary text — `Agent::run_loop` detects this prefix (before
/// `cap_tool_output` ever sees it) and builds a `content_parts` image
/// block instead of a plain-text tool result. Using a control character
/// (`\u{1}`, SOH) as part of the marker keeps a false-positive collision
/// with real tool output astronomically unlikely without requiring a new
/// `Tool::execute` return type across all ten built-ins (an L-sized
/// trait-signature change this S-sized catalog item does not call for).
pub const MULTIMODAL_IMAGE_MARKER: &str = "\u{1}SUPERCODE_IMAGE_DATA_URL\u{1}";

/// P4c (S1.2 `core.tools.read_file.multimodal` / `view_image`): recognized
/// image file extensions (lowercase, no dot) — the same set CC/pi treat as
/// "images" for multimodal read (catalog D1 row 2's `✓*`/`✓*` variants).
pub const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp"];

/// Whether `path`'s extension is a recognized image type (case-insensitive).
pub fn is_image_path(path: &Path) -> bool {
    path.extension()
        .and_then(|e| e.to_str())
        .map(|e| IMAGE_EXTENSIONS.contains(&e.to_ascii_lowercase().as_str()))
        .unwrap_or(false)
}

/// The `image/<subtype>` MIME type for a recognized image extension, for
/// the `data:` URL — falls back to `png` for anything [`is_image_path`]
/// didn't already gate (defensive; never actually hit through
/// [`is_image_path`]'s own extension list).
pub fn image_mime_for(path: &Path) -> &'static str {
    match path
        .extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_ascii_lowercase())
        .as_deref()
    {
        Some("jpg") | Some("jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("webp") => "image/webp",
        Some("bmp") => "image/bmp",
        _ => "image/png",
    }
}

/// P4c (S1.2 `core.tools.edit_file.notebook_aware`): the extension that
/// gates `EditFileTool`'s Jupyter cell-surgery branch.
pub const NOTEBOOK_EXTENSION: &str = "ipynb";

/// P4c (S2 module 5 `tools.web`, S2.1 dep "network sandbox rules", S17):
/// the network-domain policy a caller (SDK embedder) may install on a
/// [`ToolContext`] so [`crate::tools::WebFetchTool`]/[`crate::tools::WebSearchTool`]
/// respect it — see [`ToolContext::check_network`]. `None` on the context
/// (the default) means no policy is configured, matching today's honest
/// gap (no P5 `capabilities.permissions.sandbox.network` engine exists
/// yet, C3 — tracked, not hidden).
#[derive(Debug, Clone, Default)]
pub struct NetworkPolicy {
    /// Whether the policy is enforced at all. `false` behaves exactly like
    /// `None` on the context.
    pub enabled: bool,
    /// If non-empty, only these hosts are allowed. BP-10: matched as
    /// `crate::config::glob_match` patterns through the one rule engine
    /// (`domain(<entry>)`), so a bare hostname still matches exactly as
    /// before and `*.example.com` now works too.
    pub allow_domains: Vec<String>,
    /// These hosts are always denied, even if also present in
    /// `allow_domains`. Same pattern treatment as [`Self::allow_domains`].
    pub deny_domains: Vec<String>,
}

impl NetworkPolicy {
    /// BP-10 (catalog row "Allow/ask/deny rule language", the DOMAIN
    /// subject): this policy's two lists expressed IN the rule algebra —
    /// a [`crate::permissions::RuleSet`] of `domain(...)` patterns plus
    /// the baseline [`crate::permissions::Decision`] a host matching
    /// nothing gets.
    ///
    /// An allowlist is not a deny rule: in a deny→ask→allow FIRST-MATCH
    /// engine "only these hosts" is expressed by the BASELINE being
    /// `Deny`, with each allowed host in the `allow` tier — a
    /// `domain(*)` deny rule would (correctly, per tier priority) also
    /// swallow the allowlist. Empty `allow_domains` keeps the baseline
    /// `Allow`, which is why a pure denylist behaves exactly as it did
    /// before this translation existed.
    pub fn domain_rule_set(&self) -> (crate::permissions::RuleSet, crate::permissions::Decision) {
        let pattern = |d: &String| format!("domain({d})");
        let default = if self.allow_domains.is_empty() {
            crate::permissions::Decision::Allow
        } else {
            crate::permissions::Decision::Deny
        };
        (
            crate::permissions::RuleSet {
                deny: self.deny_domains.iter().map(pattern).collect(),
                ask: Vec::new(),
                allow: self.allow_domains.iter().map(pattern).collect(),
            },
            default,
        )
    }
}

/// BP-2 (catalog:32 "Edit refuses unless file was read (and unchanged)
/// this conversation"): how a path stands relative to the model's own most
/// recent read of it — see [`ToolContext::read_state`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadState {
    /// No read of this path has been recorded this conversation.
    NeverRead,
    /// Read, but the file's bytes have changed since (or it is no longer
    /// readable): the model's view is stale.
    Stale,
    /// Read, and the file is byte-identical to what the model saw.
    Fresh,
}

/// BP-2: the content stamp behind [`ReadState`] — blake3 (already a
/// dependency) truncated to 64 bits, which is a staleness detector, not a
/// security boundary: an adversary who can rewrite the file can rewrite the
/// edit too, so collision resistance beyond "different content looks
/// different" buys nothing here.
fn content_hash(bytes: &[u8]) -> u64 {
    let digest = blake3::hash(bytes);
    let b = digest.as_bytes();
    u64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]])
}

/// Filesystem confinement applied to write-capable tools — the analog of
/// Codex's `read-only` / `workspace-write` / `danger-full-access` sandbox modes.
///
/// Enforced at the tool layer for file operations (`write_file`, `edit_file`,
/// `apply_patch`). Note: this confines the *file tools*; it does not OS-sandbox
/// arbitrary subprocesses (`bash`/`shell`) — true process isolation needs
/// platform primitives (seatbelt/landlock) and is a separate concern. Use
/// [`shell_sandbox_unenforceable`] as the runtime check for whether that gap
/// applies to the current platform and enabled tools.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SandboxPolicy {
    /// No file writes are permitted by the file tools.
    ReadOnly,
    /// Writes are permitted only inside the working directory.
    WorkspaceWrite,
    /// No confinement (default — preserves prior behavior).
    #[default]
    DangerFullAccess,
}

/// P5-9 (design §2 module 20 `checkpoint`, §2.1 D-5 "write-path
/// interception seam shared with `formatters`"): the ONE well-defined
/// interception point around every file-mutating built-in tool
/// (`write_file`/`edit_file`/`apply_patch`) — installed on
/// [`ToolContext::write_observer`], `None` by default. Both hooks fire
/// AFTER [`ToolContext::check_write`] has already approved the call (so an
/// observer never sees a write the sandbox itself refused) and BEFORE/AFTER
/// the actual mutation:
/// - [`Self::before_write`] — pre-image capture. `crate::checkpoint`'s
///   [`crate::checkpoint::CheckpointObserver`] is the only implementation
///   today: it snapshots `path`'s current on-disk content (or records "did
///   not exist") so a later `checkpoint restore` can undo the write.
/// - [`Self::after_write`] — post-write. A true no-op in every
///   implementation shipped so far; reserved for `formatters` (P5-11,
///   design line 510 "shared seam with checkpoint") to run format-on-write
///   from, without needing a SECOND interception point wired through the
///   same three tools.
///
/// `None` (the default — `[capabilities.checkpoint]` off and no formatters
/// module yet) means neither hook is ever consulted: every write-tool
/// call-site's observer check is `if let Some(obs) = &ctx.write_observer`,
/// a branch that's simply never taken, so behavior is byte-identical to
/// before this seam existed.
///
/// P5-11 (§2 modules 28/29 `lsp`/`formatters`, C10): `async_trait` (rather
/// than the plain sync methods P5-9 originally shipped) because BOTH new
/// observers need real async I/O in `after_write` — `formatters` spawns and
/// awaits a subprocess, `lsp` writes/reads framed JSON-RPC over a child's
/// stdio — and neither can block the tokio runtime thread the way a
/// synchronous call from inside an already-`async fn execute()` would.
/// `CheckpointObserver`'s own hooks stay synchronous *internally* (plain
/// blocking `std::fs` calls); wrapping them in `async fn` changes nothing
/// observable for it, since that blocking work already ran on the calling
/// task before this signature changed. `after_write` now RETURNS
/// `Option<String>` — an annotation to append to the calling tool's result
/// string (formatter diff-back content, or LSP diagnostics) — `None` when
/// the observer has nothing to report, which is the only value
/// `CheckpointObserver::after_write` (still a no-op) ever returns, keeping
/// today's tool-result text byte-identical whenever checkpoint is the only
/// observer installed.
#[async_trait]
pub trait WriteObserver: Send + Sync + std::fmt::Debug {
    /// `path` (already resolved + sandbox-checked) is about to be
    /// created/overwritten/deleted. Implementations must be fast and must
    /// never propagate a failure as a tool error — a capture failure should
    /// degrade the OBSERVER (e.g. disable itself with a one-time warning),
    /// never block or fail the user's actual edit.
    async fn before_write(&self, path: &Path);
    /// `path` was just written/deleted successfully. Not called when the
    /// tool call itself failed (e.g. the write errored before completing).
    /// Returns an optional annotation for the calling tool's result text —
    /// see the trait doc comment above.
    async fn after_write(&self, path: &Path) -> Option<String>;
}

/// P5-11 (§2 modules 28/29, D-5 "shared write-path interception seam"): an
/// ORDERED chain of [`WriteObserver`]s installed as a single
/// `ToolContext::write_observer`, so the ONE seam P5-9 built keeps
/// supporting exactly one call site per tool while now composing multiple
/// concerns. Order is caller-determined (`crate::agent::build_tool_context`
/// builds it `checkpoint → formatters → lsp`, design's own required
/// ordering: checkpoint must capture the PRE-image before anything mutates
/// the file; formatters must run before lsp so diagnostics reflect the
/// FINAL, formatted file, not the model's pre-format draft).
/// `before_write` runs every observer in order; `after_write` runs every
/// observer in order too and joins any non-empty annotations with a blank
/// line, so a formatter's diff-back and an LSP diagnostics block can both
/// appear in one tool result without one silently discarding the other.
#[derive(Debug)]
pub struct WriteObserverChain(Vec<Arc<dyn WriteObserver>>);

impl WriteObserverChain {
    /// Build a chain that runs `observers` in order for both hooks.
    pub fn new(observers: Vec<Arc<dyn WriteObserver>>) -> Self {
        WriteObserverChain(observers)
    }
}

#[async_trait]
impl WriteObserver for WriteObserverChain {
    async fn before_write(&self, path: &Path) {
        for obs in &self.0 {
            obs.before_write(path).await;
        }
    }
    async fn after_write(&self, path: &Path) -> Option<String> {
        let mut notes: Vec<String> = Vec::new();
        for obs in &self.0 {
            if let Some(note) = obs.after_write(path).await {
                if !note.is_empty() {
                    notes.push(note);
                }
            }
        }
        if notes.is_empty() {
            None
        } else {
            Some(notes.join("\n\n"))
        }
    }
}

/// Ambient context passed to every tool invocation.
#[derive(Debug, Clone)]
pub struct ToolContext {
    /// The working directory tools resolve relative paths against.
    pub cwd: PathBuf,
    /// BP-10 (catalog row "Additional working directories", cc/cx
    /// `--add-dir`): extra roots granted BEYOND [`Self::cwd`], from
    /// `core.additional_dirs`/`--add-dir`. These are real grants, not
    /// discovery hints: [`Self::check_write`] treats a path under one of
    /// them as inside the workspace, the OS backstop adds each to the
    /// subprocess's writable set (`crate::sandbox::apply_linux_confinement`
    /// on Linux, the seatbelt profile on macOS), and the permissions
    /// engine's path rules are evaluated relative to each root as well as
    /// to `cwd` (so a `write(.git/**)` floor still covers an extra root's
    /// own `.git`). Empty (the default) is byte-identical to confining
    /// everything to `cwd` alone.
    pub extra_roots: Vec<PathBuf>,
    /// Filesystem confinement for write-capable tools.
    pub sandbox: SandboxPolicy,
    /// P4c (S1.2 `core.tools.read_file.multimodal`): whether `read_file`
    /// (and `view_image`, unconditionally) returns a recognized image file
    /// as a model-visible image content block. `false` (the default) is
    /// byte-identical to today's UTF-8-lossy-decode behavior.
    pub multimodal_read: bool,
    /// BP-2 (S1.2 `core.tools.read_file.line_numbers`, catalog:26): whether
    /// `read_file` prefixes every returned line with its 1-based file line
    /// number and a tab (`cat -n`), numbered from the requested `offset`.
    /// `false` (the default) returns the raw slice, as today.
    pub read_line_numbers: bool,
    /// P4c (S1.2 `core.tools.edit_file.require_read_before_edit`, UNIQUE CC
    /// row): whether `edit_file` refuses a path not yet read this
    /// conversation. `false` (the default) is byte-identical to today's
    /// behavior — [`Self::read_paths`] is simply never consulted.
    pub require_read_before_edit: bool,
    /// P4c: canonicalized paths `read_file` has successfully read so far
    /// this conversation — shared (via `Arc<Mutex<_>>`) across every clone
    /// of this context, since `Agent` constructs one `ToolContext` at
    /// startup and reuses it for every tool call. Consulted by `EditFileTool`
    /// only when [`Self::require_read_before_edit`] is `true`.
    ///
    /// BP-2 (catalog:32 "Edit refuses unless file was read **and
    /// unchanged** this conversation"): the value is the content hash AT
    /// READ TIME, so a file modified behind the model's back after its read
    /// is detected as STALE instead of editing cleanly against a view that
    /// no longer exists — see [`Self::read_state`].
    pub read_paths: Arc<Mutex<HashMap<PathBuf, u64>>>,
    /// P4c (S1.2 `core.tools.edit_file.notebook_aware`, UNIQUE CC row
    /// "NotebookEdit"): whether `edit_file` accepts Jupyter cell
    /// replace/insert/delete operations against a `.ipynb` target. `false`
    /// (the default) is byte-identical to today's exact-string-replace-only
    /// behavior.
    pub notebook_aware: bool,
    /// P4c (S1.2 `core.shell_env_snapshot`): the user's captured
    /// interactive-shell environment, if [`crate::Config::shell_env_snapshot`]
    /// is on — `BashTool`/`PersistentShellTool` merge this into the spawned
    /// process's environment. `None` (the default) is byte-identical to
    /// today's behavior: no extra environment is injected.
    pub shell_env: Option<Arc<HashMap<String, String>>>,
    /// P4c (S1.4 `core.nested_instructions`, deferred from P4b): whether a
    /// file-touching tool injects an as-yet-unseen subdirectory's own
    /// `CLAUDE.md`/`AGENTS.md` into its result the first time a path under
    /// it is touched. `false` (the default) is byte-identical to today's
    /// behavior.
    pub nested_instructions: bool,
    /// P4c: subdirectories (relative to [`Self::cwd`]) whose nested
    /// instructions have already been injected this conversation — shared
    /// across clones, same rationale as [`Self::read_paths`]. Consulted only
    /// when [`Self::nested_instructions`] is `true`.
    pub injected_instruction_dirs: Arc<Mutex<HashSet<PathBuf>>>,
    /// BP-5 (catalog D2 "Path-scoped rules", cc§2 `.claude/rules` `paths:`):
    /// the rule files this config loaded whose `paths:` selector holds them
    /// back until a matching file is touched. Empty (and inert) unless
    /// `[core.path_rules]` is on.
    pub path_rules: Arc<Vec<crate::path_rules::RuleFile>>,
    /// BP-5: which of [`Self::path_rules`] have already been injected this
    /// conversation — one injection per rule, the same de-duplication
    /// [`Self::injected_instruction_dirs`] gives nested instructions.
    pub injected_rule_files: Arc<Mutex<HashSet<PathBuf>>>,
    /// P4c (S2 module 5 `tools.web`, S17): the network-domain policy
    /// `web_fetch`/`web_search` must respect, if one is configured. `None`
    /// (the default) means no policy is enforced — see [`NetworkPolicy`]'s
    /// doc comment for the honest-gap rationale.
    pub network_policy: Option<NetworkPolicy>,
    /// BP-10 (catalog row "Allow/ask/deny rule language"): the
    /// CONFIG-DECLARED rule set (`capabilities.permissions.rules.*`, the
    /// same arrays `crate::agent::Agent`'s dispatch gate evaluates), so a
    /// `domain(...)` rule written there is enforced by the ONE engine at
    /// the network surface too — see [`Self::check_network`]. `None` (the
    /// default, and whenever `capabilities.permissions` is off) leaves the
    /// network check reading `network_policy`'s own two lists alone,
    /// byte-identical to before.
    pub permission_rules: Option<Arc<crate::permissions::RuleSet>>,
    /// P4e (S3.1 `core.tools.bash.timeout_secs`, S14): the DEFAULT
    /// execution timeout (seconds) `BashTool::execute` falls back to when a
    /// model-issued call carries no `timeout_ms` argument of its own -- see
    /// `crate::config::ToolOverride::timeout_secs`. `None` (the default) is
    /// byte-identical to today's behavior: `BashTool`'s built-in
    /// `DEFAULT_BASH_TIMEOUT_MS` (120s) stands.
    pub bash_timeout_secs: Option<u64>,
    /// P5-9 (§2 module 20, D-5 shared write-path interception seam) — see
    /// [`WriteObserver`]'s doc comment. `None` (the default) is a true
    /// no-op: every write-tool call site's `if let Some(obs) = ...` branch
    /// is simply never taken.
    pub write_observer: Option<Arc<dyn WriteObserver>>,
    /// P5-10 (§2 module 12 `permissions.sandbox`): whether the OS-level
    /// backstop (Landlock/seatbelt) is engaged for the `bash`/`shell`
    /// subprocess — see `crate::sandbox::os_sandbox_active`. `None` (the
    /// default) preserves the pre-P5-10 trigger (confine whenever
    /// [`Self::sandbox`] isn't [`SandboxPolicy::DangerFullAccess`]).
    pub sandbox_os_enabled: Option<bool>,
    /// P5-10 (§2 module 12, `escalation`): what to do when a confining fs
    /// tier can't actually be enforced on this platform/kernel — see
    /// `crate::sandbox::SandboxEscalation`. Defaults to `Deny`
    /// (fail-closed).
    pub sandbox_escalation: crate::sandbox::SandboxEscalation,
    /// P5-10 (§2 module 12, `env_policy`): child-process environment
    /// sanitization for the spawned subprocess — see
    /// `crate::sandbox::SandboxEnvPolicy`. Defaults to `Inherit`
    /// (byte-identical to pre-P5-10 behavior).
    pub sandbox_env_policy: crate::sandbox::SandboxEnvPolicy,
    /// P5-10 (§2 module 12, `escalation = "ask"` → `permissions.approvals`,
    /// P5-1): the ambient handler `crate::sandbox::decide_fs` consults for
    /// an `ask`-tier sandbox-unenforceable decision. `None` (the default —
    /// no handler installed) is fail-closed, same posture as the P5-1 rule
    /// engine's own `Ask` tier with no handler.
    pub sandbox_approval_handler: Option<crate::sandbox::SandboxApprovalHandler>,
    /// BP-3 (§2 module 6 `tools.question`): the door `ask_user` asks the
    /// human through — the SAME `elicitation/create` handler the design
    /// names as "the `tools.question` surface's PROTOCOL side"
    /// (`crate::mcp::McpElicitationHandler`), installed by
    /// `crate::agent::Agent::set_user_question_handler`. `None` (the
    /// default) means no interactive frontend is attached, and the tool
    /// says so rather than blocking on an answer nobody can give.
    pub question_handler: Option<question::UserQuestionHandler>,
    /// BP-3 (§2 module 8 `plan_mode`): the approval door `exit_plan_mode`
    /// presents the plan on — the same
    /// `crate::permissions::PermissionsApprovalHandler`
    /// `Agent::set_permissions_approval_handler` installs (under an
    /// SDK-owned runtime, that is the frontend request broker). `None` is
    /// fail-closed: the plan cannot be approved, so plan mode stays on.
    pub approval_handler: Option<ToolApprovalHandler>,
    /// BP-3 (§2 module 8): the shared plan-mode state — read by the agent's
    /// permission gate ([`plan_mode::deny_rules`]), written by
    /// `enter_plan_mode`/`exit_plan_mode` and the REPL's `/plan`. Inactive
    /// by default, and an inactive state contributes no rules at all.
    pub plan_mode: Arc<plan_mode::PlanModeState>,
    /// BP-3 (catalog row "Context-budget tools"): the shared token
    /// accounting `get_context_remaining` reads and `new_context` parks its
    /// request on. The agent publishes onto it; nothing is published until
    /// a turn has actually run.
    pub context_budget: Arc<context_budget::ContextBudget>,
    /// BP-8 (§2 module `todos` `persist`, catalog:156 "Todos/plan persisted
    /// per session"): the session's `update_plan` checklist. It lives HERE,
    /// on the context the agent owns and shares with every clone, rather
    /// than inside `UpdatePlanTool` — a plan the agent cannot read is a
    /// plan it cannot persist, which is exactly the residue the ledger row
    /// named. Empty by default, at zero cost.
    pub plan: Arc<Mutex<Vec<crate::session_journal::PlanEntry>>>,
}

/// BP-3: an approval handler reachable from inside a `Tool::execute`
/// (today, `exit_plan_mode`'s plan approval). A newtype purely so
/// [`ToolContext`] can stay `Debug` — the same shape, and the same reason,
/// as [`crate::sandbox::SandboxApprovalHandler`].
#[derive(Clone)]
pub struct ToolApprovalHandler(pub Arc<dyn crate::permissions::PermissionsApprovalHandler>);

impl std::fmt::Debug for ToolApprovalHandler {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("ToolApprovalHandler(..)")
    }
}

impl std::ops::Deref for ToolApprovalHandler {
    type Target = dyn crate::permissions::PermissionsApprovalHandler;
    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

impl ToolContext {
    /// A context rooted at `cwd` with no confinement.
    pub fn new(cwd: impl Into<PathBuf>) -> Self {
        ToolContext {
            cwd: cwd.into(),
            extra_roots: Vec::new(),
            sandbox: SandboxPolicy::DangerFullAccess,
            multimodal_read: false,
            read_line_numbers: false,
            require_read_before_edit: false,
            read_paths: Arc::new(Mutex::new(HashMap::new())),
            notebook_aware: false,
            shell_env: None,
            nested_instructions: false,
            injected_instruction_dirs: Arc::new(Mutex::new(HashSet::new())),
            path_rules: Arc::new(Vec::new()),
            injected_rule_files: Arc::new(Mutex::new(HashSet::new())),
            network_policy: None,
            permission_rules: None,
            bash_timeout_secs: None,
            write_observer: None,
            sandbox_os_enabled: None,
            sandbox_escalation: crate::sandbox::SandboxEscalation::default(),
            sandbox_env_policy: crate::sandbox::SandboxEnvPolicy::default(),
            sandbox_approval_handler: None,
            question_handler: None,
            approval_handler: None,
            plan_mode: Arc::new(plan_mode::PlanModeState::new()),
            context_budget: Arc::new(context_budget::ContextBudget::new()),
            plan: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// BP-8: the current plan, as `(step, status)` pairs.
    pub fn plan_snapshot(&self) -> Vec<crate::session_journal::PlanEntry> {
        self.plan.lock().map(|p| p.clone()).unwrap_or_default()
    }

    /// BP-8: replace the plan wholesale (`update_plan` replaces; a resume
    /// restores).
    pub fn set_plan(&self, steps: Vec<crate::session_journal::PlanEntry>) {
        if let Ok(mut p) = self.plan.lock() {
            *p = steps;
        }
    }

    /// BP-10: whether the permissions ENGINE adjudicated this call —
    /// i.e. `capabilities.permissions.enabled` was on when this context
    /// was built, so `crate::agent::Agent`'s dispatch gate ran the rule
    /// algebra (and any `Ask` tier) before the tool was invoked.
    ///
    /// The one consumer is the sandbox-escalation path
    /// (`builtins::escalation_requested`): a model-issued
    /// `with_escalated_permissions` is only honored where a gate exists to
    /// have approved it.
    pub fn permissions_engine_active(&self) -> bool {
        self.permission_rules.is_some()
    }

    /// P5-10: whether the OS-level backstop is active for this context —
    /// thin wrapper over `crate::sandbox::os_sandbox_active`.
    pub fn os_sandbox_active(&self) -> bool {
        crate::sandbox::os_sandbox_active(self.sandbox, self.sandbox_os_enabled)
    }

    /// P4c: record `path` (canonicalized if possible, else the resolved
    /// path as-is) as having been read this conversation — called by
    /// `ReadFileTool` on every successful read, unconditionally (cheap; the
    /// map is only ever CONSULTED when [`Self::require_read_before_edit`] is
    /// on, but recording it unconditionally means turning the knob on
    /// mid-conversation sees every read that already happened).
    ///
    /// BP-2: reads the file's CURRENT bytes to stamp the content hash. Use
    /// [`Self::mark_read_bytes`] from a caller that already holds them.
    pub fn mark_read(&self, path: &Path) {
        let bytes = std::fs::read(path).unwrap_or_default();
        self.mark_read_bytes(path, &bytes);
    }

    /// BP-2: the same record, stamped from bytes the caller just read.
    pub fn mark_read_bytes(&self, path: &Path, bytes: &[u8]) {
        let key = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
        if let Ok(mut map) = self.read_paths.lock() {
            map.insert(key, content_hash(bytes));
        }
    }

    /// P4c: whether `path` was previously recorded via [`Self::mark_read`],
    /// ignoring whether it has changed since.
    pub fn was_read(&self, path: &Path) -> bool {
        !matches!(self.read_state(path), ReadState::NeverRead)
    }

    /// BP-2 (catalog:32): what `edit_file` needs to know before accepting
    /// an edit — never read, read but changed on disk since, or read and
    /// still identical.
    pub fn read_state(&self, path: &Path) -> ReadState {
        let key = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
        let Some(recorded) = self
            .read_paths
            .lock()
            .ok()
            .and_then(|map| map.get(&key).copied())
        else {
            return ReadState::NeverRead;
        };
        match std::fs::read(&key) {
            Ok(bytes) if content_hash(&bytes) == recorded => ReadState::Fresh,
            // Unreadable now (deleted/permissions) counts as changed: the
            // model's view is provably not the file's current state.
            _ => ReadState::Stale,
        }
    }

    /// P4c (S2.1 S17): does `url` pass `Self::network_policy`, if one is
    /// configured? `Ok(())` when no policy is set (the honest-gap default)
    /// or the policy is present-but-disabled; `Err` names the reason
    /// otherwise. A URL with no parseable host is denied whenever a policy
    /// is actively enforced (fail closed — an unparseable host can't be
    /// matched against an allowlist).
    pub fn check_network(&self, url: &str) -> Result<()> {
        check_network_policy(
            self.network_policy.as_ref(),
            self.permission_rules.as_deref(),
            self.approval_handler.as_deref(),
            url,
        )
    }

    /// Resolve a possibly-relative path against the working directory.
    pub fn resolve(&self, path: &str) -> PathBuf {
        let p = PathBuf::from(path);
        if p.is_absolute() {
            p
        } else {
            self.cwd.join(p)
        }
    }

    /// BP-10: every root a `WorkspaceWrite` call may write under — `cwd`
    /// first, then each [`Self::extra_roots`] entry. The ONE list
    /// [`Self::check_write`], the seatbelt profile, and the Landlock
    /// writable set all read, so a grant can never be honored by one and
    /// missed by another.
    pub fn write_roots(&self) -> Vec<PathBuf> {
        let mut roots = Vec::with_capacity(1 + self.extra_roots.len());
        roots.push(self.cwd.clone());
        roots.extend(self.extra_roots.iter().cloned());
        roots
    }

    /// Enforce the sandbox policy for a write to `path`. `Err` if denied.
    pub fn check_write(&self, path: &Path) -> Result<()> {
        match self.sandbox {
            SandboxPolicy::DangerFullAccess => Ok(()),
            SandboxPolicy::ReadOnly => Err(crate::error::Error::tool(
                "sandbox",
                "write denied: sandbox is read-only",
            )),
            SandboxPolicy::WorkspaceWrite => {
                // BP-10: an `--add-dir` root is a real grant — a write
                // under one is inside the workspace, exactly as a write
                // under `cwd` is. Empty `extra_roots` (the default) makes
                // this the same single `cwd` check as before.
                if self.write_roots().iter().any(|r| path_within(r, path)) {
                    Ok(())
                } else {
                    Err(crate::error::Error::tool(
                        "sandbox",
                        format!(
                            "write denied: {} is outside the workspace {} (and its {} \
                             additional root(s))",
                            path.display(),
                            self.cwd.display(),
                            self.extra_roots.len()
                        ),
                    ))
                }
            }
        }
    }
}

/// P5-2 (§2 module 15, security note "remote MCP over http/sse: respect the
/// NetworkPolicy from P5-1 if one is active"): the same policy-and-url check
/// [`ToolContext::check_network`] performs, factored out to a free function
/// so `crate::mcp::McpClient::connect_http`/`connect_sse` can enforce the
/// identical allow/deny/SSRF floor a `web_fetch` call would get — one
/// enforcement point, not a second parallel one that could silently drift
/// from it.
pub(crate) fn check_network_policy(
    policy: Option<&NetworkPolicy>,
    rules: Option<&crate::permissions::RuleSet>,
    approval: Option<&dyn crate::permissions::PermissionsApprovalHandler>,
    url: &str,
) -> Result<()> {
    let ctx_like = domain_tier_of(policy, rules);
    check_host_against_tier(&ctx_like, approval, url_host(url).as_deref())
}

/// BP-10: [`ToolContext::domain_tier`]'s body, as a free function, so the
/// non-`ToolContext` caller (`crate::mcp::McpClient::connect_http`) folds
/// the SAME two sources in the SAME order rather than a second, drifting
/// copy. See that method's doc comment for the two sources.
pub(crate) fn domain_tier_of(
    policy: Option<&NetworkPolicy>,
    rules: Option<&crate::permissions::RuleSet>,
) -> (crate::permissions::RuleSet, crate::permissions::Decision) {
    let mut out = crate::permissions::RuleSet::default();
    let mut default = crate::permissions::Decision::Allow;
    if let Some(policy) = policy {
        if policy.enabled {
            let (list_rules, list_default) = policy.domain_rule_set();
            out.deny.extend(list_rules.deny);
            out.allow.extend(list_rules.allow);
            default = list_default;
        }
    }
    if let Some(config_rules) = rules {
        out.deny.extend(config_rules.deny.iter().cloned());
        out.ask.extend(config_rules.ask.iter().cloned());
        out.allow.extend(config_rules.allow.iter().cloned());
    }
    (out, default)
}

/// P4c-review (MEDIUM/LOW follow-up, dep 8's neighboring `tools.web` SSRF
/// gap): the SAME allow/deny decision [`ToolContext::check_network`] applies
/// to the INITIAL url, factored out so [`network_checked_redirect_policy`]
/// can apply it to every REDIRECT hop too. Without this, `check_network`
/// validated only the url the caller passed in — once a real network policy
/// is wired up (P5), a denied host reachable only via an allowed host's HTTP
/// redirect (reqwest follows up to 10 by default) bypassed the check
/// entirely. `host: None` (unparseable/absent) fails closed, exactly like
/// `check_network`'s own prior inline behavior.
fn check_host_against_tier(
    tier: &(crate::permissions::RuleSet, crate::permissions::Decision),
    approval: Option<&dyn crate::permissions::PermissionsApprovalHandler>,
    host: Option<&str>,
) -> Result<()> {
    use crate::permissions::{Decision, RuleSet};
    let (rules, default): (&RuleSet, Decision) = (&tier.0, tier.1);
    // Nothing to enforce: no domain rule from either source. Byte-identical
    // to "no policy configured" — this is the common path.
    if rules.is_empty() && default == Decision::Allow {
        return Ok(());
    }
    let Some(host_str) = host else {
        return Err(crate::error::Error::tool(
            "network",
            "cannot determine host from url; denied under an active network policy",
        ));
    };
    let host = host_str.to_ascii_lowercase();
    match crate::permissions::evaluate_domain(rules, Some(&host), default) {
        Decision::Allow => Ok(()),
        Decision::Ask => {
            // BP-10: the `domain(...)` ASK tier resolves on the SAME door
            // every other `Ask` in this engine uses. No door installed
            // denies, the fail-closed posture
            // `PermissionsApprovalHandler`'s own doc comment documents.
            let raw_args = serde_json::json!({ "host": host });
            let req = crate::permissions::ApprovalRequest {
                tool: "domain",
                subject: Some(&host),
                raw_args: &raw_args,
            };
            match approval.map(|h| h.ask(&req)) {
                Some(crate::permissions::ApprovalOutcome::Allow)
                | Some(crate::permissions::ApprovalOutcome::AllowForSession) => Ok(()),
                _ => Err(crate::error::Error::tool(
                    "network",
                    format!("host `{host}` requires approval and none was given"),
                )),
            }
        }
        Decision::Deny => {
            if crate::permissions::domain_denied_explicitly(rules, &host) {
                Err(crate::error::Error::tool(
                    "network",
                    format!("host `{host}` is denied by the active network policy"),
                ))
            } else {
                Err(crate::error::Error::tool(
                    "network",
                    format!("host `{host}` is not on the network policy's allowlist"),
                ))
            }
        }
    }
}

/// P4c-review (MEDIUM/LOW follow-up): a `reqwest::redirect::Policy` for
/// `WebFetchTool`/`WebSearchTool`'s client that re-runs
/// [`check_host_against_policy`] (the exact same check
/// [`ToolContext::check_network`] applies to the initial url) against every
/// redirect hop's target host, refusing to follow one that a network policy
/// denies. `policy: None` (no policy configured) or a present-but-disabled
/// one behaves like reqwest's own default policy — follow, capped at the
/// same 10-hop limit `redirect::Policy::default()` uses (the crate's `custom`
/// variant does NOT enforce a redirect cap on its own — see its doc comment
/// — so this reimplements that cap by hand).
pub(crate) fn network_checked_redirect_policy(
    policy: Option<NetworkPolicy>,
    rules: Option<Arc<crate::permissions::RuleSet>>,
) -> reqwest::redirect::Policy {
    const MAX_REDIRECTS: usize = 10; // matches reqwest::redirect::Policy::default()
    let tier = domain_tier_of(policy.as_ref(), rules.as_deref());
    reqwest::redirect::Policy::custom(move |attempt| {
        if attempt.previous().len() >= MAX_REDIRECTS {
            return attempt.error("too many redirects");
        }
        // BP-10: a redirect hop gets the SAME domain tier as the initial
        // url, but never an interactive prompt — an `Ask` mid-flight has
        // no user-visible action to describe, so it fails closed here
        // (`approval: None`) rather than blocking a redirect chain on a
        // question about a host the user never typed.
        if let Err(e) = check_host_against_tier(&tier, None, attempt.url().host_str()) {
            return attempt.error(e.to_string());
        }
        attempt.follow()
    })
}

/// P4c (S2.1 S17): extract the host from an `http(s)://` URL — the smallest
/// parser that satisfies [`ToolContext::check_network`]'s needs without a
/// new `url`-crate dependency (matches this crate's existing `glob_match`
/// precedent of hand-rolling a small parser rather than reaching for a
/// dependency for an S-sized need). Returns `None` for anything that isn't
/// `http://`/`https://` or has an empty host component.
fn url_host(url: &str) -> Option<String> {
    let rest = url
        .strip_prefix("https://")
        .or_else(|| url.strip_prefix("http://"))?;
    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let authority = &rest[..end];
    // Strip a `user:pass@` prefix and a `:port` suffix, keeping the host.
    let host_and_port = authority.rsplit('@').next().unwrap_or(authority);
    let host = host_and_port.split(':').next().unwrap_or(host_and_port);
    if host.is_empty() {
        None
    } else {
        Some(host.to_ascii_lowercase())
    }
}

/// True when the requested sandbox policy cannot be enforced for shell
/// subprocesses: a confining policy, a platform without an OS sandbox
/// primitive wired up (only macOS/seatbelt is, via `sandbox-exec`), and at
/// least one shell tool (`"bash"` or `"shell"`) enabled.
///
/// This is a pure function so it's mechanically testable on any host OS:
/// callers pass the platform (typically `std::env::consts::OS`) and the set
/// of enabled tool names rather than relying on `cfg!`/`target_os`. It does
/// not itself sandbox anything — it only tells embedders/CLIs whether the
/// gap documented on [`SandboxPolicy`] applies right now, so they can warn.
/// P5-10 (§2 module 12): `landlock_available` is the caller's REAL Linux
/// Landlock-availability probe (`crate::sandbox::landlock_available()`,
/// typically) — a PARAMETER, not an internal `cfg!`/probe call, same "pure,
/// mechanically testable" contract this function already had. Before
/// P5-10, `platform == "linux"` always meant "unenforceable" (no OS
/// primitive existed yet); now it means "unenforceable UNLESS Landlock is
/// actually available on this kernel" — a confining tier on a
/// Landlock-capable Linux box is REAL enforcement, not a gap, so this must
/// say `false` for it (never claim a gap that no longer exists).
/// `platform == "macos"` is unconditionally `false` regardless of this
/// parameter (seatbelt, a separate primitive, always exists there); every
/// other platform (including `platform == "linux"` with
/// `landlock_available == false`) is unaffected by this parameter and
/// keeps the pre-P5-10 "no primitive" answer.
pub fn shell_sandbox_unenforceable(
    policy: SandboxPolicy,
    platform: &str,
    tools_enabled: &[&str],
    landlock_available: bool,
) -> bool {
    policy != SandboxPolicy::DangerFullAccess
        && platform != "macos"
        && !(platform == "linux" && landlock_available)
        && tools_enabled.iter().any(|t| *t == "bash" || *t == "shell")
}

/// Whether `path` is inside `root`. SECURITY (safe-path consolidation,
/// LOWER-URGENCY fix folded into the permissions-gate CRITICAL fix): this
/// used to compare only LEXICALLY-normalized paths (`..` traversal caught,
/// but a pre-existing in-workspace symlink pointing outside `root` was NOT —
/// `link -> /etc` plus a write to `link/passwd` lexically normalizes to
/// `<root>/link/passwd`, which "starts with" `root` even though it actually
/// resolves outside it). Now delegates to `crate::safe_path::contained`,
/// which ALSO resolves symlinks along the longest existing ancestor (the
/// same proven dual lexical+resolved check `crate::checkpoint`'s P5-9 fix
/// uses), so a symlink escape is caught here too. A non-existent target
/// (e.g. a file about to be created) is still handled correctly.
fn path_within(root: &Path, path: &Path) -> bool {
    crate::safe_path::contained(root, path)
}

/// `pub(crate)`: also the lexical-`..`-collapse step
/// [`crate::checkpoint`]'s containment check builds on (P5-9) — one
/// normalizer, not a second hand-rolled one.
pub(crate) fn normalize(path: &Path) -> Option<PathBuf> {
    use std::path::Component;
    // Make absolute against CWD if needed (paths are already joined to cwd by
    // resolve(), but be defensive).
    let abs = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir().ok()?.join(path)
    };
    let mut out = PathBuf::new();
    for c in abs.components() {
        match c {
            Component::ParentDir => {
                out.pop();
            }
            Component::CurDir => {}
            other => out.push(other.as_os_str()),
        }
    }
    Some(out)
}

/// A callable capability.
#[async_trait]
pub trait Tool: Send + Sync {
    /// Stable, unique tool name (what the model calls).
    fn name(&self) -> &str;

    /// The built-in description. May be overridden via [`crate::Config`].
    fn description(&self) -> &str;

    /// JSON Schema describing the tool's input object.
    fn parameters(&self) -> serde_json::Value;

    /// Whether a successful textual result is also a complete JSON value
    /// that protocol adapters should expose as structured output. Text
    /// remains the model-facing representation, preserving compatibility.
    fn structured_output(&self) -> bool {
        false
    }

    /// Run the tool. Returns text to feed back to the model.
    async fn execute(&self, args: serde_json::Value, ctx: &ToolContext) -> Result<String>;
}

/// An ordered set of tools offered to the model.
#[derive(Default)]
pub struct ToolRegistry {
    tools: Vec<Box<dyn Tool>>,
}

impl ToolRegistry {
    /// An empty registry.
    pub fn new() -> Self {
        ToolRegistry::default()
    }

    /// A registry pre-populated with all built-in tools.
    pub fn with_builtins() -> Self {
        let mut r = ToolRegistry::new();
        r.register(ReadFileTool);
        r.register(WriteFileTool);
        r.register(EditFileTool);
        r.register(ListDirTool);
        r.register(GlobTool);
        r.register(SearchTool);
        r.register(ApplyPatchTool);
        r.register(BashTool::default());
        r.register(PersistentShellTool::default());
        r.register(UpdatePlanTool::default());
        r
    }

    /// P3 (COMPOSABLE-HARNESS-DESIGN.md §5.2 phase P3): build a registry
    /// from a resolved [`Config`]'s module-activation set, the intended
    /// replacement for unconditional [`Self::with_builtins`] call sites.
    ///
    /// **BP-1: this is now the default path.** Every `Config` materialized
    /// by [`crate::configfile::resolve`] carries
    /// [`Config::module_registry`] `= true`, so a preset's
    /// `[capabilities.*]` and `[core.tools] enabled` actually shape the
    /// registry. `[experimental] module_registry = false` is the explicit
    /// OPT-OUT that pins a resolved config back to the unfiltered stack,
    /// and a hand-built [`Config::default`] (which never went through the
    /// resolver) still has the flag `false`. In that `false` state this
    /// returns EXACTLY [`Self::with_builtins`] — same 10 tools, same
    /// order, zero behavior change. When it is on,
    /// [`Config::module_activation`]/[`Config::core_tools_enabled`]
    /// shape which tool objects get registered AT ALL: a disabled module
    /// contributes no tool (never registered, so never advertised and never
    /// mentioned anywhere) — e.g. `todos` off means `update_plan` is not in
    /// this registry; `tools_search` off (or its `list_dir`/`glob`/
    /// `content_search` sub-flags off) means the corresponding tool is
    /// absent too.
    pub fn from_config(config: &Config) -> Self {
        // The opt-out (or a Config that never met the resolver at all).
        if !config.module_registry {
            return Self::with_builtins();
        }
        let mut r = ToolRegistry::new();
        let act = &config.module_activation;

        // BP-13 (catalog D9 "Per-model capability bits drive tools", cx§9
        // "Model catalog"): the model's own capability bits, resolved out of
        // the SAME `Config::model_routing` table every other routing
        // decision reads. They shape THIS selection rather than a parallel
        // registry — the only thing they can do is decide which write
        // surface a model is offered.
        //
        // Armed only under `[capabilities.tools_apply_patch] per_model =
        // true` (the flag cx-parity already sets, and whose only previous
        // reader was the resolver's C1 warning suppression) AND only when a
        // rule actually matches this model. With no matching rule the
        // selection below is byte-identical to pre-BP-13: `core.tools`
        // decides edit/write, the module decides apply_patch.
        let bits = if act.is_active(ModuleId::ToolsApplyPatch) && act.tools_apply_patch_per_model {
            config.model_routing.rules_for(&config.model)
        } else {
            crate::model_catalog::ModelRules::default()
        };
        let core_has = |name: &str| match (name, bits.apply_patch) {
            // A model the catalog marks as NOT taking the freeform
            // apply_patch envelope gets the edit/write pair instead, even
            // where `core.tools` lists neither — that swap IS the row.
            ("edit_file" | "write_file", Some(false)) => true,
            // …and the converse: a model that DOES take apply_patch is not
            // also handed the pair, so the two write formats are never
            // co-advertised to it (§2.2 C1's whole point).
            ("edit_file" | "write_file", Some(true)) => false,
            _ => config.core_tools_enabled.iter().any(|t| t == name),
        };

        // Same relative order as `with_builtins()` for everything both paths
        // can register, so a partial activation set stays predictable.
        if core_has("read_file") {
            r.register(ReadFileTool);
        }
        if core_has("write_file") {
            r.register(WriteFileTool);
        }
        if core_has("edit_file") {
            r.register(EditFileTool);
        }
        // P4c (S1.2 `view_image`, S12): a fifth OPTIONAL default-tool name —
        // "recognized alongside read_file/bash/edit_file/write_file as a
        // fifth optional default-tool name, not a new module" — so it's
        // read from the SAME `core_tools_enabled` list as the other four,
        // not a `ModuleId`. Absent from the list by default (today's
        // `["read_file","bash","edit_file","write_file"]` default), so this
        // is a no-op unless a caller explicitly adds `"view_image"`.
        if core_has("view_image") {
            r.register(ViewImageTool);
        }
        // BP-13: `search_tool = false` withdraws the dedicated search tool
        // for a model the catalog says cannot use it (cx§9
        // `supports_search_tool`); unset leaves the module's own sub-flags
        // in sole charge, exactly as before.
        if act.is_active(ModuleId::ToolsSearch) && bits.search_tool != Some(false) {
            if act.tools_search_list_dir {
                r.register(ListDirTool);
            }
            if act.tools_search_glob {
                r.register(GlobTool);
            }
            if act.tools_search_content_search {
                r.register(SearchTool);
            }
        }
        // BP-13: with per-model bits armed, a model the catalog says cannot
        // take the freeform envelope is not offered it.
        if act.is_active(ModuleId::ToolsApplyPatch) && bits.apply_patch != Some(false) {
            r.register(ApplyPatchTool);
        }
        if core_has("bash") {
            r.register(BashTool::default());
        }
        if act.is_active(ModuleId::ToolsPersistentShell) {
            r.register(PersistentShellTool::default());
        }
        if act.is_active(ModuleId::Todos) {
            r.register(UpdatePlanTool::default());
        }
        // P4c (S2 module 5 `tools.web`, S4a "trivially addable"): single
        // tool each, gated by the module's own `fetch`/`search` sub-flags
        // (S3.1: `[capabilities.tools_web] { enabled = false, fetch = true,
        // search = true }`) exactly like `tools_search`'s three sub-flags.
        if act.is_active(ModuleId::ToolsWeb) {
            if act.tools_web_fetch {
                r.register(WebFetchTool);
            }
            if act.tools_web_search {
                r.register(WebSearchTool);
            }
        }
        // BP-3 (§2 module 6 `tools.question`): the module contributes the
        // question tool. `cx-parity` additionally names Codex's own
        // experimental spelling in `[core.tools] enabled`, so a continued
        // Codex session's `request_user_input` calls keep resolving — the
        // SAME tool object under a second registered name, never a second
        // implementation.
        if act.is_active(ModuleId::ToolsQuestion) {
            r.register(AskUserTool::new(question::ASK_USER));
        }
        if core_has(question::REQUEST_USER_INPUT) {
            r.register(AskUserTool::new(question::REQUEST_USER_INPUT));
        }
        // BP-3 (§2 module 8 `plan_mode`): the two tools the module is
        // defined by. The restriction they establish is enforced by the
        // permissions engine (`plan_mode::deny_rules`, folded into its deny
        // tier by `crate::agent`'s gate), which is why the module's §2.1
        // dependency edge is `plan_mode → permissions.rules|sandbox`.
        if act.is_active(ModuleId::PlanMode) {
            r.register(EnterPlanModeTool);
            r.register(ExitPlanModeTool);
        }
        // BP-3 (catalog rows "Clock / sleep tools", "Context-budget tools",
        // "Image generation tool"): four more OPTIONAL default-tool names,
        // read from the same `[core.tools] enabled` list as `view_image`
        // (§1.2's "fifth optional default-tool name, not a new module"
        // precedent) — absent from the default four, so a config that does
        // not name them gets byte-identical tools to before.
        if core_has(clock::CURRENT_TIME) {
            r.register(CurrentTimeTool);
        }
        if core_has(clock::SLEEP) {
            r.register(SleepTool);
        }
        if core_has(context_budget::GET_CONTEXT_REMAINING) {
            r.register(GetContextRemainingTool);
        }
        if core_has(context_budget::NEW_CONTEXT) {
            r.register(NewContextTool);
        }
        if core_has(image_gen::IMAGE_GEN) {
            r.register(ImageGenTool::new(
                config.base_url.clone(),
                config.api_key.clone(),
                config.api_key_env.clone(),
            ));
        }
        // BP-6 (catalog D1 "Skill-invocation surface"): the one tool every
        // skill is invoked through (CC's `Skill` shape). The tool IS the
        // on-demand read pathway D-7 is about, so it does not itself depend
        // on `read_file`/`bash` being present (cx-parity has neither for
        // files). Discovery runs here, at registry construction, and reads
        // only frontmatter: no body is opened until the model calls it.
        //
        // Registered exactly when the config READS a skill-root table —
        // `[core.skills] enabled` plus a `harness` naming whose roots to
        // walk, the same precondition `load_for_config` applies. A config
        // that enables skills without naming a table discovers nothing, so
        // the tool would have nothing to load; leaving it out keeps every
        // pre-BP-6 config's tool set byte-identical.
        if config.skills_enabled && config.skills_harness.is_some() {
            r.register(
                SkillTool::new(crate::skills::load_for_config(config))
                    // BP-5: the tool door loads bodies under the same
                    // permission-engine authorization every other
                    // invocation door uses.
                    .with_shell(crate::skills::ShellInjection::from_config(config)),
            );
        }
        r
    }

    /// Add a tool. A later registration with the same name shadows the earlier.
    pub fn register(&mut self, tool: impl Tool + 'static) {
        self.tools.push(Box::new(tool));
    }

    /// Look up a tool by name (last registration wins).
    pub fn get(&self, name: &str) -> Option<&dyn Tool> {
        self.tools
            .iter()
            .rev()
            .find(|t| t.name() == name)
            .map(|b| b.as_ref())
    }

    /// Iterate all tools.
    pub fn iter(&self) -> impl Iterator<Item = &dyn Tool> {
        self.tools.iter().map(|b| b.as_ref())
    }

    /// Number of registered tools.
    pub fn len(&self) -> usize {
        self.tools.len()
    }

    /// Whether the registry is empty.
    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }
}

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

    /// Truth table for [`shell_sandbox_unenforceable`]. Pure inputs — no
    /// `cfg!`/`target_os` gating — so this passes identically on macOS,
    /// Linux, and Windows CI hosts. P5-10 added the `landlock_available`
    /// parameter: a Linux host WITH Landlock is no longer a gap (this box
    /// IS one — see `sandbox::tests`/the integration test for the REAL
    /// enforcement proof); a Linux host WITHOUT it still is.
    #[test]
    fn shell_sandbox_unenforceable_truth_table() {
        // Confining policy + non-macOS + a shell tool enabled + Landlock
        // NOT available => true (still an honest gap).
        assert!(shell_sandbox_unenforceable(
            SandboxPolicy::ReadOnly,
            "linux",
            &["bash"],
            false,
        ));
        assert!(shell_sandbox_unenforceable(
            SandboxPolicy::WorkspaceWrite,
            "linux",
            &["shell"],
            false,
        ));
        // No Landlock concept on Windows at all — `landlock_available` is
        // irrelevant there (still unenforceable regardless of its value).
        assert!(shell_sandbox_unenforceable(
            SandboxPolicy::WorkspaceWrite,
            "windows",
            &["bash", "shell"],
            true,
        ));

        // P5-10: Linux WITH real Landlock support => NOT a gap anymore —
        // enforcement now exists, so this must say `false` (never claim a
        // gap that no longer applies).
        assert!(!shell_sandbox_unenforceable(
            SandboxPolicy::ReadOnly,
            "linux",
            &["bash"],
            true,
        ));
        assert!(!shell_sandbox_unenforceable(
            SandboxPolicy::WorkspaceWrite,
            "linux",
            &["shell"],
            true,
        ));

        // DangerFullAccess => false regardless of platform/tools/landlock.
        assert!(!shell_sandbox_unenforceable(
            SandboxPolicy::DangerFullAccess,
            "linux",
            &["bash", "shell"],
            false,
        ));

        // macOS => false regardless of policy (seatbelt sandboxes the
        // shell) — even with `landlock_available = true` passed in (an
        // impossible-in-practice combination, but the function must still
        // ignore it, since macOS's own primitive is what actually applies).
        assert!(!shell_sandbox_unenforceable(
            SandboxPolicy::ReadOnly,
            "macos",
            &["bash", "shell"],
            true,
        ));

        // No bash/shell in tools_enabled => false.
        assert!(!shell_sandbox_unenforceable(
            SandboxPolicy::ReadOnly,
            "linux",
            &[],
            false,
        ));
        assert!(!shell_sandbox_unenforceable(
            SandboxPolicy::ReadOnly,
            "linux",
            &["write_file"],
            false,
        ));
    }
}