Skip to main content

truth_mirror/
hooks.rs

1//! Hook installation, uninstallation, and dry-run planning.
2
3use std::{
4    fs,
5    io::{self, Read},
6    path::{Path, PathBuf},
7    process::{Command, ExitCode},
8};
9
10use anyhow::{Context, Result, bail};
11
12use crate::{
13    claim,
14    cli::{self, Agent, HookName},
15    gate,
16    reviewer::ReviewQueue,
17    surface::{self, SurfacePlan},
18};
19
20const INSTALLED_HOOKS: &[HookName] =
21    &[HookName::CommitMsg, HookName::PostCommit, HookName::PrePush];
22const MANAGED_MARKER: &str = "# truth-mirror managed hook";
23const MANAGED_END_MARKER: &str = "# truth-mirror hook end";
24const HUSKY_ENTIRE_BRIDGE_MARKER: &str = "# Bridge for the husky+entire chain";
25const FORWARDER_NAME: &str = "_forward-local.sh";
26const OUTER_HOOK_MARKERS: &[&str] = &[
27    "# Entire CLI hooks",
28    HUSKY_ENTIRE_BRIDGE_MARKER,
29    "# truth-mirror managed hook",
30    "exec truth-mirror",
31    "entire hooks git",
32];
33const STATE_GITIGNORE_HEADER: &str = "# truth-mirror runtime state - machine-generated";
34const STATE_GITIGNORE_LINES: &[&str] =
35    &["runs/", "review-queue.jsonl", "tmp/", "logs/", "*.local.*"];
36const FORWARDER_SOURCE: &str = r#"#!/bin/sh
37# _forward-local.sh - delegate to .git/hooks from a committed core.hooksPath.
38# Uses --git-common-dir (resolves to .git/) not core.hooksPath to prevent an infinite loop.
39name="$1"; shift
40git_dir="$(git rev-parse --git-common-dir 2>/dev/null)"
41[ -n "$git_dir" ] || exit 0
42local_hook="$git_dir/hooks/$name"
43if [ -x "$local_hook" ]; then exec "$local_hook" "$@"; fi
44exit 0
45"#;
46
47/// Printed after `--pi` install: Pi only executes project extensions once the
48/// folder is trusted (verified against Pi 0.80.3 `core/project-trust.js`).
49const PI_TRUST_NOTE: &str = "pi: installed .pi/extensions/truth-mirror.js — Pi loads it once you trust this project folder in Pi.";
50
51pub fn run(
52    args: cli::InstallHooksArgs,
53    state_dir: &Path,
54    config_path: Option<&Path>,
55    config: &crate::config::TruthMirrorConfig,
56) -> Result<ExitCode> {
57    let repo_root = git_root()?;
58    let hooks_path = repo_root.join(state_dir).join("hooks");
59    let plan = HookInstallPlan::new(&repo_root, &hooks_path, args.uninstall);
60    // Preserve non-default global flags so the INSTALLED hooks use the same config
61    // and state dir at runtime instead of silently reloading defaults.
62    let global_args = hook_global_args(config_path, &repo_root, state_dir);
63    let plan = HookInstallPlan {
64        global_args,
65        mode: detect_hook_mode(&repo_root, state_dir)?,
66        ..plan
67    };
68    let agents = file_surface_agents(&args);
69    let pi = pi_targeted(&args);
70
71    if args.dry_run {
72        println!("{}", plan.render());
73        for agent in &agents {
74            println!(
75                "surface: {} -> {}",
76                surface::agent_slug(*agent),
77                surface::surface_relative_path(*agent)
78            );
79        }
80        if pi {
81            println!("surface: pi -> {}", surface::PI_EXTENSION_RELATIVE);
82        }
83        return Ok(ExitCode::SUCCESS);
84    }
85
86    let enforcement_enabled = config.enforcement.is_enabled();
87
88    if args.uninstall {
89        uninstall(&plan)?;
90        for agent in &agents {
91            surface::uninstall_enforcement(&repo_root, *agent)?;
92            SurfacePlan::for_agent(&repo_root, *agent).uninstall()?;
93        }
94        if pi {
95            surface::uninstall_pi_extension(&repo_root)?;
96            remove_legacy_pi_hooks(&repo_root)?;
97        }
98    } else {
99        install(&plan, args.inject_forwarder)?;
100        for agent in &agents {
101            SurfacePlan::for_agent(&repo_root, *agent).install()?;
102            // Enforcement is opt-in: only install the tool-blocking hook when the
103            // repo config enables it. Preserve global flags so it uses this config.
104            if enforcement_enabled {
105                surface::install_enforcement(&repo_root, *agent, &plan.global_args)?;
106            }
107        }
108        if args.pi {
109            // Clean any bogus .pi/hooks.json a prior truth-mirror wrote, install the
110            // real project-local extension, and note the one-time trust step.
111            remove_legacy_pi_hooks(&repo_root)?;
112            surface::install_pi_extension(&repo_root)?;
113            println!("{PI_TRUST_NOTE}");
114        }
115    }
116
117    Ok(ExitCode::SUCCESS)
118}
119
120/// File-surface agents (Claude, Codex) touched by this invocation. Install acts
121/// only on explicitly selected agents; a bare `install-hooks --uninstall` clears
122/// all file surfaces so it fully reverses a prior per-agent install.
123fn file_surface_agents(args: &cli::InstallHooksArgs) -> Vec<Agent> {
124    let mut agents = Vec::new();
125    if args.claude {
126        agents.push(Agent::Claude);
127    }
128    if args.codex {
129        agents.push(Agent::Codex);
130    }
131
132    if agents.is_empty() && args.uninstall && !args.pi {
133        return surface::FILE_SURFACE_AGENTS.to_vec();
134    }
135    agents
136}
137
138/// Whether this invocation should act on Pi: explicit `--pi`, or a bare
139/// `--uninstall` (no agent flags) that clears everything including legacy Pi files.
140fn pi_targeted(args: &cli::InstallHooksArgs) -> bool {
141    args.pi || (args.uninstall && !args.claude && !args.codex)
142}
143
144/// Remove a `.pi/hooks.json` left by an earlier (incorrect) truth-mirror version.
145fn remove_legacy_pi_hooks(repo_root: &Path) -> Result<()> {
146    let path = repo_root.join(".pi/hooks.json");
147    if path.is_file() {
148        fs::remove_file(&path)?;
149    }
150    Ok(())
151}
152
153pub fn dispatch(
154    args: cli::HookDispatchArgs,
155    state_dir: &Path,
156    config: &crate::config::TruthMirrorConfig,
157) -> Result<ExitCode> {
158    run_chained_hook(state_dir, args.hook, &args.args)?;
159
160    match args.hook {
161        HookName::CommitMsg => dispatch_commit_msg(state_dir, &args.args, config)?,
162        HookName::PostCommit => dispatch_post_commit(state_dir)?,
163        HookName::PrePush => dispatch_pre_push(state_dir, config)?,
164    }
165
166    Ok(ExitCode::SUCCESS)
167}
168
169#[derive(Clone, Debug, Default, Eq, PartialEq)]
170pub struct HookInstallPlan {
171    pub repo_root: PathBuf,
172    pub hooks_path: PathBuf,
173    pub uninstall: bool,
174    pub mode: HookInstallMode,
175    /// Global CLI flags (`--config`, `--state-dir`) preserved into the shims so a
176    /// custom-config install keeps using that config at hook runtime. Empty for a
177    /// default install (the trailing space is included when non-empty).
178    pub global_args: String,
179}
180
181#[derive(Clone, Debug, Default, Eq, PartialEq)]
182pub enum HookInstallMode {
183    #[default]
184    Plain,
185    LegacyTruthMirrorHooksPath {
186        configured_path: String,
187    },
188    Husky {
189        content_dir: PathBuf,
190    },
191    CustomCommitted {
192        hooks_path: PathBuf,
193    },
194}
195
196impl HookInstallPlan {
197    pub fn new(repo_root: &Path, hooks_path: &Path, uninstall: bool) -> Self {
198        Self {
199            repo_root: repo_root.to_path_buf(),
200            hooks_path: hooks_path.to_path_buf(),
201            uninstall,
202            mode: HookInstallMode::Plain,
203            global_args: String::new(),
204        }
205    }
206
207    pub fn render(&self) -> String {
208        let action = if self.uninstall {
209            "uninstall"
210        } else {
211            "install"
212        };
213        let mut output = format!(
214            "truth-mirror hook plan\nrepo={}\naction={action}\nmode={}\nstateHooks={}\n",
215            self.repo_root.display(),
216            self.mode.as_str(),
217            self.hooks_path.display()
218        );
219        for hook in INSTALLED_HOOKS {
220            output.push_str(&format!(
221                "\nhook={}\npath={}\nbody:\n{}",
222                hook.as_str(),
223                self.active_hook_path(*hook).display(),
224                self.render_hook_body(*hook)
225            ));
226            if let HookInstallMode::Husky { content_dir } = &self.mode {
227                output.push_str(&format!(
228                    "\nbridge={}.pre-entire\npath={}\nbody:\n{}",
229                    hook.as_str(),
230                    husky_entire_bridge_path(content_dir, *hook).display(),
231                    render_husky_entire_bridge(*hook)
232                ));
233            }
234        }
235        output
236    }
237
238    fn active_hook_path(&self, hook: HookName) -> PathBuf {
239        match &self.mode {
240            HookInstallMode::Husky { content_dir } => content_dir.join(hook.as_str()),
241            HookInstallMode::Plain | HookInstallMode::LegacyTruthMirrorHooksPath { .. } => {
242                self.repo_root.join(".git/hooks").join(hook.as_str())
243            }
244            HookInstallMode::CustomCommitted { hooks_path } => hooks_path.join(hook.as_str()),
245        }
246    }
247
248    fn render_hook_body(&self, hook: HookName) -> String {
249        match self.mode {
250            HookInstallMode::Husky { .. } => render_husky_block(hook, &self.global_args),
251            HookInstallMode::CustomCommitted { .. } => render_custom_forwarder_stub(hook),
252            HookInstallMode::Plain | HookInstallMode::LegacyTruthMirrorHooksPath { .. } => {
253                render_shim(hook, &self.global_args)
254            }
255        }
256    }
257}
258
259impl HookInstallMode {
260    fn as_str(&self) -> &'static str {
261        match self {
262            HookInstallMode::Plain => "plain",
263            HookInstallMode::LegacyTruthMirrorHooksPath { .. } => "plain-legacy-truth-mirror",
264            HookInstallMode::Husky { .. } => "husky",
265            HookInstallMode::CustomCommitted { .. } => "custom-committed",
266        }
267    }
268}
269
270/// Build the preserved global-flag prefix (with a trailing space when non-empty).
271fn hook_global_args(config_path: Option<&Path>, repo_root: &Path, state_dir: &Path) -> String {
272    let mut parts = Vec::new();
273    if let Some(config) = config_path {
274        parts.push(format!(
275            "--config {}",
276            quote_git_arg(&absolutize(repo_root, config))
277        ));
278    }
279    if state_dir != Path::new(crate::config::DEFAULT_STATE_DIR) {
280        parts.push(format!(
281            "--state-dir {}",
282            quote_git_arg(&absolutize(repo_root, state_dir))
283        ));
284    }
285    if parts.is_empty() {
286        String::new()
287    } else {
288        format!("{} ", parts.join(" "))
289    }
290}
291
292fn absolutize(repo_root: &Path, path: &Path) -> PathBuf {
293    if path.is_absolute() {
294        path.to_path_buf()
295    } else {
296        repo_root.join(path)
297    }
298}
299
300/// POSIX single-quote escaping for a path embedded in the generated `/bin/sh`
301/// shim: wrap in single quotes and replace any embedded single quote with `'\''`
302/// so no metacharacter (`;`, `$()`, `'`, spaces, …) can break or inject shell.
303fn quote_git_arg(path: &Path) -> String {
304    let value = path.to_string_lossy();
305    format!("'{}'", value.replace('\'', "'\\''"))
306}
307
308pub fn render_shim(hook: HookName, global_args: &str) -> String {
309    format!(
310        "#!/bin/sh\n{MANAGED_MARKER}\nexec truth-mirror {global_args}hook-dispatch {} \"$@\"\n",
311        hook.as_str()
312    )
313}
314
315fn render_husky_block(hook: HookName, global_args: &str) -> String {
316    format!(
317        "{MANAGED_MARKER}\nif command -v truth-mirror >/dev/null 2>&1; then truth-mirror {global_args}hook-dispatch {} \"$@\"; else :; fi\n{MANAGED_END_MARKER}\n",
318        hook.as_str()
319    )
320}
321
322fn render_husky_entire_bridge(hook: HookName) -> String {
323    format!(
324        "#!/bin/sh\n{HUSKY_ENTIRE_BRIDGE_MARKER}\nexec \"$(dirname \"$0\")/{}\" \"$@\"\n",
325        hook.as_str()
326    )
327}
328
329fn render_custom_forwarder_stub(hook: HookName) -> String {
330    format!(
331        "#!/bin/sh\n{MANAGED_MARKER}\nexec \"$(dirname \"$0\")/{FORWARDER_NAME}\" {} \"$@\"\n",
332        hook.as_str()
333    )
334}
335
336fn detect_hook_mode(repo_root: &Path, state_dir: &Path) -> Result<HookInstallMode> {
337    let Some(configured) = git_config_get(repo_root, "core.hooksPath")? else {
338        return Ok(HookInstallMode::Plain);
339    };
340    let configured = configured.trim().to_owned();
341    if configured.is_empty() {
342        return Ok(HookInstallMode::Plain);
343    }
344    if is_managed_hooks_path(repo_root, state_dir, &configured) {
345        return Ok(HookInstallMode::LegacyTruthMirrorHooksPath {
346            configured_path: configured,
347        });
348    }
349    if configured.contains(".husky") {
350        let hooks_path = repo_relative_path(repo_root, Path::new(&configured));
351        let content_dir = if hooks_path.file_name().and_then(|name| name.to_str()) == Some("_") {
352            hooks_path
353                .parent()
354                .map_or_else(|| repo_root.join(".husky"), Path::to_path_buf)
355        } else {
356            hooks_path
357        };
358        return Ok(HookInstallMode::Husky { content_dir });
359    }
360    Ok(HookInstallMode::CustomCommitted {
361        hooks_path: repo_relative_path(repo_root, Path::new(&configured)),
362    })
363}
364
365fn repo_relative_path(repo_root: &Path, path: &Path) -> PathBuf {
366    if path.is_absolute() {
367        path.to_path_buf()
368    } else {
369        repo_root.join(path)
370    }
371}
372
373fn is_managed_hooks_path(repo_root: &Path, state_dir: &Path, configured: &str) -> bool {
374    [
375        state_dir.join("hooks"),
376        PathBuf::from(crate::config::DEFAULT_STATE_DIR).join("hooks"),
377        PathBuf::from(crate::config::LEGACY_STATE_DIR).join("hooks"),
378    ]
379    .iter()
380    .any(|candidate| path_config_matches(repo_root, candidate, configured))
381}
382
383fn path_config_matches(repo_root: &Path, candidate: &Path, configured: &str) -> bool {
384    let candidate_string = candidate.to_string_lossy().into_owned();
385    let absolute_string = repo_root.join(candidate).to_string_lossy().into_owned();
386    configured == candidate_string || configured == absolute_string
387}
388
389fn install(plan: &HookInstallPlan, inject_forwarder: bool) -> Result<()> {
390    match &plan.mode {
391        HookInstallMode::Plain => {
392            prepare_state_hooks(plan)?;
393            install_plain(plan)
394        }
395        HookInstallMode::LegacyTruthMirrorHooksPath { .. } => {
396            prepare_state_hooks(plan)?;
397            unset_core_hooks_path(&plan.repo_root)?;
398            install_plain(plan)
399        }
400        HookInstallMode::Husky { content_dir } => {
401            prepare_state_hooks(plan)?;
402            install_husky(plan, content_dir)
403        }
404        HookInstallMode::CustomCommitted { hooks_path } => {
405            install_custom(plan, hooks_path, inject_forwarder)
406        }
407    }
408}
409
410fn uninstall(plan: &HookInstallPlan) -> Result<()> {
411    match &plan.mode {
412        HookInstallMode::Plain => uninstall_plain(plan)?,
413        HookInstallMode::LegacyTruthMirrorHooksPath { .. } => {
414            unset_core_hooks_path(&plan.repo_root)?;
415            uninstall_plain(plan)?;
416        }
417        HookInstallMode::Husky { content_dir } => uninstall_husky(plan, content_dir)?,
418        HookInstallMode::CustomCommitted { hooks_path } => {
419            uninstall_plain(plan)?;
420            uninstall_custom_forwarders(hooks_path)?;
421        }
422    }
423
424    if plan.hooks_path.exists() {
425        fs::remove_dir_all(&plan.hooks_path)?;
426    }
427    Ok(())
428}
429
430fn state_dir_from_hooks_path(hooks_path: &Path) -> &Path {
431    hooks_path.parent().unwrap_or(hooks_path)
432}
433
434fn prepare_state_hooks(plan: &HookInstallPlan) -> Result<()> {
435    ensure_state_gitignore(&plan.repo_root, state_dir_from_hooks_path(&plan.hooks_path))?;
436    fs::create_dir_all(&plan.hooks_path)?;
437    fs::create_dir_all(plan.hooks_path.join("chained"))?;
438    clear_chained_hooks(plan)
439}
440
441fn install_plain(plan: &HookInstallPlan) -> Result<()> {
442    let git_hooks = plan.repo_root.join(".git/hooks");
443    fs::create_dir_all(&git_hooks)?;
444    for hook in INSTALLED_HOOKS {
445        install_local_hook(plan, &git_hooks, *hook)?;
446    }
447    Ok(())
448}
449
450fn install_local_hook(plan: &HookInstallPlan, git_hooks: &Path, hook: HookName) -> Result<()> {
451    let active = git_hooks.join(hook.as_str());
452    let backup = backup_path(&active, "pre-truth-mirror");
453    let chained = plan.hooks_path.join("chained").join(hook.as_str());
454    remove_file_if_exists(&chained)?;
455
456    let source = local_hook_source(&active, &backup)?;
457    if let Some(source) = source {
458        if source.path != backup {
459            fs::copy(&source.path, &backup)?;
460            make_executable(&backup)?;
461        }
462        if !has_outer_hook_marker(&source.content) {
463            fs::copy(&source.path, &chained)?;
464            make_executable(&chained)?;
465        }
466    }
467
468    fs::write(&active, render_shim(hook, &plan.global_args))?;
469    make_executable(&active)?;
470    Ok(())
471}
472
473fn uninstall_plain(plan: &HookInstallPlan) -> Result<()> {
474    let git_hooks = plan.repo_root.join(".git/hooks");
475    for hook in INSTALLED_HOOKS {
476        let active = git_hooks.join(hook.as_str());
477        let backup = backup_path(&active, "pre-truth-mirror");
478        let active_content = read_to_string_if_file(&active)?;
479        if active_content
480            .as_deref()
481            .is_some_and(is_truth_mirror_managed)
482        {
483            if backup.is_file() {
484                fs::copy(&backup, &active)?;
485                make_executable(&active)?;
486                fs::remove_file(&backup)?;
487            } else {
488                remove_file_if_exists(&active)?;
489            }
490        }
491        remove_file_if_exists(&plan.hooks_path.join("chained").join(hook.as_str()))?;
492    }
493    Ok(())
494}
495
496fn install_husky(plan: &HookInstallPlan, content_dir: &Path) -> Result<()> {
497    fs::create_dir_all(content_dir)?;
498    for hook in INSTALLED_HOOKS {
499        let target = content_dir.join(hook.as_str());
500        let block = render_husky_block(*hook, &plan.global_args);
501        let next = match read_to_string_if_file(&target)? {
502            Some(content) => append_managed_block(&content, &block),
503            None => format!("#!/bin/sh\n{block}"),
504        };
505        fs::write(&target, next)?;
506        make_executable(&target)?;
507        install_husky_entire_bridge(content_dir, *hook)?;
508    }
509    Ok(())
510}
511
512fn install_husky_entire_bridge(content_dir: &Path, hook: HookName) -> Result<()> {
513    let target = husky_entire_bridge_path(content_dir, hook);
514    let backup = backup_path(&target, "pre-truth-mirror");
515    if let Some(content) = read_to_string_if_file(&target)?
516        && !is_husky_entire_bridge(&content)
517    {
518        fs::copy(&target, &backup)?;
519        make_executable(&backup)?;
520    }
521    fs::write(&target, render_husky_entire_bridge(hook))?;
522    make_executable(&target)?;
523    Ok(())
524}
525
526fn uninstall_husky(_plan: &HookInstallPlan, content_dir: &Path) -> Result<()> {
527    for hook in INSTALLED_HOOKS {
528        let target = content_dir.join(hook.as_str());
529        if let Some(content) = read_to_string_if_file(&target)? {
530            let next = remove_managed_block(&content);
531            if is_empty_or_shebang_only(&next) {
532                fs::remove_file(&target)?;
533            } else {
534                fs::write(&target, next)?;
535                make_executable(&target)?;
536            }
537        }
538        uninstall_husky_entire_bridge(content_dir, *hook)?;
539    }
540    Ok(())
541}
542
543fn uninstall_husky_entire_bridge(content_dir: &Path, hook: HookName) -> Result<()> {
544    let target = husky_entire_bridge_path(content_dir, hook);
545    let backup = backup_path(&target, "pre-truth-mirror");
546    match read_to_string_if_file(&target)? {
547        Some(content) if is_husky_entire_bridge(&content) => {
548            if backup.is_file() {
549                fs::copy(&backup, &target)?;
550                make_executable(&target)?;
551                fs::remove_file(&backup)?;
552            } else {
553                remove_file_if_exists(&target)?;
554            }
555        }
556        None if backup.is_file() => {
557            fs::copy(&backup, &target)?;
558            make_executable(&target)?;
559            fs::remove_file(&backup)?;
560        }
561        _ => {}
562    }
563    Ok(())
564}
565
566fn husky_entire_bridge_path(content_dir: &Path, hook: HookName) -> PathBuf {
567    content_dir.join(format!("{}.pre-entire", hook.as_str()))
568}
569
570fn install_custom(plan: &HookInstallPlan, hooks_path: &Path, inject_forwarder: bool) -> Result<()> {
571    let missing_forwarder = INSTALLED_HOOKS
572        .iter()
573        .any(|hook| !custom_forwarder_present(hooks_path, *hook));
574    if missing_forwarder && !inject_forwarder {
575        bail!(
576            "truth-mirror: core.hooksPath is set to '{}' (a non-husky committed directory).\nTo install, either:\n  (a) run `truth-mirror install-hooks --inject-forwarder` to write a _forward-local.sh forwarder into that directory (a committed repo change), or\n  (b) unset core.hooksPath and re-run install-hooks",
577            hooks_path.display()
578        );
579    }
580
581    if inject_forwarder {
582        inject_custom_forwarders(hooks_path)?;
583    }
584
585    prepare_state_hooks(plan)?;
586    let git_hooks = plan.repo_root.join(".git/hooks");
587    fs::create_dir_all(&git_hooks)?;
588    for hook in INSTALLED_HOOKS {
589        install_local_hook(plan, &git_hooks, *hook)?;
590    }
591    Ok(())
592}
593
594fn inject_custom_forwarders(hooks_path: &Path) -> Result<()> {
595    fs::create_dir_all(hooks_path)?;
596    let forwarder = hooks_path.join(FORWARDER_NAME);
597    fs::write(&forwarder, FORWARDER_SOURCE)?;
598    make_executable(&forwarder)?;
599
600    for hook in INSTALLED_HOOKS {
601        let target = hooks_path.join(hook.as_str());
602        if custom_forwarder_present(hooks_path, *hook) {
603            continue;
604        }
605        if target.is_file() {
606            fs::copy(&target, backup_path(&target, "pre-truth-mirror"))?;
607        }
608        fs::write(&target, render_custom_forwarder_stub(*hook))?;
609        make_executable(&target)?;
610    }
611    eprintln!(
612        "hint: commit the truth-mirror forwarder changes in {}",
613        hooks_path.display()
614    );
615    Ok(())
616}
617
618fn uninstall_custom_forwarders(hooks_path: &Path) -> Result<()> {
619    for hook in INSTALLED_HOOKS {
620        let target = hooks_path.join(hook.as_str());
621        let backup = backup_path(&target, "pre-truth-mirror");
622        let content = read_to_string_if_file(&target)?;
623        if content.as_deref().is_some_and(is_truth_mirror_managed) {
624            if backup.is_file() {
625                fs::copy(&backup, &target)?;
626                make_executable(&target)?;
627                fs::remove_file(&backup)?;
628            } else {
629                remove_file_if_exists(&target)?;
630            }
631        }
632    }
633    let forwarder = hooks_path.join(FORWARDER_NAME);
634    if read_to_string_if_file(&forwarder)?.as_deref() == Some(FORWARDER_SOURCE) {
635        fs::remove_file(forwarder)?;
636    }
637    Ok(())
638}
639
640fn append_managed_block(content: &str, block: &str) -> String {
641    let mut next = remove_managed_block(content);
642    if !next.ends_with('\n') {
643        next.push('\n');
644    }
645    next.push_str(block);
646    next
647}
648
649fn remove_managed_block(content: &str) -> String {
650    let mut out = Vec::new();
651    let mut skipping = false;
652    for line in content.lines() {
653        if line == MANAGED_MARKER {
654            skipping = true;
655            continue;
656        }
657        if skipping {
658            if line == MANAGED_END_MARKER {
659                skipping = false;
660            }
661            continue;
662        }
663        out.push(line);
664    }
665    if out.is_empty() {
666        String::new()
667    } else {
668        format!("{}\n", out.join("\n"))
669    }
670}
671
672fn is_empty_or_shebang_only(content: &str) -> bool {
673    let lines = content
674        .lines()
675        .map(str::trim)
676        .filter(|line| !line.is_empty())
677        .collect::<Vec<_>>();
678    lines.is_empty() || lines == ["#!/bin/sh"]
679}
680
681#[derive(Debug)]
682struct LocalHookSource {
683    path: PathBuf,
684    content: String,
685}
686
687fn local_hook_source(active: &Path, backup: &Path) -> Result<Option<LocalHookSource>> {
688    let Some(active_content) = read_to_string_if_file(active)? else {
689        return Ok(None);
690    };
691    if is_truth_mirror_managed(&active_content) {
692        return read_to_string_if_file(backup)?.map_or(Ok(None), |content| {
693            Ok(Some(LocalHookSource {
694                path: backup.to_path_buf(),
695                content,
696            }))
697        });
698    }
699    Ok(Some(LocalHookSource {
700        path: active.to_path_buf(),
701        content: active_content,
702    }))
703}
704
705fn custom_forwarder_present(hooks_path: &Path, hook: HookName) -> bool {
706    read_to_string_if_file(&hooks_path.join(hook.as_str()))
707        .ok()
708        .flatten()
709        .is_some_and(|content| {
710            content.contains("--git-common-dir")
711                || content.contains(FORWARDER_NAME)
712                || is_truth_mirror_managed(&content)
713        })
714}
715
716fn ensure_state_gitignore(repo_root: &Path, state_dir: &Path) -> Result<()> {
717    let state_dir = absolutize(repo_root, state_dir);
718    fs::create_dir_all(&state_dir)?;
719    let gitignore = state_dir.join(".gitignore");
720    let mut content = read_to_string_if_file(&gitignore)?.unwrap_or_default();
721    if content.is_empty() {
722        content.push_str(STATE_GITIGNORE_HEADER);
723        content.push('\n');
724    }
725    for line in STATE_GITIGNORE_LINES {
726        if !content.lines().any(|existing| existing.trim() == *line) {
727            if !content.ends_with('\n') {
728                content.push('\n');
729            }
730            content.push_str(line);
731            content.push('\n');
732        }
733    }
734    fs::write(&gitignore, content)?;
735    print_tracked_runtime_hints(repo_root, &state_dir)?;
736    Ok(())
737}
738
739fn print_tracked_runtime_hints(repo_root: &Path, state_dir: &Path) -> Result<()> {
740    let rel_state = state_dir.strip_prefix(repo_root).unwrap_or(state_dir);
741    for path in [
742        rel_state.join("review-queue.jsonl"),
743        rel_state.join("runs"),
744        rel_state.join("tmp"),
745        rel_state.join("logs"),
746    ] {
747        let output = Command::new("git")
748            .args(["ls-files", "--"])
749            .arg(&path)
750            .current_dir(repo_root)
751            .output()?;
752        if output.status.success() {
753            for tracked in String::from_utf8_lossy(&output.stdout)
754                .lines()
755                .filter(|line| !line.trim().is_empty())
756            {
757                eprintln!("hint: run: git rm --cached {tracked}");
758            }
759        }
760    }
761    Ok(())
762}
763
764fn clear_chained_hooks(plan: &HookInstallPlan) -> Result<()> {
765    for hook in INSTALLED_HOOKS {
766        remove_file_if_exists(&plan.hooks_path.join("chained").join(hook.as_str()))?;
767    }
768    Ok(())
769}
770
771fn has_outer_hook_marker(content: &str) -> bool {
772    content.lines().take(20).any(|line| {
773        OUTER_HOOK_MARKERS
774            .iter()
775            .any(|marker| line.contains(marker))
776    })
777}
778
779fn is_truth_mirror_managed(content: &str) -> bool {
780    content.contains(MANAGED_MARKER)
781        || content.contains(HUSKY_ENTIRE_BRIDGE_MARKER)
782        || content.contains("exec truth-mirror")
783}
784
785fn is_husky_entire_bridge(content: &str) -> bool {
786    content.contains(HUSKY_ENTIRE_BRIDGE_MARKER)
787}
788
789fn backup_path(path: &Path, suffix: &str) -> PathBuf {
790    let file_name = path
791        .file_name()
792        .and_then(|name| name.to_str())
793        .unwrap_or("hook");
794    path.with_file_name(format!("{file_name}.{suffix}"))
795}
796
797fn read_to_string_if_file(path: &Path) -> Result<Option<String>> {
798    match fs::read_to_string(path) {
799        Ok(content) => Ok(Some(content)),
800        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
801        Err(error) => Err(error.into()),
802    }
803}
804
805fn remove_file_if_exists(path: &Path) -> Result<()> {
806    match fs::remove_file(path) {
807        Ok(()) => Ok(()),
808        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
809        Err(error) => Err(error.into()),
810    }
811}
812
813fn unset_core_hooks_path(repo_root: &Path) -> Result<()> {
814    let status = Command::new("git")
815        .args(["config", "--unset", "core.hooksPath"])
816        .current_dir(repo_root)
817        .status()?;
818    if !status.success() {
819        // Git exits non-zero when the key is already absent; migration should be idempotent.
820        return Ok(());
821    }
822    Ok(())
823}
824
825fn dispatch_commit_msg(
826    state_dir: &Path,
827    args: &[String],
828    config: &crate::config::TruthMirrorConfig,
829) -> Result<()> {
830    let commit_msg_path = args
831        .first()
832        .context("commit-msg hook requires COMMIT_EDITMSG path")?;
833    let commit_message = fs::read_to_string(commit_msg_path)?;
834    let diff = git_stdout(&["diff", "--cached"])?;
835    let claim_file = fs::read_to_string(state_dir.join("claim.txt")).ok();
836    let policy = config.gates.to_policy();
837    claim::evaluate_commit_message(&commit_message, claim_file.as_deref(), Some(&diff), &policy)?;
838    Ok(())
839}
840
841fn dispatch_post_commit(state_dir: &Path) -> Result<()> {
842    let sha = git_stdout(&["rev-parse", "HEAD"])?;
843    ReviewQueue::new(state_dir).enqueue(sha.trim())?;
844    Ok(())
845}
846
847fn dispatch_pre_push(state_dir: &Path, config: &crate::config::TruthMirrorConfig) -> Result<()> {
848    let mut stdin = String::new();
849    io::stdin().read_to_string(&mut stdin)?;
850    for line in stdin.lines() {
851        if let Some(range) = pre_push_range_from_line(line) {
852            gate::run(
853                cli::GateArgs {
854                    pre_push: Some(range),
855                    commit_msg: None,
856                    claim_file: None,
857                    diff_file: None,
858                    fake_markers: Vec::new(),
859                    pre_tool_use: false,
860                    tool: None,
861                },
862                state_dir,
863                config,
864            )?;
865        }
866    }
867    Ok(())
868}
869
870fn pre_push_range_from_line(line: &str) -> Option<String> {
871    let parts = line.split_whitespace().collect::<Vec<_>>();
872    let local_sha = parts.get(1)?;
873    let remote_sha = parts.get(3)?;
874    if is_zero_sha(local_sha) {
875        return None;
876    }
877
878    if is_zero_sha(remote_sha) {
879        Some((*local_sha).to_owned())
880    } else {
881        Some(format!("{remote_sha}..{local_sha}"))
882    }
883}
884
885fn is_zero_sha(value: &str) -> bool {
886    value.chars().all(|character| character == '0')
887}
888
889fn run_chained_hook(state_dir: &Path, hook: HookName, args: &[String]) -> Result<()> {
890    let chained = state_dir.join("hooks/chained").join(hook.as_str());
891    if !chained.is_file() {
892        return Ok(());
893    }
894    let content = fs::read_to_string(&chained)?;
895    if has_outer_hook_marker(&content) {
896        eprintln!(
897            "truth-mirror: skipping unsafe chained hook {} because it appears to invoke an outer hook manager",
898            chained.display()
899        );
900        return Ok(());
901    }
902
903    let status = Command::new(&chained).args(args).status()?;
904    if !status.success() {
905        bail!(
906            "chained hook {} failed with status {status}",
907            chained.display()
908        );
909    }
910    Ok(())
911}
912
913fn git_root() -> Result<PathBuf> {
914    Ok(PathBuf::from(
915        git_stdout(&["rev-parse", "--show-toplevel"])?.trim(),
916    ))
917}
918
919fn git_stdout(args: &[&str]) -> Result<String> {
920    let output = Command::new("git").args(args).output()?;
921    if !output.status.success() {
922        bail!(
923            "git {} failed: {}",
924            args.join(" "),
925            String::from_utf8_lossy(&output.stderr)
926        );
927    }
928    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
929}
930
931fn git_config_get(repo_root: &Path, key: &str) -> Result<Option<String>> {
932    let output = Command::new("git")
933        .args(["config", "--get", key])
934        .current_dir(repo_root)
935        .output()?;
936    if output.status.success() {
937        return Ok(Some(String::from_utf8_lossy(&output.stdout).into_owned()));
938    }
939    if output.status.code() == Some(1) {
940        return Ok(None);
941    }
942    bail!(
943        "git config --get {key} failed: {}",
944        String::from_utf8_lossy(&output.stderr)
945    );
946}
947
948#[cfg(unix)]
949fn make_executable(path: &Path) -> Result<()> {
950    use std::os::unix::fs::PermissionsExt;
951
952    let mut permissions = fs::metadata(path)?.permissions();
953    permissions.set_mode(0o755);
954    fs::set_permissions(path, permissions)?;
955    Ok(())
956}
957
958#[cfg(not(unix))]
959fn make_executable(_path: &Path) -> Result<()> {
960    Ok(())
961}
962
963#[cfg(test)]
964mod tests {
965    use proptest::prelude::*;
966
967    use super::{HookInstallMode, HookInstallPlan, pre_push_range_from_line, render_shim};
968    use crate::cli::HookName;
969
970    #[test]
971    fn hook_shim_is_only_exec_delegation() {
972        let shim = render_shim(HookName::CommitMsg, "");
973        let lines = shim.lines().collect::<Vec<_>>();
974
975        assert_eq!(lines.len(), 3);
976        assert_eq!(lines[0], "#!/bin/sh");
977        assert_eq!(lines[1], super::MANAGED_MARKER);
978        assert_eq!(
979            lines[2],
980            "exec truth-mirror hook-dispatch commit-msg \"$@\""
981        );
982    }
983
984    #[test]
985    fn quote_git_arg_escapes_shell_metacharacters() {
986        use std::path::Path;
987        assert_eq!(super::quote_git_arg(Path::new("/a/b.toml")), "'/a/b.toml'");
988        // metacharacters are neutralized by single-quoting
989        assert_eq!(
990            super::quote_git_arg(Path::new("/a/c;$(touch x).toml")),
991            "'/a/c;$(touch x).toml'"
992        );
993        // an embedded single quote is escaped as '\''
994        assert_eq!(
995            super::quote_git_arg(Path::new("/a/it's.toml")),
996            "'/a/it'\\''s.toml'"
997        );
998    }
999
1000    #[test]
1001    fn hook_shim_preserves_global_args() {
1002        let shim = render_shim(HookName::PrePush, "--config /abs/enforce.toml ");
1003        let lines = shim.lines().collect::<Vec<_>>();
1004
1005        assert_eq!(lines.len(), 3, "shim stays <=3 lines + exec-only");
1006        assert_eq!(
1007            lines[2],
1008            "exec truth-mirror --config /abs/enforce.toml hook-dispatch pre-push \"$@\""
1009        );
1010    }
1011
1012    #[test]
1013    fn husky_entire_bridge_is_only_exec_delegation() {
1014        let bridge = super::render_husky_entire_bridge(HookName::CommitMsg);
1015        let lines = bridge.lines().collect::<Vec<_>>();
1016
1017        assert_eq!(lines.len(), 3);
1018        assert_eq!(lines[0], "#!/bin/sh");
1019        assert_eq!(lines[1], super::HUSKY_ENTIRE_BRIDGE_MARKER);
1020        assert_eq!(lines[2], "exec \"$(dirname \"$0\")/commit-msg\" \"$@\"");
1021    }
1022
1023    #[test]
1024    fn dry_run_plan_names_hooks_and_hooks_path() {
1025        let plan = HookInstallPlan::new(
1026            std::path::Path::new("/repo"),
1027            std::path::Path::new("/repo/.truth/hooks"),
1028            false,
1029        );
1030        let rendered = plan.render();
1031
1032        assert!(rendered.contains("commit-msg"));
1033        assert!(rendered.contains("post-commit"));
1034        assert!(rendered.contains("pre-push"));
1035        assert!(rendered.contains("stateHooks=/repo/.truth/hooks"));
1036        assert!(rendered.contains("path=/repo/.git/hooks/commit-msg"));
1037        assert!(rendered.contains("body:\n#!/bin/sh\n# truth-mirror managed hook"));
1038    }
1039
1040    #[test]
1041    fn husky_dry_run_plan_names_entire_bridge_paths() {
1042        let mut plan = HookInstallPlan::new(
1043            std::path::Path::new("/repo"),
1044            std::path::Path::new("/repo/.truth/hooks"),
1045            false,
1046        );
1047        plan.mode = HookInstallMode::Husky {
1048            content_dir: std::path::PathBuf::from("/repo/.husky"),
1049        };
1050        let rendered = plan.render();
1051
1052        assert!(rendered.contains("bridge=commit-msg.pre-entire"));
1053        assert!(rendered.contains("path=/repo/.husky/commit-msg.pre-entire"));
1054        assert!(rendered.contains(super::HUSKY_ENTIRE_BRIDGE_MARKER));
1055    }
1056
1057    #[test]
1058    fn managed_block_replace_is_idempotent() {
1059        let block = super::render_husky_block(HookName::CommitMsg, "");
1060        let original = "#!/bin/sh\necho before\n";
1061        let once = super::append_managed_block(original, &block);
1062        let twice = super::append_managed_block(&once, &block);
1063
1064        assert_eq!(twice.matches(super::MANAGED_MARKER).count(), 1);
1065        assert!(twice.contains("echo before"));
1066    }
1067
1068    #[test]
1069    fn chained_hook_safety_filter_detects_outer_tools() {
1070        assert!(super::has_outer_hook_marker(
1071            "#!/bin/sh\n# Entire CLI hooks\nentire hooks git commit-msg\n"
1072        ));
1073        assert!(super::has_outer_hook_marker(
1074            "#!/bin/sh\n# truth-mirror managed hook\nexec truth-mirror hook-dispatch commit-msg \"$@\"\n"
1075        ));
1076        assert!(!super::has_outer_hook_marker("#!/bin/sh\necho safe\n"));
1077    }
1078
1079    #[test]
1080    fn run_chained_hook_skips_marker_bearing_stale_hook() {
1081        let temp = tempfile::tempdir().unwrap();
1082        let chained = temp.path().join("hooks/chained/commit-msg");
1083        std::fs::create_dir_all(chained.parent().unwrap()).unwrap();
1084        std::fs::write(&chained, "#!/bin/sh\n# Entire CLI hooks\nexit 42\n").unwrap();
1085        super::make_executable(&chained).unwrap();
1086
1087        super::run_chained_hook(temp.path(), HookName::CommitMsg, &[]).unwrap();
1088    }
1089
1090    #[test]
1091    fn pre_push_line_maps_to_git_range() {
1092        let line = "refs/heads/main abc123 refs/heads/main def456";
1093
1094        assert_eq!(
1095            pre_push_range_from_line(line),
1096            Some("def456..abc123".to_owned())
1097        );
1098    }
1099
1100    proptest! {
1101        #[test]
1102        fn hook_shim_rendering_stays_tiny_exec_only(index in 0usize..3) {
1103            let hook = [HookName::CommitMsg, HookName::PostCommit, HookName::PrePush][index];
1104            let shim = render_shim(hook, "");
1105            let lines = shim.lines().collect::<Vec<_>>();
1106
1107            prop_assert_eq!(lines.len(), 3);
1108            prop_assert_eq!(lines[0], "#!/bin/sh");
1109            prop_assert_eq!(lines[1], super::MANAGED_MARKER);
1110            prop_assert!(lines[2].starts_with("exec truth-mirror hook-dispatch "));
1111            prop_assert!(lines[2].contains(hook.as_str()));
1112            prop_assert_eq!(shim.matches(super::MANAGED_MARKER).count(), 1);
1113            prop_assert_eq!(shim.matches("exec truth-mirror").count(), 1);
1114        }
1115
1116        #[test]
1117        fn husky_entire_bridge_rendering_stays_tiny_exec_only(index in 0usize..3) {
1118            let hook = [HookName::CommitMsg, HookName::PostCommit, HookName::PrePush][index];
1119            let bridge = super::render_husky_entire_bridge(hook);
1120            let lines = bridge.lines().collect::<Vec<_>>();
1121
1122            prop_assert_eq!(lines.len(), 3);
1123            prop_assert_eq!(lines[0], "#!/bin/sh");
1124            prop_assert_eq!(lines[1], super::HUSKY_ENTIRE_BRIDGE_MARKER);
1125            prop_assert_eq!(lines[2], format!("exec \"$(dirname \"$0\")/{}\" \"$@\"", hook.as_str()));
1126            prop_assert_eq!(bridge.matches(super::HUSKY_ENTIRE_BRIDGE_MARKER).count(), 1);
1127            prop_assert_eq!(bridge.matches("exec ").count(), 1);
1128        }
1129    }
1130}