Skip to main content

ljos_cli/
git_hooks.rs

1//! Global git hooks that book a commit when the runner has no prompt hook.
2//!
3//! When `core.hooksPath` is unset, `install` writes a stub for every
4//! standard git hook and points the global config at ljos's directory. The
5//! stub calls `ljos git-hook <name>`, then runs the repository's
6//! `.git/hooks/<name>` or the previous path an older install recorded, with
7//! the same arguments. `post-rewrite` copies stdin first, so `ljos git-hook`
8//! and the chained hook both see the old and new shas.
9//!
10//! When `core.hooksPath` already names a directory, install leaves that
11//! setting alone and appends a delimited block to each hook there. The
12//! block calls `ljos git-hook <name>`. A missing hook file is created
13//! executable. Text that was already in the file is kept. Uninstall removes
14//! only that block, and deletes a file that held nothing else.
15//!
16//! `post-commit` and `post-rewrite` book the commit. Booking never fails
17//! the hook. `pre-commit` and `pre-push` run the sitting gate under an
18//! agent runner: a commit needs a live sitting, and a push onto a
19//! protected branch also needs the sitting's ticket to clear it. That
20//! refusal fails the hook. `pre-push` also refuses a commit it would
21//! send whose message has a by-trailer, a made-with line, or a
22//! generated line, and it refuses when those commits cannot be read.
23//! A Tests paragraph is not that line. The check runs with or without
24//! a runner. `pre-push` copies stdin like `post-rewrite`.
25//!
26//! `pre-commit install` follows `core.hooksPath` and would replace stubs
27//! ljos owns. Install the framework into the repository, then let the stub
28//! chain to it:
29//!
30//! ```text
31//! dir=$(git rev-parse --git-dir)
32//! git config --local core.hooksPath "$dir/hooks"
33//! pre-commit install
34//! git config --local --unset core.hooksPath
35//! ```
36//!
37//! A commit is booked only when a seat resolves from `LJOS_SEAT`, then an
38//! agy or opencode conversation id. A conversation id does not name a seat.
39//! The process tree is not a seat.
40//! The holder is `SEAT@TAG`, the same name `ljos claim` uses. Paths in
41//! `[git_hooks] skip` of `ljos.toml`, plus `/tmp`, `/var/tmp`, `/dev/shm`,
42//! the tracker, `CLAIMDAG_DIR` and the deedar store, are not booked.
43//! An amend or a rebase moves the citation onto the new sha.
44
45use std::cell::Cell;
46use std::fs;
47use std::path::{Path, PathBuf};
48use std::process::Command;
49
50use anyhow::{anyhow, bail, Context, Result};
51
52/// Every hook git looks up by name. A global `core.hooksPath` hides the
53/// repository's copy of each of these, so the stub has to exist for each.
54const HOOK_NAMES: &[&str] = &[
55    "applypatch-msg",
56    "pre-applypatch",
57    "post-applypatch",
58    "pre-commit",
59    "pre-merge-commit",
60    "prepare-commit-msg",
61    "commit-msg",
62    "post-commit",
63    "pre-rebase",
64    "post-checkout",
65    "post-merge",
66    "pre-push",
67    "pre-receive",
68    "update",
69    "proc-receive",
70    "post-receive",
71    "post-update",
72    "reference-transaction",
73    "push-to-checkout",
74    "pre-auto-gc",
75    "post-rewrite",
76    "sendemail-validate",
77    "fsmonitor-watchman",
78    "p4-changelist",
79    "p4-prepare-changelist",
80    "p4-post-changelist",
81    "p4-pre-submit",
82    "post-index-change",
83];
84
85fn books_commit(name: &str) -> bool {
86    matches!(name, "post-commit" | "post-rewrite")
87}
88
89fn gates_git(name: &str) -> bool {
90    matches!(name, "pre-commit" | "pre-push")
91}
92
93/// `install`, `uninstall`, or `status`.
94///
95/// # Errors
96///
97/// `action` is not one of those, or git cannot record `core.hooksPath`.
98pub fn run(action: &str) -> Result<()> {
99    match action {
100        "install" => {
101            let dir = install()?;
102            println!("installed {}", dir.display());
103            Ok(())
104        }
105        "uninstall" => {
106            uninstall()?;
107            println!("uninstalled");
108            Ok(())
109        }
110        "status" => {
111            print!("{}", status());
112            Ok(())
113        }
114        other => bail!("git-hooks: {other} is not install, uninstall, or status"),
115    }
116}
117
118/// Install the hooks `ljos doctor` checks.
119///
120/// An unset `core.hooksPath` is pointed at ljos's hook directory. A path
121/// that already names a directory is left alone, and each hook there gains
122/// a block that calls `ljos git-hook`.
123///
124/// # Errors
125///
126/// The directory cannot be written, or `git config` fails.
127pub fn install() -> Result<PathBuf> {
128    install_at(&hooks_dir(), &[])
129}
130
131/// [`install`] into `dir`, with `git_env` on the child `git config`.
132///
133/// An empty `git_env` leaves that child with this process's environment.
134/// `GIT_CONFIG_GLOBAL` and `HOME` belong here when the caller is keeping
135/// the login config untouched.
136///
137/// # Errors
138///
139/// The directory cannot be written, or `git config` fails.
140pub(crate) fn install_at(dir: &Path, git_env: &[(&str, &str)]) -> Result<PathBuf> {
141    let current = global_hooks_path(git_env);
142    if let Some(path) = nonempty(current.as_deref()) {
143        if !same_dir(Path::new(path), dir) {
144            chain_user_hooks(Path::new(path))?;
145            return Ok(PathBuf::from(path));
146        }
147    }
148    write_owned_hooks(dir)?;
149    if nonempty(current.as_deref()).is_none() {
150        let _ = fs::remove_file(dir.join("previous-hooks-path"));
151        set_global_hooks_path(dir, git_env)?;
152    }
153    Ok(dir.to_path_buf())
154}
155
156/// Remove ljos from the hooks git runs.
157///
158/// A directory ljos does not own loses only the ljos block. A file that
159/// held nothing else is deleted. When ljos owns `core.hooksPath`, the
160/// previous path is restored and the stubs are removed.
161///
162/// # Errors
163///
164/// `git config` cannot restore or unset the path, or a hook file cannot
165/// be rewritten.
166pub fn uninstall() -> Result<()> {
167    let dir = hooks_dir();
168    let current = global_hooks_path(&[]);
169    match nonempty(current.as_deref()) {
170        Some(path) if same_dir(Path::new(path), &dir) => {
171            let previous = fs::read_to_string(dir.join("previous-hooks-path"))
172                .ok()
173                .map(|text| text.trim().to_string())
174                .filter(|text| !text.is_empty());
175            if let Some(prev) = previous {
176                set_global_hooks_path(Path::new(&prev), &[])?;
177            } else {
178                unset_global_hooks_path(&[])?;
179            }
180            remove_owned_hooks(&dir);
181        }
182        Some(path) => strip_user_hooks(Path::new(path))?,
183        None => remove_owned_hooks(&dir),
184    }
185    Ok(())
186}
187
188/// Where the hooks are, and what `core.hooksPath` says.
189#[must_use]
190pub fn status() -> String {
191    let dir = hooks_dir();
192    let configured_path = global_hooks_path(&[]);
193    let configured = configured_path.clone().unwrap_or_else(|| "(unset)".into());
194    let present = nonempty(configured_path.as_deref())
195        .is_some_and(|path| hooks_present(Path::new(path), &dir));
196    let stale = nonempty(configured_path.as_deref())
197        .filter(|_| present)
198        .and_then(|path| stale_note(Path::new(path), &dir));
199    let hooks = if present {
200        configured.clone()
201    } else if owned_installed(&dir) {
202        dir.display().to_string()
203    } else {
204        "not installed".into()
205    };
206    let reach = if present && stale.is_none() {
207        "ljos hooks run".to_string()
208    } else if let Some(note) = stale {
209        format!("ljos hooks run, but {note}; {HOOKS_FIX}")
210    } else {
211        format!("ljos hooks do not run; {HOOKS_FIX}")
212    };
213    format!("hooks: {hooks}\ncore.hooksPath: {configured}\n{reach}\n")
214}
215
216/// The start of the doctor's `git hooks` state when `core.hooksPath` is
217/// unset. That row is `info`: a seat that has not onboarded books no
218/// commits, and nothing else is wrong.
219pub const HOOKS_UNSET: &str = "core.hooksPath is unset";
220
221/// The one command that installs the hooks doctor checks.
222pub const HOOKS_FIX: &str = "ljos git-hooks install";
223
224/// The doctor's `git hooks` row. It passes when `ljos git-hook` runs from
225/// the directory `core.hooksPath` names: ljos's own stubs, or a block in
226/// each hook of a directory the user already set. The `pre-commit` and
227/// `pre-push` there must carry this build's block, so that a refusal
228/// fails the hook; the other hooks only book. It does not ask to take
229/// that path over. An env file that sets `LJOS_GIT_HOOKS` to another
230/// directory fails the row.
231#[must_use]
232pub fn doctor_row() -> crate::Habitat {
233    let dir = hooks_dir();
234    let (ok, state) = doctor_state(&dir, global_hooks_path(&[]).as_deref(), &config_ljos_dir());
235    crate::Habitat {
236        name: "git hooks",
237        state,
238        ok,
239    }
240}
241
242/// [`doctor_row`] for a chosen hooks directory, the global `core.hooksPath`,
243/// and the config directory that holds env files.
244#[must_use]
245pub fn doctor_state(dir: &Path, configured: Option<&str>, config_dir: &Path) -> (bool, String) {
246    let (mut ok, mut state) = hooks_state(dir, configured);
247    if let Some(drift) = env_hooks_drift(config_dir, dir) {
248        ok = false;
249        // A mismatch is a failed row. The unset-path prefix would keep it `info`.
250        state = if state.starts_with(HOOKS_UNSET) {
251            drift
252        } else {
253            format!("{state}; {drift}")
254        };
255    }
256    (ok, state)
257}
258
259/// An env file under `config_dir` that sets `LJOS_GIT_HOOKS` to a directory
260/// other than `onboard_dir`. The expression [`HOOKS_ENV_LINE`] writes is the
261/// same directory and is not a mismatch. `None` when every assignment agrees.
262#[must_use]
263pub fn env_hooks_drift(config_dir: &Path, onboard_dir: &Path) -> Option<String> {
264    let mut files = Vec::new();
265    for name in ["env.sh", "env"] {
266        let path = config_dir.join(name);
267        if path.is_file() {
268            files.push(path);
269        }
270    }
271    if let Ok(entries) = fs::read_dir(config_dir) {
272        let mut more: Vec<PathBuf> = entries
273            .flatten()
274            .map(|entry| entry.path())
275            .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("env"))
276            .collect();
277        more.sort();
278        files.extend(more);
279    }
280    let ours = onboard_dir.display().to_string();
281    for path in files {
282        let Ok(text) = fs::read_to_string(&path) else {
283            continue;
284        };
285        for line in text.lines() {
286            let Some(value) = hooks_assignment(line) else {
287                continue;
288            };
289            if assignment_agrees(&value, onboard_dir) {
290                continue;
291            }
292            return Some(format!(
293                "{} sets LJOS_GIT_HOOKS to {value}, not {ours}, the hooks `ljos onboard` installs",
294                path.display()
295            ));
296        }
297    }
298    None
299}
300
301fn hooks_assignment(line: &str) -> Option<String> {
302    let line = line.trim();
303    if line.is_empty() || line.starts_with('#') {
304        return None;
305    }
306    let rest = line.strip_prefix("export ").unwrap_or(line).trim();
307    let rest = rest.strip_prefix("LJOS_GIT_HOOKS=")?;
308    let value = unquote_assignment(rest.trim());
309    if value.is_empty() {
310        None
311    } else {
312        Some(value)
313    }
314}
315
316fn unquote_assignment(value: &str) -> String {
317    let value = value.trim();
318    if let Some(inner) = value
319        .strip_prefix('"')
320        .and_then(|text| text.strip_suffix('"'))
321    {
322        return inner.to_string();
323    }
324    if let Some(inner) = value
325        .strip_prefix('\'')
326        .and_then(|text| text.strip_suffix('\''))
327    {
328        return inner.to_string();
329    }
330    value.split_whitespace().next().unwrap_or("").to_string()
331}
332
333fn assignment_agrees(value: &str, onboard: &Path) -> bool {
334    if value.contains("${XDG_DATA_HOME:-$HOME/.local/share}/ljos/git-hooks") {
335        return true;
336    }
337    if value.contains('$') || value.contains('`') {
338        return false;
339    }
340    same_dir(Path::new(value), onboard)
341}
342
343fn config_ljos_dir() -> PathBuf {
344    let base = std::env::var_os("XDG_CONFIG_HOME")
345        .filter(|value| !value.is_empty())
346        .map(PathBuf::from)
347        .or_else(|| {
348            std::env::var_os("HOME")
349                .filter(|value| !value.is_empty())
350                .map(|home| PathBuf::from(home).join(".config"))
351        })
352        .unwrap_or_else(|| PathBuf::from(".config"));
353    base.join("ljos")
354}
355
356/// The `LJOS_GIT_HOOKS` line `ljos onboard` writes into a shell runner's
357/// env file. It names the same directory [`install`] writes.
358pub const HOOKS_ENV_LINE: &str = "\
359# Git hooks directory. `ljos git-hooks install` writes the stubs here.\n\
360export LJOS_GIT_HOOKS=\"${LJOS_GIT_HOOKS:-${XDG_DATA_HOME:-$HOME/.local/share}/ljos/git-hooks}\"";
361
362/// [`doctor_row`]'s verdict for the onboard hooks at `ours` and the global
363/// `core.hooksPath` git reports.
364#[must_use]
365pub fn hooks_state(ours: &Path, configured: Option<&str>) -> (bool, String) {
366    let Some(path) = nonempty(configured) else {
367        return (
368            false,
369            format!("{HOOKS_UNSET}, so commits are not booked; {HOOKS_FIX}"),
370        );
371    };
372    let dir = Path::new(path);
373    if hooks_reachable(dir, ours) {
374        let state = if same_dir(dir, ours) {
375            format!("core.hooksPath is {path}; commits are booked")
376        } else {
377            format!("core.hooksPath is {path}; ljos git-hook runs from those hooks")
378        };
379        return (true, state);
380    }
381    let stale = if hooks_present(dir, ours) {
382        stale_note(dir, ours)
383    } else {
384        None
385    };
386    let state = if let Some(note) = stale {
387        format!("core.hooksPath is {path}, but {note}; {HOOKS_FIX}")
388    } else if same_dir(dir, ours) {
389        format!("core.hooksPath is {path}, but some hook stubs are missing there; {HOOKS_FIX}")
390    } else {
391        format!("core.hooksPath is {path}, and ljos is not chained there; {HOOKS_FIX}")
392    };
393    (false, state)
394}
395
396fn hooks_dir() -> PathBuf {
397    if let Some(dir) = std::env::var_os("LJOS_GIT_HOOKS").filter(|value| !value.is_empty()) {
398        return PathBuf::from(dir);
399    }
400    data_home().join("ljos").join("git-hooks")
401}
402
403pub(crate) fn onboard_hooks_dir() -> PathBuf {
404    hooks_dir()
405}
406
407pub(crate) fn onboard_hook_paths(dir: &Path) -> Vec<PathBuf> {
408    HOOK_NAMES.iter().map(|name| dir.join(name)).collect()
409}
410
411pub(crate) fn configured_hooks_path(git_env: &[(&str, &str)]) -> Option<PathBuf> {
412    let configured = global_hooks_path(git_env);
413    nonempty(configured.as_deref()).map(PathBuf::from)
414}
415
416pub(crate) fn onboarding_installed() -> bool {
417    let dir = hooks_dir();
418    let configured = global_hooks_path(&[]);
419    match nonempty(configured.as_deref()) {
420        Some(path) if same_dir(Path::new(path), &dir) => owned_installed(&dir),
421        Some(path) => hooks_present(Path::new(path), &dir),
422        None => owned_installed(&dir),
423    }
424}
425
426fn data_home() -> PathBuf {
427    if let Some(dir) = std::env::var_os("XDG_DATA_HOME").filter(|value| !value.is_empty()) {
428        return PathBuf::from(dir);
429    }
430    std::env::var_os("HOME")
431        .filter(|value| !value.is_empty())
432        .map(|home| PathBuf::from(home).join(".local").join("share"))
433        .unwrap_or_else(|| PathBuf::from("."))
434}
435
436const BLOCK_BEGIN: &str = "# ljos:begin git-hook";
437const BLOCK_END: &str = "# ljos:end git-hook";
438
439fn nonempty(value: Option<&str>) -> Option<&str> {
440    value.map(str::trim).filter(|path| !path.is_empty())
441}
442
443fn ljos_executable() -> String {
444    std::env::current_exe()
445        .map(|path| path.display().to_string())
446        .unwrap_or_else(|_| "ljos".to_string())
447}
448
449/// The block appended to a hook. `post-commit` and `post-rewrite` book
450/// through `ljos git-hook`, and the `pre-commit` and `pre-push` blocks
451/// fail the hook when it refuses. The absolute path is the fallback when
452/// `ljos` is not on `PATH`; a `pre-commit` or `pre-push` with neither
453/// runs nothing. `post-rewrite` and `pre-push` copy stdin when the caller
454/// has not, so this block and a chained hook can both read the shas and
455/// refs.
456fn hook_block(name: &str) -> String {
457    hook_block_for(name, &shell_quote(&ljos_executable()))
458}
459
460/// [`hook_block`] with `bin`, already quoted, as the fallback binary.
461fn hook_block_for(name: &str, bin: &str) -> String {
462    let (otherwise, fail) = if gates_git(name) {
463        (format!("elif [ -x {bin} ]; then"), "exit 1")
464    } else {
465        ("else".to_string(), "true")
466    };
467    if matches!(name, "post-rewrite" | "pre-push") {
468        return format!(
469            "{BLOCK_BEGIN}\n\
470             if [ -z \"${{_ljos_in:-}}\" ]; then\n\
471             \t_ljos_in=$(mktemp 2>/dev/null || true)\n\
472             \tif [ -n \"$_ljos_in\" ]; then\n\
473             \t\tcat > \"$_ljos_in\" || true\n\
474             \tfi\n\
475             fi\n\
476             if command -v ljos >/dev/null 2>&1; then\n\
477             \tif [ -n \"${{_ljos_in:-}}\" ]; then\n\
478             \t\tljos git-hook {name} \"$@\" < \"$_ljos_in\" >&2 || {fail}\n\
479             \telse\n\
480             \t\tljos git-hook {name} \"$@\" >&2 || {fail}\n\
481             \tfi\n\
482             {otherwise}\n\
483             \tif [ -n \"${{_ljos_in:-}}\" ]; then\n\
484             \t\t{bin} git-hook {name} \"$@\" < \"$_ljos_in\" >&2 || {fail}\n\
485             \telse\n\
486             \t\t{bin} git-hook {name} \"$@\" >&2 || {fail}\n\
487             \tfi\n\
488             fi\n\
489             {BLOCK_END}\n"
490        );
491    }
492    format!(
493        "{BLOCK_BEGIN}\n\
494         if command -v ljos >/dev/null 2>&1; then\n\
495         \tljos git-hook {name} \"$@\" >&2 || {fail}\n\
496         {otherwise}\n\
497         \t{bin} git-hook {name} \"$@\" >&2 || {fail}\n\
498         fi\n\
499         {BLOCK_END}\n"
500    )
501}
502
503fn has_block(text: &str, name: &str) -> bool {
504    text.contains(&hook_block(name))
505}
506
507/// Whether `text` holds the block this build writes for `name`, whatever
508/// binary it falls back to. Another `ljos` on the box wrote a different
509/// path into the same block. A block from an older build, such as one
510/// whose gated call ends in `|| true`, does not count.
511fn carries_block(text: &str, name: &str) -> bool {
512    // A path cannot hold NUL, so it marks where the fallback goes.
513    let template = hook_block_for(name, "\0");
514    let mut parts = template.split('\0');
515    let (Some(head), Some(next)) = (parts.next(), parts.next()) else {
516        return text.contains(&template);
517    };
518    text.match_indices(head).any(|(at, _)| {
519        let rest = &text[at + head.len()..];
520        let line = rest.find('\n').unwrap_or(rest.len());
521        rest.match_indices(next)
522            .take_while(|(end, _)| *end <= line)
523            .any(|(end, _)| rest.starts_with(&template.replace('\0', &rest[..end])[head.len()..]))
524    })
525}
526
527fn strip_block(text: &str) -> String {
528    let Some(start) = text.find(BLOCK_BEGIN) else {
529        return text.to_string();
530    };
531    let Some(rel) = text[start..].find(BLOCK_END) else {
532        return text.to_string();
533    };
534    let mut end = start + rel + BLOCK_END.len();
535    if text[end..].starts_with('\n') {
536        end += 1;
537    }
538    let mut out = String::new();
539    out.push_str(&text[..start]);
540    out.push_str(&text[end..]);
541    out
542}
543
544fn strip_all(text: &str) -> String {
545    let mut out = text.to_string();
546    loop {
547        let next = strip_block(&out);
548        if next == out {
549            return out;
550        }
551        out = next;
552    }
553}
554
555fn merge_block(text: &str, name: &str) -> String {
556    if has_block(text, name) {
557        return text.to_string();
558    }
559    let stripped = strip_all(text);
560    let block = hook_block(name);
561    if stripped.trim().is_empty() {
562        return format!("#!/bin/sh\n{block}");
563    }
564    if stripped.ends_with('\n') {
565        format!("{stripped}{block}")
566    } else {
567        format!("{stripped}\n{block}")
568    }
569}
570
571fn block_only(text: &str) -> bool {
572    matches!(text.trim(), "" | "#!/bin/sh")
573}
574
575fn hook_calls_ljos(text: &str, name: &str) -> bool {
576    text.contains(&format!("ljos git-hook {name} "))
577}
578
579fn is_executable(path: &Path) -> bool {
580    #[cfg(unix)]
581    {
582        use std::os::unix::fs::PermissionsExt;
583        fs::metadata(path)
584            .map(|meta| meta.permissions().mode() & 0o111 != 0)
585            .unwrap_or(false)
586    }
587    #[cfg(not(unix))]
588    {
589        path.is_file()
590    }
591}
592
593fn ensure_executable(path: &Path) -> Result<()> {
594    #[cfg(unix)]
595    {
596        use std::os::unix::fs::PermissionsExt;
597        let meta = fs::metadata(path).with_context(|| format!("git-hooks: {}", path.display()))?;
598        let mode = meta.permissions().mode();
599        if mode & 0o111 == 0 {
600            fs::set_permissions(path, fs::Permissions::from_mode(mode | 0o111))?;
601        }
602    }
603    Ok(())
604}
605
606fn owned_installed(dir: &Path) -> bool {
607    HOOK_NAMES.iter().all(|name| {
608        let path = dir.join(name);
609        let Ok(text) = fs::read_to_string(&path) else {
610            return false;
611        };
612        is_executable(&path) && (text.contains("#!/bin/sh") || hook_calls_ljos(&text, name))
613    })
614}
615
616fn user_chained(dir: &Path) -> bool {
617    HOOK_NAMES.iter().all(|name| {
618        let path = dir.join(name);
619        let Ok(text) = fs::read_to_string(&path) else {
620            return false;
621        };
622        is_executable(&path) && hook_calls_ljos(&text, name)
623    })
624}
625
626fn hooks_present(configured: &Path, ours: &Path) -> bool {
627    if same_dir(configured, ours) {
628        owned_installed(configured)
629    } else {
630        user_chained(configured)
631    }
632}
633
634/// The first `pre-commit` or `pre-push` in `dir` without this build's
635/// block. Git ignores the gate's refusal when that hook drops its exit
636/// status.
637fn stale_gate(dir: &Path) -> Option<&'static str> {
638    HOOK_NAMES
639        .iter()
640        .copied()
641        .filter(|name| gates_git(name))
642        .find(|name| {
643            !fs::read_to_string(dir.join(name)).is_ok_and(|text| carries_block(&text, name))
644        })
645}
646
647/// Why the gated hooks in `configured` let a refusal through, or `None`.
648fn stale_note(configured: &Path, ours: &Path) -> Option<String> {
649    let name = stale_gate(configured)?;
650    let verb = if name == "pre-push" { "push" } else { "commit" };
651    let what = if same_dir(configured, ours) {
652        "stub"
653    } else {
654        "hook's ljos block"
655    };
656    Some(format!(
657        "the {name} {what} predates the current gate and lets a refused {verb} through"
658    ))
659}
660
661fn hooks_reachable(configured: &Path, ours: &Path) -> bool {
662    hooks_present(configured, ours) && stale_gate(configured).is_none()
663}
664
665fn write_owned_hooks(dir: &Path) -> Result<()> {
666    fs::create_dir_all(dir).with_context(|| format!("git-hooks: {}", dir.display()))?;
667    for name in HOOK_NAMES {
668        let path = dir.join(name);
669        fs::write(&path, hook_body(name))
670            .with_context(|| format!("git-hooks: {}", path.display()))?;
671        #[cfg(unix)]
672        {
673            use std::os::unix::fs::PermissionsExt;
674            fs::set_permissions(&path, fs::Permissions::from_mode(0o755))?;
675        }
676    }
677    Ok(())
678}
679
680fn chain_user_hooks(dir: &Path) -> Result<()> {
681    fs::create_dir_all(dir).with_context(|| format!("git-hooks: {}", dir.display()))?;
682    for name in HOOK_NAMES {
683        let path = dir.join(name);
684        let existing = if path.is_file() {
685            Some(fs::read(&path).with_context(|| format!("git-hooks: {}", path.display()))?)
686        } else {
687            None
688        };
689        if let Some(bytes) = &existing {
690            if bytes.contains(&0) || std::str::from_utf8(bytes).is_err() {
691                eprintln!("ljos: {} is not a shell script; left it", path.display());
692                continue;
693            }
694        }
695        let text = existing
696            .as_deref()
697            .map(|bytes| std::str::from_utf8(bytes).unwrap_or(""))
698            .unwrap_or("");
699        let next = merge_block(text, name);
700        if existing.is_none() || next != text {
701            fs::write(&path, next).with_context(|| format!("git-hooks: {}", path.display()))?;
702        }
703        ensure_executable(&path)?;
704    }
705    Ok(())
706}
707
708fn strip_user_hooks(dir: &Path) -> Result<()> {
709    if !dir.is_dir() {
710        return Ok(());
711    }
712    for name in HOOK_NAMES {
713        let path = dir.join(name);
714        let Ok(bytes) = fs::read(&path) else {
715            continue;
716        };
717        let Ok(text) = std::str::from_utf8(&bytes) else {
718            continue;
719        };
720        if !text.contains(BLOCK_BEGIN) {
721            continue;
722        }
723        let stripped = strip_all(text);
724        if block_only(&stripped) {
725            fs::remove_file(&path).with_context(|| format!("git-hooks: {}", path.display()))?;
726        } else if stripped != text {
727            fs::write(&path, stripped).with_context(|| format!("git-hooks: {}", path.display()))?;
728        }
729    }
730    Ok(())
731}
732
733fn remove_owned_hooks(dir: &Path) {
734    for name in HOOK_NAMES {
735        let _ = fs::remove_file(dir.join(name));
736    }
737    let _ = fs::remove_file(dir.join("previous-hooks-path"));
738}
739
740fn hook_body(name: &str) -> String {
741    let block = hook_block(name);
742    format!(
743        "#!/bin/sh\n\
744         # ljos books the commit, then chains to this repository's\n\
745         # .git/hooks/{name}, or to the core.hooksPath recorded in\n\
746         # previous-hooks-path. Booking cannot fail the hook; a refusal\n\
747         # from ljos in pre-commit or pre-push does. The chained hook's\n\
748         # exit status is kept. post-rewrite and pre-push keep a copy of\n\
749         # stdin for that hook.\n\
750         #\n\
751         # pre-commit install follows core.hooksPath and would replace this\n\
752         # file. Install the framework into the repository, then re-run\n\
753         # `ljos git-hooks install` if a stub was overwritten:\n\
754         #   dir=$(git rev-parse --git-dir)\n\
755         #   git config --local core.hooksPath \"$dir/hooks\"\n\
756         #   pre-commit install\n\
757         #   git config --local --unset core.hooksPath\n\
758         {block}\
759         git_dir=$(git rev-parse --git-dir 2>/dev/null || true)\n\
760         if [ -n \"$git_dir\" ]; then\n\
761         \tcase \"$git_dir\" in\n\
762         \t\t/*) ;;\n\
763         \t\t*) git_dir=$(pwd)/$git_dir ;;\n\
764         \tesac\n\
765         \trepo_hook=\"$git_dir/hooks/{name}\"\n\
766         \tif [ -x \"$repo_hook\" ] && [ \"$repo_hook\" != \"$0\" ]; then\n\
767         \t\tif [ -n \"${{_ljos_in:-}}\" ]; then\n\
768         \t\t\texec \"$repo_hook\" \"$@\" < \"$_ljos_in\"\n\
769         \t\tfi\n\
770         \t\texec \"$repo_hook\" \"$@\"\n\
771         \tfi\n\
772         fi\n\
773         here=$(dirname \"$0\")\n\
774         here=$(CDPATH= cd -- \"$here\" && pwd) || exit 0\n\
775         prev=$(sed -n '1s/[[:space:]]*$//p' \"$here/previous-hooks-path\" 2>/dev/null || true)\n\
776         if [ -n \"$prev\" ] && [ \"$prev\" != \"$here\" ]; then\n\
777         \tprev_hook=\"$prev/{name}\"\n\
778         \tif [ -x \"$prev_hook\" ] && [ \"$prev_hook\" != \"$0\" ]; then\n\
779         \t\tif [ -n \"${{_ljos_in:-}}\" ]; then\n\
780         \t\t\texec \"$prev_hook\" \"$@\" < \"$_ljos_in\"\n\
781         \t\tfi\n\
782         \t\texec \"$prev_hook\" \"$@\"\n\
783         \tfi\n\
784         fi\n\
785         exit 0\n"
786    )
787}
788
789fn shell_quote(text: &str) -> String {
790    format!("'{}'", text.replace('\'', "'\\''"))
791}
792
793/// Book the commit that just landed. Always succeeds: the commit stands.
794///
795/// # Errors
796///
797/// None. A habitat that did not answer is a line in the book log.
798pub fn run_git_commit(hook: &str) -> Result<()> {
799    if let Err(err) = book_commit(hook) {
800        crate::bookkeep::log_line(&format!("git-hooks: {err:#}"));
801    }
802    Ok(())
803}
804
805/// Run the ljos part of git hook `name`.
806///
807/// `post-commit` and `post-rewrite` book the commit. `pre-commit` and
808/// `pre-push` run the sitting gate ([`gate`]). `pre-push` also refuses
809/// a pushed commit whose message matches [`line_refused`]. Any other
810/// name succeeds and does nothing. Arguments git passed the hook are
811/// ignored.
812///
813/// # Errors
814///
815/// The sitting gate's refusal. Booking that did not land is a line in
816/// the book log.
817pub fn run_named(name: &str) -> Result<()> {
818    let name = name.trim();
819    if books_commit(name) {
820        return run_git_commit(name);
821    }
822    if name == "pre-push" {
823        let refs = std::io::read_to_string(std::io::stdin())
824            .map_err(|err| anyhow!("pre-push: cannot read the refs ({err})"))?;
825        refuse_push_messages(&refs)?;
826        return gate(name, &refs).map_err(|err| dropped(name, err));
827    }
828    if gates_git(name) {
829        return gate(name, "").map_err(|err| dropped(name, err));
830    }
831    Ok(())
832}
833
834fn dropped(name: &str, err: anyhow::Error) -> anyhow::Error {
835    match dropped_refusal(name) {
836        Some(why) => anyhow!("{err:#}\n{why}"),
837        None => err,
838    }
839}
840
841/// Refuse when a commit the push would send cannot be read, or its
842/// message has a line [`line_refused`] names. A delete sends nothing.
843/// A line that is not a ref update is refused.
844fn refuse_push_messages(refs: &str) -> Result<()> {
845    for line in refs.lines() {
846        let line = line.trim();
847        if line.is_empty() {
848            continue;
849        }
850        let fields: Vec<&str> = line.split_whitespace().collect();
851        if fields.len() != 4 {
852            bail!("pre-push: cannot read `{line}`");
853        }
854        let local_sha = fields[1];
855        let remote_sha = fields[3];
856        if !is_object_name(local_sha) || !is_object_name(remote_sha) {
857            bail!("pre-push: cannot read `{line}`");
858        }
859        if is_zero_name(local_sha) {
860            continue;
861        }
862        let listed = if is_zero_name(remote_sha) {
863            listed_commits(&[local_sha, "--not", "--remotes"])?
864        } else {
865            let range = format!("{remote_sha}..{local_sha}");
866            listed_commits(&[&range])?
867        };
868        for sha in listed {
869            let body = commit_body(&sha)?;
870            if message_refused(&body) {
871                bail!("pre-push: {sha} message is refused");
872            }
873        }
874    }
875    Ok(())
876}
877
878fn is_object_name(text: &str) -> bool {
879    matches!(text.len(), 40 | 64) && text.bytes().all(|b| b.is_ascii_hexdigit())
880}
881
882fn is_zero_name(text: &str) -> bool {
883    is_object_name(text) && text.bytes().all(|b| b == b'0')
884}
885
886fn listed_commits(args: &[&str]) -> Result<Vec<String>> {
887    let mut git_args = vec!["rev-list"];
888    git_args.extend_from_slice(args);
889    let shown = args.join(" ");
890    let out = git_command(&git_args, &[])
891        .stdin(std::process::Stdio::null())
892        .output()
893        .with_context(|| format!("pre-push: cannot read commits in {shown}"))?;
894    if !out.status.success() {
895        let err = String::from_utf8_lossy(&out.stderr);
896        bail!("pre-push: cannot read commits in {shown} ({})", err.trim());
897    }
898    Ok(String::from_utf8_lossy(&out.stdout)
899        .lines()
900        .filter(|line| !line.is_empty())
901        .map(str::to_string)
902        .collect())
903}
904
905fn commit_body(sha: &str) -> Result<String> {
906    let out = git_command(&["log", "-1", "--format=%B", sha], &[])
907        .stdin(std::process::Stdio::null())
908        .output()
909        .with_context(|| format!("pre-push: cannot read {sha}"))?;
910    if !out.status.success() {
911        bail!("pre-push: cannot read {sha}");
912    }
913    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
914}
915
916fn message_refused(body: &str) -> bool {
917    phrase_refused(&body.to_ascii_lowercase()) || body.lines().any(line_refused)
918}
919
920/// A by-trailer, a made-with line, a generated line at the start of
921/// the line, or a machine account mark anywhere on the line. A Tests
922/// or note paragraph is none of those. A generated phrase
923/// mid-sentence is not a generated line.
924fn line_refused(line: &str) -> bool {
925    let lower = line.to_ascii_lowercase();
926    account_anywhere(&lower) || phrase_refused(&lower) || anchored_mark(&lower)
927}
928
929/// `cursor agent` and `cursoragent` match anywhere on the line.
930fn account_anywhere(lower: &str) -> bool {
931    lower.contains("cursor agent") || lower.contains("cursoragent")
932}
933
934/// `generated with` and `made with cursor` match only at the start of
935/// the line, after optional blanks.
936fn phrase_refused(lower: &str) -> bool {
937    let rest = lower.trim_start_matches([' ', '\t']);
938    rest.starts_with("generated with") || rest.starts_with("made with cursor")
939}
940
941fn anchored_mark(lower: &str) -> bool {
942    let rest = lower.trim_start_matches([' ', '\t']);
943    made_with_mark(rest) || by_mark(rest) || cursor_assign(rest)
944}
945
946fn made_with_mark(rest: &str) -> bool {
947    let Some(after) = rest.strip_prefix("made-with") else {
948        return false;
949    };
950    after.trim_start_matches([' ', '\t']).starts_with(':')
951}
952
953fn by_mark(rest: &str) -> bool {
954    let Some(colon) = rest.find(':') else {
955        return false;
956    };
957    let token = rest[..colon].trim_end_matches([' ', '\t']);
958    let Some(name) = token.strip_suffix("-by") else {
959        return false;
960    };
961    !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
962}
963
964fn cursor_assign(rest: &str) -> bool {
965    let Some(after_cursor) = rest.strip_prefix("cursor") else {
966        return false;
967    };
968    let after_sep = after_cursor
969        .strip_prefix('_')
970        .or_else(|| after_cursor.strip_prefix('-'))
971        .unwrap_or(after_cursor);
972    let Some(after_agent) = after_sep.strip_prefix("agent") else {
973        return false;
974    };
975    let mut end = 0;
976    for c in after_agent.chars() {
977        if c.is_ascii_alphanumeric() || c == '_' {
978            end += c.len_utf8();
979        } else {
980            break;
981        }
982    }
983    let after = after_agent[end..].trim_start_matches([' ', '\t']);
984    after.starts_with('=') || after.starts_with(':')
985}
986
987/// Why git goes on after the gate refuses, when the hook file it is
988/// running carries an ljos block older than this build's. Such a block
989/// can end in `|| true`, and this process cannot change the exit status
990/// the hook returns. A hook that calls `ljos git-hook` with no block is
991/// the user's own and is not judged.
992fn dropped_refusal(name: &str) -> Option<String> {
993    let raw = git_line(&["rev-parse", "--git-path", &format!("hooks/{name}")])?;
994    let path = std::env::current_dir().ok()?.join(raw);
995    let text = fs::read_to_string(&path).ok()?;
996    if !text.contains(BLOCK_BEGIN) || carries_block(&text, name) {
997        return None;
998    }
999    let verb = if name == "pre-push" { "push" } else { "commit" };
1000    Some(format!(
1001        "sitting-gate: {} predates this gate and drops its refusal, so git will {verb} anyway; {HOOKS_FIX} replaces it",
1002        path.display()
1003    ))
1004}
1005
1006/// The guard's sitting gate for a commit or push it did not see, such as
1007/// one a script runs: under a runner, `pre-commit` needs a live sitting,
1008/// and `pre-push` also needs that ticket to clear each ref it sends onto
1009/// a branch [`crate::gates::consensus_push`] names. A store or a tracker
1010/// checkout, which ljos writes itself, is not gated, and nor is the
1011/// person. When a runner variable is the only cause, and the call would
1012/// be refused, the person is asked for their passphrase on the
1013/// controlling terminal; a right answer lets this one call through.
1014fn gate(name: &str, refs: &str) -> Result<()> {
1015    let Some(cause) = crate::runner_cause() else {
1016        return Ok(());
1017    };
1018    let refused = match gate_runner(name, refs) {
1019        Ok(()) => return Ok(()),
1020        Err(refused) => refused,
1021    };
1022    if cause == crate::RunnerCause::Hard {
1023        return Err(refused);
1024    }
1025    let verb = if name == "pre-push" { "push" } else { "commit" };
1026    let marks = crate::runner_marks();
1027    match crate::person_key::ask_person(&marks, &format!("git {verb}")) {
1028        Ok(()) => Ok(()),
1029        Err(why) => {
1030            let detail = format!("{refused:#}");
1031            let detail = detail.strip_prefix("sitting-gate: ").unwrap_or(&detail);
1032            let text = crate::sitting_gate::for_marks(
1033                detail,
1034                &marks,
1035                verb,
1036                crate::person_key::is_set(),
1037                &why,
1038            );
1039            Err(anyhow!("sitting-gate: {text}"))
1040        }
1041    }
1042}
1043
1044fn gate_runner(name: &str, refs: &str) -> Result<()> {
1045    let repo = git_line(&["rev-parse", "--show-toplevel"])
1046        .map(PathBuf::from)
1047        .or_else(git_dir);
1048    if repo
1049        .as_deref()
1050        .is_some_and(|repo| is_store(repo) || holds_tracker(repo))
1051    {
1052        return Ok(());
1053    }
1054    // A commit is not this check. The push below is.
1055    if name != "pre-push" {
1056        return Ok(());
1057    }
1058    // In a hook the process tree names the hook's own shell. The seat a
1059    // booking would take is the one the sitting was taken under. With a
1060    // conversation id in the environment only that conversation's holder
1061    // counts, or for a subagent its parent's records and process when
1062    // that process carries a conversation id. With no id it falls back
1063    // to the process match.
1064    let seat = crate::git_hook_seat();
1065    let _actor = seat.as_deref().map(crate::HookActor::enter);
1066    let _push = crate::PushCheck::enter();
1067    let issue = match crate::sitting_gate::live_sitting() {
1068        Ok(issue) => issue,
1069        Err(_) => {
1070            let named = crate::sitting_gate::open_or_name_sitting().unwrap_or_default();
1071            if crate::push_slow() {
1072                if named.is_empty() {
1073                    eprintln!("{}", crate::push_slow_line());
1074                } else {
1075                    eprintln!("{}; sitting {named}", crate::push_slow_line());
1076                }
1077            }
1078            named
1079        }
1080    };
1081    let cfg = match crate::gates::consensus_push(repo.as_deref()) {
1082        Ok(cfg) => cfg,
1083        Err(why) => {
1084            return Err(anyhow!(
1085                "sitting-gate: {}",
1086                crate::sitting_gate::unread_settings(&why)
1087            ))
1088        }
1089    };
1090    let dest = protected_ref(refs, &cfg.branches);
1091    let Some(dest) = dest else {
1092        return Ok(());
1093    };
1094    // The tracker read already missed its bound. Stop before the
1095    // consensus checks. Empty notes would fail as a missing family.
1096    if crate::push_tracker_slow() {
1097        return Err(anyhow!("sitting-gate: {}", crate::push_tracker_slow_line()));
1098    }
1099    if issue.is_empty() || !crate::protected_push_cleared(&issue, &crate::seat_name(), cfg.quorum) {
1100        let why = "the sitting has no settled consensus".to_string();
1101        let wait = crate::sitting_gate::seats_wait(&dest, &cfg.branches, &issue, &why);
1102        return Err(anyhow!("sitting-gate: {wait}"));
1103    }
1104    Ok(())
1105}
1106
1107/// What a push whose pre-push stdin is `refs` sends onto a branch in
1108/// `branches`, as `sends BRANCH`, or `None` when no ref lands on one.
1109/// Git runs the hook with no lines when nothing is to be sent. A line
1110/// not in git's four-field form cannot be read, so it is taken to land
1111/// on one.
1112fn protected_ref(refs: &str, branches: &[String]) -> Option<String> {
1113    for line in refs.lines().filter(|l| !l.trim().is_empty()) {
1114        let fields: Vec<&str> = line.split_whitespace().collect();
1115        let [_, _, remote, _] = fields[..] else {
1116            return Some(format!("lists `{line}`, which is not a ref git would send"));
1117        };
1118        let Some(branch) = remote.strip_prefix("refs/heads/") else {
1119            continue;
1120        };
1121        if let Some(b) = branches.iter().find(|b| b.eq_ignore_ascii_case(branch)) {
1122            return Some(format!("sends `{b}`"));
1123        }
1124    }
1125    None
1126}
1127
1128/// Whether `repo` is a tracker checkout: it holds `vissue.toml`, or a
1129/// `Software/<project>/issues.org` as `vissue` reads a tracker root. A
1130/// bare `Software/` directory is any repository's.
1131fn holds_tracker(repo: &Path) -> bool {
1132    if repo.join("vissue.toml").is_file() {
1133        return true;
1134    }
1135    std::fs::read_dir(repo.join("Software")).is_ok_and(|entries| {
1136        entries
1137            .flatten()
1138            .any(|entry| entry.path().join("issues.org").is_file())
1139    })
1140}
1141
1142fn book_commit(hook: &str) -> Result<()> {
1143    if std::env::var_os("LJOS_GIT_HOOK").is_some() || booking_off() {
1144        return Ok(());
1145    }
1146    if foreign_session() {
1147        return Ok(());
1148    }
1149    if hook != "post-rewrite" && mid_rewrite() {
1150        return Ok(());
1151    }
1152    let Some(repo) = git_line(&["rev-parse", "--show-toplevel"]) else {
1153        return Ok(());
1154    };
1155    let repo_path = PathBuf::from(&repo);
1156    // A commit in the tracker's checkout is a tracker write: never booked,
1157    // but its seat is checked as any other write's is.
1158    let tracker = tracker_repo(&repo_path);
1159    if !tracker && (crate::bookkeep::path_is_temp(Some(&repo_path)) || skip_repo(&repo_path)) {
1160        return Ok(());
1161    }
1162    let Some(head) = git_line(&["rev-parse", "HEAD"]) else {
1163        return Ok(());
1164    };
1165    // The process tree is not a seat. Without LJOS_SEAT, or an agy or
1166    // opencode conversation, the commit stays unbooked; a subagent is told.
1167    let Some(seat) = crate::git_hook_seat() else {
1168        if tracker {
1169            refuse_tracker_commit(
1170                &head,
1171                "no seat is named; export LJOS_SEAT=<your seat> to write the tracker",
1172            );
1173        } else if crate::unseated_subagent() {
1174            // Stdout: the installed hook shows that line and drops stderr.
1175            println!(
1176                "ljos: commit {} not booked: this subagent has no seat; export LJOS_SEAT=<your seat> (the parent's) to book it",
1177                &head[..head.len().min(12)]
1178            );
1179        }
1180        return Ok(());
1181    };
1182    let _actor = crate::HookActor::enter(&seat);
1183    // Every path below writes the tracker: a repointed citation, a named
1184    // issue, an open sitting, a new claim.
1185    if let Err(e) = crate::write_seat("commit") {
1186        if tracker {
1187            refuse_tracker_commit(&head, &format!("{e:#}"));
1188        } else {
1189            println!(
1190                "ljos: commit {} not booked: {e:#}",
1191                &head[..head.len().min(12)]
1192            );
1193        }
1194        return Ok(());
1195    }
1196    if tracker {
1197        return Ok(());
1198    }
1199    let _children = HookChildren::enter();
1200    // An amend or a rebase lists old and new shas. Move the citation
1201    // before the "already booked" return: post-commit may have cited the
1202    // new HEAD already, and the old sha would otherwise stay on the issue.
1203    if already_booked(&repo, &head) {
1204        return Ok(());
1205    }
1206    let subject = git_line(&["log", "-1", "--format=%s"]).unwrap_or_default();
1207    println!(
1208        "{}",
1209        crate::bookkeep::note_after_commit(&repo, &head, &subject)
1210    );
1211    remember_booked(&repo, &head);
1212    Ok(())
1213}
1214
1215fn booking_off() -> bool {
1216    matches!(
1217        std::env::var("LJOS_OFF").ok().as_deref(),
1218        Some("1" | "true" | "TRUE" | "yes" | "YES" | "on" | "ON")
1219    ) || crate::bookkeep::guard_suspended()
1220}
1221
1222fn foreign_session() -> bool {
1223    // OpenCode's shell sets OPENCODE_SESSION_ID and never calls the plugin's
1224    // tool.execute.after, so the git hook is the booker. Claude and Codex
1225    // book from their own hooks.
1226    ["CLAUDECODE", "CODEX_THREAD_ID", "CODEX_SESSION_ID"]
1227        .iter()
1228        .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty()))
1229}
1230
1231fn mid_rewrite() -> bool {
1232    let Some(dir) = git_dir() else {
1233        return false;
1234    };
1235    dir.join("rebase-merge").is_dir()
1236        || dir.join("rebase-apply").is_dir()
1237        || dir.join("MERGE_HEAD").is_file()
1238}
1239
1240/// Whether `repo` is the tracker's checkout, `VISSUE_ROOT` or `ISSUE_ROOT`.
1241fn tracker_repo(repo: &Path) -> bool {
1242    ["VISSUE_ROOT", "ISSUE_ROOT"].iter().any(|key| {
1243        std::env::var_os(key)
1244            .filter(|value| !value.is_empty())
1245            .map(PathBuf::from)
1246            .is_some_and(|root| useful_root(&root) && covered(repo, &root))
1247    })
1248}
1249
1250/// A tracker commit no seat that may write the tracker made. It has landed
1251/// and a post-commit hook cannot take it back, so the refusal is said on
1252/// stdout, which the installed hook shows, and kept in the book log.
1253fn refuse_tracker_commit(head: &str, why: &str) {
1254    let line = format!(
1255        "ljos: tracker commit {} was not made by a seat that may write the tracker: {why}",
1256        &head[..head.len().min(12)]
1257    );
1258    println!("{line}");
1259    crate::bookkeep::log_line(&format!("git-hooks: {line}"));
1260}
1261
1262fn skip_repo(repo: &Path) -> bool {
1263    if is_store(repo) {
1264        return true;
1265    }
1266    skip_roots().iter().any(|root| covered(repo, root))
1267}
1268
1269/// Paths a commit under which is not booked. The defaults always apply.
1270/// `[git_hooks] skip` in `ljos.toml` adds box-specific paths, and a
1271/// reinstall rewrites the hook scripts without touching that file.
1272fn skip_roots() -> Vec<PathBuf> {
1273    let mut roots = vec![
1274        PathBuf::from("/tmp"),
1275        PathBuf::from("/var/tmp"),
1276        PathBuf::from("/dev/shm"),
1277    ];
1278    for key in ["VISSUE_ROOT", "ISSUE_ROOT", "CLAIMDAG_DIR"] {
1279        if let Some(path) = std::env::var_os(key).filter(|value| !value.is_empty()) {
1280            roots.push(PathBuf::from(path));
1281        }
1282    }
1283    roots.extend(store_dirs());
1284    for path in config_files() {
1285        roots.extend(configured_skips(&path));
1286    }
1287    roots.retain(|path| useful_root(path));
1288    roots
1289}
1290
1291fn useful_root(path: &Path) -> bool {
1292    let text = path.to_string_lossy();
1293    let text = text.trim();
1294    !text.is_empty() && text != "/" && text != "."
1295}
1296
1297fn config_files() -> Vec<PathBuf> {
1298    let mut out = Vec::new();
1299    let base = std::env::var_os("XDG_CONFIG_HOME")
1300        .filter(|value| !value.is_empty())
1301        .map(PathBuf::from)
1302        .or_else(|| {
1303            std::env::var_os("HOME")
1304                .filter(|value| !value.is_empty())
1305                .map(|home| PathBuf::from(home).join(".config"))
1306        });
1307    if let Some(base) = base {
1308        out.push(base.join("ljos").join("ljos.toml"));
1309        if let Some(seat) = std::env::var("LJOS_SEAT")
1310            .ok()
1311            .map(|name| name.trim().to_string())
1312            .filter(|name| !name.is_empty() && !name.contains('/') && !name.contains(".."))
1313        {
1314            out.push(base.join("ljos").join("seats").join(seat).join("ljos.toml"));
1315        }
1316    }
1317    if let Some(path) = std::env::var_os("LJOS_CONFIG").filter(|value| !value.is_empty()) {
1318        out.push(PathBuf::from(path));
1319    }
1320    if let Ok(cwd) = std::env::current_dir() {
1321        out.push(cwd.join("ljos.toml"));
1322    }
1323    out
1324}
1325
1326fn configured_skips(path: &Path) -> Vec<PathBuf> {
1327    let Ok(text) = fs::read_to_string(path) else {
1328        return Vec::new();
1329    };
1330    let Ok(value) = toml::from_str::<toml::Value>(&text) else {
1331        return Vec::new();
1332    };
1333    let Some(list) = value
1334        .get("git_hooks")
1335        .and_then(|table| table.get("skip"))
1336        .and_then(toml::Value::as_array)
1337    else {
1338        return Vec::new();
1339    };
1340    list.iter()
1341        .filter_map(toml::Value::as_str)
1342        .map(str::trim)
1343        .filter(|text| !text.is_empty())
1344        .map(PathBuf::from)
1345        .collect()
1346}
1347
1348fn covered(repo: &Path, root: &Path) -> bool {
1349    let repo = canonical_or(repo);
1350    let root = canonical_or(root);
1351    repo == root || repo.starts_with(&root)
1352}
1353
1354fn canonical_or(path: &Path) -> PathBuf {
1355    fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
1356}
1357
1358/// Whether `repo` is a deed or claim store ljos writes itself, read from
1359/// the store settings; a path that merely contains `claimdag` is not one.
1360fn is_store(repo: &Path) -> bool {
1361    store_dirs()
1362        .iter()
1363        .any(|root| same_dir(repo, root) || repo_starts(repo, root))
1364}
1365
1366fn store_dirs() -> Vec<PathBuf> {
1367    let mut out = Vec::new();
1368    if let Ok(url) = std::env::var("DEEDAR_URL") {
1369        if let Some(path) = url.strip_prefix("file://") {
1370            out.push(PathBuf::from(path));
1371        }
1372    }
1373    if let Some(data) = std::env::var_os("XDG_DATA_HOME").filter(|value| !value.is_empty()) {
1374        out.push(PathBuf::from(data).join("deedar").join("store"));
1375    } else if let Some(home) = std::env::var_os("HOME").filter(|value| !value.is_empty()) {
1376        out.push(
1377            PathBuf::from(home)
1378                .join(".local")
1379                .join("share")
1380                .join("deedar")
1381                .join("store"),
1382        );
1383    }
1384    out
1385}
1386
1387fn same_dir(left: &Path, right: &Path) -> bool {
1388    let left = fs::canonicalize(left).unwrap_or_else(|_| left.to_path_buf());
1389    let right = fs::canonicalize(right).unwrap_or_else(|_| right.to_path_buf());
1390    left == right
1391}
1392
1393fn repo_starts(repo: &Path, root: &Path) -> bool {
1394    if !root.exists() {
1395        return false;
1396    }
1397    let repo = fs::canonicalize(repo).unwrap_or_else(|_| repo.to_path_buf());
1398    let root = fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
1399    repo.starts_with(root)
1400}
1401
1402fn already_booked(repo: &str, head: &str) -> bool {
1403    let key = format!("{repo}\t{head}");
1404    fs::read_to_string(booked_path())
1405        .map(|text| text.lines().any(|line| line == key))
1406        .unwrap_or(false)
1407}
1408
1409fn remember_booked(repo: &str, head: &str) {
1410    let path = booked_path();
1411    if let Some(dir) = path.parent() {
1412        let _ = fs::create_dir_all(dir);
1413    }
1414    let mut lines: Vec<String> = fs::read_to_string(&path)
1415        .unwrap_or_default()
1416        .lines()
1417        .map(str::to_string)
1418        .filter(|line| !line.starts_with(&format!("{repo}\t")))
1419        .collect();
1420    lines.push(format!("{repo}\t{head}"));
1421    if lines.len() > 200 {
1422        lines.drain(0..lines.len() - 200);
1423    }
1424    let _ = fs::write(path, lines.join("\n") + "\n");
1425}
1426
1427fn booked_path() -> PathBuf {
1428    crate::runtime_dir().join("git-hooks-booked")
1429}
1430
1431fn git_dir() -> Option<PathBuf> {
1432    let raw = git_line(&["rev-parse", "--git-dir"])?;
1433    let path = PathBuf::from(&raw);
1434    if path.is_absolute() {
1435        Some(path)
1436    } else {
1437        std::env::current_dir().ok().map(|cwd| cwd.join(path))
1438    }
1439}
1440
1441/// `GIT_*` values a hook exports. A later `git -C` follows `GIT_DIR` and
1442/// ignores `-C`, so a tracker commit would land in the checkout that just
1443/// finished.
1444const HOOK_GIT_ENV: &[&str] = &[
1445    "GIT_DIR",
1446    "GIT_WORK_TREE",
1447    "GIT_INDEX_FILE",
1448    "GIT_PREFIX",
1449    "GIT_OBJECT_DIRECTORY",
1450    "GIT_COMMON_DIR",
1451    "GIT_NAMESPACE",
1452];
1453
1454thread_local! {
1455    static HOOK_CHILDREN: Cell<bool> = const { Cell::new(false) };
1456}
1457
1458/// While this guard is alive, child processes started through
1459/// [`hook_child_env`] carry `LJOS_GIT_HOOK=1` and do not inherit the hook's
1460/// `GIT_DIR`. Dropping it restores the previous flag. The process
1461/// environment is not changed.
1462#[must_use]
1463struct HookChildren {
1464    previous: bool,
1465}
1466
1467impl HookChildren {
1468    fn enter() -> Self {
1469        let previous = HOOK_CHILDREN.with(Cell::get);
1470        HOOK_CHILDREN.with(|flag| flag.set(true));
1471        Self { previous }
1472    }
1473}
1474
1475impl Drop for HookChildren {
1476    fn drop(&mut self) {
1477        HOOK_CHILDREN.with(|flag| flag.set(self.previous));
1478    }
1479}
1480
1481/// Put the re-entry guard on a child `git` or `ljos`, and drop the hook's
1482/// git directory from that child. No effect unless a git hook is booking
1483/// a commit on this thread.
1484pub(crate) fn hook_child_env(cmd: &mut Command) {
1485    if !HOOK_CHILDREN.with(Cell::get) {
1486        return;
1487    }
1488    cmd.env("LJOS_GIT_HOOK", "1");
1489    for key in HOOK_GIT_ENV {
1490        cmd.env_remove(key);
1491    }
1492}
1493
1494#[cfg(test)]
1495pub(crate) fn with_hook_children_for_test<T>(run: impl FnOnce() -> T) -> T {
1496    let _guard = HookChildren::enter();
1497    run()
1498}
1499
1500fn git_command(args: &[&str], git_env: &[(&str, &str)]) -> Command {
1501    let mut cmd = crate::git_cmd();
1502    cmd.args(args);
1503    for (key, value) in git_env {
1504        cmd.env(key, value);
1505    }
1506    hook_child_env(&mut cmd);
1507    cmd
1508}
1509
1510fn git_line(args: &[&str]) -> Option<String> {
1511    let out = git_command(args, &[]).output().ok()?;
1512    if !out.status.success() {
1513        return None;
1514    }
1515    let text = String::from_utf8(out.stdout).ok()?;
1516    let text = text.trim();
1517    if text.is_empty() {
1518        None
1519    } else {
1520        Some(text.to_string())
1521    }
1522}
1523
1524fn global_hooks_path(git_env: &[(&str, &str)]) -> Option<String> {
1525    let out = git_command(&["config", "--global", "--get", "core.hooksPath"], git_env)
1526        .output()
1527        .ok()?;
1528    if !out.status.success() {
1529        return None;
1530    }
1531    let text = String::from_utf8(out.stdout).ok()?;
1532    let text = text.trim();
1533    if text.is_empty() {
1534        None
1535    } else {
1536        Some(text.to_string())
1537    }
1538}
1539
1540fn set_global_hooks_path(path: &Path, git_env: &[(&str, &str)]) -> Result<()> {
1541    let value = path.display().to_string();
1542    let status = git_command(&["config", "--global", "core.hooksPath", &value], git_env)
1543        .status()
1544        .context("git-hooks: git config")?;
1545    if !status.success() {
1546        bail!("git-hooks: could not set core.hooksPath");
1547    }
1548    Ok(())
1549}
1550
1551fn unset_global_hooks_path(git_env: &[(&str, &str)]) -> Result<()> {
1552    let status = git_command(
1553        &["config", "--global", "--unset", "core.hooksPath"],
1554        git_env,
1555    )
1556    .status()
1557    .context("git-hooks: git config")?;
1558    if !status.success() {
1559        bail!("git-hooks: could not unset core.hooksPath");
1560    }
1561    Ok(())
1562}
1563
1564#[cfg(test)]
1565mod tests {
1566    use std::ffi::OsStr;
1567
1568    use super::*;
1569
1570    fn mapped<'a>(cmd: &'a Command, key: &str) -> Option<Option<&'a OsStr>> {
1571        cmd.get_envs()
1572            .find(|(name, _)| *name == OsStr::new(key))
1573            .map(|(_, value)| value)
1574    }
1575
1576    #[test]
1577    fn the_doctor_names_a_hooks_path_that_is_not_the_onboard_one() {
1578        let dir = tempfile::tempdir().unwrap();
1579        let ours = dir.path().join("ljos").join("git-hooks");
1580        let other = dir.path().join("user-hooks");
1581        std::fs::create_dir_all(&other).unwrap();
1582        let prior = "#!/bin/sh\nprintf 'user-hook\\n'\n";
1583        std::fs::write(other.join("post-commit"), prior).unwrap();
1584        let ours_s = ours.display().to_string();
1585        let other_s = other.display().to_string();
1586
1587        let (ok, state) = super::hooks_state(&ours, None);
1588        assert!(!ok);
1589        assert!(state.starts_with(super::HOOKS_UNSET), "{state}");
1590        assert_eq!(state.matches(super::HOOKS_FIX).count(), 1, "{state}");
1591
1592        let (ok, state) = super::hooks_state(&ours, Some(&other_s));
1593        assert!(!ok, "{state}");
1594        assert!(state.contains(&other_s), "{state}");
1595        assert!(!state.contains(&ours_s), "{state}");
1596        assert_eq!(state.matches(super::HOOKS_FIX).count(), 1, "{state}");
1597
1598        super::chain_user_hooks(&other).unwrap();
1599        let (ok, state) = super::hooks_state(&ours, Some(&other_s));
1600        assert!(ok, "{state}");
1601        assert!(state.contains("ljos git-hook runs"), "{state}");
1602        let hooked = std::fs::read_to_string(other.join("post-commit")).unwrap();
1603        assert!(hooked.starts_with(prior), "{hooked}");
1604        assert_eq!(
1605            hooked.matches("# ljos:begin git-hook").count(),
1606            1,
1607            "{hooked}"
1608        );
1609        super::chain_user_hooks(&other).unwrap();
1610        assert_eq!(
1611            std::fs::read_to_string(other.join("post-commit")).unwrap(),
1612            hooked
1613        );
1614        assert!(other.join("pre-push").is_file());
1615
1616        super::strip_user_hooks(&other).unwrap();
1617        assert_eq!(
1618            std::fs::read_to_string(other.join("post-commit")).unwrap(),
1619            prior
1620        );
1621        assert!(!other.join("pre-push").exists());
1622
1623        let config = dir.path().join("config");
1624        std::fs::create_dir_all(&config).unwrap();
1625        std::fs::write(
1626            config.join("env.sh"),
1627            format!("export LJOS_GIT_HOOKS={}\n", other.display()),
1628        )
1629        .unwrap();
1630        let drift = super::env_hooks_drift(&config, &ours).expect("a drifted env file");
1631        assert!(drift.contains(&other_s), "{drift}");
1632        assert!(drift.contains(&ours_s), "{drift}");
1633        let (ok, state) = super::doctor_state(&ours, None, &config);
1634        assert!(!ok, "{state}");
1635        assert!(
1636            !state.starts_with(super::HOOKS_UNSET),
1637            "a mismatch stayed info: {state}"
1638        );
1639        assert!(state.contains(&other_s), "{state}");
1640        assert!(state.contains(&ours_s), "{state}");
1641
1642        std::fs::write(
1643            config.join("env.sh"),
1644            format!("{}\n", super::HOOKS_ENV_LINE),
1645        )
1646        .unwrap();
1647        assert!(super::env_hooks_drift(&config, &ours).is_none());
1648        let body = super::hook_body("post-rewrite");
1649        assert!(body.contains("mktemp"), "{body}");
1650        assert!(body.contains("git-hook post-rewrite"), "{body}");
1651        assert!(body.contains("< \"$_ljos_in\""), "{body}");
1652        let commit = super::hook_body("post-commit");
1653        assert!(!commit.contains("mktemp"), "{commit}");
1654        assert!(commit.contains("git-hook post-commit"), "{commit}");
1655
1656        super::write_owned_hooks(&ours).unwrap();
1657        let (ok, state) = super::hooks_state(&ours, Some(&ours_s));
1658        assert!(ok, "{state}");
1659        std::fs::remove_file(ours.join("pre-push")).unwrap();
1660        let (ok, state) = super::hooks_state(&ours, Some(&ours_s));
1661        assert!(!ok, "{state}");
1662        assert!(state.contains(super::HOOKS_FIX), "{state}");
1663    }
1664
1665    /// The `pre-push` block a build before 64e489f5 wrote. `|| true`
1666    /// drops the gate's refusal, so git pushes anyway.
1667    const OLD_PRE_PUSH: &str = "# ljos:begin git-hook\n\
1668        if command -v ljos >/dev/null 2>&1; then\n\
1669        \tljos git-hook pre-push \"$@\" >&2 || true\n\
1670        else\n\
1671        \t'/usr/local/bin/ljos' git-hook pre-push \"$@\" >&2 || true\n\
1672        fi\n\
1673        # ljos:end git-hook\n";
1674
1675    #[test]
1676    fn the_doctor_fails_a_pre_push_stub_that_drops_a_refusal() {
1677        let dir = tempfile::tempdir().unwrap();
1678        let ours = dir.path().join("git-hooks");
1679        let ours_s = ours.display().to_string();
1680        let config = dir.path().join("config");
1681        super::write_owned_hooks(&ours).unwrap();
1682        let (ok, state) = super::doctor_state(&ours, Some(&ours_s), &config);
1683        assert!(ok, "{state}");
1684
1685        let fresh = super::hook_body("pre-push");
1686        let stale = fresh.replace(&super::hook_block("pre-push"), OLD_PRE_PUSH);
1687        assert_ne!(stale, fresh);
1688        std::fs::write(ours.join("pre-push"), &stale).unwrap();
1689        let (ok, state) = super::doctor_state(&ours, Some(&ours_s), &config);
1690        assert!(!ok, "a stale pre-push stub passed: {state}");
1691        assert!(state.contains("pre-push stub predates"), "{state}");
1692        assert_eq!(state.matches(super::HOOKS_FIX).count(), 1, "{state}");
1693
1694        let moved = fresh.replace(
1695            &super::shell_quote(&super::ljos_executable()),
1696            "'/opt/other/ljos'",
1697        );
1698        assert_ne!(moved, fresh);
1699        std::fs::write(ours.join("pre-push"), moved).unwrap();
1700        let (ok, state) = super::doctor_state(&ours, Some(&ours_s), &config);
1701        assert!(ok, "another fallback path failed the row: {state}");
1702
1703        let user = dir.path().join("user-hooks");
1704        super::chain_user_hooks(&user).unwrap();
1705        let user_s = user.display().to_string();
1706        let prior = format!("#!/bin/sh\necho mine\n{OLD_PRE_PUSH}");
1707        std::fs::write(user.join("pre-push"), &prior).unwrap();
1708        let (ok, state) = super::hooks_state(&ours, Some(&user_s));
1709        assert!(!ok, "a stale user block passed: {state}");
1710        assert!(state.contains("pre-push hook's ljos block"), "{state}");
1711        super::chain_user_hooks(&user).unwrap();
1712        let (ok, state) = super::hooks_state(&ours, Some(&user_s));
1713        assert!(ok, "install left the stale block: {state}");
1714        let hooked = std::fs::read_to_string(user.join("pre-push")).unwrap();
1715        assert!(hooked.starts_with("#!/bin/sh\necho mine\n"), "{hooked}");
1716        assert_eq!(hooked.matches("# ljos:begin git-hook").count(), 1);
1717        assert!(!hooked.contains("\"$@\" >&2 || true"), "{hooked}");
1718    }
1719
1720    #[test]
1721    fn a_hook_that_does_not_book_succeeds() {
1722        super::run_named("post-checkout").unwrap();
1723    }
1724
1725    #[test]
1726    fn a_pre_push_ref_list_names_the_protected_branch_it_sends() {
1727        let branches = vec!["develop".to_string(), "main".to_string()];
1728        let line = |dst: &str| format!("refs/heads/x 1111 {dst} 0000\n");
1729        assert_eq!(protected_ref("", &branches), None);
1730        assert_eq!(protected_ref(&line("refs/heads/topic"), &branches), None);
1731        assert_eq!(protected_ref(&line("refs/tags/main"), &branches), None);
1732        let both = line("refs/heads/topic") + &line("refs/heads/Main");
1733        assert_eq!(
1734            protected_ref(&both, &branches).as_deref(),
1735            Some("sends `main`")
1736        );
1737        let odd = protected_ref("refs/heads/x main\n", &branches).unwrap();
1738        assert!(odd.contains("not a ref git would send"), "{odd}");
1739    }
1740
1741    #[test]
1742    fn hook_children_carry_the_guard_without_touching_the_process() {
1743        let before_hook = std::env::var_os("LJOS_GIT_HOOK");
1744        let before_dir = std::env::var_os("GIT_DIR");
1745        let mut plain = Command::new("true");
1746        plain.env("GIT_DIR", "keep");
1747        hook_child_env(&mut plain);
1748        assert_eq!(mapped(&plain, "GIT_DIR"), Some(Some(OsStr::new("keep"))));
1749        assert_eq!(mapped(&plain, "LJOS_GIT_HOOK"), None);
1750
1751        let _guard = HookChildren::enter();
1752        let mut cmd = Command::new("true");
1753        cmd.env("GIT_DIR", "from-the-hook");
1754        cmd.env("PATH", "/usr/bin");
1755        hook_child_env(&mut cmd);
1756        assert_eq!(mapped(&cmd, "LJOS_GIT_HOOK"), Some(Some(OsStr::new("1"))));
1757        for key in HOOK_GIT_ENV {
1758            assert_eq!(mapped(&cmd, key), Some(None), "{key}");
1759        }
1760        assert_eq!(mapped(&cmd, "PATH"), Some(Some(OsStr::new("/usr/bin"))));
1761        assert_eq!(std::env::var_os("LJOS_GIT_HOOK"), before_hook);
1762        assert_eq!(std::env::var_os("GIT_DIR"), before_dir);
1763    }
1764
1765    #[test]
1766    fn a_tests_paragraph_is_kept_and_a_by_line_is_refused() {
1767        assert!(!super::line_refused("Tests: cargo test"));
1768        assert!(!super::message_refused("note\n\nTests: cargo test\n"));
1769        assert!(super::line_refused("Co-authored-by: Ada <ada@example.com>"));
1770        assert!(super::line_refused("Signed-off-by: Ada <ada@example.com>"));
1771        assert!(super::message_refused(
1772            "note\nCo-authored-by: Ada <ada@example.com>\n"
1773        ));
1774        assert!(super::line_refused("Made-with: a tool"));
1775        assert!(super::line_refused("Generated with a tool"));
1776        assert!(super::line_refused("made with cursor"));
1777        assert!(!super::line_refused(
1778            "See Co-authored-by: Ada <ada@example.com>"
1779        ));
1780        assert!(super::line_refused("Cursor Agent wrote this"));
1781        assert!(super::line_refused("cursoragent"));
1782        assert!(super::line_refused("see cursoragent in the note"));
1783        assert!(super::line_refused("see a cursor agent in the note"));
1784        assert!(!super::line_refused("the plot was made with cursor tools"));
1785        assert!(super::line_refused("CURSOR_AGENT=1"));
1786        assert!(super::line_refused("  CURSOR_AGENT=1"));
1787        assert!(super::line_refused("CURSOR_AGENT: 1"));
1788        assert!(super::line_refused("Co-authored-by : x"));
1789        assert!(super::line_refused("  Co-authored-by: x"));
1790        assert!(super::line_refused("Made-with : x"));
1791        assert!(super::line_refused(" Made-with: x"));
1792        assert!(!super::line_refused("Note: kept"));
1793        assert!(!super::line_refused("The Signed-off-by line is gone."));
1794        assert!(!super::line_refused("see CURSOR_AGENT in the prose"));
1795        assert!(super::line_refused("\tCo-authored-by: A"));
1796        assert!(super::line_refused("Co-authored-by\t: A"));
1797        assert!(super::line_refused("\tCURSOR_AGENT=1"));
1798        assert!(super::line_refused("CURSOR_AGENT\t=1"));
1799        assert!(!super::line_refused(
1800            "The figures are generated with matplotlib."
1801        ));
1802        assert!(!super::line_refused("Tests: ran cargo test"));
1803        assert!(!super::line_refused("Ask the author by mail."));
1804        assert!(!super::line_refused("Signed-off-by"));
1805    }
1806}