ah-cli 0.2.0

Agent History Search - cross-agent session full-text search CLI
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
use std::collections::HashMap;
use std::path::Path;
use std::sync::OnceLock;

use serde::Deserialize;

use crate::agents::{self, AgentPlugin};

static AGENT_REGISTRY: OnceLock<Vec<AgentDef>> = OnceLock::new();
static REMOTE_REGISTRY: OnceLock<Vec<RemoteDef>> = OnceLock::new();

/// Runtime agent definition (built-in + config merged).
pub struct AgentDef {
    pub id: String,
    pub plugin: &'static dyn AgentPlugin,
    pub glob_patterns: Vec<String>,
    pub path_markers: Vec<String>,
    pub disabled: bool,
    pub description: String,
    pub is_builtin: bool,
}

impl AgentDef {
    pub fn matches_path(&self, path: &Path) -> bool {
        let s = path.to_string_lossy();
        self.path_markers.iter().any(|marker| s.contains(marker))
    }
}

/// Remote host definition for SSH session aggregation.
pub struct RemoteDef {
    pub name: String,
    pub host: String,
    pub ah_path: String,
}

/// TOML deserialization structures.
#[derive(Deserialize, Default)]
struct AhrcConfig {
    #[serde(default)]
    agents: HashMap<String, AgentEntry>,
    #[serde(default)]
    remotes: HashMap<String, RemoteEntry>,
}

#[derive(Deserialize, Default)]
struct AgentEntry {
    plugin: Option<String>,
    file_patterns: Option<Vec<String>>,
    extra_patterns: Option<Vec<String>>,
    disabled: Option<bool>,
}

#[derive(Deserialize, Default)]
struct RemoteEntry {
    /// Optional in TOML so that one malformed `[remotes.*]` entry does not
    /// invalidate the entire `~/.ahrc` parse. Required at the validation
    /// step in `load_remotes`.
    host: Option<String>,
    ah_path: Option<String>,
}

/// Built-in agent definition (env var + default directory prefix).
struct BuiltinInfo {
    env_var: &'static str,
    default_prefix: &'static str,
}

fn builtin_env_info(agent_id: &str) -> Option<BuiltinInfo> {
    match agent_id {
        "claude" => Some(BuiltinInfo {
            env_var: "CLAUDE_CONFIG_DIR",
            default_prefix: ".claude",
        }),
        "codex" => Some(BuiltinInfo {
            env_var: "CODEX_HOME",
            default_prefix: ".codex",
        }),
        "gemini" => Some(BuiltinInfo {
            env_var: "GEMINI_CLI_HOME",
            default_prefix: ".gemini",
        }),
        "copilot" => Some(BuiltinInfo {
            env_var: "COPILOT_HOME",
            default_prefix: ".copilot",
        }),
        "cursor" => Some(BuiltinInfo {
            env_var: "CURSOR_CONFIG_DIR",
            default_prefix: ".cursor",
        }),
        _ => None,
    }
}

/// Expand a leading `~/` to the home directory path.
fn expand_tilde(s: &str, home: &Path) -> String {
    if let Some(rest) = s.strip_prefix("~/") {
        home.join(rest).to_string_lossy().to_string()
    } else {
        s.to_string()
    }
}

/// Expand `~` to home directory. Validate that patterns start with `~/` or `/`.
fn expand_pattern(pattern: &str, home: &Path) -> Result<String, String> {
    if pattern.starts_with("~/") || pattern.starts_with('/') {
        Ok(expand_tilde(pattern, home))
    } else {
        Err(format!(
            "Invalid pattern '{}': must start with ~/ or /",
            pattern
        ))
    }
}

/// Derive path_markers from glob patterns.
/// Uses the fixed (non-glob) prefix of each pattern as the marker.
fn derive_path_markers(patterns: &[String]) -> Vec<String> {
    let mut markers = Vec::new();
    for pattern in patterns {
        // Take the path up to the first glob character
        let prefix: String = pattern
            .chars()
            .take_while(|c| !matches!(c, '*' | '?' | '['))
            .collect();
        // Trim trailing slash
        let prefix = prefix.trim_end_matches('/');
        if !prefix.is_empty() && !markers.contains(&prefix.to_string()) {
            markers.push(prefix.to_string());
        }
    }
    markers
}

/// Resolve the base directory for a built-in agent (respects env var override).
pub fn resolve_agent_base(agent_id: &str) -> Option<std::path::PathBuf> {
    let info = builtin_env_info(agent_id)?;
    if let Ok(custom_dir) = std::env::var(info.env_var) {
        let trimmed = custom_dir.trim();
        if !trimmed.is_empty() {
            let home = crate::agents::common::canonical_home();
            return Some(std::path::PathBuf::from(expand_tilde(trimmed, &home)));
        }
    }
    let home = crate::agents::common::canonical_home();
    Some(home.join(info.default_prefix))
}

/// Apply env var override to built-in patterns.
/// If the env var is set, replace the default prefix with the env var value.
fn apply_env_override(patterns: &[&str], home: &Path, info: &BuiltinInfo) -> Vec<String> {
    if let Ok(custom_dir) = std::env::var(info.env_var) {
        let trimmed = custom_dir.trim();
        if trimmed.is_empty() {
            return patterns
                .iter()
                .map(|p| home.join(p).to_string_lossy().to_string())
                .collect();
        }
        let custom_dir = expand_tilde(trimmed, home);
        let custom_dir = custom_dir.trim_end_matches('/');
        patterns
            .iter()
            .map(|p| {
                // Replace the default prefix (e.g., .claude) with custom dir
                if let Some(rest) = p.strip_prefix(info.default_prefix) {
                    format!("{}{}", custom_dir, rest)
                } else {
                    home.join(p).to_string_lossy().to_string()
                }
            })
            .collect()
    } else {
        patterns
            .iter()
            .map(|p| home.join(p).to_string_lossy().to_string())
            .collect()
    }
}

/// Load config and build agent + remote registries.
fn load_config(home: &Path) -> (Vec<AgentDef>, Vec<RemoteDef>) {
    // 1. Build defaults from built-in plugins
    let mut agents: Vec<AgentDef> = agents::all_plugins()
        .iter()
        .map(|plugin| {
            let id = plugin.id().to_string();
            let (glob_patterns, env_overridden) = if let Some(info) = builtin_env_info(&id) {
                let patterns = apply_env_override(plugin.glob_patterns(), home, &info);
                let overridden = std::env::var(info.env_var)
                    .map(|v| !v.trim().is_empty())
                    .unwrap_or(false);
                (patterns, overridden)
            } else {
                let patterns = plugin
                    .glob_patterns()
                    .iter()
                    .map(|p| home.join(p).to_string_lossy().to_string())
                    .collect();
                (patterns, false)
            };
            let path_markers = if env_overridden {
                derive_path_markers(&glob_patterns)
            } else {
                plugin
                    .path_markers()
                    .iter()
                    .map(|s| s.to_string())
                    .collect()
            };
            AgentDef {
                id,
                plugin: *plugin,
                glob_patterns,
                path_markers,
                disabled: false,
                description: plugin.description().to_string(),
                is_builtin: true,
            }
        })
        .collect();

    // 2. Read ~/.ahrc if it exists
    let ahrc_path = home.join(".ahrc");
    let config = if ahrc_path.exists() {
        match std::fs::read_to_string(&ahrc_path) {
            Ok(content) => match toml::from_str::<AhrcConfig>(&content) {
                Ok(config) => config,
                Err(e) => {
                    eprintln!("Warning: failed to parse ~/.ahrc: {}", e);
                    AhrcConfig::default()
                }
            },
            Err(e) => {
                eprintln!("Warning: failed to read ~/.ahrc: {}", e);
                AhrcConfig::default()
            }
        }
    } else {
        return (agents, Vec::new());
    };

    // 3. Apply config overrides
    for (agent_id, entry) in &config.agents {
        if let Some(existing) = agents.iter_mut().find(|a| a.id == *agent_id) {
            // Override built-in agent
            if entry.disabled.unwrap_or(false) {
                existing.disabled = true;
            }
            if let Some(extra) = &entry.extra_patterns {
                for pattern in extra {
                    match expand_pattern(pattern, home) {
                        Ok(expanded) => existing.glob_patterns.push(expanded),
                        Err(e) => eprintln!("Warning: ~/.ahrc [agents.{}]: {}", agent_id, e),
                    }
                }
            }
        } else {
            // New custom agent
            let Some(plugin_name) = &entry.plugin else {
                eprintln!(
                    "Warning: ~/.ahrc [agents.{}]: 'plugin' is required for custom agents",
                    agent_id
                );
                continue;
            };
            let Some(plugin) = agents::find_builtin_plugin(plugin_name) else {
                eprintln!(
                    "Warning: ~/.ahrc [agents.{}]: unknown plugin '{}'",
                    agent_id, plugin_name
                );
                continue;
            };
            let Some(file_patterns) = &entry.file_patterns else {
                eprintln!(
                    "Warning: ~/.ahrc [agents.{}]: 'file_patterns' is required for custom agents",
                    agent_id
                );
                continue;
            };

            let mut glob_patterns = Vec::new();
            for pattern in file_patterns {
                match expand_pattern(pattern, home) {
                    Ok(expanded) => glob_patterns.push(expanded),
                    Err(e) => eprintln!("Warning: ~/.ahrc [agents.{}]: {}", agent_id, e),
                }
            }

            let path_markers = derive_path_markers(&glob_patterns);
            agents.push(AgentDef {
                id: agent_id.clone(),
                plugin,
                glob_patterns,
                path_markers,
                disabled: entry.disabled.unwrap_or(false),
                description: plugin.description().to_string(),
                is_builtin: false,
            });
        }
    }

    let remotes = load_remotes(&config);
    (agents, remotes)
}

/// Load remote definitions from parsed config.
fn load_remotes(config: &AhrcConfig) -> Vec<RemoteDef> {
    let mut remotes = Vec::new();
    for (name, entry) in &config.remotes {
        let host = match entry.host.as_deref().map(str::trim) {
            Some(h) if !h.is_empty() => h.to_string(),
            _ => {
                eprintln!(
                    "Warning: remote '{}' is missing required `host`. Skipping.",
                    name
                );
                continue;
            }
        };
        let ah_path = entry
            .ah_path
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .unwrap_or("ah")
            .to_string();
        if ah_path.starts_with('~') || (ah_path.contains('/') && !ah_path.starts_with('/')) {
            eprintln!(
                "Warning: remote '{}' has ah_path '{}' which is not an absolute path or bare command. \
                 Use an absolute path (e.g. /usr/local/bin/ah) or a bare command name (e.g. ah). Skipping.",
                name, ah_path
            );
            continue;
        }
        remotes.push(RemoteDef {
            name: name.clone(),
            host,
            ah_path,
        });
    }
    remotes.sort_by(|a, b| a.name.cmp(&b.name));
    remotes
}

/// Initialize the global agent and remote registries. Call once at startup.
pub fn init(home: &Path) {
    if AGENT_REGISTRY.get().is_some() && REMOTE_REGISTRY.get().is_some() {
        return;
    }
    let (agents, remotes) = load_config(home);
    AGENT_REGISTRY.get_or_init(|| agents);
    REMOTE_REGISTRY.get_or_init(|| remotes);
}

/// Get all agents (including disabled).
pub fn agents() -> &'static [AgentDef] {
    AGENT_REGISTRY
        .get()
        .expect("config::init() must be called before config::agents()")
}

/// Get all configured remotes.
pub fn remotes() -> &'static [RemoteDef] {
    REMOTE_REGISTRY
        .get()
        .expect("config::init() must be called before config::remotes()")
}

/// Find a remote by name.
pub fn find_remote(name: &str) -> Option<&'static RemoteDef> {
    remotes().iter().find(|r| r.name == name)
}

/// Get only active (non-disabled) agents.
pub fn active_agents() -> impl Iterator<Item = &'static AgentDef> {
    agents().iter().filter(|a| !a.disabled)
}

/// Find the best matching active agent for a path.
/// Prefers the agent with the longest matching path_marker (most specific match).
pub fn find_agent_for_path(path: &Path) -> Option<&'static AgentDef> {
    let path_str = path.to_string_lossy();
    active_agents()
        .filter(|a| a.matches_path(path))
        .max_by_key(|a| {
            a.path_markers
                .iter()
                .filter(|m| path_str.contains(m.as_str()))
                .map(|m| m.len())
                .max()
                .unwrap_or(0)
        })
}

/// Find an active agent's plugin by path.
pub fn find_plugin_for_path(path: &Path) -> &'static dyn AgentPlugin {
    find_agent_for_path(path)
        .map(|a| a.plugin)
        .unwrap_or_else(agents::unknown_plugin)
}

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

    fn test_home() -> PathBuf {
        PathBuf::from("/Users/test")
    }

    #[test]
    fn test_expand_pattern_home() {
        let home = test_home();
        assert_eq!(
            expand_pattern("~/.claude/projects/*/*.jsonl", &home).unwrap(),
            "/Users/test/.claude/projects/*/*.jsonl"
        );
    }

    #[test]
    fn test_expand_pattern_absolute() {
        let home = test_home();
        assert_eq!(
            expand_pattern("/custom/path/*.jsonl", &home).unwrap(),
            "/custom/path/*.jsonl"
        );
    }

    #[test]
    fn test_expand_pattern_relative_error() {
        let home = test_home();
        assert!(expand_pattern("relative/path", &home).is_err());
    }

    #[test]
    fn test_derive_path_markers() {
        let patterns = vec!["/Users/test/.myagent/sessions/**/*.jsonl".to_string()];
        let markers = derive_path_markers(&patterns);
        assert_eq!(markers, vec!["/Users/test/.myagent/sessions"]);
    }

    #[test]
    fn test_derive_path_markers_fixed_prefix() {
        let patterns = vec!["/custom/path/sessions/*.jsonl".to_string()];
        let markers = derive_path_markers(&patterns);
        assert_eq!(markers, vec!["/custom/path/sessions"]);
    }

    #[test]
    fn test_derive_path_markers_longer_wins() {
        // mydev path has a longer fixed prefix than local
        let local = vec!["/Users/test/.claude/projects/*/*.jsonl".to_string()];
        let remote = vec!["/Users/test/mnt/mydev/home/user/.claude/projects/*/*.jsonl".to_string()];
        let local_markers = derive_path_markers(&local);
        let remote_markers = derive_path_markers(&remote);
        assert!(remote_markers[0].len() > local_markers[0].len());
    }

    #[test]
    fn test_load_config_no_ahrc() {
        // Without ~/.ahrc, should return built-in defaults
        let home = PathBuf::from("/nonexistent/home");
        let (agents, remotes) = load_config(&home);
        assert_eq!(agents.len(), 5);
        assert_eq!(agents[0].id, "claude");
        assert_eq!(agents[1].id, "codex");
        assert!(!agents[0].disabled);
        assert!(remotes.is_empty());
    }

    #[test]
    fn test_parse_ahrc_disabled() {
        let toml_str = r#"
[agents.codex]
disabled = true
"#;
        let config: AhrcConfig = toml::from_str(toml_str).unwrap();
        assert!(config.agents["codex"].disabled.unwrap());
    }

    #[test]
    fn test_parse_ahrc_extra_patterns() {
        let toml_str = r#"
[agents.claude]
extra_patterns = ["~/.claude-dev/projects/*/*.jsonl"]
"#;
        let config: AhrcConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(
            config.agents["claude"].extra_patterns.as_ref().unwrap()[0],
            "~/.claude-dev/projects/*/*.jsonl"
        );
    }

    #[test]
    fn test_parse_ahrc_custom_agent() {
        let toml_str = r#"
[agents.mybot]
plugin = "claude"
file_patterns = ["~/.mybot/sessions/*.jsonl"]
"#;
        let config: AhrcConfig = toml::from_str(toml_str).unwrap();
        let mybot = &config.agents["mybot"];
        assert_eq!(mybot.plugin.as_deref(), Some("claude"));
        assert_eq!(
            mybot.file_patterns.as_ref().unwrap()[0],
            "~/.mybot/sessions/*.jsonl"
        );
    }
}