tirith 0.4.1

Terminal security - catches homograph attacks, pipe-to-shell, ANSI injection
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
use std::path::PathBuf;

use tirith_core::engine::{self, AnalysisContext};
use tirith_core::extract::ScanContext;
use tirith_core::policy::Policy;
use tirith_core::policy_validate::{self, IssueLevel};
use tirith_core::scan;
use tirith_core::tokenize::ShellType;
use tirith_core::verdict::Severity;

const FULL_TEMPLATE: &str = r#"# Tirith security policy
# Documentation: https://tirith.dev/docs/policy

# Fail mode: "open" (allow on error) or "closed" (block on error)
fail_mode: open

# Paranoia level (1-4): higher = more sensitive detection
paranoia: 1

# Allow TIRITH=0 bypass in interactive terminals
allow_bypass_env: true

# Require explicit acknowledgement for warn findings in interactive mode
strict_warn: false

# Severity overrides per rule (e.g., shortened_url: LOW)
severity_overrides: {}

# URL patterns to always allow
allowlist: []

# URL patterns to always block (overrides allowlist)
blocklist: []

# Force specific rules to block (upgrade only, cannot downgrade)
# action_overrides:
#   shortened_url: block

# Escalation: upgrade warnings to blocks based on session history
# escalation:
#   - trigger: repeat_count    # block after N warnings for the same rule
#     rule_ids: ["*"]          # "*" = any rule, or list specific rule IDs
#     threshold: 5
#     window_minutes: 60
#     action: block
#   - trigger: multi_medium    # block when N+ medium findings on one command
#     min_findings: 3
#     action: block

# Scan configuration overrides.
scan:
  # Glob patterns to ignore during scan
  ignore_patterns: []

  # Exact MCP server identities you trust. Each mcp:v1 key binds source path,
  # name, and transport; bare names intentionally match nothing. Trust suppresses
  # per-server config findings and ordinary drift, but never structural ambiguity
  # or an explicit tool-policy violation. Run `tirith mcp policy init` to scaffold
  # these keys from `.tirith/mcp.lock`.
  # trusted_mcp_servers:
  #   - "mcp:v1:<sha256>"

  # Per-server allowed tools. Keys are the same exact identities; values are the
  # tool names that server may expose. An explicit entry requires an approved
  # live descriptor baseline and checks both static and live names. Servers not
  # listed here are unconstrained.
  # mcp_allowed_tools:
  #   "mcp:v1:<sha256>":
  #     - read_only

# Per-agent governance rules — M4 item 8 (enforcement).
#
# `agent_rules` lets a policy declare which AgentOrigin variants it
# allows or denies, where `AgentOrigin` is the recorded caller — Human,
# Agent, Mcp, Gateway, Ci, or Ide. A `deny` match forces the verdict to
# Block and appends an `agent_denied_by_policy` finding naming the
# matched origin and policy file; a `deny` entry beats any matching
# `allow` entry, mirroring how `blocklist` beats `allowlist`. `allow`
# is NOT a bypass — a verdict the engine already blocked stays blocked
# even if the caller is on the allow list. See `rule_explanations.toml`
# (`agent_denied_by_policy`) for the operator-facing description.
#
# Enforcement scope: `apply_agent_rules` runs on every analysis path —
# `tirith check`, the gateway request / notification paths, `tirith
# paste`, `tirith install`, `tirith ecosystem scan`, and all MCP
# `tools/call_check_*` handlers (`call_check_command`, `call_check_url`,
# `call_check_paste`). The interactive `TIRITH=0` bypass currently
# skips `apply_agent_rules` (pinned by
# `agent_rules_deny_skipped_under_tirith_bypass_today`); revisit that
# semantic in M5.
#
# Trust caveat: every signal feeding AgentOrigin is OPERATOR-TRUST,
# never adversary-resistant — TIRITH_INTEGRATION, MCP clientInfo, CI
# env vars are all settable by any process running as the user. Use
# `agent_rules` for operator-trust scoping ("I do not run my MCP
# server's commands on traffic my CI ran"), not adversarial security;
# layer real authentication elsewhere if the decision must withstand a
# hostile environment.
#
# Run `tirith agent policy init` to scaffold this block from the local
# audit log's observed origins.
# agent_rules:
#   allow:
#     - kind: agent
#       name: claude-code
#     - kind: human
#   deny:
#     - kind: agent
#       name: untrusted-tool
"#;

const MINIMAL_TEMPLATE: &str = r#"fail_mode: open
paranoia: 1
allowlist: []
blocklist: []
"#;

/// Mandatory privacy boundary for policy CLI diagnostics. Policy paths and
/// parser/validation errors may contain local identities, credentials, Tirith
/// canaries, or bare private-key scalars, so project them before any human or
/// JSON presenter extracts individual fields.
fn project_policy_cli_text(value: &str) -> String {
    let share_safe = tirith_core::redact::redact_for_audience(
        value,
        tirith_core::redact::ShareAudience::PublicPaste,
    )
    .redacted_content;
    tirith_core::redact::redact_blocked_output(&share_safe)
}

fn project_policy_cli_json(value: &mut serde_json::Value) {
    match value {
        serde_json::Value::String(text) => *text = project_policy_cli_text(text),
        serde_json::Value::Array(values) => {
            for value in values {
                project_policy_cli_json(value);
            }
        }
        serde_json::Value::Object(values) => {
            for value in values.values_mut() {
                project_policy_cli_json(value);
            }
        }
        serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) => {}
    }
}

/// `individual` — defaults for a single developer (fail-open, paranoia 1, the
/// noisiest pipe-to-shell rule escalated, empty allowlist). Body lives in
/// `assets/policy_templates/individual.yaml`, resolved via `include_str!` so the
/// on-disk `.yaml` is the single source of truth (shared with the validity test).
const TEMPLATE_INDIVIDUAL: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/assets/policy_templates/individual.yaml"
));

/// `ci-strict` — locked-down CI settings: fail-closed, no bypass, strict warn,
/// and a `scan.fail_on` threshold that fails the build on high-severity findings.
const TEMPLATE_CI_STRICT: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/assets/policy_templates/ci-strict.yaml"
));

/// `ai-agent-heavy` — for environments where AI agents run many commands.
/// Fail-open (so an agent isn't wedged by an internal error) but raised
/// paranoia, no non-interactive bypass, approval for the highest-risk rules, and
/// escalation on repeated warnings.
const TEMPLATE_AI_AGENT_HEAVY: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/assets/policy_templates/ai-agent-heavy.yaml"
));

/// `oss-maintainer` — for a public OSS repo maintainer. Moderate (paranoia 2,
/// fail-open) with the untrusted-contributor threat model in focus: typosquat,
/// install-script, and untrusted-registry rules escalated.
const TEMPLATE_OSS_MAINTAINER: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/assets/policy_templates/oss-maintainer.yaml"
));

/// `startup` — for a small fast team: a notch stricter than `individual`
/// (paranoia 2, strict-warn on, noisiest pipe-to-shell rules escalated) but not
/// fail-closed.
const TEMPLATE_STARTUP: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/assets/policy_templates/startup.yaml"
));

/// `enterprise` — strict, audit-friendly defaults: fail-closed, no bypass,
/// paranoia 3, and (uniquely) an ACTIVE `package_policy:` block with strict
/// supply-chain thresholds out of the box.
const TEMPLATE_ENTERPRISE: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/assets/policy_templates/enterprise.yaml"
));

/// `mcp-strict` — locked-down for MCP-heavy environments: fail-closed,
/// paranoia 3, every MCP config rule (insecure / untrusted / overly-permissive /
/// suspicious-args / drift) escalated.
const TEMPLATE_MCP_STRICT: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/assets/policy_templates/mcp-strict.yaml"
));

/// A curated starter policy selected via `tirith policy init --template`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PolicyTemplate {
    Individual,
    CiStrict,
    AiAgentHeavy,
    OssMaintainer,
    Startup,
    Enterprise,
    McpStrict,
}

impl PolicyTemplate {
    /// Every variant, in canonical display order. The single source of truth for
    /// "which templates exist" (R20): the `--template` help list is built from
    /// this via [`PolicyTemplate::canonical_name`], so it can never go stale.
    pub const ALL: &'static [PolicyTemplate] = &[
        Self::Individual,
        Self::CiStrict,
        Self::AiAgentHeavy,
        Self::OssMaintainer,
        Self::Startup,
        Self::Enterprise,
        Self::McpStrict,
    ];

    /// Comma-separated canonical template names for help/error text, derived from
    /// [`PolicyTemplate::ALL`] so it stays in lock-step with the enum.
    fn names_csv() -> String {
        Self::ALL
            .iter()
            .map(|t| t.canonical_name())
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// Parse a `--template` value (`None` if unrecognized). `personal` is an alias
    /// for `individual` (the shipping name); both resolve to the same body.
    pub fn parse(name: &str) -> Option<Self> {
        match name.trim().to_ascii_lowercase().as_str() {
            "individual" | "personal" => Some(Self::Individual),
            "ci-strict" | "ci_strict" => Some(Self::CiStrict),
            "ai-agent-heavy" | "ai_agent_heavy" => Some(Self::AiAgentHeavy),
            "oss-maintainer" | "oss_maintainer" => Some(Self::OssMaintainer),
            "startup" => Some(Self::Startup),
            "enterprise" => Some(Self::Enterprise),
            "mcp-strict" | "mcp_strict" => Some(Self::McpStrict),
            _ => None,
        }
    }

    /// The canonical hyphenated name. Round-trips through [`PolicyTemplate::parse`]
    /// so `tirith onboard` can pass it to `policy init --template <name>`. The
    /// `personal` alias maps to `Individual`, so its canonical name is `individual`.
    pub fn canonical_name(self) -> &'static str {
        match self {
            Self::Individual => "individual",
            Self::CiStrict => "ci-strict",
            Self::AiAgentHeavy => "ai-agent-heavy",
            Self::OssMaintainer => "oss-maintainer",
            Self::Startup => "startup",
            Self::Enterprise => "enterprise",
            Self::McpStrict => "mcp-strict",
        }
    }

    /// The YAML body this template writes.
    fn body(self) -> &'static str {
        match self {
            Self::Individual => TEMPLATE_INDIVIDUAL,
            Self::CiStrict => TEMPLATE_CI_STRICT,
            Self::AiAgentHeavy => TEMPLATE_AI_AGENT_HEAVY,
            Self::OssMaintainer => TEMPLATE_OSS_MAINTAINER,
            Self::Startup => TEMPLATE_STARTUP,
            Self::Enterprise => TEMPLATE_ENTERPRISE,
            Self::McpStrict => TEMPLATE_MCP_STRICT,
        }
    }
}

pub fn init(force: bool, minimal: bool, template: Option<&str>) -> i32 {
    // Resolve the template before touching the filesystem so a typo fails fast.
    let selected_template = match template {
        Some(name) => match PolicyTemplate::parse(name) {
            Some(t) => Some(t),
            None => {
                eprintln!("tirith policy init: unknown template '{name}'");
                // Derived from `PolicyTemplate::ALL` so it can't drift (R20).
                eprintln!("  valid templates: {}", PolicyTemplate::names_csv());
                eprintln!("  ('personal' is accepted as an alias of 'individual')");
                return 1;
            }
        },
        None => None,
    };

    if selected_template.is_some() && minimal {
        eprintln!("tirith policy init: --template and --minimal cannot be combined");
        return 1;
    }

    init_with_template(force, minimal, selected_template)
}

fn init_with_template(force: bool, minimal: bool, template: Option<PolicyTemplate>) -> i32 {
    let cwd = std::env::current_dir()
        .ok()
        .map(|p| p.display().to_string());
    let repo_root = match tirith_core::policy::find_repo_root(cwd.as_deref()) {
        Some(r) => r,
        None => {
            // No git repo — fall back to cwd.
            match std::env::current_dir() {
                Ok(d) => d,
                Err(e) => {
                    eprintln!("tirith policy init: cannot determine working directory: {e}");
                    return 1;
                }
            }
        }
    };

    let tirith_dir = repo_root.join(".tirith");
    let policy_path = tirith_dir.join("policy.yaml");

    if policy_path.exists() && !force {
        eprintln!(
            "tirith policy init: {} already exists (use --force to overwrite)",
            policy_path.display()
        );
        return 1;
    }

    let template_body = match (template, minimal) {
        (Some(t), _) => t.body(),
        (None, true) => MINIMAL_TEMPLATE,
        (None, false) => FULL_TEMPLATE,
    };

    // Write the policy ATOMICALLY (temp → fsync → rename → parent fsync), so a
    // crash mid-write never loses the prior policy. Without `--force`,
    // `overwrite=false` makes it no-clobber, so a policy created in the race window
    // after the `exists()` check surfaces as a write error instead of being lost.
    //
    // C12: writing Tirith's own policy is a policy change at a Tirith-owned
    // boundary, so it goes through the gated, single-use permit. The operator
    // policy is discovered offline: a repository being initialised must not get
    // to authorise the write that creates its own policy.
    let operator_policy = tirith_core::policy::Policy::discover_local_only(cwd.as_deref());
    if let Err(e) = super::write_config_file_permitted_with_parent_creation(
        &repo_root,
        &policy_path,
        template_body.as_bytes(),
        force,
        &operator_policy,
        true,
        true,
    ) {
        eprintln!(
            "tirith policy init: cannot write {}: {e}",
            policy_path.display()
        );
        return 1;
    }

    let label = match template {
        Some(PolicyTemplate::Individual) => " (individual template)",
        Some(PolicyTemplate::CiStrict) => " (ci-strict template)",
        Some(PolicyTemplate::AiAgentHeavy) => " (ai-agent-heavy template)",
        Some(PolicyTemplate::OssMaintainer) => " (oss-maintainer template)",
        Some(PolicyTemplate::Startup) => " (startup template)",
        Some(PolicyTemplate::Enterprise) => " (enterprise template)",
        Some(PolicyTemplate::McpStrict) => " (mcp-strict template)",
        None if minimal => " (minimal template)",
        None => "",
    };
    eprintln!(
        "tirith policy init: created {}{label}",
        policy_path.display()
    );
    0
}

pub fn validate(path: Option<&str>, json: bool) -> i32 {
    let policy_path = match resolve_policy_path(path) {
        Some(p) => p,
        None => {
            eprintln!("tirith policy validate: no policy file found");
            eprintln!("  run `tirith policy init` to create one");
            return 1;
        }
    };

    let yaml = match std::fs::read_to_string(&policy_path) {
        Ok(s) => s,
        Err(e) => {
            let display_path = bounded_human_value(&policy_path.display().to_string(), 512);
            let error = bounded_human_value(&e.to_string(), 512);
            eprintln!("tirith policy validate: cannot read {display_path}: {error}");
            return 1;
        }
    };

    let issues = policy_validate::validate(&yaml);

    if json {
        print_validate_json(&policy_path, &issues);
    } else {
        print_validate_human(&policy_path, &issues);
    }

    if issues.iter().any(|i| i.level == IssueLevel::Error) {
        1
    } else {
        0
    }
}

fn print_validate_json(path: &std::path::Path, issues: &[policy_validate::PolicyIssue]) {
    #[derive(serde::Serialize)]
    struct Output<'a> {
        path: String,
        valid: bool,
        error_count: usize,
        warning_count: usize,
        issues: &'a [policy_validate::PolicyIssue],
    }

    let error_count = issues
        .iter()
        .filter(|i| i.level == IssueLevel::Error)
        .count();
    let warning_count = issues
        .iter()
        .filter(|i| i.level == IssueLevel::Warning)
        .count();

    let output = Output {
        path: path.display().to_string(),
        valid: error_count == 0,
        error_count,
        warning_count,
        issues,
    };

    let mut output = match serde_json::to_value(&output) {
        Ok(output) => output,
        Err(error) => {
            let error = bounded_human_value(&error.to_string(), 512);
            eprintln!("tirith policy validate: failed to construct JSON output: {error}");
            return;
        }
    };
    project_policy_cli_json(&mut output);

    if let Err(error) = serde_json::to_writer_pretty(std::io::stdout().lock(), &output) {
        let error = bounded_human_value(&error.to_string(), 512);
        eprintln!("tirith policy validate: failed to write JSON output: {error}");
    }
    println!();
}

fn print_validate_human(path: &std::path::Path, issues: &[policy_validate::PolicyIssue]) {
    let display_path = bounded_human_value(&path.display().to_string(), 512);
    if issues.is_empty() {
        eprintln!(
            "tirith policy validate: {} — valid, no issues",
            display_path
        );
        return;
    }

    let error_count = issues
        .iter()
        .filter(|i| i.level == IssueLevel::Error)
        .count();
    let warning_count = issues
        .iter()
        .filter(|i| i.level == IssueLevel::Warning)
        .count();

    eprintln!(
        "tirith policy validate: {}{} error(s), {} warning(s)",
        display_path, error_count, warning_count
    );

    for (index, issue) in issues.iter().enumerate() {
        let s = tirith_core::style::Stream::Stderr;
        let prefix = match issue.level {
            IssueLevel::Error => tirith_core::style::red("error", s),
            IssueLevel::Warning => tirith_core::style::yellow("warning", s),
        };
        eprintln!(
            "  {prefix}: {}",
            human_validation_issue(issue, index.saturating_add(1))
        );
    }
}

/// Render a validation issue without ever echoing an attacker-controlled policy
/// value. Projected structured diagnostics remain available through `--json`;
/// human output exposes only a fixed category plus its non-secret ordinal in the
/// structured issue list.
fn human_validation_issue(issue: &policy_validate::PolicyIssue, ordinal: usize) -> String {
    let category = if issue.message.starts_with("YAML parse error") {
        "YAML parse error"
    } else if issue.message.starts_with("Policy migration error") {
        "policy migration error"
    } else if issue.message.contains("invalid regex") {
        "invalid regular expression"
    } else if issue.message.starts_with("unknown field") {
        "unknown policy field"
    } else if issue.message.contains("too long") || issue.message.contains("maximum") {
        "policy value exceeds its allowed size"
    } else {
        match issue.level {
            IssueLevel::Error => "invalid policy value",
            IssueLevel::Warning => "policy validation warning",
        }
    };

    format!("{category} (issue #{ordinal}; details available with --json)")
}

fn bounded_human_value(value: &str, max_chars: usize) -> String {
    let projected = project_policy_cli_text(value);
    let safe = super::sanitize_for_human_output(&projected, false);
    if safe.chars().count() <= max_chars {
        return safe;
    }
    let mut bounded = safe.chars().take(max_chars).collect::<String>();
    bounded.push('');
    bounded
}

pub fn test(command: Option<&str>, file: Option<&str>, json: bool) -> i32 {
    if command.is_none() && file.is_none() {
        eprintln!("tirith policy test: specify a command or --file <path>");
        return 1;
    }

    if let Some(file_path) = file {
        return test_file(file_path, json);
    }

    test_command(command.unwrap(), json)
}

fn test_command(command: &str, json: bool) -> i32 {
    let cwd = std::env::current_dir()
        .ok()
        .map(|p| p.display().to_string());

    let ctx = AnalysisContext {
        input: command.to_string(),
        shell: ShellType::Posix,
        scan_context: ScanContext::Exec,
        raw_bytes: None,
        interactive: false,
        cwd: cwd.clone(),
        file_path: None,
        repo_root: None,
        is_config_override: false,
        clipboard_html: None,
        card_ref: None,
        clipboard_source: tirith_core::clipboard::ClipboardSourceState::Unread,
    };

    let mut verdict = engine::analyze(&ctx);
    let policy = Policy::discover(cwd.as_deref());
    engine::filter_findings_by_paranoia(&mut verdict, policy.paranoia);
    // repo-0227: apply the same policy finalization the real gate runs
    // (action_overrides / severity overrides), or `policy test` reports a
    // different action than enforcement — a Medium-to-Block override would
    // read as Warn here.
    let verdict = tirith_core::escalation::finalize_static_verdict(
        verdict.findings,
        &policy,
        verdict.tier_reached,
        verdict.timings_ms.clone(),
    );

    let trace = build_policy_trace(command, &policy);

    if json {
        print_test_command_json(command, &verdict, &policy, &trace);
    } else {
        print_test_command_human(command, &verdict, &policy, &trace);
    }

    verdict.action.exit_code()
}

fn test_file(file_path: &str, json: bool) -> i32 {
    let path = PathBuf::from(file_path);
    if !path.exists() {
        let file_path = bounded_human_value(file_path, 512);
        eprintln!("tirith policy test: file not found: {file_path}");
        return 1;
    }

    // Guarded so a crafted file that panics a rule reports an error instead of
    // crashing the process.
    use scan::{GuardedScanOutcome, ScanFileOutcome};
    let result = match scan::scan_single_file_guarded(&path) {
        GuardedScanOutcome::Completed(ScanFileOutcome::Scanned(r)) => r,
        GuardedScanOutcome::Completed(ScanFileOutcome::Skipped(gap)) => {
            let file_path = bounded_human_value(file_path, 512);
            eprintln!(
                "tirith policy test: could not analyze {file_path}: coverage gap ({})",
                gap.kind.as_str()
            );
            return 1;
        }
        GuardedScanOutcome::RulePanic(_) => {
            let file_path = bounded_human_value(file_path, 512);
            eprintln!("tirith policy test: internal error scanning {file_path}: a rule panicked");
            return 1;
        }
    };

    let cwd = std::env::current_dir()
        .ok()
        .map(|p| p.display().to_string());
    let policy = Policy::discover(cwd.as_deref());

    if json {
        print_test_file_json(file_path, &result, &policy);
    } else {
        print_test_file_human(file_path, &result, &policy);
    }

    if result.findings.is_empty() {
        0
    } else if result.findings.iter().any(|f| f.severity >= Severity::High) {
        1 // block-equivalent
    } else {
        2 // warn-equivalent
    }
}

/// Run `tirith policy tune --from-audit`: roll up per-rule audit-log statistics
/// and print deterministic tuning suggestions. Never edits the policy.
pub fn tune(from_audit: bool, json: bool) -> i32 {
    if !from_audit {
        eprintln!("tirith policy tune: specify a source — currently only --from-audit");
        eprintln!("  try: tirith policy tune --from-audit");
        return 1;
    }

    let log_path = match tirith_core::policy::data_dir() {
        Some(d) => d.join("log.jsonl"),
        None => {
            eprintln!("tirith policy tune: could not determine audit log path");
            return 1;
        }
    };

    if !log_path.exists() {
        eprintln!(
            "tirith policy tune: no audit log found at {}",
            log_path.display()
        );
        eprintln!("  tirith records an audit log as you use it; come back once you have history.");
        return 1;
    }

    let result = match tirith_core::audit_aggregator::read_log(&log_path) {
        Ok(r) => r,
        Err(e) => {
            // `read_log` only fails on an I/O error (malformed lines are skipped),
            // so re-probe to distinguish an actionable permissions problem.
            eprintln!(
                "tirith policy tune: could not read the audit log at {}",
                log_path.display()
            );
            match std::fs::File::open(&log_path) {
                Err(probe) if probe.kind() == std::io::ErrorKind::PermissionDenied => {
                    eprintln!(
                        "  permission denied — check that you can read the file \
                         (its directory may also need execute permission)."
                    );
                }
                _ => {
                    eprintln!("  {e}");
                    eprintln!(
                        "  the file may be unreadable or have been removed mid-read; \
                         retry, or check the path's permissions."
                    );
                }
            }
            return 1;
        }
    };
    if result.skipped_lines > 0 {
        eprintln!(
            "tirith policy tune: warning: {} malformed audit log line(s) skipped",
            result.skipped_lines
        );
    }

    // Every rule tirith can emit — to point out rules that never fired.
    let known_rules: Vec<&str> = tirith_core::rule_explanations::list_all()
        .iter()
        .map(|r| r.id)
        .collect();

    let report = tirith_core::audit_tune::analyze(&result.records, &known_rules);

    if json {
        if serde_json::to_writer_pretty(std::io::stdout().lock(), &report).is_err() {
            eprintln!("tirith policy tune: failed to write JSON output");
            return 1;
        }
        println!();
    } else {
        print_tune_human(&report);
    }

    0
}

fn print_tune_human(report: &tirith_core::audit_tune::TuneReport) {
    eprintln!(
        "tirith policy tune: analyzed {} audit record(s)",
        report.records_analyzed
    );

    if report.data_is_thin {
        eprintln!(
            "  not enough audit history to suggest anything yet (need at least {}).",
            tirith_core::audit_tune::MIN_OBSERVATIONS
        );
        eprintln!("  keep using tirith and re-run this once more commands have been analyzed.");
        return;
    }

    if report.suggestions.is_empty() {
        eprintln!(
            "  no policy changes suggested — your current policy looks well matched to your usage."
        );
        return;
    }

    eprintln!(
        "  {} suggestion(s) — these are SUGGESTIONS only; review each, then edit your policy yourself:",
        report.suggestions.len()
    );
    eprintln!();

    for (i, s) in report.suggestions.iter().enumerate() {
        let conf = match s.confidence {
            tirith_core::audit_tune::Confidence::Strong => "strong",
            tirith_core::audit_tune::Confidence::Moderate => "moderate",
        };
        eprintln!("  {}. [{}] {}", i + 1, conf, s.observation);
        eprintln!("     {}", s.recommendation);
        if let Some(snippet) = &s.policy_snippet {
            eprintln!("     suggested policy snippet:");
            for line in snippet.lines() {
                eprintln!("       {line}");
            }
        }
        eprintln!();
    }

    eprintln!("  tirith did not change your policy. Apply any suggestion by editing your .tirith/policy.yaml.");
}

/// The fully-resolved local policy plus its provenance, as gathered for
/// `tirith policy effective`. Factored out of [`effective`] so the gathering is
/// unit-testable without capturing stdout (the rendering is a thin function of
/// these fields).
struct EffectivePolicy {
    /// Source file the policy was loaded from, or `None` for built-in defaults.
    source_path: Option<String>,
    /// Discovery scope (which branch matched) — drives the trust framing below.
    scope: tirith_core::policy::PolicyScope,
    /// The resolved policy itself (repo-scope sanitization already applied).
    policy: Policy,
}

/// Map a [`PolicyScope`] to its lowercase label for output. The single mapping
/// point shared by both the JSON `scope` field and the human framing.
///
/// [`PolicyScope`]: tirith_core::policy::PolicyScope
fn scope_label(scope: tirith_core::policy::PolicyScope) -> &'static str {
    scope.as_str()
}

/// Gather the effective local policy for `cwd`: its source path + scope (via
/// [`discover_local_policy_path_scoped`]) and the fully-resolved policy (via
/// [`Policy::discover_local_only`], which runs LOCAL resolution + repo-scope
/// sanitize and NEVER fetches remotely). Discovery-only; no network.
///
/// [`discover_local_policy_path_scoped`]: tirith_core::policy::discover_local_policy_path_scoped
fn gather_effective(cwd: Option<&str>) -> EffectivePolicy {
    let (source_path, scope) = match tirith_core::policy::discover_local_policy_path_scoped(cwd) {
        Some((path, scope)) => (Some(path.display().to_string()), scope),
        None => (None, tirith_core::policy::PolicyScope::Default),
    };
    let policy = Policy::discover_local_only(cwd);
    EffectivePolicy {
        source_path,
        scope,
        policy,
    }
}

/// `tirith policy effective` — a transparency surface that prints the FULLY-
/// RESOLVED effective policy for the current directory, where it came from, and
/// (for a repo-scoped policy) which weakening fields were neutralized down to
/// tightening-only. Discovery-only: no path argument, no network fetch (uses
/// [`Policy::discover_local_only`], not [`Policy::discover`]).
pub fn effective(json: bool) -> i32 {
    let cwd = std::env::current_dir()
        .ok()
        .map(|p| p.display().to_string());

    let info = gather_effective(cwd.as_deref());

    if json {
        print_effective_json(&info)
    } else {
        print_effective_human(&info)
    }
}

fn print_effective_json(info: &EffectivePolicy) -> i32 {
    #[derive(serde::Serialize)]
    struct Output<'a> {
        source_path: Option<&'a str>,
        scope: &'a str,
        neutralized_fields: &'a [&'static str],
        policy: &'a Policy,
    }

    let output = Output {
        source_path: info.source_path.as_deref(),
        scope: scope_label(info.scope),
        neutralized_fields: &info.policy.neutralized_fields,
        policy: &info.policy,
    };

    if super::write_json_stdout(
        &output,
        "tirith policy effective: failed to write JSON output",
    ) {
        0
    } else {
        1
    }
}

fn print_effective_human(info: &EffectivePolicy) -> i32 {
    use tirith_core::policy::PolicyScope;

    eprintln!(
        "tirith policy effective: source = {}",
        info.source_path
            .as_deref()
            .unwrap_or("(none — built-in defaults)")
    );
    eprintln!("  scope: {}", scope_label(info.scope));
    eprintln!();

    // Render the resolved policy as readable YAML (the crate already depends on
    // serde_yaml; the policy is `Serialize`). On the unlikely serialize error,
    // fall back to a note rather than failing the command — the provenance and
    // neutralization sections below are the load-bearing transparency output.
    match serde_yaml::to_string(&info.policy) {
        Ok(yaml) => {
            eprintln!("  effective policy:");
            for line in yaml.lines() {
                eprintln!("    {line}");
            }
        }
        Err(e) => {
            eprintln!("  (could not render effective policy as YAML: {e})");
        }
    }
    eprintln!();

    let neutralized = &info.policy.neutralized_fields;
    match info.scope {
        PolicyScope::Repo if !neutralized.is_empty() => {
            eprintln!(
                "  Neutralized (this repo policy is tightening-only; these weakening fields \
                 were ignored): {}",
                neutralized.join(", ")
            );
        }
        PolicyScope::Repo => {
            eprintln!("  No weakening fields — this repo policy only tightens.");
        }
        _ => {
            eprintln!("  Operator-scoped policy — all fields honored (nothing neutralized).");
        }
    }

    0
}

#[derive(serde::Serialize)]
struct PolicyTrace {
    policy_path: Option<String>,
    allowlist_checked: Vec<AllowBlockMatch>,
    blocklist_checked: Vec<AllowBlockMatch>,
}

#[derive(serde::Serialize)]
struct AllowBlockMatch {
    pattern: String,
    matched: bool,
}

fn build_policy_trace(input: &str, policy: &Policy) -> PolicyTrace {
    let input_lower = input.to_lowercase();
    let allowlist_checked: Vec<AllowBlockMatch> = policy
        .allowlist
        .iter()
        .map(|pattern| AllowBlockMatch {
            pattern: pattern.clone(),
            matched: tirith_core::policy::allowlist_pattern_matches(pattern, input),
        })
        .collect();

    let blocklist_checked: Vec<AllowBlockMatch> = policy
        .blocklist
        .iter()
        .map(|pattern| AllowBlockMatch {
            pattern: pattern.clone(),
            matched: input_lower.contains(&pattern.to_lowercase()),
        })
        .collect();

    PolicyTrace {
        policy_path: policy.path.clone(),
        allowlist_checked,
        blocklist_checked,
    }
}

fn print_test_command_json(
    command: &str,
    verdict: &tirith_core::verdict::Verdict,
    _policy: &Policy,
    trace: &PolicyTrace,
) {
    #[derive(serde::Serialize)]
    struct Output<'a> {
        command: &'a str,
        action: &'a tirith_core::verdict::Action,
        finding_count: usize,
        findings: &'a [tirith_core::verdict::Finding],
        policy_trace: &'a PolicyTrace,
    }

    let output = Output {
        command,
        action: &verdict.action,
        finding_count: verdict.findings.len(),
        findings: &verdict.findings,
        policy_trace: trace,
    };

    let mut output = match serde_json::to_value(&output) {
        Ok(output) => output,
        Err(error) => {
            let error = bounded_human_value(&error.to_string(), 512);
            eprintln!("tirith policy test: failed to construct JSON output: {error}");
            return;
        }
    };
    project_policy_cli_json(&mut output);

    if let Err(error) = serde_json::to_writer_pretty(std::io::stdout().lock(), &output) {
        let error = bounded_human_value(&error.to_string(), 512);
        eprintln!("tirith policy test: failed to write JSON output: {error}");
    }
    println!();
}

fn print_test_file_json(file_path: &str, result: &scan::FileScanResult, _policy: &Policy) {
    #[derive(serde::Serialize)]
    struct Output<'a> {
        file: &'a str,
        finding_count: usize,
        findings: &'a [tirith_core::verdict::Finding],
    }

    let output = Output {
        file: file_path,
        finding_count: result.findings.len(),
        findings: &result.findings,
    };

    let mut output = match serde_json::to_value(&output) {
        Ok(output) => output,
        Err(error) => {
            let error = bounded_human_value(&error.to_string(), 512);
            eprintln!("tirith policy test: failed to construct JSON output: {error}");
            return;
        }
    };
    project_policy_cli_json(&mut output);

    if let Err(error) = serde_json::to_writer_pretty(std::io::stdout().lock(), &output) {
        let error = bounded_human_value(&error.to_string(), 512);
        eprintln!("tirith policy test: failed to write JSON output: {error}");
    }
    println!();
}

fn print_test_command_human(
    command: &str,
    verdict: &tirith_core::verdict::Verdict,
    _policy: &Policy,
    trace: &PolicyTrace,
) {
    let command = bounded_human_value(command, 2 * 1024);
    let policy_path = trace
        .policy_path
        .as_deref()
        .map(|path| bounded_human_value(path, 512))
        .unwrap_or_else(|| "(default — no policy file)".to_string());
    eprintln!("tirith policy test: command = {:?}", command);
    eprintln!("  policy: {policy_path}");
    eprintln!("  action: {:?}", verdict.action);
    eprintln!("  findings: {}", verdict.findings.len());

    for finding in &verdict.findings {
        let sev = tirith_core::style::severity_label(
            &finding.severity,
            tirith_core::style::Stream::Stderr,
        );
        let title = bounded_human_value(&finding.title, 2 * 1024);
        eprintln!("    {} {}{}", sev, finding.rule_id, title);
    }

    if !trace.allowlist_checked.is_empty() || !trace.blocklist_checked.is_empty() {
        eprintln!();
        eprintln!("  policy trace:");
        for entry in &trace.allowlist_checked {
            let mark = if entry.matched { "MATCH" } else { "no match" };
            let pattern = bounded_human_value(&entry.pattern, 2 * 1024);
            eprintln!("    allowlist: {pattern:?} -> {mark}");
        }
        for entry in &trace.blocklist_checked {
            let mark = if entry.matched { "MATCH" } else { "no match" };
            let pattern = bounded_human_value(&entry.pattern, 2 * 1024);
            eprintln!("    blocklist: {pattern:?} -> {mark}");
        }
    }
}

fn print_test_file_human(file_path: &str, result: &scan::FileScanResult, _policy: &Policy) {
    // The tested file path is the untrusted scan subject; a crafted name could
    // carry escapes/newlines into this label.
    let file_path = bounded_human_value(file_path, 512);
    if result.findings.is_empty() {
        eprintln!("tirith policy test: {file_path} — no findings");
        return;
    }

    eprintln!(
        "tirith policy test: {file_path}{} finding(s)",
        result.findings.len()
    );

    for finding in &result.findings {
        let sev = tirith_core::style::severity_label(
            &finding.severity,
            tirith_core::style::Stream::Stderr,
        );
        let title = bounded_human_value(&finding.title, 2 * 1024);
        let description = bounded_human_value(&finding.description, 4 * 1024);
        eprintln!("  {} {}{}", sev, finding.rule_id, title);
        eprintln!("    {description}");
    }
}

fn resolve_policy_path(explicit: Option<&str>) -> Option<PathBuf> {
    if let Some(p) = explicit {
        let path = PathBuf::from(p);
        if path.exists() {
            return Some(path);
        }
        let path = bounded_human_value(p, 512);
        eprintln!("tirith policy validate: specified path does not exist: {path}");
        return None;
    }

    // Existence-based local discovery (same resolver engine/`doctor` use).
    // `Policy::discover` would drop the path on a parse error, so `validate` could
    // not locate a corrupt policy to report on, and could resolve a `remote:` URL.
    tirith_core::policy::discover_local_policy_path(None)
}

#[cfg(test)]
mod tests {
    use super::*;
    use tirith_core::policy_validate::{self, IssueLevel};

    #[test]
    fn human_validation_issue_never_echoes_policy_values_or_controls() {
        let issue = policy_validate::PolicyIssue {
            level: IssueLevel::Error,
            message: "custom_rules.secret: invalid regex 'TOKEN-42\x1b]52;c;YQ==\x07\nFORGED'"
                .to_string(),
            field: Some("custom_rules.TOKEN-42\u{202e}\nFORGED.pattern".to_string()),
        };
        let rendered = human_validation_issue(&issue, 7);
        assert!(
            rendered.contains("invalid regular expression"),
            "{rendered:?}"
        );
        assert!(rendered.contains("issue #7"), "{rendered:?}");
        assert!(!rendered.contains("TOKEN-42"), "{rendered:?}");
        assert!(!rendered.contains('\x1b'), "{rendered:?}");
        assert!(!rendered.contains('\n'), "{rendered:?}");
        assert!(!rendered.contains('\u{202e}'), "{rendered:?}");
    }

    #[test]
    fn validation_presenters_project_paths_and_nested_json_before_rendering() {
        let canary = format!("ghp_canary_{}", "A".repeat(30));
        let private_scalar = format!("{}1", "0".repeat(63));
        let local_path = format!("/Users/alice/{canary}/policy.yaml");
        let projected = bounded_human_value(
            &format!("{local_path} command-private-key={private_scalar}"),
            512,
        );
        assert!(!projected.contains(&canary), "{projected:?}");
        assert!(!projected.contains(&private_scalar), "{projected:?}");
        assert!(!projected.contains("/Users/alice"), "{projected:?}");

        let mut json = serde_json::json!({
            "path": local_path,
            "command": private_scalar.clone(),
            "nested": [{"error": format!("cannot read {canary}")}],
            "valid": false,
            "error_count": 1,
        });
        project_policy_cli_json(&mut json);
        let rendered = serde_json::to_string(&json).unwrap();
        assert!(!rendered.contains(&canary), "{rendered}");
        assert!(!rendered.contains(&private_scalar), "{rendered}");
        assert!(!rendered.contains("/Users/alice"), "{rendered}");
        assert_eq!(json["valid"], serde_json::Value::Bool(false));
        assert_eq!(json["error_count"], serde_json::json!(1));

        assert_eq!(bounded_human_value("policy.yaml", 512), "policy.yaml");
    }

    /// Every curated template must validate cleanly — no errors AND no warnings
    /// (warnings include the unknown-field typo guard, so this proves every key
    /// is a real schema key).
    fn assert_template_valid(name: &str, body: &str) {
        let issues = policy_validate::validate(body);
        let errors: Vec<_> = issues
            .iter()
            .filter(|i| i.level == IssueLevel::Error)
            .collect();
        let warnings: Vec<_> = issues
            .iter()
            .filter(|i| i.level == IssueLevel::Warning)
            .collect();
        assert!(
            errors.is_empty(),
            "{name} template must have no validation errors: {errors:?}"
        );
        assert!(
            warnings.is_empty(),
            "{name} template must have no validation warnings \
             (unknown/typo keys are warnings): {warnings:?}"
        );
    }

    #[test]
    fn individual_template_validates() {
        assert_template_valid("individual", TEMPLATE_INDIVIDUAL);
    }

    // R20: the help/error list is derived from `PolicyTemplate::ALL`, so assert
    // the CSV contains every canonical name and each round-trips through `parse`.
    #[test]
    fn template_names_csv_covers_every_variant() {
        let csv = PolicyTemplate::names_csv();
        for t in PolicyTemplate::ALL {
            let name = t.canonical_name();
            assert!(
                csv.split(", ").any(|n| n == name),
                "names_csv ({csv:?}) must list the canonical name {name:?} for {t:?}"
            );
        }
        // Every comma-separated entry is a real, parseable canonical name.
        for entry in csv.split(", ") {
            assert!(
                PolicyTemplate::parse(entry).is_some(),
                "names_csv entry {entry:?} must parse back to a PolicyTemplate variant"
            );
        }
        // The count matches: no duplicates, no extras.
        assert_eq!(
            csv.split(", ").count(),
            PolicyTemplate::ALL.len(),
            "names_csv must have exactly one entry per variant"
        );
    }

    #[test]
    fn ci_strict_template_validates() {
        assert_template_valid("ci-strict", TEMPLATE_CI_STRICT);
    }

    #[test]
    fn ai_agent_heavy_template_validates() {
        assert_template_valid("ai-agent-heavy", TEMPLATE_AI_AGENT_HEAVY);
    }

    #[test]
    fn oss_maintainer_template_validates() {
        assert_template_valid("oss-maintainer", TEMPLATE_OSS_MAINTAINER);
    }

    #[test]
    fn startup_template_validates() {
        assert_template_valid("startup", TEMPLATE_STARTUP);
    }

    #[test]
    fn enterprise_template_validates() {
        assert_template_valid("enterprise", TEMPLATE_ENTERPRISE);
    }

    #[test]
    fn mcp_strict_template_validates() {
        assert_template_valid("mcp-strict", TEMPLATE_MCP_STRICT);
    }

    #[test]
    fn builtin_full_and_minimal_templates_validate() {
        // Guards the unchanged default + minimal templates alongside the new ones.
        assert_template_valid("full", FULL_TEMPLATE);
        assert_template_valid("minimal", MINIMAL_TEMPLATE);
    }

    #[test]
    fn template_parse_accepts_canonical_and_underscore_names() {
        assert_eq!(
            PolicyTemplate::parse("individual"),
            Some(PolicyTemplate::Individual)
        );
        assert_eq!(
            PolicyTemplate::parse("ci-strict"),
            Some(PolicyTemplate::CiStrict)
        );
        assert_eq!(
            PolicyTemplate::parse("CI-STRICT"),
            Some(PolicyTemplate::CiStrict)
        );
        assert_eq!(
            PolicyTemplate::parse("ai-agent-heavy"),
            Some(PolicyTemplate::AiAgentHeavy)
        );
        assert_eq!(
            PolicyTemplate::parse(" ai_agent_heavy "),
            Some(PolicyTemplate::AiAgentHeavy)
        );
        // M13 ch2 — the four new templates.
        assert_eq!(
            PolicyTemplate::parse("oss-maintainer"),
            Some(PolicyTemplate::OssMaintainer)
        );
        assert_eq!(
            PolicyTemplate::parse("oss_maintainer"),
            Some(PolicyTemplate::OssMaintainer)
        );
        assert_eq!(
            PolicyTemplate::parse("startup"),
            Some(PolicyTemplate::Startup)
        );
        assert_eq!(
            PolicyTemplate::parse("Enterprise"),
            Some(PolicyTemplate::Enterprise)
        );
        assert_eq!(
            PolicyTemplate::parse("mcp-strict"),
            Some(PolicyTemplate::McpStrict)
        );
        assert_eq!(
            PolicyTemplate::parse("mcp_strict"),
            Some(PolicyTemplate::McpStrict)
        );
    }

    #[test]
    fn template_parse_personal_is_alias_for_individual() {
        // `personal` is the spec word; `individual` is the shipping name. The
        // alias resolves to the same variant — and therefore the same body.
        assert_eq!(
            PolicyTemplate::parse("personal"),
            Some(PolicyTemplate::Individual)
        );
        assert_eq!(
            PolicyTemplate::parse(" PERSONAL "),
            Some(PolicyTemplate::Individual)
        );
        // The alias' canonical name is the shipping name, so `tirith onboard`
        // never emits `personal`.
        assert_eq!(
            PolicyTemplate::parse("personal").unwrap().canonical_name(),
            "individual"
        );
        // Byte-for-byte: the alias writes exactly the individual body.
        assert_eq!(
            PolicyTemplate::parse("personal").unwrap().body(),
            TEMPLATE_INDIVIDUAL
        );
        assert_eq!(
            PolicyTemplate::Individual.body(),
            PolicyTemplate::parse("personal").unwrap().body()
        );
    }

    #[test]
    fn template_parse_rejects_unknown_and_deferred_names() {
        assert_eq!(PolicyTemplate::parse("fintech"), None);
        assert_eq!(PolicyTemplate::parse("windows-enterprise"), None);
        assert_eq!(PolicyTemplate::parse(""), None);
        assert_eq!(PolicyTemplate::parse("default"), None);
    }

    /// Every template body must deserialize through the same
    /// `serde_yaml::from_str::<Policy>` path `Policy::load` uses (not just the
    /// validator).
    #[test]
    fn all_templates_deserialize_into_policy() {
        // Iterate `PolicyTemplate::ALL` (R20) so a new template is auto-covered.
        for t in PolicyTemplate::ALL {
            let body = t.body();
            let parsed: Result<tirith_core::policy::Policy, _> = serde_yaml::from_str(body);
            assert!(
                parsed.is_ok(),
                "{} template must deserialize into Policy: {:?}",
                t.canonical_name(),
                parsed.err()
            );
        }
    }

    #[test]
    fn oss_maintainer_template_is_moderate_fail_open() {
        // Contract of oss-maintainer: moderate (paranoia 2), still fail-open,
        // and a human may bypass interactively.
        let p: tirith_core::policy::Policy = serde_yaml::from_str(TEMPLATE_OSS_MAINTAINER).unwrap();
        assert_eq!(p.fail_mode, tirith_core::policy::FailMode::Open);
        assert_eq!(p.paranoia, 2);
        assert!(p.allow_bypass_env);
        assert!(!p.allow_bypass_env_noninteractive);
    }

    #[test]
    fn startup_template_is_balanced_strict_warn() {
        // Contract of startup: a notch stricter than individual — paranoia 2,
        // strict-warn on, fail-open, no non-interactive bypass.
        let p: tirith_core::policy::Policy = serde_yaml::from_str(TEMPLATE_STARTUP).unwrap();
        assert_eq!(p.fail_mode, tirith_core::policy::FailMode::Open);
        assert_eq!(p.paranoia, 2);
        assert!(p.strict_warn);
        assert!(!p.allow_bypass_env_noninteractive);
    }

    #[test]
    fn enterprise_template_is_strict_with_active_package_policy() {
        // Contract of enterprise: fail-closed, no bypass at all, AND an
        // ACTIVE (uncommented) package_policy block with strict defaults.
        // This is the M13 ch2 acceptance pin (M6_TO_M14_PLAN.md).
        let p: tirith_core::policy::Policy = serde_yaml::from_str(TEMPLATE_ENTERPRISE).unwrap();
        assert_eq!(p.fail_mode, tirith_core::policy::FailMode::Closed);
        assert!(!p.allow_bypass_env);
        assert!(!p.allow_bypass_env_noninteractive);
        // The active package_policy block — not defaults, real strict values.
        assert!(
            p.package_policy.block_not_found,
            "enterprise must ship block_not_found: true"
        );
        assert_eq!(
            p.package_policy.block_osv_min_cvss,
            Some(7.0),
            "enterprise must ship block_osv_min_cvss: 7.0"
        );
        assert_eq!(p.package_policy.block_newer_than_days, Some(7));
        assert_eq!(p.package_policy.block_typosquat_distance, Some(1));
        assert!(p.package_policy.block_repo_mismatch);
    }

    #[test]
    fn mcp_strict_template_escalates_mcp_rules() {
        // Contract of mcp-strict: fail-closed and every MCP config rule
        // escalated; the two highest-risk MCP rules are forced to block.
        let p: tirith_core::policy::Policy = serde_yaml::from_str(TEMPLATE_MCP_STRICT).unwrap();
        assert_eq!(p.fail_mode, tirith_core::policy::FailMode::Closed);
        for rule in [
            "mcp_insecure_server",
            "mcp_untrusted_server",
            "mcp_overly_permissive",
            "mcp_suspicious_args",
            "mcp_server_drift",
        ] {
            assert!(
                p.severity_overrides.contains_key(rule),
                "mcp-strict must escalate {rule}"
            );
        }
        assert_eq!(
            p.action_overrides
                .get("mcp_untrusted_server")
                .map(String::as_str),
            Some("block")
        );
    }

    #[test]
    fn ci_strict_template_is_fail_closed_no_bypass() {
        // The contract of ci-strict: fail-closed and no bypass at all.
        let p: tirith_core::policy::Policy = serde_yaml::from_str(TEMPLATE_CI_STRICT).unwrap();
        assert_eq!(p.fail_mode, tirith_core::policy::FailMode::Closed);
        assert!(!p.allow_bypass_env);
        assert!(!p.allow_bypass_env_noninteractive);
    }

    #[test]
    fn ai_agent_heavy_template_blocks_agent_bypass() {
        // An AI agent runs non-interactively; it must not be able to bypass.
        let p: tirith_core::policy::Policy = serde_yaml::from_str(TEMPLATE_AI_AGENT_HEAVY).unwrap();
        assert!(!p.allow_bypass_env_noninteractive);
        assert!(!p.approval_rules.is_empty());
        assert!(!p.escalation.is_empty());
    }

    /// `policy effective` transparency contract: for a REPO-scoped policy that
    /// declares a weakening field (a non-empty `allowlist`), the gathered data
    /// must name the source path, classify the scope as `repo`, and list
    /// `allowlist` among the neutralized fields (repo policies are tightening-
    /// only). Drives [`gather_effective`] directly so no stdout capture is
    /// needed — the renderer is a thin function of these fields.
    #[test]
    fn effective_repo_scope_lists_neutralized_allowlist() {
        use crate::cli::test_harness::{with_fake_env, EnvGuard};

        with_fake_env(true, |_home, cwd| {
            let cwd = cwd.expect("cwd set");
            // Isolate machine-level policy sources so only our repo policy is
            // discovered (these are not faked by `with_fake_env`).
            let _root = EnvGuard::remove("TIRITH_POLICY_ROOT");
            let _xdg = EnvGuard::remove("XDG_CONFIG_HOME");

            // A repo checkout: `.git` makes the walk-up stamp PolicyScope::Repo,
            // which triggers repo-scope sanitization of the weakening `allowlist`.
            std::fs::create_dir_all(cwd.join(".git")).unwrap();
            std::fs::create_dir_all(cwd.join(".tirith")).unwrap();
            std::fs::write(
                cwd.join(".tirith").join("policy.yaml"),
                "fail_mode: open\nallowlist:\n  - evil.example\n",
            )
            .unwrap();

            let info = gather_effective(cwd.to_str());

            // Source path: the repo-root policy we just wrote.
            let expected_path = cwd
                .join(".tirith")
                .join("policy.yaml")
                .display()
                .to_string();
            assert_eq!(
                info.source_path.as_deref(),
                Some(expected_path.as_str()),
                "effective must name the repo-root policy as the source",
            );

            // Scope: repo (and its lowercase label).
            assert_eq!(info.scope, tirith_core::policy::PolicyScope::Repo);
            assert_eq!(scope_label(info.scope), "repo");

            // The weakening `allowlist` was neutralized AND recorded — this is the
            // drop list `policy effective` surfaces.
            assert!(
                info.policy.neutralized_fields.contains(&"allowlist"),
                "allowlist must be listed as neutralized for a repo policy; got {:?}",
                info.policy.neutralized_fields,
            );
            // And the value itself was actually reset to tightening-only default.
            assert!(
                info.policy.allowlist.is_empty(),
                "the repo allowlist must be reset (neutralized), not honored",
            );
        });
    }
}