frigg 0.10.0

Frigg gives AI agents local, source-backed code search and navigation without sending whole repositories through every prompt.
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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
//! JSON merge helpers for Frigg MCP server entries and Claude PreToolUse hooks in project settings.
//!
//! Merges Frigg MCP server entries and Claude PreToolUse hooks while preserving unrelated project
//! JSON keys.

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

use crate::cli_args::HookMode;

#[cfg(test)]
pub(crate) const DEFAULT_MCP_SERVER_URL: &str = "http://127.0.0.1:37444/mcp";
pub(crate) const MCP_SERVER_KEY: &str = "frigg";
const MCP_SERVERS_KEY: &str = "mcpServers";
const CLAUDE_HOOKS_KEY: &str = "hooks";
const CLAUDE_PRE_TOOL_USE_KEY: &str = "PreToolUse";
const CLAUDE_HOOK_MATCHER: &str = "Grep|Glob|Bash|Read";
const CLAUDE_HOOK_COMMAND: &str = "frigg hook pretooluse";

/// Matchers Frigg wrote in earlier releases. Still treated as Frigg-managed so adopt can migrate
/// an existing install to `CLAUDE_HOOK_MATCHER` instead of leaving a stale duplicate entry behind.
const LEGACY_CLAUDE_HOOK_MATCHERS: [&str; 1] = ["Grep|Bash|Read"];

/// True when `matcher` is one Frigg owns: the current matcher or a matcher an older Frigg wrote.
///
/// Frigg hooks a user placed under any other matcher stay untouched by upsert and uninstall.
fn is_frigg_managed_matcher(matcher: &str) -> bool {
    matcher == CLAUDE_HOOK_MATCHER || LEGACY_CLAUDE_HOOK_MATCHERS.contains(&matcher)
}

/// True when `entry` is a PreToolUse entry under a Frigg-managed matcher holding a Frigg hook.
fn entry_has_frigg_hook_under_managed_matcher(entry: &Value) -> bool {
    entry
        .get("matcher")
        .and_then(Value::as_str)
        .is_some_and(is_frigg_managed_matcher)
        && entry
            .get("hooks")
            .and_then(Value::as_array)
            .is_some_and(|hooks| hooks.iter().any(is_frigg_pretooluse_hook))
}

/// True when `entry` sits under a matcher an older Frigg wrote.
fn is_legacy_matcher_entry(entry: &Value) -> bool {
    entry
        .get("matcher")
        .and_then(Value::as_str)
        .is_some_and(|matcher| LEGACY_CLAUDE_HOOK_MATCHERS.contains(&matcher))
}

/// Strips Frigg hooks from entries under a *legacy* matcher, dropping only entries this pass
/// emptied. Returns true when anything was removed.
///
/// Runs before upsert so migrating an install rewrites one entry instead of adding a second.
/// An already-empty legacy entry is left alone: Frigg did not put it there, so it is not Frigg's
/// to delete.
fn drop_legacy_frigg_hook_entries(pre_tool_use: &mut Vec<Value>) -> bool {
    let mut emptied_by_this_pass = vec![false; pre_tool_use.len()];
    let mut removed_any = false;

    for (index, entry) in pre_tool_use.iter_mut().enumerate() {
        if !is_legacy_matcher_entry(entry) {
            continue;
        }
        let Some(hooks) = entry.get_mut("hooks").and_then(Value::as_array_mut) else {
            continue;
        };
        let before = hooks.len();
        hooks.retain(|hook| !is_frigg_pretooluse_hook(hook));
        if hooks.len() < before {
            removed_any = true;
            emptied_by_this_pass[index] = hooks.is_empty();
        }
    }

    let mut index = 0;
    pre_tool_use.retain(|_| {
        let keep = !emptied_by_this_pass[index];
        index += 1;
        keep
    });

    removed_any
}

/// Classifies whether the desired Frigg MCP server entry is absent, current, or user-diverged.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum McpEntryState {
    Missing,
    Desired,
    Diverged,
}

/// Classifies whether the desired Claude PreToolUse hook command is absent, current, or diverged.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ClaudeHookState {
    Missing,
    Desired,
    Diverged,
}

/// Outcome of a JSON merge or removal attempt against an adopt target file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum McpJsonEdit {
    Changed(String),
    Unchanged,
    Skipped,
}

/// JSON adopt-target failure: parse error, unexpected shape, or serialize failure.
#[derive(Debug)]
pub(crate) enum McpJsonError {
    Parse(serde_json::Error),
    InvalidShape(&'static str),
    Serialize(serde_json::Error),
}

impl std::fmt::Display for McpJsonError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Parse(err) => write!(formatter, "invalid JSON: {err}"),
            Self::InvalidShape(message) => formatter.write_str(message),
            Self::Serialize(err) => write!(formatter, "JSON serialization failed: {err}"),
        }
    }
}

impl std::error::Error for McpJsonError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Parse(err) | Self::Serialize(err) => Some(err),
            Self::InvalidShape(_) => None,
        }
    }
}

/// Returns the canonical Frigg MCP HTTP server entry written by adopt.
pub(crate) fn desired_mcp_server(mcp_server_url: &str) -> Value {
    json!({
        "type": "http",
        "url": mcp_server_url,
    })
}

/// Classifies the Frigg MCP server entry in existing `.mcp.json` or Cursor MCP config contents.
pub(crate) fn classify_mcp_entry(
    contents: &str,
    mcp_server_url: &str,
) -> Result<McpEntryState, McpJsonError> {
    let value: Value = serde_json::from_str(contents).map_err(McpJsonError::Parse)?;
    let root = value.as_object().ok_or(McpJsonError::InvalidShape(
        "MCP config root must be a JSON object",
    ))?;
    let Some(servers) = root.get(MCP_SERVERS_KEY) else {
        return Ok(McpEntryState::Missing);
    };
    let Some(servers) = servers.as_object() else {
        return Err(McpJsonError::InvalidShape(
            "mcpServers must be a JSON object when present",
        ));
    };
    let Some(existing) = servers.get(MCP_SERVER_KEY) else {
        return Ok(McpEntryState::Missing);
    };

    if *existing == desired_mcp_server(mcp_server_url) {
        Ok(McpEntryState::Desired)
    } else {
        Ok(McpEntryState::Diverged)
    }
}

/// Classifies an existing Frigg MCP server entry for uninstall.
///
/// Install/update remains strict about the exact resolved endpoint URL so user-diverged entries
/// are not overwritten accidentally. Uninstall treats any HTTP entry under the Frigg key as owned,
/// because earlier `adopt` runs may have resolved a different CLI bind address or port.
pub(crate) fn classify_mcp_entry_for_uninstall(
    contents: &str,
) -> Result<McpEntryState, McpJsonError> {
    let value: Value = serde_json::from_str(contents).map_err(McpJsonError::Parse)?;
    let root = value.as_object().ok_or(McpJsonError::InvalidShape(
        "MCP config root must be a JSON object",
    ))?;
    let Some(servers) = root.get(MCP_SERVERS_KEY) else {
        return Ok(McpEntryState::Missing);
    };
    let Some(servers) = servers.as_object() else {
        return Err(McpJsonError::InvalidShape(
            "mcpServers must be a JSON object when present",
        ));
    };
    let Some(existing) = servers.get(MCP_SERVER_KEY) else {
        return Ok(McpEntryState::Missing);
    };

    if is_frigg_http_mcp_entry(existing) {
        Ok(McpEntryState::Desired)
    } else {
        Ok(McpEntryState::Diverged)
    }
}

/// Desired `.mcp.json` fragment: HTTP Frigg entry only (never stdio command shape).
pub(crate) fn desired_mcp_config(mcp_server_url: &str) -> Value {
    let mut servers = Map::new();
    servers.insert(
        MCP_SERVER_KEY.to_owned(),
        desired_mcp_server(mcp_server_url),
    );

    let mut root = Map::new();
    root.insert(MCP_SERVERS_KEY.to_owned(), Value::Object(servers));
    Value::Object(root)
}

/// Inserts or updates the Frigg MCP server entry while preserving unrelated JSON keys.
pub(crate) fn upsert_mcp_server(
    contents: Option<&str>,
    force: bool,
    mcp_server_url: &str,
) -> Result<McpJsonEdit, McpJsonError> {
    let Some(contents) = contents else {
        return serialize_changed(desired_mcp_config(mcp_server_url));
    };

    let mut root = parse_object_root(contents)?;
    let servers = ensure_servers_object(&mut root)?;
    match servers.get(MCP_SERVER_KEY) {
        Some(existing) if *existing == desired_mcp_server(mcp_server_url) => {
            return Ok(McpJsonEdit::Unchanged);
        }
        Some(_) if !force => return Ok(McpJsonEdit::Skipped),
        _ => {}
    }

    servers.insert(
        MCP_SERVER_KEY.to_owned(),
        desired_mcp_server(mcp_server_url),
    );
    serialize_if_changed(Value::Object(root), contents)
}

/// Removes the Frigg MCP server entry, skipping diverged entries unless `force` is set.
pub(crate) fn remove_mcp_server(
    contents: &str,
    force: bool,
    _mcp_server_url: &str,
) -> Result<McpJsonEdit, McpJsonError> {
    let mut root = parse_object_root(contents)?;
    let Some(servers) = root.get_mut(MCP_SERVERS_KEY) else {
        return Ok(McpJsonEdit::Unchanged);
    };
    let Some(servers) = servers.as_object_mut() else {
        return Err(McpJsonError::InvalidShape(
            "mcpServers must be a JSON object when present",
        ));
    };

    match servers.get(MCP_SERVER_KEY) {
        Some(existing) if is_frigg_http_mcp_entry(existing) || force => {}
        Some(_) => return Ok(McpJsonEdit::Skipped),
        None => return Ok(McpJsonEdit::Unchanged),
    }

    servers.remove(MCP_SERVER_KEY);
    serialize_if_changed(Value::Object(root), contents)
}

pub(crate) fn desired_claude_hook_command(mode: HookMode) -> Value {
    json!({
        "type": "command",
        "command": claude_hook_command_for(mode),
        "timeout": 5,
    })
}

/// The hook command line for `mode`.
///
/// Nudge stays bare so an install written before hook modes existed keeps comparing equal and is
/// not rewritten for no reason.
fn claude_hook_command_for(mode: HookMode) -> String {
    match mode {
        HookMode::Nudge => CLAUDE_HOOK_COMMAND.to_owned(),
        HookMode::Ask => format!("{CLAUDE_HOOK_COMMAND} --mode {}", mode.as_str()),
    }
}

fn desired_claude_pre_tool_use_entry(mode: HookMode) -> Value {
    json!({
        "matcher": CLAUDE_HOOK_MATCHER,
        "hooks": [desired_claude_hook_command(mode)],
    })
}

/// Classifies whether the Frigg PreToolUse hook is present in Claude settings JSON.
pub(crate) fn classify_claude_hook(
    contents: &str,
    mode: HookMode,
) -> Result<ClaudeHookState, McpJsonError> {
    let root = parse_object_root(contents)?;
    let value = Value::Object(root);
    if value
        .get(CLAUDE_HOOKS_KEY)
        .and_then(|hooks| hooks.get(CLAUDE_PRE_TOOL_USE_KEY))
        .and_then(Value::as_array)
        .is_some_and(|pre_tool_use| pre_tool_use_contains_diverged_frigg_hook(pre_tool_use, mode))
    {
        Ok(ClaudeHookState::Diverged)
    } else if contains_desired_claude_hook(&value, mode) {
        Ok(ClaudeHookState::Desired)
    } else {
        Ok(ClaudeHookState::Missing)
    }
}

/// Inserts the Frigg PreToolUse hook command while preserving sibling Claude settings and hooks.
pub(crate) fn upsert_claude_hook(
    contents: Option<&str>,
    mode: HookMode,
) -> Result<McpJsonEdit, McpJsonError> {
    let Some(contents) = contents else {
        return serialize_changed(json!({
            CLAUDE_HOOKS_KEY: {
                CLAUDE_PRE_TOOL_USE_KEY: [desired_claude_pre_tool_use_entry(mode)],
            },
        }));
    };

    let mut root = parse_object_root(contents)?;
    let pre_tool_use = ensure_pre_tool_use_array(&mut root)?;
    let migrated_legacy = drop_legacy_frigg_hook_entries(pre_tool_use);

    if let Some(entry) = pre_tool_use.iter_mut().find(|entry| {
        entry
            .get("matcher")
            .and_then(Value::as_str)
            .is_some_and(|matcher| matcher == CLAUDE_HOOK_MATCHER)
            && entry.get("hooks").is_some_and(Value::is_array)
    }) {
        let hooks = entry
            .get_mut("hooks")
            .and_then(Value::as_array_mut)
            .expect("entry hook array was checked above");
        let already_desired = {
            let frigg_hooks = hooks
                .iter()
                .filter(|hook| is_frigg_pretooluse_hook(hook))
                .collect::<Vec<_>>();
            frigg_hooks.len() == 1 && frigg_hooks[0] == &desired_claude_hook_command(mode)
        };

        // Report Unchanged only when the entry is already desired AND no legacy entry was stripped
        // above. Returning early on a migration would discard it and leave `adopt` reporting a
        // pending change forever. Returning early otherwise keeps a semantically current file from
        // being rewritten just to reformat it.
        if already_desired && !migrated_legacy {
            return Ok(McpJsonEdit::Unchanged);
        }
        if !already_desired {
            hooks.retain(|hook| !is_frigg_pretooluse_hook(hook));
            hooks.push(desired_claude_hook_command(mode));
        }
    } else {
        pre_tool_use.push(desired_claude_pre_tool_use_entry(mode));
    }

    serialize_if_changed(Value::Object(root), contents)
}

pub(crate) fn remove_claude_hook(contents: &str) -> Result<McpJsonEdit, McpJsonError> {
    let mut root = parse_object_root(contents)?;
    let Some(hooks) = root.get_mut(CLAUDE_HOOKS_KEY) else {
        return Ok(McpJsonEdit::Unchanged);
    };
    let hooks = hooks.as_object_mut().ok_or(McpJsonError::InvalidShape(
        "hooks must be a JSON object when present",
    ))?;
    let Some(pre_tool_use) = hooks.get_mut(CLAUDE_PRE_TOOL_USE_KEY) else {
        return Ok(McpJsonEdit::Unchanged);
    };
    let pre_tool_use = pre_tool_use
        .as_array_mut()
        .ok_or(McpJsonError::InvalidShape(
            "hooks.PreToolUse must be a JSON array when present",
        ))?;

    if !pre_tool_use_contains_frigg_pretooluse_hook(pre_tool_use) {
        return Ok(McpJsonEdit::Unchanged);
    }

    for entry in pre_tool_use.iter_mut().filter(|entry| {
        entry
            .get("matcher")
            .and_then(Value::as_str)
            .is_some_and(is_frigg_managed_matcher)
    }) {
        let Some(hook_commands) = entry.get_mut("hooks").and_then(Value::as_array_mut) else {
            continue;
        };
        hook_commands.retain(|hook| !is_frigg_pretooluse_hook(hook));
    }

    serialize_if_changed(Value::Object(root), contents)
}

fn parse_object_root(contents: &str) -> Result<Map<String, Value>, McpJsonError> {
    let value: Value = serde_json::from_str(contents).map_err(McpJsonError::Parse)?;
    value.as_object().cloned().ok_or(McpJsonError::InvalidShape(
        "MCP config root must be a JSON object",
    ))
}

fn contains_desired_claude_hook(root: &Value, mode: HookMode) -> bool {
    root.get(CLAUDE_HOOKS_KEY)
        .and_then(|hooks| hooks.get(CLAUDE_PRE_TOOL_USE_KEY))
        .and_then(Value::as_array)
        .is_some_and(|pre_tool_use| pre_tool_use_contains_desired_hook(pre_tool_use, mode))
}

fn is_frigg_http_mcp_entry(entry: &Value) -> bool {
    entry.as_object().is_some_and(|server| {
        server.get("type").and_then(Value::as_str) == Some("http")
            && server.get("url").and_then(Value::as_str).is_some()
    })
}

/// True for a Frigg PreToolUse hook in any mode.
///
/// Matching the bare command as a prefix keeps uninstall and de-duplication working across modes:
/// a tree installed with `--hook-mode ask` must still be recognized as Frigg's.
fn is_frigg_pretooluse_hook(hook: &Value) -> bool {
    hook.get("command")
        .and_then(Value::as_str)
        .is_some_and(|command| {
            command == CLAUDE_HOOK_COMMAND
                || command.starts_with(&format!("{CLAUDE_HOOK_COMMAND} "))
        })
}

fn pre_tool_use_contains_desired_hook(pre_tool_use: &[Value], mode: HookMode) -> bool {
    pre_tool_use.iter().any(|entry| {
        entry
            .get("matcher")
            .and_then(Value::as_str)
            .is_some_and(|matcher| matcher == CLAUDE_HOOK_MATCHER)
            && entry
                .get("hooks")
                .and_then(Value::as_array)
                .is_some_and(|hooks| {
                    hooks
                        .iter()
                        .any(|hook| *hook == desired_claude_hook_command(mode))
                })
    })
}

fn pre_tool_use_contains_frigg_pretooluse_hook(pre_tool_use: &[Value]) -> bool {
    pre_tool_use
        .iter()
        .any(entry_has_frigg_hook_under_managed_matcher)
}

fn pre_tool_use_contains_diverged_frigg_hook(pre_tool_use: &[Value], mode: HookMode) -> bool {
    pre_tool_use.iter().any(|entry| {
        let Some(matcher) = entry.get("matcher").and_then(Value::as_str) else {
            return false;
        };
        if !is_frigg_managed_matcher(matcher) {
            return false;
        }
        entry
            .get("hooks")
            .and_then(Value::as_array)
            .is_some_and(|hooks| {
                hooks.iter().any(|hook| {
                    if !is_frigg_pretooluse_hook(hook) {
                        return false;
                    }
                    // A byte-identical command still counts as diverged under a legacy matcher:
                    // the entry has to move to `CLAUDE_HOOK_MATCHER` to pick up new tool coverage.
                    matcher != CLAUDE_HOOK_MATCHER || *hook != desired_claude_hook_command(mode)
                })
            })
    })
}

fn ensure_pre_tool_use_array(
    root: &mut Map<String, Value>,
) -> Result<&mut Vec<Value>, McpJsonError> {
    if !root.contains_key(CLAUDE_HOOKS_KEY) {
        root.insert(CLAUDE_HOOKS_KEY.to_owned(), Value::Object(Map::new()));
    }

    let hooks = root
        .get_mut(CLAUDE_HOOKS_KEY)
        .and_then(Value::as_object_mut)
        .ok_or(McpJsonError::InvalidShape(
            "hooks must be a JSON object when present",
        ))?;

    if !hooks.contains_key(CLAUDE_PRE_TOOL_USE_KEY) {
        hooks.insert(CLAUDE_PRE_TOOL_USE_KEY.to_owned(), Value::Array(Vec::new()));
    }

    hooks
        .get_mut(CLAUDE_PRE_TOOL_USE_KEY)
        .and_then(Value::as_array_mut)
        .ok_or(McpJsonError::InvalidShape(
            "hooks.PreToolUse must be a JSON array when present",
        ))
}

fn ensure_servers_object(
    root: &mut Map<String, Value>,
) -> Result<&mut Map<String, Value>, McpJsonError> {
    if !root.contains_key(MCP_SERVERS_KEY) {
        root.insert(MCP_SERVERS_KEY.to_owned(), Value::Object(Map::new()));
    }

    root.get_mut(MCP_SERVERS_KEY)
        .and_then(Value::as_object_mut)
        .ok_or(McpJsonError::InvalidShape(
            "mcpServers must be a JSON object when present",
        ))
}

fn serialize_changed(value: Value) -> Result<McpJsonEdit, McpJsonError> {
    serialize_value(value).map(McpJsonEdit::Changed)
}

fn serialize_if_changed(value: Value, original: &str) -> Result<McpJsonEdit, McpJsonError> {
    let serialized = serialize_value(value)?;
    if serialized == original {
        Ok(McpJsonEdit::Unchanged)
    } else {
        Ok(McpJsonEdit::Changed(serialized))
    }
}

fn serialize_value(value: Value) -> Result<String, McpJsonError> {
    let mut serialized = serde_json::to_string_pretty(&value).map_err(McpJsonError::Serialize)?;
    serialized.push('\n');
    Ok(serialized)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::panic, clippy::unwrap_used)]

    use serde_json::{Value, json};

    use super::{
        DEFAULT_MCP_SERVER_URL, HookMode, MCP_SERVER_KEY, McpEntryState, McpJsonEdit,
        classify_claude_hook, classify_mcp_entry, classify_mcp_entry_for_uninstall,
        desired_claude_hook_command, desired_mcp_config, desired_mcp_server, remove_claude_hook,
        remove_mcp_server, upsert_claude_hook, upsert_mcp_server,
    };

    #[test]
    fn adopt_json_merge_defaults_to_loopback_http() {
        assert_eq!(MCP_SERVER_KEY, "frigg");
        assert_eq!(DEFAULT_MCP_SERVER_URL, "http://127.0.0.1:37444/mcp");
        let desired = desired_mcp_server(DEFAULT_MCP_SERVER_URL);
        assert_eq!(desired.get("type").and_then(Value::as_str), Some("http"));
        assert_eq!(
            desired.get("url").and_then(Value::as_str),
            Some(DEFAULT_MCP_SERVER_URL)
        );
        assert!(
            desired.get("command").is_none(),
            "managed MCP entry must not be stdio command-spawn shape"
        );
    }

    #[test]
    fn adopt_json_merge_desired_config_has_frigg_server_key() {
        let config = desired_mcp_config(DEFAULT_MCP_SERVER_URL);

        assert_eq!(
            config["mcpServers"][MCP_SERVER_KEY],
            desired_mcp_server(DEFAULT_MCP_SERVER_URL),
            "desired config should contain the fixed Frigg MCP entry"
        );
    }

    #[test]
    fn desired_mcp_server_uses_resolved_http_endpoint_url() {
        let custom_url = "http://127.0.0.1:5000/mcp";
        assert_eq!(
            desired_mcp_server(custom_url),
            json!({
                "type": "http",
                "url": custom_url,
            })
        );
        assert_eq!(
            upsert_mcp_server(None, false, custom_url).expect("create custom config"),
            McpJsonEdit::Changed(
                "{\n  \"mcpServers\": {\n    \"frigg\": {\n      \"type\": \"http\",\n      \"url\": \"http://127.0.0.1:5000/mcp\"\n    }\n  }\n}\n"
                    .to_owned()
            )
        );
    }

    #[test]
    fn adopt_json_merge_classifies_missing_desired_and_diverged_entries() {
        assert_eq!(
            classify_mcp_entry(
                r#"{"mcpServers":{"other":{"url":"http://localhost"}}}"#,
                DEFAULT_MCP_SERVER_URL
            )
            .expect("parse missing"),
            McpEntryState::Missing
        );
        assert_eq!(
            classify_mcp_entry(
                r#"{"mcpServers":{"frigg":{"type":"http","url":"http://127.0.0.1:37444/mcp"}}}"#,
                DEFAULT_MCP_SERVER_URL
            )
            .expect("parse desired"),
            McpEntryState::Desired
        );
        assert_eq!(
            classify_mcp_entry(
                r#"{"mcpServers":{"frigg":{"command":"frigg"}}}"#,
                DEFAULT_MCP_SERVER_URL
            )
            .expect("parse diverged"),
            McpEntryState::Diverged
        );
    }

    #[test]
    fn adopt_json_merge_uninstall_classifies_custom_http_port_as_owned() {
        let contents =
            r#"{"mcpServers":{"frigg":{"type":"http","url":"http://127.0.0.1:5000/mcp"}}}"#;

        assert_eq!(
            classify_mcp_entry(contents, DEFAULT_MCP_SERVER_URL).expect("strict classify"),
            McpEntryState::Diverged
        );
        assert_eq!(
            classify_mcp_entry_for_uninstall(contents).expect("uninstall classify"),
            McpEntryState::Desired
        );
    }

    #[test]
    fn adopt_json_merge_creates_missing_config() {
        assert_eq!(
            upsert_mcp_server(None, false, DEFAULT_MCP_SERVER_URL).expect("create config"),
            McpJsonEdit::Changed(
                "{\n  \"mcpServers\": {\n    \"frigg\": {\n      \"type\": \"http\",\n      \"url\": \"http://127.0.0.1:37444/mcp\"\n    }\n  }\n}\n"
                    .to_owned()
            )
        );
    }

    #[test]
    fn adopt_json_merge_adds_frigg_and_preserves_siblings() {
        let edit = upsert_mcp_server(
            Some(
                r#"{"unrelated":true,"mcpServers":{"other":{"command":"other","args":["serve"]}}}"#,
            ),
            false,
            DEFAULT_MCP_SERVER_URL,
        )
        .expect("merge config");

        let McpJsonEdit::Changed(updated) = edit else {
            panic!("expected changed edit");
        };
        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse updated");
        assert_eq!(value["unrelated"], true);
        assert_eq!(value["mcpServers"]["other"]["command"], "other");
        assert_eq!(
            value["mcpServers"][MCP_SERVER_KEY],
            desired_mcp_server(DEFAULT_MCP_SERVER_URL)
        );
    }

    #[test]
    fn adopt_json_merge_skips_diverged_frigg_without_force() {
        assert_eq!(
            upsert_mcp_server(
                Some(r#"{"mcpServers":{"frigg":{"command":"frigg"}}}"#),
                false,
                DEFAULT_MCP_SERVER_URL
            )
            .expect("merge config"),
            McpJsonEdit::Skipped
        );
    }

    #[test]
    fn adopt_json_merge_forces_diverged_frigg() {
        let edit = upsert_mcp_server(
            Some(r#"{"mcpServers":{"frigg":{"command":"frigg"},"other":{"url":"x"}}}"#),
            true,
            DEFAULT_MCP_SERVER_URL,
        )
        .expect("force merge config");

        let McpJsonEdit::Changed(updated) = edit else {
            panic!("expected changed edit");
        };
        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse updated");
        assert_eq!(
            value["mcpServers"]["frigg"],
            desired_mcp_server(DEFAULT_MCP_SERVER_URL)
        );
        assert_eq!(value["mcpServers"]["other"]["url"], "x");
    }

    #[test]
    fn adopt_json_merge_removes_only_frigg_on_uninstall() {
        let edit = remove_mcp_server(
            r#"{"mcpServers":{"frigg":{"type":"http","url":"http://127.0.0.1:37444/mcp"},"other":{"url":"x"}},"unrelated":1}"#,
            false,
            DEFAULT_MCP_SERVER_URL,
        )
        .expect("remove config");

        let McpJsonEdit::Changed(updated) = edit else {
            panic!("expected changed edit");
        };
        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse updated");
        assert!(value["mcpServers"].get("frigg").is_none());
        assert_eq!(value["mcpServers"]["other"]["url"], "x");
        assert_eq!(value["unrelated"], 1);
    }

    #[test]
    fn adopt_json_merge_uninstall_removes_custom_http_port() {
        let edit = remove_mcp_server(
            r#"{"mcpServers":{"frigg":{"type":"http","url":"http://127.0.0.1:5000/mcp"},"other":{"url":"x"}}}"#,
            false,
            DEFAULT_MCP_SERVER_URL,
        )
        .expect("remove custom-port config");

        let McpJsonEdit::Changed(updated) = edit else {
            panic!("expected changed edit");
        };
        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse updated");
        assert!(value["mcpServers"].get("frigg").is_none());
        assert_eq!(value["mcpServers"]["other"]["url"], "x");
    }

    #[test]
    fn adopt_json_merge_rejects_malformed_json_without_output() {
        let err = upsert_mcp_server(Some("{not json"), false, DEFAULT_MCP_SERVER_URL)
            .expect_err("reject malformed JSON");

        assert!(err.to_string().contains("invalid JSON"));
    }

    #[test]
    fn adopt_json_merge_rejects_non_object_root() {
        let err = upsert_mcp_server(Some("[]"), false, DEFAULT_MCP_SERVER_URL)
            .expect_err("reject non-object root");

        assert_eq!(err.to_string(), "MCP config root must be a JSON object");
    }

    #[test]
    fn adopt_json_merge_rejects_non_object_mcp_servers() {
        let err = upsert_mcp_server(Some(r#"{"mcpServers":[]}"#), false, DEFAULT_MCP_SERVER_URL)
            .expect_err("reject non-object mcpServers");

        assert_eq!(
            err.to_string(),
            "mcpServers must be a JSON object when present"
        );
    }

    #[test]
    fn adopt_json_merge_adds_claude_hook_and_preserves_siblings() {
        let edit = upsert_claude_hook(
            Some(
                r#"{"theme":"dark","hooks":{"PreToolUse":[{"matcher":"Write","hooks":[{"type":"command","command":"other"}]}],"PostToolUse":[{"matcher":"Bash","hooks":[]}]}}"#,
            ),
            HookMode::Nudge,
        )
        .expect("merge claude settings");

        let McpJsonEdit::Changed(updated) = edit else {
            panic!("expected changed edit");
        };
        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse updated");
        assert_eq!(value["theme"], "dark");
        assert_eq!(value["hooks"]["PostToolUse"][0]["matcher"], "Bash");
        assert_eq!(value["hooks"]["PreToolUse"][0]["matcher"], "Write");
        assert_eq!(
            value["hooks"]["PreToolUse"][1]["matcher"],
            "Grep|Glob|Bash|Read"
        );
        assert_eq!(
            value["hooks"]["PreToolUse"][1]["hooks"][0],
            desired_claude_hook_command(HookMode::Nudge)
        );
    }

    #[test]
    fn adopt_json_merge_claude_hook_is_idempotent() {
        let contents = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Glob|Bash|Read","hooks":[{"type":"command","command":"frigg hook pretooluse","timeout":5}]}]}}"#;

        assert_eq!(
            classify_claude_hook(contents, HookMode::Nudge).expect("classify claude hook"),
            super::ClaudeHookState::Desired
        );
        assert_eq!(
            upsert_claude_hook(Some(contents), HookMode::Nudge).expect("upsert claude hook"),
            McpJsonEdit::Unchanged
        );
    }

    #[test]
    fn claude_hook_classifies_diverged_when_timeout_differs() {
        let contents = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Glob|Bash|Read","hooks":[{"type":"command","command":"frigg hook pretooluse","timeout":10}]}]}}"#;

        assert_eq!(
            classify_claude_hook(contents, HookMode::Nudge).expect("classify diverged claude hook"),
            super::ClaudeHookState::Diverged
        );
    }

    #[test]
    fn claude_hook_classifies_mixed_desired_and_diverged_duplicates_as_diverged() {
        let contents = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Glob|Bash|Read","hooks":[{"type":"command","command":"frigg hook pretooluse","timeout":5},{"type":"command","command":"frigg hook pretooluse","timeout":10}]}]}}"#;

        assert_eq!(
            classify_claude_hook(contents, HookMode::Nudge)
                .expect("classify mixed duplicate claude hooks"),
            super::ClaudeHookState::Diverged
        );
    }

    #[test]
    fn upsert_claude_hook_replaces_diverged_frigg_hook() {
        let contents = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Glob|Bash|Read","hooks":[{"type":"command","command":"other"},{"type":"command","command":"frigg hook pretooluse","timeout":10}]}]}}"#;

        let edit = upsert_claude_hook(Some(contents), HookMode::Nudge)
            .expect("replace diverged claude hook");
        let McpJsonEdit::Changed(updated) = edit else {
            panic!("expected changed edit");
        };
        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse updated");
        let hooks = value["hooks"]["PreToolUse"][0]["hooks"]
            .as_array()
            .expect("hook array");
        assert_eq!(hooks.len(), 2);
        assert_eq!(hooks[0]["command"], "other");
        assert_eq!(hooks[1], desired_claude_hook_command(HookMode::Nudge));
    }

    #[test]
    fn upsert_claude_hook_deduplicates_existing_frigg_pretooluse_commands() {
        let contents = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Glob|Bash|Read","hooks":[{"type":"command","command":"frigg hook pretooluse","timeout":10},{"type":"command","command":"frigg hook pretooluse","timeout":5}]}]}}"#;

        let edit = upsert_claude_hook(Some(contents), HookMode::Nudge)
            .expect("deduplicate diverged claude hooks");
        let McpJsonEdit::Changed(updated) = edit else {
            panic!("expected changed edit");
        };
        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse updated");
        let hooks = value["hooks"]["PreToolUse"][0]["hooks"]
            .as_array()
            .expect("hook array");
        assert_eq!(hooks.len(), 1);
        assert_eq!(hooks[0], desired_claude_hook_command(HookMode::Nudge));
    }

    #[test]
    fn adopt_json_merge_removes_only_frigg_claude_hook() {
        let edit = remove_claude_hook(
            r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Glob|Bash|Read","hooks":[{"type":"command","command":"other"},{"type":"command","command":"frigg hook pretooluse","timeout":5}]},{"matcher":"Write","hooks":[{"type":"command","command":"frigg hook pretooluse","timeout":5},{"type":"command","command":"write-hook"}]}]},"unrelated":true}"#,
        )
        .expect("remove claude hook");

        let McpJsonEdit::Changed(updated) = edit else {
            panic!("expected changed edit");
        };
        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse updated");
        assert_eq!(value["unrelated"], true);
        assert_eq!(
            value["hooks"]["PreToolUse"][0]["hooks"]
                .as_array()
                .unwrap()
                .len(),
            1
        );
        assert_eq!(
            value["hooks"]["PreToolUse"][0]["hooks"][0]["command"],
            "other"
        );
        assert_eq!(value["hooks"]["PreToolUse"][1]["matcher"], "Write");
        assert_eq!(
            value["hooks"]["PreToolUse"][1]["hooks"][0],
            desired_claude_hook_command(HookMode::Nudge)
        );
        assert_eq!(
            value["hooks"]["PreToolUse"][1]["hooks"][1]["command"],
            "write-hook"
        );
    }

    #[test]
    fn adopt_json_merge_rejects_malformed_claude_settings_without_output() {
        let err = upsert_claude_hook(Some("{not json"), HookMode::Nudge)
            .expect_err("reject malformed JSON");

        assert!(err.to_string().contains("invalid JSON"));
    }

    /// Path to a file in the bundled skill tree, or None when the tree is not next to the crate.
    fn bundled_skill_file(rel: &str) -> Option<String> {
        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../..")
            .join("skills/frigg-first-code-search")
            .join(rel);
        std::fs::read_to_string(path).ok()
    }

    /// SSOT: the bundled Claude plugin must declare the same PreToolUse wiring adopt writes into
    /// `.claude/settings.json`. Two sources of truth would silently diverge on the next matcher
    /// change, leaving plugin users on stale tool coverage.
    #[test]
    fn bundled_claude_plugin_hook_matches_the_managed_hook() {
        let Some(contents) = bundled_skill_file("hooks/hooks.json") else {
            return;
        };
        let value: Value = serde_json::from_str(&contents).expect("plugin hooks.json must be JSON");

        let entry = &value["hooks"]["PreToolUse"][0];
        assert_eq!(
            entry["matcher"],
            super::CLAUDE_HOOK_MATCHER,
            "plugin hook matcher drifted from CLAUDE_HOOK_MATCHER"
        );
        assert_eq!(
            entry["hooks"][0],
            desired_claude_hook_command(HookMode::Nudge),
            "plugin hook command drifted from the managed hook command"
        );
    }

    /// SSOT: the bundled plugin's MCP entry must match the entry adopt writes to `.mcp.json`.
    #[test]
    fn bundled_claude_plugin_mcp_entry_matches_the_managed_entry() {
        let Some(contents) = bundled_skill_file(".mcp.json") else {
            return;
        };
        let value: Value = serde_json::from_str(&contents).expect("plugin .mcp.json must be JSON");

        assert_eq!(
            value["mcpServers"][MCP_SERVER_KEY],
            desired_mcp_server(DEFAULT_MCP_SERVER_URL),
            "plugin MCP entry drifted from the managed HTTP entry"
        );
    }

    /// An install written by an older Frigg still uses the narrower matcher. It must report as
    /// diverged so `adopt` (and `adopt --check`) sees pending work rather than calling it current.
    #[test]
    fn legacy_matcher_install_classifies_as_diverged() {
        let contents = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Bash|Read","hooks":[{"type":"command","command":"frigg hook pretooluse","timeout":5}]}]}}"#;

        assert_eq!(
            classify_claude_hook(contents, HookMode::Nudge).expect("classify legacy claude hook"),
            super::ClaudeHookState::Diverged
        );
    }

    /// Migrating must rewrite the single entry in place. A second entry would double the nudge.
    #[test]
    fn upsert_migrates_legacy_matcher_without_leaving_a_duplicate_entry() {
        let contents = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Bash|Read","hooks":[{"type":"command","command":"frigg hook pretooluse","timeout":5}]}]}}"#;

        let edit =
            upsert_claude_hook(Some(contents), HookMode::Nudge).expect("migrate legacy matcher");

        let McpJsonEdit::Changed(updated) = edit else {
            panic!("expected changed edit");
        };
        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse updated");
        let pre_tool_use = value["hooks"]["PreToolUse"]
            .as_array()
            .expect("PreToolUse array");
        assert_eq!(
            pre_tool_use.len(),
            1,
            "legacy entry should be rewritten, not duplicated: {updated}"
        );
        assert_eq!(pre_tool_use[0]["matcher"], "Grep|Glob|Bash|Read");
        assert_eq!(
            pre_tool_use[0]["hooks"][0],
            desired_claude_hook_command(HookMode::Nudge)
        );
    }

    /// Migration must not discard a non-Frigg hook the user parked under the legacy matcher.
    #[test]
    fn upsert_migration_preserves_sibling_hooks_under_legacy_matcher() {
        let contents = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Bash|Read","hooks":[{"type":"command","command":"frigg hook pretooluse","timeout":5},{"type":"command","command":"audit-log"}]}]}}"#;

        let edit =
            upsert_claude_hook(Some(contents), HookMode::Nudge).expect("migrate legacy matcher");

        let McpJsonEdit::Changed(updated) = edit else {
            panic!("expected changed edit");
        };
        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse updated");
        let pre_tool_use = value["hooks"]["PreToolUse"]
            .as_array()
            .expect("PreToolUse array");
        assert_eq!(pre_tool_use.len(), 2, "kept legacy entry plus migrated one");
        assert_eq!(pre_tool_use[0]["matcher"], "Grep|Bash|Read");
        assert_eq!(pre_tool_use[0]["hooks"].as_array().unwrap().len(), 1);
        assert_eq!(pre_tool_use[0]["hooks"][0]["command"], "audit-log");
        assert_eq!(pre_tool_use[1]["matcher"], "Grep|Glob|Bash|Read");
        assert_eq!(
            pre_tool_use[1]["hooks"][0],
            desired_claude_hook_command(HookMode::Nudge)
        );
    }

    /// Regression: a Frigg hook under BOTH matchers used to classify Diverged while upsert returned
    /// Unchanged, so `adopt` planned an Update that never wrote and `adopt --check` failed forever.
    #[test]
    fn upsert_converges_when_frigg_hook_exists_under_legacy_and_current_matcher() {
        let contents = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Bash|Read","hooks":[{"type":"command","command":"frigg hook pretooluse","timeout":5}]},{"matcher":"Grep|Glob|Bash|Read","hooks":[{"type":"command","command":"frigg hook pretooluse","timeout":5}]}]}}"#;

        assert_eq!(
            classify_claude_hook(contents, HookMode::Nudge).expect("classify"),
            super::ClaudeHookState::Diverged,
            "a lingering legacy entry is pending work"
        );

        let McpJsonEdit::Changed(updated) =
            upsert_claude_hook(Some(contents), HookMode::Nudge).expect("upsert")
        else {
            panic!("upsert must write the migration, not report Unchanged");
        };

        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse updated");
        let pre_tool_use = value["hooks"]["PreToolUse"]
            .as_array()
            .expect("PreToolUse array");
        assert_eq!(
            pre_tool_use.len(),
            1,
            "legacy entry should be gone: {updated}"
        );
        assert_eq!(pre_tool_use[0]["matcher"], "Grep|Glob|Bash|Read");

        // Second run must settle.
        assert_eq!(
            classify_claude_hook(&updated, HookMode::Nudge).expect("reclassify"),
            super::ClaudeHookState::Desired
        );
        assert_eq!(
            upsert_claude_hook(Some(&updated), HookMode::Nudge).expect("second upsert"),
            McpJsonEdit::Unchanged,
            "adopt must converge on the second run"
        );
    }

    /// An empty legacy-matcher entry Frigg never wrote is the user's, not Frigg's to delete.
    #[test]
    fn upsert_preserves_user_authored_empty_legacy_entry() {
        let contents = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Bash|Read","hooks":[]}]}}"#;

        let McpJsonEdit::Changed(updated) =
            upsert_claude_hook(Some(contents), HookMode::Nudge).expect("upsert")
        else {
            panic!("expected the frigg entry to be added");
        };

        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse updated");
        let pre_tool_use = value["hooks"]["PreToolUse"]
            .as_array()
            .expect("PreToolUse array");
        assert_eq!(pre_tool_use.len(), 2, "user entry must survive: {updated}");
        assert_eq!(pre_tool_use[0]["matcher"], "Grep|Bash|Read");
        assert_eq!(pre_tool_use[0]["hooks"].as_array().unwrap().len(), 0);
        assert_eq!(pre_tool_use[1]["matcher"], "Grep|Glob|Bash|Read");
    }

    /// Uninstall has to clean an install written by an older Frigg, or `--uninstall` never converges.
    #[test]
    fn remove_cleans_legacy_matcher_install() {
        let contents = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Bash|Read","hooks":[{"type":"command","command":"frigg hook pretooluse","timeout":5}]}]}}"#;

        let edit = remove_claude_hook(contents).expect("remove legacy claude hook");

        let McpJsonEdit::Changed(updated) = edit else {
            panic!("expected changed edit");
        };
        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse updated");
        assert_eq!(
            value["hooks"]["PreToolUse"][0]["hooks"]
                .as_array()
                .expect("hooks array")
                .len(),
            0,
            "frigg hook should be gone from the legacy entry: {updated}"
        );
        assert_eq!(
            classify_claude_hook(&updated, HookMode::Nudge).expect("reclassify"),
            super::ClaudeHookState::Missing,
            "uninstall must converge on Missing"
        );
    }

    /// The bare command is what nudge installs, so an install predating hook modes stays current.
    #[test]
    fn nudge_mode_keeps_the_bare_hook_command() {
        let command = desired_claude_hook_command(HookMode::Nudge);
        assert_eq!(
            command.get("command").and_then(Value::as_str),
            Some("frigg hook pretooluse")
        );
    }

    /// Ask mode carries the flag, and switching modes is a pending change rather than a no-op.
    #[test]
    fn ask_mode_installs_the_flag_and_reports_a_mode_switch_as_diverged() {
        let command = desired_claude_hook_command(super::HookMode::Ask);
        assert_eq!(
            command.get("command").and_then(Value::as_str),
            Some("frigg hook pretooluse --mode ask")
        );

        let nudged = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Glob|Bash|Read","hooks":[{"type":"command","command":"frigg hook pretooluse","timeout":5}]}]}}"#;
        assert_eq!(
            classify_claude_hook(nudged, super::HookMode::Ask).expect("classify"),
            super::ClaudeHookState::Diverged,
            "asking for a different mode is pending work"
        );

        let McpJsonEdit::Changed(updated) =
            upsert_claude_hook(Some(nudged), super::HookMode::Ask).expect("switch mode")
        else {
            panic!("expected a rewrite");
        };
        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse");
        let hooks = value["hooks"]["PreToolUse"][0]["hooks"]
            .as_array()
            .expect("hooks array");
        assert_eq!(
            hooks.len(),
            1,
            "mode switch must replace, not append: {updated}"
        );
        assert_eq!(
            classify_claude_hook(&updated, super::HookMode::Ask).expect("reclassify"),
            super::ClaudeHookState::Desired,
            "mode switch must converge"
        );
    }

    /// Uninstall has to recognize a hook installed in any mode, or `--uninstall` never converges.
    #[test]
    fn remove_cleans_an_ask_mode_install() {
        let contents = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Glob|Bash|Read","hooks":[{"type":"command","command":"frigg hook pretooluse --mode ask","timeout":5}]}]}}"#;

        let McpJsonEdit::Changed(updated) =
            remove_claude_hook(contents).expect("remove ask-mode hook")
        else {
            panic!("expected removal");
        };
        assert_eq!(
            classify_claude_hook(&updated, super::HookMode::Ask).expect("reclassify"),
            super::ClaudeHookState::Missing
        );
    }

    /// Migrating a legacy matcher and switching mode happen in the same rewrite. Both must land,
    /// and the result must be one entry rather than the duplicated nudge migration exists to stop.
    #[test]
    fn legacy_matcher_migration_and_mode_switch_collapse_to_one_entry() {
        let contents = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Bash|Read","hooks":[{"type":"command","command":"frigg hook pretooluse","timeout":5}]}]}}"#;

        let McpJsonEdit::Changed(updated) =
            upsert_claude_hook(Some(contents), super::HookMode::Ask).expect("migrate and switch")
        else {
            panic!("expected a rewrite");
        };

        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse");
        let pre_tool_use = value["hooks"]["PreToolUse"]
            .as_array()
            .expect("PreToolUse array");
        assert_eq!(pre_tool_use.len(), 1, "one entry, not two: {updated}");
        assert_eq!(pre_tool_use[0]["matcher"], "Grep|Glob|Bash|Read");
        assert_eq!(
            pre_tool_use[0]["hooks"][0]["command"],
            "frigg hook pretooluse --mode ask"
        );
        assert_eq!(
            classify_claude_hook(&updated, super::HookMode::Ask).expect("reclassify"),
            super::ClaudeHookState::Desired
        );
    }

    /// Frigg owns its own command line in any form, so a hand-tweaked invocation is reclaimed
    /// rather than left to sit beside a second canonical copy.
    #[test]
    fn a_hand_tweaked_frigg_hook_command_is_replaced_not_duplicated() {
        let contents = r#"{"hooks":{"PreToolUse":[{"matcher":"Grep|Glob|Bash|Read","hooks":[{"type":"command","command":"frigg hook pretooluse --mode ask 2>/dev/null","timeout":5}]}]}}"#;

        let McpJsonEdit::Changed(updated) =
            upsert_claude_hook(Some(contents), HookMode::Nudge).expect("reclaim")
        else {
            panic!("expected a rewrite");
        };

        let value: serde_json::Value = serde_json::from_str(&updated).expect("parse");
        let hooks = value["hooks"]["PreToolUse"][0]["hooks"]
            .as_array()
            .expect("hooks array");
        assert_eq!(hooks.len(), 1, "reclaimed, not duplicated: {updated}");
        assert_eq!(hooks[0], desired_claude_hook_command(HookMode::Nudge));
    }
}