attini 0.0.1

CLI coding agent that aims to be as autonomous as it can be, without ever leaving your control
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
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
//! Pure permission judgment for `command`, `read` and `write` tool
//! invocations.
//!
//! Rules come from the JSONL permissions files (see
//! `docs/design/permissions-file.md`). A `command` rule is an
//! argv-prefix matcher; a `read` rule grants access to a path
//! (recursive, allow-only); a `write` rule is a recursive path matcher
//! that may be `allow` or `deny`. For `command` and `write`, evaluation
//! is **last-match-wins** over the concatenated list
//! `[workspace] ++ [session]`; if no rule matches, the outcome is
//! `Pending`. `read` has no deny, so it is not evaluated as a gate —
//! its rules only widen the executor's read roots. No I/O — file
//! loading and session record writing live in the impl-layer
//! `crate::permissions` and `crate::tell_cli`.

use std::path::Path;

/// How side-effecting tool calls are authorized in this invocation.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum Authorization {
    /// Normal per-tool-call flow: patches and unmatched commands
    /// require approval via `pending.json`.
    #[default]
    PerTool,
}

/// Which kind of tool call a rule governs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PermissionKind {
    /// A `command` tool call, matched by argv prefix.
    Command,
    /// A read-only tool call (`read`/`list`/`search`), matched by path.
    Read,
    /// A `patch` tool call, matched by the target path of each edit.
    Write,
}

impl PermissionKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Command => "command",
            Self::Read => "read",
            Self::Write => "write",
        }
    }
}

/// A single permission rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rule {
    pub kind: PermissionKind,
    /// `true` = allow, `false` = deny. Always present on disk for
    /// `command` and `write` rules; an omitted `allow` is a load error,
    /// so a typo never silently turns a rule off. `read` rules are
    /// allow-only: `allow` may be omitted (meaning `true`) and
    /// `allow:false` is a load error.
    pub allow: bool,
    /// `command`: the argv prefix to match (token-wise).
    /// `read`/`write`: unused.
    pub args_prefix: Vec<String>,
    /// `read`/`write`: the path to match (recursively, on segment
    /// boundaries). `command`: unused.
    pub path: String,
}

impl Rule {
    pub fn command(allow: bool, args_prefix: Vec<String>) -> Self {
        Self {
            kind: PermissionKind::Command,
            allow,
            args_prefix,
            path: String::new(),
        }
    }

    /// A `read` rule. Read rules are allow-only (they grant access to a
    /// path); there is no `read` deny, so `allow` is always `true`.
    pub fn read(path: String) -> Self {
        Self {
            kind: PermissionKind::Read,
            allow: true,
            args_prefix: Vec::new(),
            path,
        }
    }

    pub fn write(allow: bool, path: String) -> Self {
        Self {
            kind: PermissionKind::Write,
            allow,
            args_prefix: Vec::new(),
            path,
        }
    }
}

/// Which layer a rule came from, for history output. The layer is a
/// property of which file the rule was loaded from, not a field in the
/// rule itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuleScope {
    Workspace,
    Session,
}

impl RuleScope {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Workspace => "workspace",
            Self::Session => "session",
        }
    }
}

/// One layer's rules tagged with its scope.
pub type ScopedRules<'a> = (RuleScope, &'a [Rule]);

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Judgment {
    /// Auto-run the command and record a `tool_approval` with
    /// `decision: "approve"` + sidecar.
    AutoApprove(AutoDecision),
    /// Auto-reject the command and record a `tool_approval` with
    /// `decision: "reject"` + sidecar. The loop continues.
    AutoDeny(AutoDecision),
    /// Fall back to normal pending flow.
    Pending,
}

/// The decision plus the full match history that produced it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AutoDecision {
    /// The scope of the winning (last matching) rule.
    pub scope: RuleScope,
    /// The winning rule's argv prefix (command rules) or path (read).
    pub args_prefix: Vec<String>,
    /// The winning rule's decision.
    pub allowed: bool,
    /// Every rule that matched during the walk, in evaluation order,
    /// each marked with whether it was the one finally adopted.
    pub matches: Vec<RuleMatch>,
}

/// One matched rule in the evaluation walk.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuleMatch {
    pub scope: RuleScope,
    pub kind: PermissionKind,
    pub allow: bool,
    pub args_prefix: Vec<String>,
    pub path: String,
    /// `true` for the last matching rule (the one whose `allow` decided).
    pub adopted: bool,
}

/// Evaluate a command against the permission rules. `layers` is the
/// concatenated rule chain in increasing precedence, e.g.
/// `[(Workspace, ws), (Session, sess)]`. The
/// decision of the **last** matching `command` rule wins; no match
/// yields `Pending`.
pub fn evaluate(
    layers: &[ScopedRules<'_>],
    argv: &[String],
    _authorization: &Authorization,
) -> Judgment {
    let mut matches: Vec<RuleMatch> = Vec::new();
    for (scope, rules) in layers {
        for rule in rules.iter() {
            if rule.kind != PermissionKind::Command {
                continue;
            }
            if rule_matches_argv(rule, argv) {
                matches.push(RuleMatch {
                    scope: *scope,
                    kind: rule.kind,
                    allow: rule.allow,
                    args_prefix: rule.args_prefix.clone(),
                    path: String::new(),
                    adopted: false,
                });
            }
        }
    }
    finish_decision(matches)
}

/// Evaluate a `patch` edit target (a workspace-relative path, as
/// written by the model, or the canonical path it maps to) against the
/// permission rules. Same last-match-wins semantics as `evaluate`; a
/// `write` rule is distinct from `command` and `read` kinds and does not
/// cross-match them.
pub fn evaluate_write(
    layers: &[ScopedRules<'_>],
    path: &Path,
    _authorization: &Authorization,
) -> Judgment {
    let mut matches: Vec<RuleMatch> = Vec::new();
    for (scope, rules) in layers {
        for rule in rules.iter() {
            if rule.kind != PermissionKind::Write {
                continue;
            }
            if rule_matches_path(rule, path) {
                matches.push(RuleMatch {
                    scope: *scope,
                    kind: rule.kind,
                    allow: rule.allow,
                    args_prefix: Vec::new(),
                    path: rule.path.clone(),
                    adopted: false,
                });
            }
        }
    }
    finish_decision(matches)
}

/// Turn a match history into a `Judgment`. The last match's `allow`
/// decides; the last match is marked `adopted`.
fn finish_decision(mut matches: Vec<RuleMatch>) -> Judgment {
    let Some(last) = matches.last_mut() else {
        return Judgment::Pending;
    };
    last.adopted = true;
    let scope = last.scope;
    let args_prefix = last.args_prefix.clone();
    let allowed = last.allow;
    let decision = AutoDecision {
        scope,
        args_prefix,
        allowed,
        matches,
    };
    if allowed {
        Judgment::AutoApprove(decision)
    } else {
        Judgment::AutoDeny(decision)
    }
}

fn rule_matches_argv(rule: &Rule, argv: &[String]) -> bool {
    if rule.args_prefix.is_empty() {
        return false;
    }
    if rule.args_prefix.len() > argv.len() {
        return false;
    }
    rule.args_prefix
        .iter()
        .zip(argv.iter())
        .all(|(a, b)| a == b)
}

/// Match a `read`/`write` rule against a path: the rule's path matches
/// the requested path itself and anything underneath it, on
/// path-segment boundaries (`foo/bar` matches `foo/bar/x` but not
/// `foo/barbaz`). The rule path is compared as given (usually
/// workspace-relative); the caller supplies a path in a consistent
/// form.
fn rule_matches_path(rule: &Rule, path: &Path) -> bool {
    if rule.path.is_empty() {
        return false;
    }
    let prefix = Path::new(&rule.path);
    path.starts_with(prefix)
}

// Small helper so tests can write `r.as_slice()`.
impl Rule {
    #[cfg(test)]
    fn as_slice(&self) -> &[Rule] {
        std::slice::from_ref(self)
    }
}

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

    fn argv(items: &[&str]) -> Vec<String> {
        items.iter().map(|s| s.to_string()).collect()
    }

    fn cmd(allow: bool, prefix: &[&str]) -> Rule {
        Rule::command(allow, argv(prefix))
    }

    #[test]
    fn evaluate_allow_rule_matches() {
        let r = cmd(true, &["cargo", "test"]);
        let layers = [(RuleScope::Workspace, r.as_slice())];
        match evaluate(
            &layers,
            &argv(&["cargo", "test", "--workspace"]),
            &Authorization::PerTool,
        ) {
            Judgment::AutoApprove(d) => {
                assert!(d.allowed);
                assert_eq!(d.args_prefix, argv(&["cargo", "test"]));
                assert_eq!(d.scope, RuleScope::Workspace);
                assert_eq!(d.matches.len(), 1);
                assert!(d.matches[0].adopted);
            }
            other => panic!("expected AutoApprove, got {other:?}"),
        }
    }

    #[test]
    fn evaluate_no_match_pends() {
        let r = cmd(true, &["ls"]);
        let layers = [(RuleScope::Workspace, r.as_slice())];
        assert!(matches!(
            evaluate(&layers, &argv(&["cat", "x"]), &Authorization::PerTool),
            Judgment::Pending
        ));
    }

    #[test]
    fn evaluate_deny_rule_alone_denies() {
        let r = cmd(false, &["rm", "-rf"]);
        let layers = [(RuleScope::Workspace, r.as_slice())];
        assert!(matches!(
            evaluate(
                &layers,
                &argv(&["rm", "-rf", "tmp"]),
                &Authorization::PerTool
            ),
            Judgment::AutoDeny(_)
        ));
    }

    #[test]
    fn evaluate_last_match_wins_session_overrides_workspace() {
        // Workspace denies, session allows -> session (later) wins.
        let ws = cmd(false, &["cargo", "test"]);
        let sess = cmd(true, &["cargo", "test"]);
        let layers = [
            (RuleScope::Workspace, ws.as_slice()),
            (RuleScope::Session, sess.as_slice()),
        ];
        match evaluate(&layers, &argv(&["cargo", "test"]), &Authorization::PerTool) {
            Judgment::AutoApprove(d) => {
                assert_eq!(d.scope, RuleScope::Session);
                // Both matched; the workspace one is not adopted.
                assert_eq!(d.matches.len(), 2);
                assert!(!d.matches[0].adopted);
                assert!(d.matches[1].adopted);
            }
            other => panic!("expected AutoApprove(session), got {other:?}"),
        }
    }

    #[test]
    fn evaluate_last_match_wins_workspace_deny_over_session_allow() {
        // Session allows, workspace denies -> workspace deny wins order.
        let ws = cmd(false, &["cargo", "test"]);
        let sess = cmd(true, &["cargo", "test"]);
        let layers = [
            (RuleScope::Workspace, ws.as_slice()),
            (RuleScope::Session, sess.as_slice()),
        ];
        // Session is later, so session allow actually wins here.
        assert!(matches!(
            evaluate(&layers, &argv(&["cargo", "test"]), &Authorization::PerTool),
            Judgment::AutoApprove(_)
        ));
    }

    #[test]
    fn evaluate_rule_prefix_longer_than_argv_does_not_match() {
        let r = cmd(true, &["cargo", "test", "--all"]);
        let layers = [(RuleScope::Workspace, r.as_slice())];
        assert!(matches!(
            evaluate(&layers, &argv(&["cargo", "test"]), &Authorization::PerTool),
            Judgment::Pending
        ));
    }

    #[test]
    fn evaluate_element_wise_mismatch_does_not_match() {
        let r = cmd(true, &["cargo", "test"]);
        let layers = [(RuleScope::Workspace, r.as_slice())];
        assert!(matches!(
            evaluate(&layers, &argv(&["cargo", "check"]), &Authorization::PerTool),
            Judgment::Pending
        ));
    }

    #[test]
    fn evaluate_empty_argv_prefix_never_matches() {
        let r = cmd(true, &[]);
        let layers = [(RuleScope::Workspace, r.as_slice())];
        assert!(matches!(
            evaluate(&layers, &argv(&["ls"]), &Authorization::PerTool),
            Judgment::Pending
        ));
    }

    #[test]
    fn evaluate_bash_dash_c_without_matching_rule_pends() {
        let r = cmd(true, &["cargo", "test"]);
        let layers = [(RuleScope::Workspace, r.as_slice())];
        assert!(matches!(
            evaluate(
                &layers,
                &argv(&["bash", "-c", "ls | head"]),
                &Authorization::PerTool
            ),
            Judgment::Pending
        ));
    }

    #[test]
    fn evaluate_bash_dash_c_with_matching_rule_auto_approves() {
        let r = cmd(true, &["bash", "-c"]);
        let layers = [(RuleScope::Workspace, r.as_slice())];
        match evaluate(
            &layers,
            &argv(&["bash", "-c", "ls | head"]),
            &Authorization::PerTool,
        ) {
            Judgment::AutoApprove(d) => assert_eq!(d.args_prefix, argv(&["bash", "-c"])),
            other => panic!("expected AutoApprove for approved bash -c, got {other:?}"),
        }
    }

    #[test]
    fn read_rule_matches_recursively_on_segments() {
        // Read rules are allow-only and not evaluated as a gate; their
        // path matching is exercised directly via `rule_matches_path`.
        let r = Rule::read("foo/bar".to_string());
        assert!(rule_matches_path(&r, Path::new("foo/bar")));
        assert!(rule_matches_path(&r, Path::new("foo/bar/y/z")));
        assert!(!rule_matches_path(&r, Path::new("foo/barbaz")));
    }

    #[test]
    fn write_rule_matches_recursively_on_segments() {
        let r = Rule::write(true, "src".to_string());
        let layers = [(RuleScope::Workspace, r.as_slice())];
        assert!(matches!(
            evaluate_write(&layers, Path::new("src/lib.rs"), &Authorization::PerTool),
            Judgment::AutoApprove(_)
        ));
        assert!(matches!(
            evaluate_write(
                &layers,
                Path::new("src/deep/mod.rs"),
                &Authorization::PerTool
            ),
            Judgment::AutoApprove(_)
        ));
        assert!(matches!(
            evaluate_write(&layers, Path::new("src2/lib.rs"), &Authorization::PerTool),
            Judgment::Pending
        ));
    }

    #[test]
    fn write_deny_rule_denies() {
        let r = Rule::write(false, "src/generated".to_string());
        let layers = [(RuleScope::Workspace, r.as_slice())];
        assert!(matches!(
            evaluate_write(
                &layers,
                Path::new("src/generated/x.rs"),
                &Authorization::PerTool
            ),
            Judgment::AutoDeny(_)
        ));
    }

    #[test]
    fn write_and_read_rules_do_not_cross_match() {
        let read_rule = Rule::read("src".to_string());
        let write_rule = Rule::write(true, "src".to_string());
        let layers = [
            (RuleScope::Workspace, read_rule.as_slice()),
            (RuleScope::Session, write_rule.as_slice()),
        ];
        // A write evaluation ignores the read rule; only the write match counts.
        match evaluate_write(&layers, Path::new("src/lib.rs"), &Authorization::PerTool) {
            Judgment::AutoApprove(d) => {
                assert_eq!(d.scope, RuleScope::Session);
                assert_eq!(d.matches.len(), 1);
                assert_eq!(d.matches[0].kind, PermissionKind::Write);
            }
            other => panic!("expected AutoApprove(session write), got {other:?}"),
        }
        // Read rules are not evaluated as a gate at all, so a read rule
        // never contributes a match to a write decision (asserted above)
        // and a write rule is never consulted for reads. The path matcher
        // stays kind-agnostic, so verify the read rule's shape directly.
        assert!(rule_matches_path(&read_rule, Path::new("src/lib.rs")));
    }

    #[test]
    fn read_and_command_rules_do_not_cross_match() {
        let cmd_rule = cmd(true, &["foo"]);
        let read_rule = Rule::read("foo".to_string());
        let layers = [
            (RuleScope::Workspace, cmd_rule.as_slice()),
            (RuleScope::Session, read_rule.as_slice()),
        ];
        // A command evaluation ignores the read rule; only the command match counts.
        match evaluate(&layers, &argv(&["foo", "bar"]), &Authorization::PerTool) {
            Judgment::AutoApprove(d) => {
                assert_eq!(d.scope, RuleScope::Workspace);
                assert_eq!(d.matches.len(), 1);
                assert_eq!(d.matches[0].kind, PermissionKind::Command);
            }
            other => panic!("expected AutoApprove(workspace command), got {other:?}"),
        }
    }
}