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
//! Pi-Skills cross-compatible hook implementation (MANDATORY)
//!
//! Cross-compatible skills repository supporting multiple agent platforms.
//!
//! Repository: https://github.com/badlogic/pi-skills
//! Compatible with: pi-mono, oh-my-pi, Claude Code, Codex CLI, Amp, Droid
//!
//! Available Skills:
//! - brave-search
//! - browser-tools
//! - gccli, gdcli, gmcli
//! - transcribe
//! - vscode
//! - youtube-transcript

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::{FileAction, FileInfo, SessionContext};
use crate::types::{AgentType, SessionActivity, SkillMetadata, SupportTier};

/// Pi-Skills cross-compatible hook
///
/// Supports skills from the badlogic/pi-skills repository.
/// Compatible with multiple agent platforms including pi-mono, oh-my-pi,
/// Claude Code, Codex CLI, Amp, and Droid.
///
/// # Skills Format
///
/// Uses SKILL.md format with `{baseDir}` placeholder:
/// ```markdown
/// ---
/// name: skill-name
/// description: Short description
/// ---
///
/// # Instructions
/// Helper files at: {baseDir}/
/// ```
///
/// # Available Skills
///
/// - brave-search: Web search via Brave API
/// - browser-tools: Browser automation tools
/// - gccli: Google Cloud CLI integration
/// - gdcli: Google Drive CLI integration
/// - gmcli: Gmail CLI integration
/// - transcribe: Audio transcription
/// - vscode: VS Code integration
/// - youtube-transcript: YouTube video transcripts
pub struct PiSkillsHook {
    /// Base hook functionality
    base: BaseHook,

    /// Skills directory (may be None if not found)
    skills_dir: Option<PathBuf>,

    /// Process monitor
    process_monitor: ProcessMonitor,

    /// Whether skill is installed
    skill_installed: bool,

    /// Detected skills
    detected_skills: Vec<SkillMetadata>,
}

impl PiSkillsHook {
    /// Agent type string
    pub const AGENT_TYPE: &'static str = "pi-skills";

    /// Skills directory names to check
    pub const SKILL_DIRS: &'static [&'static str] = &[".pi-skills", ".pi/skills", ".omp/skills"];

    /// Known skills from pi-skills repository
    pub const KNOWN_SKILLS: &'static [&'static str] = &[
        "brave-search",
        "browser-tools",
        "gccli",
        "gdcli",
        "gmcli",
        "transcribe",
        "vscode",
        "youtube-transcript",
    ];

    /// Create a new Pi-Skills hook
    pub fn new() -> Self {
        Self::new_with_install(true)
    }

    /// Create a new Pi-Skills hook without mutating user state.
    pub fn new_readonly() -> Self {
        Self::new_with_install(false)
    }

    fn new_with_install(auto_install: bool) -> Self {
        let skills_dir = Self::find_skills_dir();
        let skill_installed = skills_dir
            .as_ref()
            .is_some_and(|dir| Self::skill_file_path(dir).exists());

        let mut hook = Self {
            base: BaseHook::new(Self::AGENT_TYPE),
            skills_dir: skills_dir.clone(),
            process_monitor: ProcessMonitor::new(),
            skill_installed,
            detected_skills: Vec::new(),
        };

        // Discover available skills
        if let Some(ref dir) = skills_dir {
            hook.discover_skills(dir);
        }

        if auto_install && !hook.skill_installed {
            if let Some(ref dir) = skills_dir {
                if let Err(e) = hook.install_skill(dir) {
                    tracing::warn!("Failed to install pi-skills skill: {}", e);
                }
            }
        }

        hook
    }

    fn skill_file_path(skills_dir: &std::path::Path) -> PathBuf {
        skills_dir.join("nexus-memory-extraction").join("SKILL.md")
    }

    /// Find skills directory
    fn find_skills_dir() -> Option<PathBuf> {
        let home = dirs::home_dir()?;

        for dir_name in Self::SKILL_DIRS {
            let dir = home.join(dir_name);
            if dir.exists() {
                return Some(dir);
            }
        }

        None
    }

    /// Discover available skills
    fn discover_skills(&mut self, skills_dir: &PathBuf) {
        if !skills_dir.exists() {
            return;
        }

        if let Ok(entries) = std::fs::read_dir(skills_dir) {
            for entry in entries.filter_map(|e| e.ok()) {
                let skill_md = entry.path().join("SKILL.md");
                if skill_md.exists() {
                    if let Ok(content) = std::fs::read_to_string(&skill_md) {
                        if let Some(metadata) = self.parse_skill_metadata(&content) {
                            self.detected_skills.push(metadata);
                        }
                    }
                }
            }
        }
    }

    /// Parse SKILL.md frontmatter
    fn parse_skill_metadata(&self, content: &str) -> Option<SkillMetadata> {
        let content = content.trim();

        if !content.starts_with("---") {
            return None;
        }

        let end = content[3..].find("---")?;
        let frontmatter = &content[3..end + 3];

        // Parse YAML frontmatter (simplified)
        let mut metadata = SkillMetadata::default();

        for line in frontmatter.lines() {
            if let Some((key, value)) = line.split_once(':') {
                let key = key.trim();
                let value = value.trim().trim_matches('"');

                match key {
                    "name" => metadata.name = value.to_string(),
                    "description" => metadata.description = Some(value.to_string()),
                    "version" => metadata.version = Some(value.to_string()),
                    "author" => metadata.author = Some(value.to_string()),
                    _ => {}
                }
            }
        }

        if !metadata.name.is_empty() {
            Some(metadata)
        } else {
            None
        }
    }

    /// Install the nexus-memory-extraction skill
    fn install_skill(&mut self, skills_dir: &PathBuf) -> Result<()> {
        std::fs::create_dir_all(skills_dir).map_err(|e| {
            HookError::InstallationFailed(format!("Failed to create skills dir: {}", e))
        })?;

        let skill_dir = skills_dir.join("nexus-memory-extraction");
        std::fs::create_dir_all(&skill_dir).map_err(|e| {
            HookError::InstallationFailed(format!("Failed to create skill dir: {}", e))
        })?;

        let skill_md = skill_dir.join("SKILL.md");

        // Cross-compatible skill format
        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
triggers:
  - on_session_end
  - on_checkpoint
---

# Nexus Memory Extraction Skill

Cross-compatible skill for extracting session context.

## Compatible Platforms

- pi-mono
- oh-my-pi
- Claude Code
- Codex CLI
- Amp
- Droid

## Usage

This skill runs automatically when sessions end.

## Configuration

Helper files available at: {baseDir}/

Set environment variables:
- `NEXUS_AUTO_INGEST=true`
- `NEXUS_SERVER_URL=http://localhost:8768`
"#;

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

        self.skill_installed = true;
        tracing::info!("Pi-skills skill installed at: {:?}", skill_dir);

        Ok(())
    }

    /// Get list of available skills
    pub fn available_skills(&self) -> &[SkillMetadata] {
        &self.detected_skills
    }

    /// Check if a specific skill is available
    pub fn has_skill(&self, name: &str) -> bool {
        self.detected_skills.iter().any(|s| s.name == name)
    }

    /// Get skill by name
    pub fn get_skill(&self, name: &str) -> Option<&SkillMetadata> {
        self.detected_skills.iter().find(|s| s.name == name)
    }
}

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

#[async_trait]
impl AgentHook for PiSkillsHook {
    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;

        Ok(())
    }

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

        Ok(())
    }

    async fn detect_session_activity(&self) -> Result<SessionActivity> {
        let mut monitor = self.process_monitor.clone();
        let processes = monitor.find_agent_processes(AgentType::PiSkills);

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

        if !processes.is_empty() {
            activity.is_active = true;
            activity.processes = processes;
        }

        // Check for skills directory activity
        if let Some(ref dir) = self.skills_dir {
            if dir.exists() {
                if let Ok(entries) = std::fs::read_dir(dir) {
                    for entry in entries.filter_map(|e| e.ok()) {
                        let skill_md = entry.path().join("SKILL.md");
                        if skill_md.exists() {
                            if let Ok(metadata) = std::fs::metadata(&skill_md) {
                                if let Ok(modified) = metadata.modified() {
                                    let age = std::time::SystemTime::now()
                                        .duration_since(modified)
                                        .unwrap_or(std::time::Duration::MAX);

                                    if age.as_secs() < 300 {
                                        activity.is_active = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        Ok(activity)
    }

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

        // Add detected skills info
        let skill_names: Vec<String> = self
            .detected_skills
            .iter()
            .map(|s| s.name.clone())
            .collect();

        context.add_custom(
            "available_skills",
            serde_json::to_value(&skill_names).unwrap_or(serde_json::Value::Null),
        );

        // Add skill details
        for skill in &self.detected_skills {
            if let Some(ref desc) = skill.description {
                context.add_insight(format!("Skill '{}': {}", skill.name, desc));
            }
        }

        // Check for known skills availability
        for known_skill in Self::KNOWN_SKILLS {
            let is_available = self.has_skill(known_skill);
            context.add_custom(
                format!("skill_{}_available", known_skill.replace('-', "_")),
                serde_json::Value::Bool(is_available),
            );
        }

        // Get git status for skills repo if it's a git repo
        if let Some(ref dir) = self.skills_dir {
            let git_status = std::process::Command::new("git")
                .args(["status", "--porcelain"])
                .current_dir(dir)
                .output()
                .ok();

            if let Some(output) = git_status {
                if output.status.success() {
                    let status = String::from_utf8_lossy(&output.stdout);
                    for line in status.lines() {
                        if line.len() > 3 {
                            let file_path = &line[3..];
                            context.add_file(FileInfo::new(file_path, FileAction::Modified));
                        }
                    }
                }
            }
        }

        context.complete();
        Ok(context)
    }

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

    fn reliability_score(&self) -> f32 {
        if self.skill_installed {
            1.0
        } else {
            0.95
        }
    }

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

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

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

    #[test]
    fn test_pi_skills_hook_new() {
        let hook = PiSkillsHook::new();
        assert_eq!(hook.agent_type(), "pi-skills");
    }

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

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

    #[test]
    fn test_pi_skills_hook_constants() {
        assert_eq!(PiSkillsHook::AGENT_TYPE, "pi-skills");

        let known_skills = PiSkillsHook::KNOWN_SKILLS;
        assert!(known_skills.contains(&"brave-search"));
        assert!(known_skills.contains(&"transcribe"));
        assert!(known_skills.contains(&"youtube-transcript"));
    }

    #[test]
    fn test_pi_skills_hook_has_skill() {
        let hook = PiSkillsHook::new();

        // Should not have unknown skill
        assert!(!hook.has_skill("nonexistent-skill"));
    }

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

        assert!(
            !caps.session_start,
            "pi-skills does not support session_start"
        );
        assert!(caps.session_end, "pi-skills should support session_end");
        assert!(caps.checkpoint, "pi-skills should support checkpoint");
        assert!(!caps.error_hook, "pi-skills does not support error_hook");
        assert!(caps.compact, "pi-skills should support compact via skills");
    }

    #[tokio::test]
    async fn test_pi_skills_hook_install_compact_hook() {
        let mut hook = PiSkillsHook::new();
        let cb: SessionEndCallback = Arc::new(|_ctx| ());
        let result = hook.install_compact_hook(cb).await;
        assert!(
            result.is_ok(),
            "pi-skills should accept compact hook via skills"
        );
    }
}