keyhog 0.5.44

keyhog detects leaked credentials in source trees, git history, archives, and remote sources
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
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
//! Logic for the `scan` subcommand.
//!
//! Default: build a [`ScanOrchestrator`] and run the full in-process
//! pipeline. For the simple stdin / single-file case there is also a
//! daemon fast path: when `--daemon=auto` sees a live socket, eligible
//! stdin / single-file scans go through the running `keyhog daemon`
//! and skip the ~3 s `CompiledScanner::compile` cold start. The daemon
//! path is deliberately narrow - it can honor stdin and a single regular
//! file through the source-owned filesystem expansion path; directory
//! walks, git-staged scans, baseline filtering, merkle skip cache, and
//! verification still go through the orchestrator. `--daemon=on` is a hard
//! contract: if the daemon cannot honor the requested scan exactly, the
//! command fails instead of silently running a different path.

use crate::args::{DaemonMode, ScanArgs};
#[cfg(unix)]
use crate::exit_codes::{EXIT_CREDENTIALS_FOUND, EXIT_LIVE_CREDENTIALS, EXIT_SOURCE_FAILED};
// Daemon module is unix-only - Windows has no `tokio::net::UnixListener`
// or `std::os::unix::net::UnixStream`, so the whole `crate::daemon`
// subtree is `#[cfg(unix)]`. See `lib.rs` for the rationale. On
// Windows, an absent daemon flag or explicit `--daemon=off` runs in-process;
// explicit `--daemon=auto|on` fails loudly because no daemon transport exists.
#[cfg(unix)]
use crate::daemon::client;
#[cfg(unix)]
use crate::daemon::protocol::{Request, RequiredOption, Response, SourceCoverageGaps};
#[cfg(unix)]
use crate::daemon::server::default_socket_path;
use crate::orchestrator::ScanOrchestrator;
use anyhow::{bail, Result};
// The daemon-only result-massaging path (unwrap_scan_results,
// finalize_for_report) is the only consumer of `RawMatch` /
// `VerifiedFinding` in this file. The in-process orchestrator path
// handles its own conversion inside `ScanOrchestrator::run`, and shared
// postprocess helpers own dedup/redaction. Cfg-gate the imports so Windows
// builds don't trip the unused-imports denial.
#[cfg(unix)]
use anyhow::Context;
#[cfg(unix)]
use keyhog_core::{RawMatch, RuleSuppressor, ScanCompletionStatus, VerifiedFinding};
#[cfg(unix)]
use std::path::{Path, PathBuf};
use std::process::ExitCode;

pub(crate) async fn run(args: ScanArgs) -> Result<ExitCode> {
    crate::runtime_preflight::validate_scan_runtime_config()?;
    guard_multi_root_combinations(&args)?;
    if args.daemon_mode() == DaemonMode::Off && args.daemon_socket.is_some() {
        bail!("`--daemon-socket` cannot be combined with `--daemon=off`; remove the socket or choose `--daemon=auto|on`");
    }

    // On Windows, the daemon route is never available (the `crate::daemon`
    // module is cfg(unix)). If the user explicitly requested `auto` or `on`,
    // refuse loudly so the request is not silently rewritten as `off`. An
    // absent flag and explicit `off` both
    // mean the only supported Windows execution path: in-process.
    #[cfg(not(unix))]
    {
        let mode = args.daemon_mode();
        if args.daemon.is_some() && mode.may_use_daemon_transport() {
            let requested = if mode == DaemonMode::Auto {
                "auto"
            } else {
                "on"
            };
            bail!(
                "`--daemon={requested}` is a unix-only mode (the daemon serves scans \
                 over a Unix-domain socket). Drop the flag to run \
                 in-process, or pass `--daemon=off` to be explicit."
            );
        }
        let orchestrator = ScanOrchestrator::new(args)?;
        return orchestrator.run().await;
    }
    // Resolve the routing-relevant `.keyhog.toml` policy BEFORE deciding the
    // route. The orchestrator's `.keyhog.toml` merge runs LATER (inside
    // `ScanOrchestrator::new`) and only on the in-process path, so a policy set
    // via the config file rather than a CLI flag was invisible to
    // `daemon_route`: letting a config min_confidence floor, a config
    // `[lockdown] require = true` fail-closed guard, or a config
    // `show_secrets` be silently bypassed whenever a daemon happened to be
    // live. Merge onto a throwaway clone so the real `args` the orchestrator
    // consumes is untouched (it re-merges identically), then route on the
    // EFFECTIVE values.
    //
    // That probe re-reads and re-parses `.keyhog.toml` a SECOND time (the
    // orchestrator parses it again in `ScanOrchestrator::new`). It is only
    // load-bearing when a daemon could actually take the scan: `--daemon=on`, or
    // an auto route with a live socket at the address we would connect to. When
    // no daemon is reachable, the common case (`--daemon=off`, or auto with no
    // socket), the route is Forbidden regardless, so skip the probe entirely
    // and go straight to the in-process orchestrator, which resolves the config
    // exactly ONCE. `effective_daemon_socket` is the same address `daemon_route`
    // and `run_via_daemon` use, so this gate never diverges from the real route.
    #[cfg(unix)]
    {
        let mode = args.daemon_mode();
        let daemon_reachable = mode == DaemonMode::On
            || (mode != DaemonMode::Off && effective_daemon_socket(&args).exists());
        if !daemon_reachable {
            let orchestrator = ScanOrchestrator::new(args)?;
            return orchestrator.run().await;
        }
        let mut policy = EffectivePolicy::resolve(&args);
        match daemon_route(&args, &policy) {
            DaemonRoute::Required => run_via_daemon(&mut policy.effective_args).await,
            DaemonRoute::Opportunistic => {
                match acquire_via_daemon(&mut policy.effective_args).await {
                    Ok(scan) => finish_daemon_scan(scan, &policy.effective_args),
                    Err(e) => {
                        if policy.effective_args.daemon_mode() == DaemonMode::Auto {
                            let palette = crate::style::for_stderr();
                            eprintln!(
                                "{}: daemon auto route unavailable ({e:#}); running in-process scanner",
                                crate::style::warn("keyhog", &palette)
                            );
                        }
                        // LAW10: opportunistic daemon failure is reported on stderr in
                        // auto mode, then the same scan runs in-process.
                        tracing::debug!(
                            error = %e,
                            "daemon auto route unavailable; running in-process scanner"
                        );
                        // An stdin request is single-consumer. `acquire_via_daemon`
                        // buffers it before sending `ScanText`, so an execution or
                        // protocol failure can replay the exact bytes instead of
                        // retrying against EOF. File requests need no special
                        // handling because the path remains replayable.
                        let mut retry_args = args.clone();
                        retry_args.buffered_stdin = policy.effective_args.buffered_stdin.clone();
                        let orchestrator = ScanOrchestrator::new(retry_args)?;
                        orchestrator.run().await
                    }
                }
            }
            DaemonRoute::Rejected(reason) => bail!("{reason}"),
            DaemonRoute::Forbidden => {
                let orchestrator = ScanOrchestrator::new(args)?;
                orchestrator.run().await
            }
        }
    }
}

#[cfg(unix)]
enum DaemonRoute {
    Required,
    Opportunistic,
    Forbidden,
    Rejected(String),
}

/// Fail closed when several positional roots are combined with a mode that has
/// no unambiguous meaning over more than one root.
///
/// keyhog now scans multiple roots per invocation (`keyhog scan a/ b/ c/`):
/// each becomes its own filesystem source and the engine merges the multi-
/// source `Vec` it already consumes. The only positional-root mode that breaks
/// is `--git-staged`, whose exact index blobs are resolved from a SINGLE
/// repository; with several roots there is no one index to read, and silently
/// staged-scanning only the first root while
/// walking the rest in full would be a confusing, asymmetric result (Law 10).
/// Every other source (`--stdin`, `--git-blobs/-diff/-history`, the remote
/// providers, `--binary`) carries its own origin and composes cleanly, so they
/// are deliberately NOT rejected here.
pub(crate) fn guard_multi_root_combinations(args: &ScanArgs) -> Result<()> {
    let roots = args.scan_roots();
    if roots.len() <= 1 {
        return Ok(());
    }
    #[cfg(feature = "git")]
    if args.git_staged {
        let list = roots
            .iter()
            .map(|p| p.display().to_string())
            .collect::<Vec<_>>()
            .join(", ");
        bail!(
            "`--git-staged` resolves staged files from one repository working \
             tree, so it cannot span the {n} roots given ({list}).\n\
             Run `keyhog scan --git-staged <repo>` once per repository, or drop \
             `--git-staged` to walk every root on disk.",
            n = roots.len(),
            list = list,
        );
    }
    Ok(())
}

/// The routing-relevant policy AFTER merging `.keyhog.toml`, so the daemon
/// route decision sees config-file values (not just raw CLI flags). Built by
/// merging a throwaway clone of `ScanArgs` through the same
/// [`crate::config::apply_config_file`] the orchestrator uses, so the
/// effective floor / lockdown-require / secret-output policy is identical to
/// what the in-process path will enforce.
#[cfg(unix)]
struct EffectivePolicy {
    /// Routing clone after the quiet config merge. The daemon path must consume
    /// this, not the raw CLI args, for knobs it can enforce client-side
    /// (dedup, output, stdin byte limit) to match the in-process route.
    effective_args: ScanArgs,
    /// `min_confidence` after the config merge (CLI flag OR `.keyhog.toml` /
    /// `[scan]` floor). When `Some`, the daemon's floor-less finalize would
    /// surface findings the in-process path suppresses, so force in-process.
    min_confidence: Option<f64>,
    /// `show_secrets` after the merge (CLI flag OR `.keyhog.toml`). The daemon
    /// finalize redacts unconditionally, so a config-driven value would render
    /// credentials differently by route.
    show_secrets: bool,
    /// Live verification after the merge (CLI flag OR `.keyhog.toml`). The
    /// daemon returns scanner matches only, so a config-driven verify request
    /// must route in-process exactly like `--verify`.
    #[cfg(feature = "verify")]
    verify: bool,
    /// Minimum-severity filter after the merge (CLI flag OR `.keyhog.toml`).
    severity: bool,
    /// `[lockdown] require = true` from `.keyhog.toml`: a fail-closed control
    /// the daemon cannot enforce. Forces in-process so the orchestrator's
    /// `bail!` fires when `--lockdown` was not passed.
    require_lockdown: bool,
    /// Semantic config errors detected by the quiet config probe. Forces
    /// in-process so the real orchestrator emits the precise error once.
    has_config_errors: bool,
    /// Extra AWS canary/knockoff account IDs from `.keyhog.toml`. The daemon
    /// process owns its own scanner state and cannot consume per-client config.
    custom_aws_canary_accounts: bool,
    /// `[allowlist]` file/governance policy from `.keyhog.toml`. The daemon
    /// route intentionally loads only the default local `.keyhogignore`, so a
    /// configured allowlist policy must stay in-process.
    has_allowlist_config: bool,
    /// Per-detector confidence policy from `.keyhog.toml`. The daemon owns a
    /// long-lived scanner compiled without the client's local detector policy,
    /// and client-side finalization cannot recover findings an engine floor
    /// already dropped. Any such policy therefore requires the in-process path.
    has_detector_min_confidence: bool,
}

#[cfg(unix)]
impl EffectivePolicy {
    fn resolve(args: &ScanArgs) -> EffectivePolicy {
        let mut probe = args.clone();
        // Mirror `ScanOrchestrator::new`'s path normalization BEFORE the config
        // merge: the positional path binds to `input`, but config discovery
        // (`find_config_file`) walks up from `path`. Without promoting
        // `input` -> `path` here, `apply_config_file` would look in the CWD
        // instead of the scanned file's directory and miss the `.keyhog.toml`
        // whose policy we are trying to honour (the exact bug this resolves).
        if probe.path.is_none() {
            probe.path = probe.input.first().cloned();
        }
        // Quiet (diagnostics-free) merge: this probe applies the config to a
        // throwaway clone only to read the resolved routing knobs. The real
        // orchestrator merge emits any read/parse warning exactly once; the loud
        // `apply_config_file` here would warn TWICE on a malformed `.keyhog.toml`
        // over the daemon route (HUNT-2).
        let outcome = crate::config::apply_config_file_quiet(&mut probe);
        let min_confidence = probe.min_confidence;
        let show_secrets = probe.show_secrets;
        #[cfg(feature = "verify")]
        let verify = probe.verify;
        let severity = probe.severity.is_some();
        EffectivePolicy {
            effective_args: probe,
            min_confidence,
            show_secrets,
            #[cfg(feature = "verify")]
            verify,
            severity,
            require_lockdown: outcome.require_lockdown,
            has_config_errors: !outcome.config_errors.is_empty(),
            custom_aws_canary_accounts: !outcome.aws_canary_accounts.is_empty(),
            has_allowlist_config: outcome.allowlist_file.is_some()
                || outcome.allowlist_require_reason
                || outcome.allowlist_require_approved_by
                || outcome.allowlist_max_expires_days.is_some(),
            has_detector_min_confidence: !outcome.detector_min_confidence.is_empty(),
        }
    }
}

#[cfg(unix)]
fn daemon_route(args: &ScanArgs, policy: &EffectivePolicy) -> DaemonRoute {
    let mode = args.daemon_mode();
    if mode == DaemonMode::Off {
        return DaemonRoute::Forbidden;
    }
    let forced_on = mode == DaemonMode::On;

    // Daemon path doesn't run verification - the daemon process holds a
    // scanner but not the verifier engine. Trying to honour `--verify` or
    // config `verify = true` over a daemon-only result set would silently drop
    // every API-call-backed live-credential check; the orchestrator is the
    // only honest answer.
    #[cfg(feature = "verify")]
    if policy.verify {
        if let Some(route) = reject_forced_daemon(
            forced_on,
            "verification requires the in-process verifier; the daemon only returns scanner matches",
        ) {
            return route;
        }
        return DaemonRoute::Forbidden;
    }
    if args.baseline.is_some() {
        if let Some(route) = reject_forced_daemon(
            forced_on,
            "--baseline requires the in-process baseline filter; the daemon has no baseline state",
        ) {
            return route;
        }
        return DaemonRoute::Forbidden;
    }

    let single_file = match effective_single_file_path(args) {
        Ok(path) => path.is_some(),
        Err(error) => {
            if let Some(route) = reject_forced_daemon(
                forced_on,
                &format!(
                    "the daemon single-file route cannot inspect the requested path: {error:#}"
                ),
            ) {
                return route;
            }
            return DaemonRoute::Forbidden;
        }
    };
    let primary_sources = usize::from(args.stdin) + usize::from(single_file);
    if primary_sources != 1 || has_daemon_incompatible_extra_sources(args) {
        if let Some(route) = reject_forced_daemon(
            forced_on,
            "the daemon only supports exactly one source: --stdin or a single regular file; directories, git, remote, binary, dynamic, and multi-source scans require the in-process scanner",
        ) {
            return route;
        }
        return DaemonRoute::Forbidden;
    }

    // The daemon's client-side finalize mirrors allowlist/rule suppression,
    // inline suppression, match resolution, and dedup for daemon-eligible scans.
    // It still does NOT run live verification or enforce the policy/security
    // gates below (lockdown protections, secret-output policy, severity hiding,
    // client-safe hiding, or explicit confidence-floor policy). Routing a scan
    // that requests any of those over the daemon would silently change results
    // or bypass a hard security guard, and the opportunistic route flips on
    // merely because a daemon socket exists. Force the in-process path whenever
    // such policy is in play, so behavior never depends on whether a daemon
    // happens to be running.
    //
    // This SECURITY-policy check runs BEFORE the generic backend/GPU/batch
    // operational-controls check below: when a scan requests BOTH a fail-closed
    // security control (lockdown, secret-output) AND an operational control
    // (e.g. `--backend`), the refusal must name the security policy that cannot
    // be enforced, not merely the operational knob, the operator needs to know
    // their lockdown / secret-output intent is what the daemon can't honor.
    //
    // Critically, the floor / lockdown-require / show_secrets / severity checks
    // read the EFFECTIVE post-`.keyhog.toml`-merge policy, not just the raw CLI
    // flags: a `.keyhog.toml` `min_confidence`, `[lockdown] require = true`, or
    // `show_secrets` set via the config file (with no matching CLI flag) must
    // forbid the daemon route too, otherwise scan RESULTS and a fail-closed
    // SECURITY GUARD would change purely on whether a daemon is live.
    // `hide_client_safe` has no config-file surface, so the CLI flag is the
    // effective value.
    if args.lockdown
        || policy.require_lockdown
        || policy.show_secrets
        || policy.severity
        || policy.min_confidence.is_some()
        || policy.has_config_errors
        || policy.custom_aws_canary_accounts
        || policy.has_allowlist_config
        || policy.has_detector_min_confidence
        || args.hide_client_safe
    {
        if let Some(route) = reject_forced_daemon(
            forced_on,
            "this scan requests filtering, lockdown, secret-output, AWS canary config, allowlist governance, or config policy the daemon cannot enforce",
        ) {
            return route;
        }
        return DaemonRoute::Forbidden;
    }

    if let Some(reason) = daemon_incompatible_scan_options(&policy.effective_args) {
        if let Some(route) = reject_forced_daemon(forced_on, reason) {
            return route;
        }
        return DaemonRoute::Forbidden;
    }

    if forced_on {
        return DaemonRoute::Required;
    }

    // Opportunistic route flips on only when a live daemon is actually at the
    // socket we'd connect to, the `--daemon-socket` override when present, else
    // the default. Probing the default while a scan targeted an override socket
    // would mis-route (treat an unrelated daemon as ours, or miss the real one).
    if effective_daemon_socket(args).exists() {
        DaemonRoute::Opportunistic
    } else {
        DaemonRoute::Forbidden
    }
}

/// The socket the daemon route connects to: the `--daemon-socket` override when
/// the operator points the scan at a non-default daemon, else the default
/// (`$XDG_RUNTIME_DIR/keyhog.sock`). The single source of truth shared by the
/// route decision and the connect in [`run_via_daemon`], so they never diverge.
#[cfg(unix)]
fn effective_daemon_socket(args: &ScanArgs) -> std::path::PathBuf {
    args.daemon_socket
        .clone()
        // LAW10: intentional_default, absent --daemon-socket => documented default
        // socket; Tier-A transport knob, recall-irrelevant.
        .unwrap_or_else(default_socket_path)
}

#[cfg(unix)]
fn reject_forced_daemon(forced_on: bool, reason: &str) -> Option<DaemonRoute> {
    forced_on.then(|| {
        DaemonRoute::Rejected(format!(
            "--daemon=on cannot be honored: {reason}. Drop `--daemon=on`, or pass \
             `--daemon=off` to run the in-process scanner explicitly."
        ))
    })
}

#[cfg(unix)]
fn has_daemon_incompatible_extra_sources(args: &ScanArgs) -> bool {
    #[cfg(feature = "binary")]
    if args.binary {
        return true;
    }
    #[cfg(feature = "git")]
    if args.git_blobs.is_some()
        || args.git_diff.is_some()
        || args.git_history.is_some()
        || args.git_staged
    {
        return true;
    }
    #[cfg(feature = "github")]
    if args.github_org.is_some() {
        return true;
    }
    #[cfg(feature = "gitlab")]
    if args.gitlab_group.is_some() {
        return true;
    }
    #[cfg(feature = "bitbucket")]
    if args.bitbucket_workspace.is_some() {
        return true;
    }
    #[cfg(feature = "s3")]
    if args.s3_bucket.is_some() {
        return true;
    }
    #[cfg(feature = "gcs")]
    if args.gcs_bucket.is_some() {
        return true;
    }
    #[cfg(feature = "azure")]
    if args.azure_container_url.is_some() {
        return true;
    }
    #[cfg(feature = "docker")]
    if args.docker_image.is_some() {
        return true;
    }
    #[cfg(feature = "web")]
    if args.url.as_ref().is_some_and(|urls| !urls.is_empty()) {
        return true;
    }
    args.source
        .as_ref()
        .is_some_and(|sources| !sources.is_empty())
}

#[cfg(unix)]
fn daemon_incompatible_scan_options(args: &ScanArgs) -> Option<&'static str> {
    if args.detectors_cli_explicit || args.detectors != PathBuf::from("detectors") {
        return Some(
            "this scan selects a detector corpus that the precompiled daemon scanner cannot honor",
        );
    }
    if args.fast
        || args.deep
        || args.precision
        || args.no_decode
        || args.no_entropy
        || args.no_entropy_ml_scoring
        || args.no_keyword_low_entropy
        || args.entropy_source_files
        || args.no_unicode_norm
        || args.no_ml
        || args.scan_comments
        || args.benchmark
    {
        return Some(
            "this scan sets scan-mode, engine, or benchmark options that require the in-process scanner",
        );
    }
    if args.backend.is_some()
        || args.autoroute_cache.is_some()
        || args.autoroute_calibrate
        || args.autoroute_gpu
        || args.no_autoroute_gpu
        || args.no_gpu
        || args.require_gpu
        || args.batch_pipeline
        || args.no_batch_pipeline
    {
        return Some(
            "this scan sets backend, GPU, batch-pipeline, or autoroute controls the daemon protocol cannot honor per request",
        );
    }
    if args.decode_depth.is_some()
        || args.decode_size_limit.is_some()
        || args.entropy_threshold.is_some()
        || args.entropy_bpe_max_bytes_per_token.is_some()
        || args.min_secret_len.is_some()
        || args.ml_weight.is_some()
        || args.max_file_size.is_some()
        || args.regex_dfa_limit.is_some()
        || args.gpu_batch_input_limit.is_some()
        || args.cache_dir.is_some()
        || args.ml_threshold.is_some()
    {
        return Some(
            "this scan changes scanner or source-limit configuration that the precompiled daemon scanner cannot honor",
        );
    }
    if args.no_default_excludes || args.exclude_paths.is_some() {
        return Some(
            "this scan changes path exclusion policy that the daemon single-file route cannot honor",
        );
    }
    if !args.known_prefixes.is_empty()
        || !args.secret_keywords.is_empty()
        || !args.test_keywords.is_empty()
        || !args.placeholder_keywords.is_empty()
    {
        return Some(
            "this scan changes detector confidence vocabulary that the precompiled daemon scanner cannot honor",
        );
    }
    None
}

#[cfg(unix)]
fn effective_single_file_path(args: &ScanArgs) -> Result<Option<&Path>> {
    // Several positional roots are never a daemon single-file candidate. Reading
    // only `path`/`input` here would see the FIRST root, route the scan over the
    // single-path daemon protocol, and silently drop every surplus root (Law 10).
    if args.input.len() > 1 {
        return Ok(None);
    }
    let Some(raw) = args
        .path
        .as_deref()
        .or_else(|| args.input.first().map(PathBuf::as_path))
    else {
        return Ok(None);
    };
    let meta = std::fs::metadata(raw)
        .with_context(|| format!("inspect {} as daemon single-file input", raw.display()))?;
    if !meta.is_file() {
        return Ok(None);
    }
    Ok(Some(raw))
}

#[cfg(unix)]
async fn run_via_daemon(args: &mut ScanArgs) -> Result<ExitCode> {
    let scan = acquire_via_daemon(args).await?;
    finish_daemon_scan(scan, args)
}

#[cfg(unix)]
struct DaemonScan {
    matches: Vec<RawMatch>,
    source_coverage_gaps: SourceCoverageGaps,
    source_bytes_scanned: u64,
    wall_start: chrono::DateTime<chrono::Utc>,
}

#[cfg(unix)]
async fn acquire_via_daemon(args: &mut ScanArgs) -> Result<DaemonScan> {
    crate::reset_scan_runtime_state();
    if args.dogfood {
        keyhog_scanner::telemetry::enable_dogfood();
    }
    let wall_start = chrono::Utc::now();
    let socket = effective_daemon_socket(args);
    let mut conn = client::connect(&socket).await.with_context(|| {
        format!(
            "daemon route: connect to {} (start one with `keyhog daemon start{}` or pass --daemon=off)",
            socket.display(),
            match &args.daemon_socket {
                Some(path) => format!(" --socket {}", path.display()),
                None => String::new(),
            },
        )
    })?;

    let (matches, source_coverage_gaps, source_bytes_scanned) = if args.stdin {
        let bytes = read_stdin_bytes(args)?;
        let source_bytes_scanned = bytes.len() as u64;
        // Keep the owned payload on the effective argument clone until the
        // route is known to have completed. The automatic fallback consumes
        // this same buffer through `BufferedStdinSource`.
        args.buffered_stdin = Some(bytes.clone());
        let stdin_cap_bytes = args.limits.to_source_limits().stdin_bytes;
        if bytes.len() > stdin_cap_bytes {
            bail!(
                "daemon route: stdin exceeds {stdin_cap_bytes} byte limit. +                 Drop `--daemon` to use the streaming in-process path."
            );
        }
        let text = String::from_utf8_lossy(&bytes).into_owned();
        let resp = conn
            .round_trip(&Request::ScanText {
                path: None,
                text,
                dogfood: args.dogfood,
            })
            .await?;
        let (matches, gaps) = unwrap_scan_results(resp)?;
        (matches, gaps, source_bytes_scanned)
    } else if let Some(path) = effective_single_file_path(args)? {
        let source_bytes_scanned = std::fs::metadata(path)
            .with_context(|| format!("stat daemon input {}", path.display()))?
            .len();
        let working_dir = std::env::current_dir()
            .ok() // LAW10: malformed input => None (fail-closed at the boundary), recall-safe
            .map(|p| p.to_string_lossy().into_owned());
        let resp = conn
            .round_trip(&Request::ScanPath {
                path: path.to_string_lossy().into_owned(),
                working_dir,
                dogfood: args.dogfood,
            })
            .await?;
        let (matches, gaps) = unwrap_scan_results(resp)?;
        (matches, gaps, source_bytes_scanned)
    } else {
        bail!(
            "daemon route requires either --stdin or a single file path. \
             For directory scans, pass `--daemon=off` to use the in-process scanner."
        );
    };

    Ok(DaemonScan {
        matches,
        source_coverage_gaps,
        source_bytes_scanned,
        wall_start,
    })
}

#[cfg(unix)]
fn finish_daemon_scan(scan: DaemonScan, args: &ScanArgs) -> Result<ExitCode> {
    let DaemonScan {
        matches,
        source_coverage_gaps,
        source_bytes_scanned,
        wall_start,
    } = scan;
    let findings = finalize_for_report(matches, args)?;
    let report_finished_at = chrono::Utc::now();
    let mut report_metadata = crate::reporting::report_metadata_from_scan_run(
        args,
        wall_start,
        report_finished_at,
        (report_finished_at - wall_start).num_milliseconds().max(0) as u128,
        1,
        source_bytes_scanned,
        keyhog_core::embedded_detector_count(),
        None,
    );
    // Merge daemon wire gaps into process-local skip counters so
    // CoverageCounts / SARIF notifications match in-process scans (KH-1369).
    if !source_coverage_gaps.is_empty() {
        keyhog_sources::merge_skip_count_deltas(&keyhog_sources::SkipCounts {
            over_max_size: source_coverage_gaps.over_max_size,
            binary: source_coverage_gaps.binary,
            excluded: 0,
            unreadable: source_coverage_gaps.unreadable,
            git_object_unreadable: source_coverage_gaps.git_object_unreadable,
            archive_truncated: source_coverage_gaps.archive_truncated,
            binary_section_name_unresolved: source_coverage_gaps.binary_section_name_unresolved,
            source_truncated: source_coverage_gaps.source_truncated,
            structured_source_parse_failures: source_coverage_gaps.structured_source_parse_failures,
            archive_duplicate_scan_unavailable: source_coverage_gaps
                .archive_duplicate_scan_unavailable,
            git_lfs_pointer: source_coverage_gaps.git_lfs_pointer,
        });
    }
    // Partial status when any gap (WARN or FAIL) was observed; exit 13 only
    // for FAIL-class gaps so daemon matches local scan (KH-1368).
    if !source_coverage_gaps.is_empty() {
        report_metadata.scan_status = ScanCompletionStatus::Partial;
    }
    crate::reporting::report_findings_with_metadata(&findings, args, &report_metadata)?;
    if args.dogfood {
        crate::orchestrator::reporting::dump_dogfood_trace();
    }

    let fail_gaps = source_coverage_gaps.fail_class_total();
    if fail_gaps > 0 {
        let palette = crate::style::for_stderr();
        eprintln!(
            "{}: daemon input coverage was incomplete ({} FAIL-class gap(s), {} total gap(s)); some requested bytes were not scanned.",
            crate::style::warn("warning", &palette),
            fail_gaps,
            source_coverage_gaps.total()
        );
    }

    if findings.is_empty() && fail_gaps > 0 {
        let palette = crate::style::for_stderr();
        eprintln!(
            "{}: not reporting \"clean\" after incomplete daemon input coverage.",
            crate::style::fail("error", &palette)
        );
        Ok(ExitCode::from(EXIT_SOURCE_FAILED))
    } else if findings.is_empty() {
        Ok(ExitCode::SUCCESS)
    } else {
        // Same live-vs-findings precedence as in-process `resolve_scan_exit`
        // (KH-1379): a Live finding must exit 10, not collapse to exit 1.
        let code = crate::orchestrator::scan_exit_code(&findings);
        if code == EXIT_LIVE_CREDENTIALS {
            Ok(ExitCode::from(EXIT_LIVE_CREDENTIALS))
        } else {
            Ok(ExitCode::from(EXIT_CREDENTIALS_FOUND))
        }
    }
}

#[cfg(unix)]
fn read_stdin_bytes(args: &ScanArgs) -> Result<Vec<u8>> {
    use std::io::Read;
    let stdin_cap_bytes = args.limits.to_source_limits().stdin_bytes;
    let mut buf = Vec::with_capacity(8 * 1024);
    std::io::stdin()
        .lock()
        .take(stdin_cap_bytes.saturating_add(1) as u64)
        .read_to_end(&mut buf)
        .context("daemon route: reading stdin")?;
    Ok(buf)
}

#[cfg(unix)]
fn unwrap_scan_results(resp: Response) -> Result<(Vec<RawMatch>, SourceCoverageGaps)> {
    match resp {
        Response::ScanResults {
            matches,
            engine_example_suppressions,
            dogfood_events,
            static_recovery_rejections,
            dogfood_detail_events_dropped,
            source_coverage_gaps,
            backend_recovery,
            ..
        } => {
            // Merge daemon-side telemetry into the CLI's process-local
            // counters. The reporter and `dump_dogfood_trace()` both
            // read these, so without the merge the count would stay
            // at 0 (the OnceLock cell here is distinct from the
            // daemon's). Wire v4 requires exact aggregates on every
            // ScanResults frame; the Hello handshake rejects older peers
            // before a scan request is sent.
            // Validate the reason vocabulary before mutating any client-side
            // telemetry. A newer daemon must not leave partial replay state in
            // this process when its aggregate schema is incompatible.
            keyhog_scanner::telemetry::merge_daemon_aggregates(
                &static_recovery_rejections,
                dogfood_detail_events_dropped,
            )
            .map_err(|error| {
                anyhow::anyhow!(
                    "daemon returned incompatible dogfood telemetry: {error}. Restart it with `keyhog daemon stop && keyhog daemon start`, or pass `--daemon=off`."
                )
            })?;
            if engine_example_suppressions > 0 {
                keyhog_scanner::telemetry::add_example_suppressions(
                    engine_example_suppressions as usize,
                );
            }
            if !dogfood_events.is_empty() {
                keyhog_scanner::telemetry::append_daemon_events(dogfood_events);
            }
            if let RequiredOption::Some(recovery) = backend_recovery {
                if recovery.failed_backend == "autoroute-invalid" {
                    let recovery_backend = keyhog_scanner::hw_probe::parse_backend_str(
                        &recovery.recovery_backend,
                    )
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "daemon returned unknown recovery backend {:?}; restart it with this KeyHog build",
                            recovery.recovery_backend
                        )
                    })?;
                    let recovered_range_count = recovery.recovered_ranges.len();
                    let recovered_chunks = recovery.recovered_ranges.iter().try_fold(
                        std::collections::BTreeSet::new(),
                        |mut chunks, range| {
                            if range.byte_end < range.byte_start {
                                bail!("daemon returned an invalid autoroute recovery range; restart it with this KeyHog build");
                            }
                            chunks.insert(range.chunk_index);
                            Ok::<_, anyhow::Error>(chunks)
                        },
                    )?.len();
                    let recovered_bytes = recovery
                        .recovered_ranges
                        .iter()
                        .map(|range| (range.byte_end - range.byte_start) as u64)
                        .sum::<u64>();
                    if recovered_chunks != recovery.recovered_chunks
                        || recovered_bytes != recovery.recovered_bytes
                    {
                        bail!("daemon returned inconsistent autoroute-recovery totals; restart it with this KeyHog build");
                    }
                    crate::orchestrator::record_completed_remote_autoroute_state_recovery(
                        recovery_backend,
                        recovered_range_count,
                        recovered_chunks,
                        recovered_bytes,
                        recovery.reason,
                    );
                    return Ok((matches, source_coverage_gaps));
                }
                let failed_backend = keyhog_scanner::hw_probe::parse_backend_str(
                    &recovery.failed_backend,
                )
                .ok_or_else(|| {
                    anyhow::anyhow!(
                        "daemon returned unknown failed backend {:?}; restart it with this KeyHog build",
                        recovery.failed_backend
                    )
                })?;
                let recovery_backend = keyhog_scanner::hw_probe::parse_backend_str(
                    &recovery.recovery_backend,
                )
                .ok_or_else(|| {
                    anyhow::anyhow!(
                        "daemon returned unknown recovery backend {:?}; restart it with this KeyHog build",
                        recovery.recovery_backend
                    )
                })?;
                let receipt = keyhog_scanner::BackendRecoveryReceipt::new(
                    failed_backend,
                    recovery_backend,
                    recovery
                        .recovered_ranges
                        .into_iter()
                        .map(|range| {
                            keyhog_scanner::RecoveredInputRange::new(
                                range.chunk_index,
                                range.byte_start,
                                range.byte_end,
                            )
                        })
                        .collect(),
                    recovery.reason,
                );
                if receipt.recovered_chunks() != recovery.recovered_chunks
                    || receipt.recovered_bytes() != recovery.recovered_bytes
                {
                    bail!(
                        "daemon returned inconsistent backend-recovery totals; restart it with this KeyHog build"
                    );
                }
                crate::orchestrator::record_completed_backend_recovery(&receipt);
            }
            Ok((matches, source_coverage_gaps))
        }
        Response::Error { message } => bail!("daemon: {message}"),
        other => bail!("daemon route: expected ScanResults, got {other:?}"),
    }
}

#[cfg(unix)]
fn finalize_for_report(matches: Vec<RawMatch>, args: &ScanArgs) -> Result<Vec<VerifiedFinding>> {
    // Test-fixture suppression mirrors the orchestrator's
    // pipeline_tests::* filter: known-public example credentials
    // (Stripe's sk_live_4eC39…, GitHub's ghp_… README sample, …) get
    // suppressed unless the user explicitly opts out with
    // --no-suppress-test-fixtures.
    let fixtures = if args.no_suppress_test_fixtures {
        crate::test_fixture_suppressions::TestFixtureSuppressions::empty()
    } else {
        crate::test_fixture_suppressions::TestFixtureSuppressions::bundled()
    };

    // The daemon process runs only the scanner: it does NOT load the
    // CLI-side `.keyhogignore` allowlist, the `.keyhogignore.toml`
    // declarative rule suppressor, or apply inline `keyhog:ignore`
    // comment directives. The in-process orchestrator applies all three
    // (`filter_and_resolve` + the rule-suppressor pass in `run.rs`).
    // Without replicating them here, routing an eligible single-file or
    // stdin scan over the daemon would silently un-suppress findings the
    // user explicitly allowlisted - results that change purely because a
    // daemon socket happens to be live. Anchor the allowlist files at the
    // same root the orchestrator uses: the scanned path's directory, or
    // "." for the stdin / bare-filename case.
    let allowlist = load_daemon_allowlist(args)?;

    // Mirror the in-process orchestrator's behaviour: when the
    // test-fixture filter drops a credential, bump the example-suppression
    // telemetry so the reporter's empty-findings summary distinguishes "no
    // matches at all" from "matched and suppressed as a known test
    // fixture". The daemon process runs its own scanner (with its own
    // telemetry counters that this CLI can't see), so the CLI must record
    // the suppression itself based on what came back over the wire.
    let mut matches: Vec<RawMatch> = matches
        .into_iter()
        .filter(|m| {
            if crate::orchestrator::suppresses_test_fixture(&fixtures, m) {
                return false;
            }
            // `.keyhogignore` legacy line-based allowlist: path globs,
            // credential-hash entries, and whole-detector ignores. Same
            // predicates the orchestrator runs in `filter_and_resolve`.
            if crate::orchestrator::suppresses_allowlist_match(&allowlist, m) {
                return false;
            }
            true
        })
        .collect();

    // Match resolution mirrors `ScanOrchestrator::filter_and_resolve`: named
    // service detectors beat generic/entropy matches on the same secret line
    // before cross-detector dedup picks a winner. Without this, daemon stdin can
    // report `entropy-api-key` for an AKIA value even though the scanner also
    // found the canonical `aws-access-key`.
    matches = keyhog_scanner::resolution::try_resolve_matches(matches)
        .map_err(anyhow::Error::msg)
        .context("failed to resolve matches; fix the detector definitions")?;

    // Inline `keyhog:ignore` / `gitleaks:allow` comment suppression. The
    // shared filter only acts on matches whose source is "filesystem"
    // (it re-opens `file_path` to read the directive line); daemon
    // `ScanPath` matches carry the daemon's own `source_type`
    // ("daemon/scan_path"), so normalise filesystem-backed matches to the
    // "filesystem" source before the call. A daemon single-file scan IS a
    // filesystem read, and `file_path` points at the real on-disk file,
    // so this is the same suppression the in-process path performs.
    // stdin/`ScanText` matches have no `file_path` and are left untouched
    // by the filter regardless of source.
    let filesystem_source = std::sync::Arc::<str>::from("filesystem");
    for m in &mut matches {
        if m.location.file_path.is_some() && m.location.source.as_ref() != "filesystem" {
            m.location.source = filesystem_source.clone();
        }
    }
    let matches = crate::inline_suppression::filter_inline_suppressions(matches);

    let scope = args.dedup.to_core();
    let deduped = crate::orchestrator::dedup_for_report(matches, &scope);
    let findings = crate::orchestrator::skipped_findings_from_deduped(deduped, args.show_secrets);

    // `.keyhogignore.toml` declarative rule suppressor (vyre rule engine).
    // The orchestrator applies this AFTER dedup on the final
    // `VerifiedFinding` set (see `orchestrator::run`), so we match that
    // ordering exactly. A missing/empty file is a no-op.
    let rule_suppressor = load_daemon_rule_suppressor(args)?;
    Ok(findings
        .into_iter()
        .filter(|f| !rule_suppressor.matches(f))
        .collect())
}

/// Resolve the directory used to discover `.keyhogignore` /
/// `.keyhogignore.toml` for a daemon-routed scan. Mirrors
/// `orchestrator::allowlist::allowlist_root`: a scanned directory is its
/// own root, a scanned file delegates to its parent, and the stdin /
/// bare-filename case falls back to ".".
#[cfg(unix)]
fn daemon_allowlist_root(args: &ScanArgs) -> PathBuf {
    let Some(path) = args
        .path
        .as_deref()
        .or_else(|| args.input.first().map(PathBuf::as_path))
    else {
        return PathBuf::from(".");
    };
    if path.is_dir() {
        return path.to_path_buf();
    }
    path.parent()
        .filter(|p| !p.as_os_str().is_empty())
        .map(Path::to_path_buf)
        .unwrap_or_else(|| PathBuf::from(".")) // LAW10: no parent/unresolved path => '.' (current dir), intended path default; recall-safe
}

/// Load the legacy line-based `.keyhogignore` allowlist for the daemon route.
/// A malformed file is a policy failure, not an empty allowlist.
#[cfg(unix)]
fn load_daemon_allowlist(args: &ScanArgs) -> Result<keyhog_core::Allowlist> {
    let ignore_path = daemon_allowlist_root(args).join(".keyhogignore");
    if ignore_path.exists() {
        keyhog_core::Allowlist::load_with_metadata_policy(
            &ignore_path,
            false,
            false,
            None,
        )
        .with_context(|| {
            format!(
                "daemon route: failed to load {}. Fix or remove the allowlist; refusing to scan with silently ignored policy.",
                ignore_path.display()
            )
        })
    } else {
        Ok(keyhog_core::Allowlist::default())
    }
}

/// Load the declarative `.keyhogignore.toml` rule suppressor for the daemon
/// route. A malformed file is a policy failure, not an empty suppressor.
#[cfg(unix)]
fn load_daemon_rule_suppressor(args: &ScanArgs) -> Result<RuleSuppressor> {
    let toml_path = daemon_allowlist_root(args).join(".keyhogignore.toml");
    if !toml_path.exists() {
        return Ok(RuleSuppressor::default());
    }
    let raw = std::fs::read_to_string(&toml_path).with_context(|| {
        format!(
            "daemon route: failed to read {}. Fix file permissions or remove the file; refusing \
             to scan with silently ignored suppression rules.",
            toml_path.display()
        )
    })?;
    match raw.parse::<RuleSuppressor>() {
        Ok(s) => Ok(s),
        Err(e) => anyhow::bail!(
            "daemon route: failed to load {}: {e}. Fix the TOML schema \
             (see docs/src/reference/keyhogignore-toml.md) or remove the file; refusing to scan \
             with silently ignored suppression rules.",
            toml_path.display()
        ),
    }
}