godmode-core 0.8.1

Core library for godmode: task graphs, session state, dispatch, and Claude Code plugin integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
// TODO(rustqual,#90): split policy.rs (395 lines) by SRP — three distinct responsibilities:
//   1. policy_loader.rs  — YAML loading, path resolution, default/category/agent layering
//   2. policy_engine.rs  — resolve(), check(), audit() enforcement logic
//   3. policy.rs         — public types (GovernanceLevel, Policy, PolicyRule, AuditEvent)
//! Governance policy engine — loads, composes, and enforces agent policies.
//!
//! Policies live in `skills/agent-governance/policies/`:
//!   - `default.yaml` — baseline all agents inherit
//!   - `by-category/<cat>.yaml` — per-category overrides
//!   - `levels/<level>.yaml` — governance level overlays
//!
//! Composition follows most-restrictive-wins: blocked lists union,
//! allowed lists intersect, rate limits take minimum.

use std::collections::HashMap;

use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};

#[path = "policy_engine.rs"]
pub mod policy_engine;
#[path = "policy_loader.rs"]
pub mod policy_loader;

pub use policy_engine::{GovernanceEvent, check_tool, emit_audit_event, read_audit_events};
pub use policy_loader::{agent_category, list_policies, resolve};

// ── Types ────────────────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PolicyAction {
    Allow,
    Deny,
    Review,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GovernanceLevel {
    Open,
    Standard,
    Strict,
    Locked,
}

impl GovernanceLevel {
    /// Returns the lowercase governance-level name.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Open => "open",
            Self::Standard => "standard",
            Self::Strict => "strict",
            Self::Locked => "locked",
        }
    }
}

impl std::fmt::Display for GovernanceLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for GovernanceLevel {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> Result<Self> {
        match s.to_lowercase().as_str() {
            "open" => Ok(Self::Open),
            "standard" => Ok(Self::Standard),
            "strict" => Ok(Self::Strict),
            "locked" => Ok(Self::Locked),
            other => bail!("unknown governance level: {other}"),
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct SubagentConstraints {
    pub max_concurrent: usize,
    pub must_verify_branch: bool,
    pub no_commit_to_main: bool,
    pub max_retries_on_failure: usize,
    pub require_commit_before_done: bool,
    pub blocked_flags: Vec<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct AuditSettings {
    pub enabled: bool,
    pub format: String,
    pub path: String,
    pub log_allowed: bool,
    pub log_denied: bool,
    pub log_reviews: bool,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct GovernancePolicy {
    pub name: String,
    #[serde(default)]
    pub level: String,
    #[serde(default)]
    pub category: String,
    #[serde(default)]
    pub inherits: String,
    #[serde(default)]
    pub allowed_tools: Vec<String>,
    #[serde(default)]
    pub blocked_tools: Vec<String>,
    #[serde(default)]
    pub blocked_patterns: Vec<String>,
    #[serde(default = "default_max_calls")]
    pub max_calls_per_dispatch: usize,
    #[serde(default)]
    pub require_human_approval: Vec<String>,
    #[serde(default)]
    pub subagent: SubagentConstraints,
    #[serde(default)]
    pub audit: AuditSettings,
}

pub(crate) fn default_max_calls() -> usize {
    200
}

/// Result of resolving a policy for an agent.
#[derive(Debug, Clone, Serialize)]
pub struct ResolvedPolicy {
    pub policy: GovernancePolicy,
    pub agent: String,
    pub category: String,
    pub level: String,
    pub sources: Vec<String>,
}

/// Result of checking a tool call against a policy.
#[derive(Debug, Clone, Serialize)]
pub struct CheckResult {
    pub action: PolicyAction,
    pub reason: String,
}

#[derive(Debug, Serialize)]
pub struct PolicyIndex {
    pub default: Option<GovernancePolicy>,
    pub categories: HashMap<String, GovernancePolicy>,
    pub levels: HashMap<String, GovernancePolicy>,
}

/// How to apply an overlay's allowed_tools.
#[derive(Clone, Copy)]
pub(crate) enum AllowedToolsMode {
    /// Category overlays replace allowed_tools (specialization).
    Replace,
    /// Level overlays intersect allowed_tools (restriction).
    Intersect,
}

#[cfg(test)]
mod tests {
    use super::policy_engine::GovernanceEvent;
    use super::*;
    use tempfile::TempDir;

    fn write_policy(dir: &std::path::Path, rel: &str, content: &str) {
        let path = dir.join(rel);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(path, content).unwrap();
    }

    fn setup_policies(tmp: &std::path::Path) {
        let policies = tmp.join("skills").join("agent-governance").join("policies");

        write_policy(
            &policies,
            "default.yaml",
            r#"
name: default
level: standard
allowed_tools: [Read, Write, Edit, Bash, Glob, Grep]
blocked_tools: []
blocked_patterns:
  - "(?i)--no-verify"
max_calls_per_dispatch: 200
require_human_approval: []
subagent:
  max_concurrent: 5
  must_verify_branch: true
  no_commit_to_main: true
  max_retries_on_failure: 3
  require_commit_before_done: true
  blocked_flags: ["--no-verify"]
"#,
        );

        write_policy(
            &policies,
            "by-category/plan.yaml",
            r#"
name: category-plan
category: plan
allowed_tools: [Read, Write, Glob, Grep]
blocked_tools: [Bash, Agent]
blocked_patterns:
  - "(?i)cargo\\s+(build|test|run)"
max_calls_per_dispatch: 150
"#,
        );

        write_policy(
            &policies,
            "levels/strict.yaml",
            r#"
name: level-strict
level: strict
allowed_tools: [Read, Glob, Grep]
blocked_tools: [Agent]
max_calls_per_dispatch: 50
require_human_approval: [Write, Edit, Bash]
subagent:
  max_concurrent: 2
  must_verify_branch: true
  no_commit_to_main: true
  max_retries_on_failure: 1
  require_commit_before_done: true
"#,
        );

        write_policy(
            &policies,
            "by-category/blocked.yaml",
            r#"
name: category-blocked
category: blocked
subagent:
  max_concurrent: 0
  max_retries_on_failure: 0
"#,
        );

        let cfg_dir = tmp.join("agents").join("cfg");
        std::fs::create_dir_all(&cfg_dir).unwrap();
        std::fs::write(
            cfg_dir.join("test-planner.cfg.yaml"),
            "name: test-planner\ncategory: plan\n",
        )
        .unwrap();
        std::fs::write(
            cfg_dir.join("blocked-agent.cfg.yaml"),
            "name: blocked-agent\ncategory: blocked\n",
        )
        .unwrap();
    }

    #[test]
    fn default_max_calls_is_stable() {
        assert_eq!(default_max_calls(), 200);
    }

    #[test]
    fn resolve_default_policy() {
        let tmp = TempDir::new().unwrap();
        setup_policies(tmp.path());
        let resolved = resolve(tmp.path(), "unknown-agent", None).unwrap();
        assert_eq!(resolved.level, "standard");
        assert_eq!(resolved.sources, vec!["default.yaml"]);
        assert!(resolved.policy.allowed_tools.contains(&"Bash".to_string()));
    }

    #[test]
    fn resolve_with_category() {
        let tmp = TempDir::new().unwrap();
        setup_policies(tmp.path());
        let resolved = resolve(tmp.path(), "test-planner", None).unwrap();
        assert_eq!(resolved.category, "plan");
        assert!(
            resolved
                .sources
                .contains(&"by-category/plan.yaml".to_string())
        );
        assert!(!resolved.policy.allowed_tools.contains(&"Bash".to_string()));
        assert!(resolved.policy.blocked_tools.contains(&"Bash".to_string()));
        assert!(resolved.policy.blocked_tools.contains(&"Agent".to_string()));
        assert_eq!(resolved.policy.max_calls_per_dispatch, 150);
        assert_eq!(resolved.policy.subagent.max_concurrent, 5);
        assert_eq!(resolved.policy.subagent.max_retries_on_failure, 3);
    }

    #[test]
    fn resolve_with_level_override() {
        let tmp = TempDir::new().unwrap();
        setup_policies(tmp.path());
        let resolved =
            resolve(tmp.path(), "unknown-agent", Some(&GovernanceLevel::Strict)).unwrap();
        assert_eq!(resolved.level, "strict");
        assert!(!resolved.policy.allowed_tools.contains(&"Bash".to_string()));
        assert!(resolved.policy.allowed_tools.contains(&"Read".to_string()));
        assert!(
            resolved
                .policy
                .require_human_approval
                .contains(&"Write".to_string())
        );
        assert_eq!(resolved.policy.max_calls_per_dispatch, 50);
        assert_eq!(resolved.policy.subagent.max_concurrent, 2);
        assert_eq!(resolved.policy.subagent.max_retries_on_failure, 1);
    }

    #[test]
    fn resolve_preserves_explicit_zero_subagent_limits() {
        let tmp = TempDir::new().unwrap();
        setup_policies(tmp.path());
        let resolved = resolve(tmp.path(), "blocked-agent", None).unwrap();
        assert_eq!(resolved.policy.subagent.max_concurrent, 0);
        assert_eq!(resolved.policy.subagent.max_retries_on_failure, 0);
    }

    #[test]
    fn check_tool_blocked() {
        let policy = GovernancePolicy {
            blocked_tools: vec!["Agent".to_string()],
            ..Default::default()
        };
        let result = check_tool(&policy, "Agent", None);
        assert_eq!(result.action, PolicyAction::Deny);
    }

    #[test]
    fn check_tool_not_in_allowed() {
        let policy = GovernancePolicy {
            allowed_tools: vec!["Read".to_string(), "Grep".to_string()],
            ..Default::default()
        };
        let result = check_tool(&policy, "Bash", None);
        assert_eq!(result.action, PolicyAction::Deny);
    }

    #[test]
    fn check_tool_requires_approval() {
        let policy = GovernancePolicy {
            require_human_approval: vec!["Write".to_string()],
            ..Default::default()
        };
        let result = check_tool(&policy, "Write", None);
        assert_eq!(result.action, PolicyAction::Review);
    }

    #[test]
    fn check_tool_wildcard_approval() {
        let policy = GovernancePolicy {
            require_human_approval: vec!["*".to_string()],
            ..Default::default()
        };
        let result = check_tool(&policy, "Bash", None);
        assert_eq!(result.action, PolicyAction::Review);
    }

    #[test]
    fn check_tool_content_pattern() {
        let policy = GovernancePolicy {
            blocked_patterns: vec!["(?i)--no-verify".to_string()],
            ..Default::default()
        };
        let result = check_tool(&policy, "Bash", Some("git commit --no-verify -m 'test'"));
        assert_eq!(result.action, PolicyAction::Deny);
        assert!(result.reason.contains("--no-verify"));
    }

    #[test]
    fn check_tool_allows_clean_content() {
        let policy = GovernancePolicy {
            allowed_tools: vec!["Bash".to_string()],
            blocked_patterns: vec!["(?i)--no-verify".to_string()],
            ..Default::default()
        };
        let result = check_tool(&policy, "Bash", Some("git commit -m 'test'"));
        assert_eq!(result.action, PolicyAction::Allow);
    }

    #[test]
    fn check_tool_command_approval_gates_on_content() {
        // The regression this covers: approval entries are command strings, so
        // comparing them against the tool name alone made every command-level
        // entry in the shipped policies unreachable.
        let policy = GovernancePolicy {
            allowed_tools: vec!["Bash".to_string()],
            require_human_approval: vec!["git push --force".to_string()],
            ..Default::default()
        };
        let gated = check_tool(&policy, "Bash", Some("git push --force origin main"));
        assert_eq!(gated.action, PolicyAction::Review);
        assert!(gated.reason.contains("git push --force"));

        let ungated = check_tool(&policy, "Bash", Some("git push origin main"));
        assert_eq!(ungated.action, PolicyAction::Allow);
    }

    #[test]
    fn check_tool_command_approval_without_content_is_ignored() {
        // No tool input means there is no command to match; the entry must not
        // accidentally gate every call.
        let policy = GovernancePolicy {
            allowed_tools: vec!["Bash".to_string()],
            require_human_approval: vec!["git push --force".to_string()],
            ..Default::default()
        };
        let result = check_tool(&policy, "Bash", None);
        assert_eq!(result.action, PolicyAction::Allow);
    }

    #[test]
    fn check_tool_approval_takes_precedence_over_blocked_pattern() {
        // A command listed in require_human_approval must surface as Review even
        // when a broader blocked pattern also matches it. Both shipped policy
        // sets list e.g. `git push --force` in both lists.
        let policy = GovernancePolicy {
            allowed_tools: vec!["Bash".to_string()],
            blocked_patterns: vec!["(?i)--force".to_string()],
            require_human_approval: vec!["git push --force".to_string()],
            ..Default::default()
        };
        let result = check_tool(&policy, "Bash", Some("git push --force"));
        assert_eq!(result.action, PolicyAction::Review);
    }

    #[test]
    fn check_tool_unlisted_command_still_denied_by_blocked_pattern() {
        // Precedence is scoped to approval entries only — unrelated blocked
        // patterns must keep hard-denying.
        let policy = GovernancePolicy {
            allowed_tools: vec!["Bash".to_string()],
            blocked_patterns: vec!["(?i)--force".to_string()],
            require_human_approval: vec!["git push --force".to_string()],
            ..Default::default()
        };
        let result = check_tool(&policy, "Bash", Some("docker push --force"));
        assert_eq!(result.action, PolicyAction::Deny);
    }

    #[test]
    fn check_tool_wildcard_approval_beats_blocked_pattern() {
        let policy = GovernancePolicy {
            blocked_patterns: vec!["(?i)--no-verify".to_string()],
            require_human_approval: vec!["*".to_string()],
            ..Default::default()
        };
        let result = check_tool(&policy, "Bash", Some("git commit --no-verify"));
        assert_eq!(result.action, PolicyAction::Review);
    }

    #[test]
    fn list_policies_finds_all() {
        let tmp = TempDir::new().unwrap();
        setup_policies(tmp.path());
        let index = list_policies(tmp.path()).unwrap();
        assert!(index.default.is_some());
        assert!(index.categories.contains_key("plan"));
        assert!(index.levels.contains_key("strict"));
    }

    #[test]
    fn audit_roundtrip() {
        let tmp = TempDir::new().unwrap();
        let event = GovernanceEvent {
            ts: "2026-06-04T14:00:00+0000".to_string(),
            event: "governance.check".to_string(),
            action: "denied".to_string(),
            agent_id: "test-agent".to_string(),
            tool_name: "Bash".to_string(),
            reason: "blocked pattern".to_string(),
            pattern: "(?i)--no-verify".to_string(),
            session_id: "abc123".to_string(),
        };
        emit_audit_event(tmp.path(), &event).unwrap();
        let events = read_audit_events(tmp.path(), Some("2026-06-04")).unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].agent_id, "test-agent");

        let empty = read_audit_events(tmp.path(), Some("2025-01-01")).unwrap();
        assert!(empty.is_empty());
    }
}