fairlead 0.20.0

Guardrails and a guided path for coding agents: rules enforced as the agent works, tests scoped to what a change can reach, capped project memory, and KPIs.
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
//! `fairlead guard check`: the check stage over tracked files with the
//! ratchet, or with `--staged` the commit stage over what the next commit adds.

use std::collections::BTreeSet;
use std::path::Path;
use std::process::ExitCode;
use std::time::Instant;

use clap::Subcommand;
use fairlead_core::config::{self, LoadOptions};
use fairlead_guard::baseline::{self, Counts};
use fairlead_guard::events::{Event, EventLog};
use fairlead_guard::{added, git, stages, Finding, Guard, Source};
use rayon::prelude::*;

#[derive(Subcommand)]
pub enum GuardAction {
    /// Check tracked files against every rule, and ratcheted rules against the baseline.
    Check {
        /// Check only what the next commit adds: each staged file before and after.
        #[arg(long)]
        staged: bool,
        /// Print every finding, including those the baseline holds.
        #[arg(long)]
        list: bool,
        /// Record the ratcheted counts as they are now.
        #[arg(long, conflicts_with = "staged")]
        write_baseline: bool,
        /// Check migrations against the merge base with this revision,
        /// over `guard.migrations.base`.
        #[arg(long, value_name = "REV", conflicts_with = "staged")]
        base: Option<String>,
        /// Before a push: the branch's new migrations against the base
        /// fetched now, and the `[pr]` rules this machine can check.
        #[arg(long, conflicts_with_all = ["staged", "write_baseline", "base"])]
        push: bool,
    },
    /// The write stage: read a Claude Code PreToolUse call on stdin and deny
    /// it, or add a note, when it breaks a rule. `fairlead hooks install` runs it.
    Hook,
    /// The Claude Code Stop hook: send the agent back while the tree it
    /// leaves hasn't passed `fairlead done`. `fairlead hooks install` runs it.
    Stop,
    /// The Claude Code PostToolUse hook: once per session, after an edit made
    /// with no brief, a note saying how to get one. `fairlead hooks install` runs it.
    Nudge,
    /// Compare another linter's findings, one `file:line rule` per line, with
    /// the check stage's, and fail on any difference.
    Compare {
        /// The other linter's output, or `-` for stdin.
        file: String,
        /// Only these rules, on both sides.
        #[arg(long, value_delimiter = ',')]
        rules: Vec<String>,
        /// Read the other linter's rule names as Fairlead's: `theirs=ours`.
        #[arg(long = "map", value_name = "THEIRS=OURS")]
        maps: Vec<String>,
    },
    /// Replay the files each commit since REV changed through the write hook,
    /// and report how long it took and what it decided.
    Bench {
        /// Replay the commits after this one, on HEAD's first-parent line.
        #[arg(long, value_name = "REV")]
        since: String,
        /// Stop after this many edits.
        #[arg(long, default_value_t = 200)]
        limit: usize,
        /// Fail when the 95th percentile is over this many milliseconds.
        #[arg(long, value_name = "MS")]
        p95_under: Option<f64>,
    },
}

fn fail(message: impl std::fmt::Display) -> ExitCode {
    eprintln!("guard: {message}");
    ExitCode::FAILURE
}

pub fn run(action: GuardAction, sets: Vec<String>, cwd: &Path) -> ExitCode {
    if matches!(action, GuardAction::Hook) {
        return crate::hook_cmd::run();
    }
    if matches!(action, GuardAction::Stop) {
        return crate::done_cmd::stop();
    }
    if matches!(action, GuardAction::Nudge) {
        return crate::brief_cmd::nudge();
    }
    if let GuardAction::Bench {
        since,
        limit,
        p95_under,
    } = &action
    {
        return crate::bench_cmd::run(cwd, since, *limit, *p95_under);
    }
    let loaded = match config::load(cwd, &LoadOptions::from_process(sets)) {
        Ok(loaded) => loaded,
        Err(e) => return fail(e),
    };
    if !loaded.problems.is_empty() {
        for p in &loaded.problems {
            eprintln!("{}: {}", p.key, p.message);
        }
        return fail("the config has problems; run `fairlead config check`");
    }
    let root = if loaded.files.is_empty() {
        crate::graph_cmd::repo_root(cwd)
    } else {
        loaded.root.clone()
    };
    let guard = match Guard::new(&loaded.config.guard, &root) {
        Ok(guard) => guard,
        Err(e) => return fail(e),
    };
    // The built-in secret-path rule alone runs only where it can fail: at a commit.
    let staged_only = matches!(action, GuardAction::Check { staged: true, .. });
    let push = matches!(action, GuardAction::Check { push: true, .. });
    let nothing = if push {
        guard.migrations.as_ref().is_none_or(|m| !m.fetches()) && loaded.config.pr.is_none()
    } else {
        guard.is_empty() && !(staged_only && guard.paths.is_some())
    };
    if nothing {
        println!("guard: no rules configured");
        return ExitCode::SUCCESS;
    }
    if let GuardAction::Compare { file, rules, maps } = &action {
        return crate::bench_cmd::compare(&root, &guard, file, rules, maps);
    }
    let GuardAction::Check {
        staged,
        list,
        write_baseline,
        base,
        push,
    } = action
    else {
        unreachable!("the other actions returned above");
    };
    if push {
        return check_push(&root, &guard, &loaded.config);
    }
    if staged {
        return check_staged(&root, &guard, &loaded.config.guard, list);
    }
    let baseline_path = root.join(&loaded.config.guard.baseline);
    let tree = Tree {
        list,
        write: write_baseline,
        base: base.as_deref(),
    };
    check_tree(&root, &guard, &baseline_path, tree)
}

/// How the check stage was asked to run.
struct Tree<'a> {
    list: bool,
    write: bool,
    base: Option<&'a str>,
}

/// Every finding the check stage sees over the tracked files, sorted.
pub fn tree_findings(
    root: &Path,
    guard: &Guard,
    base: Option<&str>,
) -> Result<Vec<Finding>, String> {
    tree_and_warnings(root, guard, base).map(|(found, _)| found)
}

/// The check stage's findings and its warnings, which never fail it.
fn tree_and_warnings(
    root: &Path,
    guard: &Guard,
    base: Option<&str>,
) -> Result<(Vec<Finding>, Vec<Finding>), String> {
    let files = git::tracked(root)?;
    // In parallel, and still in path order, since collect keeps it.
    let mut findings: Vec<Finding> = files
        .par_iter()
        .filter(|p| guard.reads(p))
        .map(|path| match std::fs::read_to_string(root.join(path)) {
            Ok(text) => guard.lint(&Source::new(path, &text)),
            // Deleted but not yet staged, or not text: nothing to read.
            Err(_) => Vec::new(),
        })
        .collect::<Vec<_>>()
        .into_iter()
        .flatten()
        .collect();
    let more = stages::tree(guard, root, &files, base)?;
    findings.extend(more.findings);
    for note in more.notes {
        eprintln!("guard: {note}");
    }
    fairlead_guard::sort(&mut findings);
    Ok((findings, more.warnings))
}

/// Warnings go to stderr, one line each, and never change the exit code.
fn warn_all(warnings: &[Finding]) {
    for w in warnings {
        eprintln!("warning: {w}");
    }
}

fn check_tree(root: &Path, guard: &Guard, baseline_path: &Path, how: Tree<'_>) -> ExitCode {
    let Tree { list, write, base } = how;
    let (findings, warnings) = match tree_and_warnings(root, guard, base) {
        Ok(found) => found,
        Err(e) => return fail(e),
    };
    warn_all(&warnings);
    if list {
        for f in &findings {
            println!("{f}");
        }
    }
    let ratcheted = guard.ratcheted();
    let (held, zero): (Vec<&Finding>, Vec<&Finding>) =
        findings.iter().partition(|f| ratcheted.contains(f.rule));
    let now = baseline::tally(held.iter().copied());
    if write {
        return write_baseline(baseline_path, &now, held.len());
    }
    let was = match baseline::read(baseline_path) {
        Ok(counts) => only_rules(counts, &ratcheted),
        Err(e) => return fail(e),
    };
    let changes = baseline::changes(&now, &was);
    let (worse, fell): (Vec<_>, Vec<_>) = changes.into_iter().partition(|c| c.now > c.was);
    if !zero.is_empty() || !worse.is_empty() {
        eprintln!(
            "guard: {} finding(s) with no baseline, {} ratcheted file/rule pair(s) above the baseline",
            zero.len(),
            worse.len()
        );
        if !list {
            let over: BTreeSet<(&str, &str)> = worse
                .iter()
                .map(|w| (w.file.as_str(), w.rule.as_str()))
                .collect();
            let shown = held
                .iter()
                .filter(|f| over.contains(&(f.file.as_str(), f.rule)));
            for f in zero.iter().chain(shown) {
                eprintln!("{f}");
            }
        }
        for w in &worse {
            eprintln!(
                "  {} {}: {} allowed, {} found",
                w.file, w.rule, w.was, w.now
            );
        }
        eprintln!("Fix them, or record a ratcheted count on purpose with `fairlead guard check --write-baseline`.");
        return ExitCode::FAILURE;
    }
    println!(
        "guard: clean, {} finding(s) held at the baseline",
        held.len()
    );
    let mut by_rule = std::collections::BTreeMap::<&str, usize>::new();
    for f in &held {
        *by_rule.entry(f.rule).or_default() += 1;
    }
    for (rule, n) in by_rule {
        println!("  {rule}: {n}");
    }
    if !fell.is_empty() {
        println!(
            "guard: {} ratcheted count(s) fell; `fairlead guard check --write-baseline` lowers the baseline to match",
            fell.len()
        );
    }
    ExitCode::SUCCESS
}

/// A rule no longer ratcheted, or no longer configured, has nothing to hold.
fn only_rules(counts: Counts, rules: &BTreeSet<&'static str>) -> Counts {
    counts
        .into_iter()
        .map(|(file, by_rule)| {
            let kept = by_rule
                .into_iter()
                .filter(|(r, _)| rules.contains(r.as_str()))
                .collect();
            (file, kept)
        })
        .filter(
            |(_, by_rule): &(String, std::collections::BTreeMap<String, u64>)| !by_rule.is_empty(),
        )
        .collect()
}

fn write_baseline(path: &Path, counts: &Counts, total: usize) -> ExitCode {
    if let Err(e) = baseline::write(path, counts) {
        return fail(format!("{}: {e}", path.display()));
    }
    println!(
        "guard: baseline written to {}, {total} finding(s) across {} file(s)",
        path.display(),
        counts.len()
    );
    ExitCode::SUCCESS
}

fn check_staged(root: &Path, guard: &Guard, settings: &config::Guard, list: bool) -> ExitCode {
    let start = Instant::now();
    let staged = match git::staged(root) {
        Ok(staged) => staged,
        Err(e) => return fail(e),
    };
    let mut new = Vec::new();
    let mut read = 0;
    for file in staged.iter().filter(|s| guard.reads(&s.path)) {
        let Some(after) = git::in_index(root, &file.path) else {
            continue;
        };
        read += 1;
        // Both sides are linted under the new path, so a rename compares like an edit.
        let lint = |text: &str| guard.lint(&Source::new(&file.path, text));
        let now = lint(&after);
        if settings.findings == config::Findings::All {
            new.extend(now);
            continue;
        }
        let before = file
            .before
            .as_deref()
            .and_then(|b| git::at_head(root, b))
            .map(|text| lint(&text))
            .unwrap_or_default();
        new.extend(added::added(&before, &now));
    }
    match stages::staged(guard, root, &staged) {
        Ok(more) => {
            new.extend(more.findings);
            for note in more.notes {
                eprintln!("guard: {note}");
            }
            warn_all(&more.warnings);
        }
        Err(e) => return fail(e),
    }
    fairlead_guard::sort(&mut new);
    let warn = settings.on_finding == config::OnFinding::Warn;
    let decision = match (new.is_empty(), warn) {
        (true, _) => "allow",
        (false, true) => "warn",
        (false, false) => "deny",
    };
    let mut event = Event::new("commit", decision, start.elapsed());
    event.files = Some(read);
    event.added = new.len();
    event.rules = new
        .iter()
        .map(|f| f.rule)
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect();
    let log = match settings.events {
        config::Events::Local => EventLog::open(root),
        config::Events::Off => None,
    };
    if let Some(log) = log {
        // The log is a record, never a reason to block or fail a commit.
        let _ = log.append(&event);
    }
    if list {
        for f in &new {
            println!("{f}");
        }
    }
    let what = match settings.findings {
        config::Findings::Added => "the staged changes add",
        config::Findings::All => "the staged files have",
    };
    if new.is_empty() {
        // Every staged file, not only those a content rule read: the path
        // and external rules saw them all.
        println!("guard: {} staged file(s), {what} no findings", staged.len());
        return ExitCode::SUCCESS;
    }
    let then = if warn { ", committing anyway" } else { "" };
    eprintln!("guard: {what} {} finding(s){then}:", new.len());
    if !list {
        for f in &new {
            eprintln!("{f}");
        }
    }
    if warn {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    }
}

/// `guard check --push`, the pre-push hook: migration numbers against the
/// base fetched now, then the `[pr]` rules this machine can check.
fn check_push(root: &Path, guard: &Guard, config: &config::Config) -> ExitCode {
    let found = stages::push(guard, root);
    for note in &found.notes {
        eprintln!("guard: {note}");
    }
    let mut failed = !found.findings.is_empty();
    if failed {
        eprintln!(
            "guard: {} migration number(s) already taken on the base:",
            found.findings.len()
        );
        for f in &found.findings {
            eprintln!("{f}");
        }
    }
    if let Some(pr) = &config.pr {
        failed |= !crate::pr_cmd::local(root, pr);
    } else if !failed {
        println!("guard: the branch's migration numbers are free on the base");
    }
    if failed {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

/// For `fairlead doctor`: whether the gitleaks a preset rule runs is there
/// and new enough.
pub fn doctor_lines(root: &Path, config: &config::Config) -> String {
    let ids: Vec<String> = config
        .guard
        .external
        .items()
        .iter()
        .filter(|r| r.preset == Some(config::ExternalPreset::Gitleaks))
        .map(|r| r.rule_id())
        .collect();
    if ids.is_empty() {
        return String::new();
    }
    let rules = format!("`{}`", ids.join("`, `"));
    use fairlead_guard::gitleaks;
    match gitleaks::version(root) {
        Some(v) if gitleaks::new_enough(&v) => format!("gitleaks: {v}, for {rules}\n"),
        Some(v) => format!(
            "gitleaks: {v} is older than {}.{}, so {rules} fails until it's upgraded\n",
            gitleaks::OLDEST.0,
            gitleaks::OLDEST.1
        ),
        None => format!(
            "gitleaks: not installed, so {rules} notes it and scans no content \
             (https://github.com/gitleaks/gitleaks#installing)\n"
        ),
    }
}