patina-ai 0.23.0

Context orchestration for AI development - captures and evolves patterns over time
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
//! Launcher functionality for adapters
//!
//! Provides CLI detection, MCP configuration, and bootstrap generation
//! for launching AI adapters. This complements the init-time functionality
//! in the adapter modules.
//!
//! # Example
//!
//! ```no_run
//! use patina::adapters::launch;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // List available adapters
//!     let adapters = launch::list()?;
//!     for f in &adapters {
//!         println!("{}: {} (detected: {})", f.name, f.display, f.detected);
//!     }
//!
//!     // Get specific adapter
//!     let claude = launch::get("claude")?;
//!     Ok(())
//! }
//! ```

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::workspace;

/// Available adapter names
pub const ADAPTERS: &[&str] = &["claude", "gemini", "opencode"];

/// Markers for Patina-managed section in bootstrap files
const MARKER_START: &str = "<!-- PATINA:START -->";
const MARKER_END: &str = "<!-- PATINA:END -->";

// =============================================================================
// Types
// =============================================================================

/// Adapter identifier
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Adapter {
    Claude,
    Gemini,
    OpenCode,
}

impl Adapter {
    pub fn name(&self) -> &'static str {
        match self {
            Adapter::Claude => "claude",
            Adapter::Gemini => "gemini",
            Adapter::OpenCode => "opencode",
        }
    }

    pub fn display(&self) -> &'static str {
        match self {
            Adapter::Claude => "Claude Code",
            Adapter::Gemini => "Gemini CLI",
            Adapter::OpenCode => "OpenCode",
        }
    }

    pub fn from_name(name: &str) -> Option<Self> {
        match name.to_lowercase().as_str() {
            "claude" => Some(Adapter::Claude),
            "gemini" => Some(Adapter::Gemini),
            "opencode" => Some(Adapter::OpenCode),
            _ => None,
        }
    }

    pub fn bootstrap_file(&self) -> &'static str {
        match self {
            Adapter::Claude => "CLAUDE.md",
            Adapter::Gemini => "GEMINI.md",
            Adapter::OpenCode => "OPENCODE.md",
        }
    }

    pub fn detect_commands(&self) -> &'static [&'static str] {
        match self {
            Adapter::Claude => &["claude --version"],
            Adapter::Gemini => &["gemini --version"],
            Adapter::OpenCode => &["opencode --version"],
        }
    }
}

/// Runtime adapter info with detection status
#[derive(Debug, Clone)]
pub struct AdapterInfo {
    pub name: String,
    pub display: String,
    pub detected: bool,
    pub version: Option<String>,
    pub mcp: Option<McpConfig>,
}

/// MCP configuration for an adapter
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpConfig {
    pub config_path: String,
    pub config_format: String,
    #[serde(default)]
    pub config_template: Option<String>,
}

// =============================================================================
// Public API
// =============================================================================

/// List all available adapters with detection status
pub fn list() -> Result<Vec<AdapterInfo>> {
    let mut adapters = Vec::new();

    for name in ADAPTERS {
        if let Ok(info) = get(name) {
            adapters.push(info);
        }
    }

    Ok(adapters)
}

/// Get info for a specific adapter
pub fn get(name: &str) -> Result<AdapterInfo> {
    let adapter =
        Adapter::from_name(name).ok_or_else(|| anyhow::anyhow!("Unknown adapter: {}", name))?;

    let (detected, version) = detect_cli(&adapter);

    Ok(AdapterInfo {
        name: adapter.name().to_string(),
        display: adapter.display().to_string(),
        detected,
        version,
        mcp: get_mcp_config(&adapter),
    })
}

/// Check if an adapter CLI is available
pub fn is_available(name: &str) -> bool {
    get(name).map(|f| f.detected).unwrap_or(false)
}

/// Get the default adapter name from global config
pub fn default_name() -> Result<String> {
    let config = workspace::config()?;
    Ok(config.adapter.default)
}

/// Set the default adapter
pub fn set_default(name: &str) -> Result<()> {
    // Verify adapter exists
    let _ = Adapter::from_name(name).ok_or_else(|| anyhow::anyhow!("Unknown adapter: {}", name))?;

    let mut config = workspace::config()?;
    config.adapter.default = name.to_string();
    workspace::save_config(&config)?;

    Ok(())
}

/// Generate bootstrap file for a project
///
/// Uses marker-based updates to preserve user content:
/// - If file doesn't exist: create with Patina section
/// - If file exists without markers: append Patina section
/// - If file exists with markers: replace only content between markers
pub fn generate_bootstrap(name: &str, project_path: &Path) -> Result<()> {
    let adapter =
        Adapter::from_name(name).ok_or_else(|| anyhow::anyhow!("Unknown adapter: {}", name))?;

    let bootstrap_path = project_path.join(adapter.bootstrap_file());
    let section = patina_section(&adapter);

    let new_content = if bootstrap_path.exists() {
        let content = fs::read_to_string(&bootstrap_path)
            .with_context(|| format!("Failed to read {}", bootstrap_path.display()))?;
        update_or_append_section(&content, &section)
    } else {
        section
    };

    fs::write(&bootstrap_path, new_content)
        .with_context(|| format!("Failed to write {}", bootstrap_path.display()))?;

    Ok(())
}

/// Check if MCP is configured for an adapter (patina server present in config)
pub fn is_mcp_configured(name: &str) -> Result<bool> {
    let info = get(name)?;

    let mcp = match info.mcp.as_ref() {
        Some(m) => m,
        None => return Ok(true), // No MCP config needed for this adapter
    };

    let config_path = PathBuf::from(shellexpand::tilde(&mcp.config_path).as_ref());

    if !config_path.exists() {
        return Ok(false);
    }

    // Read config and check for patina server
    let content = fs::read_to_string(&config_path).unwrap_or_default();

    // Check if "patina" server is configured
    // For JSON configs, look for "patina" in mcpServers
    Ok(content.contains("\"patina\"") && content.contains("mcpServers"))
}

/// Configure MCP for an adapter (update its config file)
pub fn configure_mcp(name: &str) -> Result<()> {
    let info = get(name)?;

    let mcp = info
        .mcp
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("Adapter {} has no MCP configuration", name))?;

    let config_path = PathBuf::from(shellexpand::tilde(&mcp.config_path).as_ref());

    // Ensure parent directory exists
    if let Some(parent) = config_path.parent() {
        fs::create_dir_all(parent)?;
    }

    // For now, just write template if no config exists
    if !config_path.exists() {
        if let Some(template) = &mcp.config_template {
            fs::write(&config_path, template)?;
        }
    } else {
        // Config exists - try to add patina server if not present
        if !is_mcp_configured(name).unwrap_or(true) {
            // Read existing config and try to merge
            if let Ok(content) = fs::read_to_string(&config_path) {
                if let Ok(mut json) = serde_json::from_str::<serde_json::Value>(&content) {
                    // Add patina to mcpServers
                    if let Some(obj) = json.as_object_mut() {
                        let mcp_servers = obj
                            .entry("mcpServers")
                            .or_insert_with(|| serde_json::json!({}));
                        if let Some(servers) = mcp_servers.as_object_mut() {
                            servers.insert(
                                "patina".to_string(),
                                serde_json::json!({
                                    "command": "patina",
                                    "args": ["mother", "start", "--mcp"]
                                }),
                            );
                            // Write back
                            if let Ok(updated) = serde_json::to_string_pretty(&json) {
                                let _ = fs::write(&config_path, updated);
                            }
                        }
                    }
                }
            }
        }
    }

    Ok(())
}

/// Detect CLI version for an adapter
pub fn detect_version(name: &str) -> Option<String> {
    let adapter = Adapter::from_name(name)?;
    let (_, version) = detect_cli(&adapter);
    version
}

/// Select an adapter from available options.
///
/// Returns the chosen adapter name.
///
/// Behavior:
/// - 0 available: Error with installation instructions
/// - 1 available: Returns it (no prompt)
/// - 2+ available: Prompts user to choose
///
/// If `preference` matches an available adapter, it becomes the default selection.
/// This is used to honor the global config default without forcing it.
pub fn select_adapter(available: &[AdapterInfo], preference: Option<&str>) -> Result<String> {
    use std::io::{self, Write};

    match available.len() {
        0 => {
            anyhow::bail!(
                "No AI adapters detected on this system.\n\
                 Install one of: {}",
                ADAPTERS.join(", ")
            );
        }
        1 => {
            // Single adapter - use it without prompting
            Ok(available[0].name.clone())
        }
        _ => {
            // Multiple adapters - prompt user to choose
            println!("\n📱 Available adapters:");

            // Find which index should be default (1-based for display)
            let default_idx = preference
                .and_then(|pref| available.iter().position(|a| a.name == pref))
                .map(|i| i + 1)
                .unwrap_or(1);

            for (i, adapter) in available.iter().enumerate() {
                let num = i + 1;
                let default_marker = if num == default_idx { " (default)" } else { "" };
                println!("  [{}] {}{}", num, adapter.display, default_marker);
            }

            print!("\nSelect adapter [{}]: ", default_idx);
            io::stdout().flush()?;

            let mut input = String::new();
            io::stdin().read_line(&mut input)?;

            let choice = input.trim();
            let idx = if choice.is_empty() {
                default_idx
            } else {
                choice.parse::<usize>().unwrap_or(default_idx)
            };

            // Validate and return
            if idx >= 1 && idx <= available.len() {
                Ok(available[idx - 1].name.clone())
            } else {
                // Invalid input, use default
                Ok(available[default_idx - 1].name.clone())
            }
        }
    }
}

// =============================================================================
// Internal
// =============================================================================

/// Detect if CLI is installed and get version
fn detect_cli(adapter: &Adapter) -> (bool, Option<String>) {
    for cmd in adapter.detect_commands() {
        if let Some(version) = try_command(cmd) {
            return (true, Some(version));
        }
    }
    (false, None)
}

/// Try running a command and capture version output
fn try_command(cmd: &str) -> Option<String> {
    let parts: Vec<&str> = cmd.split_whitespace().collect();
    if parts.is_empty() {
        return None;
    }

    let output = Command::new(parts[0]).args(&parts[1..]).output().ok()?;

    if output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        // Return first non-empty line as version
        stdout
            .lines()
            .chain(stderr.lines())
            .find(|l| !l.trim().is_empty())
            .map(|s| s.trim().to_string())
    } else {
        None
    }
}

/// Get MCP config for an adapter
fn get_mcp_config(adapter: &Adapter) -> Option<McpConfig> {
    match adapter {
        Adapter::Claude => Some(McpConfig {
            config_path: "~/.claude/settings.json".to_string(),
            config_format: "json".to_string(),
            config_template: Some(MCP_TEMPLATE.to_string()),
        }),
        Adapter::Gemini => None,   // TBD
        Adapter::OpenCode => None, // TBD
    }
}

/// Update or append Patina section in existing content
fn update_or_append_section(content: &str, section: &str) -> String {
    if let (Some(start), Some(end)) = (content.find(MARKER_START), content.find(MARKER_END)) {
        if start < end {
            // Replace between markers
            let before = &content[..start];
            let after = &content[end + MARKER_END.len()..];
            return format!("{}{}{}", before, section, after);
        }
    }
    // Append (no markers or malformed)
    format!("{}\n\n{}", content.trim_end(), section)
}

/// Generate Patina section with markers
fn patina_section(adapter: &Adapter) -> String {
    format!(
        r#"<!-- PATINA:START -->
## Patina

MCP tools: `scry` (search), `context` (patterns)

*Generated by Patina | Adapter: {}*
<!-- PATINA:END -->"#,
        adapter.display()
    )
}

const MCP_TEMPLATE: &str = r#"{
  "mcpServers": {
    "patina": {
      "command": "patina",
      "args": ["mother", "start", "--mcp"]
    }
  }
}"#;

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

    #[test]
    fn test_adapter_names() {
        assert_eq!(Adapter::Claude.name(), "claude");
        assert_eq!(Adapter::Gemini.name(), "gemini");
        assert_eq!(Adapter::OpenCode.name(), "opencode");
    }

    #[test]
    fn test_adapter_from_name() {
        assert_eq!(Adapter::from_name("claude"), Some(Adapter::Claude));
        assert_eq!(Adapter::from_name("CLAUDE"), Some(Adapter::Claude));
        assert_eq!(Adapter::from_name("opencode"), Some(Adapter::OpenCode));
        assert_eq!(Adapter::from_name("OpenCode"), Some(Adapter::OpenCode));
        assert_eq!(Adapter::from_name("unknown"), None);
    }

    #[test]
    fn test_bootstrap_files() {
        assert_eq!(Adapter::Claude.bootstrap_file(), "CLAUDE.md");
        assert_eq!(Adapter::Gemini.bootstrap_file(), "GEMINI.md");
        assert_eq!(Adapter::OpenCode.bootstrap_file(), "OPENCODE.md");
    }

    #[test]
    fn test_adapters_list() {
        assert!(ADAPTERS.contains(&"claude"));
        assert!(ADAPTERS.contains(&"gemini"));
        assert!(ADAPTERS.contains(&"opencode"));
        assert_eq!(ADAPTERS.len(), 3);
    }

    #[test]
    fn test_select_adapter_zero_available() {
        let available: Vec<AdapterInfo> = vec![];
        let result = select_adapter(&available, None);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("No AI adapters detected"));
    }

    #[test]
    fn test_select_adapter_single_available() {
        let available = vec![AdapterInfo {
            name: "claude".to_string(),
            display: "Claude Code".to_string(),
            detected: true,
            version: Some("1.0".to_string()),
            mcp: None,
        }];
        let result = select_adapter(&available, None);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "claude");
    }

    #[test]
    fn test_select_adapter_single_ignores_preference() {
        let available = vec![AdapterInfo {
            name: "gemini".to_string(),
            display: "Gemini CLI".to_string(),
            detected: true,
            version: None,
            mcp: None,
        }];
        // Even with claude preference, returns the only available adapter
        let result = select_adapter(&available, Some("claude"));
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "gemini");
    }
}