Skip to main content

speccoder_runtime/tools/
policy.rs

1//! The policy classifier: every tool call is
2//! allowed, needs approval, or is denied — decided by code, before the call.
3//!
4//! It decides *which* calls run; what an allowed command can reach is the
5//! OS sandbox's job (`crate::sandbox`).
6
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10use super::paths::{Protected, normalise};
11
12/// The prefix of an MCP tool's name as the model sees it (`crate::mcp`).
13pub const MCP_PREFIX: &str = "mcp__";
14
15/// What the engine does with a call.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum Decision {
18    /// Run it.
19    Allow,
20    /// Ask a person first.
21    Approval(String),
22    /// Never run it.
23    Deny(String),
24}
25
26/// The kind of object a decision covers.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "snake_case")]
29pub enum Class {
30    /// A write or edit of one file.
31    Write,
32    /// One exact command.
33    Command,
34    /// One exact command with the network.
35    Network,
36    /// One MCP tool as defined now.
37    Mcp,
38    /// One action an external agent takes itself.
39    Agent,
40}
41
42impl Class {
43    /// Its name.
44    #[must_use]
45    pub const fn as_str(self) -> &'static str {
46        match self {
47            Self::Write => "write",
48            Self::Command => "command",
49            Self::Network => "network",
50            Self::Mcp => "mcp",
51            Self::Agent => "agent",
52        }
53    }
54}
55
56/// What a person's decision covers: exactly one resolved object — never
57/// the request's spelling and never a pattern (constitution V). A path is
58/// the canonical file a write reaches; a command is its exact argv with
59/// the directory it runs in and the executable it resolves to; an MCP tool
60/// is its name with the digest of its definition.
61#[derive(Debug, Clone, Serialize, Deserialize)]
62#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
63pub enum Object {
64    /// `write_file` / `edit_file` of this file.
65    Path {
66        /// Workspace-relative, every existing ancestor's symlinks resolved.
67        canonical: String,
68        /// The path as the model sent it (normalised).
69        asked: String,
70    },
71    /// `run_command` with exactly this argv.
72    Command {
73        /// The argv.
74        argv: Vec<String>,
75        /// Hex SHA-256 over the argv as a JSON array.
76        argv_sha256: String,
77        /// The working directory, workspace-relative (`.` for the root).
78        cwd: String,
79        /// The executable's absolute canonical path, or `not found`.
80        executable: String,
81        /// Whether the call has the network.
82        network: bool,
83    },
84    /// This MCP tool, as its server defines it now.
85    Tool {
86        /// `mcp__<server>__<tool>`.
87        name: String,
88        /// agentplane's digest over the tool's definition.
89        digest: String,
90    },
91    /// An external agent's own action, in its own process: exactly these
92    /// commands and paths — never covered by a grant of speccoder's own
93    /// calls, nor covering one.
94    Agent {
95        /// The agent (its preset id).
96        agent: String,
97        /// `execute`, `edit`, `read`, … as the agent declared it.
98        call: String,
99        /// The commands it runs, exactly.
100        argvs: Vec<Vec<String>>,
101        /// The worktree paths it names, canonical.
102        paths: Vec<String>,
103        /// A digest of what else it carries, when that decides (a call
104        /// speccoder cannot read); empty otherwise.
105        input: String,
106    },
107}
108
109/// What an executable that cannot be found is recorded as.
110pub const NOT_FOUND: &str = "not found";
111
112/// Why a command no rule allows needs a person.
113pub const NOT_ALLOWED: &str = "not a configured check or allowed command";
114
115/// A call that stopped for a person nobody could ask then, in a person's
116/// words: the call (a command's argv as typed), why, and how to let it run
117/// — for a command no rule allows, its exact `[commands] allow` entry;
118/// `decide` says how else (e.g. ``approve it: `speccoder task approve T001` ``).
119#[must_use]
120pub fn unasked(pending: &Value, decide: &str) -> String {
121    let tool = pending["tool"].as_str().unwrap_or_default();
122    let reason = pending["reason"].as_str().unwrap_or_default();
123    let arguments = &pending["arguments"];
124    if tool == "run_command" {
125        let argv = argv_of(arguments);
126        let shown = crate::approvals::present::shell_quote(&argv);
127        if reason == NOT_ALLOWED {
128            let entry = argv
129                .iter()
130                .map(|a| serde_json::to_string(a).unwrap_or_default())
131                .collect::<Vec<_>>()
132                .join(", ");
133            return format!(
134                "`{shown}` needs approval: it is {NOT_ALLOWED} — allow exactly it in speccoder.toml (`[commands] allow = [[{entry}]]`), or {decide}"
135            );
136        }
137        return format!("`{shown}` needs approval: {reason} — {decide}");
138    }
139    // An external agent's own action: what it is, in words.
140    if let Ok(o @ Object::Agent { .. }) =
141        serde_json::from_value::<Object>(pending["object"].clone())
142    {
143        return format!("{} needs approval: {reason} — {decide}", o.describe());
144    }
145    let object = arguments["path"]
146        .as_str()
147        .map(|p| format!(" `{p}`"))
148        .unwrap_or_default();
149    format!("`{tool}`{object} needs approval: {reason} — {decide}")
150}
151
152impl PartialEq for Object {
153    /// A path is the file it reaches (any spelling); a command and a tool
154    /// are every field.
155    fn eq(&self, other: &Self) -> bool {
156        match (self, other) {
157            (Self::Path { canonical: a, .. }, Self::Path { canonical: b, .. }) => a == b,
158            (
159                Self::Command {
160                    argv: a1,
161                    argv_sha256: a2,
162                    cwd: a3,
163                    executable: a4,
164                    network: a5,
165                },
166                Self::Command {
167                    argv: b1,
168                    argv_sha256: b2,
169                    cwd: b3,
170                    executable: b4,
171                    network: b5,
172                },
173            ) => a1 == b1 && a2 == b2 && a3 == b3 && a4 == b4 && a5 == b5,
174            (Self::Tool { name: a, digest: x }, Self::Tool { name: b, digest: y }) => {
175                a == b && x == y
176            }
177            (
178                Self::Agent {
179                    agent: a1,
180                    call: a2,
181                    argvs: a3,
182                    paths: a4,
183                    input: a5,
184                },
185                Self::Agent {
186                    agent: b1,
187                    call: b2,
188                    argvs: b3,
189                    paths: b4,
190                    input: b5,
191                },
192            ) => a1 == b1 && a2 == b2 && a3 == b3 && a4 == b4 && a5 == b5,
193            _ => false,
194        }
195    }
196}
197
198impl Eq for Object {}
199
200/// Hex SHA-256 over `argv` as a JSON array.
201#[must_use]
202pub fn argv_sha256(argv: &[String]) -> String {
203    use sha2::{Digest as _, Sha256};
204    let json = serde_json::to_string(argv).unwrap_or_default();
205    Sha256::digest(json.as_bytes())
206        .iter()
207        .map(|b| format!("{b:02x}"))
208        .collect()
209}
210
211fn first12(hex: &str) -> &str {
212    hex.get(..12).unwrap_or(hex)
213}
214
215impl Object {
216    /// A command object; the argv's hash is computed.
217    #[must_use]
218    pub fn command(argv: Vec<String>, cwd: String, executable: String, network: bool) -> Self {
219        Self::Command {
220            argv_sha256: argv_sha256(&argv),
221            argv,
222            cwd,
223            executable,
224            network,
225        }
226    }
227
228    /// Its class.
229    #[must_use]
230    pub const fn class(&self) -> Class {
231        match self {
232            Self::Path { .. } => Class::Write,
233            Self::Command { network: true, .. } => Class::Network,
234            Self::Command { .. } => Class::Command,
235            Self::Tool { .. } => Class::Mcp,
236            Self::Agent { .. } => Class::Agent,
237        }
238    }
239
240    /// One line for people.
241    #[must_use]
242    pub fn describe(&self) -> String {
243        match self {
244            Self::Path { canonical, .. } => format!("write `{canonical}`"),
245            Self::Command {
246                argv, cwd, network, ..
247            } => {
248                let place = if cwd == "." {
249                    String::new()
250                } else {
251                    format!(" in `{cwd}`")
252                };
253                let net = if *network { " with the network" } else { "" };
254                format!("run `{}`{place}{net}", argv.join(" "))
255            }
256            Self::Tool { name, digest } => format!("use `{name}`@{}", first12(digest)),
257            Self::Agent {
258                agent,
259                call: kind,
260                argvs,
261                paths,
262                ..
263            } => {
264                if kind == "reads" {
265                    return format!("{agent}'s plain reads of one file each, for the task");
266                }
267                let what: Vec<String> = argvs
268                    .iter()
269                    .map(|a| format!("`{}`", a.join(" ")))
270                    .chain(paths.iter().map(|p| format!("`{p}`")))
271                    .collect();
272                format!("{agent} itself: {kind} {}", what.join(", "))
273            }
274        }
275    }
276
277    /// Its grant id: `g-<16 hex>` over what the object is — the
278    /// canonical path, every field of a command, a tool's name and digest —
279    /// so one id names one object and nothing else.
280    #[must_use]
281    pub fn grant_id(&self) -> String {
282        use sha2::{Digest as _, Sha256};
283        let identity = match self {
284            Self::Path { canonical, .. } => serde_json::json!({ "path": canonical }),
285            Self::Command {
286                argv,
287                argv_sha256,
288                cwd,
289                executable,
290                network,
291            } => serde_json::json!({
292                "argv": argv, "argv_sha256": argv_sha256, "cwd": cwd,
293                "executable": executable, "network": network,
294            }),
295            Self::Tool { name, digest } => serde_json::json!({ "tool": name, "digest": digest }),
296            Self::Agent {
297                agent,
298                call,
299                argvs,
300                paths,
301                input,
302            } => {
303                serde_json::json!({ "agent": agent, "call": call, "argvs": argvs, "paths": paths, "input": input })
304            }
305        };
306        let hex: String = Sha256::digest(identity.to_string().as_bytes())
307            .iter()
308            .take(8)
309            .map(|b| format!("{b:02x}"))
310            .collect();
311        format!("g-{hex}")
312    }
313
314    /// The short form events and lists carry: the path, `argv#<12 hex>`,
315    /// `<tool>@<12 hex>` — never more of the argv than the target shows.
316    #[must_use]
317    pub fn short(&self) -> String {
318        match self {
319            Self::Path { canonical, .. } => canonical.clone(),
320            Self::Command { argv_sha256, .. } => format!("argv#{}", first12(argv_sha256)),
321            Self::Tool { name, digest } => format!("{name}@{}", first12(digest)),
322            Self::Agent { agent, call, .. } => {
323                format!("{agent}:{call}#{}", first12(&self.grant_id()))
324            }
325        }
326    }
327
328    /// Whether `other` names the same thing as this one by the request's
329    /// spelling (the path as asked, the argv, the tool's name) — the case
330    /// in which a different object is worth telling the person about.
331    #[must_use]
332    pub fn same_name(&self, other: &Self) -> bool {
333        match (self, other) {
334            (Self::Path { asked: a, .. }, Self::Path { asked: b, .. }) => a == b,
335            (
336                Self::Command {
337                    argv: a,
338                    network: x,
339                    ..
340                },
341                Self::Command {
342                    argv: b,
343                    network: y,
344                    ..
345                },
346            ) => a == b && x == y,
347            (Self::Tool { name: a, .. }, Self::Tool { name: b, .. }) => a == b,
348            _ => false,
349        }
350    }
351
352    /// What differs from `earlier`, an object of the same name a person
353    /// approved: `executable /usr/bin/make → /w/bin/make`.
354    #[must_use]
355    pub fn changed_from(&self, earlier: &Self) -> Option<String> {
356        if self == earlier || !self.same_name(earlier) {
357            return None;
358        }
359        let mut what = Vec::new();
360        match (earlier, self) {
361            (Self::Path { canonical: a, .. }, Self::Path { canonical: b, .. }) => {
362                what.push(format!("resolves to {b}, was {a}"));
363            }
364            (
365                Self::Command {
366                    cwd: c1,
367                    executable: e1,
368                    ..
369                },
370                Self::Command {
371                    cwd: c2,
372                    executable: e2,
373                    ..
374                },
375            ) => {
376                if e1 != e2 {
377                    what.push(format!("executable {e1} → {e2}"));
378                }
379                if c1 != c2 {
380                    what.push(format!("directory {c1} → {c2}"));
381                }
382            }
383            (Self::Tool { digest: a, .. }, Self::Tool { digest: b, .. }) => {
384                what.push(format!(
385                    "definition @{} → @{} (the tool's definition changed since it was approved)",
386                    first12(a),
387                    first12(b)
388                ));
389            }
390            _ => {}
391        }
392        (!what.is_empty()).then(|| what.join("; "))
393    }
394
395    /// The MCP tool's name, for a tool object.
396    #[must_use]
397    pub fn tool_name(&self) -> Option<&str> {
398        match self {
399            Self::Tool { name, .. } => Some(name),
400            _ => None,
401        }
402    }
403
404    /// The canonical path, for a path object.
405    #[must_use]
406    pub fn path(&self) -> Option<&str> {
407        match self {
408            Self::Path { canonical, .. } => Some(canonical),
409            _ => None,
410        }
411    }
412}
413
414/// A person's "no", with the reason the model is told.
415#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
416#[serde(deny_unknown_fields)]
417pub struct Rejection {
418    /// What was rejected.
419    pub object: Object,
420    /// Why.
421    pub reason: String,
422}
423
424/// The classifier for one project.
425#[derive(Debug, Clone, Default)]
426pub struct Policy {
427    /// Check-derived prefixes: each configured check's program and
428    /// subcommands up to its first option (committed configuration).
429    checks: Vec<Vec<String>>,
430    /// `[commands] allow`: exact argvs.
431    exact: std::collections::BTreeSet<Vec<String>>,
432    /// `[commands] allow_prefix`: prefixes of at least two elements.
433    prefix: Vec<Vec<String>>,
434    protected: Protected,
435    frozen: std::collections::BTreeSet<String>,
436    approved: Vec<Object>,
437    rejected: Vec<Rejection>,
438    /// MCP tools by model-facing name: `allow`, `approval` or `deny`.
439    mcp: std::collections::BTreeMap<String, String>,
440    /// The planning profile for hosted planning skills.
441    authoring: bool,
442    /// A planning task's unit directory (worktree-relative): its design
443    /// documents are the task's work, its judged files are not.
444    planning: Option<String>,
445    /// `[sandbox] network_allow`: exact argvs that get the network.
446    network_exact: std::collections::BTreeSet<Vec<String>>,
447    /// `[sandbox] network_allow_prefix`: prefixes that get it.
448    network_prefix: Vec<Vec<String>>,
449    /// An in-place attempt: git commands that move the person's checkout
450    /// are denied.
451    in_place: bool,
452    /// In place: what git ignored at the run's start (directories end in
453    /// `/`), invisible to the file tools unless protected.
454    hidden: Vec<String>,
455    /// An autopilot run: a call that would ask a person, and that
456    /// no grant covers, is refused for the run instead.
457    autopilot: bool,
458    /// The enforced sandbox's mechanism when contained calls run without
459    /// asking (`[approvals] contained`, network off or loopback).
460    contained: Option<String>,
461    /// Exploring: the paths it may write (the format's own exploration
462    /// artifacts) and the read-only commands it may run. Nothing asks.
463    exploring: Option<Exploring>,
464}
465
466/// What an exploring run may do beyond reading.
467#[derive(Debug, Clone, Copy)]
468pub struct Exploring {
469    /// Paths (workspace-relative) the format's exploration skill writes.
470    pub paths: fn(&str) -> bool,
471    /// Argv prefixes of its read-only commands.
472    pub commands: &'static [&'static [&'static str]],
473}
474
475/// Why an exploring run's write was refused.
476pub const EXPLORING_WRITE: &str = "exploring writes nothing — the brief is made when the person chooses, and *Start spec* writes the spec";
477
478/// Why an autopilot run refused a call that would have asked a person.
479pub const AUTOPILOT_DENIED: &str = "autopilot: not asked — listed for you";
480
481/// Whether `argv` starts with `prefix`, a prefix of at least two elements
482/// (a bare program allows any argument, so it is never a prefix).
483#[must_use]
484pub fn prefix_matches(prefix: &[String], argv: &[String]) -> bool {
485    prefix.len() >= 2 && argv.starts_with(prefix)
486}
487
488/// Whether `argv` is `check` given tests to run: its elements in order,
489/// with positional arguments — never an option — after its last positional
490/// one, among its trailing options (`pytest -q tests/x.py --junitxml=…`).
491fn narrows(check: &[String], argv: &[String]) -> bool {
492    let head = check
493        .iter()
494        .rposition(|a| !a.starts_with('-'))
495        .map_or(0, |i| i + 1);
496    if argv.len() <= check.len() || !argv.starts_with(&check[..head]) {
497        return false;
498    }
499    let mut rest = check[head..].iter().peekable();
500    for a in &argv[head..] {
501        if rest.peek() == Some(&a) {
502            rest.next();
503        } else if a.starts_with('-') {
504            return false;
505        }
506    }
507    rest.peek().is_none()
508}
509
510/// Why a prefix entry is refused, if it is: a bare program allows any
511/// argument.
512#[must_use]
513pub fn prefix_refusal(prefix: &[String]) -> Option<&'static str> {
514    (prefix.len() < 2).then_some(
515        "a bare program allows any argument; add the exact command to [commands] allow instead",
516    )
517}
518
519const SHELLS: &[&str] = &[
520    "sh", "bash", "zsh", "fish", "dash", "ksh", "csh", "tcsh", "pwsh",
521];
522const PRIVILEGE: &[&str] = &["sudo", "su", "doas", "pkexec"];
523const NETWORK: &[&str] = &[
524    "curl", "wget", "nc", "ncat", "ssh", "scp", "sftp", "rsync", "ftp", "telnet",
525];
526const GIT_REMOTE: &[&str] = &[
527    "push",
528    "fetch",
529    "pull",
530    "clone",
531    "remote",
532    "ls-remote",
533    "submodule",
534];
535/// What would move the checkout of an in-place run under speccoder.
536const GIT_IN_PLACE: &[&str] = &[
537    "checkout",
538    "switch",
539    "reset",
540    "commit",
541    "merge",
542    "rebase",
543    "cherry-pick",
544    "revert",
545    "stash",
546    "branch",
547    "tag",
548    "update-ref",
549    "worktree",
550    "am",
551];
552
553/// Prefixes that run whatever program follows them.
554const RUNNERS: &[&[&str]] = &[
555    &["uv", "run"],
556    &["uv", "tool", "run"],
557    &["uvx"],
558    &["poetry", "run"],
559    &["pipx", "run"],
560    &["pdm", "run"],
561    &["hatch", "run"],
562];
563
564impl Policy {
565    /// A policy allowing the command prefixes of `checks` (program and
566    /// subcommands, up to the first option) and exactly the argvs of
567    /// `exact` (`[commands] allow`).
568    #[must_use]
569    pub fn new(checks: &[Vec<String>], exact: &[Vec<String>]) -> Self {
570        let mut allowed: Vec<Vec<String>> = checks
571            .iter()
572            .map(|argv| {
573                let prefix: Vec<String> = argv
574                    .iter()
575                    .take_while(|a| !a.starts_with('-'))
576                    .cloned()
577                    .collect();
578                // `python3 -m pytest …` would leave the bare interpreter as
579                // the prefix — and allow `python3 -c <anything>`; `uv run`
580                // would allow any program. A check whose prefix is only its
581                // program, or a runner of another program, allows exactly
582                // itself.
583                if (prefix.len() == 1
584                    || RUNNERS.iter().any(|r| {
585                        prefix
586                            .iter()
587                            .map(String::as_str)
588                            .take(r.len())
589                            .eq(r.iter().copied())
590                    }))
591                    && argv.len() > prefix.len()
592                {
593                    argv.clone()
594                } else {
595                    prefix
596                }
597            })
598            .filter(|p: &Vec<String>| !p.is_empty())
599            .collect();
600        allowed.sort();
601        allowed.dedup();
602        Self {
603            checks: allowed,
604            exact: exact.iter().filter(|p| !p.is_empty()).cloned().collect(),
605            ..Self::default()
606        }
607    }
608
609    /// `[commands] allow_prefix`: prefixes of two elements or more (a
610    /// shorter one is dropped; the configuration refuses it).
611    #[must_use]
612    pub fn with_prefixes(mut self, prefixes: Vec<Vec<String>>) -> Self {
613        self.prefix = prefixes.into_iter().filter(|p| p.len() >= 2).collect();
614        self
615    }
616
617    /// The check-derived prefixes, for a coverage view.
618    #[must_use]
619    pub fn check_prefixes(&self) -> &[Vec<String>] {
620        &self.checks
621    }
622
623    /// Paths git ignored when an in-place run started: the file tools
624    /// refuse them, except the protected files (the intent stays readable).
625    #[must_use]
626    pub fn with_hidden(mut self, hidden: impl IntoIterator<Item = String>) -> Self {
627        self.hidden = hidden.into_iter().collect();
628        self
629    }
630
631    /// Whether `rel` is ignored by git in an in-place checkout and not one
632    /// of the files speccoder protects.
633    fn is_hidden(&self, rel: &str) -> bool {
634        self.protected.write_class(rel).is_none()
635            && !self.protected.is_context(rel)
636            && self.hidden.iter().any(|h| match h.strip_suffix('/') {
637                Some(dir) => rel == dir || rel.starts_with(h.as_str()),
638                None => rel == h,
639            })
640    }
641
642    /// An in-place attempt (`run --in-place`): the checkout is the
643    /// person's, so git commands that move it are denied.
644    #[must_use]
645    pub fn in_place(mut self) -> Self {
646        self.in_place = true;
647        self
648    }
649
650    /// An autopilot run: nothing asks ([`Policy::settle`]).
651    #[must_use]
652    pub const fn autopilot(mut self) -> Self {
653        self.autopilot = true;
654        self
655    }
656
657    /// Commands the enforced sandbox (`mechanism`) confines run without
658    /// asking ([`Policy::contains`]).
659    #[must_use]
660    pub fn contained(mut self, mechanism: &str) -> Self {
661        self.contained = Some(mechanism.to_owned());
662        self
663    }
664
665    /// Whether `tool` with `args`, which the policy would ask about, runs
666    /// without asking because the enforced sandbox confines it: a command
667    /// asked about only for what it runs — not a check or allowed command,
668    /// a shell, a recursive `rm` — never for the network, the repository's
669    /// state or a path; never in planning or exploring.
670    #[must_use]
671    pub fn contains(&self, tool: &str, args: &Value) -> bool {
672        if self.contained.is_none()
673            || tool != "run_command"
674            || self.authoring
675            || self.planning.is_some()
676            || self.exploring.is_some()
677            || args["network"] == true
678            || self.network_allowed(&argv_of(args))
679        {
680            return false;
681        }
682        matches!(self.base(tool, args), Decision::Approval(r)
683            if r == NOT_ALLOWED || r.ends_with("runs arbitrary commands") || r == "recursive `rm`")
684    }
685
686    /// Whether it is an autopilot run's.
687    #[must_use]
688    pub const fn is_autopilot(&self) -> bool {
689        self.autopilot
690    }
691
692    /// What a decision comes to once every grant had its say: on
693    /// autopilot a call that would still ask a person is refused for the
694    /// run ([`AUTOPILOT_DENIED`]); every other decision stands — a denial,
695    /// a rejection or a protected path is never lifted.
696    #[must_use]
697    pub fn settle(&self, decision: Decision) -> Decision {
698        match decision {
699            Decision::Approval(_) if self.autopilot => Decision::Deny(AUTOPILOT_DENIED.to_owned()),
700            d => d,
701        }
702    }
703
704    /// The explore profile: reading is allowed; a write only inside the
705    /// format's exploration paths (and only where the rules allow it), a
706    /// command only from its read-only list, never with the network —
707    /// and nothing goes to a person: what is not allowed is denied.
708    #[must_use]
709    pub const fn exploring(mut self, e: Exploring) -> Self {
710        self.exploring = Some(e);
711        self
712    }
713
714    /// The planning profile: the format's artifacts and scripts are the
715    /// work; its machinery, verification inputs and secrets stay denied;
716    /// anything else — source code included — needs approval.
717    #[must_use]
718    pub fn authoring(mut self) -> Self {
719        self.authoring = true;
720        self
721    }
722
723    /// A planning task's profile: writes inside the unit's directory
724    /// `dir` (worktree-relative) are its work, except the format's judged
725    /// files ([`crate::format::Rules::judged`]), a credential and the
726    /// person's review; everything else is as the policy says.
727    #[must_use]
728    pub fn planning(mut self, dir: &str) -> Self {
729        let dir = dir.trim_matches('/');
730        self.planning = (!dir.is_empty()).then(|| dir.to_owned());
731        self
732    }
733
734    /// Whether `rel` (resolved, worktree-relative) is a planning task's
735    /// to write: a design document inside its unit's directory
736    /// ([`Protected::is_design_doc`]), not judged by the format.
737    #[must_use]
738    pub fn is_planning_write(&self, rel: &str) -> bool {
739        let Some(dir) = &self.planning else {
740            return false;
741        };
742        rel.strip_prefix(dir.as_str())
743            .and_then(|r| r.strip_prefix('/'))
744            .is_some_and(|r| {
745                !r.is_empty()
746                    && !r.split('/').any(|s| s == ".." || s == ".")
747                    && !(self.protected.rules().judged)(r.trim_end_matches('/'))
748                    && self.protected.is_design_doc(rel)
749                    && !self.protected.is_review(rel)
750            })
751    }
752
753    /// The project's format's rules (intent, planning artifacts); the
754    /// reference format's by default.
755    #[must_use]
756    pub fn rules(mut self, rules: &'static crate::format::Rules) -> Self {
757        self.protected = Protected::new(rules);
758        self
759    }
760
761    /// `[sandbox] network_allow`: exact argvs that get the network.
762    #[must_use]
763    pub fn with_network(mut self, exact: Vec<Vec<String>>) -> Self {
764        self.network_exact = exact.into_iter().filter(|p| !p.is_empty()).collect();
765        self
766    }
767
768    /// `[sandbox] network_allow_prefix`: prefixes (two elements or more)
769    /// that get the network.
770    #[must_use]
771    pub fn with_network_prefixes(mut self, prefixes: Vec<Vec<String>>) -> Self {
772        self.network_prefix = prefixes.into_iter().filter(|p| p.len() >= 2).collect();
773        self
774    }
775
776    /// Whether `argv` gets the network without asking: an exact entry, or a
777    /// prefix entry it extends.
778    #[must_use]
779    pub fn network_allowed(&self, argv: &[String]) -> bool {
780        self.network_exact.contains(argv)
781            || self.network_prefix.iter().any(|p| prefix_matches(p, argv))
782    }
783
784    /// The project's MCP tools and their configured decisions.
785    #[must_use]
786    pub fn with_mcp(mut self, tools: impl IntoIterator<Item = (String, String)>) -> Self {
787        self.mcp = tools.into_iter().collect();
788        self
789    }
790
791    /// A person's decisions for this task: an approval turns a call that
792    /// needs approval into an allowed one (never a denied one); a rejection
793    /// turns it into a denial with the person's reason.
794    #[must_use]
795    pub fn with_decisions(mut self, approved: Vec<Object>, rejected: Vec<Rejection>) -> Self {
796        self.approved = approved;
797        self.rejected = rejected;
798        self
799    }
800
801    /// Freezes these test files: writing them needs approval.
802    #[must_use]
803    pub fn with_frozen(mut self, frozen: impl IntoIterator<Item = String>) -> Self {
804        self.frozen = frozen.into_iter().collect();
805        self
806    }
807
808    /// The protected set this policy uses.
809    #[must_use]
810    pub fn protected(&self) -> &Protected {
811        &self.protected
812    }
813
814    /// Whether this (resolved, workspace-relative) path is protected for
815    /// writing under this policy: the authoring profile writes the format's
816    /// artifacts, nothing else of the protected set.
817    #[must_use]
818    pub fn write_protected(&self, rel: &str) -> Option<super::paths::Class> {
819        if self.is_planning_write(rel) {
820            return None;
821        }
822        if self.authoring
823            && (self.protected.rules().authoring_path)(rel)
824            && !self.protected.is_secret(rel)
825            && !self.protected.is_review(rel)
826        {
827            return None;
828        }
829        self.protected.write_class(rel)
830    }
831
832    /// Classifies `tool` called with `args`. A person's decision applies
833    /// only to the call's resolved `object` (none: the request alone was
834    /// seen, and nobody's decision covers it): a rejection of that very
835    /// object denies it, an approval of it allows it, never a denial.
836    #[must_use]
837    pub fn classify(&self, tool: &str, args: &Value, object: Option<&Object>) -> Decision {
838        let decision = self.base(tool, args);
839        if !matches!(decision, Decision::Approval(_)) {
840            return decision;
841        }
842        if let Some(object) = object {
843            if let Some(r) = self.rejected.iter().find(|r| r.object == *object) {
844                return Decision::Deny(format!("a person rejected this: {}", r.reason));
845            }
846            if self.approved.iter().any(|a| a == object) {
847                return Decision::Allow;
848            }
849        }
850        if self.contains(tool, args) {
851            Decision::Allow
852        } else {
853            decision
854        }
855    }
856
857    /// A person's rejection of exactly `object`, if one holds.
858    #[must_use]
859    pub fn rejection(&self, object: &Object) -> Option<&Rejection> {
860        self.rejected.iter().find(|r| r.object == *object)
861    }
862
863    /// The person's rejections and approvals, for the changed-object line.
864    #[must_use]
865    pub fn approved(&self) -> &[Object] {
866        &self.approved
867    }
868
869    /// The rule that decides `tool` with `args` when no person does: what a
870    /// call's record names, so a rule's decision is never read as a
871    /// person's.
872    #[must_use]
873    pub fn rule(&self, tool: &str, args: &Value, object: Option<&Object>) -> String {
874        if self.autopilot && matches!(self.classify(tool, args, object), Decision::Approval(_)) {
875            return "autopilot".to_owned();
876        }
877        if let Some(object) = object
878            && matches!(self.base(tool, args), Decision::Approval(_))
879        {
880            if self.rejected.iter().any(|r| r.object == *object) {
881                return format!("rejection of {} for the task", object.describe());
882            }
883            if self.approved.iter().any(|a| a == object) {
884                return format!("grant {} for the task", object.describe());
885            }
886        }
887        if tool.starts_with(MCP_PREFIX) {
888            let entry = self.mcp.get(tool).map_or("unlisted", String::as_str);
889            return format!("[mcp] {entry}");
890        }
891        match tool {
892            "read_file" | "list_files" | "search_code" => "workspace read".to_owned(),
893            "write_file" | "edit_file" => "workspace write".to_owned(),
894            "git_status" | "git_diff" => "read-only git".to_owned(),
895            "run_command" => {
896                let argv = argv_of(args);
897                if self.exact.contains(&argv) {
898                    return format!("exact command `{}`", argv.join(" "));
899                }
900                if let Some(p) = self
901                    .checks
902                    .iter()
903                    .find(|p| argv.len() >= p.len() && argv[..p.len()] == p[..])
904                {
905                    return format!("check prefix `{}`", p.join(" "));
906                }
907                match self.prefix.iter().find(|p| prefix_matches(p, &argv)) {
908                    Some(p) => format!("allowed prefix `{}`", p.join(" ")),
909                    None => match &self.contained {
910                        Some(m) if self.contains(tool, args) => format!("contained ({m})"),
911                        _ => "command policy".to_owned(),
912                    },
913                }
914            }
915            _ => "tool policy".to_owned(),
916        }
917    }
918
919    /// The decision by rule alone, before any person's: what decides
920    /// whether a call's object is resolved and a person asked.
921    #[must_use]
922    pub fn base(&self, tool: &str, args: &Value) -> Decision {
923        self.base_of(tool, args)
924    }
925
926    fn base_of(&self, tool: &str, args: &Value) -> Decision {
927        if let Some(e) = self.exploring {
928            return self.explore_of(e, tool, args);
929        }
930        if tool.starts_with(MCP_PREFIX) {
931            return match self.mcp.get(tool).map(String::as_str) {
932                Some("allow") => Decision::Allow,
933                Some("deny") => Decision::Deny(format!("`{tool}` is denied in [mcp]")),
934                Some(_) => Decision::Approval(format!(
935                    "`{tool}` is an MCP tool; speccoder cannot know what it does"
936                )),
937                None => Decision::Deny(format!("unknown tool `{tool}`")),
938            };
939        }
940        match tool {
941            "read_file" | "list_files" | "search_code" => self.read(args),
942            "write_file" | "edit_file" => self.write(args),
943            "run_command" => self.with_network_rule(args, self.command(args)),
944            "git_status" | "git_diff" => Decision::Allow,
945            // Ask's readers (offered only on the Ask plane): history,
946            // accounts, evidence, codes — reading through runtime functions.
947            "git_log" | "git_show" | "journal_account" | "task_evidence" | "report" | "inbox"
948            | "explain" => Decision::Allow,
949            other => Decision::Deny(format!("unknown tool `{other}`")),
950        }
951    }
952
953    /// An exploring run's decision: never an approval.
954    fn explore_of(&self, e: Exploring, tool: &str, args: &Value) -> Decision {
955        match tool {
956            "read_file" | "list_files" | "search_code" => self.read(args),
957            "git_status" | "git_diff" => Decision::Allow,
958            "write_file" | "edit_file" => {
959                let rel = args["path"]
960                    .as_str()
961                    .and_then(|p| super::paths::normalise(p).ok());
962                // The format's declared exploration artifacts are its
963                // own to write — never a credential or the person's review.
964                match rel {
965                    Some(rel)
966                        if (e.paths)(&rel)
967                            && !self.protected.is_secret(&rel)
968                            && !self.protected.is_review(&rel) =>
969                    {
970                        Decision::Allow
971                    }
972                    _ => Decision::Deny(EXPLORING_WRITE.to_owned()),
973                }
974            }
975            "run_command" => {
976                let argv = argv_of(args);
977                if args.get("network").and_then(Value::as_bool) == Some(true) {
978                    return Decision::Deny("exploring has no network".to_owned());
979                }
980                if e.commands.iter().any(|p| {
981                    argv.len() >= p.len() && argv.iter().zip(p.iter()).all(|(a, b)| a == b)
982                }) {
983                    Decision::Allow
984                } else {
985                    Decision::Deny(format!(
986                        "exploring runs only the format's read-only commands; `{}` is not one",
987                        argv.join(" ")
988                    ))
989                }
990            }
991            other => Decision::Deny(format!("`{other}` is not used while exploring")),
992        }
993    }
994
995    /// A command that asks for the network (`"network": true`) needs a
996    /// person, unless its prefix is in `[sandbox] network_allow`.
997    fn with_network_rule(&self, args: &Value, decision: Decision) -> Decision {
998        if args.get("network").and_then(Value::as_bool) != Some(true)
999            || matches!(decision, Decision::Deny(_))
1000        {
1001            return decision;
1002        }
1003        let argv = argv_of(args);
1004        if self.network_allowed(&argv) {
1005            return decision;
1006        }
1007        Decision::Approval(format!(
1008            "`{}` asks for the network; commands run without it",
1009            argv.join(" ")
1010        ))
1011    }
1012
1013    fn read(&self, args: &Value) -> Decision {
1014        let Some(path) = super::below_root(args.get("path").and_then(Value::as_str)) else {
1015            return Decision::Allow; // list/search over the whole workspace
1016        };
1017        match normalise(path) {
1018            Err(e) => Decision::Deny(e.0),
1019            Ok(p) if self.protected.is_secret(&p) => {
1020                Decision::Deny(format!("`{p}` looks like a credential"))
1021            }
1022            Ok(p) if self.is_hidden(&p) => Decision::Deny(format!(
1023                "`{p}` is ignored by git in this checkout; an in-place run works only with what a worktree would hold"
1024            )),
1025            Ok(_) => Decision::Allow,
1026        }
1027    }
1028
1029    fn write(&self, args: &Value) -> Decision {
1030        let Some(path) = args.get("path").and_then(Value::as_str) else {
1031            return Decision::Deny("no `path`".to_owned());
1032        };
1033        let p = match normalise(path) {
1034            Ok(p) => p,
1035            Err(e) => return Decision::Deny(e.0),
1036        };
1037        if (self.authoring
1038            && (self.protected.rules().authoring_path)(&p)
1039            && !self.protected.is_secret(&p)
1040            && !self.protected.is_review(&p))
1041            || self.is_planning_write(&p)
1042        {
1043            return Decision::Allow;
1044        }
1045        if self.is_hidden(&p) {
1046            return Decision::Deny(format!(
1047                "`{p}` is ignored by git in this checkout; an in-place run does not write it"
1048            ));
1049        }
1050        if self.protected.is_review(&p) {
1051            return Decision::Deny(format!(
1052                "`{p}` is protected: it records a person's review of the spec; only the person writes it (`speccoder review`)"
1053            ));
1054        }
1055        if let Some(class) = self.protected.write_class(&p) {
1056            return Decision::Deny(format!(
1057                "`{p}` is protected: {}",
1058                self.protected.reason(class)
1059            ));
1060        }
1061        if self.authoring {
1062            return Decision::Approval((self.protected.rules().authoring_refusal)(&p));
1063        }
1064        if self.protected.is_context(&p) {
1065            return Decision::Approval(format!(
1066                "`{p}` is an agent context file: every later agent session reads it"
1067            ));
1068        }
1069        if self
1070            .frozen
1071            .iter()
1072            .any(|f| f.to_lowercase() == p.to_lowercase())
1073        {
1074            return Decision::Approval(format!(
1075                "`{p}` is a frozen test (it existed when the attempt started)"
1076            ));
1077        }
1078        if self.protected.is_manifest(&p) {
1079            return Decision::Approval(format!("`{p}` is a dependency manifest"));
1080        }
1081        Decision::Allow
1082    }
1083
1084    fn command(&self, args: &Value) -> Decision {
1085        let argv = argv_of(args);
1086        match (self.protected.rules().command)(&argv, self.authoring) {
1087            Some(Ok(())) => return Decision::Allow,
1088            Some(Err(why)) => return Decision::Deny(why),
1089            None => {}
1090        }
1091        let Some(program) = argv.first() else {
1092            return Decision::Deny("empty `argv`".to_owned());
1093        };
1094        let name = program.rsplit('/').next().unwrap_or(program);
1095        let has = |flag: &str| argv.iter().any(|a| a == flag);
1096
1097        if PRIVILEGE.contains(&name) {
1098            return Decision::Deny(format!("`{name}` raises privileges"));
1099        }
1100        if name == "git" {
1101            let sub = argv.get(1).map_or("", String::as_str);
1102            if GIT_REMOTE.contains(&sub) {
1103                return Decision::Deny(format!(
1104                    "`git {sub}` talks to a remote; speccoder never does"
1105                ));
1106            }
1107            // Attestations are git notes only speccoder writes.
1108            let notes_action = argv[2..]
1109                .iter()
1110                .find(|a| !a.starts_with('-'))
1111                .map_or("list", String::as_str);
1112            if (sub == "notes" && !matches!(notes_action, "show" | "list"))
1113                || (sub == "update-ref" && argv.iter().any(|a| a.starts_with("refs/notes")))
1114            {
1115                return Decision::Deny(
1116                    "git notes are speccoder's attestations; only speccoder writes them".to_owned(),
1117                );
1118            }
1119            // Read-only queries (skills and models ask where they are).
1120            let listing_branches = sub == "branch"
1121                && argv[2..].iter().all(|a| {
1122                    matches!(
1123                        a.as_str(),
1124                        "--show-current" | "--list" | "-l" | "-a" | "--all" | "-v" | "-vv"
1125                    )
1126                });
1127            if matches!(
1128                sub,
1129                "rev-parse" | "status" | "log" | "diff" | "show" | "ls-files" | "describe"
1130            ) || listing_branches
1131            {
1132                return Decision::Allow;
1133            }
1134            if self.in_place
1135                && !listing_branches
1136                && (GIT_IN_PLACE.contains(&sub)
1137                    || (sub == "apply" && has("--index"))
1138                    || (sub == "restore" && has("--staged")))
1139            {
1140                return Decision::Deny(format!(
1141                    "`git {sub}` would move the checkout of an in-place run; speccoder commits and switches it"
1142                ));
1143            }
1144            if sub == "clean" || (sub == "reset" && has("--hard")) || sub == "filter-branch" {
1145                return Decision::Deny(format!("`git {sub}` destroys work"));
1146            }
1147            if matches!(
1148                sub,
1149                "commit"
1150                    | "checkout"
1151                    | "switch"
1152                    | "rebase"
1153                    | "merge"
1154                    | "stash"
1155                    | "branch"
1156                    | "tag"
1157                    | "config"
1158                    | "worktree"
1159            ) {
1160                return Decision::Approval(format!("`git {sub}` changes repository state"));
1161            }
1162        }
1163        if SHELLS.contains(&name) || name == "eval" || name == "env" || name == "xargs" {
1164            return Decision::Approval(format!("`{name}` runs arbitrary commands"));
1165        }
1166        if NETWORK.contains(&name) {
1167            return Decision::Approval(format!("`{name}` uses the network"));
1168        }
1169        if name == "rm" && argv.iter().any(|a| a.starts_with('-') && a.contains('r')) {
1170            return Decision::Approval("recursive `rm`".to_owned());
1171        }
1172        // `cargo --version`, `rustc -V`, `python3 --version`: harmless probes.
1173        if argv.len() == 2 && matches!(argv[1].as_str(), "--version" | "-V" | "version") {
1174            return Decision::Allow;
1175        }
1176        // `[commands] allow` is exact; a check allows its prefix, and
1177        // itself narrowed to tests; a prefix entry (two elements or more)
1178        // what extends it.
1179        if self.exact.contains(&argv)
1180            || self.checks.iter().any(|prefix| {
1181                (argv.len() >= prefix.len() && argv[..prefix.len()] == prefix[..])
1182                    || narrows(prefix, &argv)
1183            })
1184            || self.prefix.iter().any(|p| prefix_matches(p, &argv))
1185        {
1186            return Decision::Allow;
1187        }
1188        Decision::Approval(NOT_ALLOWED.to_owned())
1189    }
1190}
1191
1192/// The argv a `run_command` call asks for (strings only).
1193#[must_use]
1194pub fn argv_of(args: &Value) -> Vec<String> {
1195    args.get("argv")
1196        .and_then(Value::as_array)
1197        .map(|a| {
1198            a.iter()
1199                .filter_map(|v| v.as_str().map(str::to_owned))
1200                .collect()
1201        })
1202        .unwrap_or_default()
1203}
1204
1205#[cfg(test)]
1206mod tests {
1207    use super::*;
1208    use serde_json::json;
1209
1210    fn policy() -> Policy {
1211        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1212        Policy::new(
1213            &[
1214                argv("cargo nextest run --workspace --profile speccoder"),
1215                argv("cargo clippy --workspace -- -D warnings"),
1216            ],
1217            &[],
1218        )
1219        .with_prefixes(vec![argv("cargo fmt"), argv("cargo check")])
1220    }
1221
1222    #[test]
1223    fn an_unasked_call_is_named_with_how_to_let_it_run() {
1224        let decide = "run with prompts";
1225        let refused = policy().classify("run_command", &json!({"argv": ["npm", "i"]}), None);
1226        let Decision::Approval(reason) = refused else {
1227            panic!("{refused:?}")
1228        };
1229        let m = unasked(
1230            &json!({"tool": "run_command", "arguments": {"argv": ["make", "it's"]}, "reason": reason}),
1231            decide,
1232        );
1233        assert_eq!(
1234            m,
1235            "`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"
1236        );
1237        // No allow entry lets a shell run: only a person can.
1238        let m = unasked(
1239            &json!({"tool": "run_command", "arguments": {"argv": ["sh", "-c", "x"]}, "reason": "`sh` runs arbitrary commands"}),
1240            decide,
1241        );
1242        assert_eq!(
1243            m,
1244            "`sh -c x` needs approval: `sh` runs arbitrary commands — run with prompts"
1245        );
1246        let m = unasked(
1247            &json!({"tool": "write_file", "arguments": {"path": "Cargo.toml"}, "reason": "`Cargo.toml` is a dependency manifest"}),
1248            decide,
1249        );
1250        assert_eq!(
1251            m,
1252            "`write_file` `Cargo.toml` needs approval: `Cargo.toml` is a dependency manifest — run with prompts"
1253        );
1254    }
1255
1256    fn path(canonical: &str, asked: &str) -> Object {
1257        Object::Path {
1258            canonical: canonical.to_owned(),
1259            asked: asked.to_owned(),
1260        }
1261    }
1262
1263    fn command(s: &str) -> Object {
1264        Object::command(
1265            s.split(' ').map(str::to_owned).collect(),
1266            ".".to_owned(),
1267            "/usr/bin/x".to_owned(),
1268            false,
1269        )
1270    }
1271
1272    fn cmd(s: &str) -> Value {
1273        json!({ "argv": s.split(' ').collect::<Vec<_>>() })
1274    }
1275
1276    #[test]
1277    fn classifies_the_table() {
1278        use Decision::{Allow, Approval, Deny};
1279        let p = policy();
1280        let kind = |d: Decision| match d {
1281            Allow => "allow",
1282            Approval(_) => "approval",
1283            Deny(_) => "deny",
1284        };
1285        let cases: &[(&str, Value, &str)] = &[
1286            ("read_file", json!({"path": "src/lib.rs"}), "allow"),
1287            ("read_file", json!({"path": ".env"}), "deny"),
1288            ("read_file", json!({"path": "../secret"}), "deny"),
1289            ("list_files", json!({}), "allow"),
1290            ("search_code", json!({"pattern": "fn main"}), "allow"),
1291            ("write_file", json!({"path": "src/new.rs"}), "allow"),
1292            ("edit_file", json!({"path": "specs/001-x/tasks.md"}), "deny"),
1293            ("write_file", json!({"path": "speccoder.toml"}), "deny"),
1294            (
1295                "write_file",
1296                json!({"path": ".github/workflows/ci.yml"}),
1297                "deny",
1298            ),
1299            (
1300                "write_file",
1301                json!({"path": ".git/hooks/pre-commit"}),
1302                "deny",
1303            ),
1304            ("edit_file", json!({"path": "Cargo.toml"}), "approval"),
1305            ("edit_file", json!({"path": "web/package.json"}), "approval"),
1306            ("run_command", cmd("cargo nextest run -p x"), "allow"),
1307            ("run_command", cmd("cargo clippy --all-targets"), "allow"),
1308            ("run_command", cmd("cargo fmt --all"), "allow"),
1309            ("run_command", cmd("cargo build"), "approval"),
1310            ("run_command", cmd("cargo --version"), "allow"),
1311            ("run_command", cmd("rustc -V"), "allow"),
1312            ("run_command", cmd("sudo --version"), "deny"),
1313            ("run_command", cmd("npm install left-pad"), "approval"),
1314            ("run_command", cmd("git push origin main"), "deny"),
1315            ("run_command", cmd("git fetch"), "deny"),
1316            ("run_command", cmd("git reset --hard HEAD"), "deny"),
1317            ("run_command", cmd("git clean -fdx"), "deny"),
1318            ("run_command", cmd("git commit -m x"), "approval"),
1319            (
1320                "run_command",
1321                cmd("git rev-parse --is-inside-work-tree"),
1322                "allow",
1323            ),
1324            ("run_command", cmd("git branch --show-current"), "allow"),
1325            ("run_command", cmd("git branch feature-x"), "approval"),
1326            ("run_command", cmd("git log --oneline -3"), "allow"),
1327            ("run_command", cmd("sh -c ls"), "approval"),
1328            ("run_command", cmd("sudo cargo test"), "deny"),
1329            ("run_command", cmd("curl https://example.com"), "approval"),
1330            ("run_command", cmd("rm -rf target"), "approval"),
1331            ("run_command", json!({"argv": []}), "deny"),
1332            ("git_status", json!({}), "allow"),
1333            ("git_diff", json!({}), "allow"),
1334            ("delete_everything", json!({}), "deny"),
1335        ];
1336        for (tool, args, want) in cases {
1337            assert_eq!(kind(p.classify(tool, args, None)), *want, "{tool} {args}");
1338        }
1339    }
1340
1341    /// The md2csv example's T012 (2026-11-04): its probes asked five times
1342    /// inside the enforced sandbox. Contained, they run; what leaves the
1343    /// sandbox, or a person rejected, still decides.
1344    #[test]
1345    fn a_contained_command_runs_and_what_leaves_the_sandbox_does_not() {
1346        let p = policy().contained("Seatbelt");
1347        for c in [
1348            "python3 -c print(1)",
1349            "sh -c make",
1350            "rm -r build",
1351            "uv run python -m md2csv",
1352        ] {
1353            assert_eq!(
1354                p.classify("run_command", &cmd(c), None),
1355                Decision::Allow,
1356                "{c}"
1357            );
1358            assert_eq!(
1359                p.rule("run_command", &cmd(c), None),
1360                "contained (Seatbelt)",
1361                "{c}"
1362            );
1363        }
1364        for c in ["curl https://x", "git commit -m x", "ssh host"] {
1365            assert!(
1366                !matches!(p.classify("run_command", &cmd(c), None), Decision::Allow),
1367                "{c}"
1368            );
1369        }
1370        let net = json!({ "argv": ["python3", "-c", "x"], "network": true });
1371        assert!(matches!(
1372            p.classify("run_command", &net, None),
1373            Decision::Approval(_)
1374        ));
1375        let allowed = policy()
1376            .with_network(vec![vec![
1377                "pip".to_owned(),
1378                "install".to_owned(),
1379                "x".to_owned(),
1380            ]])
1381            .contained("Seatbelt");
1382        assert!(!allowed.contains("run_command", &cmd("pip install x")));
1383        assert!(!p.contains("write_file", &json!({ "path": "tests/frozen.rs" })));
1384        assert!(!p.contains("mcp__x__y", &json!({})));
1385        // A person's rejection of the very object wins.
1386        let rejected = p.clone().with_decisions(
1387            vec![],
1388            vec![Rejection {
1389                object: command("python3 -c print(1)"),
1390                reason: "no".to_owned(),
1391            }],
1392        );
1393        assert!(matches!(
1394            rejected.classify(
1395                "run_command",
1396                &cmd("python3 -c print(1)"),
1397                Some(&command("python3 -c print(1)"))
1398            ),
1399            Decision::Deny(_)
1400        ));
1401        // On autopilot it runs, and only what still asks is refused.
1402        let auto = p.clone().autopilot();
1403        assert_eq!(
1404            auto.settle(auto.classify("run_command", &cmd("python3 -c x"), None)),
1405            Decision::Allow
1406        );
1407        assert!(matches!(
1408            auto.settle(auto.classify("run_command", &cmd("curl https://x"), None)),
1409            Decision::Deny(_)
1410        ));
1411        // Not contained: it asks.
1412        assert!(matches!(
1413            policy().classify("run_command", &cmd("python3 -c print(1)"), None),
1414            Decision::Approval(_)
1415        ));
1416    }
1417
1418    #[test]
1419    fn decisions_cover_classes_and_never_override_a_denial() {
1420        let approved = vec![
1421            path("Cargo.toml", "Cargo.toml"),
1422            command("cargo build"),
1423            path("speccoder.toml", "speccoder.toml"),
1424            // Approved and rejected alike: the rejection wins.
1425            command("curl https://x"),
1426        ];
1427        let rejected = vec![Rejection {
1428            object: command("curl https://x"),
1429            reason: "no network".to_owned(),
1430        }];
1431        let p = policy().with_decisions(approved, rejected);
1432        // Any content for an approved file, whatever spelling reaches it.
1433        assert_eq!(
1434            p.classify(
1435                "edit_file",
1436                &json!({"path": "./Cargo.toml", "old_string": "a"}),
1437                Some(&path("Cargo.toml", "./Cargo.toml"))
1438            ),
1439            Decision::Allow
1440        );
1441        // The object, not the request: no object, no grant.
1442        assert!(matches!(
1443            p.classify("edit_file", &json!({"path": "Cargo.toml"}), None),
1444            Decision::Approval(_)
1445        ));
1446        assert_eq!(
1447            p.classify(
1448                "run_command",
1449                &cmd("cargo build"),
1450                Some(&command("cargo build"))
1451            ),
1452            Decision::Allow
1453        );
1454        assert!(matches!(
1455            p.classify(
1456                "run_command",
1457                &cmd("cargo build --release"),
1458                Some(&command("cargo build --release"))
1459            ),
1460            Decision::Approval(_)
1461        ));
1462        // A rejection is a denial with the person's reason, approved or not.
1463        assert_eq!(
1464            p.classify(
1465                "run_command",
1466                &cmd("curl https://x"),
1467                Some(&command("curl https://x"))
1468            ),
1469            Decision::Deny("a person rejected this: no network".to_owned())
1470        );
1471        // A protected path stays denied whatever was approved.
1472        assert!(matches!(
1473            p.classify("write_file", &json!({"path": "speccoder.toml"}), None),
1474            Decision::Deny(_)
1475        ));
1476        // Attestations are speccoder's: the model reads notes, never writes them.
1477        let p = Policy::new(&[], &[]);
1478        for argv in [
1479            vec![
1480                "git",
1481                "notes",
1482                "--ref=speccoder",
1483                "add",
1484                "-f",
1485                "-m",
1486                "x",
1487                "HEAD",
1488            ],
1489            vec!["git", "notes", "remove", "HEAD"],
1490            vec!["git", "update-ref", "refs/notes/speccoder", "HEAD"],
1491        ] {
1492            assert!(
1493                matches!(
1494                    p.classify("run_command", &json!({ "argv": argv }), None),
1495                    Decision::Deny(_)
1496                ),
1497                "{argv:?}"
1498            );
1499        }
1500        for argv in [
1501            vec!["git", "notes", "--ref=speccoder", "show", "HEAD"],
1502            vec!["git", "notes", "list"],
1503        ] {
1504            assert!(
1505                !matches!(
1506                    p.classify("run_command", &json!({ "argv": argv }), None),
1507                    Decision::Deny(_)
1508                ),
1509                "{argv:?}"
1510            );
1511        }
1512        // In place, what moves the checkout is denied; queries still run.
1513        let in_place = Policy::new(&[], &[]).in_place();
1514        for argv in [
1515            vec!["git", "switch", "main"],
1516            vec!["git", "commit", "-m", "x"],
1517            vec!["git", "reset", "HEAD~1"],
1518            vec!["git", "stash"],
1519            vec!["git", "branch", "x"],
1520            vec!["git", "apply", "--index", "p.diff"],
1521            vec!["git", "restore", "--staged", "a"],
1522            vec!["git", "update-ref", "HEAD", "x"],
1523        ] {
1524            assert!(
1525                matches!(
1526                    in_place.classify("run_command", &json!({ "argv": argv }), None),
1527                    Decision::Deny(_)
1528                ),
1529                "{argv:?}"
1530            );
1531        }
1532        for argv in [
1533            vec!["git", "status"],
1534            vec!["git", "branch", "--show-current"],
1535        ] {
1536            assert_eq!(
1537                in_place.classify("run_command", &json!({ "argv": argv }), None),
1538                Decision::Allow,
1539                "{argv:?}"
1540            );
1541        }
1542        // Ignored files are out of sight; the protected intent is not.
1543        let hidden = Policy::new(&[], &[]).in_place().with_hidden([
1544            "target/".to_owned(),
1545            "notes.txt".to_owned(),
1546            "specs/".to_owned(),
1547        ]);
1548        for (tool, path) in [
1549            ("read_file", "target/debug/x"),
1550            ("read_file", "notes.txt"),
1551            ("list_files", "target"),
1552            ("write_file", "notes.txt"),
1553        ] {
1554            assert!(
1555                matches!(
1556                    hidden.classify(tool, &json!({ "path": path }), None),
1557                    Decision::Deny(_)
1558                ),
1559                "{tool} {path}"
1560            );
1561        }
1562        assert_eq!(
1563            hidden.classify("read_file", &json!({ "path": "specs/001-x/spec.md" }), None),
1564            Decision::Allow
1565        );
1566        assert_eq!(
1567            hidden.classify("read_file", &json!({ "path": "src/lib.rs" }), None),
1568            Decision::Allow
1569        );
1570        assert!(matches!(
1571            Policy::new(&[], &[]).classify(
1572                "run_command",
1573                &json!({ "argv": ["git", "switch", "main"] }),
1574                None
1575            ),
1576            Decision::Approval(_)
1577        ));
1578    }
1579
1580    #[test]
1581    fn a_check_through_a_runner_allows_only_itself() {
1582        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1583        let check = "uv run --locked --offline python -m pytest -q --junitxml=.speccoder/junit.xml";
1584        let p = Policy::new(&[argv(check), argv("poetry run pytest -q")], &[]);
1585        assert_eq!(
1586            p.classify("run_command", &cmd(check), None),
1587            Decision::Allow
1588        );
1589        for other in [
1590            "uv run python -c print(1)",
1591            "uv run --locked --offline sh",
1592            "poetry run sh",
1593        ] {
1594            assert!(
1595                matches!(
1596                    p.classify("run_command", &cmd(other), None),
1597                    Decision::Approval(_)
1598                ),
1599                "{other}"
1600            );
1601        }
1602    }
1603
1604    #[test]
1605    fn a_check_whose_prefix_is_its_bare_program_allows_only_itself() {
1606        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1607        let p = Policy::new(
1608            &[argv("python3 -m pytest -q --junitxml=.speccoder/junit.xml")],
1609            &[],
1610        );
1611        assert_eq!(
1612            p.classify(
1613                "run_command",
1614                &cmd("python3 -m pytest -q --junitxml=.speccoder/junit.xml"),
1615                None
1616            ),
1617            Decision::Allow
1618        );
1619        assert!(matches!(
1620            p.classify("run_command", &cmd("python3 -c print(1)"), None),
1621            Decision::Approval(_)
1622        ));
1623        assert!(matches!(
1624            p.classify("run_command", &cmd("python3 -m pytest tests/x.py"), None),
1625            Decision::Approval(_)
1626        ));
1627        // Narrowed to a test, its options kept: the check, on less.
1628        let uv = Policy::new(
1629            &[argv("uv run --locked python -m pytest -q --junitxml=j.xml")],
1630            &[],
1631        );
1632        assert_eq!(
1633            uv.classify(
1634                "run_command",
1635                &cmd("uv run --locked python -m pytest -q tests/x.py --junitxml=j.xml"),
1636                None
1637            ),
1638            Decision::Allow
1639        );
1640        for other in [
1641            "uv run --locked python -m pytest -q tests/x.py",
1642            "uv run --locked python -m pytest -q -p evil tests/x.py --junitxml=j.xml",
1643            "uv run --locked python -c tests/x.py -m pytest -q --junitxml=j.xml",
1644        ] {
1645            assert!(
1646                matches!(
1647                    uv.classify("run_command", &cmd(other), None),
1648                    Decision::Approval(_)
1649                ),
1650                "{other}"
1651            );
1652        }
1653        // `[commands] allow` is exact: the entry allows itself only.
1654        let q = Policy::new(&[], &[argv("python3 -m pytest")]);
1655        assert!(matches!(
1656            q.classify("run_command", &cmd("python3 -m pytest tests/x.py"), None),
1657            Decision::Approval(_)
1658        ));
1659        assert_eq!(
1660            q.classify("run_command", &cmd("python3 -m pytest"), None),
1661            Decision::Allow
1662        );
1663    }
1664
1665    #[test]
1666    fn mcp_tools_follow_their_configured_decision_and_unknown_ones_are_denied() {
1667        let p = Policy::new(&[], &[]).with_mcp([
1668            ("mcp__db__query".to_owned(), "allow".to_owned()),
1669            ("mcp__db__drop".to_owned(), "deny".to_owned()),
1670            ("mcp__db__insert".to_owned(), "approval".to_owned()),
1671        ]);
1672        assert_eq!(
1673            p.classify("mcp__db__query", &json!({}), None),
1674            Decision::Allow
1675        );
1676        assert!(matches!(
1677            p.classify("mcp__db__drop", &json!({}), None),
1678            Decision::Deny(_)
1679        ));
1680        assert!(matches!(
1681            p.classify("mcp__db__insert", &json!({}), None),
1682            Decision::Approval(_)
1683        ));
1684        assert!(matches!(
1685            p.classify("mcp__db__other", &json!({}), None),
1686            Decision::Deny(_)
1687        ));
1688        // An approval covers the tool as defined then; it never lifts a denial.
1689        let tool = |name: &str, digest: &str| Object::Tool {
1690            name: name.to_owned(),
1691            digest: digest.to_owned(),
1692        };
1693        let q = p.clone().with_decisions(
1694            vec![tool("mcp__db__insert", "d1"), tool("mcp__db__drop", "d1")],
1695            Vec::new(),
1696        );
1697        assert_eq!(
1698            q.classify(
1699                "mcp__db__insert",
1700                &json!({ "row": 1 }),
1701                Some(&tool("mcp__db__insert", "d1"))
1702            ),
1703            Decision::Allow
1704        );
1705        // Its server changed the definition: asked again.
1706        assert!(matches!(
1707            q.classify(
1708                "mcp__db__insert",
1709                &json!({ "row": 1 }),
1710                Some(&tool("mcp__db__insert", "d2"))
1711            ),
1712            Decision::Approval(_)
1713        ));
1714        assert!(matches!(
1715            q.classify(
1716                "mcp__db__drop",
1717                &json!({}),
1718                Some(&tool("mcp__db__drop", "d1"))
1719            ),
1720            Decision::Deny(_)
1721        ));
1722        assert_eq!(
1723            tool("mcp__db__insert", "9f8e7d6c5b4a3210").short(),
1724            "mcp__db__insert@9f8e7d6c5b4a"
1725        );
1726        assert!(
1727            tool("mcp__db__insert", "d2")
1728                .changed_from(&tool("mcp__db__insert", "d1"))
1729                .is_some_and(|c| c.contains("definition changed"))
1730        );
1731    }
1732
1733    #[test]
1734    fn a_planning_task_writes_design_docs_in_its_unit_never_a_judged_file() {
1735        let p = Policy::new(&[], &[]).planning("specs/001-x/");
1736        let w = |path: &str| p.classify("write_file", &json!({ "path": path }), None);
1737        assert_eq!(w("specs/001-x/contracts/cli.md"), Decision::Allow);
1738        assert_eq!(w("specs/001-x/data-model.md"), Decision::Allow);
1739        assert_eq!(w("specs/001-x/plan.md"), Decision::Allow);
1740        assert_eq!(p.write_protected("specs/001-x/contracts/cli.md"), None);
1741        // The judged files, the person's review, the constitution, another
1742        // unit: as the normal policy says (protected).
1743        for judged in [
1744            "specs/001-x/spec.md",
1745            "specs/001-x/tasks.md",
1746            "specs/001-x/review.json",
1747            "specs/001-x/checklists/ux.md",
1748            "specs/001-x/contracts/../spec.md",
1749            ".specify/memory/constitution.md",
1750            "specs/002-y/contracts/cli.md",
1751            "specs/001-x/.env",
1752            // Inside the unit, but no design document: git, judge inputs,
1753            // agent configuration and context, manifests, hidden files.
1754            "specs/001-x/.git/config",
1755            "specs/001-x/speccoder.toml",
1756            "specs/001-x/vitest.config.ts",
1757            "specs/001-x/.mcp.json",
1758            "specs/001-x/.claude/settings.json",
1759            "specs/001-x/AGENTS.md",
1760            "specs/001-x/CLAUDE.md",
1761            "specs/001-x/package.json",
1762            "specs/001-x/Cargo.toml",
1763            "specs/001-x/.hidden.md",
1764        ] {
1765            assert!(matches!(w(judged), Decision::Deny(_)), "{judged}");
1766            assert!(!p.is_planning_write(judged), "{judged}");
1767        }
1768        assert!(p.write_protected("specs/001-x/spec.md").is_some());
1769        // Outside the unit: the normal policy.
1770        assert_eq!(w("src/lib.rs"), Decision::Allow);
1771        assert!(matches!(w("Cargo.toml"), Decision::Approval(_)));
1772        // Without the profile, the spec tree is protected as ever.
1773        let normal = Policy::new(&[], &[]);
1774        assert!(matches!(
1775            normal.classify(
1776                "write_file",
1777                &json!({ "path": "specs/001-x/contracts/cli.md" }),
1778                None
1779            ),
1780            Decision::Deny(_)
1781        ));
1782        // OpenSpec: a change's proposal, tasks and spec deltas are judged.
1783        let o = Policy::new(&[], &[])
1784            .rules(crate::format::Adapter::rules(
1785                &crate::format::openspec::OPENSPEC,
1786            ))
1787            .planning("openspec/changes/add-x");
1788        assert!(o.is_planning_write("openspec/changes/add-x/design.md"));
1789        for judged in ["proposal.md", "tasks.md", "specs/auth/spec.md"] {
1790            assert!(
1791                !o.is_planning_write(&format!("openspec/changes/add-x/{judged}")),
1792                "{judged}"
1793            );
1794        }
1795    }
1796
1797    #[test]
1798    fn the_authoring_profile_writes_spec_kit_artifacts_and_runs_its_scripts_only() {
1799        let p = Policy::new(&[], &[]).authoring();
1800        let w = |path: &str| p.classify("write_file", &json!({ "path": path }), None);
1801        assert_eq!(w("specs/002-login/spec.md"), Decision::Allow);
1802        assert_eq!(w(".specify/feature.json"), Decision::Allow);
1803        assert_eq!(w(".specify/memory/constitution.md"), Decision::Allow);
1804        assert!(matches!(
1805            w(".specify/scripts/bash/common.sh"),
1806            Decision::Deny(_)
1807        ));
1808        assert!(matches!(
1809            w(".specify/templates/spec-template.md"),
1810            Decision::Deny(_)
1811        ));
1812        assert!(matches!(w("speccoder.toml"), Decision::Deny(_)));
1813        assert!(matches!(w("specs/.env"), Decision::Deny(_)));
1814        // A planning skill writes the spec, never the person's review of it.
1815        assert!(
1816            matches!(w("specs/002-login/review.json"), Decision::Deny(ref why) if why.contains("review")),
1817            "{:?}",
1818            w("specs/002-login/review.json")
1819        );
1820        assert!(p.write_protected("specs/002-login/review.json").is_some());
1821        assert!(matches!(w("src/lib.rs"), Decision::Approval(_)));
1822        let run = |argv: &[&str]| p.classify("run_command", &json!({ "argv": argv }), None);
1823        assert_eq!(
1824            run(&[".specify/scripts/bash/setup-plan.sh", "--json"]),
1825            Decision::Allow
1826        );
1827        assert_eq!(
1828            run(&[
1829                "bash",
1830                "./.specify/scripts/bash/check-prerequisites.sh",
1831                "--json"
1832            ]),
1833            Decision::Allow
1834        );
1835        assert!(matches!(
1836            run(&["bash", ".specify/scripts/bash/../../evil.sh"]),
1837            Decision::Approval(_)
1838        ));
1839        assert_eq!(
1840            run(&[
1841                "bash",
1842                ".specify/extensions/git/scripts/bash/create-new-feature-branch.sh",
1843                "--json"
1844            ]),
1845            Decision::Allow
1846        );
1847        assert!(matches!(
1848            run(&["bash", ".specify/extensions/git/other.sh"]),
1849            Decision::Approval(_)
1850        ));
1851        assert!(matches!(
1852            run(&["bash", "-c", "rm -rf /"]),
1853            Decision::Approval(_)
1854        ));
1855        // Outside the profile, the spec stays protected.
1856        assert!(matches!(
1857            Policy::new(&[], &[]).classify(
1858                "write_file",
1859                &json!({ "path": "specs/002-login/spec.md" }),
1860                None
1861            ),
1862            Decision::Deny(_)
1863        ));
1864    }
1865
1866    #[test]
1867    fn asking_for_the_network_needs_a_person_unless_allowed() {
1868        let checks = [vec!["cargo".to_owned(), "test".to_owned()]];
1869        let p = Policy::new(&checks, &[]);
1870        let net = json!({ "argv": ["cargo", "test"], "network": true });
1871        assert!(matches!(
1872            p.classify("run_command", &net, None),
1873            Decision::Approval(_)
1874        ));
1875        // Without the network the same command is allowed; a denial stays one.
1876        assert_eq!(
1877            p.classify("run_command", &json!({ "argv": ["cargo", "test"] }), None),
1878            Decision::Allow
1879        );
1880        assert!(matches!(
1881            p.classify(
1882                "run_command",
1883                &json!({ "argv": ["git", "push"], "network": true }),
1884                None
1885            ),
1886            Decision::Deny(_)
1887        ));
1888        // `[sandbox] network_allow` is exact; a prefix entry extends.
1889        let exact = p
1890            .clone()
1891            .with_network(vec![vec!["cargo".to_owned(), "test".to_owned()]]);
1892        assert_eq!(exact.classify("run_command", &net, None), Decision::Allow);
1893        let longer = json!({ "argv": ["cargo", "test", "--release"], "network": true });
1894        assert!(matches!(
1895            exact.classify("run_command", &longer, None),
1896            Decision::Approval(_)
1897        ));
1898        let bare = p.clone().with_network(vec![vec!["cargo".to_owned()]]);
1899        assert!(matches!(
1900            bare.classify("run_command", &net, None),
1901            Decision::Approval(_)
1902        ));
1903        let prefixed = p.clone().with_network_prefixes(vec![
1904            vec!["cargo".to_owned()],
1905            vec!["cargo".to_owned(), "test".to_owned()],
1906        ]);
1907        assert_eq!(
1908            prefixed.classify("run_command", &longer, None),
1909            Decision::Allow
1910        );
1911        let object = Object::command(
1912            vec!["cargo".to_owned(), "test".to_owned()],
1913            ".".to_owned(),
1914            "/usr/bin/cargo".to_owned(),
1915            true,
1916        );
1917        let approved = Policy::new(&checks, &[]).with_decisions(vec![object.clone()], vec![]);
1918        assert_eq!(
1919            approved.classify("run_command", &net, Some(&object)),
1920            Decision::Allow
1921        );
1922        // The same argv resolving to another executable is another object.
1923        let shadowed = Object::command(
1924            vec!["cargo".to_owned(), "test".to_owned()],
1925            ".".to_owned(),
1926            "/w/bin/cargo".to_owned(),
1927            true,
1928        );
1929        assert!(matches!(
1930            approved.classify("run_command", &net, Some(&shadowed)),
1931            Decision::Approval(_)
1932        ));
1933        assert!(
1934            shadowed
1935                .changed_from(&object)
1936                .is_some_and(|c| c == "executable /usr/bin/cargo → /w/bin/cargo")
1937        );
1938    }
1939
1940    #[test]
1941    fn commands_allow_is_exact_and_prefixes_need_two_elements() {
1942        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1943        let p = Policy::new(&[], &[argv("npm run build")]);
1944        assert_eq!(
1945            p.classify("run_command", &cmd("npm run build"), None),
1946            Decision::Allow
1947        );
1948        for longer in [
1949            "npm run build --script-shell=/tmp/x",
1950            "npm run build x",
1951            "npm run",
1952        ] {
1953            assert!(
1954                matches!(
1955                    p.classify("run_command", &cmd(longer), None),
1956                    Decision::Approval(_)
1957                ),
1958                "{longer}"
1959            );
1960        }
1961        assert_eq!(
1962            p.rule("run_command", &cmd("npm run build"), None),
1963            "exact command `npm run build`"
1964        );
1965        let q = Policy::new(&[], &[]).with_prefixes(vec![argv("npm"), argv("npm run")]);
1966        assert_eq!(
1967            q.classify("run_command", &cmd("npm run build"), None),
1968            Decision::Allow
1969        );
1970        assert_eq!(
1971            q.rule("run_command", &cmd("npm run build"), None),
1972            "allowed prefix `npm run`"
1973        );
1974        // The one-element entry was dropped: a bare program allows anything.
1975        assert!(matches!(
1976            q.classify("run_command", &cmd("npm install x"), None),
1977            Decision::Approval(_)
1978        ));
1979        assert!(
1980            prefix_refusal(&argv("npm")).is_some() && prefix_refusal(&argv("npm run")).is_none()
1981        );
1982        // Fixed rules decide before every list.
1983        let r = Policy::new(&[], &[argv("sh -c ls")]).with_prefixes(vec![argv("git push")]);
1984        assert!(matches!(
1985            r.classify("run_command", &cmd("sh -c ls"), None),
1986            Decision::Approval(_)
1987        ));
1988        assert!(matches!(
1989            r.classify("run_command", &cmd("git push origin"), None),
1990            Decision::Deny(_)
1991        ));
1992    }
1993
1994    #[test]
1995    fn autopilot_never_asks_never_lifts_a_denial_and_names_its_rule() {
1996        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1997        let p = Policy::new(&[], &[argv("cargo test")]).autopilot();
1998        assert!(p.is_autopilot());
1999        // Allowed stays allowed; asking becomes refusing; denied stays denied.
2000        assert_eq!(
2001            p.settle(p.classify("run_command", &cmd("cargo test"), None)),
2002            Decision::Allow
2003        );
2004        assert_eq!(
2005            p.settle(p.classify("run_command", &cmd("cargo add x"), None)),
2006            Decision::Deny(AUTOPILOT_DENIED.to_owned())
2007        );
2008        assert_eq!(
2009            p.rule("run_command", &cmd("cargo add x"), None),
2010            "autopilot"
2011        );
2012        assert!(matches!(
2013            p.settle(p.classify("run_command", &cmd("git push origin"), None)),
2014            Decision::Deny(r) if r != AUTOPILOT_DENIED
2015        ));
2016        // Without autopilot nothing changes.
2017        let q = Policy::new(&[], &[]);
2018        assert!(matches!(
2019            q.settle(q.classify("run_command", &cmd("cargo add x"), None)),
2020            Decision::Approval(_)
2021        ));
2022        // A grant id names exactly one object.
2023        let a = command("make check");
2024        let mut b = a.clone();
2025        if let Object::Command { cwd, .. } = &mut b {
2026            *cwd = "sub".to_owned();
2027        }
2028        assert_ne!(a.grant_id(), b.grant_id());
2029        assert_eq!(a.grant_id(), a.clone().grant_id());
2030        assert_eq!(
2031            path("src/b/x.rs", "src/a/x.rs").grant_id(),
2032            path("src/b/x.rs", "src/b/x.rs").grant_id()
2033        );
2034        assert!(a.grant_id().starts_with("g-") && a.grant_id().len() == 18);
2035    }
2036
2037    proptest::proptest! {
2038        #[test]
2039        fn on_autopilot_no_call_waits_for_a_person(words in proptest::collection::vec("[a-z]{1,6}", 1..4), tool in 0usize..4) {
2040            let p = Policy::new(&[], &[]).autopilot();
2041            let argv: Vec<String> = words.clone();
2042            let (name, args) = match tool {
2043                0 => ("run_command", json!({ "argv": argv })),
2044                1 => ("write_file", json!({ "path": format!("src/{}.rs", words[0]), "content": "" })),
2045                2 => ("write_file", json!({ "path": format!(".github/{}.yml", words[0]), "content": "" })),
2046                _ => ("mcp__x__y", json!({})),
2047            };
2048            let before = Policy::new(&[], &[]).classify(name, &args, None);
2049            let after = p.settle(p.classify(name, &args, None));
2050            proptest::prop_assert!(!matches!(after, Decision::Approval(_)));
2051            if matches!(before, Decision::Deny(_)) {
2052                proptest::prop_assert!(matches!(after, Decision::Deny(_)));
2053            }
2054            if before == Decision::Allow {
2055                proptest::prop_assert_eq!(after, Decision::Allow);
2056            }
2057        }
2058    }
2059
2060    const OPENSPEC_READS: &[&[&str]] = &[&["openspec", "list"], &["openspec", "show"]];
2061
2062    fn exploring() -> Policy {
2063        Policy::new(&[vec!["cargo".to_owned(), "test".to_owned()]], &[]).exploring(Exploring {
2064            paths: |rel| rel.starts_with(".specify/assessments/"),
2065            commands: OPENSPEC_READS,
2066        })
2067    }
2068
2069    proptest::proptest! {
2070        /// Exploring never asks a person (SC-002): every write outside the
2071        /// exploration paths and every unlisted command is denied — even a
2072        /// configured check, even with the network.
2073        #[test]
2074        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) {
2075            let p = exploring();
2076            let (name, args) = match tool {
2077                0 => ("run_command", json!({ "argv": words })),
2078                1 => ("run_command", json!({ "argv": ["cargo", "test"] })),
2079                2 => ("write_file", json!({ "path": format!("src/{}.rs", words[0]), "content": "" })),
2080                3 => ("edit_file", json!({ "path": format!("specs/{}/spec.md", words[0]), "old_string": "a", "new_string": "b" })),
2081                4 => ("run_command", json!({ "argv": ["openspec", "list", words[0].clone()], "network": true })),
2082                _ => ("mcp__x__y", json!({})),
2083            };
2084            let d = p.classify(name, &args, None);
2085            proptest::prop_assert!(matches!(d, Decision::Deny(_)), "{name} {args} → {d:?}");
2086        }
2087    }
2088
2089    #[test]
2090    fn exploring_reads_and_runs_the_formats_read_only_commands() {
2091        let p = exploring();
2092        assert_eq!(
2093            p.classify("read_file", &json!({ "path": "src/lib.rs" }), None),
2094            Decision::Allow
2095        );
2096        assert_eq!(
2097            p.classify(
2098                "run_command",
2099                &json!({ "argv": ["openspec", "list", "--json"] }),
2100                None
2101            ),
2102            Decision::Allow
2103        );
2104        assert_eq!(
2105            p.classify(
2106                "write_file",
2107                &json!({ "path": ".specify/assessments/csv/notes.md", "content": "" }),
2108                None
2109            ),
2110            Decision::Allow
2111        );
2112        let Decision::Deny(why) = p.classify(
2113            "write_file",
2114            &json!({ "path": "notes.md", "content": "" }),
2115            None,
2116        ) else {
2117            panic!("a write outside the exploration paths is denied");
2118        };
2119        assert_eq!(why, EXPLORING_WRITE);
2120    }
2121
2122    #[test]
2123    fn a_path_object_is_its_canonical_file_whatever_the_spelling() {
2124        assert_eq!(
2125            path("src/b/x.rs", "src/a/x.rs"),
2126            path("src/b/x.rs", "src/b/x.rs")
2127        );
2128        assert_ne!(
2129            path("src/b/x.rs", "src/a/x.rs"),
2130            path("src/a/x.rs", "src/a/x.rs")
2131        );
2132        assert!(
2133            path("src/b/x.rs", "src/a/x.rs")
2134                .changed_from(&path("src/a/x.rs", "src/a/x.rs"))
2135                .is_some_and(|c| c == "resolves to src/b/x.rs, was src/a/x.rs")
2136        );
2137        // Commands differ by every field.
2138        let a = command("make check");
2139        let mut b = a.clone();
2140        if let Object::Command { cwd, .. } = &mut b {
2141            *cwd = "sub".to_owned();
2142        }
2143        assert_ne!(a, b);
2144        assert_eq!(a.class(), Class::Command);
2145        assert!(a.short().starts_with("argv#") && a.short().len() == 17);
2146        // The record round-trips; an older grant shape does not read.
2147        let back: Object = serde_json::from_value(serde_json::to_value(&a).unwrap()).unwrap();
2148        assert_eq!(back, a);
2149        assert!(serde_json::from_value::<Object>(json!({ "kind": "write", "path": "x" })).is_err());
2150        assert!(
2151            serde_json::from_value::<Rejection>(json!({ "grant": { "kind": "path", "canonical": "x", "asked": "x" }, "reason": "r" }))
2152                .is_err()
2153        );
2154    }
2155
2156    #[test]
2157    fn the_grant_path_has_no_pattern() {
2158        // Matching a person's decision is object equality only.
2159        let source = include_str!("policy.rs");
2160        let classify = source
2161            .split("pub fn classify(")
2162            .nth(1)
2163            .and_then(|s| s.split("\n    }\n").next())
2164            .unwrap_or_default();
2165        assert!(!classify.is_empty());
2166        for pattern in ["starts_with", "glob", "prefix"] {
2167            assert!(!classify.contains(pattern), "{pattern} in the grant path");
2168        }
2169    }
2170}