truth-mirror 0.13.1

Truthfulness gate and adversarial reviewer harness for AI coding agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
//! Read-only repository status and wiring diagnostics.

use std::{
    fs,
    path::{Component, Path, PathBuf},
    process::{Command, ExitCode},
};

use anyhow::{Context, Result};

use crate::{
    cli,
    hooks::{FORWARDER_NAME, FORWARDER_SOURCE, MANAGED_MARKER},
    ledger::LedgerStore,
    provenance,
    reviewer::{ReviewQueue, ReviewRunStore},
    watcher,
};

const HOOKS: &[&str] = &["commit-msg", "post-commit", "pre-push"];

pub fn run(
    _args: cli::StatusArgs,
    state_dir: &Path,
    config_path: Option<&Path>,
) -> Result<ExitCode> {
    let repo_root = git_root().context("this command requires a Git repository")?;
    let resolved_state_dir = repo_relative_path(&repo_root, state_dir);
    let hook_status = inspect_hook_status(&repo_root, state_dir);
    let review_queue = ReviewQueue::new(&resolved_state_dir);
    let queue = review_queue.summary();
    let run_store = ReviewRunStore::new(&resolved_state_dir);
    let run_counts = run_store.status_counts();
    let scheduler = match review_queue.pending_read_only() {
        Ok(pending) => {
            let batch_ids = pending.into_iter().filter_map(|item| item.batch_id);
            run_store.scheduler_status_read_only(
                watcher::live_watcher_pid(&resolved_state_dir),
                batch_ids,
            )
        }
        Err(error) => Err(error),
    };
    // Best-effort config read: status deliberately runs before the CLI's
    // mandatory config load, so a broken config must degrade to a warning
    // line here rather than take the whole status report down with it. The
    // repo-resolved state dir is used so a relative --state-dir finds the
    // same config.toml the hooks use even from a nested cwd.
    let loaded_config =
        crate::config::TruthMirrorConfig::load_for_cli(config_path, &resolved_state_dir);
    let reviewer_timeout = loaded_config
        .as_ref()
        .map(|config| config.reviewer.timeout());
    // The status line must report the same set that blocks pre-push and
    // reinjection (open REJECTs + needs-human escalations) — the narrower
    // unresolved set could say "0" while the next push is refused.
    let blocking = LedgerStore::new(&resolved_state_dir).blocking_rejections();

    println!("repo: {}", repo_root.display());
    match hook_status {
        Ok(hook_status) => {
            println!("hook_mode: {}", hook_status.mode);
            for hook in hook_status.hooks {
                let state = if hook.installed {
                    "installed"
                } else {
                    "missing"
                };
                println!("hook {}: {} path={}", hook.name, state, hook.path.display());
            }
        }
        Err(error) => println!(
            "hook_mode: unavailable warning={}",
            single_line_error(error.as_ref())
        ),
    }

    match queue {
        Ok(queue) => {
            let oldest = queue
                .oldest_age_secs_at(crate::time::unix_now())
                .map_or_else(|| "none".to_owned(), |age| format!("{age}s"));
            println!("queue: pending={} oldest_age={oldest}", queue.pending_count);
        }
        Err(error) => println!("queue: unavailable warning={}", single_line_error(&error)),
    }

    match run_counts {
        Ok(run_counts) => {
            let warning = if run_counts.skipped_records == 0 {
                String::new()
            } else {
                format!(" warning=skipped_records:{}", run_counts.skipped_records)
            };
            println!(
                "review_runs: queued={} running={} completed={} failed={} cancelled={}{}",
                run_counts.queued,
                run_counts.running,
                run_counts.completed,
                run_counts.failed,
                run_counts.cancelled,
                warning
            );
        }
        Err(error) => println!(
            "review_runs: unavailable warning={}",
            single_line_error(&error)
        ),
    }
    match reviewer_timeout {
        Ok(Some(duration)) => println!("reviewer_timeout: {}s", duration.as_secs()),
        Ok(None) => println!("reviewer_timeout: disabled"),
        Err(error) => println!(
            "reviewer_timeout: unavailable warning={}",
            single_line_error(&error)
        ),
    }
    match &loaded_config {
        Ok(config) => match crate::memory_skill::memory_skill_status(&resolved_state_dir, config) {
            Ok(memory_status) => {
                println!(
                    "memory_skill: pending_candidates={} pending_advisories={} near_miss_clusters={}",
                    memory_status.pending_candidates,
                    memory_status.pending_advisories,
                    memory_status.near_misses.len()
                );
                for near_miss in memory_status.near_misses {
                    println!(
                        "memory_skill_near_miss: kind={} verdict={} occurrences={} commits={} learning={}",
                        near_miss.candidate_kind,
                        near_miss.truth_label,
                        near_miss.occurrence_count,
                        near_miss.source_commits.join(","),
                        quote_status_field(&near_miss.learning_key)
                    );
                }
            }
            Err(error) => println!(
                "memory_skill: unavailable warning={}",
                single_line_error(&error)
            ),
        },
        Err(error) => println!(
            "memory_skill: unavailable warning={}",
            single_line_error(error)
        ),
    }
    // Read-only liveness view: dead-worker `running` rows are counted (never
    // persisted here — reconciliation is ensure-watcher/watch's job).
    match ReviewRunStore::new(&resolved_state_dir).stale_running_count() {
        Ok(0) => println!("review_run_liveness: ok"),
        Ok(stale) => println!(
            "review_run_liveness: stale_running={stale} (dead worker pid; ensure-watcher/watch reconciles)"
        ),
        Err(error) => println!(
            "review_run_liveness: unavailable warning={}",
            single_line_error(&error)
        ),
    }
    match scheduler {
        Ok(snapshot) => {
            let owner = snapshot
                .owner_pid
                .map_or_else(|| "none".to_owned(), |pid| pid.to_string());
            println!(
                "scheduler: owner={owner} claimed={} inflight={} active_workers={} batches={}",
                snapshot.claimed, snapshot.inflight, snapshot.active_workers, snapshot.batches
            );
        }
        Err(error) => println!(
            "scheduler: unavailable warning={}",
            single_line_error(&error)
        ),
    }
    match blocking {
        Ok(entries) => {
            let needs_human = entries
                .iter()
                .filter(|entry| entry.is_needs_human())
                .count();
            println!(
                "ledger: blocking_rejections={} (needs_human={})",
                entries.len(),
                needs_human
            );
        }
        Err(error) => println!("ledger: unavailable warning={}", single_line_error(&error)),
    }

    if let Ok(head) = git_stdout(&repo_root, &["rev-parse", "HEAD"])
        && let Some(checkpoint) = provenance::entire_checkpoint_for_commit(&repo_root, head.trim())
    {
        println!(
            "entire: ref={} sha={}",
            checkpoint.ref_name, checkpoint.object_sha
        );
    } else {
        println!("entire: none (optional)");
    }

    Ok(ExitCode::SUCCESS)
}

struct HookStatus {
    mode: &'static str,
    hooks: Vec<HookProbe>,
}

struct HookProbe {
    name: &'static str,
    path: PathBuf,
    installed: bool,
}

fn inspect_hook_status(repo_root: &Path, state_dir: &Path) -> Result<HookStatus> {
    let mode = detect_hook_mode(repo_root, state_dir)?;
    let hooks = HOOKS
        .iter()
        .map(|hook| {
            let path = active_hook_path(repo_root, &mode, hook)?;
            let installed = hook_is_live_truth_mirror(repo_root, &path, hook, &mode);
            Ok(HookProbe {
                name: hook,
                path,
                installed,
            })
        })
        .collect::<Result<Vec<_>>>()?;

    Ok(HookStatus {
        mode: mode.as_str(),
        hooks,
    })
}

enum StatusHookMode {
    Plain,
    LegacyTruthMirror {
        hooks_path: PathBuf,
    },
    Husky {
        content_dir: PathBuf,
        entry_dir: PathBuf,
    },
    Custom {
        hooks_path: PathBuf,
    },
}

impl StatusHookMode {
    fn as_str(&self) -> &'static str {
        match self {
            Self::Plain => "plain",
            Self::LegacyTruthMirror { .. } => "plain-legacy-truth-mirror",
            Self::Husky { .. } => "husky",
            Self::Custom { .. } => "custom-committed",
        }
    }
}

fn detect_hook_mode(repo_root: &Path, state_dir: &Path) -> Result<StatusHookMode> {
    let Some(configured) = git_config_get(repo_root, "core.hooksPath")? else {
        return Ok(StatusHookMode::Plain);
    };
    let configured = configured.trim();
    if configured.is_empty() {
        return Ok(StatusHookMode::Plain);
    }
    let hooks_path = repo_relative_path(repo_root, Path::new(configured));
    if is_managed_hooks_path(repo_root, state_dir, configured) {
        return Ok(StatusHookMode::LegacyTruthMirror { hooks_path });
    }
    if configured.contains(".husky") {
        let content_dir = if hooks_path.file_name().and_then(|name| name.to_str()) == Some("_") {
            hooks_path
                .parent()
                .map_or_else(|| repo_root.join(".husky"), Path::to_path_buf)
        } else {
            hooks_path.clone()
        };
        return Ok(StatusHookMode::Husky {
            content_dir,
            entry_dir: hooks_path,
        });
    }
    Ok(StatusHookMode::Custom { hooks_path })
}

fn active_hook_path(repo_root: &Path, mode: &StatusHookMode, hook: &str) -> Result<PathBuf> {
    match mode {
        StatusHookMode::Plain => {
            let path = git_stdout(
                repo_root,
                &["rev-parse", "--git-path", &format!("hooks/{hook}")],
            )?;
            Ok(repo_relative_path(repo_root, Path::new(path.trim())))
        }
        StatusHookMode::LegacyTruthMirror { hooks_path } => Ok(hooks_path.join(hook)),
        StatusHookMode::Husky { content_dir, .. } => Ok(content_dir.join(hook)),
        StatusHookMode::Custom { hooks_path } => Ok(hooks_path.join(hook)),
    }
}

fn hook_is_live_truth_mirror(
    repo_root: &Path,
    path: &Path,
    hook: &str,
    mode: &StatusHookMode,
) -> bool {
    if let StatusHookMode::Custom { hooks_path } = mode {
        return custom_hook_forwards_to_local(repo_root, hooks_path, path, hook);
    }

    if let StatusHookMode::Husky {
        content_dir,
        entry_dir,
    } = mode
    {
        let content_is_active_entry = entry_dir == content_dir;
        let content_hook_is_live = if !content_is_active_entry
            && husky_entry_runs_content_hook_with_shell(entry_dir, content_dir, hook)
        {
            truth_mirror_husky_content_is_live(path, hook, mode)
        } else {
            hook_is_executable_with_content(path, |content| {
                hook_content_installs_truth_mirror(content, hook, mode)
            })
        };
        return content_hook_is_live
            && (content_is_active_entry
                || husky_entry_forwards_to_content(entry_dir, content_dir, hook));
    }

    direct_truth_mirror_hook_is_live(path, hook)
}

fn direct_truth_mirror_hook_is_live(path: &Path, hook: &str) -> bool {
    hook_is_executable_with_content(path, |content| {
        hook_content_installs_truth_mirror(content, hook, &StatusHookMode::Plain)
    })
}

fn truth_mirror_husky_content_is_live(path: &Path, hook: &str, mode: &StatusHookMode) -> bool {
    fs::read_to_string(path)
        .is_ok_and(|content| hook_content_installs_truth_mirror(&content, hook, mode))
}

fn hook_is_executable_with_content(path: &Path, predicate: impl FnOnce(&str) -> bool) -> bool {
    is_executable_file(path) && fs::read_to_string(path).is_ok_and(|content| predicate(&content))
}

fn hook_content_installs_truth_mirror(content: &str, hook: &str, mode: &StatusHookMode) -> bool {
    match mode {
        StatusHookMode::Custom { .. } => {
            content.contains(MANAGED_MARKER)
                && content.contains(FORWARDER_NAME)
                && content.contains(hook)
        }
        StatusHookMode::Plain | StatusHookMode::LegacyTruthMirror { .. } => {
            active_hook_lines(content).any(|line| line_invokes_truth_hook_dispatch(line, hook))
        }
        StatusHookMode::Husky { .. } => {
            active_hook_lines(content).any(|line| line_invokes_truth_hook_dispatch(line, hook))
                || husky_resolved_binary_invokes_truth_hook_dispatch(content, hook)
        }
    }
}

/// Older Husky integrations resolve the binary once (`truth_mirror_bin=$(command
/// -v truth-mirror)`) and dispatch through that shell variable. The hook is live,
/// but there is no literal `truth-mirror hook-dispatch` token sequence for the
/// strict parser above to recognize.
fn husky_resolved_binary_invokes_truth_hook_dispatch(content: &str, hook: &str) -> bool {
    let active = active_hook_lines(content).collect::<Vec<_>>();
    active
        .iter()
        .any(|line| line.contains("truth_mirror_bin") && line.contains("truth-mirror"))
        && active.iter().any(|line| {
            line.contains("$truth_mirror_bin")
                && line.contains("hook-dispatch")
                && line.contains(hook)
        })
}

fn active_hook_lines(content: &str) -> impl Iterator<Item = &str> {
    content
        .lines()
        .map(str::trim_start)
        .filter(|line| !line.trim().is_empty() && !line.starts_with('#'))
}

fn line_invokes_truth_hook_dispatch(line: &str, hook: &str) -> bool {
    crate::shell::shellish_token_segments(line)
        .iter()
        .any(|tokens| token_segment_invokes_truth_hook_dispatch(tokens, hook))
}

fn token_segment_invokes_truth_hook_dispatch(tokens: &[&str], hook: &str) -> bool {
    for (index, token) in tokens.iter().enumerate() {
        if !is_truth_binary(token) {
            continue;
        }
        let Some(dispatch_offset) = tokens[index + 1..]
            .iter()
            .position(|candidate| *candidate == "hook-dispatch")
        else {
            continue;
        };
        let hook_index = index + 1 + dispatch_offset + 1;
        if tokens
            .get(hook_index)
            .is_some_and(|candidate| *candidate == hook)
        {
            return true;
        }
    }
    false
}

fn is_truth_binary(token: &str) -> bool {
    token == "truth"
        || token == "truth-mirror"
        || token.ends_with("/truth")
        || token.ends_with("/truth-mirror")
}

fn custom_forwarder_helper_is_live(hooks_path: &Path) -> bool {
    hook_is_executable_with_content(&hooks_path.join(FORWARDER_NAME), |content| {
        content == FORWARDER_SOURCE
    })
}

fn custom_hook_forwards_to_local(
    repo_root: &Path,
    hooks_path: &Path,
    path: &Path,
    hook: &str,
) -> bool {
    if direct_truth_mirror_hook_is_live(path, hook) {
        return true;
    }
    let active_forwards = hook_is_executable_with_content(path, |content| {
        if hook_content_installs_truth_mirror(
            content,
            hook,
            &StatusHookMode::Custom {
                hooks_path: hooks_path.to_path_buf(),
            },
        ) {
            return custom_forwarder_helper_is_live(hooks_path);
        }
        content_forwards_to_local_git_hook(content, hook)
    });
    active_forwards
        && forwarded_local_hook_path(repo_root, hook)
            .is_ok_and(|local_hook| direct_truth_mirror_hook_is_live(&local_hook, hook))
}

fn content_forwards_to_local_git_hook(content: &str, hook: &str) -> bool {
    let resolves_git_dir =
        content.contains("--git-common-dir") || content.contains("git rev-parse --git-common-dir");
    resolves_git_dir
        && active_hook_lines(content).any(|line| {
            line.contains("$@")
                && (line.contains(&format!("hooks/{hook}"))
                    || line.contains("hooks/$name")
                    || line.contains("hooks/${name}")
                    || line.contains("hooks/$hook")
                    || line.contains("hooks/${hook}"))
        })
}

fn husky_entry_forwards_to_content(entry_dir: &Path, content_dir: &Path, hook: &str) -> bool {
    let entry = entry_dir.join(hook);
    hook_is_executable_with_content(&entry, |content| {
        if content_mentions_husky_content_hook(content, hook) {
            return true;
        }
        if content_mentions_husky_helper(content) {
            return husky_helper_forwards_to_content(
                entry_dir,
                content_dir,
                !content_sources_husky_helper(content),
            );
        }
        false
    })
}

fn husky_entry_runs_content_hook_with_shell(
    entry_dir: &Path,
    content_dir: &Path,
    hook: &str,
) -> bool {
    let entry = entry_dir.join(hook);
    hook_is_executable_with_content(&entry, |content| {
        if content_mentions_husky_helper(content) {
            return husky_helper_runs_content_hook_with_shell(
                entry_dir,
                content_dir,
                !content_sources_husky_helper(content),
            );
        }
        false
    })
}

fn husky_helper_forwards_to_content(
    entry_dir: &Path,
    content_dir: &Path,
    require_executable: bool,
) -> bool {
    if normalize_path(&entry_dir.join("..")) != normalize_path(content_dir) {
        return false;
    }
    let helper = entry_dir.join("h");
    if require_executable && !is_executable_file(&helper) {
        return false;
    }
    fs::read_to_string(helper).is_ok_and(|content| {
        let active_content = active_hook_lines(&content).collect::<Vec<_>>().join("\n");
        let names_active_hook = active_content.contains("hook_name")
            || active_content.contains("basename \"$0\"")
            || active_content.contains("${0##*/}");
        let targets_parent_hook = active_content.contains("content_dir")
            || active_content.contains("dirname \"$(dirname \"$0\")\"")
            || active_content.contains("${0%/*/*}");
        names_active_hook && targets_parent_hook && active_content.contains("\"$@\"")
    })
}

fn husky_helper_runs_content_hook_with_shell(
    entry_dir: &Path,
    content_dir: &Path,
    require_executable: bool,
) -> bool {
    if !husky_helper_forwards_to_content(entry_dir, content_dir, require_executable) {
        return false;
    }
    fs::read_to_string(entry_dir.join("h")).is_ok_and(|content| {
        active_hook_lines(&content).any(|line| {
            line.contains("sh -e ") || line.contains("sh \"$") || line.contains("sh '$")
        })
    })
}

fn content_mentions_husky_helper(content: &str) -> bool {
    active_hook_lines(content).any(|line| line.contains("/h\"") || line.contains("/h'"))
}

fn content_sources_husky_helper(content: &str) -> bool {
    active_hook_lines(content)
        .any(|line| line.starts_with(". ") && (line.contains("/h\"") || line.contains("/h'")))
}

fn content_mentions_husky_content_hook(content: &str, hook: &str) -> bool {
    active_hook_lines(content)
        .any(|line| line.contains(&format!("/{hook}\"")) || line.contains(&format!("/{hook}'")))
}

fn forwarded_local_hook_path(repo_root: &Path, hook: &str) -> Result<PathBuf> {
    let git_dir = git_stdout(repo_root, &["rev-parse", "--git-common-dir"])?;
    Ok(repo_relative_path(repo_root, Path::new(git_dir.trim()))
        .join("hooks")
        .join(hook))
}

fn single_line_error(error: &dyn std::error::Error) -> String {
    error.to_string().replace(['\r', '\n'], " ")
}

/// Keep one status `key=value` field parseable when the value contains
/// whitespace or shell metacharacters. Bare tokens stay bare; anything else is
/// single-quoted with the same `'\''` escape used by hook/message shell quoting.
fn quote_status_field(value: &str) -> String {
    let sanitized = value.replace(['\r', '\n'], " ");
    if sanitized.is_empty()
        || sanitized.chars().any(|character| {
            character.is_whitespace()
                || matches!(
                    character,
                    '"' | '\''
                        | '\\'
                        | '`'
                        | '$'
                        | '|'
                        | ';'
                        | '&'
                        | '<'
                        | '>'
                        | '('
                        | ')'
                        | '{'
                        | '}'
                        | '['
                        | ']'
                        | '*'
                        | '?'
                        | '#'
                        | '~'
                )
        })
    {
        format!("'{}'", sanitized.replace('\'', "'\\''"))
    } else {
        sanitized
    }
}

#[cfg(unix)]
fn is_executable_file(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;

    fs::metadata(path)
        .is_ok_and(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
}

#[cfg(not(unix))]
fn is_executable_file(path: &Path) -> bool {
    path.is_file()
}

fn repo_relative_path(repo_root: &Path, path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        repo_root.join(path)
    }
}

fn is_managed_hooks_path(repo_root: &Path, state_dir: &Path, configured: &str) -> bool {
    let configured_path = normalize_path(&repo_relative_path(repo_root, Path::new(configured)));
    [
        state_dir.join("hooks"),
        PathBuf::from(crate::config::DEFAULT_STATE_DIR).join("hooks"),
        PathBuf::from(crate::config::LEGACY_STATE_DIR).join("hooks"),
    ]
    .iter()
    .any(|candidate| normalize_path(&repo_relative_path(repo_root, candidate)) == configured_path)
}

fn normalize_path(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if normalized.as_os_str().is_empty()
                    || (!normalized.has_root() && normalized.ends_with(".."))
                {
                    normalized.push("..");
                } else {
                    normalized.pop();
                }
            }
            Component::Normal(part) => normalized.push(part),
            Component::RootDir | Component::Prefix(_) => normalized.push(component.as_os_str()),
        }
    }
    normalized
}

fn git_root() -> Result<PathBuf> {
    Ok(PathBuf::from(
        git_stdout(Path::new("."), &["rev-parse", "--show-toplevel"])?.trim(),
    ))
}

fn git_config_get(repo_root: &Path, key: &str) -> Result<Option<String>> {
    let output = Command::new("git")
        .args(["config", "--get", key])
        .current_dir(repo_root)
        .output()?;
    if output.status.success() {
        return Ok(Some(String::from_utf8_lossy(&output.stdout).into_owned()));
    }
    if output.status.code() == Some(1) {
        return Ok(None);
    }
    anyhow::bail!(
        "git config --get {key} failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

fn git_stdout(repo_root: &Path, args: &[&str]) -> Result<String> {
    let output = Command::new("git")
        .args(args)
        .current_dir(repo_root)
        .output()?;
    if !output.status.success() {
        anyhow::bail!(
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr)
        );
    }
    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};

    #[test]
    fn normalize_path_preserves_unmatched_relative_parents() {
        assert_eq!(
            super::normalize_path(Path::new("../hooks")),
            PathBuf::from("../hooks")
        );
        assert_eq!(
            super::normalize_path(Path::new("a/../../hooks")),
            PathBuf::from("../hooks")
        );
    }

    #[test]
    fn quote_status_field_keeps_simple_tokens_bare() {
        assert_eq!(
            super::quote_status_field("workspace-commands"),
            "workspace-commands"
        );
    }

    #[test]
    fn quote_status_field_quotes_values_with_spaces() {
        assert_eq!(
            super::quote_status_field("use exact workspace commands"),
            "'use exact workspace commands'"
        );
        assert_eq!(
            super::quote_status_field("it's a learning"),
            "'it'\\''s a learning'"
        );
        assert_eq!(super::quote_status_field("line\none"), "'line one'");
    }
}