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}
459
460/// Why an autopilot run refused a call that would have asked a person.
461pub const AUTOPILOT_DENIED: &str = "autopilot: not asked — listed for you";
462
463/// Whether `argv` starts with `prefix`, a prefix of at least two elements
464/// (a bare program allows any argument, so it is never a prefix).
465#[must_use]
466pub fn prefix_matches(prefix: &[String], argv: &[String]) -> bool {
467    prefix.len() >= 2 && argv.starts_with(prefix)
468}
469
470/// Why a prefix entry is refused, if it is: a bare program allows any
471/// argument.
472#[must_use]
473pub fn prefix_refusal(prefix: &[String]) -> Option<&'static str> {
474    (prefix.len() < 2).then_some(
475        "a bare program allows any argument; add the exact command to [commands] allow instead",
476    )
477}
478
479const SHELLS: &[&str] = &[
480    "sh", "bash", "zsh", "fish", "dash", "ksh", "csh", "tcsh", "pwsh",
481];
482const PRIVILEGE: &[&str] = &["sudo", "su", "doas", "pkexec"];
483const NETWORK: &[&str] = &[
484    "curl", "wget", "nc", "ncat", "ssh", "scp", "sftp", "rsync", "ftp", "telnet",
485];
486const GIT_REMOTE: &[&str] = &[
487    "push",
488    "fetch",
489    "pull",
490    "clone",
491    "remote",
492    "ls-remote",
493    "submodule",
494];
495/// What would move the checkout of an in-place run under speccoder.
496const GIT_IN_PLACE: &[&str] = &[
497    "checkout",
498    "switch",
499    "reset",
500    "commit",
501    "merge",
502    "rebase",
503    "cherry-pick",
504    "revert",
505    "stash",
506    "branch",
507    "tag",
508    "update-ref",
509    "worktree",
510    "am",
511];
512
513/// Prefixes that run whatever program follows them.
514const RUNNERS: &[&[&str]] = &[
515    &["uv", "run"],
516    &["uv", "tool", "run"],
517    &["uvx"],
518    &["poetry", "run"],
519    &["pipx", "run"],
520    &["pdm", "run"],
521    &["hatch", "run"],
522];
523
524impl Policy {
525    /// A policy allowing the command prefixes of `checks` (program and
526    /// subcommands, up to the first option) and exactly the argvs of
527    /// `exact` (`[commands] allow`).
528    #[must_use]
529    pub fn new(checks: &[Vec<String>], exact: &[Vec<String>]) -> Self {
530        let mut allowed: Vec<Vec<String>> = checks
531            .iter()
532            .map(|argv| {
533                let prefix: Vec<String> = argv
534                    .iter()
535                    .take_while(|a| !a.starts_with('-'))
536                    .cloned()
537                    .collect();
538                // `python3 -m pytest …` would leave the bare interpreter as
539                // the prefix — and allow `python3 -c <anything>`; `uv run`
540                // would allow any program. A check whose prefix is only its
541                // program, or a runner of another program, allows exactly
542                // itself.
543                if (prefix.len() == 1
544                    || RUNNERS.iter().any(|r| {
545                        prefix
546                            .iter()
547                            .map(String::as_str)
548                            .take(r.len())
549                            .eq(r.iter().copied())
550                    }))
551                    && argv.len() > prefix.len()
552                {
553                    argv.clone()
554                } else {
555                    prefix
556                }
557            })
558            .filter(|p: &Vec<String>| !p.is_empty())
559            .collect();
560        allowed.sort();
561        allowed.dedup();
562        Self {
563            checks: allowed,
564            exact: exact.iter().filter(|p| !p.is_empty()).cloned().collect(),
565            ..Self::default()
566        }
567    }
568
569    /// `[commands] allow_prefix`: prefixes of two elements or more (a
570    /// shorter one is dropped; the configuration refuses it).
571    #[must_use]
572    pub fn with_prefixes(mut self, prefixes: Vec<Vec<String>>) -> Self {
573        self.prefix = prefixes.into_iter().filter(|p| p.len() >= 2).collect();
574        self
575    }
576
577    /// The check-derived prefixes, for a coverage view.
578    #[must_use]
579    pub fn check_prefixes(&self) -> &[Vec<String>] {
580        &self.checks
581    }
582
583    /// Paths git ignored when an in-place run started: the file tools
584    /// refuse them, except the protected files (the intent stays readable).
585    #[must_use]
586    pub fn with_hidden(mut self, hidden: impl IntoIterator<Item = String>) -> Self {
587        self.hidden = hidden.into_iter().collect();
588        self
589    }
590
591    /// Whether `rel` is ignored by git in an in-place checkout and not one
592    /// of the files speccoder protects.
593    fn is_hidden(&self, rel: &str) -> bool {
594        self.protected.write_class(rel).is_none()
595            && !self.protected.is_context(rel)
596            && self.hidden.iter().any(|h| match h.strip_suffix('/') {
597                Some(dir) => rel == dir || rel.starts_with(h.as_str()),
598                None => rel == h,
599            })
600    }
601
602    /// An in-place attempt (`run --in-place`): the checkout is the
603    /// person's, so git commands that move it are denied.
604    #[must_use]
605    pub fn in_place(mut self) -> Self {
606        self.in_place = true;
607        self
608    }
609
610    /// An autopilot run: nothing asks ([`Policy::settle`]).
611    #[must_use]
612    pub const fn autopilot(mut self) -> Self {
613        self.autopilot = true;
614        self
615    }
616
617    /// Whether it is an autopilot run's.
618    #[must_use]
619    pub const fn is_autopilot(&self) -> bool {
620        self.autopilot
621    }
622
623    /// What a decision comes to once every grant had its say: on
624    /// autopilot a call that would still ask a person is refused for the
625    /// run ([`AUTOPILOT_DENIED`]); every other decision stands — a denial,
626    /// a rejection or a protected path is never lifted.
627    #[must_use]
628    pub fn settle(&self, decision: Decision) -> Decision {
629        match decision {
630            Decision::Approval(_) if self.autopilot => Decision::Deny(AUTOPILOT_DENIED.to_owned()),
631            d => d,
632        }
633    }
634
635    /// The planning profile: the format's artifacts and scripts are the
636    /// work; its machinery, verification inputs and secrets stay denied;
637    /// anything else — source code included — needs approval.
638    #[must_use]
639    pub fn authoring(mut self) -> Self {
640        self.authoring = true;
641        self
642    }
643
644    /// A planning task's profile: writes inside the unit's directory
645    /// `dir` (worktree-relative) are its work, except the format's judged
646    /// files ([`crate::format::Rules::judged`]), a credential and the
647    /// person's review; everything else is as the policy says.
648    #[must_use]
649    pub fn planning(mut self, dir: &str) -> Self {
650        let dir = dir.trim_matches('/');
651        self.planning = (!dir.is_empty()).then(|| dir.to_owned());
652        self
653    }
654
655    /// Whether `rel` (resolved, worktree-relative) is a planning task's
656    /// to write: a design document inside its unit's directory
657    /// ([`Protected::is_design_doc`]), not judged by the format.
658    #[must_use]
659    pub fn is_planning_write(&self, rel: &str) -> bool {
660        let Some(dir) = &self.planning else {
661            return false;
662        };
663        rel.strip_prefix(dir.as_str())
664            .and_then(|r| r.strip_prefix('/'))
665            .is_some_and(|r| {
666                !r.is_empty()
667                    && !r.split('/').any(|s| s == ".." || s == ".")
668                    && !(self.protected.rules().judged)(r.trim_end_matches('/'))
669                    && self.protected.is_design_doc(rel)
670                    && !self.protected.is_review(rel)
671            })
672    }
673
674    /// The project's format's rules (intent, planning artifacts); the
675    /// reference format's by default.
676    #[must_use]
677    pub fn rules(mut self, rules: &'static crate::format::Rules) -> Self {
678        self.protected = Protected::new(rules);
679        self
680    }
681
682    /// `[sandbox] network_allow`: exact argvs that get the network.
683    #[must_use]
684    pub fn with_network(mut self, exact: Vec<Vec<String>>) -> Self {
685        self.network_exact = exact.into_iter().filter(|p| !p.is_empty()).collect();
686        self
687    }
688
689    /// `[sandbox] network_allow_prefix`: prefixes (two elements or more)
690    /// that get the network.
691    #[must_use]
692    pub fn with_network_prefixes(mut self, prefixes: Vec<Vec<String>>) -> Self {
693        self.network_prefix = prefixes.into_iter().filter(|p| p.len() >= 2).collect();
694        self
695    }
696
697    /// Whether `argv` gets the network without asking: an exact entry, or a
698    /// prefix entry it extends.
699    #[must_use]
700    pub fn network_allowed(&self, argv: &[String]) -> bool {
701        self.network_exact.contains(argv)
702            || self.network_prefix.iter().any(|p| prefix_matches(p, argv))
703    }
704
705    /// The project's MCP tools and their configured decisions.
706    #[must_use]
707    pub fn with_mcp(mut self, tools: impl IntoIterator<Item = (String, String)>) -> Self {
708        self.mcp = tools.into_iter().collect();
709        self
710    }
711
712    /// A person's decisions for this task: an approval turns a call that
713    /// needs approval into an allowed one (never a denied one); a rejection
714    /// turns it into a denial with the person's reason.
715    #[must_use]
716    pub fn with_decisions(mut self, approved: Vec<Object>, rejected: Vec<Rejection>) -> Self {
717        self.approved = approved;
718        self.rejected = rejected;
719        self
720    }
721
722    /// Freezes these test files: writing them needs approval.
723    #[must_use]
724    pub fn with_frozen(mut self, frozen: impl IntoIterator<Item = String>) -> Self {
725        self.frozen = frozen.into_iter().collect();
726        self
727    }
728
729    /// The protected set this policy uses.
730    #[must_use]
731    pub fn protected(&self) -> &Protected {
732        &self.protected
733    }
734
735    /// Whether this (resolved, workspace-relative) path is protected for
736    /// writing under this policy: the authoring profile writes the format's
737    /// artifacts, nothing else of the protected set.
738    #[must_use]
739    pub fn write_protected(&self, rel: &str) -> Option<super::paths::Class> {
740        if self.is_planning_write(rel) {
741            return None;
742        }
743        if self.authoring
744            && (self.protected.rules().authoring_path)(rel)
745            && !self.protected.is_secret(rel)
746            && !self.protected.is_review(rel)
747        {
748            return None;
749        }
750        self.protected.write_class(rel)
751    }
752
753    /// Classifies `tool` called with `args`. A person's decision applies
754    /// only to the call's resolved `object` (none: the request alone was
755    /// seen, and nobody's decision covers it): a rejection of that very
756    /// object denies it, an approval of it allows it, never a denial.
757    #[must_use]
758    pub fn classify(&self, tool: &str, args: &Value, object: Option<&Object>) -> Decision {
759        let decision = self.base(tool, args);
760        if !matches!(decision, Decision::Approval(_)) {
761            return decision;
762        }
763        let Some(object) = object else {
764            return decision;
765        };
766        if let Some(r) = self.rejected.iter().find(|r| r.object == *object) {
767            return Decision::Deny(format!("a person rejected this: {}", r.reason));
768        }
769        if self.approved.iter().any(|a| a == object) {
770            return Decision::Allow;
771        }
772        decision
773    }
774
775    /// A person's rejection of exactly `object`, if one holds.
776    #[must_use]
777    pub fn rejection(&self, object: &Object) -> Option<&Rejection> {
778        self.rejected.iter().find(|r| r.object == *object)
779    }
780
781    /// The person's rejections and approvals, for the changed-object line.
782    #[must_use]
783    pub fn approved(&self) -> &[Object] {
784        &self.approved
785    }
786
787    /// The rule that decides `tool` with `args` when no person does: what a
788    /// call's record names, so a rule's decision is never read as a
789    /// person's.
790    #[must_use]
791    pub fn rule(&self, tool: &str, args: &Value, object: Option<&Object>) -> String {
792        if self.autopilot && matches!(self.classify(tool, args, object), Decision::Approval(_)) {
793            return "autopilot".to_owned();
794        }
795        if let Some(object) = object
796            && matches!(self.base(tool, args), Decision::Approval(_))
797        {
798            if self.rejected.iter().any(|r| r.object == *object) {
799                return format!("rejection of {} for the task", object.describe());
800            }
801            if self.approved.iter().any(|a| a == object) {
802                return format!("grant {} for the task", object.describe());
803            }
804        }
805        if tool.starts_with(MCP_PREFIX) {
806            let entry = self.mcp.get(tool).map_or("unlisted", String::as_str);
807            return format!("[mcp] {entry}");
808        }
809        match tool {
810            "read_file" | "list_files" | "search_code" => "workspace read".to_owned(),
811            "write_file" | "edit_file" => "workspace write".to_owned(),
812            "git_status" | "git_diff" => "read-only git".to_owned(),
813            "run_command" => {
814                let argv = argv_of(args);
815                if self.exact.contains(&argv) {
816                    return format!("exact command `{}`", argv.join(" "));
817                }
818                if let Some(p) = self
819                    .checks
820                    .iter()
821                    .find(|p| argv.len() >= p.len() && argv[..p.len()] == p[..])
822                {
823                    return format!("check prefix `{}`", p.join(" "));
824                }
825                match self.prefix.iter().find(|p| prefix_matches(p, &argv)) {
826                    Some(p) => format!("allowed prefix `{}`", p.join(" ")),
827                    None => "command policy".to_owned(),
828                }
829            }
830            _ => "tool policy".to_owned(),
831        }
832    }
833
834    /// The decision by rule alone, before any person's: what decides
835    /// whether a call's object is resolved and a person asked.
836    #[must_use]
837    pub fn base(&self, tool: &str, args: &Value) -> Decision {
838        self.base_of(tool, args)
839    }
840
841    fn base_of(&self, tool: &str, args: &Value) -> Decision {
842        if tool.starts_with(MCP_PREFIX) {
843            return match self.mcp.get(tool).map(String::as_str) {
844                Some("allow") => Decision::Allow,
845                Some("deny") => Decision::Deny(format!("`{tool}` is denied in [mcp]")),
846                Some(_) => Decision::Approval(format!(
847                    "`{tool}` is an MCP tool; speccoder cannot know what it does"
848                )),
849                None => Decision::Deny(format!("unknown tool `{tool}`")),
850            };
851        }
852        match tool {
853            "read_file" | "list_files" | "search_code" => self.read(args),
854            "write_file" | "edit_file" => self.write(args),
855            "run_command" => self.with_network_rule(args, self.command(args)),
856            "git_status" | "git_diff" => Decision::Allow,
857            other => Decision::Deny(format!("unknown tool `{other}`")),
858        }
859    }
860
861    /// A command that asks for the network (`"network": true`) needs a
862    /// person, unless its prefix is in `[sandbox] network_allow`.
863    fn with_network_rule(&self, args: &Value, decision: Decision) -> Decision {
864        if args.get("network").and_then(Value::as_bool) != Some(true)
865            || matches!(decision, Decision::Deny(_))
866        {
867            return decision;
868        }
869        let argv = argv_of(args);
870        if self.network_allowed(&argv) {
871            return decision;
872        }
873        Decision::Approval(format!(
874            "`{}` asks for the network; commands run without it",
875            argv.join(" ")
876        ))
877    }
878
879    fn read(&self, args: &Value) -> Decision {
880        // No path, `.`, `./` or "": the whole workspace (models pass all of them).
881        let Some(path) = args
882            .get("path")
883            .and_then(Value::as_str)
884            .filter(|p| !matches!(p.trim(), "" | "." | "./"))
885        else {
886            return Decision::Allow; // list/search over the whole workspace
887        };
888        match normalise(path) {
889            Err(e) => Decision::Deny(e.0),
890            Ok(p) if self.protected.is_secret(&p) => {
891                Decision::Deny(format!("`{p}` looks like a credential"))
892            }
893            Ok(p) if self.is_hidden(&p) => Decision::Deny(format!(
894                "`{p}` is ignored by git in this checkout; an in-place run works only with what a worktree would hold"
895            )),
896            Ok(_) => Decision::Allow,
897        }
898    }
899
900    fn write(&self, args: &Value) -> Decision {
901        let Some(path) = args.get("path").and_then(Value::as_str) else {
902            return Decision::Deny("no `path`".to_owned());
903        };
904        let p = match normalise(path) {
905            Ok(p) => p,
906            Err(e) => return Decision::Deny(e.0),
907        };
908        if (self.authoring
909            && (self.protected.rules().authoring_path)(&p)
910            && !self.protected.is_secret(&p)
911            && !self.protected.is_review(&p))
912            || self.is_planning_write(&p)
913        {
914            return Decision::Allow;
915        }
916        if self.is_hidden(&p) {
917            return Decision::Deny(format!(
918                "`{p}` is ignored by git in this checkout; an in-place run does not write it"
919            ));
920        }
921        if self.protected.is_review(&p) {
922            return Decision::Deny(format!(
923                "`{p}` is protected: it records a person's review of the spec; only the person writes it (`speccoder review`)"
924            ));
925        }
926        if let Some(class) = self.protected.write_class(&p) {
927            return Decision::Deny(format!(
928                "`{p}` is protected: {}",
929                self.protected.reason(class)
930            ));
931        }
932        if self.authoring {
933            return Decision::Approval((self.protected.rules().authoring_refusal)(&p));
934        }
935        if self.protected.is_context(&p) {
936            return Decision::Approval(format!(
937                "`{p}` is an agent context file: every later agent session reads it"
938            ));
939        }
940        if self
941            .frozen
942            .iter()
943            .any(|f| f.to_lowercase() == p.to_lowercase())
944        {
945            return Decision::Approval(format!(
946                "`{p}` is a frozen test (it existed when the attempt started)"
947            ));
948        }
949        if self.protected.is_manifest(&p) {
950            return Decision::Approval(format!("`{p}` is a dependency manifest"));
951        }
952        Decision::Allow
953    }
954
955    fn command(&self, args: &Value) -> Decision {
956        let argv = argv_of(args);
957        match (self.protected.rules().command)(&argv, self.authoring) {
958            Some(Ok(())) => return Decision::Allow,
959            Some(Err(why)) => return Decision::Deny(why),
960            None => {}
961        }
962        let Some(program) = argv.first() else {
963            return Decision::Deny("empty `argv`".to_owned());
964        };
965        let name = program.rsplit('/').next().unwrap_or(program);
966        let has = |flag: &str| argv.iter().any(|a| a == flag);
967
968        if PRIVILEGE.contains(&name) {
969            return Decision::Deny(format!("`{name}` raises privileges"));
970        }
971        if name == "git" {
972            let sub = argv.get(1).map_or("", String::as_str);
973            if GIT_REMOTE.contains(&sub) {
974                return Decision::Deny(format!(
975                    "`git {sub}` talks to a remote; speccoder never does"
976                ));
977            }
978            // Attestations are git notes only speccoder writes.
979            let notes_action = argv[2..]
980                .iter()
981                .find(|a| !a.starts_with('-'))
982                .map_or("list", String::as_str);
983            if (sub == "notes" && !matches!(notes_action, "show" | "list"))
984                || (sub == "update-ref" && argv.iter().any(|a| a.starts_with("refs/notes")))
985            {
986                return Decision::Deny(
987                    "git notes are speccoder's attestations; only speccoder writes them".to_owned(),
988                );
989            }
990            // Read-only queries (skills and models ask where they are).
991            let listing_branches = sub == "branch"
992                && argv[2..].iter().all(|a| {
993                    matches!(
994                        a.as_str(),
995                        "--show-current" | "--list" | "-l" | "-a" | "--all" | "-v" | "-vv"
996                    )
997                });
998            if matches!(
999                sub,
1000                "rev-parse" | "status" | "log" | "diff" | "show" | "ls-files" | "describe"
1001            ) || listing_branches
1002            {
1003                return Decision::Allow;
1004            }
1005            if self.in_place
1006                && !listing_branches
1007                && (GIT_IN_PLACE.contains(&sub)
1008                    || (sub == "apply" && has("--index"))
1009                    || (sub == "restore" && has("--staged")))
1010            {
1011                return Decision::Deny(format!(
1012                    "`git {sub}` would move the checkout of an in-place run; speccoder commits and switches it"
1013                ));
1014            }
1015            if sub == "clean" || (sub == "reset" && has("--hard")) || sub == "filter-branch" {
1016                return Decision::Deny(format!("`git {sub}` destroys work"));
1017            }
1018            if matches!(
1019                sub,
1020                "commit"
1021                    | "checkout"
1022                    | "switch"
1023                    | "rebase"
1024                    | "merge"
1025                    | "stash"
1026                    | "branch"
1027                    | "tag"
1028                    | "config"
1029                    | "worktree"
1030            ) {
1031                return Decision::Approval(format!("`git {sub}` changes repository state"));
1032            }
1033        }
1034        if SHELLS.contains(&name) || name == "eval" || name == "env" || name == "xargs" {
1035            return Decision::Approval(format!("`{name}` runs arbitrary commands"));
1036        }
1037        if NETWORK.contains(&name) {
1038            return Decision::Approval(format!("`{name}` uses the network"));
1039        }
1040        if name == "rm" && argv.iter().any(|a| a.starts_with('-') && a.contains('r')) {
1041            return Decision::Approval("recursive `rm`".to_owned());
1042        }
1043        // `cargo --version`, `rustc -V`, `python3 --version`: harmless probes.
1044        if argv.len() == 2 && matches!(argv[1].as_str(), "--version" | "-V" | "version") {
1045            return Decision::Allow;
1046        }
1047        // `[commands] allow` is exact; a check allows its prefix; a
1048        // prefix entry (two elements or more) what extends it.
1049        if self.exact.contains(&argv)
1050            || self
1051                .checks
1052                .iter()
1053                .any(|prefix| argv.len() >= prefix.len() && argv[..prefix.len()] == prefix[..])
1054            || self.prefix.iter().any(|p| prefix_matches(p, &argv))
1055        {
1056            return Decision::Allow;
1057        }
1058        Decision::Approval(NOT_ALLOWED.to_owned())
1059    }
1060}
1061
1062/// The argv a `run_command` call asks for (strings only).
1063#[must_use]
1064pub fn argv_of(args: &Value) -> Vec<String> {
1065    args.get("argv")
1066        .and_then(Value::as_array)
1067        .map(|a| {
1068            a.iter()
1069                .filter_map(|v| v.as_str().map(str::to_owned))
1070                .collect()
1071        })
1072        .unwrap_or_default()
1073}
1074
1075#[cfg(test)]
1076mod tests {
1077    use super::*;
1078    use serde_json::json;
1079
1080    fn policy() -> Policy {
1081        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1082        Policy::new(
1083            &[
1084                argv("cargo nextest run --workspace --profile speccoder"),
1085                argv("cargo clippy --workspace -- -D warnings"),
1086            ],
1087            &[],
1088        )
1089        .with_prefixes(vec![argv("cargo fmt"), argv("cargo check")])
1090    }
1091
1092    #[test]
1093    fn an_unasked_call_is_named_with_how_to_let_it_run() {
1094        let decide = "run with prompts";
1095        let refused = policy().classify("run_command", &json!({"argv": ["npm", "i"]}), None);
1096        let Decision::Approval(reason) = refused else {
1097            panic!("{refused:?}")
1098        };
1099        let m = unasked(
1100            &json!({"tool": "run_command", "arguments": {"argv": ["make", "it's"]}, "reason": reason}),
1101            decide,
1102        );
1103        assert_eq!(
1104            m,
1105            "`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"
1106        );
1107        // No allow entry lets a shell run: only a person can.
1108        let m = unasked(
1109            &json!({"tool": "run_command", "arguments": {"argv": ["sh", "-c", "x"]}, "reason": "`sh` runs arbitrary commands"}),
1110            decide,
1111        );
1112        assert_eq!(
1113            m,
1114            "`sh -c x` needs approval: `sh` runs arbitrary commands — run with prompts"
1115        );
1116        let m = unasked(
1117            &json!({"tool": "write_file", "arguments": {"path": "Cargo.toml"}, "reason": "`Cargo.toml` is a dependency manifest"}),
1118            decide,
1119        );
1120        assert_eq!(
1121            m,
1122            "`write_file` `Cargo.toml` needs approval: `Cargo.toml` is a dependency manifest — run with prompts"
1123        );
1124    }
1125
1126    fn path(canonical: &str, asked: &str) -> Object {
1127        Object::Path {
1128            canonical: canonical.to_owned(),
1129            asked: asked.to_owned(),
1130        }
1131    }
1132
1133    fn command(s: &str) -> Object {
1134        Object::command(
1135            s.split(' ').map(str::to_owned).collect(),
1136            ".".to_owned(),
1137            "/usr/bin/x".to_owned(),
1138            false,
1139        )
1140    }
1141
1142    fn cmd(s: &str) -> Value {
1143        json!({ "argv": s.split(' ').collect::<Vec<_>>() })
1144    }
1145
1146    #[test]
1147    fn classifies_the_table() {
1148        use Decision::{Allow, Approval, Deny};
1149        let p = policy();
1150        let kind = |d: Decision| match d {
1151            Allow => "allow",
1152            Approval(_) => "approval",
1153            Deny(_) => "deny",
1154        };
1155        let cases: &[(&str, Value, &str)] = &[
1156            ("read_file", json!({"path": "src/lib.rs"}), "allow"),
1157            ("read_file", json!({"path": ".env"}), "deny"),
1158            ("read_file", json!({"path": "../secret"}), "deny"),
1159            ("list_files", json!({}), "allow"),
1160            ("search_code", json!({"pattern": "fn main"}), "allow"),
1161            ("write_file", json!({"path": "src/new.rs"}), "allow"),
1162            ("edit_file", json!({"path": "specs/001-x/tasks.md"}), "deny"),
1163            ("write_file", json!({"path": "speccoder.toml"}), "deny"),
1164            (
1165                "write_file",
1166                json!({"path": ".github/workflows/ci.yml"}),
1167                "deny",
1168            ),
1169            (
1170                "write_file",
1171                json!({"path": ".git/hooks/pre-commit"}),
1172                "deny",
1173            ),
1174            ("edit_file", json!({"path": "Cargo.toml"}), "approval"),
1175            ("edit_file", json!({"path": "web/package.json"}), "approval"),
1176            ("run_command", cmd("cargo nextest run -p x"), "allow"),
1177            ("run_command", cmd("cargo clippy --all-targets"), "allow"),
1178            ("run_command", cmd("cargo fmt --all"), "allow"),
1179            ("run_command", cmd("cargo build"), "approval"),
1180            ("run_command", cmd("cargo --version"), "allow"),
1181            ("run_command", cmd("rustc -V"), "allow"),
1182            ("run_command", cmd("sudo --version"), "deny"),
1183            ("run_command", cmd("npm install left-pad"), "approval"),
1184            ("run_command", cmd("git push origin main"), "deny"),
1185            ("run_command", cmd("git fetch"), "deny"),
1186            ("run_command", cmd("git reset --hard HEAD"), "deny"),
1187            ("run_command", cmd("git clean -fdx"), "deny"),
1188            ("run_command", cmd("git commit -m x"), "approval"),
1189            (
1190                "run_command",
1191                cmd("git rev-parse --is-inside-work-tree"),
1192                "allow",
1193            ),
1194            ("run_command", cmd("git branch --show-current"), "allow"),
1195            ("run_command", cmd("git branch feature-x"), "approval"),
1196            ("run_command", cmd("git log --oneline -3"), "allow"),
1197            ("run_command", cmd("sh -c ls"), "approval"),
1198            ("run_command", cmd("sudo cargo test"), "deny"),
1199            ("run_command", cmd("curl https://example.com"), "approval"),
1200            ("run_command", cmd("rm -rf target"), "approval"),
1201            ("run_command", json!({"argv": []}), "deny"),
1202            ("git_status", json!({}), "allow"),
1203            ("git_diff", json!({}), "allow"),
1204            ("delete_everything", json!({}), "deny"),
1205        ];
1206        for (tool, args, want) in cases {
1207            assert_eq!(kind(p.classify(tool, args, None)), *want, "{tool} {args}");
1208        }
1209    }
1210
1211    #[test]
1212    fn decisions_cover_classes_and_never_override_a_denial() {
1213        let approved = vec![
1214            path("Cargo.toml", "Cargo.toml"),
1215            command("cargo build"),
1216            path("speccoder.toml", "speccoder.toml"),
1217            // Approved and rejected alike: the rejection wins.
1218            command("curl https://x"),
1219        ];
1220        let rejected = vec![Rejection {
1221            object: command("curl https://x"),
1222            reason: "no network".to_owned(),
1223        }];
1224        let p = policy().with_decisions(approved, rejected);
1225        // Any content for an approved file, whatever spelling reaches it.
1226        assert_eq!(
1227            p.classify(
1228                "edit_file",
1229                &json!({"path": "./Cargo.toml", "old_string": "a"}),
1230                Some(&path("Cargo.toml", "./Cargo.toml"))
1231            ),
1232            Decision::Allow
1233        );
1234        // The object, not the request: no object, no grant.
1235        assert!(matches!(
1236            p.classify("edit_file", &json!({"path": "Cargo.toml"}), None),
1237            Decision::Approval(_)
1238        ));
1239        assert_eq!(
1240            p.classify(
1241                "run_command",
1242                &cmd("cargo build"),
1243                Some(&command("cargo build"))
1244            ),
1245            Decision::Allow
1246        );
1247        assert!(matches!(
1248            p.classify(
1249                "run_command",
1250                &cmd("cargo build --release"),
1251                Some(&command("cargo build --release"))
1252            ),
1253            Decision::Approval(_)
1254        ));
1255        // A rejection is a denial with the person's reason, approved or not.
1256        assert_eq!(
1257            p.classify(
1258                "run_command",
1259                &cmd("curl https://x"),
1260                Some(&command("curl https://x"))
1261            ),
1262            Decision::Deny("a person rejected this: no network".to_owned())
1263        );
1264        // A protected path stays denied whatever was approved.
1265        assert!(matches!(
1266            p.classify("write_file", &json!({"path": "speccoder.toml"}), None),
1267            Decision::Deny(_)
1268        ));
1269        // Attestations are speccoder's: the model reads notes, never writes them.
1270        let p = Policy::new(&[], &[]);
1271        for argv in [
1272            vec![
1273                "git",
1274                "notes",
1275                "--ref=speccoder",
1276                "add",
1277                "-f",
1278                "-m",
1279                "x",
1280                "HEAD",
1281            ],
1282            vec!["git", "notes", "remove", "HEAD"],
1283            vec!["git", "update-ref", "refs/notes/speccoder", "HEAD"],
1284        ] {
1285            assert!(
1286                matches!(
1287                    p.classify("run_command", &json!({ "argv": argv }), None),
1288                    Decision::Deny(_)
1289                ),
1290                "{argv:?}"
1291            );
1292        }
1293        for argv in [
1294            vec!["git", "notes", "--ref=speccoder", "show", "HEAD"],
1295            vec!["git", "notes", "list"],
1296        ] {
1297            assert!(
1298                !matches!(
1299                    p.classify("run_command", &json!({ "argv": argv }), None),
1300                    Decision::Deny(_)
1301                ),
1302                "{argv:?}"
1303            );
1304        }
1305        // In place, what moves the checkout is denied; queries still run.
1306        let in_place = Policy::new(&[], &[]).in_place();
1307        for argv in [
1308            vec!["git", "switch", "main"],
1309            vec!["git", "commit", "-m", "x"],
1310            vec!["git", "reset", "HEAD~1"],
1311            vec!["git", "stash"],
1312            vec!["git", "branch", "x"],
1313            vec!["git", "apply", "--index", "p.diff"],
1314            vec!["git", "restore", "--staged", "a"],
1315            vec!["git", "update-ref", "HEAD", "x"],
1316        ] {
1317            assert!(
1318                matches!(
1319                    in_place.classify("run_command", &json!({ "argv": argv }), None),
1320                    Decision::Deny(_)
1321                ),
1322                "{argv:?}"
1323            );
1324        }
1325        for argv in [
1326            vec!["git", "status"],
1327            vec!["git", "branch", "--show-current"],
1328        ] {
1329            assert_eq!(
1330                in_place.classify("run_command", &json!({ "argv": argv }), None),
1331                Decision::Allow,
1332                "{argv:?}"
1333            );
1334        }
1335        // Ignored files are out of sight; the protected intent is not.
1336        let hidden = Policy::new(&[], &[]).in_place().with_hidden([
1337            "target/".to_owned(),
1338            "notes.txt".to_owned(),
1339            "specs/".to_owned(),
1340        ]);
1341        for (tool, path) in [
1342            ("read_file", "target/debug/x"),
1343            ("read_file", "notes.txt"),
1344            ("list_files", "target"),
1345            ("write_file", "notes.txt"),
1346        ] {
1347            assert!(
1348                matches!(
1349                    hidden.classify(tool, &json!({ "path": path }), None),
1350                    Decision::Deny(_)
1351                ),
1352                "{tool} {path}"
1353            );
1354        }
1355        assert_eq!(
1356            hidden.classify("read_file", &json!({ "path": "specs/001-x/spec.md" }), None),
1357            Decision::Allow
1358        );
1359        assert_eq!(
1360            hidden.classify("read_file", &json!({ "path": "src/lib.rs" }), None),
1361            Decision::Allow
1362        );
1363        assert!(matches!(
1364            Policy::new(&[], &[]).classify(
1365                "run_command",
1366                &json!({ "argv": ["git", "switch", "main"] }),
1367                None
1368            ),
1369            Decision::Approval(_)
1370        ));
1371    }
1372
1373    #[test]
1374    fn a_check_through_a_runner_allows_only_itself() {
1375        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1376        let check = "uv run --locked --offline python -m pytest -q --junitxml=.speccoder/junit.xml";
1377        let p = Policy::new(&[argv(check), argv("poetry run pytest -q")], &[]);
1378        assert_eq!(
1379            p.classify("run_command", &cmd(check), None),
1380            Decision::Allow
1381        );
1382        for other in [
1383            "uv run python -c print(1)",
1384            "uv run --locked --offline sh",
1385            "poetry run sh",
1386        ] {
1387            assert!(
1388                matches!(
1389                    p.classify("run_command", &cmd(other), None),
1390                    Decision::Approval(_)
1391                ),
1392                "{other}"
1393            );
1394        }
1395    }
1396
1397    #[test]
1398    fn a_check_whose_prefix_is_its_bare_program_allows_only_itself() {
1399        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1400        let p = Policy::new(
1401            &[argv("python3 -m pytest -q --junitxml=.speccoder/junit.xml")],
1402            &[],
1403        );
1404        assert_eq!(
1405            p.classify(
1406                "run_command",
1407                &cmd("python3 -m pytest -q --junitxml=.speccoder/junit.xml"),
1408                None
1409            ),
1410            Decision::Allow
1411        );
1412        assert!(matches!(
1413            p.classify("run_command", &cmd("python3 -c print(1)"), None),
1414            Decision::Approval(_)
1415        ));
1416        assert!(matches!(
1417            p.classify("run_command", &cmd("python3 -m pytest tests/x.py"), None),
1418            Decision::Approval(_)
1419        ));
1420        // `[commands] allow` is exact: the entry allows itself only.
1421        let q = Policy::new(&[], &[argv("python3 -m pytest")]);
1422        assert!(matches!(
1423            q.classify("run_command", &cmd("python3 -m pytest tests/x.py"), None),
1424            Decision::Approval(_)
1425        ));
1426        assert_eq!(
1427            q.classify("run_command", &cmd("python3 -m pytest"), None),
1428            Decision::Allow
1429        );
1430    }
1431
1432    #[test]
1433    fn mcp_tools_follow_their_configured_decision_and_unknown_ones_are_denied() {
1434        let p = Policy::new(&[], &[]).with_mcp([
1435            ("mcp__db__query".to_owned(), "allow".to_owned()),
1436            ("mcp__db__drop".to_owned(), "deny".to_owned()),
1437            ("mcp__db__insert".to_owned(), "approval".to_owned()),
1438        ]);
1439        assert_eq!(
1440            p.classify("mcp__db__query", &json!({}), None),
1441            Decision::Allow
1442        );
1443        assert!(matches!(
1444            p.classify("mcp__db__drop", &json!({}), None),
1445            Decision::Deny(_)
1446        ));
1447        assert!(matches!(
1448            p.classify("mcp__db__insert", &json!({}), None),
1449            Decision::Approval(_)
1450        ));
1451        assert!(matches!(
1452            p.classify("mcp__db__other", &json!({}), None),
1453            Decision::Deny(_)
1454        ));
1455        // An approval covers the tool as defined then; it never lifts a denial.
1456        let tool = |name: &str, digest: &str| Object::Tool {
1457            name: name.to_owned(),
1458            digest: digest.to_owned(),
1459        };
1460        let q = p.clone().with_decisions(
1461            vec![tool("mcp__db__insert", "d1"), tool("mcp__db__drop", "d1")],
1462            Vec::new(),
1463        );
1464        assert_eq!(
1465            q.classify(
1466                "mcp__db__insert",
1467                &json!({ "row": 1 }),
1468                Some(&tool("mcp__db__insert", "d1"))
1469            ),
1470            Decision::Allow
1471        );
1472        // Its server changed the definition: asked again.
1473        assert!(matches!(
1474            q.classify(
1475                "mcp__db__insert",
1476                &json!({ "row": 1 }),
1477                Some(&tool("mcp__db__insert", "d2"))
1478            ),
1479            Decision::Approval(_)
1480        ));
1481        assert!(matches!(
1482            q.classify(
1483                "mcp__db__drop",
1484                &json!({}),
1485                Some(&tool("mcp__db__drop", "d1"))
1486            ),
1487            Decision::Deny(_)
1488        ));
1489        assert_eq!(
1490            tool("mcp__db__insert", "9f8e7d6c5b4a3210").short(),
1491            "mcp__db__insert@9f8e7d6c5b4a"
1492        );
1493        assert!(
1494            tool("mcp__db__insert", "d2")
1495                .changed_from(&tool("mcp__db__insert", "d1"))
1496                .is_some_and(|c| c.contains("definition changed"))
1497        );
1498    }
1499
1500    #[test]
1501    fn a_planning_task_writes_design_docs_in_its_unit_never_a_judged_file() {
1502        let p = Policy::new(&[], &[]).planning("specs/001-x/");
1503        let w = |path: &str| p.classify("write_file", &json!({ "path": path }), None);
1504        assert_eq!(w("specs/001-x/contracts/cli.md"), Decision::Allow);
1505        assert_eq!(w("specs/001-x/data-model.md"), Decision::Allow);
1506        assert_eq!(w("specs/001-x/plan.md"), Decision::Allow);
1507        assert_eq!(p.write_protected("specs/001-x/contracts/cli.md"), None);
1508        // The judged files, the person's review, the constitution, another
1509        // unit: as the normal policy says (protected).
1510        for judged in [
1511            "specs/001-x/spec.md",
1512            "specs/001-x/tasks.md",
1513            "specs/001-x/review.json",
1514            "specs/001-x/checklists/ux.md",
1515            "specs/001-x/contracts/../spec.md",
1516            ".specify/memory/constitution.md",
1517            "specs/002-y/contracts/cli.md",
1518            "specs/001-x/.env",
1519            // Inside the unit, but no design document: git, judge inputs,
1520            // agent configuration and context, manifests, hidden files.
1521            "specs/001-x/.git/config",
1522            "specs/001-x/speccoder.toml",
1523            "specs/001-x/vitest.config.ts",
1524            "specs/001-x/.mcp.json",
1525            "specs/001-x/.claude/settings.json",
1526            "specs/001-x/AGENTS.md",
1527            "specs/001-x/CLAUDE.md",
1528            "specs/001-x/package.json",
1529            "specs/001-x/Cargo.toml",
1530            "specs/001-x/.hidden.md",
1531        ] {
1532            assert!(matches!(w(judged), Decision::Deny(_)), "{judged}");
1533            assert!(!p.is_planning_write(judged), "{judged}");
1534        }
1535        assert!(p.write_protected("specs/001-x/spec.md").is_some());
1536        // Outside the unit: the normal policy.
1537        assert_eq!(w("src/lib.rs"), Decision::Allow);
1538        assert!(matches!(w("Cargo.toml"), Decision::Approval(_)));
1539        // Without the profile, the spec tree is protected as ever.
1540        let normal = Policy::new(&[], &[]);
1541        assert!(matches!(
1542            normal.classify(
1543                "write_file",
1544                &json!({ "path": "specs/001-x/contracts/cli.md" }),
1545                None
1546            ),
1547            Decision::Deny(_)
1548        ));
1549        // OpenSpec: a change's proposal, tasks and spec deltas are judged.
1550        let o = Policy::new(&[], &[])
1551            .rules(crate::format::Adapter::rules(
1552                &crate::format::openspec::OPENSPEC,
1553            ))
1554            .planning("openspec/changes/add-x");
1555        assert!(o.is_planning_write("openspec/changes/add-x/design.md"));
1556        for judged in ["proposal.md", "tasks.md", "specs/auth/spec.md"] {
1557            assert!(
1558                !o.is_planning_write(&format!("openspec/changes/add-x/{judged}")),
1559                "{judged}"
1560            );
1561        }
1562    }
1563
1564    #[test]
1565    fn the_authoring_profile_writes_spec_kit_artifacts_and_runs_its_scripts_only() {
1566        let p = Policy::new(&[], &[]).authoring();
1567        let w = |path: &str| p.classify("write_file", &json!({ "path": path }), None);
1568        assert_eq!(w("specs/002-login/spec.md"), Decision::Allow);
1569        assert_eq!(w(".specify/feature.json"), Decision::Allow);
1570        assert_eq!(w(".specify/memory/constitution.md"), Decision::Allow);
1571        assert!(matches!(
1572            w(".specify/scripts/bash/common.sh"),
1573            Decision::Deny(_)
1574        ));
1575        assert!(matches!(
1576            w(".specify/templates/spec-template.md"),
1577            Decision::Deny(_)
1578        ));
1579        assert!(matches!(w("speccoder.toml"), Decision::Deny(_)));
1580        assert!(matches!(w("specs/.env"), Decision::Deny(_)));
1581        // A planning skill writes the spec, never the person's review of it.
1582        assert!(
1583            matches!(w("specs/002-login/review.json"), Decision::Deny(ref why) if why.contains("review")),
1584            "{:?}",
1585            w("specs/002-login/review.json")
1586        );
1587        assert!(p.write_protected("specs/002-login/review.json").is_some());
1588        assert!(matches!(w("src/lib.rs"), Decision::Approval(_)));
1589        let run = |argv: &[&str]| p.classify("run_command", &json!({ "argv": argv }), None);
1590        assert_eq!(
1591            run(&[".specify/scripts/bash/setup-plan.sh", "--json"]),
1592            Decision::Allow
1593        );
1594        assert_eq!(
1595            run(&[
1596                "bash",
1597                "./.specify/scripts/bash/check-prerequisites.sh",
1598                "--json"
1599            ]),
1600            Decision::Allow
1601        );
1602        assert!(matches!(
1603            run(&["bash", ".specify/scripts/bash/../../evil.sh"]),
1604            Decision::Approval(_)
1605        ));
1606        assert_eq!(
1607            run(&[
1608                "bash",
1609                ".specify/extensions/git/scripts/bash/create-new-feature-branch.sh",
1610                "--json"
1611            ]),
1612            Decision::Allow
1613        );
1614        assert!(matches!(
1615            run(&["bash", ".specify/extensions/git/other.sh"]),
1616            Decision::Approval(_)
1617        ));
1618        assert!(matches!(
1619            run(&["bash", "-c", "rm -rf /"]),
1620            Decision::Approval(_)
1621        ));
1622        // Outside the profile, the spec stays protected.
1623        assert!(matches!(
1624            Policy::new(&[], &[]).classify(
1625                "write_file",
1626                &json!({ "path": "specs/002-login/spec.md" }),
1627                None
1628            ),
1629            Decision::Deny(_)
1630        ));
1631    }
1632
1633    #[test]
1634    fn asking_for_the_network_needs_a_person_unless_allowed() {
1635        let checks = [vec!["cargo".to_owned(), "test".to_owned()]];
1636        let p = Policy::new(&checks, &[]);
1637        let net = json!({ "argv": ["cargo", "test"], "network": true });
1638        assert!(matches!(
1639            p.classify("run_command", &net, None),
1640            Decision::Approval(_)
1641        ));
1642        // Without the network the same command is allowed; a denial stays one.
1643        assert_eq!(
1644            p.classify("run_command", &json!({ "argv": ["cargo", "test"] }), None),
1645            Decision::Allow
1646        );
1647        assert!(matches!(
1648            p.classify(
1649                "run_command",
1650                &json!({ "argv": ["git", "push"], "network": true }),
1651                None
1652            ),
1653            Decision::Deny(_)
1654        ));
1655        // `[sandbox] network_allow` is exact; a prefix entry extends.
1656        let exact = p
1657            .clone()
1658            .with_network(vec![vec!["cargo".to_owned(), "test".to_owned()]]);
1659        assert_eq!(exact.classify("run_command", &net, None), Decision::Allow);
1660        let longer = json!({ "argv": ["cargo", "test", "--release"], "network": true });
1661        assert!(matches!(
1662            exact.classify("run_command", &longer, None),
1663            Decision::Approval(_)
1664        ));
1665        let bare = p.clone().with_network(vec![vec!["cargo".to_owned()]]);
1666        assert!(matches!(
1667            bare.classify("run_command", &net, None),
1668            Decision::Approval(_)
1669        ));
1670        let prefixed = p.clone().with_network_prefixes(vec![
1671            vec!["cargo".to_owned()],
1672            vec!["cargo".to_owned(), "test".to_owned()],
1673        ]);
1674        assert_eq!(
1675            prefixed.classify("run_command", &longer, None),
1676            Decision::Allow
1677        );
1678        let object = Object::command(
1679            vec!["cargo".to_owned(), "test".to_owned()],
1680            ".".to_owned(),
1681            "/usr/bin/cargo".to_owned(),
1682            true,
1683        );
1684        let approved = Policy::new(&checks, &[]).with_decisions(vec![object.clone()], vec![]);
1685        assert_eq!(
1686            approved.classify("run_command", &net, Some(&object)),
1687            Decision::Allow
1688        );
1689        // The same argv resolving to another executable is another object.
1690        let shadowed = Object::command(
1691            vec!["cargo".to_owned(), "test".to_owned()],
1692            ".".to_owned(),
1693            "/w/bin/cargo".to_owned(),
1694            true,
1695        );
1696        assert!(matches!(
1697            approved.classify("run_command", &net, Some(&shadowed)),
1698            Decision::Approval(_)
1699        ));
1700        assert!(
1701            shadowed
1702                .changed_from(&object)
1703                .is_some_and(|c| c == "executable /usr/bin/cargo → /w/bin/cargo")
1704        );
1705    }
1706
1707    #[test]
1708    fn commands_allow_is_exact_and_prefixes_need_two_elements() {
1709        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1710        let p = Policy::new(&[], &[argv("npm run build")]);
1711        assert_eq!(
1712            p.classify("run_command", &cmd("npm run build"), None),
1713            Decision::Allow
1714        );
1715        for longer in [
1716            "npm run build --script-shell=/tmp/x",
1717            "npm run build x",
1718            "npm run",
1719        ] {
1720            assert!(
1721                matches!(
1722                    p.classify("run_command", &cmd(longer), None),
1723                    Decision::Approval(_)
1724                ),
1725                "{longer}"
1726            );
1727        }
1728        assert_eq!(
1729            p.rule("run_command", &cmd("npm run build"), None),
1730            "exact command `npm run build`"
1731        );
1732        let q = Policy::new(&[], &[]).with_prefixes(vec![argv("npm"), argv("npm run")]);
1733        assert_eq!(
1734            q.classify("run_command", &cmd("npm run build"), None),
1735            Decision::Allow
1736        );
1737        assert_eq!(
1738            q.rule("run_command", &cmd("npm run build"), None),
1739            "allowed prefix `npm run`"
1740        );
1741        // The one-element entry was dropped: a bare program allows anything.
1742        assert!(matches!(
1743            q.classify("run_command", &cmd("npm install x"), None),
1744            Decision::Approval(_)
1745        ));
1746        assert!(
1747            prefix_refusal(&argv("npm")).is_some() && prefix_refusal(&argv("npm run")).is_none()
1748        );
1749        // Fixed rules decide before every list.
1750        let r = Policy::new(&[], &[argv("sh -c ls")]).with_prefixes(vec![argv("git push")]);
1751        assert!(matches!(
1752            r.classify("run_command", &cmd("sh -c ls"), None),
1753            Decision::Approval(_)
1754        ));
1755        assert!(matches!(
1756            r.classify("run_command", &cmd("git push origin"), None),
1757            Decision::Deny(_)
1758        ));
1759    }
1760
1761    #[test]
1762    fn autopilot_never_asks_never_lifts_a_denial_and_names_its_rule() {
1763        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1764        let p = Policy::new(&[], &[argv("cargo test")]).autopilot();
1765        assert!(p.is_autopilot());
1766        // Allowed stays allowed; asking becomes refusing; denied stays denied.
1767        assert_eq!(
1768            p.settle(p.classify("run_command", &cmd("cargo test"), None)),
1769            Decision::Allow
1770        );
1771        assert_eq!(
1772            p.settle(p.classify("run_command", &cmd("cargo add x"), None)),
1773            Decision::Deny(AUTOPILOT_DENIED.to_owned())
1774        );
1775        assert_eq!(
1776            p.rule("run_command", &cmd("cargo add x"), None),
1777            "autopilot"
1778        );
1779        assert!(matches!(
1780            p.settle(p.classify("run_command", &cmd("git push origin"), None)),
1781            Decision::Deny(r) if r != AUTOPILOT_DENIED
1782        ));
1783        // Without autopilot nothing changes.
1784        let q = Policy::new(&[], &[]);
1785        assert!(matches!(
1786            q.settle(q.classify("run_command", &cmd("cargo add x"), None)),
1787            Decision::Approval(_)
1788        ));
1789        // A grant id names exactly one object.
1790        let a = command("make check");
1791        let mut b = a.clone();
1792        if let Object::Command { cwd, .. } = &mut b {
1793            *cwd = "sub".to_owned();
1794        }
1795        assert_ne!(a.grant_id(), b.grant_id());
1796        assert_eq!(a.grant_id(), a.clone().grant_id());
1797        assert_eq!(
1798            path("src/b/x.rs", "src/a/x.rs").grant_id(),
1799            path("src/b/x.rs", "src/b/x.rs").grant_id()
1800        );
1801        assert!(a.grant_id().starts_with("g-") && a.grant_id().len() == 18);
1802    }
1803
1804    proptest::proptest! {
1805        #[test]
1806        fn on_autopilot_no_call_waits_for_a_person(words in proptest::collection::vec("[a-z]{1,6}", 1..4), tool in 0usize..4) {
1807            let p = Policy::new(&[], &[]).autopilot();
1808            let argv: Vec<String> = words.clone();
1809            let (name, args) = match tool {
1810                0 => ("run_command", json!({ "argv": argv })),
1811                1 => ("write_file", json!({ "path": format!("src/{}.rs", words[0]), "content": "" })),
1812                2 => ("write_file", json!({ "path": format!(".github/{}.yml", words[0]), "content": "" })),
1813                _ => ("mcp__x__y", json!({})),
1814            };
1815            let before = Policy::new(&[], &[]).classify(name, &args, None);
1816            let after = p.settle(p.classify(name, &args, None));
1817            proptest::prop_assert!(!matches!(after, Decision::Approval(_)));
1818            if matches!(before, Decision::Deny(_)) {
1819                proptest::prop_assert!(matches!(after, Decision::Deny(_)));
1820            }
1821            if before == Decision::Allow {
1822                proptest::prop_assert_eq!(after, Decision::Allow);
1823            }
1824        }
1825    }
1826
1827    #[test]
1828    fn a_path_object_is_its_canonical_file_whatever_the_spelling() {
1829        assert_eq!(
1830            path("src/b/x.rs", "src/a/x.rs"),
1831            path("src/b/x.rs", "src/b/x.rs")
1832        );
1833        assert_ne!(
1834            path("src/b/x.rs", "src/a/x.rs"),
1835            path("src/a/x.rs", "src/a/x.rs")
1836        );
1837        assert!(
1838            path("src/b/x.rs", "src/a/x.rs")
1839                .changed_from(&path("src/a/x.rs", "src/a/x.rs"))
1840                .is_some_and(|c| c == "resolves to src/b/x.rs, was src/a/x.rs")
1841        );
1842        // Commands differ by every field.
1843        let a = command("make check");
1844        let mut b = a.clone();
1845        if let Object::Command { cwd, .. } = &mut b {
1846            *cwd = "sub".to_owned();
1847        }
1848        assert_ne!(a, b);
1849        assert_eq!(a.class(), Class::Command);
1850        assert!(a.short().starts_with("argv#") && a.short().len() == 17);
1851        // The record round-trips; an older grant shape does not read.
1852        let back: Object = serde_json::from_value(serde_json::to_value(&a).unwrap()).unwrap();
1853        assert_eq!(back, a);
1854        assert!(serde_json::from_value::<Object>(json!({ "kind": "write", "path": "x" })).is_err());
1855        assert!(
1856            serde_json::from_value::<Rejection>(json!({ "grant": { "kind": "path", "canonical": "x", "asked": "x" }, "reason": "r" }))
1857                .is_err()
1858        );
1859    }
1860
1861    #[test]
1862    fn the_grant_path_has_no_pattern() {
1863        // Matching a person's decision is object equality only.
1864        let source = include_str!("policy.rs");
1865        let classify = source
1866            .split("pub fn classify(")
1867            .nth(1)
1868            .and_then(|s| s.split("\n    }\n").next())
1869            .unwrap_or_default();
1870        assert!(!classify.is_empty());
1871        for pattern in ["starts_with", "glob", "prefix"] {
1872            assert!(!classify.contains(pattern), "{pattern} in the grant path");
1873        }
1874    }
1875}