akicita 0.1.1

Bounded autonomy for self-acting systems: an autonomy ladder (off/suggest/safe-apply/full), protected surfaces that never auto-apply, blast-radius caps, rate limits, and dedupe — named for the Lakota camp marshals who kept warriors inside the bounds
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
//! akicita — bounded autonomy for self-acting systems.
//!
//! Named for the *akicita*, the Lakota camp marshals who policed the
//! warriors *within* the tribe during the hunt — internal enforcement
//! with bounded authority. This crate is that marshal for systems that
//! act on their own behalf: an autonomy ladder, protected surfaces that
//! never auto-apply, blast-radius caps, rate limits, and proposal dedupe,
//! with every decision written to a journal a human can audit.
//!
//! The autonomy ladder:
//! * [`Level::Off`] — nothing runs; proposals are denied.
//! * [`Level::Suggest`] — proposals are recorded for human review; nothing
//!   is applied.
//! * [`Level::SafeApply`] — in-bounds actions on unprotected surfaces are
//!   applied automatically; protected surfaces and oversize proposals hold.
//! * [`Level::Full`] — same application, without the safe-apply surface
//!   restriction — but `protected` surfaces are *still* never auto-applied.
//!   Some doors only a human opens.
//!
//! Every `check` produces a [`Decision`] and appends it to the journal —
//! refusals are as much the record as permits.

use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::collections::{HashSet, VecDeque};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::sync::Mutex;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

/// The autonomy ladder rung.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Level {
    /// Nothing runs.
    Off,
    /// Propose only — record for human review.
    Suggest,
    /// Apply in-bounds proposals on unprotected surfaces.
    SafeApply,
    /// Apply freely — protected surfaces are still never auto-applied.
    Full,
}

impl Level {
    /// Parse a persisted level string (`off|suggest|safe-apply|full`).
    pub fn parse(s: &str) -> Level {
        match s.trim().to_lowercase().as_str() {
            "off" => Level::Off,
            "safe-apply" | "safe_apply" | "safeapply" => Level::SafeApply,
            "full" => Level::Full,
            _ => Level::Suggest,
        }
    }

    /// Load the persisted level from `path` (default `suggest`).
    pub fn load(path: &PathBuf) -> Level {
        fs::read_to_string(path)
            .map(|t| Level::parse(&t))
            .unwrap_or(Level::Suggest)
    }

    /// Persist the level (0600).
    pub fn save(&self, path: &PathBuf) -> std::io::Result<()> {
        let s = match self {
            Level::Off => "off",
            Level::Suggest => "suggest",
            Level::SafeApply => "safe-apply",
            Level::Full => "full",
        };
        write_private(path, s.as_bytes())
    }
}

/// A proposal to mutate state — a file patch, a config change, any act
/// with a surface and a blast radius.
#[derive(Debug, Clone)]
pub struct Proposal {
    /// What it touches (file path, policy name, surface key).
    pub surface: String,
    /// Human-readable intent, recorded to the journal.
    pub intent: String,
    /// Blast radius: lines of change.
    pub lines: usize,
    /// Blast radius: bytes of change.
    pub bytes: usize,
    /// Fingerprint material for dedupe — typically the patch body.
    pub fingerprint: String,
}

impl Proposal {
    /// A file patch proposal (`old`→`new` at `file`).
    pub fn patch(file: impl Into<String>, old: &str, new: &str, intent: &str) -> Self {
        let file = file.into();
        let lines = new.matches('\n').count() + old.matches('\n').count() + 1;
        let bytes = old.len() + new.len();
        Self {
            surface: file.clone(),
            intent: intent.to_string(),
            lines,
            bytes,
            fingerprint: sha256_hex(format!("{file}{old}{new}").as_bytes()),
        }
    }

    /// A generic action proposal.
    pub fn action(
        surface: impl Into<String>,
        intent: impl Into<String>,
        lines: usize,
        bytes: usize,
        fingerprint: impl Into<String>,
    ) -> Self {
        Self {
            surface: surface.into(),
            intent: intent.into(),
            lines,
            bytes,
            fingerprint: fingerprint.into(),
        }
    }
}

/// What the marshal decided.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "decision", rename_all = "kebab-case")]
pub enum Decision {
    /// Apply it — within every bound.
    Permit,
    /// Record it for the human; do not apply (suggest level, protected
    /// surface, or constitutional hold).
    Hold { reason: String },
    /// Reject — level off, oversize, rate-limited, or a refiling of a
    /// previously decided proposal.
    Deny { reason: String },
}

/// Configuration for the marshal.
pub struct Config {
    /// Basenames that are *never* auto-applied, at any level — the core
    /// control files. Proposals against them hold for the human.
    pub protected_basenames: HashSet<String>,
    /// Full path prefixes that are protected (e.g. policy dir).
    pub protected_prefixes: Vec<String>,
    /// Max lines a single proposal may change.
    pub max_lines: usize,
    /// Max bytes a single proposal may change.
    pub max_bytes: usize,
    /// Minimum time between automatic applications.
    pub min_interval: Duration,
    /// How many decided fingerprints to remember for dedupe.
    pub dedupe_capacity: usize,
    /// Optional journal path (decisions land as NDJSON lines).
    pub journal_path: Option<PathBuf>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            protected_basenames: HashSet::new(),
            protected_prefixes: Vec::new(),
            max_lines: 20,
            max_bytes: 1_000,
            min_interval: Duration::from_secs(0),
            dedupe_capacity: 512,
            journal_path: None,
        }
    }
}

struct State {
    last_apply: Option<Instant>,
    dedupe: VecDeque<String>,
    dedupe_set: HashSet<String>,
}

/// The camp marshal. Checks proposals against the ladder, the bounds,
/// and the protected list; journals every decision.
pub struct Akicita {
    level: Mutex<Level>,
    level_path: Option<PathBuf>,
    config: Config,
    state: Mutex<State>,
}

impl Akicita {
    /// A marshal at `level`, configured by `config`. `level_path`
    /// optionally persists the level across restarts (re-read on each
    /// check so a human can lower autonomy live).
    pub fn new(level: Level, config: Config, level_path: Option<PathBuf>) -> Self {
        Self {
            level: Mutex::new(level),
            level_path,
            config,
            state: Mutex::new(State {
                last_apply: None,
                dedupe: VecDeque::new(),
                dedupe_set: HashSet::new(),
            }),
        }
    }

    /// Current effective level — re-read from disk if a path was given.
    pub fn level(&self) -> Level {
        if let Some(path) = &self.level_path {
            let live = Level::load(path);
            if let Ok(mut l) = self.level.lock() {
                *l = live;
            }
            return live;
        }
        *self.level.lock().expect("level lock")
    }

    /// Set the level (and persist it if a path was configured).
    pub fn set_level(&self, level: Level) {
        *self.level.lock().expect("level lock") = level;
        if let Some(path) = &self.level_path {
            let _ = level.save(path);
        }
    }

    fn is_protected(&self, surface: &str) -> bool {
        if self
            .config
            .protected_prefixes
            .iter()
            .any(|p| surface.starts_with(p))
        {
            return true;
        }
        let basename = surface.rsplit('/').next().unwrap_or(surface);
        self.config.protected_basenames.contains(basename)
    }

    /// Check a proposal. Returns the decision and journals it.
    pub fn check(&self, proposal: &Proposal) -> Decision {
        let level = self.level();
        let mut state = self.state.lock().expect("state lock");

        let decision = self.decide(level, proposal, &state);
        if matches!(decision, Decision::Permit) {
            state.last_apply = Some(Instant::now());
        }
        state.dedupe_set.insert(proposal.fingerprint.clone());
        state.dedupe.push_back(proposal.fingerprint.clone());
        while state.dedupe.len() > self.config.dedupe_capacity {
            if let Some(old) = state.dedupe.pop_front() {
                state.dedupe_set.remove(&old);
            }
        }
        self.journal(level, proposal, &decision);
        decision
    }

    fn decide(&self, level: Level, p: &Proposal, state: &State) -> Decision {
        if level == Level::Off {
            return Decision::Deny {
                reason: "autonomy level is off".into(),
            };
        }
        if state.dedupe_set.contains(&p.fingerprint) {
            return Decision::Deny {
                reason: "proposal already decided — not refiling".into(),
            };
        }
        if p.lines > self.config.max_lines || p.bytes > self.config.max_bytes {
            return Decision::Hold {
                reason: format!(
                    "oversize: {} lines/{} bytes exceeds {} line/{} byte cap — held for human",
                    p.lines, p.bytes, self.config.max_lines, self.config.max_bytes
                ),
            };
        }
        if self.is_protected(&p.surface) {
            return Decision::Hold {
                reason: format!(
                    "protected surface {} — proposed and logged for human review, never auto-applied",
                    p.surface
                ),
            };
        }
        match level {
            Level::Suggest => Decision::Hold {
                reason: "suggest level — recorded for review".into(),
            },
            Level::SafeApply | Level::Full => {
                if let Some(last) = state.last_apply {
                    if last.elapsed() < self.config.min_interval {
                        return Decision::Deny {
                            reason: format!(
                                "rate limited: {:.0}s since last apply < {}s minimum",
                                last.elapsed().as_secs_f64(),
                                self.config.min_interval.as_secs()
                            ),
                        };
                    }
                }
                Decision::Permit
            }
            Level::Off => unreachable!(),
        }
    }

    fn journal(&self, level: Level, p: &Proposal, d: &Decision) {
        let Some(path) = &self.config.journal_path else {
            return;
        };
        let ts = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let line = serde_json::json!({
            "ts": ts,
            "level": serde_json::to_value(level).unwrap_or(Value::Null),
            "surface": p.surface,
            "intent": p.intent,
            "lines": p.lines,
            "bytes": p.bytes,
            "fingerprint": p.fingerprint,
            "decision": serde_json::to_value(d).unwrap_or(Value::Null),
        });
        if let Ok(mut f) = fs::OpenOptions::new().create(true).append(true).open(path) {
            let _ = f.write_all(line.to_string().as_bytes());
            let _ = f.write_all(b"\n");
        }
    }
}

fn sha256_hex(data: &[u8]) -> String {
    hex::encode(Sha256::digest(data))
}

fn write_private(path: &PathBuf, bytes: &[u8]) -> std::io::Result<()> {
    fs::write(path, bytes)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o600));
    }
    Ok(())
}

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

    fn marshal(level: Level) -> Akicita {
        let mut config = Config::default();
        config
            .protected_basenames
            .insert("Engine.swift".to_string());
        Akicita::new(level, config, None)
    }

    #[test]
    fn off_denies_everything() {
        let a = marshal(Level::Off);
        let p = Proposal::patch("/tmp/x.rs", "a", "b", "test");
        assert!(matches!(a.check(&p), Decision::Deny { .. }));
    }

    #[test]
    fn suggest_holds_everything() {
        let a = marshal(Level::Suggest);
        let p = Proposal::patch("/tmp/x.rs", "a", "b", "test");
        assert!(matches!(a.check(&p), Decision::Hold { .. }));
    }

    #[test]
    fn safe_apply_permits_small_unprotected() {
        let a = marshal(Level::SafeApply);
        let p = Proposal::patch("/tmp/x.rs", "a", "b", "test");
        assert_eq!(a.check(&p), Decision::Permit);
    }

    #[test]
    fn protected_never_auto_applies_even_full() {
        let a = marshal(Level::Full);
        let p = Proposal::patch("/project/Engine.swift", "a", "b", "test");
        assert!(matches!(a.check(&p), Decision::Hold { .. }));
    }

    #[test]
    fn oversize_holds_not_denies() {
        let a = marshal(Level::SafeApply);
        let big = "x".repeat(2_000);
        let p = Proposal::patch("/tmp/x.rs", "", &big, "huge patch");
        assert!(matches!(a.check(&p), Decision::Hold { .. }));
    }

    #[test]
    fn dedupe_blocks_refiling() {
        let a = marshal(Level::SafeApply);
        let p = Proposal::patch("/tmp/x.rs", "a", "b", "test");
        a.check(&p);
        assert!(matches!(a.check(&p), Decision::Deny { .. }));
    }

    #[test]
    fn rate_limit_enforced() {
        let config = Config {
            min_interval: Duration::from_secs(3600),
            ..Config::default()
        };
        let a = Akicita::new(Level::Full, config, None);
        let p1 = Proposal::patch("/tmp/a.rs", "a", "b", "one");
        let p2 = Proposal::patch("/tmp/b.rs", "c", "d", "two");
        assert_eq!(a.check(&p1), Decision::Permit);
        assert!(matches!(a.check(&p2), Decision::Deny { .. }));
    }

    #[test]
    fn live_level_reload() {
        let dir = std::env::temp_dir().join(format!("akicita-test-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let level_path = dir.join("autopilot_level");
        fs::write(&level_path, "off").unwrap();
        let a = Akicita::new(Level::Full, Config::default(), Some(level_path.clone()));
        let p = Proposal::patch("/tmp/x.rs", "a", "b", "test");
        // Live read says off even though the marshal started at full.
        assert!(matches!(a.check(&p), Decision::Deny { .. }));
        fs::write(&level_path, "safe-apply").unwrap();
        let p2 = Proposal::patch("/tmp/y.rs", "a", "b", "test2");
        assert_eq!(a.check(&p2), Decision::Permit);
        let _ = fs::remove_dir_all(&dir);
    }
}