openlatch-client 0.6.6

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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
//! The effect classifier — plan 02 §2f, PRD §Client evaluator, AZ-4 §6.11.
//!
//! One tool call in, `(verb, target_class)` tuples plus the coverage gaps around
//! them out. The resolution of one action, in this order (D-4):
//!
//! 1. the **tool** entries of the bundle's [`catalogue::Catalogue`], keyed by the
//!    canonical tool name, and their `input_map`, which copies each mapped value
//!    onto a canonical key *before* anything is extracted from the input;
//! 2. a **syntactic** pass — pull the paths and URLs out of the (mapped) input and
//!    resolve each path to every `TargetClass` it carries. No policy, no verbs. A
//!    feed selector may read `path.class`, so this happens before selectors run;
//! 3. for a shell tool, the code rows of the shell classifier, then the **program**
//!    entries of the catalogue;
//! 4. every resolved path against the **target** entries — multi-class.
//!
//! **The evaluator holds no lookup table.** What `Read` does, what `rm` does and
//! what a path means arrive in the bundle (spec §6.11); what is left in code is
//! logic that is not a lookup (D-I16-30). **One conformance fixture per rule.**
//!
//! # 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 catalogue;
pub mod mcp;
pub mod path;
pub mod shell;

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

use super::facts::FactSet;
use super::types::{Classification, ClassifiedUrl, Effect, Event, UnknownCommand, UrlBoundary};
use catalogue::{Catalogue, Fallback, Origin, ToolEntry};

/// Keys in a `tool_input` that name a filesystem path: the canonical ones. Every
/// binding maps its native spellings onto them before evaluation (its alias
/// table, AZ-4 D-7), so no agent's own key is read here.
pub const PATH_KEYS: &[&str] = &["file_path", "path", "notebook_path"];
/// 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 canonical names of the tools the agents share. They carry no lookup row
/// here — what each one does is a seed entry of the catalogue — and a name that
/// appears here is never `unknown` for lack of an entry.
const BUILTIN_TOOLS: &[&str] = &[
    "Read",
    "Glob",
    "Grep",
    "Write",
    "Edit",
    "MultiEdit",
    "NotebookEdit",
    "WebFetch",
    "WebSearch",
    "Task",
    "Agent",
    "AskUserQuestion",
    "TodoWrite",
    "ExitPlanMode",
];

/// The classes a path resolves to. A `file_path` role with one of these resolves
/// the class per call instead of using the entry's fixed one.
const PATH_CLASSES: &[&str] = &[
    "secret_material",
    "agent_config",
    "system_path",
    "classified_source",
    "data_store",
    "workspace_file",
];

// ── 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.
///
/// The tuple is tagged with what the interpreter says it is being recorded for
/// (`Provenance::current`); a duplicate adds one more way to produce it.
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,
    };
    let tag = cls.provenance.tag_now();
    catalogue::record_effect(cls, effect, tag);
}

/// 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(),
    };
    let tag = cls.provenance.tag_now();
    catalogue::record_unknown(cls, entry, tag);
    add_effect(cls, "unknown", "shell", attrs_of(&[]));
}

/// D-I16-30 (3): an action that carries `unknown × shell` also carries
/// `unknown × <class>` for every distinct class among the targets it resolved,
/// and `unknown × network_host` for a URL or host — so the companion of an effect
/// rule asks on the rule's own target. `unknown × shell` stays.
pub fn add_located_unknown(cls: &mut Classification) {
    let carries_unknown_shell = cls
        .effects
        .iter()
        .any(|e| e.verb.0 == "unknown" && e.target_class.0 == "shell");
    if !carries_unknown_shell {
        return;
    }
    // Each class once, with the target entries that put it there on any path.
    let mut located: Vec<(String, catalogue::Derivations)> = Vec::new();
    for (i, path) in cls.paths.iter().enumerate() {
        let derivations = cls
            .provenance
            .paths
            .get(i)
            .map(|tag| tag.derivations.clone())
            .unwrap_or_else(catalogue::always);
        match located.iter_mut().find(|(class, _)| *class == path.class.0) {
            Some((_, seen)) => {
                for derivation in derivations {
                    if !seen.contains(&derivation) {
                        seen.push(derivation);
                    }
                }
            }
            None => located.push((path.class.0.clone(), derivations)),
        }
    }
    if !cls.urls.is_empty() {
        located.push(("network_host".to_string(), catalogue::always()));
    }
    for (class, derivations) in located {
        let effect = Effect {
            verb: EffectVerb("unknown".to_string()),
            target_class: TargetClass(class),
            attrs: serde_json::Map::new(),
        };
        let tag = catalogue::Tag {
            derivations,
            extra: Vec::new(),
            located: true,
        };
        catalogue::record_effect(cls, effect, tag);
    }
}

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

/// The tool call's input after the tool entries' `input_map` has copied each
/// mapped value onto its canonical key (D-4), and the values the roles that are
/// not keys picked up.
struct MappedInput {
    /// The input with the mapped keys added — present only when a mapping changed it,
    /// so an action nothing maps never pays to copy its payload.
    changed: Option<serde_json::Value>,
    /// `statement` role values, each with the entry that mapped it.
    statements: Vec<(String, Origin)>,
    /// `command` role values, each with the entry that mapped it.
    commands: Vec<(String, Origin)>,
}

impl MappedInput {
    fn input<'a>(&'a self, original: &'a serde_json::Value) -> &'a serde_json::Value {
        self.changed.as_ref().unwrap_or(original)
    }
}

fn map_input(input: &serde_json::Value, entries: &[&ToolEntry]) -> MappedInput {
    let mut mapped = MappedInput {
        changed: None,
        statements: Vec::new(),
        commands: Vec::new(),
    };
    for entry in entries.iter().filter(|e| !e.narrow) {
        for (pointer, role) in &entry.input_map {
            let Some(value) = input.pointer(pointer) else {
                continue;
            };
            let key = match role.as_str() {
                "file_path" => "file_path",
                "url" => "url",
                "statement" | "command" => {
                    if let Some(text) = value.as_str() {
                        let target = if role == "statement" {
                            &mut mapped.statements
                        } else {
                            &mut mapped.commands
                        };
                        target.push((text.to_string(), entry.origin.clone()));
                    }
                    continue;
                }
                _ => continue,
            };
            if !input.is_object() {
                continue;
            }
            let working = mapped.changed.get_or_insert_with(|| input.clone());
            let Some(object) = working.as_object_mut() else {
                continue;
            };
            // A second value for the same canonical key keeps both.
            match object.get_mut(key) {
                None => {
                    object.insert(key.to_string(), value.clone());
                }
                Some(existing) => {
                    let mut all: Vec<serde_json::Value> = match &*existing {
                        serde_json::Value::Array(items) => items.clone(),
                        other => vec![other.clone()],
                    };
                    match value {
                        serde_json::Value::Array(items) => all.extend(items.iter().cloned()),
                        other => all.push(other.clone()),
                    }
                    *existing = serde_json::Value::Array(all);
                }
            }
        }
    }
    mapped
}

/// Classify one action into effect tuples plus the coverage gaps around them.
///
/// See the module doc for the order. `catalogue` is the bundle's, or `None` for a
/// bundle that carries none: then no entry exists and nothing is looked up.
pub fn classify(event: &Event, facts: &FactSet, catalogue: Option<&Catalogue>) -> Classification {
    let mut cls = Classification::default();
    classify_into(event, facts, catalogue, &mut cls);
    add_located_unknown(&mut cls);
    cls
}

fn classify_into(
    event: &Event,
    facts: &FactSet,
    catalogue: Option<&Catalogue>,
    cls: &mut Classification,
) {
    let env = path::PathEnv::from_event(event.env.as_ref()).with_catalogue(catalogue);
    let tool = event.tool_name.as_str();
    let entries: Vec<&ToolEntry> = catalogue.map(|c| c.tool_entries(tool)).unwrap_or_default();

    // D-4: the tool entries' `input_map` first, so a learned tool's URL or path
    // is visible to the extraction below.
    let mapped = map_input(&event.tool_input, &entries);

    // The syntactic layer: paths and URLs exist independently of any verb, and a
    // feed selector may read `path.class` or `url.host`.
    let input = mapped.input(&event.tool_input);
    for raw in collect(input, PATH_KEYS) {
        for found in path::resolve_all(&raw, &env, facts) {
            let needs = catalogue::one_of(&found.origins);
            catalogue::within(cls, &needs, &[], |cls| {
                shell::record_path(cls, &raw, &found.class);
            });
        }
    }
    for raw in collect(input, URL_KEYS) {
        if let Some(url) = parse_url(&raw) {
            cls.urls.push(url);
        }
    }

    // An entry claims the call when every selector it carries matches (a v3 entry
    // carries none); one that does not match is silence for this event, never an
    // erasure of what the classifier would otherwise have said.
    let mut matched: Vec<&ToolEntry> = entries
        .iter()
        .copied()
        .filter(|entry| mcp::claims(entry, event, cls))
        .collect();
    // A `narrow` entry only subtracts from entries that add: alone it classifies nothing.
    if matched.iter().all(|entry| entry.narrow) {
        matched.clear();
    }
    let classifies_shell = SHELL_TOOLS.contains(&tool);

    // A v2 feed entry claims the tool outright (D-2): it overrides what the
    // catalogue's own entries and the shell classifier would have said, exactly as
    // it overrode the built-in row. A v3 entry adds, and a shell tool still gets
    // its code rows.
    let claimers: Vec<&ToolEntry> = matched.iter().copied().filter(|e| e.claims).collect();
    if !claimers.is_empty() {
        apply_tool_entries(&claimers, &mapped, tool, facts, &env, cls);
        return;
    }

    if !matched.is_empty() {
        apply_tool_entries(&matched, &mapped, tool, facts, &env, cls);
        if !BUILTIN_TOOLS.contains(&tool) && !classifies_shell {
            // The fallback the tool gets for an artifact that holds none of its
            // entries: nothing classifies it (Z19).
            let mut fallback = Classification::default();
            add_unknown(
                &mut fallback,
                13,
                format!("{tool} is not yet classified (Z19)"),
                tool,
            );
            cls.provenance.fallbacks.push(Fallback {
                stands_for: matched.iter().map(|e| e.origin.clone()).collect(),
                items: fallback,
            });
        }
    }

    if classifies_shell {
        let command = input
            .get("command")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default();
        shell::classify_into(command, cls, facts, &env);
        return;
    }
    if !matched.is_empty() || BUILTIN_TOOLS.contains(&tool) {
        // Classified by its entries, or a canonical tool the catalogue says
        // nothing about: no Z19 for either.
        return;
    }
    // No entry claimed this tool and no code row names it: that is Z19 (D-28, shape
    // 13) — there is no classifier at all, not merely a silent one, so effect atoms
    // go to ASK on the `unknown x shell` tuple `add_unknown` records. Kept out of
    // shape 10 ("no resolvable path operand") because the two name different gaps —
    // 10 is a tool this bundle DOES classify, on a path it could not place; 13 is a
    // tool nothing classifies.
    //
    // AZ-4 D-I16-17 lifts the `mcp__` guard: ANY tool no alias, no entry and no
    // code row covers is `unknown`, whatever the agent — except an event that is
    // not a tool call at all (a session start, a displayed message, a stop), which
    // has nothing to classify.
    if !tool.is_empty() && (tool.starts_with("mcp__") || is_tool_event(event)) {
        add_unknown(cls, 13, format!("{tool} is not yet classified (Z19)"), tool);
    }
}

/// The events that are not a tool call: their `tool_name` is a label, not a tool.
const NON_TOOL_EVENTS: &[&str] = &[
    "session_start",
    "message_display",
    "stop",
    "post_tool_batch",
];

fn is_tool_event(event: &Event) -> bool {
    !NON_TOOL_EVENTS.contains(&event.event_type.as_str())
}

/// Apply the tool entries that claimed this call: their merged effects (narrow
/// entries subtracted in every scope), then the values their `command` role
/// carries, as a shell command line.
fn apply_tool_entries(
    matched: &[&ToolEntry],
    mapped: &MappedInput,
    tool: &str,
    facts: &FactSet,
    env: &path::PathEnv,
    cls: &mut Classification,
) {
    let (effects, narrowed_by) = catalogue::merge_tool_effects(matched);
    let has_file_role = matched
        .iter()
        .any(|e| e.input_map.iter().any(|(_, role)| role == "file_path"));
    for merged in &effects {
        let needs = catalogue::one_of(&merged.origins);
        catalogue::within(cls, &needs, &narrowed_by, |cls| {
            apply_tool_effect(&merged.spec, mapped, tool, has_file_role, env, cls);
        });
    }
    for (command, origin) in &mapped.commands {
        let needs = catalogue::one_of(std::slice::from_ref(origin));
        catalogue::within(cls, &needs, &narrowed_by, |cls| {
            shell::classify_into(command, cls, facts, env);
        });
    }
}

fn apply_tool_effect(
    spec: &catalogue::EffectSpec,
    mapped: &MappedInput,
    tool: &str,
    has_file_role: bool,
    env: &path::PathEnv,
    cls: &mut Classification,
) {
    if spec.verb == catalogue::VERB_STATEMENT {
        for (statement, _) in &mapped.statements {
            match shell::classify_sql(statement) {
                Some(verb) => add_effect(cls, verb, &spec.target_class, attrs_of(&[])),
                None => add_unknown(cls, 9, format!("{tool}: unparsed statement"), tool),
            }
        }
        return;
    }
    let Some(role) = spec.target_class.strip_prefix('@') else {
        // A fixed class — except that a `file_path` role with a path-based class
        // resolves the class per call (spec P1).
        if has_file_role
            && PATH_CLASSES.contains(&spec.target_class.as_str())
            && !cls.paths.is_empty()
        {
            add_path_tuples(cls, &spec.verb);
            return;
        }
        add_effect(cls, &spec.verb, &spec.target_class, attrs_of(&[]));
        return;
    };
    // `@target` and `@<role>`: the class is resolved per call from the values
    // under that role — a path through the target entries and the resolver, a URL
    // or host as `network_host`. No resolvable value is shape 10.
    let (paths, urls) = match role {
        "url" | "host" => (false, true),
        "file" => (true, false),
        _ => (true, true),
    };
    if (paths && !cls.paths.is_empty()) || (urls && !cls.urls.is_empty()) {
        if paths {
            add_path_tuples(cls, &spec.verb);
        }
        if urls && !cls.urls.is_empty() {
            add_effect(cls, &spec.verb, "network_host", attrs_of(&[]));
            let hosts: Vec<String> = cls.urls.iter().map(|u| u.host.clone()).collect();
            for host in hosts {
                add_host_classes(cls, &spec.verb, &host, env, &attrs_of(&[]));
            }
        }
        return;
    }
    add_unknown(cls, 10, format!("{tool}: no resolvable path operand"), tool);
}

/// One tuple per path class the action named, each carrying the target entries
/// that produced the class.
fn add_path_tuples(cls: &mut Classification, verb: &str) {
    let named: Vec<(String, catalogue::Derivations)> = cls
        .paths
        .iter()
        .enumerate()
        .map(|(i, p)| {
            let derivations = cls
                .provenance
                .paths
                .get(i)
                .map(|t| t.derivations.clone())
                .unwrap_or_else(catalogue::always);
            (p.class.0.clone(), derivations)
        })
        .collect();
    for (class, derivations) in named {
        catalogue::within(cls, &derivations, &[], |cls| {
            add_effect(cls, verb, &class, attrs_of(&[]));
        });
    }
}

/// 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()) {
                    match child {
                        serde_json::Value::String(text) => out.push(text.clone()),
                        // A multi-value input keeps every target (D-7): `files[].path`
                        // arrives as an array under one canonical key.
                        serde_json::Value::Array(items) => {
                            out.extend(items.iter().filter_map(|v| v.as_str().map(str::to_string)));
                        }
                        _ => {}
                    }
                }
                collect_into(child, keys, out);
            }
        }
        serde_json::Value::Array(items) => {
            for child in items {
                collect_into(child, keys, out);
            }
        }
        _ => {}
    }
}

/// A bare host an operand names (`dig evil.example`, `ping 10.0.0.5`,
/// `ssh deploy@build.example.com`) as the `url.*` family sees it. `None` for what
/// is not a host: a flag-like token, a number, an empty string.
pub(super) fn host_url(raw: &str) -> Option<ClassifiedUrl> {
    // `dig @8.8.8.8 host` names the resolver it asks as well; both are contacted.
    let text = raw.trim_start_matches('@');
    let text = text.rsplit_once('@').map_or(text, |(_, host)| host);
    let host = text.split(['/', ':']).next().unwrap_or_default();
    if host.is_empty()
        || host.starts_with(['+', '-'])
        || host.chars().all(|c| c.is_ascii_digit())
        || host.contains(['$', '*', '?', '`'])
    {
        return None;
    }
    let mut url = parse_url(&format!("x://{host}"))?;
    url.value = raw.to_string();
    url.scheme = String::new();
    Some(url)
}

/// The extra classes the catalogue's host patterns give a host, beside
/// `network_host`: each carries the entries that put it there.
pub(super) fn add_host_classes(
    cls: &mut Classification,
    verb: &str,
    host: &str,
    env: &path::PathEnv,
    attrs: &serde_json::Map<String, serde_json::Value>,
) {
    for found in path::resolve_host(host, env) {
        if found.class.0 == "network_host" {
            continue;
        }
        let needs = catalogue::one_of(&found.origins);
        catalogue::within(cls, &needs, &[], |cls| {
            add_effect(cls, verb, &found.class.0, attrs.clone());
        });
    }
}

// ── 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::catalogue::fixtures::seed_r1;
    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(),
            Some(seed_r1()),
        );
        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(),
            Some(seed_r1()),
        );
        assert_eq!(tuples(&cls), vec!["unknownxshell"]);
        assert_eq!(cls.unknown.first().map(|u| u.shape), Some(10));
    }

    /// D-28: an `mcp__*` tool no feed entry and no built-in row claims is Z19,
    /// not silence — shape 13, carrying the `unknown x shell` tuple that
    /// forces effect atoms to ASK.
    #[test]
    fn an_unclaimed_mcp_tool_produces_the_z19_shape() {
        let cls = classify(
            &event(
                "mcp__jira__create_issue",
                serde_json::json!({"summary": "x"}),
            ),
            &FactSet::default(),
            Some(seed_r1()),
        );
        assert_eq!(
            cls.effects,
            vec![Effect {
                verb: EffectVerb("unknown".to_string()),
                target_class: TargetClass("shell".to_string()),
                attrs: serde_json::Map::new(),
            }]
        );
        assert_eq!(cls.unknown.len(), 1);
        let unknown = &cls.unknown[0];
        assert_eq!(unknown.shape, 13);
        assert_eq!(unknown.command, "mcp__jira__create_issue");
        assert_eq!(
            unknown.reason,
            "mcp__jira__create_issue is not yet classified (Z19)"
        );
    }

    /// AZ-4 D-I16-17 lifts D-28's `mcp__` guard: a tool no alias, no entry and no
    /// code row covers is `unknown`, whatever the agent, so an effect rule never
    /// passes it silently.
    #[test]
    fn a_tool_nobody_has_classified_is_unknown_whatever_the_agent() {
        for tool in ["KillShell", "cline_hook:browser_action"] {
            let cls = classify(
                &Event {
                    event_type: "pre_tool_use".to_string(),
                    ..event(tool, serde_json::json!({"shell_id": "bash-1"}))
                },
                &FactSet::default(),
                Some(seed_r1()),
            );
            assert_eq!(tuples(&cls), vec!["unknownxshell"], "{tool}");
            assert_eq!(cls.unknown.first().map(|u| u.shape), Some(13), "{tool}");
        }
    }

    /// A session start or a displayed message has a label where a tool would be.
    #[test]
    fn an_event_that_is_not_a_tool_call_has_nothing_to_classify() {
        let cls = classify(
            &Event {
                event_type: "message_display".to_string(),
                ..event("message_display", serde_json::json!({"message": "hi"}))
            },
            &FactSet::default(),
            Some(seed_r1()),
        );
        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(),
                Some(seed_r1()),
            );
            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(),
            Some(seed_r1()),
        );
        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(),
            Some(seed_r1()),
        );
        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"
        );
    }

    // ── The catalogue: provenance, scope and the merge (AZ-4 §6.11, §6.13) ──

    use super::catalogue::fixtures::seed_r1_plus;
    use super::catalogue::{Entries, Scope, SeedRev};

    /// Seed revision 2's readers and 3's pgpass, an org `tar` entry and a narrow one:
    /// the parts of the worked example these tests need.
    fn worked() -> &'static Catalogue {
        seed_r1_plus(serde_json::json!({
            "programs": [
                {"id": "seed:prog:cat", "origin": "seed", "since_rev": 2, "key": "cat",
                 "effects": [{"verb": "read", "target_class": "@file"}],
                 "operands": {"file": "positional_all"}},
                {"id": "5be0417f", "origin": "org", "key": "tar",
                 "effects": [{"verb": "read", "target_class": "@file"}],
                 "operands": {"file": "positional_all"}},
                {"id": "org-rm-read", "origin": "org", "key": "rm",
                 "effects": [{"verb": "read", "target_class": "@file"}],
                 "operands": {"file": "positional_all"}},
                {"id": "admin-rm-narrow", "origin": "org", "narrow": true, "key": "rm",
                 "effects": [{"verb": "delete", "target_class": "@file"}]},
            ],
            "targets": [
                {"id": "seed:tgt:pgpass", "origin": "seed", "since_rev": 3,
                 "pattern_kind": "path", "key": "~/.pgpass", "target_class": "secret_material"},
            ],
        }))
    }

    fn bash(command: &str) -> Classification {
        classify(
            &event("Bash", serde_json::json!({"command": command})),
            &FactSet::default(),
            Some(worked()),
        )
    }

    fn origins_of(cls: &Classification, verb: &str, class: &str) -> Vec<String> {
        cls.tuples_with_origins()
            .into_iter()
            .find(|(e, _)| e.verb.0 == verb && e.target_class.0 == class)
            .map(|(_, origins)| origins.iter().map(Origin::label).collect())
            .unwrap_or_default()
    }

    /// AC-82: the full classification names where each tuple came from.
    #[test]
    fn a_tuple_reports_every_entry_that_produced_it() {
        let cls = bash("cat ~/.pgpass");
        assert_eq!(
            origins_of(&cls, "read", "secret_material"),
            vec!["seed@2", "seed@3"],
            "`cat` (seed r2) and the pattern (seed r3), nothing else"
        );
        let cls = bash("cat ~/.ssh/id_rsa");
        assert_eq!(
            origins_of(&cls, "read", "secret_material"),
            vec!["seed@1", "seed@2"]
        );
    }

    /// AC-68: an added tuple keeps the seed's, and `narrow` — the only subtraction —
    /// leaves its id on what remains.
    #[test]
    fn narrow_subtracts_and_records_its_entry_id() {
        let cls = bash("rm -rf /data/warehouse/x");
        assert_eq!(
            tuples(&cls),
            vec!["readxdata_store"],
            "the seed delete is gone"
        );
        assert!(
            origins_of(&cls, "read", "data_store").contains(&"admin-rm-narrow".to_string()),
            "{:?}",
            cls.tuples_with_origins()
        );
    }

    /// §6.13: a tuple needs every entry of one derivation. `tar` is `read` for the
    /// artifact that holds its entry and `unknown` for one that holds only the seed.
    #[test]
    fn a_view_drops_a_tuple_whose_entry_is_out_of_scope_and_falls_back_to_unknown() {
        let cls = bash("tar -cf - ~/.ssh/id_rsa");
        assert_eq!(tuples(&cls), vec!["readxsecret_material"]);

        let strict = Scope {
            seed_rev: SeedRev::Rev(2),
            entries: Entries::Ids(Vec::new()),
        };
        let view = cls.view(&strict);
        assert_eq!(
            tuples(&view),
            vec!["unknownxshell", "executexshell", "unknownxsecret_material"],
            "the fallback of `tar`, with its target located"
        );
        assert_eq!(
            view.unknown.iter().map(|u| u.shape).collect::<Vec<_>>(),
            vec![9]
        );

        let explicit = Scope {
            seed_rev: SeedRev::Rev(2),
            entries: Entries::Ids(vec!["5be0417f".to_string()]),
        };
        assert_eq!(tuples(&cls.view(&explicit)), vec!["readxsecret_material"]);
        assert_eq!(tuples(&cls.view(&Scope::all())), tuples(&cls));
    }

    /// AC-82: `cat ~/.pgpass` under a pin that predates the pattern is decided by
    /// nothing — and the full classification still says what it is.
    #[test]
    fn a_pin_before_a_pattern_does_not_see_it_but_the_classification_does() {
        let cls = bash("cat ~/.pgpass");
        let strict = Scope {
            seed_rev: SeedRev::Rev(2),
            entries: Entries::Ids(Vec::new()),
        };
        assert!(
            !tuples(&cls.view(&strict)).contains(&"readxsecret_material".to_string()),
            "{:?}",
            tuples(&cls.view(&strict))
        );
        assert!(tuples(&cls).contains(&"readxsecret_material".to_string()));
    }

    #[test]
    fn a_narrow_entry_applies_in_every_scope() {
        let cls = bash("rm -rf /data/warehouse/x");
        let pinned = Scope {
            seed_rev: SeedRev::Rev(1),
            entries: Entries::Ids(Vec::new()),
        };
        assert!(
            !tuples(&cls.view(&pinned)).contains(&"deletexdata_store".to_string()),
            "the correction reaches a scope that does not list the narrow entry"
        );
    }

    #[test]
    fn an_empty_classified_tool_entry_suppresses_unknown() {
        let catalogue = seed_r1_plus(serde_json::json!({"tools": [
            {"id": "org-noop", "origin": "org", "key": "mcp__jira__ping", "effects": []}
        ]}));
        let cls = classify(
            &event("mcp__jira__ping", serde_json::json!({})),
            &FactSet::default(),
            Some(catalogue),
        );
        assert!(cls.effects.is_empty() && cls.unknown.is_empty());
    }

    /// AC-65: `input_map` runs before extraction, so a learned tool's path and URL are
    /// visible; a `statement` is classified as SQL and a `command` as a Bash command.
    #[test]
    fn input_map_roles_feed_the_extraction_the_sql_classifier_and_the_shell() {
        let catalogue = seed_r1_plus(serde_json::json!({"tools": [
            {"id": "fs", "origin": "org", "key": "mcp__fs__read_file",
             "effects": [{"verb": "read", "target_class": "workspace_file"}],
             "input_map": {"/path": "file_path"}},
            {"id": "db", "origin": "org", "key": "mcp__db__query",
             "effects": [{"verb": "@statement", "target_class": "data_store"}],
             "input_map": {"/sql": "statement"}},
            {"id": "sh", "origin": "org", "key": "mcp__sh__run", "effects": [],
             "input_map": {"/cmd": "command"}},
            {"id": "web", "origin": "org", "key": "mcp__web__get",
             "effects": [{"verb": "network_egress", "target_class": "@target"}],
             "input_map": {"/link": "url"}},
        ]}));
        let run = |tool: &str, input: serde_json::Value| {
            classify(&event(tool, input), &FactSet::default(), Some(catalogue))
        };
        let read = run(
            "mcp__fs__read_file",
            serde_json::json!({"path": "~/.ssh/id_rsa"}),
        );
        assert_eq!(tuples(&read), vec!["readxsecret_material"]);
        let drop = run("mcp__db__query", serde_json::json!({"sql": "DROP TABLE t"}));
        assert_eq!(tuples(&drop), vec!["deletexdata_store"]);
        let cmd = run(
            "mcp__sh__run",
            serde_json::json!({"cmd": "rm -rf /data/warehouse/x"}),
        );
        assert_eq!(tuples(&cmd), vec!["deletexdata_store"]);
        let web = run(
            "mcp__web__get",
            serde_json::json!({"link": "https://www.google.fr"}),
        );
        assert_eq!(tuples(&web), vec!["network_egressxnetwork_host"]);
        assert_eq!(web.urls[0].host, "www.google.fr");
    }

    /// D-I16-30 (3): the unreadable keeps its target.
    #[test]
    fn an_unreadable_action_carries_a_located_tuple_per_class_and_per_url() {
        let cls = bash("stat ~/.ssh/id_rsa /data/warehouse/x.db https://example.org/x");
        assert_eq!(
            tuples(&cls),
            vec![
                "unknownxshell",
                "executexshell",
                "unknownxsecret_material",
                "unknownxdata_store",
                "unknownxnetwork_host"
            ]
        );
        assert_eq!(
            tuples(&bash("weirdtool --flag")),
            vec!["unknownxshell", "executexshell"]
        );
    }

    /// AC-94: a listed global flag is skipped, an unlisted one stops the match.
    #[test]
    fn global_flags_are_skipped_before_the_subcommand_and_an_unlisted_one_stops_the_match() {
        let catalogue = seed_r1_plus(serde_json::json!({"programs": [
            {"id": "ssm", "origin": "org", "key": "aws secretsmanager get-secret-value",
             "effects": [{"verb": "read", "target_class": "secret_material"}],
             "global_flags": ["--profile", "--region"]},
        ]}));
        let run = |command: &str| {
            classify(
                &event("Bash", serde_json::json!({"command": command})),
                &FactSet::default(),
                Some(catalogue),
            )
        };
        let listed =
            run("aws --profile p --region=eu-west-1 secretsmanager get-secret-value --secret-id x");
        assert_eq!(tuples(&listed), vec!["readxsecret_material"]);
        let unlisted = run("aws --debug secretsmanager get-secret-value --secret-id x");
        assert!(!tuples(&unlisted).contains(&"readxsecret_material".to_string()));
        assert!(
            tuples(&unlisted).contains(&"unknownxshell".to_string()),
            "{:?}",
            tuples(&unlisted)
        );
    }

    /// An entry that only carries `global_flags` classifies nothing.
    #[test]
    fn a_flags_only_entry_does_not_silence_the_unknown() {
        let catalogue = seed_r1_plus(serde_json::json!({"programs": [
            {"id": "git-flags", "origin": "seed", "since_rev": 2, "key": "git", "effects": [],
             "global_flags": ["-C"]},
        ]}));
        let cls = classify(
            &event("Bash", serde_json::json!({"command": "git status"})),
            &FactSet::default(),
            Some(catalogue),
        );
        assert_eq!(tuples(&cls), vec!["unknownxshell", "executexshell"]);
    }

    /// D-14: `<` reads, a heredoc does not, `sh -c '<literal>'` recurses, inline code is
    /// unreadable but its literals are examined.
    #[test]
    fn the_code_rows_of_d_i16_30() {
        let cat = |command: &str| tuples(&bash(command));
        assert_eq!(
            cat("mail ops < ~/.aws/credentials"),
            vec![
                "readxsecret_material",
                "unknownxshell",
                "executexshell",
                "unknownxsecret_material"
            ]
        );
        assert_eq!(cat("cat <<< hello"), Vec::<String>::new());
        assert_eq!(
            cat("bash -c \"cat ~/.ssh/id_rsa\""),
            vec!["readxsecret_material"]
        );
        assert_eq!(
            cat("python3 -c \"print(open('/home/dev/.ssh/id_rsa').read())\""),
            vec!["executexshell", "unknownxshell", "unknownxsecret_material"]
        );
        assert!(cat("bash -c \"$CMD\"").contains(&"unknownxshell".to_string()));
    }

    #[test]
    fn a_network_tuple_names_its_program() {
        let cls = bash("curl https://www.google.fr");
        let egress = cls
            .effects
            .iter()
            .find(|e| e.verb.0 == "network_egress")
            .expect("egress");
        assert_eq!(
            egress.attrs.get("program"),
            Some(&serde_json::json!("curl"))
        );
        assert_eq!(cls.urls[0].host, "www.google.fr");
    }

    #[test]
    fn a_bare_host_operand_is_a_host_and_a_number_or_flag_is_not() {
        let host = host_url("deploy@Build.Example.com:22/x").expect("a host");
        assert_eq!(host.host, "build.example.com");
        assert!(host_url("1").is_none());
        assert!(host_url("+short").is_none());
        assert!(host_url("").is_none());
    }
}