Skip to main content

lean_ctx/core/
roles.rs

1//! Role-based access control for agent governance.
2//!
3//! Roles define what tools an agent can use, shell policy, and resource limits.
4//! Resolution order: Env (`LEAN_CTX_ROLE`) -> Project `.lean-ctx/roles/` -> Global `~/.lean-ctx/roles/` -> Built-in.
5
6use serde::{Deserialize, Serialize};
7use std::collections::{HashMap, HashSet};
8use std::env;
9use std::path::{Path, PathBuf};
10use std::sync::OnceLock;
11
12static ACTIVE_ROLE_NAME: OnceLock<std::sync::Mutex<String>> = OnceLock::new();
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct Role {
16    #[serde(default)]
17    pub role: RoleMeta,
18    #[serde(default)]
19    pub tools: ToolPolicy,
20    #[serde(default)]
21    pub io: IoPolicy,
22    #[serde(default)]
23    pub limits: RoleLimits,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct RoleMeta {
28    #[serde(default)]
29    pub name: String,
30    #[serde(default)]
31    pub inherits: Option<String>,
32    #[serde(default)]
33    pub description: String,
34    #[serde(default = "default_shell_policy")]
35    pub shell_policy: String,
36}
37
38impl Default for RoleMeta {
39    fn default() -> Self {
40        Self {
41            name: String::new(),
42            inherits: None,
43            description: String::new(),
44            shell_policy: default_shell_policy(),
45        }
46    }
47}
48
49fn default_shell_policy() -> String {
50    "track".to_string()
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize, Default)]
54pub struct ToolPolicy {
55    #[serde(default)]
56    pub allowed: Vec<String>,
57    #[serde(default)]
58    pub denied: Vec<String>,
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct RoleLimits {
63    #[serde(default = "default_context_tokens")]
64    pub max_context_tokens: usize,
65    #[serde(default = "default_shell_invocations")]
66    pub max_shell_invocations: usize,
67    #[serde(default = "default_cost_usd")]
68    pub max_cost_usd: f64,
69    #[serde(default = "default_warn_pct")]
70    pub warn_at_percent: u8,
71    #[serde(default = "default_block_pct")]
72    pub block_at_percent: u8,
73}
74
75impl Default for RoleLimits {
76    fn default() -> Self {
77        Self {
78            max_context_tokens: default_context_tokens(),
79            max_shell_invocations: default_shell_invocations(),
80            max_cost_usd: default_cost_usd(),
81            warn_at_percent: default_warn_pct(),
82            block_at_percent: default_block_pct(),
83        }
84    }
85}
86
87fn default_context_tokens() -> usize {
88    200_000
89}
90fn default_shell_invocations() -> usize {
91    100
92}
93fn default_cost_usd() -> f64 {
94    5.0
95}
96fn default_warn_pct() -> u8 {
97    80
98}
99fn default_block_pct() -> u8 {
100    // 255 = effectively never block (would need >255% budget usage)
101    // LeanCTX philosophy: always help, never block. Warnings are enough.
102    // Users can explicitly set block_at_percent: 100 in role config if they want blocking.
103    255
104}
105
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct IoPolicy {
108    /// Boundary enforcement mode for sensitive I/O (warn|enforce).
109    #[serde(default = "default_boundary_mode")]
110    pub boundary_mode: String,
111    /// Allow search to ignore .gitignore and scan everything.
112    #[serde(default)]
113    pub allow_ignore_gitignore: bool,
114    /// Allow reading/indexing secret-like paths (e.g. .env, *.pem).
115    #[serde(default)]
116    pub allow_secret_paths: bool,
117    /// Enable output redaction for tool outputs (admin can disable; non-admin always on).
118    #[serde(default = "default_redact_outputs")]
119    pub redact_outputs: bool,
120    /// Allow cross-project knowledge search (default: false for non-admin roles).
121    #[serde(default)]
122    pub allow_cross_project_search: bool,
123}
124
125fn default_boundary_mode() -> String {
126    "enforce".to_string()
127}
128
129fn default_redact_outputs() -> bool {
130    true
131}
132
133impl Default for IoPolicy {
134    fn default() -> Self {
135        Self {
136            boundary_mode: default_boundary_mode(),
137            allow_ignore_gitignore: false,
138            allow_secret_paths: false,
139            redact_outputs: default_redact_outputs(),
140            allow_cross_project_search: false,
141        }
142    }
143}
144
145impl IoPolicy {
146    fn is_default(&self) -> bool {
147        self.boundary_mode == default_boundary_mode()
148            && !self.allow_ignore_gitignore
149            && !self.allow_secret_paths
150            && self.redact_outputs == default_redact_outputs()
151    }
152}
153
154impl Role {
155    pub fn is_tool_allowed(&self, tool_name: &str) -> bool {
156        if !self.tools.denied.is_empty()
157            && self.tools.denied.iter().any(|d| d == tool_name || d == "*")
158        {
159            return false;
160        }
161        if self.tools.allowed.is_empty() || self.tools.allowed.iter().any(|a| a == "*") {
162            return true;
163        }
164        self.tools.allowed.iter().any(|a| a == tool_name)
165    }
166
167    pub fn is_shell_allowed(&self) -> bool {
168        self.role.shell_policy != "deny"
169    }
170
171    pub fn allowed_tools_set(&self) -> HashSet<String> {
172        if self.tools.allowed.is_empty() || self.tools.allowed.iter().any(|a| a == "*") {
173            return HashSet::new(); // empty = all allowed
174        }
175        self.tools.allowed.iter().cloned().collect()
176    }
177}
178
179// ── Built-in roles ──────────────────────────────────────────────
180
181fn builtin_coder() -> Role {
182    Role {
183        role: RoleMeta {
184            name: "coder".into(),
185            description: "Full access for code implementation".into(),
186            shell_policy: "track".into(),
187            inherits: None,
188        },
189        tools: ToolPolicy {
190            allowed: vec!["*".into()],
191            denied: vec![],
192        },
193        io: IoPolicy::default(),
194        limits: RoleLimits {
195            max_context_tokens: 200_000,
196            max_shell_invocations: 100,
197            max_cost_usd: 5.0,
198            ..Default::default()
199        },
200    }
201}
202
203/// A role used when an inherited source view has closed or lost its authority.
204/// Returning a denying role prevents stale worker state from falling through
205/// to a more permissive process-wide active role.
206pub(crate) fn closed_source_view_role() -> Role {
207    Role {
208        role: RoleMeta {
209            name: "closed-source-view".into(),
210            inherits: None,
211            description: "closed source policy view".into(),
212            shell_policy: "deny".into(),
213        },
214        tools: ToolPolicy {
215            allowed: Vec::new(),
216            denied: vec!["*".into()],
217        },
218        io: IoPolicy::default(),
219        limits: RoleLimits {
220            max_context_tokens: 0,
221            max_shell_invocations: 0,
222            max_cost_usd: 0.0,
223            warn_at_percent: 0,
224            block_at_percent: 0,
225        },
226    }
227}
228
229fn builtin_reviewer() -> Role {
230    Role {
231        role: RoleMeta {
232            name: "reviewer".into(),
233            description: "Read-only access for code review".into(),
234            shell_policy: "track".into(),
235            inherits: None,
236        },
237        tools: ToolPolicy {
238            allowed: vec![
239                "ctx_read".into(),
240                "ctx_multi_read".into(),
241                "ctx_smart_read".into(),
242                "ctx_fill".into(),
243                "ctx_search".into(),
244                "ctx_tree".into(),
245                "ctx_graph".into(),
246                "ctx_architecture".into(),
247                "ctx_analyze".into(),
248                "ctx_diff".into(),
249                "ctx_symbol".into(),
250                "ctx_expand".into(),
251                "ctx_deps".into(),
252                "ctx_review".into(),
253                "ctx_session".into(),
254                "ctx_knowledge".into(),
255                "ctx_semantic_search".into(),
256                "ctx_overview".into(),
257                "ctx_preload".into(),
258                "ctx_metrics".into(),
259                "ctx_cost".into(),
260                "ctx_gain".into(),
261            ],
262            denied: vec!["ctx_edit".into(), "ctx_shell".into(), "ctx_execute".into()],
263        },
264        io: IoPolicy {
265            boundary_mode: "enforce".into(),
266            ..Default::default()
267        },
268        limits: RoleLimits {
269            max_context_tokens: 150_000,
270            max_shell_invocations: 0,
271            max_cost_usd: 3.0,
272            ..Default::default()
273        },
274    }
275}
276
277fn builtin_debugger() -> Role {
278    Role {
279        role: RoleMeta {
280            name: "debugger".into(),
281            description: "Debug-focused with shell access".into(),
282            shell_policy: "track".into(),
283            inherits: None,
284        },
285        tools: ToolPolicy {
286            allowed: vec!["*".into()],
287            denied: vec![],
288        },
289        io: IoPolicy::default(),
290        limits: RoleLimits {
291            max_context_tokens: 150_000,
292            max_shell_invocations: 200,
293            max_cost_usd: 5.0,
294            ..Default::default()
295        },
296    }
297}
298
299fn builtin_ops() -> Role {
300    Role {
301        role: RoleMeta {
302            name: "ops".into(),
303            description: "Infrastructure and CI/CD operations".into(),
304            shell_policy: "compress".into(),
305            inherits: None,
306        },
307        tools: ToolPolicy {
308            allowed: vec![
309                "ctx_read".into(),
310                "ctx_shell".into(),
311                "ctx_search".into(),
312                "ctx_tree".into(),
313                "ctx_session".into(),
314                "ctx_knowledge".into(),
315                "ctx_overview".into(),
316                "ctx_metrics".into(),
317                "ctx_cost".into(),
318            ],
319            denied: vec!["ctx_edit".into()],
320        },
321        io: IoPolicy::default(),
322        limits: RoleLimits {
323            max_context_tokens: 100_000,
324            max_shell_invocations: 300,
325            max_cost_usd: 3.0,
326            ..Default::default()
327        },
328    }
329}
330
331fn builtin_admin() -> Role {
332    Role {
333        role: RoleMeta {
334            name: "admin".into(),
335            description: "Unrestricted access, all tools and unlimited budgets".into(),
336            shell_policy: "track".into(),
337            inherits: None,
338        },
339        tools: ToolPolicy {
340            allowed: vec!["*".into()],
341            denied: vec![],
342        },
343        io: IoPolicy {
344            boundary_mode: "enforce".into(),
345            allow_ignore_gitignore: true,
346            allow_secret_paths: true,
347            redact_outputs: true,
348            allow_cross_project_search: true,
349        },
350        limits: RoleLimits {
351            max_context_tokens: 500_000,
352            max_shell_invocations: 500,
353            max_cost_usd: 50.0,
354            warn_at_percent: 90,
355            ..Default::default() // block_at_percent: 255 (never block)
356        },
357    }
358}
359
360fn builtin_roles() -> HashMap<String, Role> {
361    let mut m = HashMap::new();
362    m.insert("coder".into(), builtin_coder());
363    m.insert("reviewer".into(), builtin_reviewer());
364    m.insert("debugger".into(), builtin_debugger());
365    m.insert("ops".into(), builtin_ops());
366    m.insert("admin".into(), builtin_admin());
367    m
368}
369
370// ── Disk loading ────────────────────────────────────────────────
371
372fn roles_dir_global() -> Option<PathBuf> {
373    crate::core::data_dir::lean_ctx_data_dir()
374        .ok()
375        .map(|d| d.join("roles"))
376}
377
378fn roles_dir_project() -> Option<PathBuf> {
379    match crate::core::policy::runtime::REQUEST_PROJECT.try_with(|slot| slot.borrow().clone()) {
380        Ok(Some(project_root)) => {
381            let candidate = project_root.join(".lean-ctx").join("roles");
382            candidate.is_dir().then_some(candidate)
383        }
384        // An explicit unbound scope must not fall back to the process CWD.
385        Ok(None) => None,
386        Err(_) => roles_dir_project_from(None),
387    }
388}
389
390fn roles_dir_project_from(project_root: Option<&str>) -> Option<PathBuf> {
391    if let Some(root) = project_root {
392        let candidate = PathBuf::from(root).join(".lean-ctx").join("roles");
393        if candidate.is_dir() {
394            return Some(candidate);
395        }
396    }
397    let mut dir = std::env::current_dir().ok()?;
398    loop {
399        let candidate = dir.join(".lean-ctx").join("roles");
400        if candidate.is_dir() {
401            return Some(candidate);
402        }
403        if !dir.pop() {
404            break;
405        }
406    }
407    None
408}
409
410fn try_load_toml(path: &Path) -> Option<Role> {
411    let content = std::fs::read_to_string(path).ok()?;
412    toml::from_str(&content).ok()
413}
414
415fn load_role_from_disk(name: &str) -> Option<Role> {
416    if !is_valid_role_name(name) {
417        tracing::warn!(
418            "[SECURITY] Invalid role name rejected (path-traversal/special chars): {name}"
419        );
420        return None;
421    }
422
423    let filename = format!("{name}.toml");
424    if let Some(dir) = roles_dir_project() {
425        let path = dir.join(&filename);
426        if path.exists() {
427            if RESERVED_ROLE_NAMES
428                .iter()
429                .any(|r| r.eq_ignore_ascii_case(name))
430            {
431                tracing::warn!(
432                    "[SECURITY] Project-level shadowing of reserved role '{name}' ignored. \
433                     Use global ~/.lean-ctx/roles/ to customize built-in roles."
434                );
435            } else if let Some(mut r) = try_load_toml(&path) {
436                r.role.name = name.to_string();
437                return Some(r);
438            }
439        }
440    }
441    if let Some(dir) = roles_dir_global() {
442        let path = dir.join(&filename);
443        if let Some(mut r) = try_load_toml(&path) {
444            r.role.name = name.to_string();
445            return Some(r);
446        }
447    }
448    None
449}
450
451fn merge_roles(parent: &Role, child: &Role) -> Role {
452    Role {
453        role: RoleMeta {
454            name: child.role.name.clone(),
455            inherits: child.role.inherits.clone(),
456            description: if child.role.description.is_empty() {
457                parent.role.description.clone()
458            } else {
459                child.role.description.clone()
460            },
461            shell_policy: if child.role.shell_policy == default_shell_policy()
462                && parent.role.shell_policy != default_shell_policy()
463            {
464                parent.role.shell_policy.clone()
465            } else {
466                child.role.shell_policy.clone()
467            },
468        },
469        tools: if child.tools.allowed.is_empty() && child.tools.denied.is_empty() {
470            parent.tools.clone()
471        } else {
472            child.tools.clone()
473        },
474        io: if child.io.is_default() && !parent.io.is_default() {
475            parent.io.clone()
476        } else {
477            child.io.clone()
478        },
479        limits: RoleLimits {
480            max_context_tokens: child.limits.max_context_tokens,
481            max_shell_invocations: child.limits.max_shell_invocations,
482            max_cost_usd: child.limits.max_cost_usd,
483            warn_at_percent: child.limits.warn_at_percent,
484            block_at_percent: child.limits.block_at_percent,
485        },
486    }
487}
488
489fn load_role_recursive(name: &str, visited: &mut HashSet<String>) -> Option<Role> {
490    if !visited.insert(name.to_string()) {
491        tracing::warn!("[SECURITY] Circular role inheritance detected at '{name}'");
492        return None;
493    }
494    let role = load_role_from_disk(name).or_else(|| builtin_roles().remove(name))?;
495    if let Some(parent_name) = &role.role.inherits {
496        if is_privileged_role(parent_name) && roles_dir_project().is_some() {
497            let is_from_project =
498                roles_dir_project().is_some_and(|d| d.join(format!("{name}.toml")).exists());
499            if is_from_project {
500                tracing::warn!(
501                    "[SECURITY] Project-level role '{name}' inheriting from privileged \
502                     role '{parent_name}' is blocked."
503                );
504                return None;
505            }
506        }
507        if let Some(parent) = load_role_recursive(parent_name, visited) {
508            return Some(merge_roles(&parent, &role));
509        }
510    }
511    Some(role)
512}
513
514// ── Public API ──────────────────────────────────────────────────
515
516pub fn load_role(name: &str) -> Option<Role> {
517    let mut visited = HashSet::new();
518    load_role_recursive(name, &mut visited)
519}
520
521pub fn active_role_name() -> String {
522    let lock = ACTIVE_ROLE_NAME.get_or_init(|| std::sync::Mutex::new(String::new()));
523    let mut guard = lock
524        .lock()
525        .unwrap_or_else(std::sync::PoisonError::into_inner);
526
527    if guard.is_empty() {
528        let from_env = env::var("LEAN_CTX_ROLE")
529            .ok()
530            .map(|s| s.trim().to_string())
531            .filter(|s| !s.is_empty());
532        *guard = from_env.unwrap_or_else(|| "coder".to_string());
533    }
534
535    guard.clone()
536}
537
538pub fn active_role() -> Role {
539    if let Some(role) = crate::core::policy::runtime::pinned_role() {
540        return role;
541    }
542    #[cfg(test)]
543    if let Ok(Some(role)) = TEST_ACTIVE_ROLE.try_with(|slot| slot.borrow().clone()) {
544        return role;
545    }
546    let name = active_role_name();
547    load_role(&name).unwrap_or_else(builtin_coder)
548}
549
550#[cfg(test)]
551tokio::task_local! {
552    static TEST_ACTIVE_ROLE: std::cell::RefCell<Option<Role>>;
553}
554
555#[cfg(test)]
556pub(crate) fn with_test_active_role<T>(role: Role, operation: impl FnOnce() -> T) -> T {
557    TEST_ACTIVE_ROLE.sync_scope(std::cell::RefCell::new(Some(role)), operation)
558}
559
560#[cfg(test)]
561pub(crate) fn set_test_active_role(role: Role) {
562    TEST_ACTIVE_ROLE.with(|slot| *slot.borrow_mut() = Some(role));
563}
564
565/// Roles that grant elevated privileges and cannot be activated via MCP tool calls.
566/// These roles must be set via env var (`LEAN_CTX_ROLE`) or config file.
567const PRIVILEGED_ROLES: &[&str] = &["admin", "ops"];
568
569/// Reserved role names that cannot be shadowed from project-level config.
570const RESERVED_ROLE_NAMES: &[&str] = &["coder", "reviewer", "debugger", "ops", "admin"];
571
572/// Returns true if the named role has elevated privileges that require
573/// explicit configuration (env/config) rather than runtime activation.
574/// Case-insensitive comparison to prevent "Admin" bypass.
575pub fn is_privileged_role(name: &str) -> bool {
576    let lower = name.to_ascii_lowercase();
577    PRIVILEGED_ROLES.iter().any(|p| *p == lower)
578}
579
580/// Validate role name: alphanumeric, underscore, hyphen only. No path traversal.
581fn is_valid_role_name(name: &str) -> bool {
582    !name.is_empty()
583        && name.len() <= 64
584        && name
585            .chars()
586            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
587}
588
589/// Check if a merged role is effectively privileged (wildcard tools + no denials, or secret paths).
590fn is_effectively_privileged(role: &Role) -> bool {
591    let wildcard_tools =
592        role.tools.allowed.iter().any(|a| a == "*") && role.tools.denied.is_empty();
593    wildcard_tools || role.io.allow_secret_paths
594}
595
596pub fn set_active_role(name: &str) -> Result<Role, String> {
597    set_active_role_with_source(name, false)
598}
599
600/// Set active role. `from_config` = true allows privileged roles (env/config startup).
601pub fn set_active_role_with_source(name: &str, from_config: bool) -> Result<Role, String> {
602    if !is_valid_role_name(name) {
603        return Err(format!(
604            "[SECURITY] Invalid role name '{name}'. Only alphanumeric, underscore, and hyphen allowed."
605        ));
606    }
607
608    let role = load_role(name).ok_or_else(|| format!("Role '{name}' not found"))?;
609
610    if !from_config && is_privileged_role(name) {
611        return Err(format!(
612            "[SECURITY] Cannot escalate to privileged role '{name}' at runtime. \
613             Set LEAN_CTX_ROLE={name} in your environment or config to use this role."
614        ));
615    }
616
617    let is_builtin = builtin_roles().contains_key(name);
618    if !from_config && !is_builtin && is_effectively_privileged(&role) {
619        return Err(format!(
620            "[SECURITY] Cannot activate role '{name}' at runtime: it has effectively \
621             privileged permissions (wildcard tools or secret path access). \
622             Set LEAN_CTX_ROLE={name} in environment or config."
623        ));
624    }
625
626    let prev = active_role_name();
627    let lock = ACTIVE_ROLE_NAME.get_or_init(|| std::sync::Mutex::new("coder".to_string()));
628    match lock.lock() {
629        Ok(mut g) => *g = name.to_string(),
630        Err(poisoned) => *poisoned.into_inner() = name.to_string(),
631    }
632    if prev != name {
633        crate::core::events::emit_role_changed(&prev, name);
634    }
635    Ok(role)
636}
637
638pub fn list_roles() -> Vec<RoleInfo> {
639    let active = active_role_name();
640    let builtins = builtin_roles();
641    let mut seen = HashSet::new();
642    let mut result = Vec::new();
643
644    for dir in [roles_dir_project(), roles_dir_global()]
645        .into_iter()
646        .flatten()
647    {
648        if let Ok(entries) = std::fs::read_dir(&dir) {
649            for entry in entries.flatten() {
650                let path = entry.path();
651                if path.extension().is_some_and(|e| e == "toml")
652                    && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
653                    && seen.insert(stem.to_string())
654                    && let Some(r) = load_role(stem)
655                {
656                    result.push(RoleInfo {
657                        name: stem.to_string(),
658                        source: if dir == roles_dir_project().unwrap_or_default() {
659                            RoleSource::Project
660                        } else {
661                            RoleSource::Global
662                        },
663                        description: r.role.description.clone(),
664                        is_active: stem == active,
665                    });
666                }
667            }
668        }
669    }
670
671    for (name, r) in &builtins {
672        if seen.insert(name.clone()) {
673            result.push(RoleInfo {
674                name: name.clone(),
675                source: RoleSource::BuiltIn,
676                description: r.role.description.clone(),
677                is_active: name == &active,
678            });
679        }
680    }
681
682    result.sort_by_key(|r| r.name.clone());
683    result
684}
685
686#[derive(Debug, Clone)]
687pub struct RoleInfo {
688    pub name: String,
689    pub source: RoleSource,
690    pub description: String,
691    pub is_active: bool,
692}
693
694#[derive(Debug, Clone, PartialEq)]
695pub enum RoleSource {
696    BuiltIn,
697    Project,
698    Global,
699}
700
701impl std::fmt::Display for RoleSource {
702    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
703        match self {
704            Self::BuiltIn => write!(f, "built-in"),
705            Self::Project => write!(f, "project"),
706            Self::Global => write!(f, "global"),
707        }
708    }
709}
710
711// ── Tests ───────────────────────────────────────────────────────
712
713#[cfg(test)]
714pub mod tests {
715    use super::*;
716
717    #[test]
718    fn builtin_count() {
719        assert_eq!(builtin_roles().len(), 5);
720    }
721
722    #[test]
723    fn coder_allows_all() {
724        let r = builtin_coder();
725        assert!(r.is_tool_allowed("ctx_read"));
726        assert!(r.is_tool_allowed("ctx_edit"));
727        assert!(r.is_tool_allowed("ctx_shell"));
728        assert!(r.is_tool_allowed("anything"));
729    }
730
731    #[test]
732    fn reviewer_denies_edits() {
733        let r = builtin_reviewer();
734        assert!(r.is_tool_allowed("ctx_read"));
735        assert!(r.is_tool_allowed("ctx_review"));
736        assert!(!r.is_tool_allowed("ctx_edit"));
737        assert!(!r.is_tool_allowed("ctx_shell"));
738        assert!(!r.is_tool_allowed("ctx_execute"));
739    }
740
741    #[test]
742    fn reviewer_no_shell() {
743        let r = builtin_reviewer();
744        assert_eq!(r.limits.max_shell_invocations, 0);
745    }
746
747    #[test]
748    fn ops_denies_edit() {
749        let r = builtin_ops();
750        assert!(!r.is_tool_allowed("ctx_edit"));
751        assert!(r.is_tool_allowed("ctx_shell"));
752        assert!(r.is_shell_allowed());
753    }
754
755    #[test]
756    fn admin_unlimited() {
757        let r = builtin_admin();
758        assert!(r.is_tool_allowed("ctx_edit"));
759        assert!(r.is_tool_allowed("ctx_shell"));
760        assert_eq!(r.limits.max_context_tokens, 500_000);
761        assert_eq!(r.limits.max_cost_usd, 50.0);
762    }
763
764    #[test]
765    fn denied_overrides_allowed() {
766        let r = Role {
767            role: RoleMeta {
768                name: "test".into(),
769                ..Default::default()
770            },
771            tools: ToolPolicy {
772                allowed: vec!["*".into()],
773                denied: vec!["ctx_edit".into()],
774            },
775            io: IoPolicy::default(),
776            limits: RoleLimits::default(),
777        };
778        assert!(r.is_tool_allowed("ctx_read"));
779        assert!(!r.is_tool_allowed("ctx_edit"));
780    }
781
782    #[test]
783    fn shell_deny_policy() {
784        let r = Role {
785            role: RoleMeta {
786                name: "noshell".into(),
787                shell_policy: "deny".into(),
788                ..Default::default()
789            },
790            tools: ToolPolicy::default(),
791            io: IoPolicy::default(),
792            limits: RoleLimits::default(),
793        };
794        assert!(!r.is_shell_allowed());
795    }
796
797    #[test]
798    fn load_builtin_by_name() {
799        assert!(load_role("coder").is_some());
800        assert!(load_role("reviewer").is_some());
801        assert!(load_role("debugger").is_some());
802        assert!(load_role("ops").is_some());
803        assert!(load_role("admin").is_some());
804        assert!(load_role("nonexistent").is_none());
805    }
806
807    #[test]
808    fn merge_inherits_parent_tools() {
809        let parent = builtin_reviewer();
810        let child = Role {
811            role: RoleMeta {
812                name: "custom".into(),
813                inherits: Some("reviewer".into()),
814                description: "Custom reviewer".into(),
815                ..Default::default()
816            },
817            tools: ToolPolicy::default(),
818            io: IoPolicy::default(),
819            limits: RoleLimits {
820                max_context_tokens: 50_000,
821                ..Default::default()
822            },
823        };
824        let merged = merge_roles(&parent, &child);
825        assert_eq!(merged.role.name, "custom");
826        assert_eq!(merged.role.description, "Custom reviewer");
827        assert!(!merged.is_tool_allowed("ctx_edit"));
828        assert_eq!(merged.limits.max_context_tokens, 50_000);
829    }
830
831    #[test]
832    fn default_role_is_coder() {
833        let name = active_role_name();
834        assert!(!name.is_empty());
835    }
836
837    #[test]
838    fn list_roles_includes_builtins() {
839        let roles = list_roles();
840        let names: Vec<_> = roles.iter().map(|r| r.name.as_str()).collect();
841        assert!(names.contains(&"coder"));
842        assert!(names.contains(&"reviewer"));
843        assert!(names.contains(&"admin"));
844    }
845
846    #[test]
847    fn warn_and_block_thresholds() {
848        let r = builtin_coder();
849        assert_eq!(r.limits.warn_at_percent, 80);
850        // 255 = never block (LeanCTX philosophy: always help, never block)
851        assert_eq!(r.limits.block_at_percent, 255);
852    }
853
854    #[test]
855    fn runtime_escalation_to_admin_blocked() {
856        let result = set_active_role("admin");
857        assert!(
858            result.is_err(),
859            "runtime escalation to admin must be blocked"
860        );
861        let err = result.unwrap_err();
862        assert!(
863            err.contains("SECURITY"),
864            "error must indicate security: {err}"
865        );
866    }
867
868    #[test]
869    fn runtime_escalation_to_ops_blocked() {
870        let result = set_active_role("ops");
871        assert!(result.is_err(), "runtime escalation to ops must be blocked");
872    }
873
874    #[test]
875    fn config_escalation_to_admin_allowed() {
876        let result = set_active_role_with_source("admin", true);
877        assert!(
878            result.is_ok(),
879            "config-source escalation to admin must work"
880        );
881    }
882
883    #[test]
884    fn runtime_switch_to_coder_allowed() {
885        let result = set_active_role("coder");
886        assert!(result.is_ok(), "switching to coder must always work");
887    }
888
889    #[test]
890    fn runtime_switch_to_reviewer_allowed() {
891        let result = set_active_role("reviewer");
892        assert!(result.is_ok(), "switching to reviewer must always work");
893    }
894
895    #[test]
896    fn privileged_roles_detected() {
897        assert!(is_privileged_role("admin"));
898        assert!(is_privileged_role("ops"));
899        assert!(!is_privileged_role("coder"));
900        assert!(!is_privileged_role("reviewer"));
901        assert!(!is_privileged_role("debugger"));
902    }
903
904    // --- Phase 2 V2: Role name validation ---
905
906    #[test]
907    fn valid_role_names() {
908        assert!(is_valid_role_name("coder"));
909        assert!(is_valid_role_name("my-custom-role"));
910        assert!(is_valid_role_name("Role_123"));
911        assert!(is_valid_role_name("ADMIN"));
912    }
913
914    #[test]
915    fn invalid_role_names() {
916        assert!(!is_valid_role_name(""));
917        assert!(!is_valid_role_name("../../evil"));
918        assert!(!is_valid_role_name("role with spaces"));
919        assert!(!is_valid_role_name("role;drop"));
920        assert!(!is_valid_role_name("a".repeat(65).as_str()));
921    }
922
923    #[test]
924    fn case_insensitive_privileged_check() {
925        assert!(is_privileged_role("Admin"));
926        assert!(is_privileged_role("ADMIN"));
927        assert!(is_privileged_role("Ops"));
928        assert!(is_privileged_role("OPS"));
929    }
930
931    #[test]
932    fn invalid_role_name_rejected_at_set() {
933        let result = set_active_role("../../evil");
934        assert!(result.is_err());
935        assert!(result.unwrap_err().contains("Invalid role name"));
936    }
937
938    #[test]
939    fn effectively_privileged_role_blocked_at_runtime() {
940        let role = Role {
941            role: RoleMeta {
942                name: "sneaky".into(),
943                ..Default::default()
944            },
945            tools: ToolPolicy {
946                allowed: vec!["*".into()],
947                denied: vec![],
948            },
949            io: IoPolicy::default(),
950            limits: RoleLimits::default(),
951        };
952        assert!(
953            is_effectively_privileged(&role),
954            "wildcard + no denials = effectively privileged"
955        );
956    }
957
958    #[test]
959    fn debugger_runtime_switch_allowed() {
960        let result = set_active_role("debugger");
961        assert!(
962            result.is_ok(),
963            "built-in debugger must be activatable at runtime"
964        );
965    }
966}