truth-mirror 0.9.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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
//! Per-agent reinjection surface installation.
//!
//! `install-hooks --claude|--codex|--pi|--grok` installs `truth-mirror reinject --agent <agent>`
//! into each selected agent's repo-local configuration surface. Installs are
//! non-clobbering (existing config is merged, not overwritten), idempotent, and
//! reversible: uninstall removes only truth-mirror's own entries.

use std::{
    fs,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result};
use serde_json::{Map, Value, json};

use crate::cli::Agent;

/// Agents whose reinjection surface is a JSON hook file this module manages.
///
/// Pi is excluded (JS extension). Grok is excluded from UserPromptSubmit file
/// surfaces: Grok treats non-`PreToolUse` hooks as passive and ignores stdout
/// (xAI hooks docs), so Claude-style reinject-via-stdout does not work. Grok
/// reinjection uses a project skill instead (see [`GROK_SKILL_RELATIVE`]).
pub const FILE_SURFACE_AGENTS: [Agent; 2] = [Agent::Claude, Agent::Codex];

pub fn agent_slug(agent: Agent) -> &'static str {
    match agent {
        Agent::Claude => "claude",
        Agent::Codex => "codex",
        Agent::Pi => "pi",
        Agent::Grok => "grok",
    }
}

/// Repo-relative path of a file-surface agent's reinjection hook file.
/// Only meaningful for [`FILE_SURFACE_AGENTS`] (and Grok enforcement hooks).
pub fn surface_relative_path(agent: Agent) -> &'static str {
    match agent {
        Agent::Claude => ".claude/settings.json",
        Agent::Codex => ".codex/hooks.json",
        // Pi has no hook file; its real project config is .pi/settings.json packages[].
        Agent::Pi => ".pi/settings.json",
        // Grok enforcement-only hook file (PreToolUse). Not used for stdout reinjection.
        Agent::Grok => ".grok/hooks/truth-mirror.json",
    }
}

/// Repo-relative path of the Grok project skill that loads reinjection.
pub const GROK_SKILL_RELATIVE: &str = ".grok/skills/truth-mirror/SKILL.md";

/// Marker embedded in managed Grok skill content. Required before uninstall or
/// Claude-under-Grok skip treats the skill as truth-mirror-owned.
pub const GROK_SKILL_MANAGED_MARKER: &str = "<!-- truth-mirror managed grok skill -->";

/// Grok skill body: Grok does not inject passive-hook stdout into context, so the
/// agent must actively run `truth-mirror reinject --agent grok`.
pub const GROK_SKILL_SOURCE: &str = r#"---
name: truth-mirror
description: Use at session start, before completion claims, before push, and whenever truth-mirror ledger rejections or memory-skill candidates may be unresolved. Run `truth-mirror reinject --agent grok` and treat non-empty output as mandatory work.
---

<!-- truth-mirror managed grok skill -->

# Truth Mirror Unresolved Findings (Grok)

Grok Build does **not** inject `UserPromptSubmit` (or other passive) hook stdout into the model context. Reinjection is active, not hook-stdout:

```bash
truth-mirror reinject --agent grok
```

If the command prints anything, address or waive those findings before claiming completion or pushing. Do not ignore empty success as "all clear" without having run the command in this session when ledger state may have changed.

Optional status:

```bash
truth-mirror ledger list
truth-mirror status
```
"#;

/// Absolute path of the project-local Grok reinjection skill.
pub fn grok_skill_path(repo_root: &Path) -> PathBuf {
    repo_root.join(GROK_SKILL_RELATIVE)
}

/// Whether a truth-mirror-owned Grok reinjection skill is present under `repo_root`.
pub fn grok_skill_installed(repo_root: &Path) -> bool {
    let path = grok_skill_path(repo_root);
    fs::read_to_string(path)
        .map(|body| body.contains(GROK_SKILL_MANAGED_MARKER))
        .unwrap_or(false)
}

/// Write the project-local Grok reinjection skill without clobbering foreign content.
pub fn install_grok_skill(repo_root: &Path) -> Result<()> {
    let path = grok_skill_path(repo_root);
    reject_symlink_path(repo_root, &path)?;
    if path.exists() {
        let meta = fs::symlink_metadata(&path)
            .with_context(|| format!("statting grok skill {}", path.display()))?;
        if !meta.is_file() {
            anyhow::bail!(
                "refusing to install Grok skill at {} (not a regular file)",
                path.display()
            );
        }
        let existing = fs::read_to_string(&path)
            .with_context(|| format!("reading existing grok skill {}", path.display()))?;
        if !existing.contains(GROK_SKILL_MANAGED_MARKER) {
            anyhow::bail!(
                "refusing to overwrite foreign Grok skill at {} (missing managed marker); move it aside or pass force via manual edit",
                path.display()
            );
        }
    }
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("creating grok skills dir {}", parent.display()))?;
    }
    // Re-check after create_dir_all in case a symlink was planted concurrently.
    reject_symlink_path(repo_root, &path)?;
    fs::write(&path, GROK_SKILL_SOURCE)
        .with_context(|| format!("writing grok skill {}", path.display()))?;
    Ok(())
}

fn reject_symlink_path(repo_root: &Path, path: &Path) -> Result<()> {
    // Reject a symlink at the leaf *or* any existing ancestor so a malicious
    // `.grok` / `.grok/skills` symlink cannot redirect writes outside the repo.
    // Start at repo_root so normal platform symlinks outside the repo, such as
    // macOS /var -> /private/var tempdirs, do not make safe installs fail.
    let relative = path.strip_prefix(repo_root).unwrap_or(path);
    let mut prefix = repo_root.to_path_buf();
    for component in relative.components() {
        prefix.push(component);
        match fs::symlink_metadata(&prefix) {
            Ok(meta) if meta.file_type().is_symlink() => anyhow::bail!(
                "refusing to use Grok skill path {} (symlink at {}; possible write-outside-repo attack)",
                path.display(),
                prefix.display()
            ),
            Ok(_) | Err(_) => {}
        }
    }
    Ok(())
}

/// Remove the project-local Grok reinjection skill (owned only) and empty parents.
pub fn uninstall_grok_skill(repo_root: &Path) -> Result<()> {
    let path = grok_skill_path(repo_root);
    if path.is_file() {
        let existing = fs::read_to_string(&path)
            .with_context(|| format!("reading grok skill {}", path.display()))?;
        if !existing.contains(GROK_SKILL_MANAGED_MARKER) {
            // Leave foreign skills in place.
            return Ok(());
        }
        fs::remove_file(&path)
            .with_context(|| format!("removing grok skill {}", path.display()))?;
    }
    // Best-effort empty dir cleanup (same pattern as Pi extension uninstall).
    let _ = fs::remove_dir(repo_root.join(".grok/skills/truth-mirror"));
    let _ = fs::remove_dir(repo_root.join(".grok/skills"));
    let _ = fs::remove_dir(repo_root.join(".grok"));
    Ok(())
}

/// Remove empty Grok hook dirs after enforcement/hook file uninstall.
pub fn cleanup_empty_grok_dirs(repo_root: &Path) {
    let _ = fs::remove_dir(repo_root.join(".grok/hooks"));
    let _ = fs::remove_dir(repo_root.join(".grok"));
}

/// The exact command truth-mirror installs into each surface.
pub fn reinject_command(agent: Agent) -> String {
    format!("truth-mirror reinject --agent {}", agent_slug(agent))
}

/// Repo-relative path of the project-local Pi extension file.
pub const PI_EXTENSION_RELATIVE: &str = ".pi/extensions/truth-mirror.js";

/// Absolute path of the project-local Pi extension file.
///
/// Pi auto-loads every `*.js`/`*.ts` file in `<cwd>/.pi/extensions/` (verified
/// against Pi 0.80.3 `core/extensions/loader.js:466-490,511-512`), subject to the
/// one-time project-folder trust prompt (`core/project-trust.js`).
pub fn pi_extension_path(repo_root: &Path) -> PathBuf {
    repo_root.join(PI_EXTENSION_RELATIVE)
}

/// The project-local Pi extension. Default-exports a factory `(pi) => {}` that
/// registers a `context` handler (fires before every LLM call) and appends the
/// output of `truth-mirror reinject --agent pi` as a user message, with a dedup
/// guard so findings inject once per change, not once per tool round-trip.
pub const PI_EXTENSION_SOURCE: &str = r#"// truth-mirror Pi reinjection extension.
// Auto-generated by `truth-mirror install-hooks --pi`. Pi auto-loads this file
// from <repo>/.pi/extensions/ once the project folder is trusted.
import { execFile } from "node:child_process";
import { promisify } from "node:util";

const run = promisify(execFile);

export default function truthMirror(pi) {
  let lastInjected = "";
  pi.on("context", async (event) => {
    let text = "";
    try {
      const { stdout } = await run("truth-mirror", ["reinject", "--agent", "pi"], {
        cwd: process.cwd(),
      });
      text = (stdout || "").trim();
    } catch {
      return; // truth-mirror missing or errored: stay silent.
    }
    // `context` fires before every LLM call; dedup so findings inject once per change.
    if (!text || text === lastInjected) return;
    lastInjected = text;
    return {
      messages: [
        ...event.messages,
        { role: "user", content: [{ type: "text", text }] },
      ],
    };
  });
}
"#;

/// Write the project-local Pi reinjection extension into `<repo>/.pi/extensions/`.
pub fn install_pi_extension(repo_root: &Path) -> Result<()> {
    let path = pi_extension_path(repo_root);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("creating pi extensions dir {}", parent.display()))?;
    }
    fs::write(&path, PI_EXTENSION_SOURCE)
        .with_context(|| format!("writing pi extension {}", path.display()))?;
    Ok(())
}

/// Remove the project-local Pi reinjection extension.
pub fn uninstall_pi_extension(repo_root: &Path) -> Result<()> {
    let path = pi_extension_path(repo_root);
    if path.is_file() {
        fs::remove_file(&path)
            .with_context(|| format!("removing pi extension {}", path.display()))?;
    }
    Ok(())
}

/// The enforcement subcommand marker. Matched only when the command's program
/// token is also `truth-mirror` (see `is_own_enforcement_command`), so preserved
/// `--config`/`--state-dir` variants match but foreign hooks never do.
pub const ENFORCE_COMMAND: &str = "gate --pre-tool-use";

fn enforce_command(global_args: &str) -> String {
    format!("truth-mirror {global_args}{ENFORCE_COMMAND}")
}

/// Install a `PreToolUse` enforcement hook into a nested (Claude/Codex/Grok) surface.
/// The hook exits non-zero to block a mutating tool while the ledger has
/// unresolved rejections beyond the configured threshold. `global_args` preserves
/// the install-time `--config`/`--state-dir` so the hook uses the same config.
pub fn install_enforcement(repo_root: &Path, agent: Agent, global_args: &str) -> Result<()> {
    debug_assert!(is_nested(agent), "enforcement hook is nested-surface only");
    let command = enforce_command(global_args);
    let path = repo_root.join(surface_relative_path(agent));
    let mut root = read_object(&path)?;
    // Remove any prior truth-mirror enforcement entry first so a reinstall UPDATES
    // the preserved flags (foreign hooks are left untouched).
    remove_own_enforcement(&mut root, "PreToolUse");
    let entries = event_array_mut(&mut root, "PreToolUse");
    entries.push(json!({ "hooks": [ { "type": "command", "command": command } ] }));
    write_object(&path, &root)
}

/// Remove the `PreToolUse` enforcement hook from a nested surface.
pub fn uninstall_enforcement(repo_root: &Path, agent: Agent) -> Result<()> {
    let path = repo_root.join(surface_relative_path(agent));
    if !path.exists() {
        return Ok(());
    }
    let mut root = read_object(&path)?;
    remove_own_enforcement(&mut root, "PreToolUse");
    if root.is_empty() {
        fs::remove_file(&path)
            .with_context(|| format!("removing empty surface {}", path.display()))?;
    } else {
        write_object(&path, &root)?;
    }
    Ok(())
}

/// Whether an entry is truth-mirror's OWN enforcement command — the program token
/// must be `truth-mirror`, so a foreign hook like `external-auditor gate
/// --pre-tool-use` is never matched, removed, or clobbered.
fn is_own_enforcement_command(entry: &Value) -> bool {
    entry
        .get("command")
        .and_then(Value::as_str)
        .is_some_and(|value| {
            value.split_whitespace().next() == Some("truth-mirror")
                && value.contains(ENFORCE_COMMAND)
        })
}

/// Mutable handle to `hooks.<event>` array, creating nested containers as needed.
fn event_array_mut<'a>(root: &'a mut Map<String, Value>, event: &str) -> &'a mut Vec<Value> {
    let hooks = root
        .entry("hooks")
        .or_insert_with(|| Value::Object(Map::new()));
    if !hooks.is_object() {
        *hooks = Value::Object(Map::new());
    }
    let hooks = hooks.as_object_mut().expect("hooks is object");
    let entries = hooks
        .entry(event.to_owned())
        .or_insert_with(|| Value::Array(Vec::new()));
    if !entries.is_array() {
        *entries = Value::Array(Vec::new());
    }
    entries.as_array_mut().expect("event is array")
}

fn remove_own_enforcement(root: &mut Map<String, Value>, event: &str) {
    let Some(hooks) = root.get_mut("hooks").and_then(Value::as_object_mut) else {
        return;
    };
    if let Some(groups) = hooks.get_mut(event).and_then(Value::as_array_mut) {
        for group in groups.iter_mut() {
            if let Some(inner) = group.get_mut("hooks").and_then(Value::as_array_mut) {
                // Only truth-mirror's own enforcement command is removed; foreign
                // hooks (even ones mentioning the subcommand) are left intact.
                inner.retain(|entry| !is_own_enforcement_command(entry));
            }
        }
        groups.retain(|group| {
            group
                .get("hooks")
                .and_then(Value::as_array)
                .is_none_or(|inner| !inner.is_empty())
        });
        if groups.is_empty() {
            hooks.remove(event);
        }
    }
    if hooks.is_empty() {
        root.remove("hooks");
    }
}

/// Claude Code (`.claude/settings.json`), Codex (`.codex/hooks.json`), and Grok
/// (`.grok/hooks/*.json`) use the same nested shape for hook entries.
/// Codex verified against 0.142.4 (`config/src/hook_config.rs`); Grok against xAI
/// hooks docs. Grok uses this shape for optional PreToolUse enforcement only.
fn is_nested(agent: Agent) -> bool {
    matches!(agent, Agent::Claude | Agent::Codex | Agent::Grok)
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SurfacePlan {
    pub agent: Agent,
    pub path: PathBuf,
}

impl SurfacePlan {
    pub fn for_agent(repo_root: &Path, agent: Agent) -> Self {
        Self {
            agent,
            path: repo_root.join(surface_relative_path(agent)),
        }
    }

    pub fn install(&self) -> Result<()> {
        let mut root = read_object(&self.path)?;
        install_command(self.agent, &mut root, &reinject_command(self.agent));
        write_object(&self.path, &root)
    }

    pub fn uninstall(&self) -> Result<()> {
        if !self.path.exists() {
            return Ok(());
        }
        let mut root = read_object(&self.path)?;
        remove_command(self.agent, &mut root, &reinject_command(self.agent));
        if root.is_empty() {
            fs::remove_file(&self.path)
                .with_context(|| format!("removing empty surface {}", self.path.display()))?;
        } else {
            write_object(&self.path, &root)?;
        }
        Ok(())
    }

    pub fn contains_reinject(&self) -> Result<bool> {
        if !self.path.exists() {
            return Ok(false);
        }
        let root = read_object(&self.path)?;
        Ok(surface_contains(
            self.agent,
            &root,
            &reinject_command(self.agent),
        ))
    }
}

fn read_object(path: &Path) -> Result<Map<String, Value>> {
    match fs::read_to_string(path) {
        Ok(contents) if contents.trim().is_empty() => Ok(Map::new()),
        Ok(contents) => {
            let value: Value = serde_json::from_str(&contents)
                .with_context(|| format!("parsing existing surface {}", path.display()))?;
            match value {
                Value::Object(map) => Ok(map),
                _ => anyhow::bail!(
                    "surface {} is not a JSON object; refusing to clobber",
                    path.display()
                ),
            }
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Map::new()),
        Err(error) => Err(error).with_context(|| format!("reading surface {}", path.display()))?,
    }
}

fn write_object(path: &Path, root: &Map<String, Value>) -> Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("creating surface dir {}", parent.display()))?;
    }
    let mut serialized = serde_json::to_string_pretty(&Value::Object(root.clone()))?;
    serialized.push('\n');
    fs::write(path, serialized).with_context(|| format!("writing surface {}", path.display()))?;
    Ok(())
}

fn install_command(agent: Agent, root: &mut Map<String, Value>, command: &str) {
    let entries = user_prompt_submit_mut(agent, root);
    if array_contains_command(agent, entries, command) {
        return;
    }
    entries.push(surface_entry(agent, command));
}

fn remove_command(agent: Agent, root: &mut Map<String, Value>, command: &str) {
    if is_nested(agent) {
        let Some(hooks) = root.get_mut("hooks").and_then(Value::as_object_mut) else {
            return;
        };
        if let Some(groups) = hooks
            .get_mut("UserPromptSubmit")
            .and_then(Value::as_array_mut)
        {
            for group in groups.iter_mut() {
                if let Some(inner) = group.get_mut("hooks").and_then(Value::as_array_mut) {
                    inner.retain(|entry| !entry_matches_command(entry, command));
                }
            }
            groups.retain(|group| {
                group
                    .get("hooks")
                    .and_then(Value::as_array)
                    .is_none_or(|inner| !inner.is_empty())
            });
            if groups.is_empty() {
                hooks.remove("UserPromptSubmit");
            }
        }
        if hooks.is_empty() {
            root.remove("hooks");
        }
    } else if let Some(entries) = root
        .get_mut("UserPromptSubmit")
        .and_then(Value::as_array_mut)
    {
        entries.retain(|entry| !entry_matches_command(entry, command));
        if entries.is_empty() {
            root.remove("UserPromptSubmit");
        }
    }
}

/// Return a mutable handle to the array we append entries to, creating the
/// nested containers if they do not exist.
fn user_prompt_submit_mut(agent: Agent, root: &mut Map<String, Value>) -> &mut Vec<Value> {
    if is_nested(agent) {
        let hooks = root
            .entry("hooks")
            .or_insert_with(|| Value::Object(Map::new()));
        if !hooks.is_object() {
            *hooks = Value::Object(Map::new());
        }
        let hooks = hooks.as_object_mut().expect("hooks is object");
        let entries = hooks
            .entry("UserPromptSubmit")
            .or_insert_with(|| Value::Array(Vec::new()));
        if !entries.is_array() {
            *entries = Value::Array(Vec::new());
        }
        entries.as_array_mut().expect("UserPromptSubmit is array")
    } else {
        let entries = root
            .entry("UserPromptSubmit")
            .or_insert_with(|| Value::Array(Vec::new()));
        if !entries.is_array() {
            *entries = Value::Array(Vec::new());
        }
        entries.as_array_mut().expect("UserPromptSubmit is array")
    }
}

fn surface_entry(agent: Agent, command: &str) -> Value {
    if is_nested(agent) {
        json!({ "hooks": [ { "type": "command", "command": command } ] })
    } else {
        json!({ "command": command })
    }
}

fn array_contains_command(agent: Agent, entries: &[Value], command: &str) -> bool {
    if is_nested(agent) {
        entries.iter().any(|group| {
            group
                .get("hooks")
                .and_then(Value::as_array)
                .is_some_and(|inner| inner.iter().any(|e| entry_matches_command(e, command)))
        })
    } else {
        entries.iter().any(|e| entry_matches_command(e, command))
    }
}

fn entry_matches_command(entry: &Value, command: &str) -> bool {
    entry
        .get("command")
        .and_then(Value::as_str)
        .is_some_and(|value| value == command)
}

/// Whether the surface JSON already carries the reinject command for an agent.
pub fn surface_contains(agent: Agent, root: &Map<String, Value>, command: &str) -> bool {
    if is_nested(agent) {
        root.get("hooks")
            .and_then(Value::as_object)
            .and_then(|hooks| hooks.get("UserPromptSubmit"))
            .and_then(Value::as_array)
            .is_some_and(|entries| array_contains_command(agent, entries, command))
    } else {
        root.get("UserPromptSubmit")
            .and_then(Value::as_array)
            .is_some_and(|entries| array_contains_command(agent, entries, command))
    }
}

#[cfg(test)]
mod tests {
    use super::{
        Agent, SurfacePlan, install_command, reinject_command, remove_command, surface_contains,
    };
    use proptest::prelude::*;
    use serde_json::{Map, Value, json};

    fn install_into(agent: Agent, mut root: Map<String, Value>) -> Map<String, Value> {
        install_command(agent, &mut root, &reinject_command(agent));
        root
    }

    #[test]
    fn claude_surface_uses_nested_user_prompt_submit() {
        let root = install_into(Agent::Claude, Map::new());
        let value = Value::Object(root.clone());

        let command = value
            .pointer("/hooks/UserPromptSubmit/0/hooks/0/command")
            .and_then(Value::as_str)
            .unwrap();
        assert_eq!(command, "truth-mirror reinject --agent claude");
        assert!(surface_contains(
            Agent::Claude,
            &root,
            &reinject_command(Agent::Claude)
        ));
    }

    #[test]
    fn codex_uses_nested_user_prompt_submit_like_claude() {
        // Verified against Codex 0.142.4: hooks.json is nested, not flat.
        let root = install_into(Agent::Codex, Map::new());
        let value = Value::Object(root.clone());

        let command = value
            .pointer("/hooks/UserPromptSubmit/0/hooks/0/command")
            .and_then(Value::as_str)
            .unwrap();
        assert_eq!(command, "truth-mirror reinject --agent codex");
        assert!(surface_contains(
            Agent::Codex,
            &root,
            &reinject_command(Agent::Codex)
        ));
    }

    #[test]
    fn grok_skill_install_round_trips() {
        let temp = tempfile::tempdir().unwrap();
        super::install_grok_skill(temp.path()).unwrap();
        let path = super::grok_skill_path(temp.path());
        assert!(path.is_file());
        let body = std::fs::read_to_string(&path).unwrap();
        assert!(body.contains("truth-mirror reinject --agent grok"));
        assert!(body.contains(super::GROK_SKILL_MANAGED_MARKER));
        assert!(super::grok_skill_installed(temp.path()));
        super::uninstall_grok_skill(temp.path()).unwrap();
        assert!(!path.is_file());
        assert!(!super::grok_skill_installed(temp.path()));
    }

    #[test]
    fn grok_skill_refuses_foreign_file() {
        let temp = tempfile::tempdir().unwrap();
        let path = super::grok_skill_path(temp.path());
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "hand-written skill without marker").unwrap();
        let err = super::install_grok_skill(temp.path()).unwrap_err();
        assert!(err.to_string().contains("foreign"));
        assert!(!super::grok_skill_installed(temp.path()));
        super::uninstall_grok_skill(temp.path()).unwrap();
        assert!(path.is_file(), "foreign skill preserved on uninstall");
    }

    #[cfg(unix)]
    #[test]
    fn grok_skill_refuses_symlink_path() {
        use std::os::unix::fs::symlink;
        let temp = tempfile::tempdir().unwrap();
        let outside = temp.path().join("outside.md");
        std::fs::write(&outside, super::GROK_SKILL_SOURCE).unwrap();
        let path = super::grok_skill_path(temp.path());
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        symlink(&outside, &path).unwrap();
        let err = super::install_grok_skill(temp.path()).unwrap_err();
        assert!(err.to_string().contains("symlink"));
        assert_eq!(
            std::fs::read_to_string(&outside).unwrap(),
            super::GROK_SKILL_SOURCE,
            "outside target must not be rewritten"
        );
    }

    #[cfg(unix)]
    #[test]
    fn grok_skill_refuses_project_ancestor_symlink() {
        use std::os::unix::fs::symlink;
        let temp = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        symlink(outside.path(), temp.path().join(".grok")).unwrap();

        let err = super::install_grok_skill(temp.path()).unwrap_err();

        assert!(err.to_string().contains("symlink"));
        assert!(
            !outside.path().join("skills/truth-mirror/SKILL.md").exists(),
            "ancestor symlink target must not receive the managed Grok skill"
        );
    }

    #[test]
    fn grok_enforcement_uses_nested_hooks_path() {
        assert_eq!(
            super::surface_relative_path(Agent::Grok),
            ".grok/hooks/truth-mirror.json"
        );
        let temp = tempfile::tempdir().unwrap();
        super::install_enforcement(temp.path(), Agent::Grok, "").unwrap();
        let content =
            std::fs::read_to_string(temp.path().join(".grok/hooks/truth-mirror.json")).unwrap();
        assert!(content.contains("PreToolUse"));
        assert!(content.contains("truth-mirror gate --pre-tool-use"));
        assert!(!content.contains("UserPromptSubmit"));
        super::uninstall_enforcement(temp.path(), Agent::Grok).unwrap();
        super::cleanup_empty_grok_dirs(temp.path());
        assert!(!temp.path().join(".grok/hooks/truth-mirror.json").exists());
    }

    #[test]
    fn install_is_idempotent() {
        let mut root = install_into(Agent::Claude, Map::new());
        install_command(Agent::Claude, &mut root, &reinject_command(Agent::Claude));

        let count = Value::Object(root)
            .pointer("/hooks/UserPromptSubmit")
            .and_then(Value::as_array)
            .map(Vec::len)
            .unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn install_preserves_foreign_config() {
        let existing: Map<String, Value> = json!({
            "model": "sonnet",
            "hooks": { "PreToolUse": [ { "matcher": "Bash" } ] }
        })
        .as_object()
        .cloned()
        .unwrap();

        let root = install_into(Agent::Claude, existing);
        let value = Value::Object(root);

        assert_eq!(
            value.pointer("/model").and_then(Value::as_str),
            Some("sonnet")
        );
        assert!(value.pointer("/hooks/PreToolUse").is_some());
        assert!(value.pointer("/hooks/UserPromptSubmit/0").is_some());
    }

    #[test]
    fn uninstall_removes_only_truth_mirror_entries() {
        let existing: Map<String, Value> = json!({
            "model": "sonnet",
            "hooks": {
                "UserPromptSubmit": [ { "hooks": [ { "type": "command", "command": "other-tool" } ] } ]
            }
        })
        .as_object()
        .cloned()
        .unwrap();

        let mut root = install_into(Agent::Claude, existing);
        remove_command(Agent::Claude, &mut root, &reinject_command(Agent::Claude));
        let value = Value::Object(root);

        assert_eq!(
            value.pointer("/model").and_then(Value::as_str),
            Some("sonnet")
        );
        let commands: Vec<&str> = value
            .pointer("/hooks/UserPromptSubmit")
            .and_then(Value::as_array)
            .unwrap()
            .iter()
            .filter_map(|group| group.pointer("/hooks/0/command").and_then(Value::as_str))
            .collect();
        assert_eq!(commands, ["other-tool"]);
    }

    #[test]
    fn enforcement_hook_installs_and_coexists_with_reinject() {
        let temp = tempfile::tempdir().unwrap();
        let plan = SurfacePlan::for_agent(temp.path(), Agent::Claude);
        plan.install().unwrap(); // UserPromptSubmit reinject
        super::install_enforcement(temp.path(), Agent::Claude, "").unwrap();

        let content = std::fs::read_to_string(&plan.path).unwrap();
        assert!(content.contains("UserPromptSubmit"));
        assert!(content.contains("PreToolUse"));
        assert!(content.contains("truth-mirror gate --pre-tool-use"));

        // Removing enforcement leaves the reinject hook intact.
        super::uninstall_enforcement(temp.path(), Agent::Claude).unwrap();
        let after = std::fs::read_to_string(&plan.path).unwrap();
        assert!(after.contains("UserPromptSubmit"));
        assert!(!after.contains("PreToolUse"));
    }

    #[test]
    fn reinstalling_enforcement_updates_preserved_flags() {
        let temp = tempfile::tempdir().unwrap();
        super::install_enforcement(temp.path(), Agent::Codex, "").unwrap();
        // Reinstall with a preserved --config: must UPDATE, not leave a stale entry.
        super::install_enforcement(temp.path(), Agent::Codex, "--config '/abs/x.toml' ").unwrap();

        let content = std::fs::read_to_string(temp.path().join(".codex/hooks.json")).unwrap();
        assert_eq!(content.matches("gate --pre-tool-use").count(), 1);
        assert!(content.contains("--config '/abs/x.toml'"));
    }

    #[test]
    fn enforcement_leaves_foreign_pretooluse_hooks_intact() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join(".codex/hooks.json");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        // A FOREIGN hook that merely mentions the subcommand must not be clobbered.
        let foreign = "external-auditor gate --pre-tool-use --keep";
        std::fs::write(
            &path,
            format!(
                "{{\"hooks\":{{\"PreToolUse\":[{{\"hooks\":[{{\"type\":\"command\",\"command\":\"{foreign}\"}}]}}]}}}}"
            ),
        )
        .unwrap();

        super::install_enforcement(temp.path(), Agent::Codex, "").unwrap();
        let after_install = std::fs::read_to_string(&path).unwrap();
        assert!(
            after_install.contains(foreign),
            "foreign hook survives install"
        );
        assert!(after_install.contains("truth-mirror gate --pre-tool-use"));

        super::uninstall_enforcement(temp.path(), Agent::Codex).unwrap();
        let after_uninstall = std::fs::read_to_string(&path).unwrap();
        assert!(
            after_uninstall.contains(foreign),
            "foreign hook survives uninstall"
        );
        assert!(!after_uninstall.contains("truth-mirror gate --pre-tool-use"));
    }

    #[test]
    fn enforcement_round_trips_for_codex() {
        let temp = tempfile::tempdir().unwrap();
        super::install_enforcement(temp.path(), Agent::Codex, "").unwrap();
        assert!(
            std::fs::read_to_string(temp.path().join(".codex/hooks.json"))
                .unwrap()
                .contains("truth-mirror gate --pre-tool-use")
        );
        super::uninstall_enforcement(temp.path(), Agent::Codex).unwrap();
        assert!(!temp.path().join(".codex/hooks.json").exists());
    }

    #[test]
    fn install_then_uninstall_on_disk_round_trips() {
        let temp = tempfile::tempdir().unwrap();
        for agent in super::FILE_SURFACE_AGENTS {
            let plan = SurfacePlan::for_agent(temp.path(), agent);
            plan.install().unwrap();
            assert!(plan.contains_reinject().unwrap());
            plan.uninstall().unwrap();
            assert!(!plan.contains_reinject().unwrap());
            assert!(!plan.path.exists());
        }
    }

    proptest! {
        #[test]
        fn foreign_keys_survive_install_uninstall(
            key in "[a-z]{1,8}",
            val in "[a-z0-9]{1,8}",
        ) {
            prop_assume!(key != "hooks" && key != "UserPromptSubmit");
            let existing: Map<String, Value> = json!({ key.clone(): val.clone() })
                .as_object()
                .cloned()
                .unwrap();

            let mut root = existing.clone();
            install_command(Agent::Codex, &mut root, &reinject_command(Agent::Codex));
            prop_assert!(surface_contains(Agent::Codex, &root, &reinject_command(Agent::Codex)));

            remove_command(Agent::Codex, &mut root, &reinject_command(Agent::Codex));
            prop_assert!(!surface_contains(Agent::Codex, &root, &reinject_command(Agent::Codex)));
            prop_assert_eq!(root.get(&key).and_then(Value::as_str), Some(val.as_str()));
        }
    }
}