openlatch-client 0.3.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
//! The path → `TargetClass` resolver — plan 02 §2f, PRD §Client evaluator.
//!
//! Ordered, **first match wins**. Roots are bundle facts the customer can extend
//! (`env_selectors`, `data_store_roots`, `classified_sources`):
//!
//! | Order | Class | Seeds |
//! | ----- | ----- | ----- |
//! | 1 | `secret_material` | `.env*`, `~/.aws/**`, `~/.ssh/**`, `~/.kube/config`, `~/.docker/config.json`, `~/.netrc`, `*.pem`, `*.key`, `*.p12`, keychain/token files |
//! | 2 | `agent_config` | `.claude/**`, `.mcp.json`, `.claude.json`, `.git/hooks/**`, shell rc files, `.npmrc`, pre-commit / lefthook configs, IDE dirs |
//! | 3 | `system_path` | `/`, top-level dirs, home root, drive roots, cwd and its parents, `$PATH` dirs, `/etc` |
//! | 4 | `classified_source` | anything in the `classified_sources` fact |
//! | 5 | `data_store` | `*.db`, `*.sqlite*`, DB dumps, migration dirs, `/data/**`, `/var/lib/{postgresql,mysql,mongodb}/**`, `s3://`, `gs://`, plus `data_store_roots` |
//! | 6 | `workspace_file` | under the agent's working directory or additional directories |
//!
//! # Rows 3 and 6 read `Event.env`, and nothing else
//!
//! They need the home root, the cwd and its parents, the `$PATH` dirs, and the
//! agent's working directory — host state the Event carries as **declared
//! strings**. This resolver never stats a path and never walks a tree
//! (guarantee G4): the hook path walks up from the payload's working directory
//! and this one must not. A path that does not exist classifies exactly like one
//! that does, because neither is ever looked at.
//!
//! **With no `env` on the Event, neither row fires, and an absolute path no other
//! row places resolves to unknown — never a guessed `workspace_file`.**
//!
//! # portability-ok: these are classification data, not paths this process resolves
//!
//! `ci/check-portability.py` reads `/var/lib/mongodb/**`, `/etc/**` and `~/` as
//! POSIX assumptions, and everywhere else in this crate it would be right. Here
//! the whole file IS the resolver table: these literals are a description of
//! what a path MEANS, matched as text against a string the caller declared. The
//! engine never touches a filesystem at all — `ci/check-engine-purity.py` rule
//! `filesystem` enforces that, and it is a stronger claim than the waiver needs,
//! because the path classifier reads DECLARED STRINGS ONLY: a path that does not
//! exist classifies exactly like one that does. So a second gate proves what
//! this one is being asked to take on trust.
//!
//! The Windows rows sit in the same table for the same reason (`C:\\`,
//! `C:\\Windows\\**`) — a Windows agent's paths are classified by a Linux daemon
//! whenever a replay crosses hosts, so both vocabularies have to be present on
//! every platform. Waiving per file rather than per line is deliberate: 24
//! identical trailing comments would bury the one line where a future reader
//! should have thought harder.

use crate::generated::types::TargetClass;

use super::super::facts::FactSet;
use super::super::types::EventEnv;

// ── The seed lists ───────────────────────────────────────────────────
//
// Transcribed from the PRD's resolver table, in its order. `const`, not a
// `OnceLock`: they are derived from nothing and retained across nothing, which
// is what `ci/check-engine-purity.py` rule `global-state` is asking for.

/// Row 1. `.env` is `secret_material` before it is anything else.
pub const SECRET_MATERIAL_GLOBS: &[&str] = &[
    ".env",
    ".env.*",
    "**/.env",
    "**/.env.*",
    "~/.aws/**",
    "**/.aws/**",
    "~/.ssh/**",
    "**/.ssh/**",
    "~/.kube/config",
    "**/.kube/config",
    "~/.docker/config.json",
    "**/.docker/config.json",
    "~/.netrc",
    "**/.netrc",
    "*.pem",
    "**/*.pem",
    "*.key",
    "**/*.key",
    "*.p12",
    "**/*.p12",
    "**/keychain*",
    "**/*token*",
    "~/.config/gh/hosts.yml",
];

/// Row 2.
pub const AGENT_CONFIG_GLOBS: &[&str] = &[
    ".claude/**",
    "**/.claude/**",
    ".mcp.json",
    "**/.mcp.json",
    ".claude.json",
    "**/.claude.json",
    ".git/hooks/**",
    "**/.git/hooks/**",
    "~/.bashrc",
    "~/.zshrc",
    "~/.profile",
    "**/.bashrc",
    "**/.zshrc",
    "**/.profile",
    ".npmrc",
    "**/.npmrc",
    ".pre-commit-config.yaml",
    "**/.pre-commit-config.yaml",
    "lefthook.yml",
    "**/lefthook.yml",
    ".vscode/**",
    "**/.vscode/**",
    ".idea/**",
    "**/.idea/**",
];

/// Row 3, the part that is a pattern rather than a piece of `env`.
///
/// **`/var` is here and `/var/**` is not**, deliberately: `/var/lib/postgresql/**`
/// is row 5, and a `/var/**` seed would shadow it from row 3 and turn every
/// database directory into a `system_path`.
pub const SYSTEM_PATH_GLOBS: &[&str] = &[
    "/",
    "/etc",
    "/etc/**",
    "/usr",
    "/usr/**",
    "/bin",
    "/bin/**",
    "/sbin",
    "/sbin/**",
    "/lib",
    "/lib/**",
    "/opt",
    "/opt/**",
    "/boot",
    "/boot/**",
    "/proc",
    "/proc/**",
    "/sys",
    "/sys/**",
    "/var",
    "/dev",
    "/dev/**",
    "C:\\",
    "C:\\Windows\\**",
];

/// Row 5, before the customer's `data_store_roots` are added to it.
pub const DATA_STORE_GLOBS: &[&str] = &[
    "*.db",
    "**/*.db",
    "*.sqlite",
    "**/*.sqlite",
    "*.sqlite3",
    "**/*.sqlite3",
    "*.dump",
    "**/*.dump",
    "*.sql",
    "**/*.sql",
    "**/migrations/**",
    "/data/**",
    "/var/lib/postgresql/**",
    "/var/lib/mysql/**",
    "/var/lib/mongodb/**",
    "s3://**",
    "gs://**",
];

// ── Glob matching ────────────────────────────────────────────────────

/// `globset` semantics narrowed to what the seed lists use: `**` crosses `/`,
/// `*` and `?` do not, every other character is a literal.
///
/// `{a,b}` alternation and `[…]` classes are deliberately **not** supported, and
/// a brace or a bracket matches itself. They would serve one seed pattern; a
/// seed list that writes its three roots out in full costs a reader nothing,
/// while two extra pattern syntaxes cost every reader a translation.
///
/// Hand-rolled rather than `globset::Glob`: the whole matcher is thirty lines,
/// it needs no compile step to cache, and it cannot disagree with the oracle's
/// `glob_to_regex` about a corner it never implemented.
pub fn glob_match(pattern: &str, value: &str) -> bool {
    let pattern: Vec<char> = pattern.chars().collect();
    let value: Vec<char> = value.chars().collect();
    match_from(&pattern, 0, &value, 0)
}

fn match_from(pattern: &[char], mut pi: usize, value: &[char], mut vi: usize) -> bool {
    while pi < pattern.len() {
        if pattern[pi] == '*' {
            if pattern.get(pi + 1) == Some(&'*') {
                // `**` — any sequence, `/` included.
                let rest = pi + 2;
                if rest == pattern.len() {
                    return true;
                }
                return (vi..=value.len()).any(|k| match_from(pattern, rest, value, k));
            }
            // `*` — any sequence that does not cross a `/`.
            let rest = pi + 1;
            let mut k = vi;
            loop {
                if match_from(pattern, rest, value, k) {
                    return true;
                }
                if k >= value.len() || value[k] == '/' {
                    return false;
                }
                k += 1;
            }
        }
        let Some(&ch) = value.get(vi) else {
            return false;
        };
        if pattern[pi] == '?' {
            if ch == '/' {
                return false;
            }
        } else if pattern[pi] != ch {
            return false;
        }
        pi += 1;
        vi += 1;
    }
    vi == value.len()
}

// ── The host context rows 3 and 6 need ───────────────────────────────

/// [`EventEnv`] flattened into the four strings the resolver reads, so a caller
/// with no `env` and a caller with an empty one take the same path through here.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct PathEnv {
    pub home: String,
    pub cwd: String,
    pub path_dirs: Vec<String>,
    pub additional_dirs: Vec<String>,
}

impl PathEnv {
    /// Read the declared strings off the Event. `None` yields the empty context,
    /// under which rows 3 and 6 simply do not fire.
    pub fn from_event(env: Option<&EventEnv>) -> PathEnv {
        let Some(env) = env else {
            return PathEnv::default();
        };
        PathEnv {
            home: env.home.clone().unwrap_or_default(),
            cwd: env.cwd.clone().unwrap_or_default(),
            path_dirs: env.path_dirs.clone(),
            additional_dirs: env.additional_dirs.clone(),
        }
    }
}

// ── Fact-supplied roots ──────────────────────────────────────────────

/// The roots a set-shaped fact supplies, or `[]` when it does not resolve.
///
/// A fact that cannot be resolved contributes **no** roots. It never contributes
/// a default: an unresolvable `data_store_roots` means the customer's extra roots
/// are unknown, not that they are empty-and-therefore-fine — and the resulting
/// coverage gap on the path is what the atom's `on_inconclusive` then decides.
///
/// Staleness and the validity window are [`facts::resolve_set`]'s, read against
/// the frame's own `now_ms` off the [`FactSet`]. The classifier has no `now_ms`
/// parameter of its own and must not grow one: a second timestamp is a second
/// answer to "is this fact fresh?".
pub fn fact_members(facts: &FactSet, fact_id: &str) -> Vec<String> {
    super::super::facts::resolve_set(facts, fact_id, facts.now_ms).unwrap_or_default()
}

// ── The resolver ─────────────────────────────────────────────────────

/// Whether `path` is `root` or sits under it. Pure string comparison.
fn under(path: &str, root: &str) -> bool {
    if root.is_empty() {
        return false;
    }
    path == root || path.starts_with(&format!("{}/", root.trim_end_matches('/')))
}

fn same_dir(left: &str, right: &str) -> bool {
    !left.is_empty() && left.trim_end_matches('/') == right.trim_end_matches('/')
}

/// `~` and `~/…` against the declared home. The home is a **declared string**,
/// so expanding against it stays inside guarantee G4.
///
/// The oracle only builds the other direction — an absolute path re-written
/// `~`-relative so a `~/.ssh/**` seed can match it — and so answers `unknown` on
/// `cp /etc/hosts ~/proj/notes.md` even with an `env` in hand. Both directions
/// are the same substitution; doing only one leaves a path the caller fully
/// described unplaceable.
fn expand_home(path: &str, home: &str) -> Option<String> {
    if home.is_empty() {
        return None;
    }
    if path == "~" {
        return Some(home.to_string());
    }
    path.strip_prefix("~/")
        .map(|rest| format!("{}/{rest}", home.trim_end_matches('/')))
}

/// One pattern, one match, in a loop.
///
/// Up to four combinations per pattern — the path and its `~`-relative form,
/// against the pattern and its `~`-expanded form — because a seed written
/// `~/.ssh/**` has to match `/home/dev/.ssh/id_rsa` and a seed written
/// `**/.ssh/**` has to match both. With no `home` only the literal patterns can
/// fire.
fn match_any(path: &str, patterns: &[&str], env: &PathEnv) -> bool {
    match_any_owned(path, patterns.iter().map(|p| (*p).to_string()), env)
}

fn match_any_owned<I: IntoIterator<Item = String>>(path: &str, patterns: I, env: &PathEnv) -> bool {
    let mut candidates = vec![path.to_string()];
    if !env.home.is_empty() {
        if let Some(rest) = path.strip_prefix(env.home.as_str()) {
            candidates.push(format!("~{rest}"));
        }
        if let Some(expanded) = expand_home(path, &env.home) {
            candidates.push(expanded);
        }
    }
    for pattern in patterns {
        let expanded = match pattern.strip_prefix('~') {
            Some(rest) if !env.home.is_empty() => format!("{}{rest}", env.home),
            _ => pattern.clone(),
        };
        for candidate in &candidates {
            if glob_match(&pattern, candidate) || glob_match(&expanded, candidate) {
                return true;
            }
        }
    }
    false
}

/// Resolve one path to its target class, or `None` when no row places it.
///
/// Returning `None` rather than guessing `workspace_file` is the whole point:
/// an absolute path the resolver cannot place is a coverage gap the caller turns
/// into an `unknown`, not a quietly-downgraded workspace write.
pub fn resolve(path: &str, env: Option<&EventEnv>, facts: &FactSet) -> Option<TargetClass> {
    resolve_with(path, &PathEnv::from_event(env), facts)
}

/// [`resolve`], against an already-flattened context — the shell classifier
/// resolves dozens of operands per command and builds the context once.
pub fn resolve_with(path: &str, env: &PathEnv, facts: &FactSet) -> Option<TargetClass> {
    if path.is_empty() {
        return None;
    }
    let class = |name: &str| Some(TargetClass(name.to_string()));
    // `~/proj/x` and `/home/dev/proj/x` are the same path when the Event says
    // what home is; the row-3 and row-6 comparisons read the expanded form.
    let absolute = expand_home(path, &env.home).unwrap_or_else(|| path.to_string());

    if match_any(path, SECRET_MATERIAL_GLOBS, env) {
        return class("secret_material");
    }
    if match_any(path, AGENT_CONFIG_GLOBS, env) {
        return class("agent_config");
    }
    if match_any(path, SYSTEM_PATH_GLOBS, env) {
        return class("system_path");
    }
    // Row 3's `env` half: the home root, the cwd's PARENTS, and the `$PATH` dirs.
    if same_dir(&absolute, &env.home) {
        return class("system_path");
    }
    if !env.cwd.is_empty() && !same_dir(&absolute, &env.cwd) && under(&env.cwd, &absolute) {
        return class("system_path");
    }
    if env.path_dirs.iter().any(|dir| same_dir(&absolute, dir)) {
        return class("system_path");
    }
    if match_any_owned(path, fact_members(facts, "classified_sources"), env) {
        return class("classified_source");
    }
    if match_any(path, DATA_STORE_GLOBS, env) {
        return class("data_store");
    }
    if fact_members(facts, "data_store_roots")
        .iter()
        .any(|root| under(&absolute, root))
    {
        return class("data_store");
    }
    // A relative path is under the working directory by construction.
    if !path.starts_with('/') && !path.starts_with('~') && !path.contains("://") {
        return class("workspace_file");
    }
    if under(&absolute, &env.cwd) || env.additional_dirs.iter().any(|dir| under(&absolute, dir)) {
        return class("workspace_file");
    }
    None
}

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

    fn env() -> PathEnv {
        PathEnv {
            home: "/home/dev".to_string(),
            cwd: "/home/dev/proj".to_string(),
            path_dirs: vec!["/usr/local/bin".to_string()],
            additional_dirs: vec!["/srv/extra".to_string()],
        }
    }

    fn class_of(path: &str, env: &PathEnv) -> Option<String> {
        resolve_with(path, env, &FactSet::default()).map(|c| c.0)
    }

    #[test]
    fn double_star_crosses_a_slash_and_single_star_does_not() {
        assert!(glob_match("**/*.pem", "certs/nested/server.pem"));
        assert!(!glob_match("*.pem", "certs/server.pem"));
        assert!(glob_match("*.pem", "server.pem"));
        assert!(glob_match("**/migrations/**", "db/migrations/0001.py"));
        assert!(!glob_match("/etc/**", "/etcetera/x"));
    }

    #[test]
    fn a_backslash_in_a_windows_seed_is_a_literal() {
        assert!(glob_match(
            "C:\\Windows\\**",
            "C:\\Windows\\System32\\hosts"
        ));
        assert!(!glob_match("C:\\Windows\\**", "C:/Windows/System32"));
    }

    #[test]
    fn the_order_is_the_semantics() {
        let env = PathEnv::default();
        assert_eq!(
            class_of("config/.env", &env).as_deref(),
            Some("secret_material")
        );
        assert_eq!(
            class_of(".claude/x.md", &env).as_deref(),
            Some("agent_config")
        );
        // `/var` is row 3 and `/var/lib/postgresql/**` is row 5: the narrower
        // seed must win, which it only does because `/var/**` is not row 3.
        assert_eq!(
            class_of("/var/lib/postgresql/16/base", &env).as_deref(),
            Some("data_store")
        );
    }

    #[test]
    fn rows_three_and_six_need_env_and_stay_silent_without_it() {
        let none = PathEnv::default();
        assert_eq!(class_of("/home/dev", &none), None, "no env, no home root");
        assert_eq!(class_of("/srv/extra/notes.md", &none), None);
        let env = env();
        assert_eq!(class_of("/home/dev", &env).as_deref(), Some("system_path"));
        assert_eq!(
            class_of("/usr/local/bin", &env).as_deref(),
            Some("system_path")
        );
        assert_eq!(
            class_of("/srv/extra/notes.md", &env).as_deref(),
            Some("workspace_file")
        );
    }

    #[test]
    fn an_unplaceable_absolute_path_is_never_a_guessed_workspace_file() {
        assert_eq!(class_of("/srv/blob/opaque.bin", &env()), None);
    }

    #[test]
    fn a_tilde_resolves_against_the_declared_home_and_not_the_host() {
        assert_eq!(
            class_of("~/proj/notes.md", &env()).as_deref(),
            Some("workspace_file")
        );
        assert_eq!(
            class_of("~/tmp/stale", &PathEnv::default()),
            None,
            "with no declared home there is nothing to expand against"
        );
    }

    #[test]
    fn a_customer_root_arrives_as_a_fact_and_not_as_a_constant() {
        let facts = FactSet::new(
            vec![serde_json::from_value(serde_json::json!({
                "fact_id": "data_store_roots",
                "kind": "set",
                "observed_at": "2025-09-01T15:59:00+00:00",
                "max_age_s": 86400,
                "value": ["/lake"],
            }))
            .expect("the fixture fact parses")],
            1_756_742_400_000,
        );
        assert_eq!(
            resolve_with("/lake/raw/x.parquet", &PathEnv::default(), &facts).map(|c| c.0),
            Some("data_store".to_string())
        );
        assert_eq!(
            resolve_with(
                "/lake/raw/x.parquet",
                &PathEnv::default(),
                &FactSet::default()
            ),
            None,
            "without the fact the root is unknown, not empty-and-therefore-fine"
        );
    }
}