bobbin-ai 0.25.2

Local-first context injection engine for AI coding agents
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! Role-based repository access filtering (§69).
//!
//! Provides [`RepoFilter`] which determines which repos a caller can see
//! based on their role and the `[access]` config section.

use std::collections::HashSet;

use glob::Pattern;

use crate::config::{AccessConfig, RoleConfig};

/// Determines which repositories are visible to a given role.
#[derive(Debug, Clone)]
pub struct RepoFilter {
    /// Repos explicitly allowed (None = allow all per default_allow)
    allowed: Option<HashSet<String>>,
    /// Repos explicitly denied (always takes precedence)
    denied: HashSet<String>,
    /// Whether unlisted repos are visible
    default_allow: bool,
    /// File path patterns to deny within allowed repos
    denied_paths: Vec<Pattern>,
}

impl RepoFilter {
    /// Build a filter from config and the caller's role string.
    ///
    /// If no `[access]` section is configured (empty roles list), returns
    /// a permissive filter that allows everything.
    pub fn from_config(config: &AccessConfig, role: &str) -> Self {
        if config.roles.is_empty() {
            return Self::allow_all();
        }

        // Find matching role config (most specific wins)
        let matched = Self::find_matching_role(&config.roles, role);

        match matched {
            Some(role_config) => {
                let allowed = if role_config.allow.is_empty() {
                    None // No allow list = use default_allow
                } else {
                    Some(role_config.allow.iter().cloned().collect())
                };
                let denied = role_config.deny.iter().cloned().collect();
                let denied_paths = role_config
                    .deny_paths
                    .iter()
                    .filter_map(|p| Pattern::new(p).ok())
                    .collect();
                Self {
                    allowed,
                    denied,
                    default_allow: config.default_allow,
                    denied_paths,
                }
            }
            None => {
                // No matching role — use default_allow with no explicit grants
                Self {
                    allowed: None,
                    denied: HashSet::new(),
                    default_allow: config.default_allow,
                    denied_paths: Vec::new(),
                }
            }
        }
    }

    /// Create a filter that allows everything (for backward compat / no config).
    pub fn allow_all() -> Self {
        Self {
            allowed: None,
            denied: HashSet::new(),
            default_allow: true,
            denied_paths: Vec::new(),
        }
    }

    /// Check if a repository name is visible under this filter.
    pub fn is_allowed(&self, repo_name: &str) -> bool {
        // Deny always wins
        if self.matches_any(&self.denied, repo_name) {
            return false;
        }

        // If there's an explicit allow list, repo must match it
        if let Some(ref allowed) = self.allowed {
            return self.matches_any(allowed, repo_name);
        }

        // No explicit allow list — use default_allow
        self.default_allow
    }

    /// Filter a list of results, keeping only those from allowed repos.
    /// The `repo_extractor` function extracts the repo name from each item.
    pub fn filter_vec<T, F>(&self, items: Vec<T>, repo_extractor: F) -> Vec<T>
    where
        F: Fn(&T) -> &str,
    {
        items
            .into_iter()
            .filter(|item| self.is_allowed(repo_extractor(item)))
            .collect()
    }

    /// Check if a full file path is allowed (repo-level + path-level filtering).
    ///
    /// This checks both the repo-level access (same as `is_allowed`) and any
    /// `deny_paths` patterns configured for the role.
    pub fn is_path_allowed(&self, file_path: &str) -> bool {
        let repo = Self::repo_from_path(file_path);
        if !self.is_allowed(repo) {
            return false;
        }

        // Check deny_paths patterns against the path relative to repo root
        if !self.denied_paths.is_empty() {
            // Extract path after repo name (e.g. "src/main.rs" from "/var/lib/bobbin/repos/aegis/src/main.rs")
            let rel_path = Self::path_after_repo(file_path);
            for pattern in &self.denied_paths {
                if pattern.matches(rel_path) {
                    return false;
                }
            }
        }

        true
    }

    /// Filter a list of results by file path, keeping only those from allowed repos
    /// and not matching deny_paths patterns.
    pub fn filter_vec_by_path<T, F>(&self, items: Vec<T>, path_extractor: F) -> Vec<T>
    where
        F: Fn(&T) -> &str,
    {
        items
            .into_iter()
            .filter(|item| self.is_path_allowed(path_extractor(item)))
            .collect()
    }

    /// Extract repo name from a file path like `/var/lib/bobbin/repos/aegis/src/main.rs`.
    /// Returns the segment after "repos/" or the first path component.
    pub fn repo_from_path(path: &str) -> &str {
        // Bead chunks have synthetic paths `beads:<rig>:<id>` (no slashes). Scope
        // their access to the owning rig so per-rig deny rules apply — otherwise
        // the whole `beads:<rig>:<id>` string is treated as the repo, matches no
        // deny rule, and falls through default_allow=true (security gap GH#13/bo-y0z).
        if let Some(rest) = path.strip_prefix("beads:") {
            return rest.split(':').next().unwrap_or(rest);
        }
        // Look for "/repos/<name>/" pattern (absolute paths)
        if let Some(idx) = path.find("/repos/") {
            let after = &path[idx + 7..]; // skip "/repos/"
            if let Some(slash) = after.find('/') {
                return &after[..slash];
            }
            return after;
        }
        // Handle "repos/<name>/..." (relative paths starting with repos/)
        if let Some(after) = path.strip_prefix("repos/") {
            if let Some(slash) = after.find('/') {
                return &after[..slash];
            }
            return after;
        }
        // Fallback: first path component (for relative paths like "aegis/src/main.rs")
        path.split('/').next().unwrap_or(path)
    }

    /// Extract the path after the repo name from a full file path.
    /// E.g. "/var/lib/bobbin/repos/aegis/src/main.rs" → "src/main.rs"
    fn path_after_repo(path: &str) -> &str {
        // Look for "/repos/<name>/" pattern
        if let Some(idx) = path.find("/repos/") {
            let after = &path[idx + 7..]; // skip "/repos/"
            if let Some(slash) = after.find('/') {
                return &after[slash + 1..];
            }
            return "";
        }
        // Handle "repos/<name>/..."
        if let Some(after) = path.strip_prefix("repos/") {
            if let Some(slash) = after.find('/') {
                return &after[slash + 1..];
            }
            return "";
        }
        // Fallback: everything after first slash
        if let Some(slash) = path.find('/') {
            return &path[slash + 1..];
        }
        path
    }

    /// Resolve the effective role from explicit value, env vars, or default.
    ///
    /// Priority: explicit > BOBBIN_ROLE > GT_ROLE > BD_ACTOR > "default"
    pub fn resolve_role(explicit: Option<&str>) -> String {
        if let Some(role) = explicit {
            if !role.is_empty() {
                return role.to_string();
            }
        }
        if let Ok(role) = std::env::var("BOBBIN_ROLE") {
            if !role.is_empty() {
                return role;
            }
        }
        if let Ok(role) = std::env::var("GT_ROLE") {
            if !role.is_empty() {
                return role;
            }
        }
        if let Ok(role) = std::env::var("BD_ACTOR") {
            if !role.is_empty() {
                return role;
            }
        }
        "default".to_string()
    }

    /// Find the most specific matching role config for a given role string.
    ///
    /// Matching priority:
    /// 1. Exact match (e.g. "aegis/crew/ian" matches "aegis/crew/ian")
    /// 2. Wildcard match, most specific first (e.g. "aegis/crew/*" before "aegis/*")
    /// 3. "default" role as fallback
    fn find_matching_role<'a>(roles: &'a [RoleConfig], role: &str) -> Option<&'a RoleConfig> {
        // 1. Exact match
        if let Some(r) = roles.iter().find(|r| r.name == role) {
            return Some(r);
        }

        // 2. Wildcard match — find all that match, pick most specific (longest prefix)
        let mut best_match: Option<&RoleConfig> = None;
        let mut best_len = 0;
        for r in roles {
            if let Some(prefix) = r.name.strip_suffix("/*") {
                if role.starts_with(prefix)
                    && (role.len() == prefix.len()
                        || role.as_bytes().get(prefix.len()) == Some(&b'/'))
                {
                    if prefix.len() > best_len {
                        best_len = prefix.len();
                        best_match = Some(r);
                    }
                }
            }
        }
        if best_match.is_some() {
            return best_match;
        }

        // 3. "default" fallback
        roles.iter().find(|r| r.name == "default")
    }

    /// Check if a repo name matches any pattern in the set.
    /// Supports "*" (match all) and literal names.
    fn matches_any(&self, patterns: &HashSet<String>, repo_name: &str) -> bool {
        if patterns.contains("*") {
            return true;
        }
        patterns.contains(repo_name)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::RoleConfig;

    fn make_config(default_allow: bool, roles: Vec<RoleConfig>) -> AccessConfig {
        AccessConfig {
            default_allow,
            roles,
        }
    }

    fn role(name: &str, allow: &[&str], deny: &[&str]) -> RoleConfig {
        RoleConfig {
            name: name.to_string(),
            allow: allow.iter().map(|s| s.to_string()).collect(),
            deny: deny.iter().map(|s| s.to_string()).collect(),
            deny_paths: vec![],
        }
    }

    fn role_with_paths(
        name: &str,
        allow: &[&str],
        deny: &[&str],
        deny_paths: &[&str],
    ) -> RoleConfig {
        RoleConfig {
            name: name.to_string(),
            allow: allow.iter().map(|s| s.to_string()).collect(),
            deny: deny.iter().map(|s| s.to_string()).collect(),
            deny_paths: deny_paths.iter().map(|s| s.to_string()).collect(),
        }
    }

    #[test]
    fn test_no_config_allows_everything() {
        let config = make_config(true, vec![]);
        let filter = RepoFilter::from_config(&config, "anything");
        assert!(filter.is_allowed("aegis"));
        assert!(filter.is_allowed("personal-planning"));
        assert!(filter.is_allowed("cv"));
    }

    #[test]
    fn test_default_role_deny() {
        let config = make_config(
            true,
            vec![role("default", &[], &["personal-planning", "cv", "resume"])],
        );
        let filter = RepoFilter::from_config(&config, "unknown-agent");
        assert!(filter.is_allowed("aegis"));
        assert!(filter.is_allowed("bobbin"));
        assert!(!filter.is_allowed("personal-planning"));
        assert!(!filter.is_allowed("cv"));
        assert!(!filter.is_allowed("resume"));
    }

    #[test]
    fn test_human_sees_everything() {
        let config = make_config(
            true,
            vec![
                role("default", &[], &["personal-planning", "cv"]),
                role("human", &["*"], &[]),
            ],
        );
        let filter = RepoFilter::from_config(&config, "human");
        assert!(filter.is_allowed("personal-planning"));
        assert!(filter.is_allowed("cv"));
        assert!(filter.is_allowed("aegis"));
    }

    #[test]
    fn test_deny_overrides_allow() {
        let config = make_config(true, vec![role("test", &["*"], &["secret-repo"])]);
        let filter = RepoFilter::from_config(&config, "test");
        assert!(filter.is_allowed("aegis"));
        assert!(!filter.is_allowed("secret-repo"));
    }

    #[test]
    fn test_wildcard_role_matching() {
        let config = make_config(
            false,
            vec![role("aegis/*", &["aegis", "bobbin", "gastown"], &[])],
        );
        let filter = RepoFilter::from_config(&config, "aegis/crew/ian");
        assert!(filter.is_allowed("aegis"));
        assert!(filter.is_allowed("bobbin"));
        assert!(!filter.is_allowed("personal-planning"));
    }

    #[test]
    fn test_most_specific_wildcard_wins() {
        let config = make_config(
            false,
            vec![
                role("aegis/*", &["aegis", "bobbin"], &[]),
                role(
                    "aegis/crew/*",
                    &["aegis", "bobbin", "gastown", "homelab-mcp"],
                    &[],
                ),
            ],
        );
        // aegis/crew/ian should match aegis/crew/* (more specific) over aegis/*
        let filter = RepoFilter::from_config(&config, "aegis/crew/ian");
        assert!(filter.is_allowed("homelab-mcp"));

        // aegis/polecats/alpha should match aegis/* (less specific)
        let filter2 = RepoFilter::from_config(&config, "aegis/polecats/alpha");
        assert!(!filter2.is_allowed("homelab-mcp"));
        assert!(filter2.is_allowed("bobbin"));
    }

    #[test]
    fn test_exact_match_over_wildcard() {
        let config = make_config(
            false,
            vec![
                role("aegis/*", &["aegis"], &[]),
                role(
                    "aegis/crew/ian",
                    &["aegis", "bobbin", "personal-planning"],
                    &[],
                ),
            ],
        );
        let filter = RepoFilter::from_config(&config, "aegis/crew/ian");
        assert!(filter.is_allowed("personal-planning"));
    }

    #[test]
    fn test_default_allow_false_no_match() {
        let config = make_config(false, vec![role("human", &["*"], &[])]);
        // Unknown role, no default role defined, default_allow=false
        let filter = RepoFilter::from_config(&config, "random-agent");
        assert!(!filter.is_allowed("aegis"));
    }

    #[test]
    fn test_default_allow_true_no_match() {
        let config = make_config(true, vec![role("human", &["*"], &[])]);
        // Unknown role, no default role defined, default_allow=true
        let filter = RepoFilter::from_config(&config, "random-agent");
        assert!(filter.is_allowed("aegis"));
    }

    #[test]
    fn test_filter_vec() {
        let config = make_config(true, vec![role("default", &[], &["secret"])]);
        let filter = RepoFilter::from_config(&config, "default");

        let items = vec!["aegis/main.rs", "secret/passwords.txt", "bobbin/lib.rs"];
        let filtered = filter.filter_vec(items, |item| item.split('/').next().unwrap());
        assert_eq!(filtered, vec!["aegis/main.rs", "bobbin/lib.rs"]);
    }

    #[test]
    fn test_repo_from_path() {
        assert_eq!(
            RepoFilter::repo_from_path("/var/lib/bobbin/repos/aegis/src/main.rs"),
            "aegis"
        );
        assert_eq!(
            RepoFilter::repo_from_path("/var/lib/bobbin/repos/homelab-mcp/tools.go"),
            "homelab-mcp"
        );
        assert_eq!(RepoFilter::repo_from_path("bobbin/src/lib.rs"), "bobbin");
        // Relative paths starting with "repos/"
        assert_eq!(
            RepoFilter::repo_from_path("repos/reckoning/packages/client/src/main.ts"),
            "reckoning"
        );
        assert_eq!(RepoFilter::repo_from_path("repos/cv/resume.md"), "cv");
        // Bead chunks map to their rig (GH#13/bo-y0z access fix).
        assert_eq!(
            RepoFilter::repo_from_path("beads:pixelsrc:bo-x"),
            "pixelsrc"
        );
        assert_eq!(RepoFilter::repo_from_path("beads:aegis:aegis-h8x"), "aegis");
        assert_eq!(RepoFilter::repo_from_path("beads:hq:hq-9f2"), "hq");
    }

    #[test]
    fn test_bead_access_scoped_to_rig() {
        // A role that denies the `pixelsrc` repo must also be denied pixelsrc beads.
        let config = make_config(true, vec![role("aegis", &[], &["pixelsrc"])]);
        let filter = RepoFilter::from_config(&config, "aegis");
        // Code from pixelsrc denied (baseline).
        assert!(!filter.is_path_allowed("/var/lib/bobbin/repos/pixelsrc/src/x.rs"));
        // Bead from the pixelsrc rig must ALSO be denied (this was the security gap).
        assert!(!filter.is_path_allowed("beads:pixelsrc:bo-x"));
        // Beads from an allowed rig still pass.
        assert!(filter.is_path_allowed("beads:aegis:aegis-h8x"));
    }

    #[test]
    fn test_bead_hq_human_only_deny() {
        // hq beads (security/escalation) gated to humans via an agent-role deny.
        let config = make_config(
            true,
            vec![role("human", &["*"], &[]), role("default", &[], &["hq"])],
        );
        let agent = RepoFilter::from_config(&config, "default");
        assert!(!agent.is_path_allowed("beads:hq:hq-secret"));
        let human = RepoFilter::from_config(&config, "human");
        assert!(human.is_path_allowed("beads:hq:hq-secret"));
    }

    #[test]
    fn test_resolve_role_explicit() {
        assert_eq!(RepoFilter::resolve_role(Some("human")), "human");
    }

    #[test]
    fn test_resolve_role_default() {
        // Clear env vars to test default
        std::env::remove_var("BOBBIN_ROLE");
        std::env::remove_var("GT_ROLE");
        std::env::remove_var("BD_ACTOR");
        assert_eq!(RepoFilter::resolve_role(None), "default");
    }

    #[test]
    fn test_config_toml_roundtrip() {
        let config = AccessConfig {
            default_allow: true,
            roles: vec![
                RoleConfig {
                    name: "human".to_string(),
                    allow: vec!["*".to_string()],
                    deny: vec![],
                    deny_paths: vec![],
                },
                RoleConfig {
                    name: "default".to_string(),
                    allow: vec![],
                    deny: vec!["cv".to_string(), "resume".to_string()],
                    deny_paths: vec![],
                },
            ],
        };
        let serialized = toml::to_string_pretty(&config).unwrap();
        let deserialized: AccessConfig = toml::from_str(&serialized).unwrap();
        assert_eq!(deserialized.default_allow, true);
        assert_eq!(deserialized.roles.len(), 2);
        assert_eq!(deserialized.roles[0].name, "human");
        assert_eq!(deserialized.roles[1].deny, vec!["cv", "resume"]);
    }

    #[test]
    fn test_backward_compat_no_access_section() {
        // Config TOML without [access] section should deserialize with defaults
        let toml_str = r#"
[embedding]
model = "all-MiniLM-L6-v2"
"#;
        let config: crate::config::Config = toml::from_str(toml_str).unwrap();
        assert!(config.access.default_allow);
        assert!(config.access.roles.is_empty());
        let filter = RepoFilter::from_config(&config.access, "anything");
        assert!(filter.is_allowed("any-repo"));
    }

    #[test]
    fn test_deny_paths_filters_files() {
        let config = make_config(
            true,
            vec![role_with_paths(
                "default",
                &[],
                &["cv"],
                &["harnesses/*/CLAUDE.md"],
            )],
        );
        let filter = RepoFilter::from_config(&config, "agent");

        // Denied repos still denied
        assert!(!filter.is_path_allowed("/var/lib/bobbin/repos/cv/resume.md"));

        // Denied paths within allowed repos
        assert!(!filter.is_path_allowed("/var/lib/bobbin/repos/aegis/harnesses/ian/CLAUDE.md"));

        // Allowed paths in allowed repos
        assert!(filter.is_path_allowed("/var/lib/bobbin/repos/aegis/src/main.rs"));
    }

    #[test]
    fn test_deny_paths_no_patterns_allows_all() {
        let config = make_config(true, vec![role("default", &[], &[])]);
        let filter = RepoFilter::from_config(&config, "agent");

        // Everything allowed when no deny_paths
        assert!(filter.is_path_allowed("/var/lib/bobbin/repos/aegis/harnesses/ian/CLAUDE.md"));
        assert!(filter.is_path_allowed("/var/lib/bobbin/repos/aegis/src/main.rs"));
    }

    #[test]
    fn test_filter_vec_by_path() {
        let config = make_config(
            true,
            vec![role_with_paths(
                "default",
                &[],
                &[],
                &["harnesses/*/CLAUDE.md"],
            )],
        );
        let filter = RepoFilter::from_config(&config, "agent");

        let items = vec![
            "/var/lib/bobbin/repos/aegis/src/main.rs",
            "/var/lib/bobbin/repos/aegis/harnesses/ian/CLAUDE.md",
            "/var/lib/bobbin/repos/aegis/docs/design.md",
        ];
        let filtered = filter.filter_vec_by_path(items, |item| item);
        assert_eq!(
            filtered,
            vec![
                "/var/lib/bobbin/repos/aegis/src/main.rs",
                "/var/lib/bobbin/repos/aegis/docs/design.md",
            ]
        );
    }

    #[test]
    fn test_deny_paths_config_roundtrip() {
        let toml_str = r#"
default_allow = true

[[roles]]
name = "default"
deny = ["cv"]
deny_paths = ["harnesses/*/CLAUDE.md", "crew/*/CLAUDE.md"]
"#;
        let config: AccessConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.roles[0].deny_paths.len(), 2);
        assert_eq!(config.roles[0].deny_paths[0], "harnesses/*/CLAUDE.md");

        let filter = RepoFilter::from_config(&config, "agent");
        assert!(!filter.is_path_allowed("/var/lib/bobbin/repos/aegis/harnesses/ian/CLAUDE.md"));
        assert!(filter.is_path_allowed("/var/lib/bobbin/repos/aegis/src/main.rs"));
    }
}