nexus-memory-hooks 1.3.2

Agent hooks system for Nexus Memory System - automated memory extraction
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
//! Claude Code hook implementation
//!
//! Uses Skills-based lifecycle hooks for native integration.

use async_trait::async_trait;
use std::path::PathBuf;

use crate::base::{AgentHook, BaseHook, LifecycleCapabilities, SessionEndCallback};
use crate::error::{HookError, Result};
use crate::monitor::ProcessMonitor;
use crate::session::SessionContext;
use crate::types::{AgentType, SessionActivity, SupportTier};

/// Claude Code hook using Skills lifecycle
///
/// Installation:
/// 1. Creates Claude Code Skill at ~/.claude/skills/nexus-memory/SKILL.md
/// 2. Skill auto-triggers on session_end, checkpoint, completion
/// 3. Skill calls MCP tool to store memory
///
/// Lifecycle support:
/// - **session_start**: Via settings.json `SessionStart` hook entry
/// - **session_end**: Via skill (on_session_end trigger)
/// - **checkpoint**: Via skill (on_checkpoint trigger)
/// - **error**: Via skill (on_error trigger)
/// - **compact**: Via skill (on_completion trigger)
pub struct ClaudeCodeHook {
    /// Base hook functionality
    base: BaseHook,

    /// Skill path
    skill_path: PathBuf,

    /// Whether skill is installed
    skill_installed: bool,

    /// Whether a SessionStart hook was written to settings.json
    settings_hook_installed: bool,

    /// Process monitor for fallback detection
    process_monitor: ProcessMonitor,
}

impl ClaudeCodeHook {
    /// Skill name
    pub const SKILL_NAME: &'static str = "nexus-memory-extraction";

    /// Config directory
    pub const CONFIG_DIR: &'static str = ".claude";

    /// Skills subdirectory
    pub const SKILLS_DIR: &'static str = "skills";

    /// Create a new Claude Code hook with full installation.
    pub fn new() -> Self {
        Self::new_with_install(true)
    }

    /// Create a new Claude Code hook without mutating user state.
    ///
    /// Skips skill installation and session-start injection so the
    /// hook can be used for inspection/status reporting without side
    /// effects on the filesystem.
    pub fn new_readonly() -> Self {
        Self::new_with_install(false)
    }

    fn new_with_install(should_install: bool) -> Self {
        let skill_path = dirs::home_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join(Self::CONFIG_DIR)
            .join(Self::SKILLS_DIR)
            .join(Self::SKILL_NAME);

        let mut hook = Self {
            base: BaseHook::new("claude-code"),
            skill_path,
            skill_installed: false,
            settings_hook_installed: Self::has_settings_hook(),
            process_monitor: ProcessMonitor::new(),
        };

        if should_install {
            // Try to install skill
            if let Err(e) = hook.install_skill() {
                tracing::warn!("Failed to install Claude Code skill: {}", e);
            }
        }

        hook
    }

    /// Install the SKILL.md file
    fn install_skill(&mut self) -> Result<()> {
        // Create skill directory
        std::fs::create_dir_all(&self.skill_path).map_err(|e| {
            HookError::InstallationFailed(format!("Failed to create skill dir: {}", e))
        })?;

        let skill_md = self.skill_path.join("SKILL.md");

        let skill_content = r#"---
name: nexus-memory-extraction
description: Automatically extract session context to Nexus Memory System
version: 1.0.0
author: Nexus Memory System
trigger:
  - on_session_end
  - on_checkpoint
  - on_completion
  - on_error
priority: high
---

# Nexus Memory Extraction Skill

## Overview

This skill automatically triggers when your Claude Code session ends, ensuring no context is lost.

## What It Does

1. **Captures Context**: Extracts current conversation, decisions, and context
2. **Summarizes**: Creates structured summary of key points
3. **Stores**: Automatically stores to Nexus Memory System
4. **Confirms**: Shows what was stored

## Triggers

- **on_session_end**: When you close Claude Code
- **on_checkpoint**: At periodic checkpoints during long sessions
- **on_completion**: When a task is completed
- **on_error**: If an error occurs (stores context for debugging)

## No Manual Action Required

This skill runs automatically. You don't need to remember to trigger it.
You do not need to start a Nexus server manually for normal CLI memory capture.

## Configuration

The skill reads from:
- `NEXUS_AUTO_INGEST=true` environment variable
- the local Nexus CLI runtime for default operation

Optional:
- an external Nexus endpoint only when explicitly configured for advanced remote workflows

## Output

After storing, you'll see:
```
[Nexus] Stored 3 memories from Claude Code session:
  - 2 decisions
  - 1 context item
  - Memory IDs: nexus_123, nexus_124, nexus_125
```
"#;

        std::fs::write(&skill_md, skill_content).map_err(|e| {
            HookError::InstallationFailed(format!("Failed to write skill file: {}", e))
        })?;

        self.skill_installed = true;
        tracing::info!("Claude Code Skill installed at: {:?}", self.skill_path);

        Ok(())
    }

    /// Settings file path for Claude Code hooks configuration.
    fn settings_path() -> PathBuf {
        dirs::home_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join(Self::CONFIG_DIR)
            .join("settings.json")
    }

    /// Install a SessionStart hook entry into Claude Code's settings.json.
    ///
    /// Claude Code natively supports `SessionStart` as a hook event type.
    /// This writes a hook entry that invokes `nexus session start` when a
    /// new Claude Code session begins.
    fn install_settings_hook(&mut self) -> Result<()> {
        let settings_path = Self::settings_path();
        let command = Self::desired_session_start_command();

        let mut settings = if settings_path.exists() {
            let content = std::fs::read_to_string(&settings_path).map_err(|e| {
                HookError::InstallationFailed(format!("Failed to read settings.json: {}", e))
            })?;
            serde_json::from_str::<serde_json::Value>(&content).map_err(|e| {
                HookError::InstallationFailed(format!("Failed to parse settings.json: {}", e))
            })?
        } else {
            serde_json::json!({})
        };

        Self::upsert_session_start_hook(&mut settings, &command)?;

        // Install subconscious retrieval hooks (UserPromptSubmit, PreToolUse, Stop)
        // Respect NEXUS_SUBCONSCIOUS_MODE — skip when set to 'off'
        let subconscious_mode = std::env::var("NEXUS_SUBCONSCIOUS_MODE")
            .unwrap_or_default()
            .to_lowercase();
        if subconscious_mode != "off" {
            for event_type in ["UserPromptSubmit", "PreToolUse", "Stop"] {
                let cmd = Self::desired_subconscious_command(event_type);
                if cmd.is_empty() {
                    continue;
                }
                Self::upsert_hook_entry(&mut settings, event_type, &cmd, &|command: &str| {
                    Self::command_is_subconscious_hook(command, event_type)
                })?;
            }
        }
        // Write back
        let serialized = serde_json::to_string_pretty(&settings).map_err(|e| {
            HookError::InstallationFailed(format!("Failed to serialize settings: {}", e))
        })?;

        // Create parent dir if needed
        if let Some(parent) = settings_path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                HookError::InstallationFailed(format!("Failed to create settings dir: {}", e))
            })?;
        }

        std::fs::write(&settings_path, serialized).map_err(|e| {
            HookError::InstallationFailed(format!("Failed to write settings.json: {}", e))
        })?;

        self.settings_hook_installed = true;
        tracing::info!(
            "Claude Code SessionStart hook written to: {:?}",
            settings_path
        );

        Ok(())
    }

    /// Find the nexus binary path for use in hook commands.
    fn find_nexus_binary() -> String {
        if let Ok(bin) = std::env::var("NEXUS_HOOK_BINARY") {
            if !bin.trim().is_empty() {
                return bin;
            }
        }

        if let Ok(current_exe) = std::env::current_exe() {
            if current_exe
                .file_name()
                .and_then(|name| name.to_str())
                .is_some_and(|name| name == "nexus")
            {
                return current_exe.to_string_lossy().to_string();
            }
        }

        // Check common installation paths
        let candidates: Vec<PathBuf> = [
            dirs::home_dir().map(|h| h.join(".local").join("bin").join("nexus")),
            Some(PathBuf::from("/usr/local/bin/nexus")),
        ]
        .into_iter()
        .flatten()
        .collect();

        for candidate in candidates {
            if candidate.exists() {
                return candidate.to_string_lossy().to_string();
            }
        }

        // Fallback: assume it's in PATH
        "nexus".to_string()
    }

    fn desired_session_start_command() -> String {
        let nexus_bin = Self::find_nexus_binary();
        format!(
            "'{}' session start --agent claude-code --mode session",
            nexus_bin.replace('\'', "'\\''")
        )
    }

    fn desired_subconscious_command(event_type: &str) -> String {
        let nexus_bin = Self::find_nexus_binary();
        let escaped = nexus_bin.replace('\'', "'\\''");
        match event_type {
            "UserPromptSubmit" => format!("'{}' subconscious recall --agent claude-code", escaped),
            "PreToolUse" => format!("'{}' subconscious sync-check --agent claude-code", escaped),
            "Stop" => format!(
                "'{}' subconscious ingest-transcript --agent claude-code",
                escaped
            ),
            _ => String::new(),
        }
    }

    /// Detect whether a command string is a nexus subconscious hook.
    fn command_is_subconscious_hook(command: &str, event_type: &str) -> bool {
        command.contains("nexus")
            && command.contains("subconscious")
            && match event_type {
                "UserPromptSubmit" => command.contains("recall"),
                "PreToolUse" => command.contains("sync-check"),
                "Stop" => command.contains("ingest-transcript"),
                _ => false,
            }
    }

    /// Generic hook upsert for any event type (used for subconscious hooks).
    fn upsert_hook_entry(
        settings: &mut serde_json::Value,
        event_type: &str,
        desired_command: &str,
        is_match: &dyn Fn(&str) -> bool,
    ) -> Result<()> {
        let settings_obj = settings.as_object_mut().ok_or_else(|| {
            HookError::InstallationFailed(
                "settings.json must contain a top-level JSON object".to_string(),
            )
        })?;

        let hooks = settings_obj
            .entry("hooks")
            .or_insert_with(|| serde_json::json!({}));
        let hooks_obj = hooks.as_object_mut().ok_or_else(|| {
            HookError::InstallationFailed("'hooks' must be a JSON object".to_string())
        })?;

        let event_arr = hooks_obj
            .entry(event_type)
            .or_insert_with(|| serde_json::json!([]));
        let entries = event_arr.as_array_mut().ok_or_else(|| {
            HookError::InstallationFailed(format!("'hooks.{}' must be an array", event_type))
        })?;

        // Try to replace existing entry
        for entry in entries.iter_mut() {
            // Check flat command
            if entry
                .get("command")
                .and_then(|v| v.as_str())
                .map(is_match)
                .unwrap_or(false)
            {
                *entry = serde_json::json!({
                    "matcher": "",
                    "hooks": [{
                        "type": "command",
                        "command": desired_command,
                    }]
                });
                return Ok(());
            }

            // Check nested hooks array
            if let Some(hooks) = entry.get_mut("hooks").and_then(|v| v.as_array_mut()) {
                for hook in hooks.iter_mut() {
                    if hook
                        .get("command")
                        .and_then(|v| v.as_str())
                        .map(is_match)
                        .unwrap_or(false)
                    {
                        *hook = serde_json::json!({
                            "type": "command",
                            "command": desired_command,
                        });
                        return Ok(());
                    }
                }
            }
        }

        // No existing entry found — append new one
        entries.push(serde_json::json!({
            "matcher": "",
            "hooks": [{
                "type": "command",
                "command": desired_command,
            }]
        }));

        Ok(())
    }

    fn has_settings_hook() -> bool {
        let settings_path = Self::settings_path();
        let Ok(content) = std::fs::read_to_string(settings_path) else {
            return false;
        };
        let Ok(settings) = serde_json::from_str::<serde_json::Value>(&content) else {
            return false;
        };
        let desired_command = Self::desired_session_start_command();
        settings
            .get("hooks")
            .and_then(|hooks| hooks.get("SessionStart"))
            .and_then(|value| value.as_array())
            .is_some_and(|entries| {
                entries.iter().any(|entry| {
                    Self::entry_contains_exact_session_start_hook(entry, &desired_command)
                })
            })
    }

    #[cfg(test)]
    fn entry_has_session_start_hook(entry: &serde_json::Value) -> bool {
        entry
            .get("command")
            .and_then(|command| command.as_str())
            .map(Self::command_is_session_start_hook)
            .unwrap_or(false)
            || entry
                .get("hooks")
                .and_then(|hooks| hooks.as_array())
                .is_some_and(|hooks| {
                    hooks.iter().any(|hook| {
                        hook.get("command")
                            .and_then(|command| command.as_str())
                            .map(Self::command_is_session_start_hook)
                            .unwrap_or(false)
                    })
                })
    }

    fn command_is_session_start_hook(command: &str) -> bool {
        command.contains("nexus")
            && command.contains("session start")
            && command.contains("claude-code")
    }

    fn entry_contains_exact_session_start_hook(
        entry: &serde_json::Value,
        desired_command: &str,
    ) -> bool {
        entry
            .get("command")
            .and_then(|command| command.as_str())
            .map(|command| command == desired_command)
            .unwrap_or(false)
            || entry
                .get("hooks")
                .and_then(|hooks| hooks.as_array())
                .is_some_and(|hooks| {
                    hooks.iter().any(|hook| {
                        hook.get("command")
                            .and_then(|command| command.as_str())
                            .map(|command| command == desired_command)
                            .unwrap_or(false)
                    })
                })
    }

    fn upsert_session_start_hook(
        settings: &mut serde_json::Value,
        desired_command: &str,
    ) -> Result<()> {
        let settings_obj = settings.as_object_mut().ok_or_else(|| {
            HookError::InstallationFailed(
                "settings.json must contain a top-level JSON object".to_string(),
            )
        })?;

        let hooks = settings_obj
            .entry("hooks")
            .or_insert_with(|| serde_json::json!({}));
        let hooks_obj = hooks.as_object_mut().ok_or_else(|| {
            HookError::InstallationFailed("'hooks' must be a JSON object".to_string())
        })?;

        let session_start = hooks_obj
            .entry("SessionStart")
            .or_insert_with(|| serde_json::json!([]));
        let entries = session_start.as_array_mut().ok_or_else(|| {
            HookError::InstallationFailed("'hooks.SessionStart' must be an array".to_string())
        })?;

        if Self::replace_existing_session_start_hook(entries, desired_command) {
            return Ok(());
        }

        entries.push(serde_json::json!({
            "matcher": "",
            "hooks": [{
                "type": "command",
                "command": desired_command,
            }]
        }));

        Ok(())
    }

    fn replace_existing_session_start_hook(
        entries: &mut [serde_json::Value],
        desired_command: &str,
    ) -> bool {
        for entry in entries {
            if entry
                .get("command")
                .and_then(|value| value.as_str())
                .is_some_and(Self::command_is_session_start_hook)
            {
                *entry = serde_json::json!({
                    "matcher": "",
                    "hooks": [{
                        "type": "command",
                        "command": desired_command,
                    }]
                });
                return true;
            }

            if let Some(hooks) = entry
                .get_mut("hooks")
                .and_then(|value| value.as_array_mut())
            {
                for hook in hooks {
                    if hook
                        .get("command")
                        .and_then(|value| value.as_str())
                        .is_some_and(Self::command_is_session_start_hook)
                    {
                        *hook = serde_json::json!({
                            "type": "command",
                            "command": desired_command,
                        });
                        return true;
                    }
                }
            }
        }

        false
    }

    /// Read session file
    fn read_session_file(&self) -> Option<serde_json::Value> {
        let session_file = dirs::home_dir()?
            .join(Self::CONFIG_DIR)
            .join("session.json");

        if session_file.exists() {
            let content = std::fs::read_to_string(&session_file).ok()?;
            serde_json::from_str(&content).ok()
        } else {
            None
        }
    }

    /// Read checkpoint data
    fn read_checkpoint_data(&self) -> Option<Vec<serde_json::Value>> {
        let checkpoint_dir = dirs::home_dir()?.join(Self::CONFIG_DIR).join("checkpoints");

        if !checkpoint_dir.exists() {
            return None;
        }

        let mut checkpoints = Vec::new();

        if let Ok(entries) = std::fs::read_dir(&checkpoint_dir) {
            for entry in entries.flatten() {
                if entry
                    .path()
                    .extension()
                    .map(|e| e == "json")
                    .unwrap_or(false)
                {
                    if let Ok(content) = std::fs::read_to_string(entry.path()) {
                        if let Ok(data) = serde_json::from_str(&content) {
                            checkpoints.push(data);
                        }
                    }
                }
            }
        }

        Some(checkpoints)
    }
}

impl Default for ClaudeCodeHook {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl AgentHook for ClaudeCodeHook {
    fn agent_type(&self) -> &str {
        &self.base.agent_type
    }

    async fn install_session_end_hook(&mut self, callback: SessionEndCallback) -> Result<()> {
        self.base.add_callback(callback);
        self.base.installed = true;

        if !self.skill_installed {
            tracing::warn!("Claude Code Skill not installed, using fallback detection");
        }

        Ok(())
    }

    /// Install a SessionStart hook via Claude Code's settings.json.
    ///
    /// Claude Code natively supports the `SessionStart` hook event type,
    /// which fires when a new Claude Code session begins. This writes a
    /// hook entry that invokes `nexus session start --agent claude-code`.
    async fn install_session_start_hook(&mut self, callback: SessionEndCallback) -> Result<()> {
        self.base.add_session_start_callback(callback);

        self.install_settings_hook()?;

        Ok(())
    }

    /// Checkpoint hooks are supported via the installed skill's on_checkpoint trigger.
    async fn install_checkpoint_hook(&mut self, callback: SessionEndCallback) -> Result<()> {
        self.base.add_checkpoint_callback(callback);
        Ok(())
    }

    /// Compact hooks are supported via the installed skill's on_completion trigger.
    async fn install_compact_hook(&mut self, callback: SessionEndCallback) -> Result<()> {
        self.base.add_callback(callback);
        Ok(())
    }

    /// Error hooks are supported via the installed skill's on_error trigger.
    async fn install_error_hook(&mut self, callback: SessionEndCallback) -> Result<()> {
        self.base.add_error_callback(callback);
        Ok(())
    }

    async fn detect_session_activity(&self) -> Result<SessionActivity> {
        // Also check for session file to get recent turn content
        let mut recent_content = "claude session active".to_string();
        if let Some(session) = self.read_session_file() {
            if let Some(messages) = session.get("messages").and_then(|m| m.as_array()) {
                if let Some(last_msg) = messages.last() {
                    if let Some(content) = last_msg.get("content").and_then(|c| c.as_str()) {
                        recent_content = content.to_string();
                    }
                }
            }
        }

        // Refresh process monitor
        let mut monitor = self.process_monitor.clone();
        let processes = monitor.find_agent_processes(AgentType::ClaudeCode);

        let mut activity = SessionActivity::new(AgentType::ClaudeCode);

        if !processes.is_empty() {
            activity.is_active = true;
            activity.processes = processes;
            self.base.record_activity_with_content(&recent_content);
        }

        // Also check for session file
        if let Some(session) = self.read_session_file() {
            if let Some(id) = session.get("session_id").and_then(|s| s.as_str()) {
                activity.session_id = Some(id.to_string());
            }
        }

        Ok(activity)
    }

    async fn extract_session_context(&self) -> Result<SessionContext> {
        let mut context = SessionContext::new("claude-code")
            .with_source("native")
            .with_reliability(1.0);

        // Read session file
        if let Some(session) = self.read_session_file() {
            if let Some(messages) = session.get("messages").and_then(|m| m.as_array()) {
                for msg in messages {
                    let role = msg
                        .get("role")
                        .and_then(|r| r.as_str())
                        .unwrap_or("unknown");
                    let content = msg.get("content").and_then(|c| c.as_str()).unwrap_or("");
                    context.add_message(role, content);
                }
            }

            if let Some(project_ctx) = session.get("project_context") {
                context.add_custom("project_context", project_ctx.clone());
            }
        }

        // Read checkpoint data
        if let Some(checkpoints) = self.read_checkpoint_data() {
            for checkpoint in checkpoints {
                if let Some(decisions) = checkpoint.get("decisions").and_then(|d| d.as_array()) {
                    for decision in decisions {
                        if let Some(summary) = decision.get("summary").and_then(|s| s.as_str()) {
                            let mut dec = crate::session::Decision::new(summary);
                            if let Some(rationale) =
                                decision.get("rationale").and_then(|r| r.as_str())
                            {
                                dec.rationale = Some(rationale.to_string());
                            }
                            context.add_decision(dec);
                        }
                    }
                }

                if let Some(files) = checkpoint.get("files").and_then(|f| f.as_array()) {
                    for file in files {
                        if let Some(path) = file.get("path").and_then(|p| p.as_str()) {
                            let action = file
                                .get("action")
                                .and_then(|a| a.as_str())
                                .unwrap_or("modified");
                            let file_action = match action {
                                "created" => crate::session::FileAction::Created,
                                "deleted" => crate::session::FileAction::Deleted,
                                "read" => crate::session::FileAction::Read,
                                _ => crate::session::FileAction::Modified,
                            };
                            context.add_file(crate::session::FileInfo::new(path, file_action));
                        }
                    }
                }
            }
        }

        context.complete();
        Ok(context)
    }

    fn is_hook_installed(&self) -> bool {
        self.skill_installed || self.settings_hook_installed
    }

    fn reliability_score(&self) -> f32 {
        if self.skill_installed && self.settings_hook_installed {
            1.0
        } else if self.skill_installed || self.settings_hook_installed {
            0.98
        } else {
            0.95 // Fallback to process monitoring
        }
    }

    fn lifecycle_capabilities(&self) -> LifecycleCapabilities {
        LifecycleCapabilities {
            session_start: true,
            session_end: true,
            checkpoint: true,
            error_hook: true,
            compact: true,
        }
    }

    fn support_tier(&self) -> SupportTier {
        SupportTier::NativeLifecycle
    }
}

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

    #[test]
    fn test_claude_hook_new() {
        let hook = ClaudeCodeHook::new();
        assert_eq!(hook.agent_type(), "claude-code");
    }

    #[tokio::test]
    async fn test_claude_hook_detect_activity() {
        let hook = ClaudeCodeHook::new();
        let activity = hook.detect_session_activity().await.unwrap();

        assert_eq!(activity.agent_type, AgentType::ClaudeCode);
    }

    #[test]
    fn test_claude_hook_lifecycle_capabilities() {
        let hook = ClaudeCodeHook::new();
        let caps = hook.lifecycle_capabilities();

        assert!(
            caps.session_start,
            "Claude Code should support session_start"
        );
        assert!(caps.session_end, "Claude Code should support session_end");
        assert!(caps.checkpoint, "Claude Code should support checkpoint");
        assert!(caps.error_hook, "Claude Code should support error_hook");
        assert!(caps.compact, "Claude Code should support compact");
    }

    #[tokio::test]
    async fn test_claude_hook_install_session_start() {
        let mut hook = ClaudeCodeHook::new();
        let callback = std::sync::Arc::new(|_ctx| {});

        // Should succeed (may write to settings.json)
        let result = hook.install_session_start_hook(callback).await;
        // Result depends on whether settings.json is writable, but should not be NotSupported
        match result {
            Ok(()) => {
                assert!(hook.settings_hook_installed);
            }
            Err(HookError::InstallationFailed(_)) => {
                // Acceptable if file system is not writable in test env
            }
            Err(HookError::NotSupported(msg)) => {
                panic!(
                    "Session start should be supported for Claude Code, got: {}",
                    msg
                );
            }
            Err(e) => {
                panic!("Unexpected error: {}", e);
            }
        }
    }

    #[tokio::test]
    async fn test_claude_hook_install_checkpoint_supported() {
        let mut hook = ClaudeCodeHook::new();
        let callback = std::sync::Arc::new(|_ctx| {});

        let result = hook.install_checkpoint_hook(callback).await;
        assert!(
            result.is_ok(),
            "Checkpoint should be supported for Claude Code"
        );
    }

    #[tokio::test]
    async fn test_claude_hook_install_error_supported() {
        let mut hook = ClaudeCodeHook::new();
        let callback = std::sync::Arc::new(|_ctx| {});

        let result = hook.install_error_hook(callback).await;
        assert!(
            result.is_ok(),
            "Error hook should be supported for Claude Code"
        );
    }

    #[test]
    fn test_find_nexus_binary() {
        let bin = ClaudeCodeHook::find_nexus_binary();
        assert!(!bin.is_empty());
        // Should either be a full path or "nexus" fallback
        assert!(bin.contains("nexus"));
    }

    #[test]
    fn test_entry_has_session_start_hook_detects_nested_command() {
        let entry = serde_json::json!({
            "matcher": "",
            "hooks": [
                {
                    "type": "command",
                    "command": "/tmp/nexus session start --agent claude-code --mode session"
                }
            ]
        });

        assert!(ClaudeCodeHook::entry_has_session_start_hook(&entry));
    }

    #[test]
    fn test_upsert_session_start_hook_repairs_stale_command() {
        let desired = "'/new/nexus' session start --agent claude-code --mode session";
        let mut settings = serde_json::json!({
            "hooks": {
                "SessionStart": [{
                    "matcher": "",
                    "hooks": [{
                        "type": "command",
                        "command": "'/old/nexus' session start --agent claude-code --mode session"
                    }]
                }]
            }
        });

        ClaudeCodeHook::upsert_session_start_hook(&mut settings, desired).unwrap();

        let hooks = settings["hooks"]["SessionStart"].as_array().unwrap();
        assert_eq!(hooks.len(), 1);
        assert_eq!(hooks[0]["hooks"][0]["command"], desired);
    }

    #[test]
    fn test_upsert_session_start_hook_rejects_invalid_shapes() {
        let mut settings = serde_json::json!({
            "hooks": {
                "SessionStart": {}
            }
        });

        let error = ClaudeCodeHook::upsert_session_start_hook(
            &mut settings,
            "'/nexus' session start --agent claude-code --mode session",
        )
        .unwrap_err();

        assert!(error.to_string().contains("SessionStart"));
    }

    #[test]
    fn test_desired_subconscious_command_returns_commands() {
        let recall = ClaudeCodeHook::desired_subconscious_command("UserPromptSubmit");
        assert!(recall.contains("subconscious recall"));
        let sync = ClaudeCodeHook::desired_subconscious_command("PreToolUse");
        assert!(sync.contains("subconscious sync-check"));
        let stop = ClaudeCodeHook::desired_subconscious_command("Stop");
        assert!(stop.contains("subconscious ingest-transcript"));
    }

    #[test]
    fn test_desired_subconscious_command_unknown_returns_empty() {
        let cmd = ClaudeCodeHook::desired_subconscious_command("Unknown");
        assert!(cmd.is_empty());
    }

    #[test]
    fn test_command_is_subconscious_hook_matches() {
        assert!(ClaudeCodeHook::command_is_subconscious_hook(
            "/nexus subconscious recall --agent claude-code",
            "UserPromptSubmit"
        ));
        assert!(!ClaudeCodeHook::command_is_subconscious_hook(
            "/nexus subconscious recall --agent claude-code",
            "PreToolUse"
        ));
    }

    #[test]
    fn test_upsert_hook_entry_adds_new_event() {
        let mut settings = serde_json::json!({"hooks": {}});
        ClaudeCodeHook::upsert_hook_entry(
            &mut settings,
            "UserPromptSubmit",
            "nexus subconscious recall",
            &|cmd: &str| cmd.contains("subconscious recall"),
        )
        .unwrap();

        let entries = settings["hooks"]["UserPromptSubmit"].as_array().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(
            entries[0]["hooks"][0]["command"],
            "nexus subconscious recall"
        );
    }

    #[test]
    fn test_upsert_hook_entry_replaces_existing() {
        let mut settings = serde_json::json!({
            "hooks": {
                "PreToolUse": [{
                    "matcher": "",
                    "hooks": [{
                        "type": "command",
                        "command": "/old/nexus subconscious sync-check"
                    }]
                }]
            }
        });

        ClaudeCodeHook::upsert_hook_entry(
            &mut settings,
            "PreToolUse",
            "/new/nexus subconscious sync-check",
            &|cmd: &str| cmd.contains("subconscious sync-check"),
        )
        .unwrap();

        let entries = settings["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(
            entries[0]["hooks"][0]["command"],
            "/new/nexus subconscious sync-check"
        );
    }

    #[test]
    fn test_upsert_hook_entry_replaces_flat_command() {
        let mut settings = serde_json::json!({
            "hooks": {
                "UserPromptSubmit": [{
                    "type": "command",
                    "command": "/old/nexus subconscious recall"
                }]
            }
        });

        ClaudeCodeHook::upsert_hook_entry(
            &mut settings,
            "UserPromptSubmit",
            "/new/nexus subconscious recall",
            &|cmd: &str| cmd.contains("subconscious recall"),
        )
        .unwrap();

        let entries = settings["hooks"]["UserPromptSubmit"].as_array().unwrap();
        assert_eq!(entries.len(), 1);
        // Should have converged to nested shape
        assert!(entries[0].get("hooks").is_some(), "Should use nested shape");
        assert_eq!(
            entries[0]["hooks"][0]["command"],
            "/new/nexus subconscious recall"
        );
    }

    #[test]
    fn test_command_is_subconscious_hook_stop_event() {
        assert!(ClaudeCodeHook::command_is_subconscious_hook(
            "/nexus subconscious ingest-transcript --agent claude-code",
            "Stop"
        ));
        assert!(!ClaudeCodeHook::command_is_subconscious_hook(
            "/nexus subconscious recall",
            "Stop"
        ));
    }
}