Skip to main content

lean_ctx/core/
capabilities.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashSet;
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
5#[serde(rename_all = "snake_case")]
6pub enum Capability {
7    FsRead,
8    FsWrite,
9    FsDelete,
10    NetOutbound,
11    /// Only the organization's linked Hive (its connection, lease and
12    /// opt-in decide what goes out), never another host.
13    HiveNet,
14    ExecSandbox,
15    ExecUnrestricted,
16    KnowledgeRead,
17    KnowledgeWrite,
18    CrossProject,
19    ConfigWrite,
20    AgentManage,
21}
22
23impl Capability {
24    pub fn display_name(&self) -> &'static str {
25        match self {
26            Self::FsRead => "fs:read",
27            Self::FsWrite => "fs:write",
28            Self::FsDelete => "fs:delete",
29            Self::NetOutbound => "net:outbound",
30            Self::HiveNet => "x-hive:net",
31            Self::ExecSandbox => "exec:sandbox",
32            Self::ExecUnrestricted => "exec:unrestricted",
33            Self::KnowledgeRead => "knowledge:read",
34            Self::KnowledgeWrite => "knowledge:write",
35            Self::CrossProject => "cross_project",
36            Self::ConfigWrite => "config:write",
37            Self::AgentManage => "agent:manage",
38        }
39    }
40}
41
42pub struct CapabilityCheckResult {
43    pub allowed: bool,
44    pub missing: Vec<Capability>,
45}
46
47pub fn required_capabilities(tool_name: &str) -> &'static [Capability] {
48    match tool_name {
49        "ctx_edit" => &[Capability::FsRead, Capability::FsWrite],
50        "ctx_shell" => &[Capability::ExecUnrestricted],
51        "ctx_knowledge" => &[Capability::KnowledgeRead, Capability::KnowledgeWrite],
52        // ctx_share is agent-to-agent handover WITHIN one project: the store is
53        // keyed per project root and push is jailed to it (enterprise#28), so it
54        // is not a cross-project data flow. AgentManage keeps it (like
55        // ctx_handoff) out of read-only roles (reviewer/ci/minimal).
56        "ctx_handoff" | "ctx_share" => &[Capability::KnowledgeRead, Capability::AgentManage],
57        "ctx_agent" | "ctx_work_graph" => &[Capability::AgentManage],
58        "ctx_tasks" => &[Capability::AgentManage, Capability::HiveNet],
59        // Task Compute reads the checkout into a bundle and spends the
60        // workspace's prepaid credit: never from a read-only role.
61        "ctx_compute" => &[
62            Capability::FsRead,
63            Capability::AgentManage,
64            Capability::HiveNet,
65        ],
66        "ctx_session" | "ctx" => &[],
67        _ => &[Capability::FsRead],
68    }
69}
70
71pub fn role_capabilities(role_name: &str) -> HashSet<Capability> {
72    let mut caps = granted_capabilities(role_name);
73    // The Hive release switch (3.12.1): off, no role holds or advertises
74    // the Hive capability, as the Hive tools are withheld.
75    if !crate::core::hive::available_locally() {
76        caps.remove(&Capability::HiveNet);
77    }
78    caps
79}
80
81fn granted_capabilities(role_name: &str) -> HashSet<Capability> {
82    match role_name {
83        "admin" => HashSet::from([
84            Capability::FsRead,
85            Capability::FsWrite,
86            Capability::FsDelete,
87            Capability::NetOutbound,
88            Capability::HiveNet,
89            Capability::ExecSandbox,
90            Capability::ExecUnrestricted,
91            Capability::KnowledgeRead,
92            Capability::KnowledgeWrite,
93            Capability::CrossProject,
94            Capability::ConfigWrite,
95            Capability::AgentManage,
96        ]),
97        "reviewer" | "ci" => HashSet::from([
98            Capability::FsRead,
99            Capability::ExecSandbox,
100            Capability::KnowledgeRead,
101        ]),
102        "minimal" => HashSet::from([Capability::FsRead, Capability::KnowledgeRead]),
103        _ => capabilities_from_role(role_name),
104    }
105}
106
107fn capabilities_from_role(role_name: &str) -> HashSet<Capability> {
108    let Some(role) = crate::core::roles::load_role(role_name) else {
109        return HashSet::from([
110            Capability::FsRead,
111            Capability::FsWrite,
112            Capability::ExecSandbox,
113            Capability::ExecUnrestricted,
114            Capability::KnowledgeRead,
115            Capability::KnowledgeWrite,
116            Capability::AgentManage,
117            Capability::HiveNet,
118        ]);
119    };
120
121    let mut caps = HashSet::new();
122    caps.insert(Capability::FsRead);
123
124    let has_tool = |name: &str| {
125        role.tools.allowed.iter().any(|a| a == "*" || a == name)
126            && !role.tools.denied.iter().any(|d| d == name || d == "*")
127    };
128
129    if has_tool("ctx_edit") {
130        caps.insert(Capability::FsWrite);
131    }
132    if has_tool("ctx_shell") {
133        caps.insert(Capability::ExecSandbox);
134        caps.insert(Capability::ExecUnrestricted);
135    }
136    if has_tool("ctx_knowledge") {
137        caps.insert(Capability::KnowledgeRead);
138        caps.insert(Capability::KnowledgeWrite);
139    }
140    if has_tool("ctx_agent") || has_tool("ctx_handoff") || has_tool("ctx_work_graph") {
141        caps.insert(Capability::AgentManage);
142    }
143    // Hive tasks reach the organization's linked Hive only; the
144    // connection, its lease and the opt-in decide what goes out (C0 1.9 §4).
145    if crate::core::hive::available_locally() && (has_tool("ctx_tasks") || has_tool("ctx_compute"))
146    {
147        caps.insert(Capability::AgentManage);
148        caps.insert(Capability::HiveNet);
149    }
150    if role.io.allow_cross_project_search {
151        caps.insert(Capability::CrossProject);
152    }
153    if role.io.allow_secret_paths {
154        caps.insert(Capability::ConfigWrite);
155    }
156
157    caps
158}
159
160pub fn check_capabilities(role_name: &str, tool_name: &str) -> CapabilityCheckResult {
161    let required = required_capabilities(tool_name);
162    if required.is_empty() {
163        return CapabilityCheckResult {
164            allowed: true,
165            missing: Vec::new(),
166        };
167    }
168    let granted = role_capabilities(role_name);
169    let missing: Vec<Capability> = required
170        .iter()
171        .filter(|c| !granted.contains(c))
172        .copied()
173        .collect();
174    CapabilityCheckResult {
175        allowed: missing.is_empty(),
176        missing,
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn admin_has_all_capabilities() {
186        let caps = role_capabilities("admin");
187        assert!(caps.contains(&Capability::FsRead));
188        assert!(caps.contains(&Capability::FsWrite));
189        assert!(caps.contains(&Capability::FsDelete));
190        assert!(caps.contains(&Capability::NetOutbound));
191        assert!(caps.contains(&Capability::ExecUnrestricted));
192        assert!(caps.contains(&Capability::ConfigWrite));
193        assert!(caps.contains(&Capability::AgentManage));
194    }
195
196    #[test]
197    fn reviewer_cannot_write() {
198        let result = check_capabilities("reviewer", "ctx_edit");
199        assert!(!result.allowed);
200        assert!(result.missing.contains(&Capability::FsWrite));
201    }
202
203    #[test]
204    fn minimal_cannot_shell() {
205        let result = check_capabilities("minimal", "ctx_shell");
206        assert!(!result.allowed);
207        assert!(result.missing.contains(&Capability::ExecUnrestricted));
208    }
209
210    #[test]
211    fn session_always_allowed() {
212        let result = check_capabilities("minimal", "ctx_session");
213        assert!(result.allowed);
214        assert!(result.missing.is_empty(), "{:?}", result.missing);
215    }
216
217    #[test]
218    fn developer_can_edit() {
219        let result = check_capabilities("developer", "ctx_edit");
220        assert!(result.allowed);
221    }
222
223    /// With the Hive release switch off, no role holds the Hive capability.
224    #[test]
225    fn no_role_holds_hive_net_while_hive_is_withheld() {
226        if crate::core::hive::available_locally() {
227            return;
228        }
229        for role in ["admin", "coder", "unknown_role", "reviewer", "minimal"] {
230            assert!(!role_capabilities(role).contains(&Capability::HiveNet));
231        }
232        assert!(!check_capabilities("admin", "ctx_tasks").allowed);
233    }
234
235    /// ctx_tasks works out of the box for the default role (and any role
236    /// that allows it), never for the read-only ones — once the Hive
237    /// switch is on (here: the test preview).
238    #[test]
239    fn tasks_work_for_the_default_role_only_where_allowed() {
240        if crate::test_env::run_in_own_process(
241            "core::capabilities::tests::tasks_work_for_the_default_role_only_where_allowed",
242            &[(crate::core::hive::PREVIEW_ENV, "1")],
243        ) {
244            return;
245        }
246        assert!(check_capabilities("coder", "ctx_tasks").allowed);
247        assert!(check_capabilities("unknown_role", "ctx_tasks").allowed);
248        for read_only in ["reviewer", "ci", "minimal"] {
249            assert!(!check_capabilities(read_only, "ctx_tasks").allowed);
250            assert!(!check_capabilities(read_only, "ctx_compute").allowed);
251        }
252        assert!(check_capabilities("coder", "ctx_compute").allowed);
253        // Hive only: no role but admin reaches other hosts.
254        for role in ["coder", "unknown_role", "reviewer", "minimal"] {
255            assert!(!role_capabilities(role).contains(&Capability::NetOutbound));
256        }
257        assert_eq!(Capability::HiveNet.display_name(), "x-hive:net");
258    }
259
260    #[test]
261    fn unknown_role_gets_defaults() {
262        let result = check_capabilities("unknown_role", "ctx_read");
263        assert!(result.allowed);
264    }
265
266    #[test]
267    fn unknown_tool_requires_fs_read() {
268        let required = required_capabilities("some_unknown_tool");
269        assert_eq!(required, &[Capability::FsRead]);
270    }
271
272    #[test]
273    fn display_names_are_colon_separated() {
274        assert_eq!(Capability::FsRead.display_name(), "fs:read");
275        assert_eq!(
276            Capability::ExecUnrestricted.display_name(),
277            "exec:unrestricted"
278        );
279        assert_eq!(Capability::AgentManage.display_name(), "agent:manage");
280    }
281}