doover-core 0.1.0

Core library for doover: session-scoped snapshot, journal, and undo for AI agent shell actions
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
//! Reversibility registry: classifies commands and shell constructs by effect,
//! affected-path scope, and undo strategy. Data lives in `registry/*.yaml`
//! (CC0); a user overlay directory can add rules or *upgrade* severity, but a
//! shipped destructive classification can never be silently downgraded.

use serde::Deserialize;
use std::collections::HashMap;
use std::path::Path;

/// Effect classes ordered by severity: later variants are strictly more
/// dangerous. `Ord` is load-bearing — the overlay downgrade check relies on it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Effect {
    Safe,
    Mutating,
    Externalizing,
    Destructive,
    Irreversible,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum UndoStrategy {
    SnapshotRestore,
    None,
    Recompute,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PathSource {
    Positional,
    PositionalLast,
    RedirectTarget,
    Repo,
    None,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ScopeSpec {
    pub paths: PathSource,
    #[serde(default = "default_true")]
    pub globs: bool,
    /// Leading positional arguments that are not paths (sed scripts, chmod
    /// modes) and must be dropped before scope extraction.
    #[serde(default)]
    pub skip: usize,
    /// Flags that consume the following argument (`truncate -s 0`): that
    /// argument is not a path and must not enter the scope.
    #[serde(default)]
    pub flag_args: Vec<String>,
    /// Flags whose value *is* a target path to snapshot, in either the
    /// separate (`-o out.txt`) or attached (`--output=out.txt`) form.
    #[serde(default)]
    pub path_flags: Vec<String>,
    #[serde(default)]
    pub recursive_flags: Vec<String>,
}

fn default_true() -> bool {
    true
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MatchSpec {
    pub command: Option<String>,
    pub subcommand: Option<String>,
    pub flags_any: Option<Vec<String>>,
    pub redirect: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rule {
    pub id: String,
    #[serde(rename = "match")]
    pub matcher: MatchSpec,
    pub effect: Effect,
    #[serde(default)]
    pub scope: Option<ScopeSpec>,
    pub undo: UndoStrategy,
    #[serde(default)]
    pub notes: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RegistryFile {
    rules: Vec<Rule>,
}

#[derive(Debug, thiserror::Error)]
pub enum RegistryError {
    #[error("failed to parse {file}: {source}")]
    Parse {
        file: String,
        #[source]
        source: serde_yaml::Error,
    },
    #[error("invalid rule `{id}` in {file}: {reason}")]
    InvalidRule {
        file: String,
        id: String,
        reason: String,
    },
    #[error("duplicate rule id `{id}`")]
    DuplicateId { id: String },
    #[error("failed to read {path}: {source}")]
    Io {
        path: String,
        #[source]
        source: std::io::Error,
    },
}

/// Shipped registry data, embedded at compile time.
const SHIPPED: &[(&str, &str)] = &[
    ("coreutils.yaml", include_str!("../registry/coreutils.yaml")),
    ("shell.yaml", include_str!("../registry/shell.yaml")),
    ("git.yaml", include_str!("../registry/git.yaml")),
    ("net.yaml", include_str!("../registry/net.yaml")),
    ("posix.yaml", include_str!("../registry/posix.yaml")),
    ("services.yaml", include_str!("../registry/services.yaml")),
];

pub struct Registry {
    rules: Vec<Rule>,
    index: HashMap<String, usize>,
    /// Number of leading rules that are SHIPPED (built-in). Everything at or
    /// after this index is a user overlay. Lookup uses this to enforce a
    /// protection floor: an overlay can never resolve a command to a WEAKER
    /// effect than the shipped registry alone would (the shadow-attack guard,
    /// round 21) — regardless of rule id, match score, or tie-breaks.
    shipped_count: usize,
}

impl Registry {
    /// Parse and validate the rules of one YAML document. Public so tests and
    /// future tooling (registry linters, the doctor command) can reuse it.
    pub fn parse_rules(file: &str, contents: &str) -> Result<Vec<Rule>, RegistryError> {
        let parsed: RegistryFile =
            serde_yaml::from_str(contents).map_err(|source| RegistryError::Parse {
                file: file.to_string(),
                source,
            })?;
        for rule in &parsed.rules {
            validate(file, rule)?;
        }
        Ok(parsed.rules)
    }

    /// Build a registry from already-parsed rules, rejecting duplicate ids.
    pub fn from_rules(rules: Vec<Rule>) -> Result<Self, RegistryError> {
        let mut index = HashMap::with_capacity(rules.len());
        for (i, rule) in rules.iter().enumerate() {
            if index.insert(rule.id.clone(), i).is_some() {
                return Err(RegistryError::DuplicateId {
                    id: rule.id.clone(),
                });
            }
        }
        let shipped_count = rules.len();
        Ok(Self {
            rules,
            index,
            shipped_count,
        })
    }

    /// The shipped registry. Must always be valid — a failure here is a bug
    /// caught by the T2 suite, never a runtime condition.
    pub fn builtin() -> Result<Self, RegistryError> {
        let mut rules = Vec::new();
        for (file, contents) in SHIPPED {
            rules.extend(Self::parse_rules(file, contents)?);
        }
        Self::from_rules(rules)
    }

    /// Builtin rules plus a user overlay directory (`*.yaml`, lexical order).
    /// Overlay problems are warnings, never failures: a broken user file must
    /// not take the safety net down with it. Severity downgrades of shipped
    /// destructive/irreversible rules are rejected loudly.
    pub fn with_overlay(dir: &Path) -> Result<(Self, Vec<String>), RegistryError> {
        let mut registry = Self::builtin()?;
        let mut warnings = Vec::new();

        if !dir.is_dir() {
            return Ok((registry, warnings));
        }
        let mut entries: Vec<_> = std::fs::read_dir(dir)
            .map_err(|source| RegistryError::Io {
                path: dir.display().to_string(),
                source,
            })?
            .filter_map(Result::ok)
            .map(|e| e.path())
            .filter(|p| {
                p.extension()
                    .is_some_and(|ext| ext == "yaml" || ext == "yml")
            })
            .collect();
        entries.sort();

        for path in entries {
            let file = path.display().to_string();
            let contents = match std::fs::read_to_string(&path) {
                Ok(c) => c,
                Err(e) => {
                    warnings.push(format!("skipping {file}: {e}"));
                    continue;
                }
            };
            let rules = match Self::parse_rules(&file, &contents) {
                Ok(r) => r,
                Err(e) => {
                    warnings.push(format!("skipping {file}: {e}"));
                    continue;
                }
            };
            for rule in rules {
                registry.insert_overlay(rule, &mut warnings);
            }
        }
        Ok((registry, warnings))
    }

    fn insert_overlay(&mut self, rule: Rule, warnings: &mut Vec<String>) {
        match self.index.get(&rule.id) {
            Some(&i) => {
                let shipped = &self.rules[i];
                // never let a user overlay quietly weaken a safety-relevant
                // shipped classification. Both data-loss (destructive/
                // irreversible) and exfiltration (externalizing) qualify —
                // downgrading either could disable a protection the user relies
                // on without them noticing.
                if is_protected(shipped.effect) && rule.effect < shipped.effect {
                    warnings.push(format!(
                        "refusing to downgrade `{}` from {:?} to {:?}; overlay rule ignored",
                        rule.id, shipped.effect, rule.effect
                    ));
                    return;
                }
                self.rules[i] = rule;
            }
            None => {
                // A new-id overlay rule that matches the same command as a
                // protected shipped rule but classifies it WEAKER is a shadow
                // attempt. The lookup floor already prevents the downgrade;
                // warn so the user knows their rule was (partially) ignored
                // (round 21).
                if let Some(cmd) = rule.matcher.command.as_deref() {
                    let shadows_protected = self.rules[..self.shipped_count].iter().any(|s| {
                        s.matcher.command.as_deref() == Some(cmd)
                            && is_protected(s.effect)
                            && rule.effect < s.effect
                    });
                    if shadows_protected {
                        warnings.push(format!(
                            "overlay `{}` classifies `{cmd}` weaker than the shipped protection; \
                             the downgrade is ignored at lookup (safety floor)",
                            rule.id
                        ));
                    }
                }
                self.index.insert(rule.id.clone(), self.rules.len());
                self.rules.push(rule);
            }
        }
    }

    /// Most-specific match for a simple command: a rule with a matching
    /// subcommand outranks a bare-command rule, and a matching `flags_any`
    /// outranks both. Rules with a subcommand or flags requirement that the
    /// invocation doesn't satisfy don't match at all.
    pub fn lookup_command<'a>(
        &'a self,
        command: &str,
        subcommand: Option<&str>,
        flags: &[String],
    ) -> Option<&'a Rule> {
        let best = |rules: &'a [Rule]| -> Option<&'a Rule> {
            rules
                .iter()
                .filter_map(|rule| {
                    score_command_match(rule, command, subcommand, flags).map(|s| (s, rule))
                })
                // most specific match wins; on a tie, the STRONGER effect wins
                // (a protection tool must never resolve a tie toward the less
                // dangerous classification); id only for final determinism
                .max_by(|(sa, ra), (sb, rb)| {
                    sa.cmp(sb)
                        .then_with(|| ra.effect.cmp(&rb.effect))
                        .then_with(|| rb.id.cmp(&ra.id))
                })
                .map(|(_, rule)| rule)
        };
        let overall = best(&self.rules);
        // Protection floor (shadow-attack guard, round 21): an overlay may
        // add or STRENGTHEN a classification, never weaken the shipped one.
        // If the shipped-only best is protected and stronger than the overall
        // winner, the shipped rule stands — no overlay id/score/tie-break can
        // downgrade `rm` to safe.
        let shipped = best(&self.rules[..self.shipped_count]);
        match (overall, shipped) {
            (Some(o), Some(s)) if is_protected(s.effect) && s.effect > o.effect => Some(s),
            (o, _) => o,
        }
    }

    pub fn lookup_redirect(&self, op: &str) -> Option<&Rule> {
        self.rules
            .iter()
            .find(|rule| rule.matcher.redirect.as_deref() == Some(op))
    }

    pub fn rules(&self) -> impl Iterator<Item = &Rule> {
        self.rules.iter()
    }

    pub fn len(&self) -> usize {
        self.rules.len()
    }

    pub fn is_empty(&self) -> bool {
        self.rules.is_empty()
    }
}

/// Match score of `rule` against a command invocation, or `None` if the rule
/// does not apply. Shared by the overall and shipped-only lookup passes so the
/// protection floor compares like with like.
fn score_command_match(
    rule: &Rule,
    command: &str,
    subcommand: Option<&str>,
    flags: &[String],
) -> Option<usize> {
    let m = &rule.matcher;
    if m.command.as_deref() != Some(command) {
        return None;
    }
    let mut score = 1usize;
    if let Some(want) = m.subcommand.as_deref() {
        if subcommand != Some(want) {
            return None;
        }
        score += 2;
    }
    if let Some(want_any) = &m.flags_any {
        // a flag is value-taking when the rule itself declares it
        // consumes/carries a value; only then can `-oVALUE` attached-short
        // forms match (never `-rf` boolean clusters)
        let value_taking = |w: &str| {
            rule.scope.as_ref().is_some_and(|s| {
                s.path_flags.iter().any(|x| x == w) || s.flag_args.iter().any(|x| x == w)
            })
        };
        if !want_any
            .iter()
            .any(|w| flags.iter().any(|f| flag_matches(f, w, value_taking(w))))
        {
            return None;
        }
        score += 4;
    }
    Some(score)
}

/// Whether an observed flag token satisfies a wanted flag: exact match, the
/// `--long=value` attached form, or — only for value-taking flags — the
/// `-oVALUE` attached-short form.
fn flag_matches(observed: &str, want: &str, value_taking: bool) -> bool {
    observed == want
        || (want.starts_with("--")
            && observed
                .split_once('=')
                .is_some_and(|(name, _)| name == want))
        || (value_taking
            && want.len() == 2
            && want.starts_with('-')
            && !want.starts_with("--")
            && observed.len() > 2
            && observed.starts_with(want))
}

/// Safety-relevant classifications an overlay may not silently weaken:
/// externalizing (exfiltration) and above (data loss).
fn is_protected(effect: Effect) -> bool {
    effect >= Effect::Externalizing
}

fn validate(file: &str, rule: &Rule) -> Result<(), RegistryError> {
    let fail = |reason: &str| {
        Err(RegistryError::InvalidRule {
            file: file.to_string(),
            id: rule.id.clone(),
            reason: reason.to_string(),
        })
    };
    if rule.id.trim().is_empty() {
        return fail("empty id");
    }
    let m = &rule.matcher;
    match (&m.command, &m.redirect) {
        (Some(_), Some(_)) => {
            return fail("match must have exactly one of `command` or `redirect`, not both");
        }
        (None, None) => return fail("match must have one of `command` or `redirect`"),
        (None, Some(_)) if m.subcommand.is_some() || m.flags_any.is_some() => {
            return fail("`subcommand`/`flags_any` require `command`");
        }
        _ => {}
    }
    Ok(())
}