klasp-agents-claude 0.4.0

Claude Code agent surface for klasp — installs the PreToolUse hook that gates AI commits.
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
//! Surgical merge of klasp's hook entry into `.claude/settings.json`.
//!
//! Highest-risk module of v0.1 — see [docs/design.md §5] (closing line) and
//! §14 (4th bullet on key-order roundtrip). Every key the user (or any
//! sibling tool: fallow, claude-code itself, the user's own pre-tool hooks)
//! has set must survive untouched. Idempotency is by exact match on the
//! `command` string of klasp's hook entry: re-running the merge with the
//! same input produces a byte-identical output.

use serde_json::{Map, Value};
use thiserror::Error;

// Claude Code's `.claude/settings.json` hook schema. These keys appear
// across the merge / unmerge / lookup helpers; pinning them as constants
// turns a typo into a compile error instead of a silent no-op.
const HOOKS: &str = "hooks";
const PRETOOL_USE: &str = "PreToolUse";
const MATCHER: &str = "matcher";
const TYPE: &str = "type";
const COMMAND: &str = "command";
const BASH: &str = "Bash";

#[derive(Debug, Error)]
pub enum SettingsError {
    #[error("settings.json: invalid JSON: {0}")]
    Parse(#[from] serde_json::Error),

    /// Some node along the path `hooks.PreToolUse[*]` has a JSON type that
    /// conflicts with the Claude Code hook schema. We refuse to coerce
    /// (silently dropping a user's data is the worst possible outcome).
    #[error("settings.json: at `{path}`, expected {expected} but found {got}")]
    Shape {
        path: String,
        expected: &'static str,
        got: &'static str,
    },
}

/// Append klasp's PreToolUse `Bash` hook entry to `settings_json`, returning
/// the new file body. Idempotent: if an entry with the exact `hook_command`
/// is already present, returns the input unchanged (modulo re-serialisation
/// whitespace — see §14).
///
/// Empty input is treated as `"{}"`, so the call site doesn't have to special-case
/// missing settings files.
pub fn merge_hook_entry(settings_json: &str, hook_command: &str) -> Result<String, SettingsError> {
    let trimmed = settings_json.trim();
    let mut root: Value = if trimmed.is_empty() {
        Value::Object(Map::new())
    } else {
        serde_json::from_str(trimmed)?
    };

    let root_obj = expect_object_mut(&mut root, "")?;

    let hooks = get_or_insert_object(root_obj, HOOKS, HOOKS)?;
    let pretool = get_or_insert_array(hooks, PRETOOL_USE, "hooks.PreToolUse")?;

    let bash_idx = find_bash_matcher(pretool)?;
    let bash_entry = match bash_idx {
        Some(i) => &mut pretool[i],
        None => {
            pretool.push(Value::Object({
                let mut m = Map::new();
                m.insert(MATCHER.into(), Value::String(BASH.into()));
                m.insert(HOOKS.into(), Value::Array(Vec::new()));
                m
            }));
            pretool.last_mut().expect("just pushed")
        }
    };

    let bash_obj = expect_object_mut(bash_entry, "hooks.PreToolUse[Bash]")?;
    let inner = get_or_insert_array(bash_obj, HOOKS, "hooks.PreToolUse[Bash].hooks")?;

    if !inner.iter().any(|h| hook_command_matches(h, hook_command)) {
        let mut entry = Map::new();
        entry.insert(TYPE.into(), Value::String(COMMAND.into()));
        entry.insert(COMMAND.into(), Value::String(hook_command.into()));
        inner.push(Value::Object(entry));
    }

    Ok(serialise(&root))
}

/// Inverse of [`merge_hook_entry`]: remove every hook with `command` exactly
/// equal to `hook_command`, then clean up the empty `Bash` matcher and
/// surrounding `hooks.PreToolUse` / `hooks` containers when they're left
/// empty. After install→uninstall, an `.claude/settings.json` that had no
/// pre-existing hook content returns to `{}`.
///
/// Round-trip is best-effort, not byte-identical: serialised output uses
/// 2-space pretty-print + trailing newline regardless of pre-install
/// formatting. A pre-existing `{matcher: "Bash", hooks: []}` placeholder
/// is also dropped — we can't distinguish "klasp emptied this" from
/// "user pre-installed an empty placeholder" — but that shape is rare in
/// practice. Non-Bash matchers and Bash matchers with surviving sibling
/// hooks are preserved.
///
/// Idempotent: running on a settings.json that has no klasp entry parses
/// and re-serialises (whitespace may differ but JSON content is unchanged).
pub fn unmerge_hook_entry(
    settings_json: &str,
    hook_command: &str,
) -> Result<String, SettingsError> {
    let trimmed = settings_json.trim();
    if trimmed.is_empty() {
        return Ok(String::new());
    }

    let mut root: Value = serde_json::from_str(trimmed)?;
    let root_obj = expect_object_mut(&mut root, "")?;

    let Some(hooks_val) = root_obj.get_mut(HOOKS) else {
        return Ok(serialise(&root));
    };
    let hooks = expect_object_mut(hooks_val, HOOKS)?;

    let Some(pretool_val) = hooks.get_mut(PRETOOL_USE) else {
        return Ok(serialise(&root));
    };
    let pretool = expect_array_mut(pretool_val, "hooks.PreToolUse")?;

    for matcher in pretool.iter_mut() {
        let Some(matcher_obj) = matcher.as_object_mut() else {
            continue;
        };
        let Some(inner_val) = matcher_obj.get_mut(HOOKS) else {
            continue;
        };
        let Some(inner) = inner_val.as_array_mut() else {
            continue;
        };
        inner.retain(|h| !hook_command_matches(h, hook_command));
    }

    // See the function doc-comment for why pre-existing empty Bash
    // placeholders are also swept (provenance is unrecoverable).
    pretool.retain(|m| {
        let Some(obj) = m.as_object() else {
            return true;
        };
        if obj.get(MATCHER).and_then(Value::as_str) != Some(BASH) {
            return true;
        }
        !matches!(
            obj.get(HOOKS).and_then(Value::as_array),
            Some(arr) if arr.is_empty()
        )
    });

    if pretool.is_empty() {
        hooks.remove(PRETOOL_USE);
    }
    if hooks.is_empty() {
        root_obj.remove(HOOKS);
    }

    Ok(serialise(&root))
}

fn serialise(value: &Value) -> String {
    let mut out = serde_json::to_string_pretty(value).expect("Value -> string is infallible");
    out.push('\n');
    out
}

fn expect_object_mut<'a>(
    value: &'a mut Value,
    path: &str,
) -> Result<&'a mut Map<String, Value>, SettingsError> {
    let got = describe(value);
    value.as_object_mut().ok_or_else(|| SettingsError::Shape {
        path: path.to_string(),
        expected: "object",
        got,
    })
}

fn expect_array_mut<'a>(
    value: &'a mut Value,
    path: &str,
) -> Result<&'a mut Vec<Value>, SettingsError> {
    let got = describe(value);
    value.as_array_mut().ok_or_else(|| SettingsError::Shape {
        path: path.to_string(),
        expected: "array",
        got,
    })
}

fn get_or_insert_object<'a>(
    map: &'a mut Map<String, Value>,
    key: &str,
    path: &str,
) -> Result<&'a mut Map<String, Value>, SettingsError> {
    let entry = map.entry(key).or_insert_with(|| Value::Object(Map::new()));
    let got = describe(entry);
    entry.as_object_mut().ok_or(SettingsError::Shape {
        path: path.to_string(),
        expected: "object",
        got,
    })
}

fn get_or_insert_array<'a>(
    map: &'a mut Map<String, Value>,
    key: &str,
    path: &str,
) -> Result<&'a mut Vec<Value>, SettingsError> {
    let entry = map.entry(key).or_insert_with(|| Value::Array(Vec::new()));
    let got = describe(entry);
    entry.as_array_mut().ok_or(SettingsError::Shape {
        path: path.to_string(),
        expected: "array",
        got,
    })
}

fn find_bash_matcher(pretool: &[Value]) -> Result<Option<usize>, SettingsError> {
    for (i, m) in pretool.iter().enumerate() {
        let Some(obj) = m.as_object() else {
            return Err(SettingsError::Shape {
                path: format!("hooks.PreToolUse[{i}]"),
                expected: "object",
                got: describe(m),
            });
        };
        if obj.get(MATCHER).and_then(Value::as_str) == Some(BASH) {
            return Ok(Some(i));
        }
    }
    Ok(None)
}

fn hook_command_matches(hook: &Value, expected_command: &str) -> bool {
    hook.get(COMMAND).and_then(Value::as_str) == Some(expected_command)
}

fn describe(v: &Value) -> &'static str {
    match v {
        Value::Null => "null",
        Value::Bool(_) => "boolean",
        Value::Number(_) => "number",
        Value::String(_) => "string",
        Value::Array(_) => "array",
        Value::Object(_) => "object",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const KLASP_CMD: &str = "${CLAUDE_PROJECT_DIR}/.claude/hooks/klasp-gate.sh";

    fn parse(s: &str) -> Value {
        serde_json::from_str(s).expect("test fixture must be valid JSON")
    }

    #[test]
    fn merge_into_empty_creates_full_path() {
        let out = merge_hook_entry("", KLASP_CMD).unwrap();
        let v = parse(&out);
        assert_eq!(
            v["hooks"]["PreToolUse"][0]["matcher"],
            Value::String("Bash".into())
        );
        let hook = &v["hooks"]["PreToolUse"][0]["hooks"][0];
        assert_eq!(hook["type"], Value::String("command".into()));
        assert_eq!(hook["command"], Value::String(KLASP_CMD.into()));
    }

    #[test]
    fn merge_into_empty_object_creates_full_path() {
        let out = merge_hook_entry("{}", KLASP_CMD).unwrap();
        let v = parse(&out);
        assert_eq!(v["hooks"]["PreToolUse"][0]["matcher"], "Bash");
    }

    #[test]
    fn merge_preserves_unrelated_top_level_keys() {
        let input = r#"{
            "theme": "dark",
            "permissions": { "allow": ["Read"] }
        }"#;
        let out = merge_hook_entry(input, KLASP_CMD).unwrap();
        let v = parse(&out);
        assert_eq!(v["theme"], "dark");
        assert_eq!(v["permissions"]["allow"][0], "Read");
    }

    #[test]
    fn merge_preserves_sibling_hook_types() {
        let input = r#"{
            "hooks": {
                "PostToolUse": [
                    { "matcher": "Write", "hooks": [{ "type": "command", "command": "echo wrote" }] }
                ]
            }
        }"#;
        let out = merge_hook_entry(input, KLASP_CMD).unwrap();
        let v = parse(&out);
        assert_eq!(v["hooks"]["PostToolUse"][0]["matcher"], "Write");
        assert_eq!(
            v["hooks"]["PostToolUse"][0]["hooks"][0]["command"],
            "echo wrote"
        );
        assert_eq!(v["hooks"]["PreToolUse"][0]["matcher"], "Bash");
    }

    #[test]
    fn merge_appends_alongside_existing_bash_hooks() {
        let input = r#"{
            "hooks": {
                "PreToolUse": [
                    {
                        "matcher": "Bash",
                        "hooks": [
                            { "type": "command", "command": "fallow gate" }
                        ]
                    }
                ]
            }
        }"#;
        let out = merge_hook_entry(input, KLASP_CMD).unwrap();
        let v = parse(&out);
        let inner = v["hooks"]["PreToolUse"][0]["hooks"].as_array().unwrap();
        assert_eq!(inner.len(), 2);
        assert_eq!(inner[0]["command"], "fallow gate");
        assert_eq!(inner[1]["command"], KLASP_CMD);
    }

    #[test]
    fn merge_is_idempotent() {
        let once = merge_hook_entry("{}", KLASP_CMD).unwrap();
        let twice = merge_hook_entry(&once, KLASP_CMD).unwrap();
        assert_eq!(once, twice);
    }

    #[test]
    fn merge_does_not_duplicate_existing_klasp_entry() {
        let input = format!(
            r#"{{
                "hooks": {{
                    "PreToolUse": [
                        {{
                            "matcher": "Bash",
                            "hooks": [
                                {{ "type": "command", "command": "{KLASP_CMD}" }}
                            ]
                        }}
                    ]
                }}
            }}"#
        );
        let out = merge_hook_entry(&input, KLASP_CMD).unwrap();
        let v = parse(&out);
        let inner = v["hooks"]["PreToolUse"][0]["hooks"].as_array().unwrap();
        assert_eq!(inner.len(), 1);
        assert_eq!(inner[0]["command"], KLASP_CMD);
    }

    #[test]
    fn merge_creates_bash_matcher_alongside_other_matchers() {
        let input = r#"{
            "hooks": {
                "PreToolUse": [
                    { "matcher": "Write|Edit", "hooks": [{ "type": "command", "command": "lint" }] }
                ]
            }
        }"#;
        let out = merge_hook_entry(input, KLASP_CMD).unwrap();
        let v = parse(&out);
        let arr = v["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(arr.len(), 2);
        assert_eq!(arr[0]["matcher"], "Write|Edit");
        assert_eq!(arr[1]["matcher"], "Bash");
    }

    #[test]
    fn merge_fails_on_malformed_json() {
        let err = merge_hook_entry("{ not json", KLASP_CMD).expect_err("must fail");
        assert!(matches!(err, SettingsError::Parse(_)));
    }

    #[test]
    fn merge_fails_when_root_is_array() {
        let err = merge_hook_entry("[]", KLASP_CMD).expect_err("must fail");
        match err {
            SettingsError::Shape {
                expected,
                got,
                path,
            } => {
                assert_eq!(expected, "object");
                assert_eq!(got, "array");
                assert_eq!(path, "");
            }
            other => panic!("expected Shape, got {other:?}"),
        }
    }

    #[test]
    fn merge_fails_when_pretooluse_is_object() {
        let input = r#"{ "hooks": { "PreToolUse": {} } }"#;
        let err = merge_hook_entry(input, KLASP_CMD).expect_err("must fail");
        assert!(matches!(err, SettingsError::Shape { .. }));
    }

    #[test]
    fn unmerge_removes_only_klasp_entry() {
        let input = format!(
            r#"{{
                "theme": "dark",
                "hooks": {{
                    "PreToolUse": [
                        {{
                            "matcher": "Bash",
                            "hooks": [
                                {{ "type": "command", "command": "fallow gate" }},
                                {{ "type": "command", "command": "{KLASP_CMD}" }}
                            ]
                        }}
                    ]
                }}
            }}"#
        );
        let out = unmerge_hook_entry(&input, KLASP_CMD).unwrap();
        let v = parse(&out);
        assert_eq!(v["theme"], "dark");
        let inner = v["hooks"]["PreToolUse"][0]["hooks"].as_array().unwrap();
        assert_eq!(inner.len(), 1);
        assert_eq!(inner[0]["command"], "fallow gate");
    }

    #[test]
    fn unmerge_drops_empty_bash_matcher_and_collapses_path() {
        let input = format!(
            r#"{{
                "hooks": {{
                    "PreToolUse": [
                        {{
                            "matcher": "Bash",
                            "hooks": [
                                {{ "type": "command", "command": "{KLASP_CMD}" }}
                            ]
                        }}
                    ]
                }}
            }}"#
        );
        let out = unmerge_hook_entry(&input, KLASP_CMD).unwrap();
        let v = parse(&out);
        assert!(v.get("hooks").is_none(), "got: {v:#?}");
    }

    #[test]
    fn unmerge_is_noop_when_klasp_not_present() {
        let input = r#"{ "theme": "dark" }"#;
        let out = unmerge_hook_entry(input, KLASP_CMD).unwrap();
        let v = parse(&out);
        assert_eq!(v["theme"], "dark");
    }

    #[test]
    fn unmerge_is_idempotent() {
        let installed = merge_hook_entry("{}", KLASP_CMD).unwrap();
        let once = unmerge_hook_entry(&installed, KLASP_CMD).unwrap();
        let twice = unmerge_hook_entry(&once, KLASP_CMD).unwrap();
        assert_eq!(once, twice);
    }

    #[test]
    fn install_uninstall_round_trip_drops_to_empty_object() {
        let installed = merge_hook_entry("{}", KLASP_CMD).unwrap();
        let restored = unmerge_hook_entry(&installed, KLASP_CMD).unwrap();
        let v = parse(&restored);
        assert!(v.as_object().unwrap().is_empty());
    }
}