supercode-harness 0.4.14

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
//! BP-10 (`.volter/tracker/markdown/BP-10.md`): the ten Domain-4 permission
//! behaviours, proved over the RESOLVED `cc-parity` / `cx-parity` configs —
//! never over a hand-built `Config`, which would pass even if the preset
//! never armed the knob.
//!
//! Every gate this unit adds is a rule or a tier INSIDE the one permissions
//! engine, so the proofs run through that engine's own entry points:
//! `Agent::permissions_gate_denial` (the dispatch gate),
//! `Agent::prepare_tool_call` (the whole pre-dispatch path),
//! `Agent::tool_schemas` (what the model can see), `ToolContext`'s own
//! checks, and the real tools.
//!
//! Offline and hermetic: no provider is ever called, and every persisted
//! store (approvals, trust) is redirected onto a temp directory, so no real
//! harness home is read or written.
//!
//! A `#[path]`-included sibling of `agent.rs` purely for file size; it is an
//! ordinary in-crate `#[cfg(test)]` module, the same shape as
//! `bp3_new_core_tool_tests`/`bp4_prompt_context_tests` above it.

use super::*;
use crate::config::{HookDecision, PreToolOutcome};
use crate::configfile::{resolve_with_layers, ConfigLayers, ResolveOptions};
use crate::permissions::{ApprovalOutcome, ApprovalRequest, PermissionsApprovalHandler};

/// A command every `bash(rm -rf*)` deny rule below matches. Spelled with a
/// harmless target: no test ever executes it (the gate refuses first), and
/// a literal root-delete string in a source file is a hazard for anything
/// that greps this tree.
const DENIED_COMMAND: &str = "rm -rf /tmp/bp10-never-runs";

#[derive(Debug)]
struct NeverCalledProvider;

#[async_trait::async_trait]
impl Provider for NeverCalledProvider {
    async fn complete(
        &self,
        _req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> crate::Result<(ChatMessage, crate::provider::Usage)> {
        unreachable!("BP-10 tests never issue a request")
    }
}

fn tmp(tag: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "supercode-bp10-{tag}-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

/// A resolved parity preset, with `cwd` and both persisted stores moved onto
/// a fresh temp tree. `overrides` are `-c key=value` assignments — the SAME
/// per-run layer `--config`/`--permission-profile` travel, so a test that
/// writes a rule writes it the way a user does.
fn resolved(preset: &str, tag: &str, overrides: &[String]) -> Config {
    let toml = crate::presets::lookup(preset).unwrap();
    let layers = ConfigLayers {
        overrides,
        ..Default::default()
    };
    let mut config = resolve_with_layers(toml, &layers, &ResolveOptions { strict: true })
        .unwrap_or_else(|e| panic!("{preset} resolves: {e}"))
        .config;
    let dir = tmp(tag);
    config.permissions_approval_store = Some(dir.join(".approvals.json"));
    config.trust_store = Some(dir.join(".trust.json"));
    config.cwd = dir;
    config
}

fn plain(preset: &str, tag: &str) -> Config {
    resolved(preset, tag, &[])
}

fn agent_for(config: Config) -> Agent {
    Agent::with_provider(config, Box::new(NeverCalledProvider))
}

/// The gate's own answer, in the shape every assertion below wants.
fn allows(agent: &Agent, tool: &str, args: &serde_json::Value) -> bool {
    agent
        .permissions_gate_denial(tool, args, HookDecision::Pass)
        .is_none()
}

struct Answer(ApprovalOutcome);
impl PermissionsApprovalHandler for Answer {
    fn ask(&self, _req: &ApprovalRequest) -> ApprovalOutcome {
        self.0
    }
}

/// Records what it was asked, so a test can prove a door was (or was not)
/// consulted, and with what.
struct RecordingDoor {
    outcome: ApprovalOutcome,
    seen: std::sync::Mutex<Vec<(String, String)>>,
}

impl RecordingDoor {
    fn answering(outcome: ApprovalOutcome) -> std::sync::Arc<Self> {
        std::sync::Arc::new(RecordingDoor {
            outcome,
            seen: std::sync::Mutex::new(Vec::new()),
        })
    }
    fn seen(&self) -> Vec<(String, String)> {
        self.seen.lock().unwrap().clone()
    }
}

impl PermissionsApprovalHandler for RecordingDoor {
    fn ask(&self, req: &ApprovalRequest) -> ApprovalOutcome {
        self.seen
            .lock()
            .unwrap()
            .push((req.tool.to_string(), req.raw_args.to_string()));
        self.outcome
    }
}

/// `set_permissions_approval_handler` takes ownership; these tests keep a
/// handle on the recorder afterwards, so the `Arc` is installed through a
/// thin forwarding wrapper.
struct Shared(std::sync::Arc<RecordingDoor>);
impl PermissionsApprovalHandler for Shared {
    fn ask(&self, req: &ApprovalRequest) -> ApprovalOutcome {
        self.0.ask(req)
    }
}

// ---- row: allow-ask-deny-rule-language (the DOMAIN subject) -------------

/// The fourth rule subject is part of the ALGEBRA, under both presets: a
/// `domain(...)` pattern in `capabilities.permissions.rules.deny` refuses a
/// fetch through the ordinary tiers, with no `sandbox.network` list involved
/// at all — which is exactly what the row's residue said was missing.
#[test]
fn domain_rules_are_part_of_the_rule_algebra_under_both_presets() {
    for preset in ["cc-parity", "cx-parity"] {
        let config = resolved(
            preset,
            "domain-deny",
            &["capabilities.permissions.rules.deny=[\"domain(blocked.example)\"]".to_string()],
        );
        assert!(
            config
                .tool_deny_patterns
                .iter()
                .any(|p| p == "domain(blocked.example)"),
            "{preset}: the domain rule must reach the ONE engine's deny tier"
        );
        let agent = agent_for(config);
        let err = agent
            .ctx
            .check_network("https://blocked.example/page")
            .expect_err("a domain deny rule must refuse the fetch");
        assert!(err.to_string().contains("denied"), "{preset}: {err}");
        assert!(
            agent.ctx.check_network("https://ok.example/page").is_ok(),
            "{preset}: an unnamed host is untouched — this is a rule, not a switch"
        );
    }
}

/// The domain subject globs like every other subject (`bash(rm -rf*)`,
/// `write(.git/**)`) — something a literal-equality host list could never
/// do.
#[test]
fn a_domain_rule_globs_like_every_other_subject() {
    let config = resolved(
        "cc-parity",
        "domain-glob",
        &["capabilities.permissions.rules.deny=[\"domain(*.evil.example)\"]".to_string()],
    );
    let agent = agent_for(config);
    assert!(agent
        .ctx
        .check_network("https://api.evil.example/x")
        .is_err());
    assert!(agent
        .ctx
        .check_network("https://evil.example.org/x")
        .is_ok());
}

/// The `ask` tier works for a domain too, on the ONE door.
#[test]
fn a_domain_ask_resolves_on_the_one_approval_door() {
    let config = resolved(
        "cc-parity",
        "domain-ask",
        &["capabilities.permissions.rules.ask=[\"domain(maybe.example)\"]".to_string()],
    );
    let mut agent = agent_for(config);
    assert!(
        agent.ctx.check_network("https://maybe.example/x").is_err(),
        "no door installed must fail closed"
    );
    agent.set_permissions_approval_handler(Answer(ApprovalOutcome::Allow));
    assert!(agent.ctx.check_network("https://maybe.example/x").is_ok());
}

// ---- row: session-approval-caching -------------------------------------

/// A grant made by one Agent is honored by a LATER Agent over the same
/// project — read back off disk, with a deny-everything door installed so a
/// pass is only possible if the persisted grant was found. Then a clear
/// re-asks.
#[test]
fn an_approval_grant_survives_the_process_and_a_clear_re_asks() {
    for preset in ["cc-parity", "cx-parity"] {
        // Force the Ask tier under BOTH presets: cx-parity's
        // `model_requested` baseline is Allow, so without a rule the gate
        // would never reach a door and there would be no grant to persist
        // — a test that passed on that would be measuring nothing.
        let ask_everything = vec!["capabilities.permissions.rules.ask=[\"bash(*)\"]".to_string()];
        let first = resolved(preset, "approval-persist", &ask_everything);
        let store = first.permissions_approval_store.clone().unwrap();
        let cwd = first.cwd.clone();
        assert!(
            first.permissions_approvals_persist,
            "{preset} must arm `capabilities.permissions.approvals.persist`"
        );

        {
            let mut agent = agent_for(first);
            agent.set_permissions_approval_handler(Answer(ApprovalOutcome::AllowForSession));
            assert!(
                allows(
                    &agent,
                    "bash",
                    &serde_json::json!({"command": "git status"})
                ),
                "{preset}: the door approved it"
            );
        }
        assert!(store.exists(), "{preset}: the grant is on disk");

        let mut second = resolved(preset, "approval-persist-2", &ask_everything);
        second.cwd = cwd;
        second.permissions_approval_store = Some(store.clone());
        let mut agent = agent_for(second);
        agent.set_permissions_approval_handler(Answer(ApprovalOutcome::Deny));
        assert!(
            allows(
                &agent,
                "bash",
                &serde_json::json!({"command": "git status"})
            ),
            "{preset}: the remembered grant must skip the refusing door entirely"
        );
        assert!(
            !allows(&agent, "bash", &serde_json::json!({"command": "git push"})),
            "{preset}: the grant is per subject, not per tool"
        );

        agent.permissions_approval_cache().clear();
        assert!(!store.exists(), "{preset}: clearing removes the store");
        assert!(
            !allows(
                &agent,
                "bash",
                &serde_json::json!({"command": "git status"})
            ),
            "{preset}: after a clear the refusing door is consulted again"
        );
    }
}

// ---- row: child-process-env-sanitization -------------------------------

/// cx-parity FILTERS a secret out of a spawned shell; cc-parity states CC's
/// inherit posture and passes it through. The proof is the child's own view
/// of the variable, not the config value.
#[tokio::test]
async fn cx_parity_strips_a_secret_from_the_spawned_shell_and_cc_parity_does_not() {
    std::env::set_var("BP10_FAKE_API_KEY", "super-secret");
    for (preset, expected) in [("cx-parity", "[]"), ("cc-parity", "[super-secret]")] {
        let config = plain(preset, "env");
        let registry = crate::tools::ToolRegistry::from_config(&config);
        let bash = registry.get("bash").expect("both presets register bash");
        let (ctx, _cp, _lsp) = build_tool_context(&config);
        let out = bash
            .execute(
                serde_json::json!({"command": "echo [$BP10_FAKE_API_KEY]"}),
                &ctx,
            )
            .await
            .expect("the command runs");
        assert!(
            out.contains(expected),
            "{preset} must render `{expected}`: {out}"
        );
    }
    std::env::remove_var("BP10_FAKE_API_KEY");
}

// ---- row: tool-hiding-via-policy ---------------------------------------

/// A bare-name deny REMOVES the tool from the model's view (cc§4), not
/// merely refuses the call.
#[test]
fn a_bare_name_deny_hides_the_tool_from_the_model() {
    for (preset, tool) in [("cc-parity", "write_file"), ("cx-parity", "apply_patch")] {
        let visible = agent_for(plain(preset, "hide-a"));
        assert!(
            visible.tool_schemas().iter().any(|s| s.name == tool),
            "{preset}: `{tool}` is advertised without the rule"
        );

        let hidden = agent_for(resolved(
            preset,
            "hide-b",
            &[format!("capabilities.permissions.rules.deny=[\"{tool}\"]")],
        ));
        assert!(
            !hidden.tool_schemas().iter().any(|s| s.name == tool),
            "{preset}: a bare-name deny must remove `{tool}` from the model's view"
        );
        assert!(
            hidden.tool_schemas().iter().any(|s| s.name == "bash"),
            "{preset}: unrelated tools stay advertised"
        );
    }
}

/// A rule that names a command constraint refuses the call without hiding
/// the tool — `bash(rm -rf*)` cannot be satisfied by a tool name alone, so
/// Bash stays advertised and the refusal happens at dispatch.
#[test]
fn a_subject_bearing_deny_refuses_without_hiding() {
    let agent = agent_for(resolved(
        "cc-parity",
        "hide-subject",
        &["capabilities.permissions.rules.deny=[\"bash(rm -rf*)\"]".to_string()],
    ));
    assert!(
        agent.tool_schemas().iter().any(|s| s.name == "bash"),
        "a command-constrained rule must not hide the tool"
    );
    assert!(!allows(
        &agent,
        "bash",
        &serde_json::json!({ "command": DENIED_COMMAND })
    ));
}

// ---- row: additional-working-directories -------------------------------

/// An `--add-dir` root is REACHABLE by the tools — a write under it is
/// permitted by the very sandbox check that refuses an ungranted directory —
/// and the grant does not also delete the root-relative protected-path floor
/// inside it.
#[test]
fn an_extra_root_is_writable_and_still_carries_the_protected_path_floor() {
    let mut config = plain("cx-parity", "add-dir");
    let extra = tmp("add-dir-extra");
    config.additional_dirs = vec![extra.clone()];
    let agent = agent_for(config);

    assert_eq!(
        agent.ctx.extra_roots,
        vec![extra.clone()],
        "the grant reaches ToolContext"
    );
    assert_eq!(
        agent.ctx.sandbox,
        crate::tools::SandboxPolicy::WorkspaceWrite
    );
    assert!(
        agent.ctx.check_write(&extra.join("notes.txt")).is_ok(),
        "a granted root must be writable"
    );
    let stranger = tmp("add-dir-stranger");
    assert!(
        agent.ctx.check_write(&stranger.join("notes.txt")).is_err(),
        "an ungranted directory is still outside the workspace"
    );

    let protected = extra.join(".git").join("config");
    assert!(
        !allows(
            &agent,
            "write_file",
            &serde_json::json!({"path": protected.to_string_lossy(), "content": "x"})
        ),
        "`.git/**` must still be a floor inside a granted root"
    );
}

// ---- row: sandbox-escalation-path --------------------------------------

/// Under cx-parity's `model_requested` approval — whose baseline is Allow,
/// which is exactly why a model-requested escalation used to be a no-op — a
/// call carrying `with_escalated_permissions` is forced to the Ask tier, the
/// door sees the model's justification, and a refusal stops the call.
#[test]
fn a_model_requested_escalation_is_forced_to_the_ask_tier_with_its_justification() {
    let door = RecordingDoor::answering(ApprovalOutcome::Deny);
    let mut agent = agent_for(plain("cx-parity", "escalate"));
    agent.set_permissions_approval_handler(Shared(door.clone()));

    assert!(
        allows(
            &agent,
            "bash",
            &serde_json::json!({"command": "cargo build"})
        ),
        "an ordinary command is not prompted under model_requested"
    );
    assert!(door.seen().is_empty(), "and the door was never consulted");

    assert!(
        !allows(
            &agent,
            "bash",
            &serde_json::json!({
                "command": "cargo build",
                "with_escalated_permissions": true,
                "justification": "the build writes outside the workspace",
            })
        ),
        "a refused escalation must stop the call"
    );
    let seen = door.seen();
    assert_eq!(seen.len(), 1, "exactly one prompt: {seen:?}");
    assert_eq!(seen[0].0, "bash");
    assert!(
        seen[0].1.contains("the build writes outside the workspace"),
        "the door must see the model's own justification: {seen:?}"
    );
}

/// An approved escalation proceeds; a deny rule is a floor it cannot lift.
#[test]
fn an_escalation_never_beats_a_deny_rule() {
    let mut agent = agent_for(resolved(
        "cx-parity",
        "escalate-deny",
        &["capabilities.permissions.rules.deny=[\"bash(rm -rf*)\"]".to_string()],
    ));
    agent.set_permissions_approval_handler(Answer(ApprovalOutcome::Allow));
    assert!(allows(
        &agent,
        "bash",
        &serde_json::json!({"command": "echo ok", "with_escalated_permissions": true})
    ));
    assert!(
        !allows(
            &agent,
            "bash",
            &serde_json::json!({
                "command": DENIED_COMMAND,
                "with_escalated_permissions": true,
                "justification": "trust me",
            })
        ),
        "a deny rule is a floor an escalation cannot lift"
    );
}

/// The tool refuses to honor the flag where no engine adjudicated it — "the
/// request is not the grant", checked on the tool itself.
#[tokio::test]
async fn the_escalation_flag_is_refused_without_the_permissions_engine() {
    let config = Config::builder().cwd(tmp("escalate-nogate")).build();
    let registry = crate::tools::ToolRegistry::from_config(&config);
    let bash = registry.get("bash").expect("bash is a default tool");
    let ctx = crate::tools::ToolContext::new(config.cwd.clone());
    let err = bash
        .execute(
            serde_json::json!({"command": "echo hi", "with_escalated_permissions": true}),
            &ctx,
        )
        .await
        .expect_err("with no engine there is no door to have granted it");
    assert!(
        err.to_string().contains("requires the permissions engine"),
        "{err}"
    );
}

/// cx-parity advertises the escalation CHANNEL to the model — without the
/// two argument names in the schema the model has no way to discover that an
/// unsandboxed rerun can even be asked for.
#[test]
fn the_escalation_channel_is_advertised_under_cx_parity() {
    let agent = agent_for(plain("cx-parity", "escalate-schema"));
    let bash = agent
        .tool_schemas()
        .into_iter()
        .find(|s| s.name == "bash")
        .expect("cx-parity advertises bash");
    let props = bash.parameters["properties"].as_object().unwrap();
    assert!(props.contains_key("with_escalated_permissions"));
    assert!(props.contains_key("justification"));
}

// ---- row: hook-plugin-permission-veto ----------------------------------

/// The ALLOW half: under cc-parity's `untrusted` approval every
/// non-auto-approved tool asks. A hook answering `allow` skips the prompt —
/// proved with a door that refuses everything, so a pass is only possible if
/// the hook answered on the user's behalf.
#[test]
fn a_hook_allow_answers_the_ask() {
    let door = RecordingDoor::answering(ApprovalOutcome::Deny);
    let mut agent = agent_for(plain("cc-parity", "hook-allow"));
    agent.set_permissions_approval_handler(Shared(door.clone()));
    let args = serde_json::json!({"command": "echo hi"});
    assert!(
        agent
            .permissions_gate_denial("bash", &args, HookDecision::Allow)
            .is_none(),
        "a hook `allow` must satisfy the Ask tier without the door"
    );
    assert!(door.seen().is_empty(), "and the door is never consulted");
    assert!(
        !allows(&agent, "bash", &args),
        "without the hook's answer the same call reaches the refusing door"
    );
}

/// The ASK half: a hook answering `ask` forces a prompt where the rules
/// alone would have allowed the call (cx-parity's `model_requested`
/// baseline), and the refusing door then stops it.
#[test]
fn a_hook_ask_forces_a_prompt_the_rules_would_not_have_asked_for() {
    let door = RecordingDoor::answering(ApprovalOutcome::Deny);
    let mut agent = agent_for(plain("cx-parity", "hook-ask"));
    agent.set_permissions_approval_handler(Shared(door.clone()));
    let args = serde_json::json!({"command": "echo hi"});
    assert!(allows(&agent, "bash", &args), "the rules alone allow it");
    assert!(
        agent
            .permissions_gate_denial("bash", &args, HookDecision::Ask)
            .is_some(),
        "the hook's `ask` must reach the door, which refused"
    );
    assert_eq!(door.seen().len(), 1, "and the door really was consulted");
}

/// A hook `allow` can never override a deny rule — the floor holds.
#[test]
fn a_hook_allow_cannot_lift_a_deny_rule() {
    let mut agent = agent_for(resolved(
        "cc-parity",
        "hook-floor",
        &["capabilities.permissions.rules.deny=[\"bash(rm -rf*)\"]".to_string()],
    ));
    agent.set_permissions_approval_handler(Answer(ApprovalOutcome::Allow));
    assert!(agent
        .permissions_gate_denial(
            "bash",
            &serde_json::json!({ "command": DENIED_COMMAND }),
            HookDecision::Allow
        )
        .is_some());
}

/// The REWRITE half, end to end through `prepare_tool_call`: the hook
/// replaces the arguments, and it is the REWRITTEN call the engine judges
/// and the tool would run — so a rewrite cannot launder a denied command
/// past the rules.
#[test]
fn a_hook_rewrite_is_what_the_engine_judges_and_what_runs() {
    let mut config = plain("cc-parity", "hook-rewrite");
    config.pre_tool_hook = Some(Box::new(|_name, _args| {
        PreToolOutcome::rewrite(serde_json::json!({"command": "echo REWRITTEN"}))
    }));
    let mut agent = agent_for(config);
    agent.set_permissions_approval_handler(Answer(ApprovalOutcome::Allow));
    let call = crate::message::ToolCall {
        id: "c1".to_string(),
        kind: "function".to_string(),
        function: crate::message::FunctionCall {
            name: "bash".to_string(),
            arguments: serde_json::json!({"command": "echo ORIGINAL"}).to_string(),
        },
    };
    match agent.prepare_tool_call(&call) {
        PreparedCall::Ready { name, args } => {
            assert_eq!(name, "bash");
            assert_eq!(args["command"], "echo REWRITTEN");
        }
        _ => panic!("expected a rewritten Ready"),
    }

    let mut config = resolved(
        "cc-parity",
        "hook-rewrite-deny",
        &["capabilities.permissions.rules.deny=[\"bash(rm -rf*)\"]".to_string()],
    );
    config.pre_tool_hook = Some(Box::new(|_n, _a| {
        PreToolOutcome::rewrite(serde_json::json!({ "command": DENIED_COMMAND }))
    }));
    let mut agent = agent_for(config);
    agent.set_permissions_approval_handler(Answer(ApprovalOutcome::Allow));
    let call = crate::message::ToolCall {
        id: "c2".to_string(),
        kind: "function".to_string(),
        function: crate::message::FunctionCall {
            name: "bash".to_string(),
            arguments: serde_json::json!({"command": "echo harmless"}).to_string(),
        },
    };
    match agent.prepare_tool_call(&call) {
        PreparedCall::Done((text, is_error)) => {
            assert!(is_error);
            assert!(text.contains("Deny"), "{text}");
        }
        _ => panic!("the gate must judge the REWRITTEN command, not the model's own"),
    }
}

/// A hook `deny` still refuses the call outright, with its reason — the half
/// that already worked, pinned so the widening did not lose it.
#[test]
fn a_hook_deny_still_refuses_with_its_reason() {
    let mut config = plain("cc-parity", "hook-deny");
    config.pre_tool_hook = Some(Box::new(|_n, _a| PreToolOutcome::deny("no shells today")));
    let mut agent = agent_for(config);
    agent.set_permissions_approval_handler(Answer(ApprovalOutcome::Allow));
    let call = crate::message::ToolCall {
        id: "c3".to_string(),
        kind: "function".to_string(),
        function: crate::message::FunctionCall {
            name: "bash".to_string(),
            arguments: serde_json::json!({"command": "echo hi"}).to_string(),
        },
    };
    match agent.prepare_tool_call(&call) {
        PreparedCall::Done((text, is_error)) => {
            assert!(is_error);
            assert!(text.contains("no shells today"), "{text}");
        }
        _ => panic!("expected a denial"),
    }
}

// ---- row: project-workspace-trust-gate ---------------------------------

/// Both presets ship `default = "ask"`. With a trust door installed that is
/// now a real question, and a refusal keeps the project's own instruction
/// file out of the prompt.
#[test]
fn a_refused_trust_prompt_keeps_project_instructions_out_of_the_prompt() {
    const MARKER: &str = "BP10-PROJECT-INSTRUCTION-MARKER";
    for preset in ["cc-parity", "cx-parity"] {
        let mut config = plain(preset, "trust-refuse");
        std::fs::write(config.cwd.join("CLAUDE.md"), MARKER).unwrap();
        std::fs::write(config.cwd.join("AGENTS.md"), MARKER).unwrap();
        assert!(config.trust_enabled, "{preset} enables the trust module");

        let blob = assemble_project_instructions(&config);
        assert!(
            blob.contains(MARKER),
            "{preset}: with no door to ask through, the text still loads"
        );

        let door = RecordingDoor::answering(ApprovalOutcome::Deny);
        config.trust_handler = Some(door.clone());
        let blob = assemble_project_instructions(&config);
        assert!(
            !blob.contains(MARKER),
            "{preset}: a refused workspace must not splice its own instructions"
        );
        assert!(
            blob.contains("this workspace is not trusted"),
            "{preset}: and it must say so, not fail silently"
        );
        assert_eq!(door.seen().len(), 1, "{preset}: the door was asked once");
        assert_eq!(
            door.seen()[0].0,
            "trust",
            "{preset}: on the one engine's own door"
        );
    }
}

/// "Yes, and don't ask again" is remembered per project and survives the
/// process; `revoke` puts it back to asking.
#[test]
fn a_remembered_trust_answer_survives_and_is_revocable() {
    const MARKER: &str = "BP10-PROJECT-INSTRUCTION-MARKER";
    let mut config = plain("cc-parity", "trust-remember");
    std::fs::write(config.cwd.join("CLAUDE.md"), MARKER).unwrap();

    let door = RecordingDoor::answering(ApprovalOutcome::AllowForSession);
    config.trust_handler = Some(door.clone());
    assert!(assemble_project_instructions(&config).contains(MARKER));
    assert_eq!(door.seen().len(), 1);

    // Same project, a door that would REFUSE: the recorded answer means it
    // is never asked.
    let refusing = RecordingDoor::answering(ApprovalOutcome::Deny);
    config.trust_handler = Some(refusing.clone());
    assert!(assemble_project_instructions(&config).contains(MARKER));
    assert!(
        refusing.seen().is_empty(),
        "the recorded answer skipped the door"
    );

    crate::trust::revoke(&config);
    assert!(!assemble_project_instructions(&config).contains(MARKER));
    assert_eq!(refusing.seen().len(), 1, "after a revoke it asks again");
}

/// One decision, three surfaces — and `plugins::is_trusted` routes through
/// it rather than keeping its own answer.
#[test]
fn the_same_decision_gates_plugins_hooks_and_instructions() {
    let mut config = plain("cx-parity", "trust-code");
    config.trust_handler = Some(RecordingDoor::answering(ApprovalOutcome::Deny));
    for surface in [
        crate::trust::TrustSurface::Plugins,
        crate::trust::TrustSurface::Hooks,
        crate::trust::TrustSurface::Instructions,
    ] {
        assert!(
            !crate::trust::is_trusted(&config, surface),
            "a refused workspace gates {surface:?} too"
        );
    }
    assert!(!crate::plugins::is_trusted(&config));
}

// ---- row: named-permission-profiles (cx column) ------------------------

/// A named bundle is selectable PER RUN, through the same layer
/// `--permission-profile` uses, and changes the resolved posture without
/// editing config.
#[test]
fn a_named_permission_profile_is_selectable_per_run() {
    let base = plain("cx-parity", "profile-base");
    assert_eq!(
        base.sandbox,
        crate::tools::SandboxPolicy::WorkspaceWrite,
        "cx-parity's own posture stands when no profile is named"
    );

    let picked = resolved(
        "cx-parity",
        "profile-ro",
        &["capabilities.permissions.profile=read-only".to_string()],
    );
    assert_eq!(picked.sandbox, crate::tools::SandboxPolicy::ReadOnly);
    // The bundle carries the fs tier, not the approval mode — see the
    // preset's own comment on why (C4/C6 couple `approval` to the loop's
    // shape, so a permission bundle must not silently change it).
    assert_eq!(picked.approval, base.approval);
}

/// The bundles INHERIT: `locked-down` extends `read-only`, carrying the
/// ancestor's posture plus its own deny rules — which land in the ONE engine
/// and therefore also hide the shell from the model.
#[test]
fn a_profile_extends_its_ancestor_and_its_rules_join_the_one_engine() {
    let config = resolved(
        "cx-parity",
        "profile-locked",
        &["capabilities.permissions.profile=locked-down".to_string()],
    );
    assert_eq!(
        config.sandbox,
        crate::tools::SandboxPolicy::ReadOnly,
        "inherited from `read-only`"
    );
    assert!(
        config.tool_deny_patterns.iter().any(|p| p == "bash"),
        "and its own deny rules are in the engine's deny tier"
    );
    let agent = agent_for(config);
    assert!(
        !agent.tool_schemas().iter().any(|s| s.name == "bash"),
        "a bare-name deny in a profile hides the tool, like any other"
    );
}

/// A profile may ADD a floor but never remove one the config already set.
#[test]
fn a_profile_cannot_remove_a_floor_the_base_layer_set() {
    let config = resolved(
        "cx-parity",
        "profile-monotonic",
        &[
            "capabilities.permissions.rules.deny=[\"bash(curl*)\"]".to_string(),
            "capabilities.permissions.profile=locked-down".to_string(),
        ],
    );
    assert!(
        config.tool_deny_patterns.iter().any(|p| p == "bash(curl*)"),
        "the base layer's own deny rule survives the bundle: {:?}",
        config.tool_deny_patterns
    );
    assert!(config.tool_deny_patterns.iter().any(|p| p == "bash"));
}

/// A profile name with no table behind it is a warning and a NO-OP — never a
/// silent posture change.
#[test]
fn an_unknown_profile_name_warns_and_changes_nothing() {
    let toml = crate::presets::lookup("cx-parity").unwrap();
    let overrides = vec!["capabilities.permissions.profile=nope".to_string()];
    let layers = ConfigLayers {
        overrides: &overrides,
        ..Default::default()
    };
    let r = resolve_with_layers(toml, &layers, &ResolveOptions { strict: true }).unwrap();
    assert_eq!(
        r.config.sandbox,
        crate::tools::SandboxPolicy::WorkspaceWrite
    );
    assert!(
        r.warnings.iter().any(|w| w.contains("names no")),
        "{:?}",
        r.warnings
    );
}

// ---- row: network-sandbox-domain-rules (the preset-armed half) ---------

/// Both presets now STATE their network posture; before this, neither set
/// `sandbox.network.*` at all, so no policy was active under either.
#[test]
fn the_presets_state_their_network_posture() {
    let cx = plain("cx-parity", "net-cx");
    assert!(
        cx.network_policy.as_ref().expect("cx sets it").enabled,
        "workspace_write cuts subprocess network"
    );
    let cc = plain("cc-parity", "net-cc");
    assert!(
        !cc.network_policy.as_ref().expect("cc states it").enabled,
        "CC's `/sandbox` (and its proxy) is opt-in"
    );
}

// ---- the engine stays ONE engine ---------------------------------------

/// Default-deny is intact: engine on, no door, an `Ask`-tier call is refused
/// under both presets.
#[test]
fn an_ask_with_no_door_still_denies_under_both_presets() {
    for preset in ["cc-parity", "cx-parity"] {
        let config = resolved(
            preset,
            "default-deny",
            &["capabilities.permissions.rules.ask=[\"bash(*)\"]".to_string()],
        );
        assert!(config.permissions_enabled, "{preset}");
        let agent = agent_for(config);
        assert!(
            !allows(&agent, "bash", &serde_json::json!({"command": "echo hi"})),
            "{preset}: no handler installed must deny an Ask"
        );
    }
}

/// Every gate BP-10 adds is a rule or a tier inside the one engine, so one
/// `deny` rule still beats all of them at once: a hook `allow`, a remembered
/// approval, and a model-requested escalation together cannot get a denied
/// command through.
#[test]
fn every_new_gate_still_loses_to_one_deny_rule() {
    let mut agent = agent_for(resolved(
        "cx-parity",
        "one-engine",
        &["capabilities.permissions.rules.deny=[\"bash(rm -rf*)\"]".to_string()],
    ));
    agent.set_permissions_approval_handler(Answer(ApprovalOutcome::AllowForSession));
    assert!(allows(
        &agent,
        "bash",
        &serde_json::json!({"command": "echo hi"})
    ));
    assert!(agent
        .permissions_gate_denial(
            "bash",
            &serde_json::json!({
                "command": DENIED_COMMAND,
                "with_escalated_permissions": true,
                "justification": "please",
            }),
            HookDecision::Allow
        )
        .is_some());
}