amont-agent 2.3.0

A guard that inspects a shell command before Claude Code runs it
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
//! Editing Claude Code's `settings.json` without breaking it.
//!
//! This is a file the user writes by hand. Everything here is arranged around
//! that one fact: we add one handler, we remove exactly what we added, and we
//! touch nothing else — not the key order, not the indentation, not somebody
//! else's hook.
//!
//! ## Refuse rather than guess
//!
//! If the file does not parse, we do **not** attempt a textual patch. A regex
//! edit of JSON that is already malformed is how a hand-maintained config gets
//! destroyed. We say what is wrong, print the block to paste, and change
//! nothing.
//!
//! ## Why not `hookfile::guard_write`
//!
//! That guard is a statement about `.git/hooks`: it refuses a **tracked** file
//! outright, and refuses when git cannot answer at all. Both are right there —
//! `.git/hooks` is machine-local scratch, so a tracked file in it means a
//! symlink has escaped. Neither is right here. A project `.claude/settings.json`
//! is legitimately tracked and we are being asked to edit it, and a user-level
//! `~/.claude/settings.json` sits outside any repository, where "git cannot
//! answer" is the normal case rather than a warning.
//!
//! So the symlink and regular-file checks are re-stated for this context, and
//! only the atomic swap — `hookfile::stage` then `hookfile::commit_all` — is
//! reused. That swap is what makes a symlinked `settings.json` get REPLACED
//! rather than written through to its target.

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

use serde_json::{json, Map, Value};

/// The Claude Code config directory.
///
/// `$CLAUDE_CONFIG_DIR` wins because that is the override Claude Code itself
/// honours. `$HOME` is not enough on its own: Windows usually leaves it unset
/// and uses `%USERPROFILE%`, and this repository ships a Windows installer and
/// gates a Windows CI job, so "no home directory" there would mean install and
/// the journal both silently giving up.
pub fn config_dir() -> Option<std::path::PathBuf> {
    if let Some(d) = std::env::var_os("CLAUDE_CONFIG_DIR") {
        return Some(std::path::PathBuf::from(d));
    }
    let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
    Some(std::path::PathBuf::from(home).join(".claude"))
}

/// How we recognise our own handler on the way back out. Matched on the
/// command's file name, so moving the binary does not orphan the entry.
pub const BIN: &str = "amont-agent";

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Scope {
    User,
    Project,
    ProjectLocal,
}

impl Scope {
    pub fn path(self, project: &Path) -> Option<PathBuf> {
        match self {
            Scope::User => Some(config_dir()?.join("settings.json")),
            Scope::Project => Some(project.join(".claude").join("settings.json")),
            Scope::ProjectLocal => Some(project.join(".claude").join("settings.local.json")),
        }
    }
}

pub enum Change {
    Add,
    Update,
    AlreadyCurrent,
    Remove,
    NothingToRemove,
    /// The file uses formatting this program cannot reproduce, so writing it
    /// back would reformat parts we were not asked to touch. See
    /// [`would_reformat`].
    WouldReformat,
}

impl Change {
    pub fn describe(&self, path: &Path) -> String {
        let p = path.display();
        match self {
            Change::Add => format!("added the PreToolUse hook to {p}"),
            Change::Update => format!("updated the PreToolUse hook in {p}"),
            Change::AlreadyCurrent => format!("{p} is already current — nothing written"),
            Change::Remove => format!("removed the PreToolUse hook from {p}"),
            Change::NothingToRemove => format!("no amont-agent hook in {p} — nothing written"),
            Change::WouldReformat => format!(
                "{p} uses formatting this program cannot reproduce — writing it back would \
                 reformat parts of the file nobody asked to change.\n\
                 Paste the block below in by hand, or re-run with --reformat to accept a \
                 normalised file."
            ),
        }
    }
}

/// Would writing this file back change anything we were not asked to change?
///
/// The test is a round trip: parse the file and render it with no edits at all.
/// If that already differs from what is on disk, then our renderer and the
/// author's formatting disagree — `serde_json`'s pretty printer always expands
/// arrays, so a hand-written `"allow": ["one"]` comes back over three lines —
/// and every edit we make would arrive buried in that noise.
///
/// The promise at the top of this module is that we touch nothing else. When we
/// cannot keep it, the right move is to say so and write nothing, not to keep it
/// approximately.
fn would_reformat(raw: &str, doc: &Value, indent: &str, nl: bool) -> bool {
    if raw.trim().is_empty() {
        return false;
    }
    // Re-render the document as it was READ, before any of our edits.
    match serde_json::from_str::<Value>(raw) {
        Ok(original) => {
            let _ = doc;
            render(&original, indent, nl) != raw
        }
        Err(_) => false,
    }
}

pub struct Plan {
    pub path: PathBuf,
    pub after: String,
    pub change: Change,
}

pub enum MergeError {
    Unparseable { path: PathBuf, why: String },
    WrongShape { path: PathBuf, key: &'static str },
    NotAFile(PathBuf),
}

impl MergeError {
    pub fn explain(&self) -> String {
        match self {
            MergeError::Unparseable { path, why } => format!(
                "{} is not valid JSON ({why}).\n\
                 Refusing to edit it — fix the file, or paste the block below in by hand.",
                path.display()
            ),
            MergeError::WrongShape { path, key } => format!(
                "{} has a `{key}` that is not the shape Claude Code expects; refusing to edit it",
                path.display()
            ),
            MergeError::NotAFile(p) => format!(
                "{} is not a regular file; refusing to write through it",
                p.display()
            ),
        }
    }
}

/// The handler we write. Three deliberate choices, each of which has a failure
/// mode attached:
///
/// * **An absolute path.** A command resolved from `PATH` exits 127 the moment
///   `PATH` differs — and 127 lands in Claude Code's *non-blocking* bucket, so
///   the guard is silently gone with nothing to notice it.
/// * **A positional verb first.** `crates/amont/src/main.rs` learned this the
///   hard way: only position 0 should ever decide what runs.
/// * **No `if` field.** `if: "Bash(git *)"` looks like a cheap prefilter, but
///   it fails open when it cannot parse a command and would silently drop every
///   non-git rule. This hook is not slow enough to need it.
fn handler(bin: &Path) -> Value {
    json!({
        "type": "command",
        "command": bin.display().to_string(),
        "args": ["hook"],
        "timeout": 10
    })
}

pub fn is_ours(h: &Value) -> bool {
    h.get("command")
        .and_then(|c| c.as_str())
        .map(|c| {
            Path::new(c)
                .file_name()
                .is_some_and(|n| n.to_string_lossy().trim_end_matches(".exe") == BIN)
        })
        .unwrap_or(false)
}

/// Two spaces unless the file says otherwise, and whether it ended in a
/// newline. Preserving both is the difference between a one-line diff and a
/// diff that looks like we rewrote the file.
fn shape(raw: &str) -> (String, bool) {
    let indent = raw
        .lines()
        .find_map(|l| {
            let ws: String = l.chars().take_while(|c| *c == ' ' || *c == '\t').collect();
            if !ws.is_empty() && l.trim_start().starts_with('"') {
                Some(ws)
            } else {
                None
            }
        })
        .unwrap_or_else(|| "  ".to_string());
    (indent, raw.ends_with('\n'))
}

fn render(doc: &Value, indent: &str, trailing_newline: bool) -> String {
    let mut buf = Vec::new();
    let fmt = serde_json::ser::PrettyFormatter::with_indent(indent.as_bytes());
    let mut ser = serde_json::Serializer::with_formatter(&mut buf, fmt);
    use serde::Serialize;
    doc.serialize(&mut ser).expect("a Value always serialises");
    let mut out = String::from_utf8(buf).expect("serde_json emits UTF-8");
    if trailing_newline {
        out.push('\n');
    }
    out
}

fn read(path: &Path) -> Result<(Value, String), MergeError> {
    if path.exists() {
        let meta =
            std::fs::symlink_metadata(path).map_err(|_| MergeError::NotAFile(path.into()))?;
        // A symlink is allowed; `commit_all` renames over it, which replaces
        // the link rather than writing through to whatever it points at.
        if !meta.is_file() && !meta.file_type().is_symlink() {
            return Err(MergeError::NotAFile(path.into()));
        }
        let raw = std::fs::read_to_string(path).map_err(|_| MergeError::NotAFile(path.into()))?;
        if raw.trim().is_empty() {
            return Ok((Value::Object(Map::new()), raw));
        }
        let doc = serde_json::from_str(&raw).map_err(|e| MergeError::Unparseable {
            path: path.into(),
            why: e.to_string(),
        })?;
        Ok((doc, raw))
    } else {
        Ok((Value::Object(Map::new()), String::new()))
    }
}

/// Where we install, and why each one is there.
///
/// `SessionStart` is not decoration. It fires once per session and writes a
/// heartbeat, which is the ONLY way `doctor` can tell "no rule fired this week"
/// apart from "the guard has been dead since Tuesday". Writing that heartbeat
/// from `PreToolUse` instead would put a filesystem write on the path that runs
/// before every shell command — the one path this crate promises to keep free.
pub const TARGETS: &[(&str, Option<&str>)] =
    &[("PreToolUse", Some("Bash")), ("SessionStart", None)];

/// Add our handler to one event, joining an existing block rather than adding a
/// competing one. Returns whether anything changed.
fn ensure(
    hooks: &mut Map<String, Value>,
    path: &Path,
    event: &str,
    matcher: Option<&str>,
    want: &Value,
) -> Result<(), MergeError> {
    let list = hooks
        .entry(event.to_string())
        .or_insert_with(|| Value::Array(Vec::new()));
    let list = list.as_array_mut().ok_or(MergeError::WrongShape {
        path: path.into(),
        key: "an event",
    })?;

    for block in list.iter_mut() {
        if block.get("matcher").and_then(|m| m.as_str()) != matcher {
            continue;
        }
        let Some(handlers) = block.get_mut("hooks").and_then(|h| h.as_array_mut()) else {
            continue;
        };
        if let Some(mine) = handlers.iter_mut().find(|h| is_ours(h)) {
            *mine = want.clone();
        } else {
            // Somebody else already hooks this event. Join them.
            handlers.push(want.clone());
        }
        return Ok(());
    }

    let block = match matcher {
        Some(m) => json!({ "matcher": m, "hooks": [want] }),
        None => json!({ "hooks": [want] }),
    };
    list.push(block);
    Ok(())
}

pub fn plan_install(path: &Path, bin: &Path, reformat: bool) -> Result<Plan, MergeError> {
    let (mut doc, raw) = read(path)?;
    let (indent, nl) = shape(&raw);
    if !reformat && would_reformat(&raw, &doc, &indent, nl) {
        return Ok(Plan {
            path: path.into(),
            after: raw,
            change: Change::WouldReformat,
        });
    }
    let before = raw.clone();

    let root = doc.as_object_mut().ok_or(MergeError::WrongShape {
        path: path.into(),
        key: "(root)",
    })?;
    let existed = root.contains_key("hooks");
    let hooks = root
        .entry("hooks")
        .or_insert_with(|| Value::Object(Map::new()));
    let hooks = hooks.as_object_mut().ok_or(MergeError::WrongShape {
        path: path.into(),
        key: "hooks",
    })?;

    let want = handler(bin);
    for (event, matcher) in TARGETS {
        ensure(hooks, path, event, *matcher, &want)?;
    }

    let after = render(&doc, &indent, nl || before.is_empty());
    let change = if after == before {
        Change::AlreadyCurrent
    } else if existed {
        Change::Update
    } else {
        Change::Add
    };
    Ok(Plan {
        path: path.into(),
        after,
        change,
    })
}

pub fn plan_uninstall(path: &Path, reformat: bool) -> Result<Plan, MergeError> {
    let (mut doc, raw) = read(path)?;
    let (indent, nl) = shape(&raw);
    if raw.is_empty() {
        return Ok(Plan {
            path: path.into(),
            after: raw,
            change: Change::NothingToRemove,
        });
    }
    if !reformat && would_reformat(&raw, &doc, &indent, nl) {
        return Ok(Plan {
            path: path.into(),
            after: raw,
            change: Change::WouldReformat,
        });
    }

    let mut removed = false;
    for (event, _) in TARGETS {
        let Some(list) = doc
            .get_mut("hooks")
            .and_then(|h| h.get_mut(*event))
            .and_then(|p| p.as_array_mut())
        else {
            continue;
        };
        // Which blocks we emptied, by position. The old shape dropped every
        // block with an empty `hooks` array, which is not the same set: a
        // block the AUTHOR left empty — a matcher they are still deciding
        // about — was swept away by an uninstall that had nothing to do with
        // it. "We remove exactly what we added" is the promise at the top of
        // this module, and an empty block we never touched is not ours.
        let mut emptied: Vec<usize> = Vec::new();
        for (i, block) in list.iter_mut().enumerate() {
            if let Some(handlers) = block.get_mut("hooks").and_then(|h| h.as_array_mut()) {
                let before = handlers.len();
                handlers.retain(|h| !is_ours(h));
                if handlers.len() != before {
                    removed = true;
                    if handlers.is_empty() {
                        emptied.push(i);
                    }
                }
            }
        }
        let mut at = 0;
        list.retain(|_| {
            let keep = !emptied.contains(&at);
            at += 1;
            keep
        });
        if list.is_empty() {
            if let Some(hooks) = doc.get_mut("hooks").and_then(|h| h.as_object_mut()) {
                hooks.remove(*event);
            }
        }
    }
    if let Some(hooks) = doc.get("hooks").and_then(|h| h.as_object()) {
        if hooks.is_empty() {
            if let Some(root) = doc.as_object_mut() {
                root.remove("hooks");
            }
        }
    }

    if !removed {
        return Ok(Plan {
            path: path.into(),
            after: raw,
            change: Change::NothingToRemove,
        });
    }
    Ok(Plan {
        path: path.into(),
        after: render(&doc, &indent, nl),
        change: Change::Remove,
    })
}

/// Write the plan, atomically. Staged to a temp file next to the destination,
/// then renamed — so a symlinked `settings.json` is replaced rather than
/// written through, and a crash mid-write cannot leave a half-file.
pub fn apply(plan: &Plan) -> std::io::Result<()> {
    if matches!(
        plan.change,
        Change::AlreadyCurrent | Change::NothingToRemove | Change::WouldReformat
    ) {
        return Ok(());
    }
    if let Some(parent) = plan.path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    crate::atomic::write_atomic(&plan.path, &plan.after)
}

/// The block to paste when we will not write it ourselves.
pub fn snippet(bin: &Path) -> String {
    let want = handler(bin);
    let mut hooks = Map::new();
    for (event, matcher) in TARGETS {
        let block = match matcher {
            Some(m) => json!({ "matcher": m, "hooks": [want.clone()] }),
            None => json!({ "hooks": [want.clone()] }),
        };
        hooks.insert((*event).to_string(), Value::Array(vec![block]));
    }
    render(&json!({ "hooks": hooks }), "  ", true)
}