trusty-code 0.8.1

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
//! Runtime-decision tests for `crate::permissions::gate` and `session`
//! (#7948).
//!
//! Why: one test per acceptance criterion — `ask` blocks and resolves, a
//! timeout or an abandoned request denies, headless denies, `allow-asks`
//! allows, `allow_for_session` is remembered within a session and not across
//! sessions, and a credential in a subject is redacted.
//! What: `PermissionGate::evaluate` (pure) and `resolve` (async, against a real
//! broker), plus `redact_subject`.
//! Test: this module.

use std::sync::{Arc, Mutex};
use std::time::Duration;

use serde_json::json;

use crate::agents::config::AgentConfig;
use crate::agents::md_loader::project_embedded_md;
use crate::permissions::{
    Decision, DenySource, HARNESS_REGISTERED_TOOLS, Outcome, PermissionBroker, PermissionContext,
    PermissionDecision, PermissionEvents, PermissionGate, PermissionMode, SessionPermissions,
    redact_subject,
};

use super::{agent_with_allowlist, agent_with_permissions};

// ── The pure half: `PermissionGate::evaluate` ───────────────────────────────

/// The legacy allowlist is checked BEFORE the map, so a map cannot widen it.
#[test]
fn legacy_allowlist_denial_precedes_the_map() {
    let agent = agent_with_allowlist(&["read_file"], Some("permissions:\n  bash: allow\n"));
    assert_eq!(
        PermissionGate::evaluate(&agent, "bash", &json!({"command": "ls"})),
        Decision::Deny {
            rule: "tcode_tools allowlist".to_string()
        }
    );
}

/// An absent allowlist and an absent map permit every tool, as before #7948.
#[test]
fn legacy_allowlist_absent_means_every_tool() {
    assert_eq!(
        PermissionGate::evaluate(&AgentConfig::default(), "bash", &json!({"command": "ls"})),
        Decision::Allow
    );
}

/// A call no rule matches is allowed.
#[test]
fn unmatched_tool_is_allowed() {
    let agent = agent_with_permissions("permissions:\n  read_file: deny\n");
    assert_eq!(
        PermissionGate::evaluate(&agent, "bash", &json!({"command": "ls"})),
        Decision::Allow
    );
}

/// A `deny` rule evaluates to `Deny`, carrying the rule text.
#[test]
fn deny_rule_produces_deny() {
    let agent = agent_with_permissions("permissions:\n  bash:\n    \"rm *\": deny\n");
    assert_eq!(
        PermissionGate::evaluate(&agent, "bash", &json!({"command": "rm -rf build"})),
        Decision::Deny {
            rule: "bash[rm *]".to_string()
        }
    );
}

/// An `ask` rule evaluates to `Ask`, carrying the rule text.
#[test]
fn ask_rule_produces_ask() {
    let agent = agent_with_permissions("permissions:\n  \"mcp__*\": ask\n");
    assert_eq!(
        PermissionGate::evaluate(&agent, "mcp__fixture__search", &json!({"q": "x"})),
        Decision::Ask {
            rule: "mcp__*".to_string()
        }
    );
}

// ── Harness-registered tools vs. the legacy allowlist (#7948) ───────────────

/// The stock `pm` agent, loaded through the real embedded-agent path so the
/// test sees the shipped `tcode_tools:` line rather than a hand-written copy.
fn stock_pm_agent() -> AgentConfig {
    // #9013: the card is content, read from the running checkout.
    let root = trusty_common::test_harness::test_repo_root().expect("workspace root");
    let content =
        trusty_agents_common::agent_content::checkout_content(&root).expect("repo content");
    let md = crate::assets::content::direct_agent_from(&content, "pm")
        .expect("content carries pm.md")
        .expect("the built-in roster carries a Direct `pm` agent");
    project_embedded_md("pm", &md).expect("stock pm.md loads")
}

/// #7948 regression: `delegate_to_agent` is registered on the PM
/// unconditionally (`run_task::execute_run_task`, `task::executor`), yet stock
/// `pm.md` never lists it, so the allowlist branch refused the PM's own
/// delegation on both run-task paths.
#[test]
fn stock_pm_agent_may_call_delegate_to_agent() {
    let pm = stock_pm_agent();
    let allowed = pm
        .tools
        .as_ref()
        .and_then(|t| t.allowed.as_ref())
        .expect("stock pm.md declares a tcode_tools allowlist");
    assert!(
        !allowed.iter().any(|t| t == "delegate_to_agent"),
        "fixture premise: stock pm.md must still omit delegate_to_agent, got {allowed:?}"
    );
    assert_eq!(
        PermissionGate::evaluate(
            &pm,
            "delegate_to_agent",
            &json!({"agent_name": "engineer", "task": "build it"})
        ),
        Decision::Allow
    );
}

/// #8235 regression: `todo_write` is registered on the session agent
/// unconditionally (`task::executor::run_and_record`) and stock `pm.md` does
/// not list it, so without the harness exemption the gate refuses the agent's
/// own checklist — which is how the tool's first end-to-end run failed, with
/// `denied by policy (tcode_tools allowlist)`.
#[test]
fn stock_pm_agent_may_call_todo_write() {
    let pm = stock_pm_agent();
    let allowed = pm
        .tools
        .as_ref()
        .and_then(|t| t.allowed.as_ref())
        .expect("stock pm.md declares a tcode_tools allowlist");
    assert!(
        !allowed.iter().any(|t| t == "todo_write"),
        "fixture premise: stock pm.md must still omit todo_write, got {allowed:?}"
    );
    assert_eq!(
        PermissionGate::evaluate(
            &pm,
            "todo_write",
            &json!({"todos": [{"content": "plan", "status": "in_progress"}]})
        ),
        Decision::Allow
    );
}

/// Every tool the harness registers clears an allowlist naming none of them.
#[test]
fn harness_registered_tool_bypasses_the_legacy_allowlist() {
    let agent = agent_with_allowlist(&["read_file"], None);
    for tool in HARNESS_REGISTERED_TOOLS {
        assert_eq!(
            PermissionGate::evaluate(&agent, tool, &json!({})),
            Decision::Allow,
            "{tool} is harness-registered and must clear the allowlist"
        );
    }
}

/// The exemption is a closed list, not a widening — a tool the author left out
/// is still denied by the allowlist.
#[test]
fn harness_exemption_does_not_widen_an_ordinary_tool() {
    let agent = agent_with_allowlist(&["read_file"], None);
    assert_eq!(
        PermissionGate::evaluate(&agent, "bash", &json!({"command": "ls"})),
        Decision::Deny {
            rule: "tcode_tools allowlist".to_string()
        }
    );
}

/// An operator's written `deny` still refuses a harness-registered tool: the
/// exemption waives only the allowlist's blanket "absent means denied".
#[test]
fn explicit_deny_beats_the_harness_registered_exemption() {
    let agent = agent_with_allowlist(
        &["read_file"],
        Some("permissions:\n  delegate_to_agent: deny\n"),
    );
    assert_eq!(
        PermissionGate::evaluate(&agent, "delegate_to_agent", &json!({"agent_name": "qa"})),
        Decision::Deny {
            rule: "delegate_to_agent".to_string()
        }
    );
}

/// (#7948 regression) A path `deny` written RELATIVE refuses the absolute
/// in-root spelling of the same file once the gate knows the run's root.
///
/// Why: `tools::fs::scoped_path` accepts an absolute path inside the working
/// root, so both spellings reach the same file; before the root was threaded
/// into `PermissionContext`, only the relative one met the rule.
/// What: the same agent and the same absolute path, decided with and without a
/// root — the pair pins that the root, not the rule text, is what closed it.
#[tokio::test]
async fn absolute_in_root_path_meets_a_relative_deny() {
    let agent = agent_with_permissions("permissions:\n  read_file:\n    \"secrets/**\": deny\n");
    let root = std::path::PathBuf::from("/Users/me/proj");
    let call = json!({"path": "/Users/me/proj/secrets/x"});

    let rooted = PermissionContext::headless(PermissionMode::Default).with_root(root);
    assert_eq!(
        gate(&rooted, agent.clone())
            .resolve("read_file", &call)
            .await,
        Outcome::Denied {
            rule: "read_file[secrets/**]".to_string(),
            source: DenySource::Policy
        }
    );

    let rootless = PermissionContext::headless(PermissionMode::Default);
    assert_eq!(
        gate(&rootless, agent).resolve("read_file", &call).await,
        Outcome::Allow,
        "with no root the gate can only judge the spelling the model wrote"
    );
}

// ── The async half: `PermissionGate::resolve` ───────────────────────────────

/// A recording `PermissionEvents` sink; the event is also how a test learns a
/// request id, exactly as a real client does.
#[derive(Default)]
struct RecordingEvents {
    lines: Mutex<Vec<String>>,
    request_ids: Mutex<Vec<String>>,
    /// #8100: `false` (the default) is "a client is watching", which is what
    /// every interactive test in this module assumes.
    detached: std::sync::atomic::AtomicBool,
}

impl RecordingEvents {
    fn lines(&self) -> Vec<String> {
        self.lines.lock().expect("lock").clone()
    }

    fn pending_request_id(&self) -> Option<String> {
        self.request_ids.lock().expect("lock").last().cloned()
    }

    /// #8100: a sink nobody is reading — the daemon `task.run` shape.
    fn detached() -> Self {
        Self {
            detached: std::sync::atomic::AtomicBool::new(true),
            ..Self::default()
        }
    }
}

impl PermissionEvents for RecordingEvents {
    fn permission_requested(
        &self,
        _session_id: &str,
        request_id: &str,
        agent: &str,
        _agent_id: &str,
        tool: &str,
        subject: &str,
        rule: &str,
    ) {
        self.lines
            .lock()
            .expect("lock")
            .push(format!("requested {agent} {tool} {subject} {rule}"));
        self.request_ids
            .lock()
            .expect("lock")
            .push(request_id.to_string());
    }

    fn permission_resolved(
        &self,
        _session_id: &str,
        _request_id: &str,
        _agent: &str,
        _agent_id: &str,
        decision: &str,
        source: &str,
    ) {
        self.lines
            .lock()
            .expect("lock")
            .push(format!("resolved {decision} {source}"));
    }

    fn prompter_attached(&self, _session_id: &str) -> bool {
        !self.detached.load(std::sync::atomic::Ordering::Relaxed)
    }
}

/// An interactive context wired to `broker`'s slot for `session`.
fn interactive_ctx(
    broker: &PermissionBroker,
    session: &str,
    timeout: Duration,
) -> (PermissionContext, Arc<RecordingEvents>) {
    ctx_with_events(broker, session, timeout, RecordingEvents::default())
}

/// [`interactive_ctx`] with the sink supplied, so a test can build the
/// no-client shape (#8100).
fn ctx_with_events(
    broker: &PermissionBroker,
    session: &str,
    timeout: Duration,
    sink: RecordingEvents,
) -> (PermissionContext, Arc<RecordingEvents>) {
    let events = Arc::new(sink);
    let ctx = PermissionContext {
        mode: PermissionMode::Default,
        timeout,
        session_id: session.to_string(),
        ask: Some(broker.session(session)),
        events: Some(Arc::clone(&events) as Arc<dyn PermissionEvents>),
        root: None,
        delegator: None,
    };
    (ctx, events)
}

fn gate(ctx: &PermissionContext, agent: AgentConfig) -> PermissionGate {
    ctx.gate_for(Arc::new(agent), "agent-1")
}

fn ask_bash() -> AgentConfig {
    agent_with_permissions("permissions:\n  bash: ask\n")
}

/// #8288 FAIL-OPEN CHECK: a delegator's own write is denied before every
/// widening path — an explicit `allow` rule, `allow-asks` mode, and arguments
/// that do not even parse — while another agent on the same context, and the
/// delegator's own reads, keep their normal decision.
/// Test: this test.
#[tokio::test]
async fn delegator_write_is_denied_before_any_rule() {
    let ctx = PermissionContext::headless(PermissionMode::AllowAsks).with_delegator("t");
    let delegator =
        agent_with_permissions("permissions:\n  write_file: allow\n  edit: ask\n  bash: ask\n");
    let denied = Outcome::Denied {
        rule: crate::permissions::gate::DELEGATOR_DENY_RULE.to_string(),
        source: DenySource::Policy,
    };
    for (tool, args) in [
        ("write_file", json!({"path": "src/lib.rs", "content": "x"})),
        ("write_file", json!("not an object")),
        ("write_files", json!(null)),
        ("edit", json!({"path": "src/lib.rs"})),
        ("bash", json!({"command": "echo x > src/lib.rs"})),
    ] {
        let outcome = gate(&ctx, delegator.clone()).resolve(tool, &args).await;
        assert_eq!(outcome, denied, "{tool}({args}) must be denied");
    }
    assert_eq!(
        gate(&ctx, delegator.clone())
            .resolve("read_file", &json!({"path": "src/lib.rs"}))
            .await,
        Outcome::Allow,
        "the lock covers writes only"
    );

    let mut other = delegator;
    other.agent.name = "engineer".into();
    assert_eq!(
        gate(&ctx, other)
            .resolve("write_file", &json!({"path": "src/lib.rs", "content": "x"}))
            .await,
        Outcome::Allow,
        "a delegated engineer keeps its own write decision"
    );
}

/// #8288: the delegator lock ignores case. A disk card with no `name:` takes
/// its name from the requested file stem, so on a case-insensitive filesystem
/// `delegate_to_agent("PM")` loads `pm.md` named "PM".
/// FAILS at 97038f5a23: the exact comparison misses and the `ask` is allowed.
/// Test: this test.
#[tokio::test]
async fn delegator_lock_ignores_case() {
    let ctx = PermissionContext::headless(PermissionMode::AllowAsks).with_delegator("pm");
    let mut card = agent_with_permissions("permissions:\n  write_file: ask\n");
    card.agent.name = "PM".into();
    assert_eq!(
        gate(&ctx, card)
            .resolve("write_file", &json!({"path": "src/lib.rs", "content": "x"}))
            .await,
        Outcome::Denied {
            rule: crate::permissions::gate::DELEGATOR_DENY_RULE.to_string(),
            source: DenySource::Policy,
        }
    );
}

/// A gate for an agent with no map allows everything.
#[tokio::test]
async fn gate_for_agent_without_a_map_allows_everything() {
    let ctx = PermissionContext::headless(PermissionMode::Default);
    let outcome = gate(&ctx, AgentConfig::default())
        .resolve("bash", &json!({"command": "rm -rf /"}))
        .await;
    assert_eq!(outcome, Outcome::Allow);
}

/// HEADLESS: an `ask` with no client to answer it is denied.
#[tokio::test]
async fn headless_ask_is_denied() {
    let ctx = PermissionContext::headless(PermissionMode::Default);
    assert_eq!(
        gate(&ctx, ask_bash())
            .resolve("bash", &json!({"command": "ls"}))
            .await,
        Outcome::Denied {
            rule: "bash".to_string(),
            source: DenySource::Headless
        }
    );
}

/// (#8100) HEADLESS, the daemon shape: broker state exists — `task.run`
/// always mints it — but no client is watching, so the `ask` denies at once
/// instead of sitting out `DEFAULT_ASK_TIMEOUT_SECS`.
///
/// The `tokio::time::timeout` is the assertion: the context carries the real
/// 300 s ask budget, so a gate that still waits fails here in 200 ms rather
/// than hanging the suite.
#[tokio::test]
async fn ask_without_an_attached_prompter_denies_immediately() {
    let broker = PermissionBroker::new();
    let (ctx, events) = ctx_with_events(
        &broker,
        "s-no-client",
        Duration::from_secs(crate::permissions::DEFAULT_ASK_TIMEOUT_SECS),
        RecordingEvents::detached(),
    );
    let gate = gate(&ctx, ask_bash());

    let outcome = tokio::time::timeout(
        Duration::from_millis(200),
        gate.resolve("bash", &json!({"command": "ls"})),
    )
    .await
    .expect("an ask nobody can answer must not wait out the ask timeout");

    assert_eq!(
        outcome,
        Outcome::Denied {
            rule: "bash".to_string(),
            source: DenySource::Headless
        }
    );
    assert_eq!(
        outcome.message().as_deref(),
        Some("denied by policy (bash): headless run")
    );
    assert!(
        events.lines().is_empty(),
        "nothing was asked, so nothing may be published: {:?}",
        events.lines()
    );
}

/// (#8100) An `ask` with a rendezvous but no event sink is headless too: the
/// request id only reaches a client through the event, so an unpublished
/// request can never be answered.
#[tokio::test]
async fn an_ask_with_no_event_sink_is_headless() {
    let broker = PermissionBroker::new();
    let ctx = PermissionContext {
        ask: Some(broker.session("s-silent")),
        ..PermissionContext::headless(PermissionMode::Default)
    };

    let outcome = tokio::time::timeout(
        Duration::from_millis(200),
        gate(&ctx, ask_bash()).resolve("bash", &json!({"command": "ls"})),
    )
    .await
    .expect("an unpublishable ask must not wait out the ask timeout");

    assert_eq!(
        outcome,
        Outcome::Denied {
            rule: "bash".to_string(),
            source: DenySource::Headless
        }
    );
}

/// (#8100) The cross-session regression, against the REAL `SessionRegistry`
/// sink: one attached session and one headless sibling. The sibling's `ask`
/// denies at once; the watched session's still suspends for its client.
///
/// Why this shape: the first cut read `crate::events::bus().receiver_count()`,
/// which is daemon-global, so the sibling read as watched and went back to the
/// 300 s stall. Both contexts carry the real [`DEFAULT_ASK_TIMEOUT_SECS`]
/// budget, so a daemon-global reading fails here in 200 ms rather than hanging.
#[tokio::test]
async fn an_ask_on_an_unwatched_session_is_headless_while_a_sibling_is_watched() {
    use crate::binding::ProjectBinding;
    use crate::permissions::DEFAULT_ASK_TIMEOUT_SECS;
    use crate::session::registry::SessionRegistry;
    use uuid::Uuid;

    let registry = Arc::new(SessionRegistry::new());
    let watched = registry.create("watched".to_string(), None, ProjectBinding::None);
    let headless = registry.create("headless".to_string(), None, ProjectBinding::None);
    let broker = PermissionBroker::new();
    let (notify, _held) = tokio::sync::mpsc::unbounded_channel();
    registry
        .attach(&watched.id, Uuid::new_v4(), notify)
        .expect("attach must succeed");

    let ctx_for = |session_id: &str| PermissionContext {
        mode: PermissionMode::Default,
        timeout: Duration::from_secs(DEFAULT_ASK_TIMEOUT_SECS),
        session_id: session_id.to_string(),
        ask: Some(broker.session(session_id)),
        events: Some(Arc::clone(&registry) as Arc<dyn PermissionEvents>),
        root: None,
        delegator: None,
    };
    let agent = Arc::new(ask_bash());

    let denied = tokio::time::timeout(
        Duration::from_millis(200),
        ctx_for(&headless.id)
            .gate_for(Arc::clone(&agent), "agent-1")
            .resolve("bash", &json!({"command": "ls"})),
    )
    .await
    .expect("an unwatched session must not wait out the ask timeout");
    assert_eq!(
        denied,
        Outcome::Denied {
            rule: "bash".to_string(),
            source: DenySource::Headless
        }
    );

    // The watched session still suspends: it reaches the 200 ms boundary
    // unresolved, which is what "waiting for its client" looks like.
    let pending = tokio::time::timeout(
        Duration::from_millis(200),
        ctx_for(&watched.id)
            .gate_for(agent, "agent-2")
            .resolve("bash", &json!({"command": "ls"})),
    )
    .await;
    assert!(
        pending.is_err(),
        "the watched session's ask must still be waiting for its client: {pending:?}"
    );
}

/// `allow-asks` permits an `ask` a headless run could not put to anyone.
#[tokio::test]
async fn allow_asks_mode_permits_an_ask() {
    let ctx = PermissionContext::headless(PermissionMode::AllowAsks);
    assert_eq!(
        gate(&ctx, ask_bash())
            .resolve("bash", &json!({"command": "ls"}))
            .await,
        Outcome::Allow
    );
}

/// (#7948) `allow-asks` leaves an audit trail: the auto-approval emits
/// `permission_resolved` marked `allow_asks`, with no request event before it.
#[tokio::test]
async fn allow_asks_mode_emits_an_audit_event() {
    let events = Arc::new(RecordingEvents::default());
    let ctx = PermissionContext {
        events: Some(Arc::clone(&events) as Arc<dyn PermissionEvents>),
        ..PermissionContext::headless(PermissionMode::AllowAsks)
    };
    let outcome = gate(&ctx, ask_bash())
        .resolve("bash", &json!({"command": "ls"}))
        .await;
    assert_eq!(outcome, Outcome::Allow);
    assert_eq!(events.lines(), vec!["resolved allow_once allow_asks"]);
}

/// `allow-asks` does NOT soften a `deny`.
#[tokio::test]
async fn allow_asks_mode_does_not_soften_a_deny() {
    let ctx = PermissionContext::headless(PermissionMode::AllowAsks);
    let agent = agent_with_permissions("permissions:\n  bash: deny\n");
    assert!(matches!(
        gate(&ctx, agent)
            .resolve("bash", &json!({"command": "ls"}))
            .await,
        Outcome::Denied {
            source: DenySource::Policy,
            ..
        }
    ));
}

/// TIMEOUT: an `ask` nobody answers inside the budget resolves to deny.
#[tokio::test]
async fn timed_out_ask_is_denied() {
    let broker = PermissionBroker::new();
    let (ctx, events) = interactive_ctx(&broker, "s-timeout", Duration::from_millis(30));
    let outcome = gate(&ctx, ask_bash())
        .resolve("bash", &json!({"command": "ls"}))
        .await;
    assert_eq!(
        outcome,
        Outcome::Denied {
            rule: "bash".to_string(),
            source: DenySource::Timeout
        }
    );
    assert_eq!(
        outcome.message().as_deref(),
        Some("denied by policy (bash): no decision")
    );
    assert_eq!(
        events.lines().last().map(String::as_str),
        Some("resolved deny timeout")
    );
}

/// FAIL-CLOSED (#7948): a request whose responder is dropped without an answer
/// resolves to deny long before the timeout — an error never becomes an allow.
#[tokio::test]
async fn abandoned_request_resolves_to_deny() {
    let broker = Arc::new(PermissionBroker::new());
    let (ctx, events) = interactive_ctx(&broker, "s-abandon", Duration::from_secs(30));
    let state = broker.session("s-abandon");
    let abandoning = tokio::spawn({
        let events = Arc::clone(&events);
        async move {
            let id = wait_for_request(&events).await;
            state.forget(&id);
        }
    });
    let started = std::time::Instant::now();
    let outcome = gate(&ctx, ask_bash())
        .resolve("bash", &json!({"command": "ls"}))
        .await;
    abandoning.await.expect("abandoning task must not panic");
    assert!(matches!(
        outcome,
        Outcome::Denied {
            source: DenySource::Timeout,
            ..
        }
    ));
    assert!(
        started.elapsed() < Duration::from_secs(10),
        "a dropped responder must resolve at once, not wait out the timeout"
    );
}

/// A client's `deny` refuses the call.
#[tokio::test]
async fn client_deny_is_denied() {
    let broker = Arc::new(PermissionBroker::new());
    let (ctx, events) = interactive_ctx(&broker, "s-deny", Duration::from_secs(5));
    let answering = answer_next_request(&broker, "s-deny", events, PermissionDecision::Deny);
    let outcome = gate(&ctx, ask_bash())
        .resolve("bash", &json!({"command": "ls"}))
        .await;
    answering.await.expect("answering task must not panic");
    assert!(matches!(
        outcome,
        Outcome::Denied {
            source: DenySource::Client,
            ..
        }
    ));
}

/// The request/resolve event pair is emitted around an answered `ask`.
///
/// #8100: this is also the ATTACHED arm — `interactive_ctx` builds a sink that
/// reports a watching client, and the round trip must still happen in full.
#[tokio::test]
async fn ask_emits_requested_then_resolved() {
    let broker = Arc::new(PermissionBroker::new());
    let (ctx, events) = interactive_ctx(&broker, "s-events", Duration::from_secs(5));
    let answering = answer_next_request(
        &broker,
        "s-events",
        Arc::clone(&events),
        PermissionDecision::AllowOnce,
    );
    let outcome = gate(&ctx, ask_bash())
        .resolve("bash", &json!({"command": "ls -la"}))
        .await;
    answering.await.expect("answering task must not panic");

    assert_eq!(outcome, Outcome::Allow);
    assert_eq!(
        events.lines(),
        vec!["requested t bash ls -la bash", "resolved allow_once client"]
    );
}

/// `allow_for_session` is remembered for a later matching call in the SAME
/// session — the second call emits no second request.
#[tokio::test]
async fn allow_for_session_is_remembered_for_a_later_matching_call() {
    let broker = Arc::new(PermissionBroker::new());
    let (ctx, events) = interactive_ctx(&broker, "s-remember", Duration::from_secs(5));
    let gate = gate(&ctx, ask_bash());
    let answering = answer_next_request(
        &broker,
        "s-remember",
        Arc::clone(&events),
        PermissionDecision::AllowForSession {
            pattern: Some("git *".to_string()),
        },
    );
    let first = gate
        .resolve("bash", &json!({"command": "git status"}))
        .await;
    answering.await.expect("answering task must not panic");
    assert_eq!(first, Outcome::Allow);

    let second = gate.resolve("bash", &json!({"command": "git diff"})).await;
    assert_eq!(second, Outcome::Allow);
    // #7948: the reuse is recorded, but nobody is asked again — one resolution
    // with no `requested` before it, not a second request/resolve pair.
    assert_eq!(
        events.lines(),
        vec![
            "requested t bash git status bash",
            "resolved allow_for_session client",
            "resolved allow_for_session remembered",
        ]
    );
}

/// (#7948 regression) Reusing a remembered grant emits `permission_resolved`,
/// so an audit sees the call the grant covered.
///
/// Why: the short-circuit returned `Outcome::Allow` with no log and no event,
/// making every call after the first one invisible — the grant's whole point is
/// that there is no prompt to see instead.
/// What: one `allow_for_session` answer, then a second matching call; assert
/// the second call's own resolution line, sourced `remembered` rather than
/// `client` because no client was consulted.
#[tokio::test]
async fn remembered_grant_emits_a_resolution_event() {
    let broker = Arc::new(PermissionBroker::new());
    let (ctx, events) = interactive_ctx(&broker, "s-remember-event", Duration::from_secs(5));
    let gate = gate(&ctx, ask_bash());
    let answering = answer_next_request(
        &broker,
        "s-remember-event",
        Arc::clone(&events),
        PermissionDecision::AllowForSession {
            pattern: Some("git *".to_string()),
        },
    );
    let first = gate
        .resolve("bash", &json!({"command": "git status"}))
        .await;
    answering.await.expect("answering task must not panic");
    assert_eq!(first, Outcome::Allow);

    let before = events.lines().len();
    assert_eq!(
        gate.resolve("bash", &json!({"command": "git diff"})).await,
        Outcome::Allow
    );
    assert_eq!(
        events.lines().get(before..),
        Some(["resolved allow_for_session remembered".to_string()].as_slice()),
        "the remembered grant must record the call it covered"
    );
}

/// A remembered grant does not leak into another session.
#[tokio::test]
async fn allow_for_session_does_not_leak_across_sessions() {
    let broker = Arc::new(PermissionBroker::new());
    let (first, events) = interactive_ctx(&broker, "s-a", Duration::from_secs(5));
    let answering = answer_next_request(
        &broker,
        "s-a",
        events,
        PermissionDecision::AllowForSession {
            pattern: Some("git *".to_string()),
        },
    );
    let granted = gate(&first, ask_bash())
        .resolve("bash", &json!({"command": "git status"}))
        .await;
    answering.await.expect("answering task must not panic");
    assert_eq!(granted, Outcome::Allow);

    let (second, _events) = interactive_ctx(&broker, "s-b", Duration::from_millis(30));
    let other = gate(&second, ask_bash())
        .resolve("bash", &json!({"command": "git diff"}))
        .await;
    assert!(
        matches!(
            other,
            Outcome::Denied {
                source: DenySource::Timeout,
                ..
            }
        ),
        "session A's grant must not reach session B"
    );
}

/// A bare `allow_for_session` (no pattern) grants exactly that subject.
#[tokio::test]
async fn bare_allow_for_session_grants_only_that_subject() {
    let broker = Arc::new(PermissionBroker::new());
    let (ctx, events) = interactive_ctx(&broker, "s-bare", Duration::from_millis(30));
    let gate = gate(&ctx, ask_bash());
    let answering = answer_next_request(
        &broker,
        "s-bare",
        events,
        PermissionDecision::AllowForSession { pattern: None },
    );
    let first = gate
        .resolve("bash", &json!({"command": "git status"}))
        .await;
    answering.await.expect("answering task must not panic");
    assert_eq!(first, Outcome::Allow);

    assert_eq!(
        gate.resolve("bash", &json!({"command": "git status"}))
            .await,
        Outcome::Allow,
        "the exact same subject is covered"
    );
    assert!(
        matches!(
            gate.resolve("bash", &json!({"command": "git status --short"}))
                .await,
            Outcome::Denied { .. }
        ),
        "a bare grant must not widen to a prefix match"
    );
}

/// A client-supplied pattern grants the whole glob.
#[tokio::test]
async fn allow_for_session_pattern_grants_the_glob() {
    let broker = Arc::new(PermissionBroker::new());
    let (ctx, events) = interactive_ctx(&broker, "s-glob", Duration::from_millis(30));
    let gate = gate(&ctx, ask_bash());
    let answering = answer_next_request(
        &broker,
        "s-glob",
        events,
        PermissionDecision::AllowForSession {
            pattern: Some("*".to_string()),
        },
    );
    let first = gate
        .resolve("bash", &json!({"command": "git status"}))
        .await;
    answering.await.expect("answering task must not panic");
    assert_eq!(first, Outcome::Allow);
    assert_eq!(
        gate.resolve("bash", &json!({"command": "anything at all"}))
            .await,
        Outcome::Allow
    );
}

/// An uncompilable pattern still allows THIS call but remembers nothing.
#[tokio::test]
async fn unusable_allow_for_session_pattern_remembers_nothing() {
    let broker = Arc::new(PermissionBroker::new());
    let (ctx, events) = interactive_ctx(&broker, "s-badglob", Duration::from_millis(30));
    let gate = gate(&ctx, ask_bash());
    let answering = answer_next_request(
        &broker,
        "s-badglob",
        events,
        PermissionDecision::AllowForSession {
            pattern: Some("a[".to_string()),
        },
    );
    let first = gate
        .resolve("bash", &json!({"command": "git status"}))
        .await;
    answering.await.expect("answering task must not panic");
    assert_eq!(first, Outcome::Allow);
    assert!(matches!(
        gate.resolve("bash", &json!({"command": "git status"}))
            .await,
        Outcome::Denied { .. }
    ));
}

/// The refusal message names the rule that produced it.
#[test]
fn deny_message_names_the_rule() {
    let denied = Outcome::Denied {
        rule: "bash[rm *]".to_string(),
        source: DenySource::Policy,
    };
    assert_eq!(
        denied.message().as_deref(),
        Some("denied by policy (bash[rm *])")
    );
    assert!(Outcome::Allow.message().is_none());
}

// ── Broker / responder ──────────────────────────────────────────────────────

/// The broker hands back the same state for one session id.
#[test]
fn broker_hands_the_same_state_back_for_one_session() {
    let broker = PermissionBroker::new();
    let a = broker.session("s");
    assert!(Arc::ptr_eq(&a, &broker.session("s")));
    assert!(!Arc::ptr_eq(&a, &broker.session("other")));
}

/// Answering a request nobody is waiting on is a client error.
#[test]
fn respond_to_unknown_request_is_an_error() {
    let err = SessionPermissions::default()
        .respond("missing", PermissionDecision::AllowOnce)
        .expect_err("an unknown request id must be rejected");
    assert!(err.message.contains("missing"), "{}", err.message);
}

/// Answering a session that has never asked anything is a client error.
#[test]
fn respond_to_unknown_session_is_an_error() {
    let err = PermissionBroker::new()
        .respond("nope", "req", PermissionDecision::AllowOnce)
        .expect_err("an unknown session must be rejected");
    assert!(err.message.contains("nope"), "{}", err.message);
}

/// A response delivered while a gate waits resolves that gate.
#[tokio::test]
async fn respond_resolves_the_waiting_gate() {
    let broker = Arc::new(PermissionBroker::new());
    let (ctx, events) = interactive_ctx(&broker, "s-resp", Duration::from_secs(5));
    let answering = answer_next_request(&broker, "s-resp", events, PermissionDecision::AllowOnce);
    let outcome = gate(&ctx, ask_bash())
        .resolve("bash", &json!({"command": "ls"}))
        .await;
    answering.await.expect("answering task must not panic");
    assert_eq!(outcome, Outcome::Allow);
}

// ── Mode resolution ─────────────────────────────────────────────────────────

/// The `allow-asks` spellings an operator might type all parse.
#[test]
fn permission_mode_parses_allow_asks_spellings() {
    for spelling in ["allow-asks", "allow_asks", "ALLOW-ASKS", "  allow-asks "] {
        assert_eq!(
            PermissionMode::parse_lenient(spelling),
            Some(PermissionMode::AllowAsks),
            "{spelling}"
        );
    }
    assert_eq!(
        PermissionMode::parse_lenient("default"),
        Some(PermissionMode::Default)
    );
    assert_eq!(PermissionMode::parse_lenient("yolo"), None);
}

/// A flag outranks the environment variable.
#[test]
fn cli_permission_mode_outranks_the_env_var() {
    assert_eq!(
        PermissionMode::resolve_from(Some("default"), Some("allow-asks")),
        PermissionMode::Default
    );
}

/// With no flag, the environment variable applies.
#[test]
fn env_permission_mode_applies_when_no_flag_is_given() {
    assert_eq!(
        PermissionMode::resolve_from(None, Some("allow-asks")),
        PermissionMode::AllowAsks
    );
}

/// FAIL-CLOSED: an unrecognised value never widens; the next tier or `Default`
/// applies.
#[test]
fn unrecognised_permission_mode_falls_back_to_default() {
    assert_eq!(
        PermissionMode::resolve_from(Some("yolo"), None),
        PermissionMode::Default
    );
    assert_eq!(
        PermissionMode::resolve_from(Some("yolo"), Some("allow-asks")),
        PermissionMode::AllowAsks
    );
    assert_eq!(
        PermissionMode::resolve_from(None, Some("yolo")),
        PermissionMode::Default
    );
}

// ── Redaction ───────────────────────────────────────────────────────────────

/// A lowercase `token=` assignment is redacted.
#[test]
fn redacts_a_lowercase_token_assignment() {
    let out = redact_subject("curl -d token=abc123 https://example.test");
    assert!(!out.contains("abc123"), "{out}");
    assert!(out.contains("token=<redacted>"), "{out}");
}

/// An uppercase environment assignment prefixing a command is redacted.
#[test]
fn redacts_an_uppercase_env_assignment() {
    let out = redact_subject("GITHUB_TOKEN=ghp_realsecret gh pr create");
    assert!(!out.contains("ghp_realsecret"), "{out}");
    assert!(out.contains("GITHUB_TOKEN=<redacted>"), "{out}");
    assert!(out.contains("gh pr create"), "{out}");
}

/// An `Authorization:` header value is redacted.
#[test]
fn redacts_an_authorization_header() {
    // #7948: a value under 8 chars stays below gitleaks' `curl-auth-header` rule.
    let out = redact_subject("curl -H 'Authorization: Bearer abc123' https://example.test");
    assert!(!out.contains("abc123"), "{out}");
    assert!(out.contains("Authorization: <redacted>"), "{out}");
}

/// An ordinary command passes through untouched.
#[test]
fn leaves_an_ordinary_command_untouched() {
    let command = "cargo test -p trusty-code --no-fail-fast";
    assert_eq!(redact_subject(command), command);
}

/// The subject is bounded so a multi-KB command cannot saturate the bus.
#[test]
fn bounds_the_subject_to_500_chars() {
    assert_eq!(redact_subject(&"a".repeat(2_000)).chars().count(), 501);
}

// ── Helpers ─────────────────────────────────────────────────────────────────

/// Poll the recorder until a request id appears (5 s hang guard).
async fn wait_for_request(events: &RecordingEvents) -> String {
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    loop {
        if let Some(id) = events.pending_request_id() {
            return id;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "no permission request arrived within 5s"
        );
        tokio::time::sleep(Duration::from_millis(2)).await;
    }
}

/// Answer the next `PermissionRequested` through the broker — the same round
/// trip a real client makes.
fn answer_next_request(
    broker: &Arc<PermissionBroker>,
    session: &str,
    events: Arc<RecordingEvents>,
    decision: PermissionDecision,
) -> tokio::task::JoinHandle<()> {
    let broker = Arc::clone(broker);
    let session = session.to_string();
    tokio::spawn(async move {
        let id = wait_for_request(&events).await;
        broker
            .respond(&session, &id, decision)
            .expect("respond must succeed");
    })
}