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
//! The effect classifier — plan 02 §2f, PRD §Client evaluator.
//!
//! One tool call in, `(verb, target_class)` tuples plus the coverage gaps around
//! them out. Two layers, in this order:
//!
//! 1. a **syntactic** pass — pull the paths and URLs out of `tool_input` and
//!    resolve each path to a `TargetClass`. No policy, no verbs. A feed selector
//!    may read `path.class`, so this has to happen first.
//! 2. an **effect** pass — the bundle's `effect_classes` feed first (keyed by
//!    `tool_key`), the built-in table second, and for a shell tool the shell
//!    classifier.
//!
//! The tables are frozen in the PRD and ship as data on the feed: the path →
//! `TargetClass` resolver (ordered, first match wins, roots from the
//! `env_selectors` / `data_store_roots` / `classified_sources` facts), the shell
//! → effect table, the built-in tool table, and the MCP feed keyed by `tool_key`.
//! **One conformance fixture per table row.**
//!
//! # D-15 — the one thing the spike caught
//!
//! Unknown-ness is **per simple command** and is carried **alongside** confident
//! tuples, never in place of them. `rm -rf /data/x && $UNKNOWN_CMD` classified as
//! wholly `unknown` ERASED the confident `delete × data_store` from the `rm`; the
//! action then matched no rule at all and was silently allowed. One unmapped
//! sibling disarmed the enforcement. That is why [`Classification`] is a struct
//! with two accumulators and not a `Result`.
//!
//! Join rule: effect-class atoms see `unknown` and go to ASK (Z19) **if** their
//! target tuple is not already covered by `effects`. Value-shaped atoms run over
//! the raw string and every literal argv regardless — an explicit Block-shaped
//! value atom still Blocks on garbage.
//!
//! # Guarantee G4, and why it is not incidental here
//!
//! Nothing under this directory touches the filesystem. The hook path walks up
//! the directory tree from the payload's working directory; the path classifier
//! reads **declared strings only** — no `canonicalize`, no `exists`, no
//! metadata. A path that does not exist classifies exactly like one that does,
//! which is what lets this run on a box holding nothing but the binary, and what
//! makes a replay of a corpus row reproducible on a machine that never had the
//! files.

pub mod mcp;
pub mod path;
pub mod shell;

use crate::generated::types::{EffectVerb, PolicyBundleEffectClasses, TargetClass};

use super::facts::FactSet;
use super::types::{
    Classification, ClassifiedPath, ClassifiedUrl, Effect, Event, UnknownCommand, UrlBoundary,
};

/// Keys in a `tool_input` that name a filesystem path.
pub const PATH_KEYS: &[&str] = &[
    "file_path",
    "filePath",
    "path",
    "notebook_path",
    "notebookPath",
    "file",
];
/// Keys in a `tool_input` that name a URL.
pub const URL_KEYS: &[&str] = &["url", "uri"];

/// Tools whose input is a shell command line.
pub const SHELL_TOOLS: &[&str] = &["Bash", "BashOutput", "PowerShell"];

/// The built-in tool table — PRD §Coverage matrix (Claude Code, Mode 1).
///
/// `"PATH"` means: resolve the target class from the call's own path arguments.
///
/// A tool with **no row and no feed entry produces no tuples**. That is not an
/// oversight and not an error: the feed is how a newly popular tool becomes
/// classifiable, and inventing a verb for a tool nobody has classified would be
/// a guess with enforcement consequences. Value-shaped atoms still run over
/// `input.strings`, so the action is not unobserved — only unclassified.
const BUILTIN_TOOLS: &[(&str, &[(&str, &str)])] = &[
    ("Read", &[("read", "PATH")]),
    ("Glob", &[("read", "PATH")]),
    ("Grep", &[("read", "PATH")]),
    ("Write", &[("write", "PATH")]),
    ("Edit", &[("write", "PATH")]),
    ("MultiEdit", &[("write", "PATH")]),
    ("NotebookEdit", &[("write", "PATH")]),
    (
        "WebFetch",
        &[("network_egress", "network_host"), ("read", "network_host")],
    ),
    (
        "WebSearch",
        &[("network_egress", "network_host"), ("read", "network_host")],
    ),
    (
        "Task",
        &[("delegate", "model_call"), ("spend", "model_call")],
    ),
    (
        "Agent",
        &[("delegate", "model_call"), ("spend", "model_call")],
    ),
    ("AskUserQuestion", &[]),
    ("TodoWrite", &[]),
    ("ExitPlanMode", &[]),
];

// ── The two accumulators ─────────────────────────────────────────────

/// Build an `attrs` map. `effect.attrs.<name>` reads these — `is_production`,
/// `force`, `branch`, `program`.
pub fn attrs_of(pairs: &[(&str, serde_json::Value)]) -> serde_json::Map<String, serde_json::Value> {
    pairs
        .iter()
        .map(|(key, value)| ((*key).to_string(), value.clone()))
        .collect()
}

/// Record a confident tuple. Duplicates collapse; **order is preserved**, and it
/// is load-bearing: the corpus compares `effects` as a list.
pub fn add_effect(
    cls: &mut Classification,
    verb: &str,
    target_class: &str,
    attrs: serde_json::Map<String, serde_json::Value>,
) {
    let effect = Effect {
        verb: EffectVerb(verb.to_string()),
        target_class: TargetClass(target_class.to_string()),
        attrs,
    };
    if !cls.effects.contains(&effect) {
        cls.effects.push(effect);
    }
}

/// Record a coverage gap. **Never drops or replaces a confident tuple** (D-15).
///
/// It also adds `unknown × shell`, because `unknown` is an ordinary `EffectVerb`
/// and that tuple is what an effect-class atom sees when it goes to ASK.
pub fn add_unknown(cls: &mut Classification, shape: i64, reason: String, command: &str) {
    let entry = UnknownCommand {
        shape,
        reason,
        command: command.to_string(),
    };
    if !cls.unknown.contains(&entry) {
        cls.unknown.push(entry);
    }
    add_effect(cls, "unknown", "shell", attrs_of(&[]));
}

// ── The entry point ──────────────────────────────────────────────────

/// Classify one action into effect tuples plus the coverage gaps around them.
///
/// Order: the bundle's `effect_classes` feed first, then the built-in table, and
/// for a shell tool the shell classifier.
pub fn classify(
    event: &Event,
    facts: &FactSet,
    feed: Option<&PolicyBundleEffectClasses>,
) -> Classification {
    let mut cls = Classification::default();
    let env = path::PathEnv::from_event(event.env.as_ref());

    // The syntactic layer first: paths and URLs exist independently of any verb,
    // and a feed selector may read `path.class` or `url.host`.
    for raw in collect(&event.tool_input, PATH_KEYS) {
        if let Some(class) = path::resolve_with(&raw, &env, facts) {
            cls.paths.push(ClassifiedPath { class, value: raw });
        }
    }
    for raw in collect(&event.tool_input, URL_KEYS) {
        if let Some(url) = parse_url(&raw) {
            cls.urls.push(url);
        }
    }

    let entries = mcp::entries_for(feed, &event.tool_name);
    if !entries.is_empty() && mcp::apply(&entries, event, &mut cls, facts) {
        return cls;
    }

    if SHELL_TOOLS.contains(&event.tool_name.as_str()) {
        let command = event
            .tool_input
            .get("command")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default();
        shell::classify_into(command, &mut cls, facts, &env);
        return cls;
    }

    let Some(row) = builtin_row(&event.tool_name) else {
        // No feed entry and no built-in row. **Not** an unknown shape — the
        // shapes are about shell commands.
        return cls;
    };
    for (verb, target_class) in row {
        if *target_class != "PATH" {
            add_effect(&mut cls, verb, target_class, attrs_of(&[]));
            continue;
        }
        let classes: Vec<String> = cls.paths.iter().map(|p| p.class.0.clone()).collect();
        if classes.is_empty() {
            add_unknown(
                &mut cls,
                10,
                format!("{}: no resolvable path operand", event.tool_name),
                &event.tool_name,
            );
            continue;
        }
        for class in classes {
            add_effect(&mut cls, verb, &class, attrs_of(&[]));
        }
    }
    cls
}

fn builtin_row(tool_name: &str) -> Option<&'static [(&'static str, &'static str)]> {
    BUILTIN_TOOLS
        .iter()
        .find(|(name, _)| *name == tool_name)
        .map(|(_, row)| *row)
}

/// The built-in tool table, as tuples, for a caller that wants the row rather
/// than the classification. `None` means "not a built-in", which sends the tool
/// to the feed lookup.
///
/// The `PATH` rows resolve against the call's own operands and so cannot be
/// answered from the tool name alone; they come back with the literal target
/// class `PATH`, exactly as the table writes it.
pub fn builtin_tool_effects(tool_name: &str) -> Option<Vec<Effect>> {
    builtin_row(tool_name).map(|row| {
        row.iter()
            .map(|(verb, target_class)| Effect {
                verb: EffectVerb((*verb).to_string()),
                target_class: TargetClass((*target_class).to_string()),
                attrs: serde_json::Map::new(),
            })
            .collect()
    })
}

/// Every string under one of `keys`, anywhere in the input. Recursive, and dumb
/// on purpose: a tool nobody has modelled still has its `file_path` read.
fn collect(value: &serde_json::Value, keys: &[&str]) -> Vec<String> {
    let mut out = Vec::new();
    collect_into(value, keys, &mut out);
    out
}

fn collect_into(value: &serde_json::Value, keys: &[&str], out: &mut Vec<String>) {
    match value {
        serde_json::Value::Object(map) => {
            for (key, child) in map {
                if keys.contains(&key.as_str()) {
                    if let serde_json::Value::String(text) = child {
                        out.push(text.clone());
                    }
                }
                collect_into(child, keys, out);
            }
        }
        serde_json::Value::Array(items) => {
            for child in items {
                collect_into(child, keys, out);
            }
        }
        _ => {}
    }
}

// ── URL shape ────────────────────────────────────────────────────────

const PRIVATE_HOST_SUFFIXES: &[&str] =
    &[".local", ".internal", ".lan", ".home.arpa", ".localdomain"];
const PRIVATE_HOST_PREFIXES: &[&str] = &["10.", "127.", "192.168.", "169.254."];

/// RFC 1918's `172.16.0.0/12` — all sixteen blocks, not the three a string
/// prefix happens to spell.
///
/// `172.16.` through `172.31.` are private and `172.15.` / `172.32.` are not,
/// and that boundary is arithmetic, not textual. A prefix list gets thirteen of
/// the sixteen wrong **in the direction of calling an internal host external**,
/// so an atom gated on `url.boundary == internal` silently misses most of the
/// range.
fn is_private_172(host: &str) -> bool {
    let octets: Vec<&str> = host.split('.').collect();
    if octets.len() != 4 || !octets.iter().all(|o| o.chars().all(|c| c.is_ascii_digit())) {
        return false;
    }
    octets[0] == "172"
        && octets[1]
            .parse::<u32>()
            .is_ok_and(|n| (16..=31).contains(&n))
}

/// The `url.*` field family, on the `url` crate with `psl` for the suffix.
///
/// `url.tld` is the **registrable public suffix**, so `example.co.uk` yields
/// `co.uk`. The oracle has no PSL and yields the last label (`uk`) — a known,
/// documented divergence, which is why `tld_in` corpus rows are written against
/// single-label TLDs.
pub fn parse_url(raw: &str) -> Option<ClassifiedUrl> {
    if !raw.contains("://") {
        return None;
    }
    let parsed = url::Url::parse(raw).ok()?;
    // `host_str` has already dropped userinfo and the port, and brackets an IPv6
    // literal.
    let host = parsed.host_str().unwrap_or_default().to_lowercase();
    let tld = psl::suffix_str(&host)
        .map(str::to_string)
        .unwrap_or_else(|| {
            host.rsplit_once('.')
                .map(|(_, last)| last.to_string())
                .unwrap_or_default()
        });
    let internal = matches!(host.as_str(), "localhost" | "::1" | "[::1]")
        || !host.contains('.')
        || PRIVATE_HOST_SUFFIXES.iter().any(|s| host.ends_with(s))
        || PRIVATE_HOST_PREFIXES.iter().any(|p| host.starts_with(p))
        || is_private_172(&host);
    Some(ClassifiedUrl {
        value: raw.to_string(),
        host,
        tld,
        scheme: parsed.scheme().to_lowercase(),
        boundary: if internal {
            UrlBoundary::Internal
        } else {
            UrlBoundary::External
        },
    })
}

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

    fn event(tool: &str, input: serde_json::Value) -> Event {
        Event {
            tool_name: tool.to_string(),
            tool_input: input,
            ..Event::default()
        }
    }

    fn tuples(cls: &Classification) -> Vec<String> {
        cls.effects
            .iter()
            .map(|e| format!("{}x{}", e.verb.0, e.target_class.0))
            .collect()
    }

    #[test]
    fn the_builtin_table_resolves_path_rows_from_the_calls_own_operands() {
        let cls = classify(
            &event(
                "Read",
                serde_json::json!({"file_path": "/data/warehouse/x.db"}),
            ),
            &FactSet::default(),
            None,
        );
        assert_eq!(tuples(&cls), vec!["readxdata_store"]);
    }

    #[test]
    fn a_path_row_with_no_resolvable_operand_is_a_coverage_gap_not_a_guess() {
        let cls = classify(
            &event(
                "Read",
                serde_json::json!({"file_path": "/srv/blob/opaque.bin"}),
            ),
            &FactSet::default(),
            None,
        );
        assert_eq!(tuples(&cls), vec!["unknownxshell"]);
        assert_eq!(cls.unknown.first().map(|u| u.shape), Some(10));
    }

    #[test]
    fn a_tool_nobody_has_classified_produces_no_tuple_and_no_shape() {
        let cls = classify(
            &event(
                "mcp__jira__create_issue",
                serde_json::json!({"summary": "x"}),
            ),
            &FactSet::default(),
            None,
        );
        assert!(cls.effects.is_empty() && cls.unknown.is_empty());
    }

    #[test]
    fn the_no_effect_tools_really_produce_none() {
        for tool in ["AskUserQuestion", "TodoWrite", "ExitPlanMode"] {
            let cls = classify(
                &event(tool, serde_json::json!({})),
                &FactSet::default(),
                None,
            );
            assert!(cls.effects.is_empty(), "{tool} should carry no effect");
        }
    }

    /// `path.value` has no other home: a `read × workspace_file` tuple does not
    /// say WHICH path produced it, so `paths` is not redundant with `effects`.
    #[test]
    fn a_builtin_tool_call_records_the_path_and_the_url_it_named() {
        let cls = classify(
            &event(
                "Read",
                serde_json::json!({"file_path": "/home/dev/.aws/credentials"}),
            ),
            &FactSet::default(),
            None,
        );
        assert_eq!(cls.paths.len(), 1);
        assert_eq!(cls.paths[0].value, "/home/dev/.aws/credentials");
        assert_eq!(cls.paths[0].class.0, "secret_material");

        let cls = classify(
            &event(
                "WebFetch",
                serde_json::json!({"url": "https://API.Example.com/v1"}),
            ),
            &FactSet::default(),
            None,
        );
        assert_eq!(cls.urls.len(), 1);
        assert_eq!(cls.urls[0].host, "api.example.com", "lowercased");
        assert_eq!(cls.urls[0].scheme, "https");
        assert_eq!(cls.urls[0].boundary, UrlBoundary::External);
    }

    #[test]
    fn the_url_boundary_is_arithmetic_and_not_a_string_prefix() {
        for host in ["172.16.0.1", "172.20.5.5", "172.31.255.254"] {
            let url = parse_url(&format!("https://{host}/x")).expect("parses");
            assert_eq!(url.boundary, UrlBoundary::Internal, "{host} is RFC 1918");
        }
        for host in ["172.15.0.1", "172.32.0.1"] {
            let url = parse_url(&format!("https://{host}/x")).expect("parses");
            assert_eq!(url.boundary, UrlBoundary::External, "{host} is not");
        }
    }

    #[test]
    fn the_tld_is_the_public_suffix_and_not_the_last_label() {
        assert_eq!(
            parse_url("https://a.example.co.uk/x").expect("parses").tld,
            "co.uk"
        );
    }
}