agpm-cli 0.4.14

AGent Package Manager - A Git-based package manager for coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
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
//! Hook merging logic for safely integrating AGPM hooks with user settings
//!
//! This module provides the critical functionality for merging AGPM-managed hooks
//! into Claude Code's settings.local.json while preserving user configurations.

use anyhow::{Context, Result};
use serde_json::Value;
use std::collections::HashMap;

use super::{AgpmHookMetadata, HookCommand, HookConfig, HookEvent, MatcherGroup};

/// Result of a merge operation for debugging and validation
#[derive(Debug)]
pub struct MergeResult {
    /// The merged hooks structure
    pub hooks: Value,
    /// Number of user hooks preserved
    pub user_hooks_preserved: usize,
    /// Number of AGPM hooks added
    pub agpm_hooks_added: usize,
    /// Number of AGPM hooks updated
    pub agpm_hooks_updated: usize,
    /// Number of AGPM hooks removed
    pub agpm_hooks_removed: usize,
}

/// Merge AGPM hooks into existing settings with comprehensive conflict resolution
///
/// This function implements a sophisticated merge strategy that:
/// 1. Preserves all user-managed hooks
/// 2. Removes outdated AGPM-managed hooks
/// 3. Adds or updates current AGPM-managed hooks
/// 4. Groups hooks by matcher pattern for efficiency
/// 5. Maintains stable ordering where possible
pub fn merge_hooks_advanced(
    existing_hooks: Option<&Value>,
    agpm_hooks: HashMap<String, HookConfig>,
    source_info: &HashMap<String, (String, String)>, // name -> (source, version)
) -> Result<MergeResult> {
    let mut merged: HashMap<String, Vec<MatcherGroup>> = HashMap::new();
    let mut stats = MergeResult {
        hooks: Value::Null,
        user_hooks_preserved: 0,
        agpm_hooks_added: 0,
        agpm_hooks_updated: 0,
        agpm_hooks_removed: 0,
    };

    // Step 1: Parse and categorize existing hooks
    let (user_hooks, existing_agpm) = parse_existing_hooks(existing_hooks)?;

    // Step 2: Preserve all user hooks
    for (event_name, groups) in user_hooks {
        stats.user_hooks_preserved += groups.iter().map(|g| g.hooks.len()).sum::<usize>();
        merged.insert(event_name, groups);
    }

    // Step 3: Track which AGPM hooks to keep
    let mut active_agpm_hooks: HashMap<String, bool> = HashMap::new();

    // Step 4: Add/update AGPM hooks
    for (name, config) in agpm_hooks {
        let (source, version) = source_info
            .get(&name)
            .ok_or_else(|| anyhow::anyhow!("Missing source info for hook: {}", name))?;

        active_agpm_hooks.insert(name.clone(), true);

        for event in &config.events {
            let event_name = event_to_string(event);

            let hook_cmd = HookCommand {
                hook_type: config.hook_type.clone(),
                command: config.command.clone(),
                timeout: config.timeout,
                agpm_metadata: Some(AgpmHookMetadata {
                    managed: true,
                    dependency_name: name.clone(),
                    source: source.clone(),
                    version: version.clone(),
                    installed_at: chrono::Utc::now().to_rfc3339(),
                }),
            };

            // Check if this hook already exists (update vs add)
            let is_update = existing_agpm
                .iter()
                .any(|(existing_name, _)| existing_name == &name);

            if is_update {
                stats.agpm_hooks_updated += 1;
            } else {
                stats.agpm_hooks_added += 1;
            }

            // Add to appropriate matcher group
            add_hook_to_groups(&mut merged, event_name, config.matcher.clone(), hook_cmd);
        }
    }

    // Step 5: Count removed AGPM hooks
    for (old_name, _) in existing_agpm {
        if !active_agpm_hooks.contains_key(&old_name) {
            stats.agpm_hooks_removed += 1;
        }
    }

    // Step 6: Convert to final structure
    stats.hooks = convert_to_value(merged)?;

    Ok(stats)
}

/// Type alias for parsed hooks result
type ParsedHooks = (
    HashMap<String, Vec<MatcherGroup>>, // User hooks
    HashMap<String, Vec<String>>,       // AGPM hooks: name -> events
);

/// Parse existing hooks and separate user-managed from AGPM-managed
fn parse_existing_hooks(existing: Option<&Value>) -> Result<ParsedHooks> {
    let mut user_hooks: HashMap<String, Vec<MatcherGroup>> = HashMap::new();
    let mut agpm_hooks: HashMap<String, Vec<String>> = HashMap::new();

    if let Some(existing) = existing
        && let Some(obj) = existing.as_object()
    {
        for (event_name, matcher_groups) in obj {
            if let Some(groups) = matcher_groups.as_array() {
                let mut user_groups = Vec::new();

                for group in groups {
                    if let Some(group_obj) = group.as_object() {
                        let matcher = group_obj
                            .get("matcher")
                            .and_then(|m| m.as_str())
                            .unwrap_or("")
                            .to_string();

                        if let Some(hooks_array) = group_obj.get("hooks").and_then(|h| h.as_array())
                        {
                            let mut user_hooks_in_group = Vec::new();

                            for hook in hooks_array {
                                // Check if this is AGPM-managed
                                if let Some(agpm_meta) = hook.get("_agpm") {
                                    if let Some(dep_name) =
                                        agpm_meta.get("dependency_name").and_then(|n| n.as_str())
                                    {
                                        agpm_hooks
                                            .entry(dep_name.to_string())
                                            .or_default()
                                            .push(event_name.clone());
                                    }
                                } else {
                                    // User-managed hook
                                    let hook_cmd: HookCommand =
                                        serde_json::from_value(hook.clone())
                                            .context("Failed to parse user hook")?;
                                    user_hooks_in_group.push(hook_cmd);
                                }
                            }

                            // Only keep the group if it has user hooks
                            if !user_hooks_in_group.is_empty() {
                                user_groups.push(MatcherGroup {
                                    matcher: matcher.clone(),
                                    hooks: user_hooks_in_group,
                                });
                            }
                        }
                    }
                }

                if !user_groups.is_empty() {
                    user_hooks.insert(event_name.clone(), user_groups);
                }
            }
        }
    }

    Ok((user_hooks, agpm_hooks))
}

/// Add a hook to the appropriate matcher group
fn add_hook_to_groups(
    merged: &mut HashMap<String, Vec<MatcherGroup>>,
    event_name: String,
    matcher: String,
    hook: HookCommand,
) {
    let event_groups = merged.entry(event_name).or_default();

    // Find existing matcher group or create new one
    if let Some(group) = event_groups.iter_mut().find(|g| g.matcher == matcher) {
        // Remove any existing AGPM hook with the same dependency_name
        if let Some(ref new_meta) = hook.agpm_metadata {
            group.hooks.retain(|h| {
                h.agpm_metadata
                    .as_ref()
                    .map(|m| m.dependency_name != new_meta.dependency_name)
                    .unwrap_or(true)
            });
        }
        group.hooks.push(hook);
    } else {
        event_groups.push(MatcherGroup {
            matcher,
            hooks: vec![hook],
        });
    }
}

/// Convert event enum to string
fn event_to_string(event: &HookEvent) -> String {
    match event {
        HookEvent::PreToolUse => "PreToolUse".to_string(),
        HookEvent::PostToolUse => "PostToolUse".to_string(),
        HookEvent::Notification => "Notification".to_string(),
        HookEvent::UserPromptSubmit => "UserPromptSubmit".to_string(),
        HookEvent::Stop => "Stop".to_string(),
        HookEvent::SubagentStop => "SubagentStop".to_string(),
        HookEvent::PreCompact => "PreCompact".to_string(),
        HookEvent::SessionStart => "SessionStart".to_string(),
        HookEvent::SessionEnd => "SessionEnd".to_string(),
    }
}

/// Convert merged structure back to JSON Value
fn convert_to_value(merged: HashMap<String, Vec<MatcherGroup>>) -> Result<Value> {
    // Sort events for deterministic output
    let mut sorted_events: Vec<_> = merged.into_iter().collect();
    sorted_events.sort_by(|a, b| a.0.cmp(&b.0));

    let mut result = serde_json::Map::new();

    for (event_name, mut groups) in sorted_events {
        // Sort matcher groups for deterministic output
        groups.sort_by(|a, b| a.matcher.cmp(&b.matcher));

        let groups_value = serde_json::to_value(groups)?;
        result.insert(event_name, groups_value);
    }

    Ok(Value::Object(result))
}

/// Apply merged hooks to ClaudeSettings
pub fn apply_hooks_to_settings(
    settings: &mut crate::mcp::ClaudeSettings,
    merged_hooks: Value,
) -> Result<()> {
    // Only update if there are hooks to set
    if merged_hooks
        .as_object()
        .map(|o| o.is_empty())
        .unwrap_or(true)
    {
        settings.hooks = None;
    } else {
        settings.hooks = Some(merged_hooks);
    }
    Ok(())
}

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

    #[test]
    fn test_empty_merge() {
        let result = merge_hooks_advanced(None, HashMap::new(), &HashMap::new()).unwrap();

        assert_eq!(result.user_hooks_preserved, 0);
        assert_eq!(result.agpm_hooks_added, 0);
        assert_eq!(result.agpm_hooks_updated, 0);
        assert_eq!(result.agpm_hooks_removed, 0);
        assert_eq!(result.hooks, json!({}));
    }

    #[test]
    fn test_preserve_user_hooks() {
        let existing = json!({
            "PreToolUse": [{
                "matcher": "Bash",
                "hooks": [{
                    "type": "command",
                    "command": "user-script.sh",
                    "timeout": 5000
                }]
            }]
        });

        let result =
            merge_hooks_advanced(Some(&existing), HashMap::new(), &HashMap::new()).unwrap();

        assert_eq!(result.user_hooks_preserved, 1);
        assert_eq!(result.agpm_hooks_added, 0);

        // Verify user hook is preserved
        let hooks = result.hooks.as_object().unwrap();
        let pre_tool = hooks.get("PreToolUse").unwrap().as_array().unwrap();
        assert_eq!(pre_tool.len(), 1);
        let group = pre_tool[0].as_object().unwrap();
        assert_eq!(group.get("matcher").unwrap().as_str().unwrap(), "Bash");
        let hooks_array = group.get("hooks").unwrap().as_array().unwrap();
        assert_eq!(hooks_array.len(), 1);
        assert!(hooks_array[0].get("_agpm").is_none());
    }

    #[test]
    fn test_add_agpm_hooks() {
        let mut agpm_hooks = HashMap::new();
        agpm_hooks.insert(
            "security-hook".to_string(),
            HookConfig {
                events: vec![HookEvent::PreToolUse],
                matcher: "Bash|Write".to_string(),
                hook_type: "command".to_string(),
                command: ".claude/scripts/security.sh".to_string(),
                timeout: Some(3000),
                description: None,
            },
        );

        let mut source_info = HashMap::new();
        source_info.insert(
            "security-hook".to_string(),
            ("test-source".to_string(), "v1.0.0".to_string()),
        );

        let result = merge_hooks_advanced(None, agpm_hooks, &source_info).unwrap();

        assert_eq!(result.agpm_hooks_added, 1);
        assert_eq!(result.user_hooks_preserved, 0);

        // Verify AGPM hook was added
        let hooks = result.hooks.as_object().unwrap();
        let pre_tool = hooks.get("PreToolUse").unwrap().as_array().unwrap();
        assert_eq!(pre_tool.len(), 1);
        let group = pre_tool[0].as_object().unwrap();
        assert_eq!(
            group.get("matcher").unwrap().as_str().unwrap(),
            "Bash|Write"
        );
        let hooks_array = group.get("hooks").unwrap().as_array().unwrap();
        assert_eq!(hooks_array.len(), 1);

        // Check AGPM metadata
        let agpm_meta = hooks_array[0].get("_agpm").unwrap();
        assert_eq!(
            agpm_meta.get("dependency_name").unwrap().as_str().unwrap(),
            "security-hook"
        );
        assert_eq!(
            agpm_meta.get("source").unwrap().as_str().unwrap(),
            "test-source"
        );
        assert_eq!(
            agpm_meta.get("version").unwrap().as_str().unwrap(),
            "v1.0.0"
        );
    }

    #[test]
    fn test_merge_with_same_matcher() {
        // Existing user hook
        let existing = json!({
            "PreToolUse": [{
                "matcher": "Bash",
                "hooks": [{
                    "type": "command",
                    "command": "user-script.sh",
                    "timeout": 5000
                }]
            }]
        });

        // AGPM hook with same matcher
        let mut agpm_hooks = HashMap::new();
        agpm_hooks.insert(
            "security-hook".to_string(),
            HookConfig {
                events: vec![HookEvent::PreToolUse],
                matcher: "Bash".to_string(),
                hook_type: "command".to_string(),
                command: ".claude/scripts/security.sh".to_string(),
                timeout: Some(3000),
                description: None,
            },
        );

        let mut source_info = HashMap::new();
        source_info.insert(
            "security-hook".to_string(),
            ("test-source".to_string(), "v1.0.0".to_string()),
        );

        let result = merge_hooks_advanced(Some(&existing), agpm_hooks, &source_info).unwrap();

        assert_eq!(result.user_hooks_preserved, 1);
        assert_eq!(result.agpm_hooks_added, 1);

        // Verify both hooks are in the same matcher group
        let hooks = result.hooks.as_object().unwrap();
        let pre_tool = hooks.get("PreToolUse").unwrap().as_array().unwrap();
        assert_eq!(pre_tool.len(), 1, "Should have one matcher group");

        let group = pre_tool[0].as_object().unwrap();
        assert_eq!(group.get("matcher").unwrap().as_str().unwrap(), "Bash");

        let hooks_array = group.get("hooks").unwrap().as_array().unwrap();
        assert_eq!(hooks_array.len(), 2, "Should have both user and AGPM hooks");

        // Check that we have one user hook and one AGPM hook
        let agpm_count = hooks_array
            .iter()
            .filter(|h| h.get("_agpm").is_some())
            .count();
        assert_eq!(agpm_count, 1);

        let user_count = hooks_array
            .iter()
            .filter(|h| h.get("_agpm").is_none())
            .count();
        assert_eq!(user_count, 1);
    }

    #[test]
    fn test_update_existing_agpm_hook() {
        // Existing AGPM hook
        let existing = json!({
            "PreToolUse": [{
                "matcher": "Bash",
                "hooks": [{
                    "type": "command",
                    "command": ".claude/scripts/old-security.sh",
                    "timeout": 5000,
                    "_agpm": {
                        "managed": true,
                        "dependency_name": "security-hook",
                        "source": "test-source",
                        "version": "v0.9.0",
                        "installed_at": "2024-01-01T00:00:00Z"
                    }
                }]
            }]
        });

        let mut agpm_hooks = HashMap::new();
        agpm_hooks.insert(
            "security-hook".to_string(),
            HookConfig {
                events: vec![HookEvent::PreToolUse],
                matcher: "Bash".to_string(),
                hook_type: "command".to_string(),
                command: ".claude/scripts/new-security.sh".to_string(),
                timeout: Some(3000),
                description: None,
            },
        );

        let mut source_info = HashMap::new();
        source_info.insert(
            "security-hook".to_string(),
            ("test-source".to_string(), "v1.0.0".to_string()),
        );

        let result = merge_hooks_advanced(Some(&existing), agpm_hooks, &source_info).unwrap();

        assert_eq!(result.user_hooks_preserved, 0);
        assert_eq!(result.agpm_hooks_added, 0);
        assert_eq!(result.agpm_hooks_updated, 1);
        assert_eq!(result.agpm_hooks_removed, 0);

        // Verify hook was updated
        let hooks = result.hooks.as_object().unwrap();
        let pre_tool = hooks.get("PreToolUse").unwrap().as_array().unwrap();
        assert_eq!(pre_tool.len(), 1);

        let group = pre_tool[0].as_object().unwrap();
        let hooks_array = group.get("hooks").unwrap().as_array().unwrap();
        assert_eq!(hooks_array.len(), 1);

        // Check updated values
        let hook = &hooks_array[0];
        assert_eq!(
            hook.get("command").unwrap().as_str().unwrap(),
            ".claude/scripts/new-security.sh"
        );
        assert_eq!(hook.get("timeout").unwrap().as_u64().unwrap(), 3000);

        let agpm_meta = hook.get("_agpm").unwrap();
        assert_eq!(
            agpm_meta.get("version").unwrap().as_str().unwrap(),
            "v1.0.0"
        );
    }

    #[test]
    fn test_remove_outdated_agpm_hooks() {
        // Existing with two AGPM hooks
        let existing = json!({
            "PreToolUse": [{
                "matcher": "Bash",
                "hooks": [{
                    "type": "command",
                    "command": ".claude/scripts/keep.sh",
                    "_agpm": {
                        "managed": true,
                        "dependency_name": "keep-hook",
                        "source": "test-source",
                        "version": "v1.0.0",
                        "installed_at": "2024-01-01T00:00:00Z"
                    }
                }]
            }, {
                "matcher": "Write",
                "hooks": [{
                    "type": "command",
                    "command": ".claude/scripts/remove.sh",
                    "_agpm": {
                        "managed": true,
                        "dependency_name": "remove-hook",
                        "source": "test-source",
                        "version": "v1.0.0",
                        "installed_at": "2024-01-01T00:00:00Z"
                    }
                }]
            }]
        });

        // Only keep one hook
        let mut agpm_hooks = HashMap::new();
        agpm_hooks.insert(
            "keep-hook".to_string(),
            HookConfig {
                events: vec![HookEvent::PreToolUse],
                matcher: "Bash".to_string(),
                hook_type: "command".to_string(),
                command: ".claude/scripts/keep.sh".to_string(),
                timeout: None,
                description: None,
            },
        );

        let mut source_info = HashMap::new();
        source_info.insert(
            "keep-hook".to_string(),
            ("test-source".to_string(), "v1.0.0".to_string()),
        );

        let result = merge_hooks_advanced(Some(&existing), agpm_hooks, &source_info).unwrap();

        assert_eq!(result.agpm_hooks_removed, 1);
        assert_eq!(result.agpm_hooks_updated, 1);

        // Verify only one hook remains
        let hooks = result.hooks.as_object().unwrap();
        let pre_tool = hooks.get("PreToolUse").unwrap().as_array().unwrap();
        assert_eq!(pre_tool.len(), 1);

        // The "Write" matcher group should be gone
        assert!(
            !pre_tool
                .iter()
                .any(|g| g.get("matcher").and_then(|m| m.as_str()) == Some("Write"))
        );
    }

    #[test]
    fn test_multiple_events_same_hook() {
        let mut agpm_hooks = HashMap::new();
        agpm_hooks.insert(
            "multi-event-hook".to_string(),
            HookConfig {
                events: vec![
                    HookEvent::PreToolUse,
                    HookEvent::PostToolUse,
                    HookEvent::UserPromptSubmit,
                ],
                matcher: ".*".to_string(),
                hook_type: "command".to_string(),
                command: "multi-event.sh".to_string(),
                timeout: Some(1000),
                description: None,
            },
        );

        let mut source_info = HashMap::new();
        source_info.insert(
            "multi-event-hook".to_string(),
            ("test-source".to_string(), "v1.0.0".to_string()),
        );

        let result = merge_hooks_advanced(None, agpm_hooks, &source_info).unwrap();

        assert_eq!(result.agpm_hooks_added, 3); // One hook added to 3 events

        // Verify hook appears in all three events
        let hooks = result.hooks.as_object().unwrap();
        assert!(hooks.contains_key("PreToolUse"));
        assert!(hooks.contains_key("PostToolUse"));
        assert!(hooks.contains_key("UserPromptSubmit"));

        // Each event should have the hook
        for event in ["PreToolUse", "PostToolUse", "UserPromptSubmit"] {
            let event_hooks = hooks.get(event).unwrap().as_array().unwrap();
            assert_eq!(event_hooks.len(), 1);
            let group = event_hooks[0].as_object().unwrap();
            assert_eq!(group.get("matcher").unwrap().as_str().unwrap(), ".*");
        }
    }

    #[test]
    fn test_invalid_regex_matcher() {
        // Test that invalid regex matchers are handled gracefully
        let mut agpm_hooks = HashMap::new();
        agpm_hooks.insert(
            "test-hook".to_string(),
            HookConfig {
                events: vec![HookEvent::PreToolUse],
                matcher: "[invalid(regex".to_string(), // Invalid regex but we still store it
                hook_type: "command".to_string(),
                command: "test.sh".to_string(),
                timeout: None,
                description: None,
            },
        );

        let mut source_info = HashMap::new();
        source_info.insert(
            "test-hook".to_string(),
            ("test-source".to_string(), "v1.0.0".to_string()),
        );

        let result = merge_hooks_advanced(None, agpm_hooks, &source_info).unwrap();

        assert_eq!(result.agpm_hooks_added, 1);

        // The hook should still be added even with invalid regex
        // (validation happens elsewhere)
        let hooks = result.hooks.as_object().unwrap();
        let pre_tool = hooks.get("PreToolUse").unwrap().as_array().unwrap();
        assert_eq!(pre_tool.len(), 1);
    }

    #[test]
    fn test_empty_matcher_string() {
        let mut agpm_hooks = HashMap::new();
        agpm_hooks.insert(
            "empty-matcher".to_string(),
            HookConfig {
                events: vec![HookEvent::PreToolUse],
                matcher: "".to_string(), // Empty matcher
                hook_type: "command".to_string(),
                command: "test.sh".to_string(),
                timeout: None,
                description: None,
            },
        );

        let mut source_info = HashMap::new();
        source_info.insert(
            "empty-matcher".to_string(),
            ("test-source".to_string(), "v1.0.0".to_string()),
        );

        let result = merge_hooks_advanced(None, agpm_hooks, &source_info).unwrap();

        assert_eq!(result.agpm_hooks_added, 1);

        // Empty matcher should still work
        let hooks = result.hooks.as_object().unwrap();
        let pre_tool = hooks.get("PreToolUse").unwrap().as_array().unwrap();
        assert_eq!(pre_tool[0].get("matcher").unwrap().as_str().unwrap(), "");
    }

    #[test]
    fn test_duplicate_hooks_in_same_matcher() {
        // Test that duplicate AGPM hooks with same name get deduplicated
        let existing = json!({
            "PreToolUse": [{
                "matcher": "Bash",
                "hooks": [{
                    "type": "command",
                    "command": "old-security.sh",
                    "_agpm": {
                        "managed": true,
                        "dependency_name": "security",
                        "source": "test",
                        "version": "v1.0.0"
                    }
                }]
            }]
        });

        let mut agpm_hooks = HashMap::new();
        agpm_hooks.insert(
            "security".to_string(), // Same dependency name
            HookConfig {
                events: vec![HookEvent::PreToolUse],
                matcher: "Bash".to_string(), // Same matcher
                hook_type: "command".to_string(),
                command: "new-security.sh".to_string(),
                timeout: None,
                description: None,
            },
        );

        let mut source_info = HashMap::new();
        source_info.insert(
            "security".to_string(),
            ("test".to_string(), "v2.0.0".to_string()),
        );

        let result = merge_hooks_advanced(Some(&existing), agpm_hooks, &source_info).unwrap();

        // Should update, not add
        assert_eq!(result.agpm_hooks_updated, 1);
        assert_eq!(result.agpm_hooks_added, 0);

        // Should have only one hook in the matcher group
        let hooks = result.hooks.as_object().unwrap();
        let pre_tool = hooks.get("PreToolUse").unwrap().as_array().unwrap();
        assert_eq!(pre_tool.len(), 1);

        let group = pre_tool[0].as_object().unwrap();
        let hooks_array = group.get("hooks").unwrap().as_array().unwrap();
        assert_eq!(hooks_array.len(), 1);
        assert_eq!(
            hooks_array[0].get("command").unwrap().as_str().unwrap(),
            "new-security.sh"
        );
    }

    #[test]
    fn test_malformed_existing_hooks() {
        // Test handling of malformed existing hook structure
        let existing = json!({
            "PreToolUse": [
                {
                    // Missing matcher field
                    "hooks": [{
                        "type": "command",
                        "command": "test.sh"
                    }]
                },
                {
                    "matcher": "Bash",
                    // Missing hooks array
                },
                {
                    "matcher": "Write",
                    "hooks": "not-an-array" // Wrong type
                },
                {
                    "matcher": "Edit",
                    "hooks": [
                        "not-an-object", // Wrong type in array
                        {
                            "type": "command",
                            "command": "valid.sh"
                        }
                    ]
                }
            ]
        });

        let mut agpm_hooks = HashMap::new();
        agpm_hooks.insert(
            "new-hook".to_string(),
            HookConfig {
                events: vec![HookEvent::PreToolUse],
                matcher: "Test".to_string(),
                hook_type: "command".to_string(),
                command: "new.sh".to_string(),
                timeout: None,
                description: None,
            },
        );

        let mut source_info = HashMap::new();
        source_info.insert(
            "new-hook".to_string(),
            ("test".to_string(), "v1.0.0".to_string()),
        );

        // Should handle gracefully without panicking
        let result = merge_hooks_advanced(Some(&existing), agpm_hooks, &source_info);

        // We expect this to either succeed with partial data or fail gracefully
        assert!(result.is_ok() || result.is_err());

        if let Ok(result) = result {
            assert_eq!(result.agpm_hooks_added, 1);

            // New hook should be added
            let hooks = result.hooks.as_object().unwrap();
            assert!(hooks.contains_key("PreToolUse"));
        }
    }

    #[test]
    fn test_very_long_matcher_pattern() {
        let long_pattern = "A|".repeat(1000) + "B"; // Very long pattern

        let mut agpm_hooks = HashMap::new();
        agpm_hooks.insert(
            "long-hook".to_string(),
            HookConfig {
                events: vec![HookEvent::PreToolUse],
                matcher: long_pattern.clone(),
                hook_type: "command".to_string(),
                command: "test.sh".to_string(),
                timeout: None,
                description: None,
            },
        );

        let mut source_info = HashMap::new();
        source_info.insert(
            "long-hook".to_string(),
            ("test".to_string(), "v1.0.0".to_string()),
        );

        let result = merge_hooks_advanced(None, agpm_hooks, &source_info).unwrap();

        assert_eq!(result.agpm_hooks_added, 1);

        // Long pattern should be preserved
        let hooks = result.hooks.as_object().unwrap();
        let pre_tool = hooks.get("PreToolUse").unwrap().as_array().unwrap();
        assert_eq!(
            pre_tool[0].get("matcher").unwrap().as_str().unwrap(),
            &long_pattern
        );
    }

    #[test]
    fn test_special_characters_in_names() {
        // Test hooks with special characters in names
        let mut agpm_hooks = HashMap::new();
        agpm_hooks.insert(
            "hook-with-special!@#$%^&*()_+chars".to_string(),
            HookConfig {
                events: vec![HookEvent::PreToolUse],
                matcher: ".*".to_string(),
                hook_type: "command".to_string(),
                command: "test.sh".to_string(),
                timeout: None,
                description: None,
            },
        );

        let mut source_info = HashMap::new();
        source_info.insert(
            "hook-with-special!@#$%^&*()_+chars".to_string(),
            ("test-source".to_string(), "v1.0.0".to_string()),
        );

        let result = merge_hooks_advanced(None, agpm_hooks, &source_info).unwrap();

        assert_eq!(result.agpm_hooks_added, 1);

        // Special characters should be preserved
        let hooks = result.hooks.as_object().unwrap();
        let pre_tool = hooks.get("PreToolUse").unwrap().as_array().unwrap();
        let hook = &pre_tool[0].get("hooks").unwrap().as_array().unwrap()[0];
        assert_eq!(
            hook.get("_agpm")
                .unwrap()
                .get("dependency_name")
                .unwrap()
                .as_str()
                .unwrap(),
            "hook-with-special!@#$%^&*()_+chars"
        );
    }

    #[test]
    fn test_complex_merge_scenario() {
        // Complex existing configuration
        let existing = json!({
            "PreToolUse": [
                {
                    "matcher": "Bash",
                    "hooks": [
                        {
                            "type": "command",
                            "command": "user-bash-hook.sh"
                        },
                        {
                            "type": "command",
                            "command": "old-agpm-hook.sh",
                            "_agpm": {
                                "managed": true,
                                "dependency_name": "old-hook",
                                "source": "old-source",
                                "version": "v0.1.0"
                            }
                        }
                    ]
                },
                {
                    "matcher": "Write|Edit",
                    "hooks": [
                        {
                            "type": "command",
                            "command": "user-write-hook.sh"
                        }
                    ]
                }
            ],
            "PostToolUse": [
                {
                    "matcher": ".*",
                    "hooks": [
                        {
                            "type": "command",
                            "command": "logging.sh",
                            "_agpm": {
                                "managed": true,
                                "dependency_name": "logger",
                                "source": "utils",
                                "version": "v1.0.0"
                            }
                        }
                    ]
                }
            ]
        });

        // New AGPM hooks configuration
        let mut agpm_hooks = HashMap::new();

        // Keep and update the logger
        agpm_hooks.insert(
            "logger".to_string(),
            HookConfig {
                events: vec![HookEvent::PostToolUse],
                matcher: ".*".to_string(),
                hook_type: "command".to_string(),
                command: "new-logging.sh".to_string(),
                timeout: Some(500),
                description: None,
            },
        );

        // Add a new security hook
        agpm_hooks.insert(
            "security".to_string(),
            HookConfig {
                events: vec![HookEvent::PreToolUse],
                matcher: "Bash".to_string(),
                hook_type: "command".to_string(),
                command: "security-check.sh".to_string(),
                timeout: Some(2000),
                description: None,
            },
        );

        let mut source_info = HashMap::new();
        source_info.insert(
            "logger".to_string(),
            ("utils".to_string(), "v2.0.0".to_string()),
        );
        source_info.insert(
            "security".to_string(),
            ("security-tools".to_string(), "v1.0.0".to_string()),
        );

        let result = merge_hooks_advanced(Some(&existing), agpm_hooks, &source_info).unwrap();

        assert_eq!(result.user_hooks_preserved, 2); // user-bash-hook and user-write-hook
        assert_eq!(result.agpm_hooks_added, 1); // security hook
        assert_eq!(result.agpm_hooks_updated, 1); // logger hook
        assert_eq!(result.agpm_hooks_removed, 1); // old-hook

        // Verify final structure
        let hooks = result.hooks.as_object().unwrap();

        // Check PreToolUse
        let pre_tool = hooks.get("PreToolUse").unwrap().as_array().unwrap();

        // Find Bash matcher group
        let bash_group = pre_tool
            .iter()
            .find(|g| g.get("matcher").and_then(|m| m.as_str()) == Some("Bash"))
            .unwrap()
            .as_object()
            .unwrap();

        let bash_hooks = bash_group.get("hooks").unwrap().as_array().unwrap();
        assert_eq!(bash_hooks.len(), 2); // user hook + security hook

        // Find Write|Edit matcher group
        let write_group = pre_tool
            .iter()
            .find(|g| g.get("matcher").and_then(|m| m.as_str()) == Some("Write|Edit"))
            .unwrap()
            .as_object()
            .unwrap();

        let write_hooks = write_group.get("hooks").unwrap().as_array().unwrap();
        assert_eq!(write_hooks.len(), 1); // Just the user hook
        assert!(write_hooks[0].get("_agpm").is_none());

        // Check PostToolUse
        let post_tool = hooks.get("PostToolUse").unwrap().as_array().unwrap();
        assert_eq!(post_tool.len(), 1);

        let post_group = post_tool[0].as_object().unwrap();
        let post_hooks = post_group.get("hooks").unwrap().as_array().unwrap();
        assert_eq!(post_hooks.len(), 1);
        assert_eq!(
            post_hooks[0].get("command").unwrap().as_str().unwrap(),
            "new-logging.sh"
        );
    }
}