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            return Err(crate::policy_label::failed(
853                "effect-unavailable",
854                anyhow!("pre-push: cannot read `{line}`"),
855            ));
856        }
857        let local_sha = fields[1];
858        let remote_sha = fields[3];
859        if !is_object_name(local_sha) || !is_object_name(remote_sha) {
860            return Err(crate::policy_label::failed(
861                "effect-unavailable",
862                anyhow!("pre-push: cannot read `{line}`"),
863            ));
864        }
865        if is_zero_name(local_sha) {
866            continue;
867        }
868        let listed = if is_zero_name(remote_sha) {
869            listed_commits(&[local_sha, "--not", "--remotes"])?
870        } else {
871            let range = format!("{remote_sha}..{local_sha}");
872            listed_commits(&[&range])?
873        };
874        for sha in listed {
875            let body = commit_body(&sha)?;
876            if message_refused(&body) {
877                let detail =
878                    format!("machine-trailer: {sha} message carries a machine mark; the push runs");
879                crate::memory_port::record_label("commit-message-warning", &detail, "labelled");
880                eprintln!("ljos: label commit-message-warning: {detail}");
881            }
882        }
883    }
884    Ok(())
885}
886
887fn is_object_name(text: &str) -> bool {
888    matches!(text.len(), 40 | 64) && text.bytes().all(|b| b.is_ascii_hexdigit())
889}
890
891fn is_zero_name(text: &str) -> bool {
892    is_object_name(text) && text.bytes().all(|b| b == b'0')
893}
894
895fn listed_commits(args: &[&str]) -> Result<Vec<String>> {
896    let mut git_args = vec!["rev-list"];
897    git_args.extend_from_slice(args);
898    let shown = args.join(" ");
899    let out = git_command(&git_args, &[])
900        .stdin(std::process::Stdio::null())
901        .output()
902        .with_context(|| format!("pre-push: cannot read commits in {shown}"))?;
903    if !out.status.success() {
904        let err = String::from_utf8_lossy(&out.stderr);
905        bail!("pre-push: cannot read commits in {shown} ({})", err.trim());
906    }
907    Ok(String::from_utf8_lossy(&out.stdout)
908        .lines()
909        .filter(|line| !line.is_empty())
910        .map(str::to_string)
911        .collect())
912}
913
914fn commit_body(sha: &str) -> Result<String> {
915    let out = git_command(&["log", "-1", "--format=%B", sha], &[])
916        .stdin(std::process::Stdio::null())
917        .output()
918        .with_context(|| format!("pre-push: cannot read {sha}"))?;
919    if !out.status.success() {
920        bail!("pre-push: cannot read {sha}");
921    }
922    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
923}
924
925fn message_refused(body: &str) -> bool {
926    phrase_refused(&body.to_ascii_lowercase()) || body.lines().any(line_refused)
927}
928
929/// A by-trailer, a made-with line, a generated line at the start of
930/// the line, or a machine account mark anywhere on the line. A Tests
931/// or note paragraph is none of those. A generated phrase
932/// mid-sentence is not a generated line.
933fn line_refused(line: &str) -> bool {
934    let lower = line.to_ascii_lowercase();
935    account_anywhere(&lower) || phrase_refused(&lower) || anchored_mark(&lower)
936}
937
938/// `seat alfa` and `seatalfa` match anywhere on the line.
939fn account_anywhere(lower: &str) -> bool {
940    lower.contains("seat alfa") || lower.contains("seatalfa")
941}
942
943/// `generated with` and `made with the editor harness` match only at the start of
944/// the line, after optional blanks.
945fn phrase_refused(lower: &str) -> bool {
946    let rest = lower.trim_start_matches([' ', '\t']);
947    rest.starts_with("generated with") || rest.starts_with("made with cursor")
948}
949
950fn anchored_mark(lower: &str) -> bool {
951    let rest = lower.trim_start_matches([' ', '\t']);
952    made_with_mark(rest) || by_mark(rest) || cursor_assign(rest)
953}
954
955fn made_with_mark(rest: &str) -> bool {
956    let Some(after) = rest.strip_prefix("made-with") else {
957        return false;
958    };
959    after.trim_start_matches([' ', '\t']).starts_with(':')
960}
961
962fn by_mark(rest: &str) -> bool {
963    let Some(colon) = rest.find(':') else {
964        return false;
965    };
966    let token = rest[..colon].trim_end_matches([' ', '\t']);
967    let Some(name) = token.strip_suffix("-by") else {
968        return false;
969    };
970    !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
971}
972
973fn cursor_assign(rest: &str) -> bool {
974    let Some(after_cursor) = rest.strip_prefix("cursor") else {
975        return false;
976    };
977    let after_sep = after_cursor
978        .strip_prefix('_')
979        .or_else(|| after_cursor.strip_prefix('-'))
980        .unwrap_or(after_cursor);
981    let Some(after_agent) = after_sep.strip_prefix("agent") else {
982        return false;
983    };
984    let mut end = 0;
985    for c in after_agent.chars() {
986        if c.is_ascii_alphanumeric() || c == '_' {
987            end += c.len_utf8();
988        } else {
989            break;
990        }
991    }
992    let after = after_agent[end..].trim_start_matches([' ', '\t']);
993    after.starts_with('=') || after.starts_with(':')
994}
995
996/// Why git goes on after the gate refuses, when the hook file it is
997/// running carries an ljos block older than this build's. Such a block
998/// can end in `|| true`, and this process cannot change the exit status
999/// the hook returns. A hook that calls `ljos git-hook` with no block is
1000/// the user's own and is not judged.
1001fn dropped_refusal(name: &str) -> Option<String> {
1002    let raw = git_line(&["rev-parse", "--git-path", &format!("hooks/{name}")])?;
1003    let path = std::env::current_dir().ok()?.join(raw);
1004    let text = fs::read_to_string(&path).ok()?;
1005    if !text.contains(BLOCK_BEGIN) || carries_block(&text, name) {
1006        return None;
1007    }
1008    let verb = if name == "pre-push" { "push" } else { "commit" };
1009    Some(format!(
1010        "sitting-gate: {} predates this gate and drops its refusal, so git will {verb} anyway; {HOOKS_FIX} replaces it",
1011        path.display()
1012    ))
1013}
1014
1015/// The guard's sitting gate for a commit or push it did not see, such as
1016/// one a script runs: under a runner, `pre-commit` needs a live sitting,
1017/// and `pre-push` also needs that ticket to clear each ref it sends onto
1018/// a branch [`crate::gates::consensus_push`] names. A store or a tracker
1019/// checkout, which ljos writes itself, is not gated, and nor is the
1020/// person. When a runner variable is the only cause, and the call would
1021/// be refused, the person is asked for their passphrase on the
1022/// controlling terminal; a right answer lets this one call through.
1023fn gate(name: &str, refs: &str) -> Result<()> {
1024    if crate::runner_cause().is_none() {
1025        return Ok(());
1026    }
1027    let refused = match gate_runner(name, refs) {
1028        Ok(()) => return Ok(()),
1029        Err(refused) => refused,
1030    };
1031    // A sitting that has not settled is a label. The push or commit runs.
1032    // The cloud seat push rule is judged on the shell line, not here.
1033    eprintln!("ljos: sitting-gate: {refused:#}");
1034    if let Some(why) = dropped_refusal(name) {
1035        eprintln!("ljos: {why}");
1036    }
1037    Ok(())
1038}
1039
1040fn gate_runner(name: &str, refs: &str) -> Result<()> {
1041    let repo = git_line(&["rev-parse", "--show-toplevel"])
1042        .map(PathBuf::from)
1043        .or_else(git_dir);
1044    if repo
1045        .as_deref()
1046        .is_some_and(|repo| is_store(repo) || crate::tracker_place::is_tracker(repo))
1047    {
1048        return Ok(());
1049    }
1050    // A commit is not this check. The push below is.
1051    if name != "pre-push" {
1052        return Ok(());
1053    }
1054    // In a hook the process tree names the hook's own shell. The seat a
1055    // booking would take is the one the sitting was taken under. With a
1056    // conversation id in the environment only that conversation's holder
1057    // counts, or for a subagent its parent's records and process when
1058    // that process carries a conversation id. With no id it falls back
1059    // to the process match.
1060    let seat = crate::git_hook_seat();
1061    let _actor = seat.as_deref().map(crate::HookActor::enter);
1062    let _push = crate::PushCheck::enter();
1063    let issue = match crate::sitting_gate::live_sitting() {
1064        Ok(issue) => issue,
1065        Err(_) => {
1066            let named = crate::sitting_gate::open_or_name_sitting().unwrap_or_default();
1067            if crate::push_slow() {
1068                if named.is_empty() {
1069                    eprintln!("{}", crate::push_slow_line());
1070                } else {
1071                    eprintln!("{}; sitting {named}", crate::push_slow_line());
1072                }
1073            }
1074            named
1075        }
1076    };
1077    let cfg = match crate::gates::consensus_push(repo.as_deref()) {
1078        Ok(cfg) => cfg,
1079        Err(why) => {
1080            return Err(anyhow!(
1081                "sitting-gate: {}",
1082                crate::sitting_gate::unread_settings(&why)
1083            ))
1084        }
1085    };
1086    let dest = protected_ref(refs, &cfg.branches);
1087    let Some(dest) = dest else {
1088        return Ok(());
1089    };
1090    // The person's own allow for this push, as a user rule over the line
1091    // `git push REMOTE BRANCH` or `git push REMOTE LOCAL:BRANCH`, clears
1092    // the sitting check: their yes is what the check exists to get.
1093    if push_lines(refs, &cfg.branches)
1094        .iter()
1095        .any(|line| crate::user_rules::allows(line).is_some())
1096    {
1097        return Ok(());
1098    }
1099    // The tracker read already missed its bound. Stop before the
1100    // consensus checks. Empty notes would fail as a missing family.
1101    if crate::push_tracker_slow() {
1102        return Err(anyhow!("sitting-gate: {}", crate::push_tracker_slow_line()));
1103    }
1104    if issue.is_empty() {
1105        let why = "the sitting has no settled consensus".to_string();
1106        let wait = crate::sitting_gate::seats_wait(&dest, &cfg.branches, &issue, &why);
1107        return Err(anyhow!("sitting-gate: {wait}"));
1108    }
1109    if let Err(reason) = crate::protected_push_refusal(&issue, &crate::seat_name(), cfg.quorum) {
1110        let why = format!("the sitting has no settled consensus: {reason}");
1111        let wait = crate::sitting_gate::seats_wait(&dest, &cfg.branches, &issue, &why);
1112        return Err(anyhow!("sitting-gate: {wait}"));
1113    }
1114    Ok(())
1115}
1116
1117/// The command lines a pre-push onto a protected branch stands for, one
1118/// per ref that lands on one: `git push REMOTE BRANCH` and
1119/// `git push REMOTE LOCAL:BRANCH`, with the remote git named the hook
1120/// (its first argument, `origin` when none), so a person's allow rule
1121/// written over either form covers it.
1122fn push_lines(refs: &str, branches: &[String]) -> Vec<String> {
1123    let remote = std::env::args()
1124        .nth(3)
1125        .filter(|a| !a.is_empty() && !a.starts_with('-'))
1126        .unwrap_or_else(|| "origin".to_string());
1127    let mut out = Vec::new();
1128    for line in refs.lines().filter(|l| !l.trim().is_empty()) {
1129        let fields: Vec<&str> = line.split_whitespace().collect();
1130        let [local, _, remote_ref, _] = fields[..] else {
1131            continue;
1132        };
1133        let Some(branch) = remote_ref.strip_prefix("refs/heads/") else {
1134            continue;
1135        };
1136        if !branches.iter().any(|b| b.eq_ignore_ascii_case(branch)) {
1137            continue;
1138        }
1139        let short = local.strip_prefix("refs/heads/").unwrap_or(local);
1140        out.push(format!("git push {remote} {branch}"));
1141        out.push(format!("git push {remote} {short}:{branch}"));
1142        out.push(format!("git push {remote} {local}:{remote_ref}"));
1143    }
1144    out
1145}
1146
1147/// What a push whose pre-push stdin is `refs` sends onto a branch in
1148/// `branches`, as `sends BRANCH`, or `None` when no ref lands on one.
1149/// Git runs the hook with no lines when nothing is to be sent. A line
1150/// not in git's four-field form cannot be read, so it is taken to land
1151/// on one.
1152fn protected_ref(refs: &str, branches: &[String]) -> Option<String> {
1153    for line in refs.lines().filter(|l| !l.trim().is_empty()) {
1154        let fields: Vec<&str> = line.split_whitespace().collect();
1155        let [_, _, remote, _] = fields[..] else {
1156            return Some(format!("lists `{line}`, which is not a ref git would send"));
1157        };
1158        let Some(branch) = remote.strip_prefix("refs/heads/") else {
1159            continue;
1160        };
1161        if let Some(b) = branches.iter().find(|b| b.eq_ignore_ascii_case(branch)) {
1162            return Some(format!("sends `{b}`"));
1163        }
1164    }
1165    None
1166}
1167
1168fn book_commit(hook: &str) -> Result<()> {
1169    if std::env::var_os("LJOS_GIT_HOOK").is_some() || booking_off() {
1170        return Ok(());
1171    }
1172    if foreign_session() {
1173        return Ok(());
1174    }
1175    if hook != "post-rewrite" && mid_rewrite() {
1176        return Ok(());
1177    }
1178    let Some(repo) = git_line(&["rev-parse", "--show-toplevel"]) else {
1179        return Ok(());
1180    };
1181    let repo_path = PathBuf::from(&repo);
1182    // A commit in the tracker's checkout is a tracker write: never booked,
1183    // but its seat is checked as any other write's is.
1184    let tracker = crate::tracker_place::is_tracker(&repo_path);
1185    if !tracker && (crate::bookkeep::path_is_temp(Some(&repo_path)) || skip_repo(&repo_path)) {
1186        return Ok(());
1187    }
1188    let Some(head) = git_line(&["rev-parse", "HEAD"]) else {
1189        return Ok(());
1190    };
1191    // The process tree is not a seat. Without LJOS_SEAT, or an agy or
1192    // opencode conversation, the commit stays unbooked; a subagent is told.
1193    let Some(seat) = crate::git_hook_seat() else {
1194        if tracker {
1195            refuse_tracker_commit(
1196                &head,
1197                "no seat is named; export LJOS_SEAT=<your seat> to write the tracker",
1198            );
1199        } else if crate::unseated_subagent() {
1200            // Stdout: the installed hook shows that line and drops stderr.
1201            println!(
1202                "ljos: commit {} not booked: this subagent has no seat; export LJOS_SEAT=<your seat> (the parent's) to book it",
1203                &head[..head.len().min(12)]
1204            );
1205        }
1206        return Ok(());
1207    };
1208    let _actor = crate::HookActor::enter(&seat);
1209    // Every path below writes the tracker: a repointed citation, a named
1210    // issue, an open sitting, a new claim.
1211    if let Err(e) = crate::write_seat("commit") {
1212        if tracker {
1213            refuse_tracker_commit(&head, &format!("{e:#}"));
1214        } else {
1215            println!(
1216                "ljos: commit {} not booked: {e:#}",
1217                &head[..head.len().min(12)]
1218            );
1219        }
1220        return Ok(());
1221    }
1222    if tracker {
1223        return Ok(());
1224    }
1225    let _children = HookChildren::enter();
1226    // An amend or a rebase lists old and new shas. Move the citation
1227    // before the "already booked" return: post-commit may have cited the
1228    // new HEAD already, and the old sha would otherwise stay on the issue.
1229    if already_booked(&repo, &head) {
1230        return Ok(());
1231    }
1232    let subject = git_line(&["log", "-1", "--format=%s"]).unwrap_or_default();
1233    println!(
1234        "{}",
1235        crate::bookkeep::note_after_commit(&repo, &head, &subject)
1236    );
1237    remember_booked(&repo, &head);
1238    Ok(())
1239}
1240
1241fn booking_off() -> bool {
1242    matches!(
1243        std::env::var("LJOS_OFF").ok().as_deref(),
1244        Some("1" | "true" | "TRUE" | "yes" | "YES" | "on" | "ON")
1245    ) || crate::bookkeep::guard_suspended()
1246}
1247
1248fn foreign_session() -> bool {
1249    // OpenCode's shell sets OPENCODE_SESSION_ID and never calls the plugin's
1250    // tool.execute.after, so the git hook is the booker. the terminal harness and the command harness
1251    // book from their own hooks.
1252    ["CLAUDECODE", "CODEX_THREAD_ID", "CODEX_SESSION_ID"]
1253        .iter()
1254        .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty()))
1255}
1256
1257fn mid_rewrite() -> bool {
1258    let Some(dir) = git_dir() else {
1259        return false;
1260    };
1261    dir.join("rebase-merge").is_dir()
1262        || dir.join("rebase-apply").is_dir()
1263        || dir.join("MERGE_HEAD").is_file()
1264}
1265
1266/// A tracker commit no seat that may write the tracker made. It has landed
1267/// and a post-commit hook cannot take it back, so the refusal is said on
1268/// stdout, which the installed hook shows, and kept in the book log.
1269fn refuse_tracker_commit(head: &str, why: &str) {
1270    let line = format!(
1271        "ljos: tracker commit {} was not made by a seat that may write the tracker: {why}",
1272        &head[..head.len().min(12)]
1273    );
1274    println!("{line}");
1275    crate::bookkeep::log_line(&format!("git-hooks: {line}"));
1276}
1277
1278fn skip_repo(repo: &Path) -> bool {
1279    if is_store(repo) {
1280        return true;
1281    }
1282    skip_roots().iter().any(|root| covered(repo, root))
1283}
1284
1285/// Paths a commit under which is not booked. The defaults always apply.
1286/// `[git_hooks] skip` in `ljos.toml` adds box-specific paths, and a
1287/// reinstall rewrites the hook scripts without touching that file.
1288fn skip_roots() -> Vec<PathBuf> {
1289    let mut roots = vec![
1290        PathBuf::from("/tmp"),
1291        PathBuf::from("/var/tmp"),
1292        PathBuf::from("/dev/shm"),
1293    ];
1294    for key in ["VISSUE_ROOT", "ISSUE_ROOT", "CLAIMDAG_DIR"] {
1295        if let Some(path) = std::env::var_os(key).filter(|value| !value.is_empty()) {
1296            roots.push(PathBuf::from(path));
1297        }
1298    }
1299    roots.extend(store_dirs());
1300    for path in config_files() {
1301        roots.extend(configured_skips(&path));
1302    }
1303    roots.retain(|path| useful_root(path));
1304    roots
1305}
1306
1307fn useful_root(path: &Path) -> bool {
1308    let text = path.to_string_lossy();
1309    let text = text.trim();
1310    !text.is_empty() && text != "/" && text != "."
1311}
1312
1313fn config_files() -> Vec<PathBuf> {
1314    let mut out = Vec::new();
1315    let base = std::env::var_os("XDG_CONFIG_HOME")
1316        .filter(|value| !value.is_empty())
1317        .map(PathBuf::from)
1318        .or_else(|| {
1319            std::env::var_os("HOME")
1320                .filter(|value| !value.is_empty())
1321                .map(|home| PathBuf::from(home).join(".config"))
1322        });
1323    if let Some(base) = base {
1324        out.push(base.join("ljos").join("ljos.toml"));
1325        if let Some(seat) = std::env::var("LJOS_SEAT")
1326            .ok()
1327            .map(|name| name.trim().to_string())
1328            .filter(|name| !name.is_empty() && !name.contains('/') && !name.contains(".."))
1329        {
1330            out.push(base.join("ljos").join("seats").join(seat).join("ljos.toml"));
1331        }
1332    }
1333    if let Some(path) = std::env::var_os("LJOS_CONFIG").filter(|value| !value.is_empty()) {
1334        out.push(PathBuf::from(path));
1335    }
1336    if let Ok(cwd) = std::env::current_dir() {
1337        out.push(cwd.join("ljos.toml"));
1338    }
1339    out
1340}
1341
1342fn configured_skips(path: &Path) -> Vec<PathBuf> {
1343    let Ok(text) = fs::read_to_string(path) else {
1344        return Vec::new();
1345    };
1346    let Ok(value) = toml::from_str::<toml::Value>(&text) else {
1347        return Vec::new();
1348    };
1349    let Some(list) = value
1350        .get("git_hooks")
1351        .and_then(|table| table.get("skip"))
1352        .and_then(toml::Value::as_array)
1353    else {
1354        return Vec::new();
1355    };
1356    list.iter()
1357        .filter_map(toml::Value::as_str)
1358        .map(str::trim)
1359        .filter(|text| !text.is_empty())
1360        .map(PathBuf::from)
1361        .collect()
1362}
1363
1364fn covered(repo: &Path, root: &Path) -> bool {
1365    let repo = canonical_or(repo);
1366    let root = canonical_or(root);
1367    repo == root || repo.starts_with(&root)
1368}
1369
1370fn canonical_or(path: &Path) -> PathBuf {
1371    fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
1372}
1373
1374/// Whether `repo` is a deed or claim store ljos writes itself, read from
1375/// the store settings; a path that merely contains `claimdag` is not one.
1376fn is_store(repo: &Path) -> bool {
1377    store_dirs()
1378        .iter()
1379        .any(|root| same_dir(repo, root) || repo_starts(repo, root))
1380}
1381
1382fn store_dirs() -> Vec<PathBuf> {
1383    let mut out = Vec::new();
1384    if let Ok(url) = std::env::var("DEEDAR_URL") {
1385        if let Some(path) = url.strip_prefix("file://") {
1386            out.push(PathBuf::from(path));
1387        }
1388    }
1389    if let Some(data) = std::env::var_os("XDG_DATA_HOME").filter(|value| !value.is_empty()) {
1390        out.push(PathBuf::from(data).join("deedar").join("store"));
1391    } else if let Some(home) = std::env::var_os("HOME").filter(|value| !value.is_empty()) {
1392        out.push(
1393            PathBuf::from(home)
1394                .join(".local")
1395                .join("share")
1396                .join("deedar")
1397                .join("store"),
1398        );
1399    }
1400    out
1401}
1402
1403fn same_dir(left: &Path, right: &Path) -> bool {
1404    let left = fs::canonicalize(left).unwrap_or_else(|_| left.to_path_buf());
1405    let right = fs::canonicalize(right).unwrap_or_else(|_| right.to_path_buf());
1406    left == right
1407}
1408
1409fn repo_starts(repo: &Path, root: &Path) -> bool {
1410    if !root.exists() {
1411        return false;
1412    }
1413    let repo = fs::canonicalize(repo).unwrap_or_else(|_| repo.to_path_buf());
1414    let root = fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
1415    repo.starts_with(root)
1416}
1417
1418fn already_booked(repo: &str, head: &str) -> bool {
1419    let key = format!("{repo}\t{head}");
1420    fs::read_to_string(booked_path())
1421        .map(|text| text.lines().any(|line| line == key))
1422        .unwrap_or(false)
1423}
1424
1425fn remember_booked(repo: &str, head: &str) {
1426    let path = booked_path();
1427    if let Some(dir) = path.parent() {
1428        let _ = fs::create_dir_all(dir);
1429    }
1430    let mut lines: Vec<String> = fs::read_to_string(&path)
1431        .unwrap_or_default()
1432        .lines()
1433        .map(str::to_string)
1434        .filter(|line| !line.starts_with(&format!("{repo}\t")))
1435        .collect();
1436    lines.push(format!("{repo}\t{head}"));
1437    if lines.len() > 200 {
1438        lines.drain(0..lines.len() - 200);
1439    }
1440    let _ = fs::write(path, lines.join("\n") + "\n");
1441}
1442
1443fn booked_path() -> PathBuf {
1444    crate::runtime_dir().join("git-hooks-booked")
1445}
1446
1447fn git_dir() -> Option<PathBuf> {
1448    let raw = git_line(&["rev-parse", "--git-dir"])?;
1449    let path = PathBuf::from(&raw);
1450    if path.is_absolute() {
1451        Some(path)
1452    } else {
1453        std::env::current_dir().ok().map(|cwd| cwd.join(path))
1454    }
1455}
1456
1457/// `GIT_*` values a hook exports. A later `git -C` follows `GIT_DIR` and
1458/// ignores `-C`, so a tracker commit would land in the checkout that just
1459/// finished.
1460const HOOK_GIT_ENV: &[&str] = &[
1461    "GIT_DIR",
1462    "GIT_WORK_TREE",
1463    "GIT_INDEX_FILE",
1464    "GIT_PREFIX",
1465    "GIT_OBJECT_DIRECTORY",
1466    "GIT_COMMON_DIR",
1467    "GIT_NAMESPACE",
1468];
1469
1470thread_local! {
1471    static HOOK_CHILDREN: Cell<bool> = const { Cell::new(false) };
1472}
1473
1474/// While this guard is alive, child processes started through
1475/// [`hook_child_env`] carry `LJOS_GIT_HOOK=1` and do not inherit the hook's
1476/// `GIT_DIR`. Dropping it restores the previous flag. The process
1477/// environment is not changed.
1478#[must_use]
1479struct HookChildren {
1480    previous: bool,
1481}
1482
1483impl HookChildren {
1484    fn enter() -> Self {
1485        let previous = HOOK_CHILDREN.with(Cell::get);
1486        HOOK_CHILDREN.with(|flag| flag.set(true));
1487        Self { previous }
1488    }
1489}
1490
1491impl Drop for HookChildren {
1492    fn drop(&mut self) {
1493        HOOK_CHILDREN.with(|flag| flag.set(self.previous));
1494    }
1495}
1496
1497/// Put the re-entry guard on a child `git` or `ljos`, and drop the hook's
1498/// git directory from that child. No effect unless a git hook is booking
1499/// a commit on this thread.
1500pub(crate) fn hook_child_env(cmd: &mut Command) {
1501    if !HOOK_CHILDREN.with(Cell::get) {
1502        return;
1503    }
1504    cmd.env("LJOS_GIT_HOOK", "1");
1505    for key in HOOK_GIT_ENV {
1506        cmd.env_remove(key);
1507    }
1508}
1509
1510#[cfg(test)]
1511pub(crate) fn with_hook_children_for_test<T>(run: impl FnOnce() -> T) -> T {
1512    let _guard = HookChildren::enter();
1513    run()
1514}
1515
1516fn git_command(args: &[&str], git_env: &[(&str, &str)]) -> Command {
1517    let mut cmd = crate::git_cmd();
1518    cmd.args(args);
1519    for (key, value) in git_env {
1520        cmd.env(key, value);
1521    }
1522    hook_child_env(&mut cmd);
1523    cmd
1524}
1525
1526fn git_line(args: &[&str]) -> Option<String> {
1527    let out = crate::bounded_output(&mut git_command(args, &[])).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 global_hooks_path(git_env: &[(&str, &str)]) -> Option<String> {
1541    let out = git_command(&["config", "--global", "--get", "core.hooksPath"], git_env)
1542        .output()
1543        .ok()?;
1544    if !out.status.success() {
1545        return None;
1546    }
1547    let text = String::from_utf8(out.stdout).ok()?;
1548    let text = text.trim();
1549    if text.is_empty() {
1550        None
1551    } else {
1552        Some(text.to_string())
1553    }
1554}
1555
1556fn set_global_hooks_path(path: &Path, git_env: &[(&str, &str)]) -> Result<()> {
1557    let value = path.display().to_string();
1558    let status = git_command(&["config", "--global", "core.hooksPath", &value], git_env)
1559        .status()
1560        .context("git-hooks: git config")?;
1561    if !status.success() {
1562        bail!("git-hooks: could not set core.hooksPath");
1563    }
1564    Ok(())
1565}
1566
1567fn unset_global_hooks_path(git_env: &[(&str, &str)]) -> Result<()> {
1568    let status = git_command(
1569        &["config", "--global", "--unset", "core.hooksPath"],
1570        git_env,
1571    )
1572    .status()
1573    .context("git-hooks: git config")?;
1574    if !status.success() {
1575        bail!("git-hooks: could not unset core.hooksPath");
1576    }
1577    Ok(())
1578}
1579
1580#[cfg(test)]
1581mod tests {
1582    use std::ffi::OsStr;
1583
1584    use super::*;
1585
1586    fn mapped<'a>(cmd: &'a Command, key: &str) -> Option<Option<&'a OsStr>> {
1587        cmd.get_envs()
1588            .find(|(name, _)| *name == OsStr::new(key))
1589            .map(|(_, value)| value)
1590    }
1591
1592    #[test]
1593    fn the_doctor_names_a_hooks_path_that_is_not_the_onboard_one() {
1594        let dir = tempfile::tempdir().unwrap();
1595        let ours = dir.path().join("ljos").join("git-hooks");
1596        let other = dir.path().join("user-hooks");
1597        std::fs::create_dir_all(&other).unwrap();
1598        let prior = "#!/bin/sh\nprintf 'user-hook\\n'\n";
1599        std::fs::write(other.join("post-commit"), prior).unwrap();
1600        let ours_s = ours.display().to_string();
1601        let other_s = other.display().to_string();
1602
1603        let (ok, state) = super::hooks_state(&ours, None);
1604        assert!(!ok);
1605        assert!(state.starts_with(super::HOOKS_UNSET), "{state}");
1606        assert_eq!(state.matches(super::HOOKS_FIX).count(), 1, "{state}");
1607
1608        let (ok, state) = super::hooks_state(&ours, Some(&other_s));
1609        assert!(!ok, "{state}");
1610        assert!(state.contains(&other_s), "{state}");
1611        assert!(!state.contains(&ours_s), "{state}");
1612        assert_eq!(state.matches(super::HOOKS_FIX).count(), 1, "{state}");
1613
1614        super::chain_user_hooks(&other).unwrap();
1615        let (ok, state) = super::hooks_state(&ours, Some(&other_s));
1616        assert!(ok, "{state}");
1617        assert!(state.contains("ljos git-hook runs"), "{state}");
1618        let hooked = std::fs::read_to_string(other.join("post-commit")).unwrap();
1619        assert!(hooked.starts_with(prior), "{hooked}");
1620        assert_eq!(
1621            hooked.matches("# ljos:begin git-hook").count(),
1622            1,
1623            "{hooked}"
1624        );
1625        super::chain_user_hooks(&other).unwrap();
1626        assert_eq!(
1627            std::fs::read_to_string(other.join("post-commit")).unwrap(),
1628            hooked
1629        );
1630        assert!(other.join("pre-push").is_file());
1631
1632        super::strip_user_hooks(&other).unwrap();
1633        assert_eq!(
1634            std::fs::read_to_string(other.join("post-commit")).unwrap(),
1635            prior
1636        );
1637        assert!(!other.join("pre-push").exists());
1638
1639        let config = dir.path().join("config");
1640        std::fs::create_dir_all(&config).unwrap();
1641        std::fs::write(
1642            config.join("env.sh"),
1643            format!("export LJOS_GIT_HOOKS={}\n", other.display()),
1644        )
1645        .unwrap();
1646        let drift = super::env_hooks_drift(&config, &ours).expect("a drifted env file");
1647        assert!(drift.contains(&other_s), "{drift}");
1648        assert!(drift.contains(&ours_s), "{drift}");
1649        let (ok, state) = super::doctor_state(&ours, None, &config);
1650        assert!(!ok, "{state}");
1651        assert!(
1652            !state.starts_with(super::HOOKS_UNSET),
1653            "a mismatch stayed info: {state}"
1654        );
1655        assert!(state.contains(&other_s), "{state}");
1656        assert!(state.contains(&ours_s), "{state}");
1657
1658        std::fs::write(
1659            config.join("env.sh"),
1660            format!("{}\n", super::HOOKS_ENV_LINE),
1661        )
1662        .unwrap();
1663        assert!(super::env_hooks_drift(&config, &ours).is_none());
1664        let body = super::hook_body("post-rewrite");
1665        assert!(body.contains("mktemp"), "{body}");
1666        assert!(body.contains("git-hook post-rewrite"), "{body}");
1667        assert!(body.contains("< \"$_ljos_in\""), "{body}");
1668        let commit = super::hook_body("post-commit");
1669        assert!(!commit.contains("mktemp"), "{commit}");
1670        assert!(commit.contains("git-hook post-commit"), "{commit}");
1671
1672        super::write_owned_hooks(&ours).unwrap();
1673        let (ok, state) = super::hooks_state(&ours, Some(&ours_s));
1674        assert!(ok, "{state}");
1675        std::fs::remove_file(ours.join("pre-push")).unwrap();
1676        let (ok, state) = super::hooks_state(&ours, Some(&ours_s));
1677        assert!(!ok, "{state}");
1678        assert!(state.contains(super::HOOKS_FIX), "{state}");
1679    }
1680
1681    /// The `pre-push` block a build before 64e489f5 wrote. `|| true`
1682    /// drops the gate's refusal, so git pushes anyway.
1683    const OLD_PRE_PUSH: &str = "# ljos:begin git-hook\n\
1684        if command -v ljos >/dev/null 2>&1; then\n\
1685        \tljos git-hook pre-push \"$@\" >&2 || true\n\
1686        else\n\
1687        \t'/usr/local/bin/ljos' git-hook pre-push \"$@\" >&2 || true\n\
1688        fi\n\
1689        # ljos:end git-hook\n";
1690
1691    #[test]
1692    fn the_doctor_fails_a_pre_push_stub_that_drops_a_refusal() {
1693        let dir = tempfile::tempdir().unwrap();
1694        let ours = dir.path().join("git-hooks");
1695        let ours_s = ours.display().to_string();
1696        let config = dir.path().join("config");
1697        super::write_owned_hooks(&ours).unwrap();
1698        let (ok, state) = super::doctor_state(&ours, Some(&ours_s), &config);
1699        assert!(ok, "{state}");
1700
1701        let fresh = super::hook_body("pre-push");
1702        let stale = fresh.replace(&super::hook_block("pre-push"), OLD_PRE_PUSH);
1703        assert_ne!(stale, fresh);
1704        std::fs::write(ours.join("pre-push"), &stale).unwrap();
1705        let (ok, state) = super::doctor_state(&ours, Some(&ours_s), &config);
1706        assert!(!ok, "a stale pre-push stub passed: {state}");
1707        assert!(state.contains("pre-push stub predates"), "{state}");
1708        assert_eq!(state.matches(super::HOOKS_FIX).count(), 1, "{state}");
1709
1710        let moved = fresh.replace(
1711            &super::shell_quote(&super::ljos_executable()),
1712            "'/opt/other/ljos'",
1713        );
1714        assert_ne!(moved, fresh);
1715        std::fs::write(ours.join("pre-push"), moved).unwrap();
1716        let (ok, state) = super::doctor_state(&ours, Some(&ours_s), &config);
1717        assert!(ok, "another fallback path failed the row: {state}");
1718
1719        let user = dir.path().join("user-hooks");
1720        super::chain_user_hooks(&user).unwrap();
1721        let user_s = user.display().to_string();
1722        let prior = format!("#!/bin/sh\necho mine\n{OLD_PRE_PUSH}");
1723        std::fs::write(user.join("pre-push"), &prior).unwrap();
1724        let (ok, state) = super::hooks_state(&ours, Some(&user_s));
1725        assert!(!ok, "a stale user block passed: {state}");
1726        assert!(state.contains("pre-push hook's ljos block"), "{state}");
1727        super::chain_user_hooks(&user).unwrap();
1728        let (ok, state) = super::hooks_state(&ours, Some(&user_s));
1729        assert!(ok, "install left the stale block: {state}");
1730        let hooked = std::fs::read_to_string(user.join("pre-push")).unwrap();
1731        assert!(hooked.starts_with("#!/bin/sh\necho mine\n"), "{hooked}");
1732        assert_eq!(hooked.matches("# ljos:begin git-hook").count(), 1);
1733        assert!(!hooked.contains("\"$@\" >&2 || true"), "{hooked}");
1734    }
1735
1736    #[test]
1737    fn a_hook_that_does_not_book_succeeds() {
1738        super::run_named("post-checkout").unwrap();
1739    }
1740
1741    #[test]
1742    fn a_pre_push_ref_list_names_the_protected_branch_it_sends() {
1743        let branches = vec!["develop".to_string(), "main".to_string()];
1744        let line = |dst: &str| format!("refs/heads/x 1111 {dst} 0000\n");
1745        assert_eq!(protected_ref("", &branches), None);
1746        assert_eq!(protected_ref(&line("refs/heads/topic"), &branches), None);
1747        assert_eq!(protected_ref(&line("refs/tags/main"), &branches), None);
1748        let both = line("refs/heads/topic") + &line("refs/heads/Main");
1749        assert_eq!(
1750            protected_ref(&both, &branches).as_deref(),
1751            Some("sends `main`")
1752        );
1753        let odd = protected_ref("refs/heads/x main\n", &branches).unwrap();
1754        assert!(odd.contains("not a ref git would send"), "{odd}");
1755    }
1756
1757    #[test]
1758    fn hook_children_carry_the_guard_without_touching_the_process() {
1759        let before_hook = std::env::var_os("LJOS_GIT_HOOK");
1760        let before_dir = std::env::var_os("GIT_DIR");
1761        let mut plain = Command::new("true");
1762        plain.env("GIT_DIR", "keep");
1763        hook_child_env(&mut plain);
1764        assert_eq!(mapped(&plain, "GIT_DIR"), Some(Some(OsStr::new("keep"))));
1765        assert_eq!(mapped(&plain, "LJOS_GIT_HOOK"), None);
1766
1767        let _guard = HookChildren::enter();
1768        let mut cmd = Command::new("true");
1769        cmd.env("GIT_DIR", "from-the-hook");
1770        cmd.env("PATH", "/usr/bin");
1771        hook_child_env(&mut cmd);
1772        assert_eq!(mapped(&cmd, "LJOS_GIT_HOOK"), Some(Some(OsStr::new("1"))));
1773        for key in HOOK_GIT_ENV {
1774            assert_eq!(mapped(&cmd, key), Some(None), "{key}");
1775        }
1776        assert_eq!(mapped(&cmd, "PATH"), Some(Some(OsStr::new("/usr/bin"))));
1777        assert_eq!(std::env::var_os("LJOS_GIT_HOOK"), before_hook);
1778        assert_eq!(std::env::var_os("GIT_DIR"), before_dir);
1779    }
1780
1781    #[test]
1782    fn a_tests_paragraph_is_kept_and_a_by_line_is_refused() {
1783        assert!(!super::line_refused("Tests: cargo test"));
1784        assert!(!super::message_refused("note\n\nTests: cargo test\n"));
1785        assert!(super::line_refused("Co-authored-by: Ada <ada@example.com>"));
1786        assert!(super::line_refused("Signed-off-by: Ada <ada@example.com>"));
1787        assert!(super::message_refused(
1788            "note\nCo-authored-by: Ada <ada@example.com>\n"
1789        ));
1790        assert!(super::line_refused("Made-with: a tool"));
1791        assert!(super::line_refused("Generated with a tool"));
1792        assert!(super::line_refused("made with cursor"));
1793        assert!(!super::line_refused(
1794            "See Co-authored-by: Ada <ada@example.com>"
1795        ));
1796        assert!(super::line_refused("Seat alfa wrote this"));
1797        assert!(super::line_refused("seatalfa"));
1798        assert!(super::line_refused("see seatalfa in the note"));
1799        assert!(super::line_refused("see a seat alfa in the note"));
1800        assert!(!super::line_refused("the plot was made with cursor tools"));
1801        assert!(super::line_refused("CURSOR_AGENT=1"));
1802        assert!(super::line_refused("  CURSOR_AGENT=1"));
1803        assert!(super::line_refused("CURSOR_AGENT: 1"));
1804        assert!(super::line_refused("Co-authored-by : x"));
1805        assert!(super::line_refused("  Co-authored-by: x"));
1806        assert!(super::line_refused("Made-with : x"));
1807        assert!(super::line_refused(" Made-with: x"));
1808        assert!(!super::line_refused("Note: kept"));
1809        assert!(!super::line_refused("The Signed-off-by line is gone."));
1810        assert!(!super::line_refused("see CURSOR_AGENT in the prose"));
1811        assert!(super::line_refused("\tCo-authored-by: A"));
1812        assert!(super::line_refused("Co-authored-by\t: A"));
1813        assert!(super::line_refused("\tCURSOR_AGENT=1"));
1814        assert!(super::line_refused("CURSOR_AGENT\t=1"));
1815        assert!(!super::line_refused(
1816            "The figures are generated with matplotlib."
1817        ));
1818        assert!(!super::line_refused("Tests: ran cargo test"));
1819        assert!(!super::line_refused("Ask the author by mail."));
1820        assert!(!super::line_refused("Signed-off-by"));
1821    }
1822}