fallow-core 3.44.0

Internal detector backend for fallow-engine and fallow-api
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
//! Git hook command scanner for dependency usage detection.
//!
//! Reads the commands that git hook managers and staged-file task runners
//! run: husky and Vite+ hook scripts, lefthook configs, simple-git-hooks and
//! lint-staged configs (in package.json or in their own files), and the
//! `staged` block of a Vite+ config. It also reads the agent hook commands of
//! the shared `.claude/settings.json` and `.codex/hooks.json`. A hook command
//! that runs the agent gate that Fallow generates credits the `fallow`
//! package. A package these
//! commands invoke is used, the same way a package.json script or a CI
//! workflow step makes it used.
//!
//! The scanner credits packages only. It does not seed entry files, because a
//! hook argument such as `{staged_files}` is a placeholder, not a path.

use std::path::Path;

use rustc_hash::{FxHashMap, FxHashSet};

use super::{IgnoredCommandEntries, ScriptCatalog, analyze_commands_with_context};

/// The hook script directories: husky, and Vite+ (`vp config`).
const HOOK_SCRIPT_DIRS: &[&str] = &[".husky", ".vite-hooks"];

const LEFTHOOK_FILES: &[&str] = &[
    "lefthook.yml",
    "lefthook.yaml",
    ".lefthook.yml",
    ".lefthook.yaml",
    "lefthook-local.yml",
    "lefthook-local.yaml",
    ".lefthook-local.yml",
    ".lefthook-local.yaml",
];

const SIMPLE_GIT_HOOKS_JSON_FILES: &[&str] = &[".simple-git-hooks.json", "simple-git-hooks.json"];

const SIMPLE_GIT_HOOKS_JS_FILES: &[&str] = &[
    ".simple-git-hooks.js",
    ".simple-git-hooks.cjs",
    ".simple-git-hooks.mjs",
    "simple-git-hooks.js",
    "simple-git-hooks.cjs",
    "simple-git-hooks.mjs",
];

const LINT_STAGED_YAML_FILES: &[&str] = &[".lintstagedrc.yaml", ".lintstagedrc.yml"];

const LINT_STAGED_JS_FILES: &[&str] = &[
    ".lintstagedrc.js",
    ".lintstagedrc.cjs",
    ".lintstagedrc.mjs",
    ".lintstagedrc.ts",
    "lint-staged.config.js",
    "lint-staged.config.cjs",
    "lint-staged.config.mjs",
    "lint-staged.config.ts",
];

/// The package.json keys that hold hook or staged-file commands.
const MANIFEST_COMMAND_KEYS: &[&str] = &["simple-git-hooks", "lint-staged"];

/// The agent hook configs, as pairs of the config file and its harness
/// directory. Each config holds `hooks.<Event>[].hooks[].command` entries.
/// The personal `.claude/settings.local.json` is not read: Claude Code keeps
/// it out of git, so a local run and a CI run would credit different
/// packages.
const AGENT_HOOK_FILES: &[(&str, &str)] = &[
    (".claude/settings.json", ".claude"),
    (".codex/hooks.json", ".codex"),
];

/// The project directory prefixes of an agent hook command, in the order
/// that they are removed. Claude Code sets `CLAUDE_PROJECT_DIR` to the project
/// root and runs hooks from it, so a removed prefix leaves a path relative to
/// the root that the command scanner can follow.
const PROJECT_DIR_PREFIXES: &[&str] = &[
    "\"$CLAUDE_PROJECT_DIR\"/",
    "\"${CLAUDE_PROJECT_DIR}\"/",
    "$CLAUDE_PROJECT_DIR/",
    "${CLAUDE_PROJECT_DIR}/",
    "\"$PWD\"/",
    "\"${PWD}\"/",
    "$PWD/",
    "${PWD}/",
];

/// The agent gate that `fallow agent install` and `fallow setup-hooks` write,
/// relative to the harness directory.
const GENERATED_GATE: &str = "hooks/fallow-gate.sh";

/// The header line of the generated gate.
const GENERATED_GATE_MARKER: &str = "# Generated by fallow setup-hooks.";

/// The package that the generated gate runs. The gate passes the binary as
/// an argument to a shell function, so the command scanner cannot see it.
const GENERATED_GATE_PACKAGE: &str = "fallow";

/// Inputs shared by every hook source of one package root.
pub struct HookContext<'a> {
    pub bin_map: &'a FxHashMap<String, String>,
    pub declared_packages: &'a FxHashSet<String>,
    pub scripts: &'a ScriptCatalog,
    pub ignored: IgnoredCommandEntries<'a>,
}

/// Return the package names that the git hooks and staged-file commands
/// under `root` invoke.
#[must_use]
pub fn analyze_hook_files(root: &Path, context: &HookContext<'_>) -> FxHashSet<String> {
    let _span = tracing::info_span!("analyze_hook_files").entered();
    let mut commands = collect_hook_commands(root);
    let agent_commands = collect_agent_hook_commands(root);
    let runs_gate = runs_generated_gate(root, &agent_commands);
    commands.extend(agent_commands.into_iter().map(|(_, command)| command));
    if commands.is_empty() {
        return FxHashSet::default();
    }
    let mut used = analyze_commands_with_context(
        &commands,
        root,
        context.bin_map,
        context.declared_packages,
        context.scripts,
        context.ignored,
    )
    .used_packages;
    if runs_gate {
        used.insert(GENERATED_GATE_PACKAGE.to_string());
    }
    used
}

/// Gather every `hooks.<Event>[].hooks[].command` string of the agent hook
/// configs under `root`.
fn collect_agent_hook_commands(root: &Path) -> Vec<(&'static str, String)> {
    let mut commands = Vec::new();
    for (file, harness) in AGENT_HOOK_FILES {
        let Some(config) = read_json(&root.join(file)) else {
            continue;
        };
        let Some(events) = config.get("hooks").and_then(serde_json::Value::as_object) else {
            continue;
        };
        let entries = events
            .values()
            .filter_map(serde_json::Value::as_array)
            .flatten()
            .filter_map(|group| group.get("hooks")?.as_array())
            .flatten();
        for entry in entries {
            if let Some(command) = entry.get("command").and_then(serde_json::Value::as_str) {
                commands.push((*harness, strip_project_dir(command)));
            }
        }
    }
    commands
}

/// Remove each project directory prefix from an agent hook command, so
/// `"$CLAUDE_PROJECT_DIR"/.claude/hooks/a.sh` becomes `.claude/hooks/a.sh`.
fn strip_project_dir(command: &str) -> String {
    PROJECT_DIR_PREFIXES
        .iter()
        .fold(command.to_string(), |command, prefix| {
            command.replace(prefix, "")
        })
}

/// Whether an agent hook command runs the generated gate of its harness.
fn runs_generated_gate(root: &Path, commands: &[(&str, String)]) -> bool {
    commands.iter().any(|(harness, command)| {
        let gate = format!("{harness}/{GENERATED_GATE}");
        command.contains(&gate)
            && std::fs::read_to_string(root.join(&gate))
                .is_ok_and(|content| content.contains(GENERATED_GATE_MARKER))
    })
}

/// Gather every hook and staged-file command string under `root`.
fn collect_hook_commands(root: &Path) -> Vec<String> {
    let mut commands = Vec::new();
    for dir in HOOK_SCRIPT_DIRS {
        collect_hook_script_commands(&root.join(dir), &mut commands);
    }
    commands.extend(super::vite_plus::staged_commands(root));

    for name in LEFTHOOK_FILES {
        if let Ok(content) = std::fs::read_to_string(root.join(name)) {
            commands.extend(super::ci::extract_ci_commands(&content));
        }
    }

    if let Some(manifest) = read_json(&root.join("package.json")) {
        for key in MANIFEST_COMMAND_KEYS {
            if let Some(value) = manifest.get(*key) {
                collect_json_strings(value, &mut commands);
            }
        }
    }

    for name in SIMPLE_GIT_HOOKS_JSON_FILES
        .iter()
        .chain(&[".lintstagedrc.json"])
    {
        if let Some(value) = read_json(&root.join(name)) {
            collect_json_strings(&value, &mut commands);
        }
    }

    // `.lintstagedrc` is JSON or YAML.
    if let Ok(content) = std::fs::read_to_string(root.join(".lintstagedrc")) {
        match serde_json::from_str::<serde_json::Value>(&content) {
            Ok(value) => collect_json_strings(&value, &mut commands),
            Err(_) => commands.extend(yaml_scalar_values(&content)),
        }
    }
    for name in LINT_STAGED_YAML_FILES {
        if let Ok(content) = std::fs::read_to_string(root.join(name)) {
            commands.extend(yaml_scalar_values(&content));
        }
    }

    for name in SIMPLE_GIT_HOOKS_JS_FILES.iter().chain(LINT_STAGED_JS_FILES) {
        if let Ok(content) = std::fs::read_to_string(root.join(name)) {
            commands.extend(js_string_literals(&content));
        }
    }

    commands
}

/// Read the hook scripts directly inside a hook directory such as `.husky/`.
/// The `_` directory holds the runtime of the hook manager and is skipped
/// with every other directory.
fn collect_hook_script_commands(dir: &Path, commands: &mut Vec<String>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    let mut paths: Vec<_> = entries
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| path.is_file())
        .filter(|path| {
            path.file_name()
                .is_some_and(|name| !name.to_string_lossy().starts_with('.'))
        })
        .collect();
    paths.sort();
    for path in paths {
        if let Ok(content) = std::fs::read_to_string(&path) {
            commands.extend(super::shell_helpers::script_file_commands(&content));
        }
    }
}

fn read_json(path: &Path) -> Option<serde_json::Value> {
    let content = std::fs::read_to_string(path).ok()?;
    serde_json::from_str(&content).ok()
}

/// Collect every string value (not key) of a JSON value.
fn collect_json_strings(value: &serde_json::Value, out: &mut Vec<String>) {
    match value {
        serde_json::Value::String(text) => out.push(text.clone()),
        serde_json::Value::Array(items) => {
            for item in items {
                collect_json_strings(item, out);
            }
        }
        serde_json::Value::Object(map) => {
            for item in map.values() {
                collect_json_strings(item, out);
            }
        }
        _ => {}
    }
}

/// The scalar values of a flat YAML mapping or list, as a lint-staged YAML
/// config writes them: `"*.ts": tool --fix` and `  - tool --check`.
fn yaml_scalar_values(content: &str) -> Vec<String> {
    let mut values = Vec::new();
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        let value = if let Some(item) = trimmed.strip_prefix("- ") {
            item
        } else if let Some((_, value)) = split_yaml_key(trimmed) {
            value
        } else {
            continue;
        };
        let value = unquote(value.trim());
        if !value.is_empty() && value != "|" && value != ">" {
            values.push(value.to_string());
        }
    }
    values
}

/// Split `key: value` where the key may be quoted and contain `:`.
fn split_yaml_key(line: &str) -> Option<(&str, &str)> {
    let first = line.chars().next()?;
    if first == '"' || first == '\'' {
        let close = line[1..].find(first)? + 1;
        let rest = line[close + 1..].trim_start();
        return rest.strip_prefix(':').map(|value| (&line[..=close], value));
    }
    line.split_once(": ")
        .or_else(|| line.strip_suffix(':').map(|key| (key, "")))
}

fn unquote(value: &str) -> &str {
    for quote in ['"', '\''] {
        if let Some(inner) = value
            .strip_prefix(quote)
            .and_then(|rest| rest.strip_suffix(quote))
        {
            return inner;
        }
    }
    value
}

/// The string literals of a JavaScript config, as candidate commands. A
/// template literal contributes the text before its first `${`, which names
/// the binary in a command such as `` `tool ${files.join(" ")}` ``. Comments
/// are skipped. Strings that are not commands, such as glob keys, resolve to
/// no declared package and credit nothing.
fn js_string_literals(content: &str) -> Vec<String> {
    let bytes = content.as_bytes();
    let mut literals = Vec::new();
    let mut index = 0;
    while index < bytes.len() {
        match bytes[index] {
            b'/' if bytes.get(index + 1) == Some(&b'/') => {
                while index < bytes.len() && bytes[index] != b'\n' {
                    index += 1;
                }
            }
            b'/' if bytes.get(index + 1) == Some(&b'*') => {
                index += 2;
                while index + 1 < bytes.len() && !(bytes[index] == b'*' && bytes[index + 1] == b'/')
                {
                    index += 1;
                }
                index += 2;
            }
            quote @ (b'"' | b'\'' | b'`') => {
                let start = index + 1;
                let mut end = start;
                let mut template_cut = None;
                while end < bytes.len() && bytes[end] != quote {
                    if bytes[end] == b'\\' {
                        end += 1;
                    } else if quote == b'`'
                        && template_cut.is_none()
                        && bytes[end] == b'$'
                        && bytes.get(end + 1) == Some(&b'{')
                    {
                        template_cut = Some(end);
                    } else if bytes[end] == b'\n' && quote != b'`' {
                        break;
                    }
                    end += 1;
                }
                let literal_end = template_cut.unwrap_or(end).min(bytes.len());
                if let Some(text) = content.get(start..literal_end) {
                    let text = text.trim();
                    if !text.is_empty() && !text.contains('\n') {
                        literals.push(text.to_string());
                    }
                }
                index = end + 1;
            }
            _ => index += 1,
        }
    }
    literals
}

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

    fn write(root: &Path, path: &str, content: &str) {
        let full = root.join(path);
        if let Some(parent) = full.parent() {
            std::fs::create_dir_all(parent).expect("create parent dir");
        }
        std::fs::write(full, content).expect("write file");
    }

    fn used(root: &Path, declared: &[&str]) -> Vec<String> {
        let declared: FxHashSet<String> = declared.iter().map(|d| (*d).to_string()).collect();
        let catalog = ScriptCatalog::default();
        let mut packages: Vec<String> = analyze_hook_files(
            root,
            &HookContext {
                bin_map: &FxHashMap::default(),
                declared_packages: &declared,
                scripts: &catalog,
                ignored: IgnoredCommandEntries::NONE,
            },
        )
        .into_iter()
        .filter(|name| declared.contains(name))
        .collect();
        packages.sort();
        packages
    }

    #[test]
    fn husky_hook_scripts_credit_invoked_tools() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        write(
            root,
            ".husky/pre-commit",
            "#!/usr/bin/env sh\n. \"$(dirname -- \"$0\")/_/husky.sh\"\n\nnpx lint-tool --staged\n",
        );
        write(
            root,
            ".husky/commit-msg",
            "npx --no -- msg-tool --edit \"$1\"\n",
        );
        write(root, ".husky/_/husky.sh", "other-tool\n");
        assert_eq!(
            used(root, &["lint-tool", "msg-tool", "other-tool"]),
            vec!["lint-tool".to_string(), "msg-tool".to_string()]
        );
    }

    #[test]
    fn lefthook_run_commands_credit_invoked_tools() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        write(
            root,
            "lefthook.yml",
            "pre-commit:\n  commands:\n    lint:\n      glob: \"*.js\"\n      run: npx lint-tool {staged_files}\n",
        );
        assert_eq!(used(root, &["lint-tool"]), vec!["lint-tool".to_string()]);
    }

    #[test]
    fn manifest_hook_and_staged_commands_credit_invoked_tools() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        write(
            root,
            "package.json",
            r#"{
              "simple-git-hooks": { "pre-commit": "npx staged-runner" },
              "lint-staged": { "*.ts": ["lint-tool --fix", "format-tool --write"] }
            }"#,
        );
        assert_eq!(
            used(
                root,
                &["staged-runner", "lint-tool", "format-tool", "unused-tool"]
            ),
            vec![
                "format-tool".to_string(),
                "lint-tool".to_string(),
                "staged-runner".to_string()
            ]
        );
    }

    #[test]
    fn lint_staged_files_credit_invoked_tools() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        write(
            root,
            ".lintstagedrc",
            "\"*.js\": lint-tool\n\"*.css\":\n  - style-tool --fix\n",
        );
        write(
            root,
            "lint-staged.config.mjs",
            "// comment-tool is not a command\nexport default {\n  '*.ts': (files) => `type-tool ${files.join(' ')}`,\n  '*.md': 'doc-tool',\n};\n",
        );
        assert_eq!(
            used(
                root,
                &[
                    "lint-tool",
                    "style-tool",
                    "type-tool",
                    "doc-tool",
                    "comment-tool"
                ]
            ),
            vec![
                "doc-tool".to_string(),
                "lint-tool".to_string(),
                "style-tool".to_string(),
                "type-tool".to_string()
            ]
        );
    }

    #[test]
    fn agent_hook_commands_credit_invoked_tools() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        write(
            root,
            ".claude/settings.json",
            r#"{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"npx audit-tool audit"}]}],"Stop":[{"hooks":[{"type":"command","command":".claude/hooks/a.sh"}]}]},"env":{"X":"not-run-tool"}}"#,
        );
        write(
            root,
            ".claude/hooks/a.sh",
            "#!/bin/sh\nnpx helper-tool check\n",
        );
        write(
            root,
            ".codex/hooks.json",
            r#"{"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"lint-tool --fix"}]}]}}"#,
        );
        assert_eq!(
            used(
                root,
                &["audit-tool", "helper-tool", "lint-tool", "not-run-tool"]
            ),
            vec![
                "audit-tool".to_string(),
                "helper-tool".to_string(),
                "lint-tool".to_string()
            ]
        );
    }

    #[test]
    fn project_dir_prefixed_hook_scripts_credit_invoked_tools() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        write(
            root,
            ".claude/settings.json",
            r#"{"hooks":{"Stop":[{"hooks":[
              {"type":"command","command":"\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/a.sh"},
              {"type":"command","command":"bash ${CLAUDE_PROJECT_DIR}/.claude/hooks/b.sh"},
              {"type":"command","command":"$PWD/.claude/hooks/c.sh --flag"}
            ]}]}}"#,
        );
        write(root, ".claude/hooks/a.sh", "#!/bin/sh\nnpx tool-a\n");
        write(root, ".claude/hooks/b.sh", "#!/bin/sh\nnpx tool-b\n");
        write(root, ".claude/hooks/c.sh", "#!/bin/sh\nnpx tool-c\n");
        assert_eq!(
            used(root, &["tool-a", "tool-b", "tool-c", "tool-d"]),
            vec![
                "tool-a".to_string(),
                "tool-b".to_string(),
                "tool-c".to_string()
            ]
        );
    }

    #[test]
    fn local_claude_settings_credit_nothing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        write(
            root,
            ".claude/settings.local.json",
            r#"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"npx local-tool"}]}]}}"#,
        );
        assert!(used(root, &["local-tool"]).is_empty());
    }

    #[test]
    fn generated_agent_gate_credits_fallow() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        write(
            root,
            ".codex/hooks.json",
            r#"{"hooks":{"PreToolUse":[{"matcher":"^Bash$","hooks":[{"type":"command","command":"cd \"$d\" && exec ./.codex/hooks/fallow-gate.sh"}]}]}}"#,
        );
        write(
            root,
            ".codex/hooks/fallow-gate.sh",
            "#!/usr/bin/env bash\n# Generated by fallow setup-hooks.\ngate_try_json_runner \"$anchor\" npx --no-install fallow\n",
        );
        assert_eq!(used(root, &["fallow"]), vec!["fallow".to_string()]);
    }

    #[test]
    fn unreferenced_agent_gate_credits_nothing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        write(
            root,
            ".claude/hooks/fallow-gate.sh",
            "#!/usr/bin/env bash\n# Generated by fallow setup-hooks.\n",
        );
        assert!(used(root, &["fallow"]).is_empty());
    }

    #[test]
    fn no_hook_sources_credit_nothing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        write(
            root,
            "package.json",
            r#"{ "scripts": { "lint": "lint-tool" } }"#,
        );
        assert!(used(root, &["lint-tool"]).is_empty());
    }
}