harn-vm 0.10.141

Async bytecode virtual machine for the Harn programming language
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
use std::collections::BTreeMap;

use super::*;
use crate::orchestration::{pop_execution_policy, push_execution_policy, CapabilityPolicy};
use crate::tool_annotations::{SideEffectLevel, ToolAnnotations, ToolArgSchema, ToolKind};

fn policy_with_path_annotation(tool: &str, kind: ToolKind) {
    let mut annotations = BTreeMap::new();
    annotations.insert(
        tool.to_string(),
        ToolAnnotations {
            kind,
            side_effect_level: match kind {
                ToolKind::Fetch => SideEffectLevel::Network,
                ToolKind::Execute => SideEffectLevel::ProcessExec,
                ToolKind::Edit | ToolKind::Delete | ToolKind::Move => {
                    SideEffectLevel::WorkspaceWrite
                }
                _ => SideEffectLevel::ReadOnly,
            },
            arg_schema: ToolArgSchema {
                path_params: vec!["path".to_string()],
                ..Default::default()
            },
            ..Default::default()
        },
    );
    push_execution_policy(CapabilityPolicy {
        tool_annotations: annotations,
        ..Default::default()
    });
}

#[test]
fn compact_rule_shorthand_deserializes() {
    let rule: PolicyRule = serde_json::from_value(serde_json::json!({
        "deny": {"tool": "read_*", "path": "**/.env"},
        "reason": "secret file"
    }))
    .expect("rule");
    assert_eq!(rule.action, PolicyAction::Deny);
    assert_eq!(rule.matches.tool, vec!["read_*"]);
    assert_eq!(rule.matches.path, vec!["**/.env"]);
    assert_eq!(rule.reason.as_deref(), Some("secret file"));
}

#[test]
fn ambiguous_or_invalid_rule_shapes_are_rejected() {
    let invalid_action = serde_json::from_value::<PolicyRule>(serde_json::json!({
        "action": "maybe",
        "match": {"tool": "read_file"}
    }));
    assert!(invalid_action.is_err());

    let mixed_matchers = serde_json::from_value::<PolicyRule>(serde_json::json!({
        "action": "deny",
        "match": {"tool": "read_file"},
        "path": "**/.env"
    }));
    assert!(mixed_matchers.is_err());
}

#[test]
fn deny_beats_ask_and_allow_regardless_of_order() {
    let policy: ToolApprovalPolicy = serde_json::from_value(serde_json::json!({
        "rules": [
            {"allow": {"tool": "write_file"}},
            {"ask": {"tool": "write_*"}},
            {"deny": {"tool": "write_file"}, "reason": "blocked"}
        ]
    }))
    .expect("policy");
    let decision =
        evaluate_tool_approval_policy(&policy, "write_file", &serde_json::json!({}), None);
    assert!(decision.is_deny());
    assert_eq!(decision.reason, "blocked");
    assert_eq!(
        decision.matched_rule.as_ref().and_then(|rule| rule.index),
        Some(2)
    );
}

#[test]
fn sensitive_paths_are_denied_by_default() {
    policy_with_path_annotation("read_file", ToolKind::Read);
    let policy = ToolApprovalPolicy::default();
    let decisions = [
        "config/.env",
        ".env.local",
        "/home/agent/.ssh/id_rsa",
        "/home/agent/.aws/credentials",
        "certificates/client.pem",
        "certificates/client.key",
    ]
    .map(|path| {
        evaluate_tool_approval_policy(
            &policy,
            "read_file",
            &serde_json::json!({"path": path}),
            None,
        )
    });
    pop_execution_policy();

    for decision in decisions {
        assert!(decision.is_deny(), "sensitive path was allowed");
        assert!(decision.risk_labels.contains(&"sensitive_path".to_string()));
    }
}

#[test]
fn unannotated_approval_api_preserves_conventional_path_safety() {
    let policy = ToolApprovalPolicy::default();
    assert!(evaluate_tool_approval_policy(
        &policy,
        "read_file",
        &serde_json::json!({"path": ".env"}),
        None,
    )
    .is_deny());
    assert!(evaluate_tool_approval_policy(
        &policy,
        "render",
        &serde_json::json!({"content": "document cat .env here"}),
        None,
    )
    .is_allow());
}

#[test]
fn sensitive_command_reads_use_structural_command_facts() {
    let policy = ToolApprovalPolicy::default();
    for arguments in [
        serde_json::json!({"argv": ["cat", ".env"]}),
        serde_json::json!({"command": "sh -c 'cat .env'"}),
    ] {
        assert!(
            evaluate_tool_approval_policy(&policy, "run_command", &arguments, None).is_deny(),
            "sensitive command read was allowed: {arguments}"
        );
    }
    let payload = serde_json::json!({"argv": ["python", "-c", "print('cat .env')"]});
    assert!(
        evaluate_tool_approval_policy(&policy, "run_command", &payload, None).is_allow(),
        "inert interpreter payload was treated as a command"
    );
}

#[test]
fn sensitive_path_default_does_not_classify_edit_content_as_a_path() {
    policy_with_path_annotation("edit_file", ToolKind::Edit);
    let policy = ToolApprovalPolicy::default();
    let decisions = [
        "value = os.environ['API_KEY']\n",
        "const value = process.env.API_KEY;\n",
        "for key in config.keys():\n    print(key)\n",
        "documentation = 'read config/.env before starting'\n",
    ]
    .map(|content| {
        evaluate_tool_approval_policy(
            &policy,
            "edit_file",
            &serde_json::json!({"path": "src/example.py", "content": content}),
            None,
        )
    });
    pop_execution_policy();

    for decision in decisions {
        assert!(
            decision.is_allow(),
            "non-path content was denied: {}",
            decision.reason
        );
    }
}

#[test]
fn sensitive_path_default_uses_path_globs_not_substrings() {
    policy_with_path_annotation("read_file", ToolKind::Read);
    let policy = ToolApprovalPolicy::default();
    let decisions = ["src/os.environment.rs", "src/thing.keyword"].map(|path| {
        evaluate_tool_approval_policy(
            &policy,
            "read_file",
            &serde_json::json!({"path": path}),
            None,
        )
    });
    pop_execution_policy();

    for decision in decisions {
        assert!(
            decision.is_allow(),
            "lookalike path was denied: {}",
            decision.reason
        );
    }
}

#[test]
fn sensitive_path_denial_reason_has_bounded_evidence() {
    policy_with_path_annotation("read_file", ToolKind::Read);
    let long_path = format!("{}/.env", "directory".repeat(128));
    let decision = evaluate_tool_approval_policy(
        &ToolApprovalPolicy::default(),
        "read_file",
        &serde_json::json!({"path": long_path}),
        None,
    );
    pop_execution_policy();

    assert!(decision.is_deny());
    assert!(decision.reason.chars().count() < 300, "{}", decision.reason);
    assert!(decision.reason.contains('…'), "{}", decision.reason);
    assert!(decision.reason.contains("/.env"), "{}", decision.reason);
}

#[test]
fn custom_sensitive_path_patterns_preserve_full_glob_grammar() {
    let policy = ToolApprovalPolicy {
        sensitive_path_patterns: vec![
            "secret[0-9].txt".to_string(),
            "config/{prod,stage}/credentials.json".to_string(),
        ],
        ..Default::default()
    };
    for path in ["secret7.txt", "config/prod/credentials.json"] {
        assert!(
            evaluate_tool_approval_policy(
                &policy,
                "read_file",
                &serde_json::json!({"path": path}),
                None,
            )
            .is_deny(),
            "custom sensitive glob did not match {path}"
        );
    }
}

#[test]
fn explicit_sensitive_opt_out_allows_regular_evaluation() {
    let policy = ToolApprovalPolicy {
        allow_sensitive_paths: true,
        ..Default::default()
    };
    let decision = evaluate_tool_approval_policy(
        &policy,
        "read_file",
        &serde_json::json!({"path": "config/.env"}),
        None,
    );
    assert!(decision.is_allow());
    assert!(!decision.has_audit_signal());

    let command = evaluate_tool_approval_policy(
        &policy,
        "run_command",
        &serde_json::json!({"argv": ["cat", ".env"]}),
        None,
    );
    assert!(command.is_allow());
}

#[test]
fn external_declared_paths_are_denied_without_root() {
    let temp = tempfile::tempdir().unwrap();
    crate::stdlib::process::set_thread_execution_context(Some(
        crate::orchestration::RunExecutionRecord {
            cwd: Some(temp.path().to_string_lossy().into_owned()),
            project_root: None,
            source_dir: Some(temp.path().to_string_lossy().into_owned()),
            env: BTreeMap::new(),
            adapter: None,
            repo_path: None,
            worktree_path: None,
            branch: None,
            base_ref: None,
            cleanup: None,
            environment_policy: Default::default(),
            grants: Vec::new(),
            admitted_environment: Vec::new(),
        },
    ));
    policy_with_path_annotation("read_file", ToolKind::Read);
    let decision = evaluate_tool_approval_policy(
        &ToolApprovalPolicy::default(),
        "read_file",
        &serde_json::json!({"path": "/tmp/outside.txt"}),
        None,
    );
    assert!(decision.is_deny());
    assert!(decision.risk_labels.contains(&"external_path".to_string()));
    pop_execution_policy();
    crate::stdlib::process::set_thread_execution_context(None);
}

#[test]
fn path_rule_uses_declared_path_params() {
    policy_with_path_annotation("write_file", ToolKind::Edit);
    let policy: ToolApprovalPolicy = serde_json::from_value(serde_json::json!({
        "allow_sensitive_paths": true,
        "rules": [{"ask": {"tool": "write_*", "path": "src/**"}, "reason": "source edit"}]
    }))
    .expect("policy");
    let decision = evaluate_tool_approval_policy(
        &policy,
        "write_file",
        &serde_json::json!({"path": "src/lib.rs"}),
        None,
    );
    assert!(decision.is_ask());
    assert_eq!(decision.reason, "source edit");
    pop_execution_policy();
}

#[test]
fn command_url_mcp_identity_and_repeat_rules_match() {
    let policy: ToolApprovalPolicy = serde_json::from_value(serde_json::json!({
        "allow_sensitive_paths": true,
        "rules": [
            {"ask": {"tool": "run_command", "command_identity": "npm"}},
            {"deny": {"tool": "fetch_url", "domain": "*.example.com", "method": "POST"}},
            {"deny": {"mcp_server": "github", "mcp_tool": "create_issue"}},
            {"deny": {"tool": "read_file", "repeat_count_gte": 3}}
        ]
    }))
    .expect("policy");
    assert!(evaluate_tool_approval_policy(
        &policy,
        "run_command",
        &serde_json::json!({"argv": ["npm", "install"]}),
        None,
    )
    .is_ask());
    assert!(evaluate_tool_approval_policy(
        &policy,
        "fetch_url",
        &serde_json::json!({"url": "https://api.example.com/v1", "method": "post"}),
        None,
    )
    .is_deny());
    assert!(evaluate_tool_approval_policy(
        &policy,
        "github__create_issue",
        &serde_json::json!({}),
        None,
    )
    .is_deny());
    assert!(evaluate_tool_approval_policy(
        &policy,
        "read_file",
        &serde_json::json!({"path": "README.md"}),
        Some(3),
    )
    .is_deny());
}

#[test]
fn persona_agent_and_mode_rules_match_args() {
    let policy: ToolApprovalPolicy = serde_json::from_value(serde_json::json!({
        "allow_sensitive_paths": true,
        "rules": [{"deny": {"agent": "release-*", "persona": "shipper", "mode": "act"}}]
    }))
    .expect("policy");
    let decision = evaluate_tool_approval_policy(
        &policy,
        "publish",
        &serde_json::json!({"agent": "release-1", "persona": "shipper", "mode": "act"}),
        None,
    );
    assert!(decision.is_deny());
}

#[test]
fn host_request_normalizes_harn_context_and_emits_canonical_receipt() {
    let policy: ToolApprovalPolicy = serde_json::from_value(serde_json::json!({
        "allow_sensitive_paths": true,
        "rules": [
            {
                "id": "allow-fallback",
                "allow": {"tool": "run"}
            },
            {
                "id": "deny-release-publish",
                "deny": {
                    "tool": "run",
                    "tool_kind": "execute",
                    "side_effect": "process_exec",
                    "command_identity": "cargo",
                    "domain": "crates.io",
                    "method": "POST",
                    "agent": "release-*",
                    "persona": "shipper",
                    "mode": "act",
                    "env_mode": "patch",
                    "capability": "terminal.execute"
                },
                "reason": "release publishing is supervised"
            }
        ]
    }))
    .expect("policy");
    let request = ToolApprovalRequest {
        tool_name: "run".to_string(),
        arguments: serde_json::json!({
            "rawInput": {
                "argv": ["cargo", "publish"],
                "url": "https://crates.io/api/v1/crates",
                "method": "post",
                "envMode": "patch"
            }
        }),
        policy_decision: Some(serde_json::json!({
            "context": {
                "toolName": "run",
                "toolKind": "execute",
                "requestedSideEffectLevel": "process_exec",
                "agent_id": "release-1",
                "persona_id": "shipper",
                "action": "act",
                "policy_context": {
                    "capabilities": ["terminal.execute"]
                }
            }
        })),
        approval_request: None,
        repeat_count: None,
    };

    let decision = policy.evaluate_request(&request);

    assert!(decision.is_deny());
    assert_eq!(decision.reason, "release publishing is supervised");
    assert_eq!(
        decision
            .matched_rule
            .as_ref()
            .and_then(|rule| rule.id.as_deref()),
        Some("deny-release-publish")
    );
    assert_eq!(
        decision.receipt.get("type").and_then(JsonValue::as_str),
        Some(POLICY_RECEIPT_TYPE)
    );
    assert_eq!(
        decision
            .receipt
            .pointer("/context/command_identities/0")
            .and_then(JsonValue::as_str),
        Some("cargo")
    );
}

#[test]
fn host_request_normalizes_generic_argument_paths() {
    let policy: ToolApprovalPolicy = serde_json::from_value(serde_json::json!({
        "allow_sensitive_paths": true,
        "rules": [{
            "id": "ask-source-read",
            "ask": {"tool": "read", "path": "src/**"},
            "reason": "source read"
        }]
    }))
    .expect("policy");
    let request = ToolApprovalRequest {
        tool_name: "read".to_string(),
        arguments: serde_json::json!({"path": "src/main.rs"}),
        ..Default::default()
    };

    let decision = policy.evaluate_request(&request);

    assert!(decision.is_ask());
    assert_eq!(decision.reason, "source read");
    assert_eq!(
        decision
            .matched_rule
            .as_ref()
            .and_then(|rule| rule.id.as_deref()),
        Some("ask-source-read")
    );
}

#[test]
fn write_environment_allows_require_an_exact_mode_match() {
    let wildcard: ToolApprovalPolicy = serde_json::from_value(serde_json::json!({
        "allow_sensitive_paths": true,
        "rules": [{"id": "wildcard", "allow": {"tool": "run", "env_mode": "*"}}]
    }))
    .expect("policy");
    let exact: ToolApprovalPolicy = serde_json::from_value(serde_json::json!({
        "allow_sensitive_paths": true,
        "rules": [{"id": "exact", "allow": {"tool": "run", "env_mode": "patch"}}]
    }))
    .expect("policy");
    let request = ToolApprovalRequest {
        tool_name: "run".to_string(),
        arguments: serde_json::json!({"env_mode": "patch"}),
        ..Default::default()
    };

    let wildcard_decision = wildcard.evaluate_request(&request);
    let exact_decision = exact.evaluate_request(&request);

    assert!(wildcard_decision.is_allow());
    assert!(
        wildcard_decision.matched_rule.is_none(),
        "a wildcard must not grant patch-mode writes"
    );
    assert_eq!(
        exact_decision
            .matched_rule
            .as_ref()
            .and_then(|rule| rule.id.as_deref()),
        Some("exact")
    );
}

#[test]
fn approval_request_undo_metadata_is_a_supported_host_boundary() {
    let policy: ToolApprovalPolicy = serde_json::from_value(serde_json::json!({
        "allow_sensitive_paths": true,
        "rules": [{"id": "ask-network", "ask": {"side_effect": "network"}}]
    }))
    .expect("policy");
    let request = ToolApprovalRequest {
        tool_name: "fetch".to_string(),
        arguments: serde_json::json!({}),
        approval_request: Some(serde_json::json!({
            "undo_metadata": {
                "policy_decision": {
                    "context": {"side_effect": "network"}
                }
            }
        })),
        ..Default::default()
    };

    let decision = policy.evaluate_request(&request);

    assert!(decision.is_ask());
    assert_eq!(
        decision
            .matched_rule
            .as_ref()
            .and_then(|rule| rule.id.as_deref()),
        Some("ask-network")
    );
}

#[test]
fn approval_unavailable_class_count_uses_sorted_risk_labels() {
    clear_all_approval_policy_repeat_counts();
    let labels = vec![
        "package_install".to_string(),
        "approval_required".to_string(),
    ];
    let reversed = vec![
        "approval_required".to_string(),
        "package_install".to_string(),
    ];

    let (class, count) = next_approval_unavailable_class_repeat_count("s1", &labels);
    assert_eq!(class, "approval_required+package_install");
    assert_eq!(count, 1);
    let (class, count) = next_approval_unavailable_class_repeat_count("s1", &reversed);
    assert_eq!(class, "approval_required+package_install");
    assert_eq!(count, 2);
    let (class, count) = next_approval_unavailable_class_repeat_count("s2", &[]);
    assert_eq!(class, "approval_required");
    assert_eq!(count, 1);

    clear_approval_policy_repeat_counts("s1");
    let (_, count) = next_approval_unavailable_class_repeat_count("s1", &labels);
    assert_eq!(count, 1);
}

#[test]
fn approval_repeat_digest_ignores_argument_key_order() {
    let first: serde_json::Value = serde_json::from_str(r#"{"zeta":1,"alpha":2}"#).unwrap();
    let second: serde_json::Value = serde_json::from_str(r#"{"alpha":2,"zeta":1}"#).unwrap();

    assert_eq!(stable_json_digest(&first), stable_json_digest(&second));
}

/// bc#8748 / harn#8463. A refusal must name the rule that refused it.
///
/// Every deny used to leave this evaluator wearing `approval_policy`,
/// including the two refusals the built-in guards make before a single
/// configured rule is read. A person who had turned interactive approval off
/// was told approval had denied them, and went to inspect a control that had
/// no part in it. The falsifier is per source: each of the deciding
/// mechanisms below must produce a DIFFERENT gate, so relabelling everything
/// to one new value cannot pass either.
#[test]
fn each_deciding_source_names_its_own_gate() {
    use crate::agent_events::DenialGate;

    let temp = tempfile::tempdir().unwrap();
    crate::stdlib::process::set_thread_execution_context(Some(
        crate::orchestration::RunExecutionRecord {
            cwd: Some(temp.path().to_string_lossy().into_owned()),
            project_root: None,
            source_dir: Some(temp.path().to_string_lossy().into_owned()),
            env: BTreeMap::new(),
            adapter: None,
            repo_path: None,
            worktree_path: None,
            branch: None,
            base_ref: None,
            cleanup: None,
            environment_policy: Default::default(),
            grants: Vec::new(),
            admitted_environment: Vec::new(),
        },
    ));
    policy_with_path_annotation("read_file", ToolKind::Read);

    // The workspace path boundary: outside the workspace, no external root.
    let outside = evaluate_tool_approval_policy(
        &ToolApprovalPolicy::default(),
        "read_file",
        &serde_json::json!({"path": "/tmp/outside.txt"}),
        None,
    );
    assert!(outside.is_deny());
    assert_eq!(
        outside
            .matched_rule
            .as_ref()
            .map(|rule| rule.source.as_str()),
        Some(SOURCE_DEFAULT_EXTERNAL_PATH),
    );
    assert_eq!(outside.denial_gate(), DenialGate::WorkspaceBoundary);

    // The sensitive-path default, decided in the same pass but by a
    // different rule, on a path INSIDE the workspace so the boundary above
    // cannot be what refused it.
    let sensitive = evaluate_tool_approval_policy(
        &ToolApprovalPolicy::default(),
        "read_file",
        &serde_json::json!({"path": "config/.env"}),
        None,
    );
    assert!(sensitive.is_deny());
    assert_eq!(
        sensitive
            .matched_rule
            .as_ref()
            .map(|rule| rule.source.as_str()),
        Some(SOURCE_DEFAULT_SENSITIVE_PATH),
    );
    assert_eq!(sensitive.denial_gate(), DenialGate::SensitivePath);

    // NEGATIVE CONTROL. A configured approval decision is still an approval
    // decision. Without this the change could pass by giving every refusal a
    // new name, which would move the misreport rather than fix it.
    let configured = evaluate_tool_approval_policy(
        &ToolApprovalPolicy {
            auto_deny: vec!["read_file".to_string()],
            allow_sensitive_paths: true,
            allow_external_paths: true,
            ..Default::default()
        },
        "read_file",
        &serde_json::json!({"path": "src/main.rs"}),
        None,
    );
    assert!(configured.is_deny());
    assert_eq!(configured.denial_gate(), DenialGate::ApprovalPolicy);

    // The rendered signatures a person reads must differ too, or the typed
    // gate is legible and the message still is not.
    // Through the same constructor the dispatch seam uses, so this asserts
    // production behaviour and not a re-derivation of it.
    let rendered = [&outside, &sensitive, &configured].map(|decision| {
        let denial = decision.terminal_denial();
        assert_eq!(denial.gate, decision.denial_gate());
        assert!(!denial.retryable, "a policy refusal is terminal");
        (denial.reason, denial.denied_paths)
    });
    // The subject is a typed value, not only prose. A configured deny that
    // did not refuse ON a path declares none, so "empty" keeps meaning
    // "no path was the reason" instead of "nobody filled this in".
    assert_eq!(rendered[0].1, vec!["/tmp/outside.txt".to_string()]);
    // The sensitive-path guard reports the path it resolved and matched on,
    // which for a workspace-relative argument is the absolute form.
    assert_eq!(rendered[1].1.len(), 1, "{:?}", rendered[1].1);
    assert!(
        rendered[1].1[0].ends_with("config/.env"),
        "{:?}",
        rendered[1].1
    );
    assert!(rendered[2].1.is_empty(), "{:?}", rendered[2].1);
    let rendered = rendered.map(|(reason, _)| reason);
    assert!(
        rendered[0].starts_with("Workspace boundary denial:"),
        "{rendered:?}"
    );
    assert!(
        rendered[1].starts_with("Sensitive path denial:"),
        "{rendered:?}"
    );
    assert!(
        rendered[2].starts_with("Approval policy denial:"),
        "{rendered:?}"
    );
    // The subject the boundary refused is named, not only described.
    assert!(rendered[0].contains("/tmp/outside.txt"), "{rendered:?}");

    pop_execution_policy();
    crate::stdlib::process::set_thread_execution_context(None);
}

/// A deny carrying no matched rule cannot silently become a path denial.
#[test]
fn a_ruleless_deny_stays_an_approval_denial() {
    use crate::agent_events::DenialGate;
    assert_eq!(denial_gate_for_source(None), DenialGate::ApprovalPolicy);
    assert_eq!(
        denial_gate_for_source(Some("auto_deny")),
        DenialGate::ApprovalPolicy,
    );
    assert_eq!(
        denial_gate_for_source(Some("repeat_limit")),
        DenialGate::ApprovalPolicy,
    );
    assert_eq!(
        denial_gate_for_source(Some(SOURCE_DEFAULT_PATH_GUARD)),
        DenialGate::WorkspaceBoundary,
    );
}

/// The half of #8463 that is easy to overstate, pinned so it cannot be.
///
/// `denied_paths` was never empty before this change: the dispatch seam
/// backfilled it with EVERY path the call declared whenever the denial
/// carried none. So the improvement is not "a path is named where none was",
/// it is "the path that actually refused is named instead of the whole
/// declared set". On a single-path call the two are indistinguishable, which
/// is why this test uses a tool that declares two and refuses on one.
#[test]
fn a_path_refusal_names_the_path_that_refused_not_every_path_declared() {
    let temp = tempfile::tempdir().unwrap();
    crate::stdlib::process::set_thread_execution_context(Some(
        crate::orchestration::RunExecutionRecord {
            cwd: Some(temp.path().to_string_lossy().into_owned()),
            project_root: None,
            source_dir: Some(temp.path().to_string_lossy().into_owned()),
            env: BTreeMap::new(),
            adapter: None,
            repo_path: None,
            worktree_path: None,
            branch: None,
            base_ref: None,
            cleanup: None,
            environment_policy: Default::default(),
            grants: Vec::new(),
            admitted_environment: Vec::new(),
        },
    ));
    let mut annotations = BTreeMap::new();
    annotations.insert(
        "move_file".to_string(),
        ToolAnnotations {
            kind: ToolKind::Move,
            side_effect_level: SideEffectLevel::WorkspaceWrite,
            arg_schema: ToolArgSchema {
                path_params: vec!["from".to_string(), "to".to_string()],
                ..Default::default()
            },
            ..Default::default()
        },
    );
    push_execution_policy(CapabilityPolicy {
        tool_annotations: annotations,
        ..Default::default()
    });

    // `from` is inside the workspace and unobjectionable; `to` is what the
    // boundary refuses.
    let args = serde_json::json!({"from": "src/main.rs", "to": "/tmp/outside.txt"});
    let decision =
        evaluate_tool_approval_policy(&ToolApprovalPolicy::default(), "move_file", &args, None);
    assert!(decision.is_deny());

    let declared = crate::orchestration::current_tool_declared_paths("move_file", &args);
    assert!(
        declared.len() > 1,
        "this test measures nothing unless the call declares more than one path: {declared:?}"
    );

    let denial = decision.terminal_denial();
    assert_eq!(
        denial.denied_paths,
        vec!["/tmp/outside.txt".to_string()],
        "the refusal must name the path that refused, not the declared set {declared:?}"
    );

    pop_execution_policy();
    crate::stdlib::process::set_thread_execution_context(None);
}