speccoder-runtime 0.7.0

Application services of speccoder: the only crate that executes anything.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
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
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
//! The policy classifier: every tool call is
//! allowed, needs approval, or is denied — decided by code, before the call.
//!
//! It decides *which* calls run; what an allowed command can reach is the
//! OS sandbox's job (`crate::sandbox`).

use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::paths::{Protected, normalise};

/// The prefix of an MCP tool's name as the model sees it (`crate::mcp`).
pub const MCP_PREFIX: &str = "mcp__";

/// What the engine does with a call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
    /// Run it.
    Allow,
    /// Ask a person first.
    Approval(String),
    /// Never run it.
    Deny(String),
}

/// The kind of object a decision covers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Class {
    /// A write or edit of one file.
    Write,
    /// One exact command.
    Command,
    /// One exact command with the network.
    Network,
    /// One MCP tool as defined now.
    Mcp,
    /// One action an external agent takes itself.
    Agent,
}

impl Class {
    /// Its name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Write => "write",
            Self::Command => "command",
            Self::Network => "network",
            Self::Mcp => "mcp",
            Self::Agent => "agent",
        }
    }
}

/// What a person's decision covers: exactly one resolved object — never
/// the request's spelling and never a pattern (constitution V). A path is
/// the canonical file a write reaches; a command is its exact argv with
/// the directory it runs in and the executable it resolves to; an MCP tool
/// is its name with the digest of its definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Object {
    /// `write_file` / `edit_file` of this file.
    Path {
        /// Workspace-relative, every existing ancestor's symlinks resolved.
        canonical: String,
        /// The path as the model sent it (normalised).
        asked: String,
    },
    /// `run_command` with exactly this argv.
    Command {
        /// The argv.
        argv: Vec<String>,
        /// Hex SHA-256 over the argv as a JSON array.
        argv_sha256: String,
        /// The working directory, workspace-relative (`.` for the root).
        cwd: String,
        /// The executable's absolute canonical path, or `not found`.
        executable: String,
        /// Whether the call has the network.
        network: bool,
    },
    /// This MCP tool, as its server defines it now.
    Tool {
        /// `mcp__<server>__<tool>`.
        name: String,
        /// agentplane's digest over the tool's definition.
        digest: String,
    },
    /// An external agent's own action, in its own process: exactly these
    /// commands and paths — never covered by a grant of speccoder's own
    /// calls, nor covering one.
    Agent {
        /// The agent (its preset id).
        agent: String,
        /// `execute`, `edit`, `read`, … as the agent declared it.
        call: String,
        /// The commands it runs, exactly.
        argvs: Vec<Vec<String>>,
        /// The worktree paths it names, canonical.
        paths: Vec<String>,
        /// A digest of what else it carries, when that decides (a call
        /// speccoder cannot read); empty otherwise.
        input: String,
    },
}

/// What an executable that cannot be found is recorded as.
pub const NOT_FOUND: &str = "not found";

/// Why a command no rule allows needs a person.
pub const NOT_ALLOWED: &str = "not a configured check or allowed command";

/// A call that stopped for a person nobody could ask then, in a person's
/// words: the call (a command's argv as typed), why, and how to let it run
/// — for a command no rule allows, its exact `[commands] allow` entry;
/// `decide` says how else (e.g. ``approve it: `speccoder task approve T001` ``).
#[must_use]
pub fn unasked(pending: &Value, decide: &str) -> String {
    let tool = pending["tool"].as_str().unwrap_or_default();
    let reason = pending["reason"].as_str().unwrap_or_default();
    let arguments = &pending["arguments"];
    if tool == "run_command" {
        let argv = argv_of(arguments);
        let shown = crate::approvals::present::shell_quote(&argv);
        if reason == NOT_ALLOWED {
            let entry = argv
                .iter()
                .map(|a| serde_json::to_string(a).unwrap_or_default())
                .collect::<Vec<_>>()
                .join(", ");
            return format!(
                "`{shown}` needs approval: it is {NOT_ALLOWED} — allow exactly it in speccoder.toml (`[commands] allow = [[{entry}]]`), or {decide}"
            );
        }
        return format!("`{shown}` needs approval: {reason} — {decide}");
    }
    // An external agent's own action: what it is, in words.
    if let Ok(o @ Object::Agent { .. }) =
        serde_json::from_value::<Object>(pending["object"].clone())
    {
        return format!("{} needs approval: {reason} — {decide}", o.describe());
    }
    let object = arguments["path"]
        .as_str()
        .map(|p| format!(" `{p}`"))
        .unwrap_or_default();
    format!("`{tool}`{object} needs approval: {reason} — {decide}")
}

impl PartialEq for Object {
    /// A path is the file it reaches (any spelling); a command and a tool
    /// are every field.
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Path { canonical: a, .. }, Self::Path { canonical: b, .. }) => a == b,
            (
                Self::Command {
                    argv: a1,
                    argv_sha256: a2,
                    cwd: a3,
                    executable: a4,
                    network: a5,
                },
                Self::Command {
                    argv: b1,
                    argv_sha256: b2,
                    cwd: b3,
                    executable: b4,
                    network: b5,
                },
            ) => a1 == b1 && a2 == b2 && a3 == b3 && a4 == b4 && a5 == b5,
            (Self::Tool { name: a, digest: x }, Self::Tool { name: b, digest: y }) => {
                a == b && x == y
            }
            (
                Self::Agent {
                    agent: a1,
                    call: a2,
                    argvs: a3,
                    paths: a4,
                    input: a5,
                },
                Self::Agent {
                    agent: b1,
                    call: b2,
                    argvs: b3,
                    paths: b4,
                    input: b5,
                },
            ) => a1 == b1 && a2 == b2 && a3 == b3 && a4 == b4 && a5 == b5,
            _ => false,
        }
    }
}

impl Eq for Object {}

/// Hex SHA-256 over `argv` as a JSON array.
#[must_use]
pub fn argv_sha256(argv: &[String]) -> String {
    use sha2::{Digest as _, Sha256};
    let json = serde_json::to_string(argv).unwrap_or_default();
    Sha256::digest(json.as_bytes())
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

fn first12(hex: &str) -> &str {
    hex.get(..12).unwrap_or(hex)
}

impl Object {
    /// A command object; the argv's hash is computed.
    #[must_use]
    pub fn command(argv: Vec<String>, cwd: String, executable: String, network: bool) -> Self {
        Self::Command {
            argv_sha256: argv_sha256(&argv),
            argv,
            cwd,
            executable,
            network,
        }
    }

    /// Its class.
    #[must_use]
    pub const fn class(&self) -> Class {
        match self {
            Self::Path { .. } => Class::Write,
            Self::Command { network: true, .. } => Class::Network,
            Self::Command { .. } => Class::Command,
            Self::Tool { .. } => Class::Mcp,
            Self::Agent { .. } => Class::Agent,
        }
    }

    /// One line for people.
    #[must_use]
    pub fn describe(&self) -> String {
        match self {
            Self::Path { canonical, .. } => format!("write `{canonical}`"),
            Self::Command {
                argv, cwd, network, ..
            } => {
                let place = if cwd == "." {
                    String::new()
                } else {
                    format!(" in `{cwd}`")
                };
                let net = if *network { " with the network" } else { "" };
                format!("run `{}`{place}{net}", argv.join(" "))
            }
            Self::Tool { name, digest } => format!("use `{name}`@{}", first12(digest)),
            Self::Agent {
                agent,
                call: kind,
                argvs,
                paths,
                ..
            } => {
                if kind == "reads" {
                    return format!("{agent}'s plain reads of one file each, for the task");
                }
                let what: Vec<String> = argvs
                    .iter()
                    .map(|a| format!("`{}`", a.join(" ")))
                    .chain(paths.iter().map(|p| format!("`{p}`")))
                    .collect();
                format!("{agent} itself: {kind} {}", what.join(", "))
            }
        }
    }

    /// Its grant id: `g-<16 hex>` over what the object is — the
    /// canonical path, every field of a command, a tool's name and digest —
    /// so one id names one object and nothing else.
    #[must_use]
    pub fn grant_id(&self) -> String {
        use sha2::{Digest as _, Sha256};
        let identity = match self {
            Self::Path { canonical, .. } => serde_json::json!({ "path": canonical }),
            Self::Command {
                argv,
                argv_sha256,
                cwd,
                executable,
                network,
            } => serde_json::json!({
                "argv": argv, "argv_sha256": argv_sha256, "cwd": cwd,
                "executable": executable, "network": network,
            }),
            Self::Tool { name, digest } => serde_json::json!({ "tool": name, "digest": digest }),
            Self::Agent {
                agent,
                call,
                argvs,
                paths,
                input,
            } => {
                serde_json::json!({ "agent": agent, "call": call, "argvs": argvs, "paths": paths, "input": input })
            }
        };
        let hex: String = Sha256::digest(identity.to_string().as_bytes())
            .iter()
            .take(8)
            .map(|b| format!("{b:02x}"))
            .collect();
        format!("g-{hex}")
    }

    /// The short form events and lists carry: the path, `argv#<12 hex>`,
    /// `<tool>@<12 hex>` — never more of the argv than the target shows.
    #[must_use]
    pub fn short(&self) -> String {
        match self {
            Self::Path { canonical, .. } => canonical.clone(),
            Self::Command { argv_sha256, .. } => format!("argv#{}", first12(argv_sha256)),
            Self::Tool { name, digest } => format!("{name}@{}", first12(digest)),
            Self::Agent { agent, call, .. } => {
                format!("{agent}:{call}#{}", first12(&self.grant_id()))
            }
        }
    }

    /// Whether `other` names the same thing as this one by the request's
    /// spelling (the path as asked, the argv, the tool's name) — the case
    /// in which a different object is worth telling the person about.
    #[must_use]
    pub fn same_name(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Path { asked: a, .. }, Self::Path { asked: b, .. }) => a == b,
            (
                Self::Command {
                    argv: a,
                    network: x,
                    ..
                },
                Self::Command {
                    argv: b,
                    network: y,
                    ..
                },
            ) => a == b && x == y,
            (Self::Tool { name: a, .. }, Self::Tool { name: b, .. }) => a == b,
            _ => false,
        }
    }

    /// What differs from `earlier`, an object of the same name a person
    /// approved: `executable /usr/bin/make → /w/bin/make`.
    #[must_use]
    pub fn changed_from(&self, earlier: &Self) -> Option<String> {
        if self == earlier || !self.same_name(earlier) {
            return None;
        }
        let mut what = Vec::new();
        match (earlier, self) {
            (Self::Path { canonical: a, .. }, Self::Path { canonical: b, .. }) => {
                what.push(format!("resolves to {b}, was {a}"));
            }
            (
                Self::Command {
                    cwd: c1,
                    executable: e1,
                    ..
                },
                Self::Command {
                    cwd: c2,
                    executable: e2,
                    ..
                },
            ) => {
                if e1 != e2 {
                    what.push(format!("executable {e1} → {e2}"));
                }
                if c1 != c2 {
                    what.push(format!("directory {c1} → {c2}"));
                }
            }
            (Self::Tool { digest: a, .. }, Self::Tool { digest: b, .. }) => {
                what.push(format!(
                    "definition @{} → @{} (the tool's definition changed since it was approved)",
                    first12(a),
                    first12(b)
                ));
            }
            _ => {}
        }
        (!what.is_empty()).then(|| what.join("; "))
    }

    /// The MCP tool's name, for a tool object.
    #[must_use]
    pub fn tool_name(&self) -> Option<&str> {
        match self {
            Self::Tool { name, .. } => Some(name),
            _ => None,
        }
    }

    /// The canonical path, for a path object.
    #[must_use]
    pub fn path(&self) -> Option<&str> {
        match self {
            Self::Path { canonical, .. } => Some(canonical),
            _ => None,
        }
    }
}

/// A person's "no", with the reason the model is told.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rejection {
    /// What was rejected.
    pub object: Object,
    /// Why.
    pub reason: String,
}

/// The classifier for one project.
#[derive(Debug, Clone, Default)]
pub struct Policy {
    /// Check-derived prefixes: each configured check's program and
    /// subcommands up to its first option (committed configuration).
    checks: Vec<Vec<String>>,
    /// `[commands] allow`: exact argvs.
    exact: std::collections::BTreeSet<Vec<String>>,
    /// `[commands] allow_prefix`: prefixes of at least two elements.
    prefix: Vec<Vec<String>>,
    protected: Protected,
    frozen: std::collections::BTreeSet<String>,
    approved: Vec<Object>,
    rejected: Vec<Rejection>,
    /// MCP tools by model-facing name: `allow`, `approval` or `deny`.
    mcp: std::collections::BTreeMap<String, String>,
    /// The planning profile for hosted planning skills.
    authoring: bool,
    /// A planning task's unit directory (worktree-relative): its design
    /// documents are the task's work, its judged files are not.
    planning: Option<String>,
    /// `[sandbox] network_allow`: exact argvs that get the network.
    network_exact: std::collections::BTreeSet<Vec<String>>,
    /// `[sandbox] network_allow_prefix`: prefixes that get it.
    network_prefix: Vec<Vec<String>>,
    /// An in-place attempt: git commands that move the person's checkout
    /// are denied.
    in_place: bool,
    /// In place: what git ignored at the run's start (directories end in
    /// `/`), invisible to the file tools unless protected.
    hidden: Vec<String>,
    /// An autopilot run: a call that would ask a person, and that
    /// no grant covers, is refused for the run instead.
    autopilot: bool,
    /// Exploring: the paths it may write (the format's own exploration
    /// artifacts) and the read-only commands it may run. Nothing asks.
    exploring: Option<Exploring>,
}

/// What an exploring run may do beyond reading.
#[derive(Debug, Clone, Copy)]
pub struct Exploring {
    /// Paths (workspace-relative) the format's exploration skill writes.
    pub paths: fn(&str) -> bool,
    /// Argv prefixes of its read-only commands.
    pub commands: &'static [&'static [&'static str]],
}

/// Why an exploring run's write was refused.
pub const EXPLORING_WRITE: &str = "exploring writes nothing — the brief is made when the person chooses, and *Start spec* writes the spec";

/// Why an autopilot run refused a call that would have asked a person.
pub const AUTOPILOT_DENIED: &str = "autopilot: not asked — listed for you";

/// Whether `argv` starts with `prefix`, a prefix of at least two elements
/// (a bare program allows any argument, so it is never a prefix).
#[must_use]
pub fn prefix_matches(prefix: &[String], argv: &[String]) -> bool {
    prefix.len() >= 2 && argv.starts_with(prefix)
}

/// Why a prefix entry is refused, if it is: a bare program allows any
/// argument.
#[must_use]
pub fn prefix_refusal(prefix: &[String]) -> Option<&'static str> {
    (prefix.len() < 2).then_some(
        "a bare program allows any argument; add the exact command to [commands] allow instead",
    )
}

const SHELLS: &[&str] = &[
    "sh", "bash", "zsh", "fish", "dash", "ksh", "csh", "tcsh", "pwsh",
];
const PRIVILEGE: &[&str] = &["sudo", "su", "doas", "pkexec"];
const NETWORK: &[&str] = &[
    "curl", "wget", "nc", "ncat", "ssh", "scp", "sftp", "rsync", "ftp", "telnet",
];
const GIT_REMOTE: &[&str] = &[
    "push",
    "fetch",
    "pull",
    "clone",
    "remote",
    "ls-remote",
    "submodule",
];
/// What would move the checkout of an in-place run under speccoder.
const GIT_IN_PLACE: &[&str] = &[
    "checkout",
    "switch",
    "reset",
    "commit",
    "merge",
    "rebase",
    "cherry-pick",
    "revert",
    "stash",
    "branch",
    "tag",
    "update-ref",
    "worktree",
    "am",
];

/// Prefixes that run whatever program follows them.
const RUNNERS: &[&[&str]] = &[
    &["uv", "run"],
    &["uv", "tool", "run"],
    &["uvx"],
    &["poetry", "run"],
    &["pipx", "run"],
    &["pdm", "run"],
    &["hatch", "run"],
];

impl Policy {
    /// A policy allowing the command prefixes of `checks` (program and
    /// subcommands, up to the first option) and exactly the argvs of
    /// `exact` (`[commands] allow`).
    #[must_use]
    pub fn new(checks: &[Vec<String>], exact: &[Vec<String>]) -> Self {
        let mut allowed: Vec<Vec<String>> = checks
            .iter()
            .map(|argv| {
                let prefix: Vec<String> = argv
                    .iter()
                    .take_while(|a| !a.starts_with('-'))
                    .cloned()
                    .collect();
                // `python3 -m pytest …` would leave the bare interpreter as
                // the prefix — and allow `python3 -c <anything>`; `uv run`
                // would allow any program. A check whose prefix is only its
                // program, or a runner of another program, allows exactly
                // itself.
                if (prefix.len() == 1
                    || RUNNERS.iter().any(|r| {
                        prefix
                            .iter()
                            .map(String::as_str)
                            .take(r.len())
                            .eq(r.iter().copied())
                    }))
                    && argv.len() > prefix.len()
                {
                    argv.clone()
                } else {
                    prefix
                }
            })
            .filter(|p: &Vec<String>| !p.is_empty())
            .collect();
        allowed.sort();
        allowed.dedup();
        Self {
            checks: allowed,
            exact: exact.iter().filter(|p| !p.is_empty()).cloned().collect(),
            ..Self::default()
        }
    }

    /// `[commands] allow_prefix`: prefixes of two elements or more (a
    /// shorter one is dropped; the configuration refuses it).
    #[must_use]
    pub fn with_prefixes(mut self, prefixes: Vec<Vec<String>>) -> Self {
        self.prefix = prefixes.into_iter().filter(|p| p.len() >= 2).collect();
        self
    }

    /// The check-derived prefixes, for a coverage view.
    #[must_use]
    pub fn check_prefixes(&self) -> &[Vec<String>] {
        &self.checks
    }

    /// Paths git ignored when an in-place run started: the file tools
    /// refuse them, except the protected files (the intent stays readable).
    #[must_use]
    pub fn with_hidden(mut self, hidden: impl IntoIterator<Item = String>) -> Self {
        self.hidden = hidden.into_iter().collect();
        self
    }

    /// Whether `rel` is ignored by git in an in-place checkout and not one
    /// of the files speccoder protects.
    fn is_hidden(&self, rel: &str) -> bool {
        self.protected.write_class(rel).is_none()
            && !self.protected.is_context(rel)
            && self.hidden.iter().any(|h| match h.strip_suffix('/') {
                Some(dir) => rel == dir || rel.starts_with(h.as_str()),
                None => rel == h,
            })
    }

    /// An in-place attempt (`run --in-place`): the checkout is the
    /// person's, so git commands that move it are denied.
    #[must_use]
    pub fn in_place(mut self) -> Self {
        self.in_place = true;
        self
    }

    /// An autopilot run: nothing asks ([`Policy::settle`]).
    #[must_use]
    pub const fn autopilot(mut self) -> Self {
        self.autopilot = true;
        self
    }

    /// Whether it is an autopilot run's.
    #[must_use]
    pub const fn is_autopilot(&self) -> bool {
        self.autopilot
    }

    /// What a decision comes to once every grant had its say: on
    /// autopilot a call that would still ask a person is refused for the
    /// run ([`AUTOPILOT_DENIED`]); every other decision stands — a denial,
    /// a rejection or a protected path is never lifted.
    #[must_use]
    pub fn settle(&self, decision: Decision) -> Decision {
        match decision {
            Decision::Approval(_) if self.autopilot => Decision::Deny(AUTOPILOT_DENIED.to_owned()),
            d => d,
        }
    }

    /// The explore profile: reading is allowed; a write only inside the
    /// format's exploration paths (and only where the rules allow it), a
    /// command only from its read-only list, never with the network —
    /// and nothing goes to a person: what is not allowed is denied.
    #[must_use]
    pub const fn exploring(mut self, e: Exploring) -> Self {
        self.exploring = Some(e);
        self
    }

    /// The planning profile: the format's artifacts and scripts are the
    /// work; its machinery, verification inputs and secrets stay denied;
    /// anything else — source code included — needs approval.
    #[must_use]
    pub fn authoring(mut self) -> Self {
        self.authoring = true;
        self
    }

    /// A planning task's profile: writes inside the unit's directory
    /// `dir` (worktree-relative) are its work, except the format's judged
    /// files ([`crate::format::Rules::judged`]), a credential and the
    /// person's review; everything else is as the policy says.
    #[must_use]
    pub fn planning(mut self, dir: &str) -> Self {
        let dir = dir.trim_matches('/');
        self.planning = (!dir.is_empty()).then(|| dir.to_owned());
        self
    }

    /// Whether `rel` (resolved, worktree-relative) is a planning task's
    /// to write: a design document inside its unit's directory
    /// ([`Protected::is_design_doc`]), not judged by the format.
    #[must_use]
    pub fn is_planning_write(&self, rel: &str) -> bool {
        let Some(dir) = &self.planning else {
            return false;
        };
        rel.strip_prefix(dir.as_str())
            .and_then(|r| r.strip_prefix('/'))
            .is_some_and(|r| {
                !r.is_empty()
                    && !r.split('/').any(|s| s == ".." || s == ".")
                    && !(self.protected.rules().judged)(r.trim_end_matches('/'))
                    && self.protected.is_design_doc(rel)
                    && !self.protected.is_review(rel)
            })
    }

    /// The project's format's rules (intent, planning artifacts); the
    /// reference format's by default.
    #[must_use]
    pub fn rules(mut self, rules: &'static crate::format::Rules) -> Self {
        self.protected = Protected::new(rules);
        self
    }

    /// `[sandbox] network_allow`: exact argvs that get the network.
    #[must_use]
    pub fn with_network(mut self, exact: Vec<Vec<String>>) -> Self {
        self.network_exact = exact.into_iter().filter(|p| !p.is_empty()).collect();
        self
    }

    /// `[sandbox] network_allow_prefix`: prefixes (two elements or more)
    /// that get the network.
    #[must_use]
    pub fn with_network_prefixes(mut self, prefixes: Vec<Vec<String>>) -> Self {
        self.network_prefix = prefixes.into_iter().filter(|p| p.len() >= 2).collect();
        self
    }

    /// Whether `argv` gets the network without asking: an exact entry, or a
    /// prefix entry it extends.
    #[must_use]
    pub fn network_allowed(&self, argv: &[String]) -> bool {
        self.network_exact.contains(argv)
            || self.network_prefix.iter().any(|p| prefix_matches(p, argv))
    }

    /// The project's MCP tools and their configured decisions.
    #[must_use]
    pub fn with_mcp(mut self, tools: impl IntoIterator<Item = (String, String)>) -> Self {
        self.mcp = tools.into_iter().collect();
        self
    }

    /// A person's decisions for this task: an approval turns a call that
    /// needs approval into an allowed one (never a denied one); a rejection
    /// turns it into a denial with the person's reason.
    #[must_use]
    pub fn with_decisions(mut self, approved: Vec<Object>, rejected: Vec<Rejection>) -> Self {
        self.approved = approved;
        self.rejected = rejected;
        self
    }

    /// Freezes these test files: writing them needs approval.
    #[must_use]
    pub fn with_frozen(mut self, frozen: impl IntoIterator<Item = String>) -> Self {
        self.frozen = frozen.into_iter().collect();
        self
    }

    /// The protected set this policy uses.
    #[must_use]
    pub fn protected(&self) -> &Protected {
        &self.protected
    }

    /// Whether this (resolved, workspace-relative) path is protected for
    /// writing under this policy: the authoring profile writes the format's
    /// artifacts, nothing else of the protected set.
    #[must_use]
    pub fn write_protected(&self, rel: &str) -> Option<super::paths::Class> {
        if self.is_planning_write(rel) {
            return None;
        }
        if self.authoring
            && (self.protected.rules().authoring_path)(rel)
            && !self.protected.is_secret(rel)
            && !self.protected.is_review(rel)
        {
            return None;
        }
        self.protected.write_class(rel)
    }

    /// Classifies `tool` called with `args`. A person's decision applies
    /// only to the call's resolved `object` (none: the request alone was
    /// seen, and nobody's decision covers it): a rejection of that very
    /// object denies it, an approval of it allows it, never a denial.
    #[must_use]
    pub fn classify(&self, tool: &str, args: &Value, object: Option<&Object>) -> Decision {
        let decision = self.base(tool, args);
        if !matches!(decision, Decision::Approval(_)) {
            return decision;
        }
        let Some(object) = object else {
            return decision;
        };
        if let Some(r) = self.rejected.iter().find(|r| r.object == *object) {
            return Decision::Deny(format!("a person rejected this: {}", r.reason));
        }
        if self.approved.iter().any(|a| a == object) {
            return Decision::Allow;
        }
        decision
    }

    /// A person's rejection of exactly `object`, if one holds.
    #[must_use]
    pub fn rejection(&self, object: &Object) -> Option<&Rejection> {
        self.rejected.iter().find(|r| r.object == *object)
    }

    /// The person's rejections and approvals, for the changed-object line.
    #[must_use]
    pub fn approved(&self) -> &[Object] {
        &self.approved
    }

    /// The rule that decides `tool` with `args` when no person does: what a
    /// call's record names, so a rule's decision is never read as a
    /// person's.
    #[must_use]
    pub fn rule(&self, tool: &str, args: &Value, object: Option<&Object>) -> String {
        if self.autopilot && matches!(self.classify(tool, args, object), Decision::Approval(_)) {
            return "autopilot".to_owned();
        }
        if let Some(object) = object
            && matches!(self.base(tool, args), Decision::Approval(_))
        {
            if self.rejected.iter().any(|r| r.object == *object) {
                return format!("rejection of {} for the task", object.describe());
            }
            if self.approved.iter().any(|a| a == object) {
                return format!("grant {} for the task", object.describe());
            }
        }
        if tool.starts_with(MCP_PREFIX) {
            let entry = self.mcp.get(tool).map_or("unlisted", String::as_str);
            return format!("[mcp] {entry}");
        }
        match tool {
            "read_file" | "list_files" | "search_code" => "workspace read".to_owned(),
            "write_file" | "edit_file" => "workspace write".to_owned(),
            "git_status" | "git_diff" => "read-only git".to_owned(),
            "run_command" => {
                let argv = argv_of(args);
                if self.exact.contains(&argv) {
                    return format!("exact command `{}`", argv.join(" "));
                }
                if let Some(p) = self
                    .checks
                    .iter()
                    .find(|p| argv.len() >= p.len() && argv[..p.len()] == p[..])
                {
                    return format!("check prefix `{}`", p.join(" "));
                }
                match self.prefix.iter().find(|p| prefix_matches(p, &argv)) {
                    Some(p) => format!("allowed prefix `{}`", p.join(" ")),
                    None => "command policy".to_owned(),
                }
            }
            _ => "tool policy".to_owned(),
        }
    }

    /// The decision by rule alone, before any person's: what decides
    /// whether a call's object is resolved and a person asked.
    #[must_use]
    pub fn base(&self, tool: &str, args: &Value) -> Decision {
        self.base_of(tool, args)
    }

    fn base_of(&self, tool: &str, args: &Value) -> Decision {
        if let Some(e) = self.exploring {
            return self.explore_of(e, tool, args);
        }
        if tool.starts_with(MCP_PREFIX) {
            return match self.mcp.get(tool).map(String::as_str) {
                Some("allow") => Decision::Allow,
                Some("deny") => Decision::Deny(format!("`{tool}` is denied in [mcp]")),
                Some(_) => Decision::Approval(format!(
                    "`{tool}` is an MCP tool; speccoder cannot know what it does"
                )),
                None => Decision::Deny(format!("unknown tool `{tool}`")),
            };
        }
        match tool {
            "read_file" | "list_files" | "search_code" => self.read(args),
            "write_file" | "edit_file" => self.write(args),
            "run_command" => self.with_network_rule(args, self.command(args)),
            "git_status" | "git_diff" => Decision::Allow,
            // Ask's readers (offered only on the Ask plane): history,
            // accounts, evidence, codes — reading through runtime functions.
            "git_log" | "git_show" | "journal_account" | "task_evidence" | "report" | "inbox"
            | "explain" => Decision::Allow,
            other => Decision::Deny(format!("unknown tool `{other}`")),
        }
    }

    /// An exploring run's decision: never an approval.
    fn explore_of(&self, e: Exploring, tool: &str, args: &Value) -> Decision {
        match tool {
            "read_file" | "list_files" | "search_code" => self.read(args),
            "git_status" | "git_diff" => Decision::Allow,
            "write_file" | "edit_file" => {
                let rel = args["path"]
                    .as_str()
                    .and_then(|p| super::paths::normalise(p).ok());
                // The format's declared exploration artifacts are its
                // own to write — never a credential or the person's review.
                match rel {
                    Some(rel)
                        if (e.paths)(&rel)
                            && !self.protected.is_secret(&rel)
                            && !self.protected.is_review(&rel) =>
                    {
                        Decision::Allow
                    }
                    _ => Decision::Deny(EXPLORING_WRITE.to_owned()),
                }
            }
            "run_command" => {
                let argv = argv_of(args);
                if args.get("network").and_then(Value::as_bool) == Some(true) {
                    return Decision::Deny("exploring has no network".to_owned());
                }
                if e.commands.iter().any(|p| {
                    argv.len() >= p.len() && argv.iter().zip(p.iter()).all(|(a, b)| a == b)
                }) {
                    Decision::Allow
                } else {
                    Decision::Deny(format!(
                        "exploring runs only the format's read-only commands; `{}` is not one",
                        argv.join(" ")
                    ))
                }
            }
            other => Decision::Deny(format!("`{other}` is not used while exploring")),
        }
    }

    /// A command that asks for the network (`"network": true`) needs a
    /// person, unless its prefix is in `[sandbox] network_allow`.
    fn with_network_rule(&self, args: &Value, decision: Decision) -> Decision {
        if args.get("network").and_then(Value::as_bool) != Some(true)
            || matches!(decision, Decision::Deny(_))
        {
            return decision;
        }
        let argv = argv_of(args);
        if self.network_allowed(&argv) {
            return decision;
        }
        Decision::Approval(format!(
            "`{}` asks for the network; commands run without it",
            argv.join(" ")
        ))
    }

    fn read(&self, args: &Value) -> Decision {
        let Some(path) = super::below_root(args.get("path").and_then(Value::as_str)) else {
            return Decision::Allow; // list/search over the whole workspace
        };
        match normalise(path) {
            Err(e) => Decision::Deny(e.0),
            Ok(p) if self.protected.is_secret(&p) => {
                Decision::Deny(format!("`{p}` looks like a credential"))
            }
            Ok(p) if self.is_hidden(&p) => Decision::Deny(format!(
                "`{p}` is ignored by git in this checkout; an in-place run works only with what a worktree would hold"
            )),
            Ok(_) => Decision::Allow,
        }
    }

    fn write(&self, args: &Value) -> Decision {
        let Some(path) = args.get("path").and_then(Value::as_str) else {
            return Decision::Deny("no `path`".to_owned());
        };
        let p = match normalise(path) {
            Ok(p) => p,
            Err(e) => return Decision::Deny(e.0),
        };
        if (self.authoring
            && (self.protected.rules().authoring_path)(&p)
            && !self.protected.is_secret(&p)
            && !self.protected.is_review(&p))
            || self.is_planning_write(&p)
        {
            return Decision::Allow;
        }
        if self.is_hidden(&p) {
            return Decision::Deny(format!(
                "`{p}` is ignored by git in this checkout; an in-place run does not write it"
            ));
        }
        if self.protected.is_review(&p) {
            return Decision::Deny(format!(
                "`{p}` is protected: it records a person's review of the spec; only the person writes it (`speccoder review`)"
            ));
        }
        if let Some(class) = self.protected.write_class(&p) {
            return Decision::Deny(format!(
                "`{p}` is protected: {}",
                self.protected.reason(class)
            ));
        }
        if self.authoring {
            return Decision::Approval((self.protected.rules().authoring_refusal)(&p));
        }
        if self.protected.is_context(&p) {
            return Decision::Approval(format!(
                "`{p}` is an agent context file: every later agent session reads it"
            ));
        }
        if self
            .frozen
            .iter()
            .any(|f| f.to_lowercase() == p.to_lowercase())
        {
            return Decision::Approval(format!(
                "`{p}` is a frozen test (it existed when the attempt started)"
            ));
        }
        if self.protected.is_manifest(&p) {
            return Decision::Approval(format!("`{p}` is a dependency manifest"));
        }
        Decision::Allow
    }

    fn command(&self, args: &Value) -> Decision {
        let argv = argv_of(args);
        match (self.protected.rules().command)(&argv, self.authoring) {
            Some(Ok(())) => return Decision::Allow,
            Some(Err(why)) => return Decision::Deny(why),
            None => {}
        }
        let Some(program) = argv.first() else {
            return Decision::Deny("empty `argv`".to_owned());
        };
        let name = program.rsplit('/').next().unwrap_or(program);
        let has = |flag: &str| argv.iter().any(|a| a == flag);

        if PRIVILEGE.contains(&name) {
            return Decision::Deny(format!("`{name}` raises privileges"));
        }
        if name == "git" {
            let sub = argv.get(1).map_or("", String::as_str);
            if GIT_REMOTE.contains(&sub) {
                return Decision::Deny(format!(
                    "`git {sub}` talks to a remote; speccoder never does"
                ));
            }
            // Attestations are git notes only speccoder writes.
            let notes_action = argv[2..]
                .iter()
                .find(|a| !a.starts_with('-'))
                .map_or("list", String::as_str);
            if (sub == "notes" && !matches!(notes_action, "show" | "list"))
                || (sub == "update-ref" && argv.iter().any(|a| a.starts_with("refs/notes")))
            {
                return Decision::Deny(
                    "git notes are speccoder's attestations; only speccoder writes them".to_owned(),
                );
            }
            // Read-only queries (skills and models ask where they are).
            let listing_branches = sub == "branch"
                && argv[2..].iter().all(|a| {
                    matches!(
                        a.as_str(),
                        "--show-current" | "--list" | "-l" | "-a" | "--all" | "-v" | "-vv"
                    )
                });
            if matches!(
                sub,
                "rev-parse" | "status" | "log" | "diff" | "show" | "ls-files" | "describe"
            ) || listing_branches
            {
                return Decision::Allow;
            }
            if self.in_place
                && !listing_branches
                && (GIT_IN_PLACE.contains(&sub)
                    || (sub == "apply" && has("--index"))
                    || (sub == "restore" && has("--staged")))
            {
                return Decision::Deny(format!(
                    "`git {sub}` would move the checkout of an in-place run; speccoder commits and switches it"
                ));
            }
            if sub == "clean" || (sub == "reset" && has("--hard")) || sub == "filter-branch" {
                return Decision::Deny(format!("`git {sub}` destroys work"));
            }
            if matches!(
                sub,
                "commit"
                    | "checkout"
                    | "switch"
                    | "rebase"
                    | "merge"
                    | "stash"
                    | "branch"
                    | "tag"
                    | "config"
                    | "worktree"
            ) {
                return Decision::Approval(format!("`git {sub}` changes repository state"));
            }
        }
        if SHELLS.contains(&name) || name == "eval" || name == "env" || name == "xargs" {
            return Decision::Approval(format!("`{name}` runs arbitrary commands"));
        }
        if NETWORK.contains(&name) {
            return Decision::Approval(format!("`{name}` uses the network"));
        }
        if name == "rm" && argv.iter().any(|a| a.starts_with('-') && a.contains('r')) {
            return Decision::Approval("recursive `rm`".to_owned());
        }
        // `cargo --version`, `rustc -V`, `python3 --version`: harmless probes.
        if argv.len() == 2 && matches!(argv[1].as_str(), "--version" | "-V" | "version") {
            return Decision::Allow;
        }
        // `[commands] allow` is exact; a check allows its prefix; a
        // prefix entry (two elements or more) what extends it.
        if self.exact.contains(&argv)
            || self
                .checks
                .iter()
                .any(|prefix| argv.len() >= prefix.len() && argv[..prefix.len()] == prefix[..])
            || self.prefix.iter().any(|p| prefix_matches(p, &argv))
        {
            return Decision::Allow;
        }
        Decision::Approval(NOT_ALLOWED.to_owned())
    }
}

/// The argv a `run_command` call asks for (strings only).
#[must_use]
pub fn argv_of(args: &Value) -> Vec<String> {
    args.get("argv")
        .and_then(Value::as_array)
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(str::to_owned))
                .collect()
        })
        .unwrap_or_default()
}

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

    fn policy() -> Policy {
        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
        Policy::new(
            &[
                argv("cargo nextest run --workspace --profile speccoder"),
                argv("cargo clippy --workspace -- -D warnings"),
            ],
            &[],
        )
        .with_prefixes(vec![argv("cargo fmt"), argv("cargo check")])
    }

    #[test]
    fn an_unasked_call_is_named_with_how_to_let_it_run() {
        let decide = "run with prompts";
        let refused = policy().classify("run_command", &json!({"argv": ["npm", "i"]}), None);
        let Decision::Approval(reason) = refused else {
            panic!("{refused:?}")
        };
        let m = unasked(
            &json!({"tool": "run_command", "arguments": {"argv": ["make", "it's"]}, "reason": reason}),
            decide,
        );
        assert_eq!(
            m,
            "`make 'it'\\''s'` needs approval: it is not a configured check or allowed command — allow exactly it in speccoder.toml (`[commands] allow = [[\"make\", \"it's\"]]`), or run with prompts"
        );
        // No allow entry lets a shell run: only a person can.
        let m = unasked(
            &json!({"tool": "run_command", "arguments": {"argv": ["sh", "-c", "x"]}, "reason": "`sh` runs arbitrary commands"}),
            decide,
        );
        assert_eq!(
            m,
            "`sh -c x` needs approval: `sh` runs arbitrary commands — run with prompts"
        );
        let m = unasked(
            &json!({"tool": "write_file", "arguments": {"path": "Cargo.toml"}, "reason": "`Cargo.toml` is a dependency manifest"}),
            decide,
        );
        assert_eq!(
            m,
            "`write_file` `Cargo.toml` needs approval: `Cargo.toml` is a dependency manifest — run with prompts"
        );
    }

    fn path(canonical: &str, asked: &str) -> Object {
        Object::Path {
            canonical: canonical.to_owned(),
            asked: asked.to_owned(),
        }
    }

    fn command(s: &str) -> Object {
        Object::command(
            s.split(' ').map(str::to_owned).collect(),
            ".".to_owned(),
            "/usr/bin/x".to_owned(),
            false,
        )
    }

    fn cmd(s: &str) -> Value {
        json!({ "argv": s.split(' ').collect::<Vec<_>>() })
    }

    #[test]
    fn classifies_the_table() {
        use Decision::{Allow, Approval, Deny};
        let p = policy();
        let kind = |d: Decision| match d {
            Allow => "allow",
            Approval(_) => "approval",
            Deny(_) => "deny",
        };
        let cases: &[(&str, Value, &str)] = &[
            ("read_file", json!({"path": "src/lib.rs"}), "allow"),
            ("read_file", json!({"path": ".env"}), "deny"),
            ("read_file", json!({"path": "../secret"}), "deny"),
            ("list_files", json!({}), "allow"),
            ("search_code", json!({"pattern": "fn main"}), "allow"),
            ("write_file", json!({"path": "src/new.rs"}), "allow"),
            ("edit_file", json!({"path": "specs/001-x/tasks.md"}), "deny"),
            ("write_file", json!({"path": "speccoder.toml"}), "deny"),
            (
                "write_file",
                json!({"path": ".github/workflows/ci.yml"}),
                "deny",
            ),
            (
                "write_file",
                json!({"path": ".git/hooks/pre-commit"}),
                "deny",
            ),
            ("edit_file", json!({"path": "Cargo.toml"}), "approval"),
            ("edit_file", json!({"path": "web/package.json"}), "approval"),
            ("run_command", cmd("cargo nextest run -p x"), "allow"),
            ("run_command", cmd("cargo clippy --all-targets"), "allow"),
            ("run_command", cmd("cargo fmt --all"), "allow"),
            ("run_command", cmd("cargo build"), "approval"),
            ("run_command", cmd("cargo --version"), "allow"),
            ("run_command", cmd("rustc -V"), "allow"),
            ("run_command", cmd("sudo --version"), "deny"),
            ("run_command", cmd("npm install left-pad"), "approval"),
            ("run_command", cmd("git push origin main"), "deny"),
            ("run_command", cmd("git fetch"), "deny"),
            ("run_command", cmd("git reset --hard HEAD"), "deny"),
            ("run_command", cmd("git clean -fdx"), "deny"),
            ("run_command", cmd("git commit -m x"), "approval"),
            (
                "run_command",
                cmd("git rev-parse --is-inside-work-tree"),
                "allow",
            ),
            ("run_command", cmd("git branch --show-current"), "allow"),
            ("run_command", cmd("git branch feature-x"), "approval"),
            ("run_command", cmd("git log --oneline -3"), "allow"),
            ("run_command", cmd("sh -c ls"), "approval"),
            ("run_command", cmd("sudo cargo test"), "deny"),
            ("run_command", cmd("curl https://example.com"), "approval"),
            ("run_command", cmd("rm -rf target"), "approval"),
            ("run_command", json!({"argv": []}), "deny"),
            ("git_status", json!({}), "allow"),
            ("git_diff", json!({}), "allow"),
            ("delete_everything", json!({}), "deny"),
        ];
        for (tool, args, want) in cases {
            assert_eq!(kind(p.classify(tool, args, None)), *want, "{tool} {args}");
        }
    }

    #[test]
    fn decisions_cover_classes_and_never_override_a_denial() {
        let approved = vec![
            path("Cargo.toml", "Cargo.toml"),
            command("cargo build"),
            path("speccoder.toml", "speccoder.toml"),
            // Approved and rejected alike: the rejection wins.
            command("curl https://x"),
        ];
        let rejected = vec![Rejection {
            object: command("curl https://x"),
            reason: "no network".to_owned(),
        }];
        let p = policy().with_decisions(approved, rejected);
        // Any content for an approved file, whatever spelling reaches it.
        assert_eq!(
            p.classify(
                "edit_file",
                &json!({"path": "./Cargo.toml", "old_string": "a"}),
                Some(&path("Cargo.toml", "./Cargo.toml"))
            ),
            Decision::Allow
        );
        // The object, not the request: no object, no grant.
        assert!(matches!(
            p.classify("edit_file", &json!({"path": "Cargo.toml"}), None),
            Decision::Approval(_)
        ));
        assert_eq!(
            p.classify(
                "run_command",
                &cmd("cargo build"),
                Some(&command("cargo build"))
            ),
            Decision::Allow
        );
        assert!(matches!(
            p.classify(
                "run_command",
                &cmd("cargo build --release"),
                Some(&command("cargo build --release"))
            ),
            Decision::Approval(_)
        ));
        // A rejection is a denial with the person's reason, approved or not.
        assert_eq!(
            p.classify(
                "run_command",
                &cmd("curl https://x"),
                Some(&command("curl https://x"))
            ),
            Decision::Deny("a person rejected this: no network".to_owned())
        );
        // A protected path stays denied whatever was approved.
        assert!(matches!(
            p.classify("write_file", &json!({"path": "speccoder.toml"}), None),
            Decision::Deny(_)
        ));
        // Attestations are speccoder's: the model reads notes, never writes them.
        let p = Policy::new(&[], &[]);
        for argv in [
            vec![
                "git",
                "notes",
                "--ref=speccoder",
                "add",
                "-f",
                "-m",
                "x",
                "HEAD",
            ],
            vec!["git", "notes", "remove", "HEAD"],
            vec!["git", "update-ref", "refs/notes/speccoder", "HEAD"],
        ] {
            assert!(
                matches!(
                    p.classify("run_command", &json!({ "argv": argv }), None),
                    Decision::Deny(_)
                ),
                "{argv:?}"
            );
        }
        for argv in [
            vec!["git", "notes", "--ref=speccoder", "show", "HEAD"],
            vec!["git", "notes", "list"],
        ] {
            assert!(
                !matches!(
                    p.classify("run_command", &json!({ "argv": argv }), None),
                    Decision::Deny(_)
                ),
                "{argv:?}"
            );
        }
        // In place, what moves the checkout is denied; queries still run.
        let in_place = Policy::new(&[], &[]).in_place();
        for argv in [
            vec!["git", "switch", "main"],
            vec!["git", "commit", "-m", "x"],
            vec!["git", "reset", "HEAD~1"],
            vec!["git", "stash"],
            vec!["git", "branch", "x"],
            vec!["git", "apply", "--index", "p.diff"],
            vec!["git", "restore", "--staged", "a"],
            vec!["git", "update-ref", "HEAD", "x"],
        ] {
            assert!(
                matches!(
                    in_place.classify("run_command", &json!({ "argv": argv }), None),
                    Decision::Deny(_)
                ),
                "{argv:?}"
            );
        }
        for argv in [
            vec!["git", "status"],
            vec!["git", "branch", "--show-current"],
        ] {
            assert_eq!(
                in_place.classify("run_command", &json!({ "argv": argv }), None),
                Decision::Allow,
                "{argv:?}"
            );
        }
        // Ignored files are out of sight; the protected intent is not.
        let hidden = Policy::new(&[], &[]).in_place().with_hidden([
            "target/".to_owned(),
            "notes.txt".to_owned(),
            "specs/".to_owned(),
        ]);
        for (tool, path) in [
            ("read_file", "target/debug/x"),
            ("read_file", "notes.txt"),
            ("list_files", "target"),
            ("write_file", "notes.txt"),
        ] {
            assert!(
                matches!(
                    hidden.classify(tool, &json!({ "path": path }), None),
                    Decision::Deny(_)
                ),
                "{tool} {path}"
            );
        }
        assert_eq!(
            hidden.classify("read_file", &json!({ "path": "specs/001-x/spec.md" }), None),
            Decision::Allow
        );
        assert_eq!(
            hidden.classify("read_file", &json!({ "path": "src/lib.rs" }), None),
            Decision::Allow
        );
        assert!(matches!(
            Policy::new(&[], &[]).classify(
                "run_command",
                &json!({ "argv": ["git", "switch", "main"] }),
                None
            ),
            Decision::Approval(_)
        ));
    }

    #[test]
    fn a_check_through_a_runner_allows_only_itself() {
        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
        let check = "uv run --locked --offline python -m pytest -q --junitxml=.speccoder/junit.xml";
        let p = Policy::new(&[argv(check), argv("poetry run pytest -q")], &[]);
        assert_eq!(
            p.classify("run_command", &cmd(check), None),
            Decision::Allow
        );
        for other in [
            "uv run python -c print(1)",
            "uv run --locked --offline sh",
            "poetry run sh",
        ] {
            assert!(
                matches!(
                    p.classify("run_command", &cmd(other), None),
                    Decision::Approval(_)
                ),
                "{other}"
            );
        }
    }

    #[test]
    fn a_check_whose_prefix_is_its_bare_program_allows_only_itself() {
        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
        let p = Policy::new(
            &[argv("python3 -m pytest -q --junitxml=.speccoder/junit.xml")],
            &[],
        );
        assert_eq!(
            p.classify(
                "run_command",
                &cmd("python3 -m pytest -q --junitxml=.speccoder/junit.xml"),
                None
            ),
            Decision::Allow
        );
        assert!(matches!(
            p.classify("run_command", &cmd("python3 -c print(1)"), None),
            Decision::Approval(_)
        ));
        assert!(matches!(
            p.classify("run_command", &cmd("python3 -m pytest tests/x.py"), None),
            Decision::Approval(_)
        ));
        // `[commands] allow` is exact: the entry allows itself only.
        let q = Policy::new(&[], &[argv("python3 -m pytest")]);
        assert!(matches!(
            q.classify("run_command", &cmd("python3 -m pytest tests/x.py"), None),
            Decision::Approval(_)
        ));
        assert_eq!(
            q.classify("run_command", &cmd("python3 -m pytest"), None),
            Decision::Allow
        );
    }

    #[test]
    fn mcp_tools_follow_their_configured_decision_and_unknown_ones_are_denied() {
        let p = Policy::new(&[], &[]).with_mcp([
            ("mcp__db__query".to_owned(), "allow".to_owned()),
            ("mcp__db__drop".to_owned(), "deny".to_owned()),
            ("mcp__db__insert".to_owned(), "approval".to_owned()),
        ]);
        assert_eq!(
            p.classify("mcp__db__query", &json!({}), None),
            Decision::Allow
        );
        assert!(matches!(
            p.classify("mcp__db__drop", &json!({}), None),
            Decision::Deny(_)
        ));
        assert!(matches!(
            p.classify("mcp__db__insert", &json!({}), None),
            Decision::Approval(_)
        ));
        assert!(matches!(
            p.classify("mcp__db__other", &json!({}), None),
            Decision::Deny(_)
        ));
        // An approval covers the tool as defined then; it never lifts a denial.
        let tool = |name: &str, digest: &str| Object::Tool {
            name: name.to_owned(),
            digest: digest.to_owned(),
        };
        let q = p.clone().with_decisions(
            vec![tool("mcp__db__insert", "d1"), tool("mcp__db__drop", "d1")],
            Vec::new(),
        );
        assert_eq!(
            q.classify(
                "mcp__db__insert",
                &json!({ "row": 1 }),
                Some(&tool("mcp__db__insert", "d1"))
            ),
            Decision::Allow
        );
        // Its server changed the definition: asked again.
        assert!(matches!(
            q.classify(
                "mcp__db__insert",
                &json!({ "row": 1 }),
                Some(&tool("mcp__db__insert", "d2"))
            ),
            Decision::Approval(_)
        ));
        assert!(matches!(
            q.classify(
                "mcp__db__drop",
                &json!({}),
                Some(&tool("mcp__db__drop", "d1"))
            ),
            Decision::Deny(_)
        ));
        assert_eq!(
            tool("mcp__db__insert", "9f8e7d6c5b4a3210").short(),
            "mcp__db__insert@9f8e7d6c5b4a"
        );
        assert!(
            tool("mcp__db__insert", "d2")
                .changed_from(&tool("mcp__db__insert", "d1"))
                .is_some_and(|c| c.contains("definition changed"))
        );
    }

    #[test]
    fn a_planning_task_writes_design_docs_in_its_unit_never_a_judged_file() {
        let p = Policy::new(&[], &[]).planning("specs/001-x/");
        let w = |path: &str| p.classify("write_file", &json!({ "path": path }), None);
        assert_eq!(w("specs/001-x/contracts/cli.md"), Decision::Allow);
        assert_eq!(w("specs/001-x/data-model.md"), Decision::Allow);
        assert_eq!(w("specs/001-x/plan.md"), Decision::Allow);
        assert_eq!(p.write_protected("specs/001-x/contracts/cli.md"), None);
        // The judged files, the person's review, the constitution, another
        // unit: as the normal policy says (protected).
        for judged in [
            "specs/001-x/spec.md",
            "specs/001-x/tasks.md",
            "specs/001-x/review.json",
            "specs/001-x/checklists/ux.md",
            "specs/001-x/contracts/../spec.md",
            ".specify/memory/constitution.md",
            "specs/002-y/contracts/cli.md",
            "specs/001-x/.env",
            // Inside the unit, but no design document: git, judge inputs,
            // agent configuration and context, manifests, hidden files.
            "specs/001-x/.git/config",
            "specs/001-x/speccoder.toml",
            "specs/001-x/vitest.config.ts",
            "specs/001-x/.mcp.json",
            "specs/001-x/.claude/settings.json",
            "specs/001-x/AGENTS.md",
            "specs/001-x/CLAUDE.md",
            "specs/001-x/package.json",
            "specs/001-x/Cargo.toml",
            "specs/001-x/.hidden.md",
        ] {
            assert!(matches!(w(judged), Decision::Deny(_)), "{judged}");
            assert!(!p.is_planning_write(judged), "{judged}");
        }
        assert!(p.write_protected("specs/001-x/spec.md").is_some());
        // Outside the unit: the normal policy.
        assert_eq!(w("src/lib.rs"), Decision::Allow);
        assert!(matches!(w("Cargo.toml"), Decision::Approval(_)));
        // Without the profile, the spec tree is protected as ever.
        let normal = Policy::new(&[], &[]);
        assert!(matches!(
            normal.classify(
                "write_file",
                &json!({ "path": "specs/001-x/contracts/cli.md" }),
                None
            ),
            Decision::Deny(_)
        ));
        // OpenSpec: a change's proposal, tasks and spec deltas are judged.
        let o = Policy::new(&[], &[])
            .rules(crate::format::Adapter::rules(
                &crate::format::openspec::OPENSPEC,
            ))
            .planning("openspec/changes/add-x");
        assert!(o.is_planning_write("openspec/changes/add-x/design.md"));
        for judged in ["proposal.md", "tasks.md", "specs/auth/spec.md"] {
            assert!(
                !o.is_planning_write(&format!("openspec/changes/add-x/{judged}")),
                "{judged}"
            );
        }
    }

    #[test]
    fn the_authoring_profile_writes_spec_kit_artifacts_and_runs_its_scripts_only() {
        let p = Policy::new(&[], &[]).authoring();
        let w = |path: &str| p.classify("write_file", &json!({ "path": path }), None);
        assert_eq!(w("specs/002-login/spec.md"), Decision::Allow);
        assert_eq!(w(".specify/feature.json"), Decision::Allow);
        assert_eq!(w(".specify/memory/constitution.md"), Decision::Allow);
        assert!(matches!(
            w(".specify/scripts/bash/common.sh"),
            Decision::Deny(_)
        ));
        assert!(matches!(
            w(".specify/templates/spec-template.md"),
            Decision::Deny(_)
        ));
        assert!(matches!(w("speccoder.toml"), Decision::Deny(_)));
        assert!(matches!(w("specs/.env"), Decision::Deny(_)));
        // A planning skill writes the spec, never the person's review of it.
        assert!(
            matches!(w("specs/002-login/review.json"), Decision::Deny(ref why) if why.contains("review")),
            "{:?}",
            w("specs/002-login/review.json")
        );
        assert!(p.write_protected("specs/002-login/review.json").is_some());
        assert!(matches!(w("src/lib.rs"), Decision::Approval(_)));
        let run = |argv: &[&str]| p.classify("run_command", &json!({ "argv": argv }), None);
        assert_eq!(
            run(&[".specify/scripts/bash/setup-plan.sh", "--json"]),
            Decision::Allow
        );
        assert_eq!(
            run(&[
                "bash",
                "./.specify/scripts/bash/check-prerequisites.sh",
                "--json"
            ]),
            Decision::Allow
        );
        assert!(matches!(
            run(&["bash", ".specify/scripts/bash/../../evil.sh"]),
            Decision::Approval(_)
        ));
        assert_eq!(
            run(&[
                "bash",
                ".specify/extensions/git/scripts/bash/create-new-feature-branch.sh",
                "--json"
            ]),
            Decision::Allow
        );
        assert!(matches!(
            run(&["bash", ".specify/extensions/git/other.sh"]),
            Decision::Approval(_)
        ));
        assert!(matches!(
            run(&["bash", "-c", "rm -rf /"]),
            Decision::Approval(_)
        ));
        // Outside the profile, the spec stays protected.
        assert!(matches!(
            Policy::new(&[], &[]).classify(
                "write_file",
                &json!({ "path": "specs/002-login/spec.md" }),
                None
            ),
            Decision::Deny(_)
        ));
    }

    #[test]
    fn asking_for_the_network_needs_a_person_unless_allowed() {
        let checks = [vec!["cargo".to_owned(), "test".to_owned()]];
        let p = Policy::new(&checks, &[]);
        let net = json!({ "argv": ["cargo", "test"], "network": true });
        assert!(matches!(
            p.classify("run_command", &net, None),
            Decision::Approval(_)
        ));
        // Without the network the same command is allowed; a denial stays one.
        assert_eq!(
            p.classify("run_command", &json!({ "argv": ["cargo", "test"] }), None),
            Decision::Allow
        );
        assert!(matches!(
            p.classify(
                "run_command",
                &json!({ "argv": ["git", "push"], "network": true }),
                None
            ),
            Decision::Deny(_)
        ));
        // `[sandbox] network_allow` is exact; a prefix entry extends.
        let exact = p
            .clone()
            .with_network(vec![vec!["cargo".to_owned(), "test".to_owned()]]);
        assert_eq!(exact.classify("run_command", &net, None), Decision::Allow);
        let longer = json!({ "argv": ["cargo", "test", "--release"], "network": true });
        assert!(matches!(
            exact.classify("run_command", &longer, None),
            Decision::Approval(_)
        ));
        let bare = p.clone().with_network(vec![vec!["cargo".to_owned()]]);
        assert!(matches!(
            bare.classify("run_command", &net, None),
            Decision::Approval(_)
        ));
        let prefixed = p.clone().with_network_prefixes(vec![
            vec!["cargo".to_owned()],
            vec!["cargo".to_owned(), "test".to_owned()],
        ]);
        assert_eq!(
            prefixed.classify("run_command", &longer, None),
            Decision::Allow
        );
        let object = Object::command(
            vec!["cargo".to_owned(), "test".to_owned()],
            ".".to_owned(),
            "/usr/bin/cargo".to_owned(),
            true,
        );
        let approved = Policy::new(&checks, &[]).with_decisions(vec![object.clone()], vec![]);
        assert_eq!(
            approved.classify("run_command", &net, Some(&object)),
            Decision::Allow
        );
        // The same argv resolving to another executable is another object.
        let shadowed = Object::command(
            vec!["cargo".to_owned(), "test".to_owned()],
            ".".to_owned(),
            "/w/bin/cargo".to_owned(),
            true,
        );
        assert!(matches!(
            approved.classify("run_command", &net, Some(&shadowed)),
            Decision::Approval(_)
        ));
        assert!(
            shadowed
                .changed_from(&object)
                .is_some_and(|c| c == "executable /usr/bin/cargo → /w/bin/cargo")
        );
    }

    #[test]
    fn commands_allow_is_exact_and_prefixes_need_two_elements() {
        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
        let p = Policy::new(&[], &[argv("npm run build")]);
        assert_eq!(
            p.classify("run_command", &cmd("npm run build"), None),
            Decision::Allow
        );
        for longer in [
            "npm run build --script-shell=/tmp/x",
            "npm run build x",
            "npm run",
        ] {
            assert!(
                matches!(
                    p.classify("run_command", &cmd(longer), None),
                    Decision::Approval(_)
                ),
                "{longer}"
            );
        }
        assert_eq!(
            p.rule("run_command", &cmd("npm run build"), None),
            "exact command `npm run build`"
        );
        let q = Policy::new(&[], &[]).with_prefixes(vec![argv("npm"), argv("npm run")]);
        assert_eq!(
            q.classify("run_command", &cmd("npm run build"), None),
            Decision::Allow
        );
        assert_eq!(
            q.rule("run_command", &cmd("npm run build"), None),
            "allowed prefix `npm run`"
        );
        // The one-element entry was dropped: a bare program allows anything.
        assert!(matches!(
            q.classify("run_command", &cmd("npm install x"), None),
            Decision::Approval(_)
        ));
        assert!(
            prefix_refusal(&argv("npm")).is_some() && prefix_refusal(&argv("npm run")).is_none()
        );
        // Fixed rules decide before every list.
        let r = Policy::new(&[], &[argv("sh -c ls")]).with_prefixes(vec![argv("git push")]);
        assert!(matches!(
            r.classify("run_command", &cmd("sh -c ls"), None),
            Decision::Approval(_)
        ));
        assert!(matches!(
            r.classify("run_command", &cmd("git push origin"), None),
            Decision::Deny(_)
        ));
    }

    #[test]
    fn autopilot_never_asks_never_lifts_a_denial_and_names_its_rule() {
        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
        let p = Policy::new(&[], &[argv("cargo test")]).autopilot();
        assert!(p.is_autopilot());
        // Allowed stays allowed; asking becomes refusing; denied stays denied.
        assert_eq!(
            p.settle(p.classify("run_command", &cmd("cargo test"), None)),
            Decision::Allow
        );
        assert_eq!(
            p.settle(p.classify("run_command", &cmd("cargo add x"), None)),
            Decision::Deny(AUTOPILOT_DENIED.to_owned())
        );
        assert_eq!(
            p.rule("run_command", &cmd("cargo add x"), None),
            "autopilot"
        );
        assert!(matches!(
            p.settle(p.classify("run_command", &cmd("git push origin"), None)),
            Decision::Deny(r) if r != AUTOPILOT_DENIED
        ));
        // Without autopilot nothing changes.
        let q = Policy::new(&[], &[]);
        assert!(matches!(
            q.settle(q.classify("run_command", &cmd("cargo add x"), None)),
            Decision::Approval(_)
        ));
        // A grant id names exactly one object.
        let a = command("make check");
        let mut b = a.clone();
        if let Object::Command { cwd, .. } = &mut b {
            *cwd = "sub".to_owned();
        }
        assert_ne!(a.grant_id(), b.grant_id());
        assert_eq!(a.grant_id(), a.clone().grant_id());
        assert_eq!(
            path("src/b/x.rs", "src/a/x.rs").grant_id(),
            path("src/b/x.rs", "src/b/x.rs").grant_id()
        );
        assert!(a.grant_id().starts_with("g-") && a.grant_id().len() == 18);
    }

    proptest::proptest! {
        #[test]
        fn on_autopilot_no_call_waits_for_a_person(words in proptest::collection::vec("[a-z]{1,6}", 1..4), tool in 0usize..4) {
            let p = Policy::new(&[], &[]).autopilot();
            let argv: Vec<String> = words.clone();
            let (name, args) = match tool {
                0 => ("run_command", json!({ "argv": argv })),
                1 => ("write_file", json!({ "path": format!("src/{}.rs", words[0]), "content": "" })),
                2 => ("write_file", json!({ "path": format!(".github/{}.yml", words[0]), "content": "" })),
                _ => ("mcp__x__y", json!({})),
            };
            let before = Policy::new(&[], &[]).classify(name, &args, None);
            let after = p.settle(p.classify(name, &args, None));
            proptest::prop_assert!(!matches!(after, Decision::Approval(_)));
            if matches!(before, Decision::Deny(_)) {
                proptest::prop_assert!(matches!(after, Decision::Deny(_)));
            }
            if before == Decision::Allow {
                proptest::prop_assert_eq!(after, Decision::Allow);
            }
        }
    }

    const OPENSPEC_READS: &[&[&str]] = &[&["openspec", "list"], &["openspec", "show"]];

    fn exploring() -> Policy {
        Policy::new(&[vec!["cargo".to_owned(), "test".to_owned()]], &[]).exploring(Exploring {
            paths: |rel| rel.starts_with(".specify/assessments/"),
            commands: OPENSPEC_READS,
        })
    }

    proptest::proptest! {
        /// Exploring never asks a person (SC-002): every write outside the
        /// exploration paths and every unlisted command is denied — even a
        /// configured check, even with the network.
        #[test]
        fn exploring_denies_what_it_does_not_allow_and_never_asks(words in proptest::collection::vec("[a-z]{1,6}", 1..4), tool in 0usize..6) {
            let p = exploring();
            let (name, args) = match tool {
                0 => ("run_command", json!({ "argv": words })),
                1 => ("run_command", json!({ "argv": ["cargo", "test"] })),
                2 => ("write_file", json!({ "path": format!("src/{}.rs", words[0]), "content": "" })),
                3 => ("edit_file", json!({ "path": format!("specs/{}/spec.md", words[0]), "old_string": "a", "new_string": "b" })),
                4 => ("run_command", json!({ "argv": ["openspec", "list", words[0].clone()], "network": true })),
                _ => ("mcp__x__y", json!({})),
            };
            let d = p.classify(name, &args, None);
            proptest::prop_assert!(matches!(d, Decision::Deny(_)), "{name} {args} → {d:?}");
        }
    }

    #[test]
    fn exploring_reads_and_runs_the_formats_read_only_commands() {
        let p = exploring();
        assert_eq!(
            p.classify("read_file", &json!({ "path": "src/lib.rs" }), None),
            Decision::Allow
        );
        assert_eq!(
            p.classify(
                "run_command",
                &json!({ "argv": ["openspec", "list", "--json"] }),
                None
            ),
            Decision::Allow
        );
        assert_eq!(
            p.classify(
                "write_file",
                &json!({ "path": ".specify/assessments/csv/notes.md", "content": "" }),
                None
            ),
            Decision::Allow
        );
        let Decision::Deny(why) = p.classify(
            "write_file",
            &json!({ "path": "notes.md", "content": "" }),
            None,
        ) else {
            panic!("a write outside the exploration paths is denied");
        };
        assert_eq!(why, EXPLORING_WRITE);
    }

    #[test]
    fn a_path_object_is_its_canonical_file_whatever_the_spelling() {
        assert_eq!(
            path("src/b/x.rs", "src/a/x.rs"),
            path("src/b/x.rs", "src/b/x.rs")
        );
        assert_ne!(
            path("src/b/x.rs", "src/a/x.rs"),
            path("src/a/x.rs", "src/a/x.rs")
        );
        assert!(
            path("src/b/x.rs", "src/a/x.rs")
                .changed_from(&path("src/a/x.rs", "src/a/x.rs"))
                .is_some_and(|c| c == "resolves to src/b/x.rs, was src/a/x.rs")
        );
        // Commands differ by every field.
        let a = command("make check");
        let mut b = a.clone();
        if let Object::Command { cwd, .. } = &mut b {
            *cwd = "sub".to_owned();
        }
        assert_ne!(a, b);
        assert_eq!(a.class(), Class::Command);
        assert!(a.short().starts_with("argv#") && a.short().len() == 17);
        // The record round-trips; an older grant shape does not read.
        let back: Object = serde_json::from_value(serde_json::to_value(&a).unwrap()).unwrap();
        assert_eq!(back, a);
        assert!(serde_json::from_value::<Object>(json!({ "kind": "write", "path": "x" })).is_err());
        assert!(
            serde_json::from_value::<Rejection>(json!({ "grant": { "kind": "path", "canonical": "x", "asked": "x" }, "reason": "r" }))
                .is_err()
        );
    }

    #[test]
    fn the_grant_path_has_no_pattern() {
        // Matching a person's decision is object equality only.
        let source = include_str!("policy.rs");
        let classify = source
            .split("pub fn classify(")
            .nth(1)
            .and_then(|s| s.split("\n    }\n").next())
            .unwrap_or_default();
        assert!(!classify.is_empty());
        for pattern in ["starts_with", "glob", "prefix"] {
            assert!(!classify.contains(pattern), "{pattern} in the grant path");
        }
    }
}