truth-mirror 0.3.0

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
//! Per-agent reinjection surface installation.
//!
//! `install-hooks --claude|--codex|--pi` 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 intentionally excluded: verified against Pi 0.80.3 source, Pi has no
/// `hooks.json` surface. Its project reinjection is a Pi extension package listed
/// in `<repo>/.pi/settings.json` `packages[]` (tracked separately); it is handled
/// outside this module.
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",
    }
}

/// Repo-relative path of a file-surface agent's reinjection hook file.
/// Only meaningful for [`FILE_SURFACE_AGENTS`].
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",
    }
}

/// 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) 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");
    }
}

/// Both Claude Code (`.claude/settings.json`) and Codex (`.codex/hooks.json`)
/// use the same nested shape: `hooks.UserPromptSubmit[].hooks[] = {type, command}`.
/// Verified against Codex 0.142.4 source (`config/src/hook_config.rs`).
fn is_nested(agent: Agent) -> bool {
    matches!(agent, Agent::Claude | Agent::Codex)
}

#[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 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()));
        }
    }
}