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
//! Template extraction and management
//!
//! Handles extracting embedded templates to ~/.patina/adapters/
//! and copying templates to projects.
//!
//! Templates are embedded at compile time and extracted on first run.
//! This allows user customization of templates in ~/.patina/adapters/.

use anyhow::{Context, Result};
use std::fs;
use std::path::Path;

use crate::paths;

// =============================================================================
// Thin wrapper scripts — shared across all adapters
// =============================================================================
// These forward to `patina session` Rust commands. Deployed to .{adapter}/bin/
// for backward compatibility with any code still calling session-*.sh directly.

const WRAPPER_START: &str = "#!/bin/bash\nexec patina session start \"$@\"\n";
const WRAPPER_UPDATE: &str = "#!/bin/bash\nexec patina session update \"$@\"\n";
const WRAPPER_NOTE: &str = "#!/bin/bash\nexec patina session note \"$@\"\n";
const WRAPPER_END: &str = "#!/bin/bash\nexec patina session end \"$@\"\n";

// =============================================================================
// Embedded Templates - Claude
// =============================================================================

mod claude_templates {
    // Commands (markdown)
    pub const SESSION_START_MD: &str = include_str!("../../resources/claude/session-start.md");
    pub const SESSION_UPDATE_MD: &str = include_str!("../../resources/claude/session-update.md");
    pub const SESSION_NOTE_MD: &str = include_str!("../../resources/claude/session-note.md");
    pub const SESSION_END_MD: &str = include_str!("../../resources/claude/session-end.md");
    pub const PATINA_REVIEW_MD: &str = include_str!("../../resources/claude/patina-review.md");

    // Skills - epistemic-beliefs
    pub const SKILL_EPISTEMIC_BELIEFS_MD: &str =
        include_str!("../../resources/claude/skills/epistemic-beliefs/SKILL.md");
    pub const SKILL_EPISTEMIC_BELIEFS_CREATE_SH: &str =
        include_str!("../../resources/claude/skills/epistemic-beliefs/scripts/create-belief.sh");
    pub const SKILL_EPISTEMIC_BELIEFS_EXAMPLE_MD: &str = include_str!(
        "../../resources/claude/skills/epistemic-beliefs/references/belief-example.md"
    );
}

// =============================================================================
// Embedded Templates - Gemini
// =============================================================================

mod gemini_templates {
    // Commands (TOML format for Gemini)
    pub const SESSION_START_TOML: &str = include_str!("../../resources/gemini/session-start.toml");
    pub const SESSION_UPDATE_TOML: &str =
        include_str!("../../resources/gemini/session-update.toml");
    pub const SESSION_NOTE_TOML: &str = include_str!("../../resources/gemini/session-note.toml");
    pub const SESSION_END_TOML: &str = include_str!("../../resources/gemini/session-end.toml");
    pub const PATINA_REVIEW_TOML: &str = include_str!("../../resources/gemini/patina-review.toml");

    // Context template
    pub const GEMINI_MD: &str = include_str!("../../resources/gemini/GEMINI.md");
}

// =============================================================================
// Embedded Templates - OpenCode
// =============================================================================

mod opencode_templates {
    // Commands (markdown format, same as Claude)
    pub const SESSION_START_MD: &str = include_str!("../../resources/opencode/session-start.md");
    pub const SESSION_UPDATE_MD: &str = include_str!("../../resources/opencode/session-update.md");
    pub const SESSION_NOTE_MD: &str = include_str!("../../resources/opencode/session-note.md");
    pub const SESSION_END_MD: &str = include_str!("../../resources/opencode/session-end.md");
    pub const PATINA_REVIEW_MD: &str = include_str!("../../resources/opencode/patina-review.md");
}

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

/// Extract all templates to ~/.patina/adapters/
///
/// Called during first-run setup. Creates the full template structure
/// for all supported adapters.
pub fn install_all(adapters_dir: &Path) -> Result<()> {
    install_claude_templates(adapters_dir)?;
    install_gemini_templates(adapters_dir)?;
    install_opencode_templates(adapters_dir)?;
    Ok(())
}

/// Copy adapter templates to project
///
/// Copies the adapter-specific directory (.claude/, .gemini/) from
/// central templates to the project.
pub fn copy_to_project(adapter_name: &str, project_path: &Path) -> Result<()> {
    let templates_dir = paths::adapters_dir().join(adapter_name).join("templates");

    let adapter_dir_name = format!(".{}", adapter_name);
    let src = templates_dir.join(&adapter_dir_name);
    let dest = project_path.join(&adapter_dir_name);

    // Always refresh cache from embedded templates
    // This ensures updates to templates in the binary are applied
    let adapters = paths::adapters_dir();
    install_all(&adapters)?;

    copy_dir_recursive(&src, &dest)?;
    Ok(())
}

/// Check if templates are installed for an adapter
pub fn templates_installed(adapter_name: &str) -> bool {
    let templates_dir = paths::adapters_dir().join(adapter_name).join("templates");
    templates_dir.exists()
}

// =============================================================================
// Claude Templates Installation
// =============================================================================

fn install_claude_templates(adapters_dir: &Path) -> Result<()> {
    let templates_dir = adapters_dir.join("claude").join("templates");
    // Create .claude/ structure inside templates/ so copy_to_project works correctly
    let claude_dir = templates_dir.join(".claude");
    let bin_dir = claude_dir.join("bin");
    let commands_dir = claude_dir.join("commands");
    let context_dir = claude_dir.join("context");
    let skills_dir = claude_dir.join("skills");

    // Create directories
    fs::create_dir_all(&bin_dir)?;
    fs::create_dir_all(&commands_dir)?;
    fs::create_dir_all(&context_dir)?;
    fs::create_dir_all(&skills_dir)?;

    // Write wrapper scripts (forward to patina session commands)
    write_executable(&bin_dir.join("session-start.sh"), WRAPPER_START)?;
    write_executable(&bin_dir.join("session-update.sh"), WRAPPER_UPDATE)?;
    write_executable(&bin_dir.join("session-note.sh"), WRAPPER_NOTE)?;
    write_executable(&bin_dir.join("session-end.sh"), WRAPPER_END)?;

    // Write commands
    fs::write(
        commands_dir.join("session-start.md"),
        claude_templates::SESSION_START_MD,
    )?;
    fs::write(
        commands_dir.join("session-update.md"),
        claude_templates::SESSION_UPDATE_MD,
    )?;
    fs::write(
        commands_dir.join("session-note.md"),
        claude_templates::SESSION_NOTE_MD,
    )?;
    fs::write(
        commands_dir.join("session-end.md"),
        claude_templates::SESSION_END_MD,
    )?;
    fs::write(
        commands_dir.join("patina-review.md"),
        claude_templates::PATINA_REVIEW_MD,
    )?;

    // Write skills - epistemic-beliefs
    let epistemic_beliefs_dir = skills_dir.join("epistemic-beliefs");
    let epistemic_scripts_dir = epistemic_beliefs_dir.join("scripts");
    let epistemic_refs_dir = epistemic_beliefs_dir.join("references");
    fs::create_dir_all(&epistemic_scripts_dir)?;
    fs::create_dir_all(&epistemic_refs_dir)?;

    fs::write(
        epistemic_beliefs_dir.join("SKILL.md"),
        claude_templates::SKILL_EPISTEMIC_BELIEFS_MD,
    )?;
    write_executable(
        &epistemic_scripts_dir.join("create-belief.sh"),
        claude_templates::SKILL_EPISTEMIC_BELIEFS_CREATE_SH,
    )?;
    fs::write(
        epistemic_refs_dir.join("belief-example.md"),
        claude_templates::SKILL_EPISTEMIC_BELIEFS_EXAMPLE_MD,
    )?;

    Ok(())
}

// =============================================================================
// Gemini Templates Installation
// =============================================================================

fn install_gemini_templates(adapters_dir: &Path) -> Result<()> {
    let templates_dir = adapters_dir.join("gemini").join("templates");
    // Create .gemini/ structure inside templates/ so copy_to_project works correctly
    let gemini_dir = templates_dir.join(".gemini");
    let bin_dir = gemini_dir.join("bin");
    let commands_dir = gemini_dir.join("commands");

    // Create directories
    fs::create_dir_all(&bin_dir)?;
    fs::create_dir_all(&commands_dir)?;

    // Write wrapper scripts (forward to patina session commands)
    write_executable(&bin_dir.join("session-start.sh"), WRAPPER_START)?;
    write_executable(&bin_dir.join("session-update.sh"), WRAPPER_UPDATE)?;
    write_executable(&bin_dir.join("session-note.sh"), WRAPPER_NOTE)?;
    write_executable(&bin_dir.join("session-end.sh"), WRAPPER_END)?;

    // Write commands (TOML format for Gemini)
    fs::write(
        commands_dir.join("session-start.toml"),
        gemini_templates::SESSION_START_TOML,
    )?;
    fs::write(
        commands_dir.join("session-update.toml"),
        gemini_templates::SESSION_UPDATE_TOML,
    )?;
    fs::write(
        commands_dir.join("session-note.toml"),
        gemini_templates::SESSION_NOTE_TOML,
    )?;
    fs::write(
        commands_dir.join("session-end.toml"),
        gemini_templates::SESSION_END_TOML,
    )?;
    fs::write(
        commands_dir.join("patina-review.toml"),
        gemini_templates::PATINA_REVIEW_TOML,
    )?;

    // Write GEMINI.md template
    fs::write(templates_dir.join("GEMINI.md"), gemini_templates::GEMINI_MD)?;

    Ok(())
}

// =============================================================================
// OpenCode Templates Installation
// =============================================================================

fn install_opencode_templates(adapters_dir: &Path) -> Result<()> {
    let templates_dir = adapters_dir.join("opencode").join("templates");
    // Create .opencode/ structure inside templates/ so copy_to_project works correctly
    let opencode_dir = templates_dir.join(".opencode");
    let bin_dir = opencode_dir.join("bin");
    let commands_dir = opencode_dir.join("commands");

    // Create directories
    fs::create_dir_all(&bin_dir)?;
    fs::create_dir_all(&commands_dir)?;

    // Write wrapper scripts (forward to patina session commands)
    write_executable(&bin_dir.join("session-start.sh"), WRAPPER_START)?;
    write_executable(&bin_dir.join("session-update.sh"), WRAPPER_UPDATE)?;
    write_executable(&bin_dir.join("session-note.sh"), WRAPPER_NOTE)?;
    write_executable(&bin_dir.join("session-end.sh"), WRAPPER_END)?;

    // Write commands (markdown format, same as Claude)
    fs::write(
        commands_dir.join("session-start.md"),
        opencode_templates::SESSION_START_MD,
    )?;
    fs::write(
        commands_dir.join("session-update.md"),
        opencode_templates::SESSION_UPDATE_MD,
    )?;
    fs::write(
        commands_dir.join("session-note.md"),
        opencode_templates::SESSION_NOTE_MD,
    )?;
    fs::write(
        commands_dir.join("session-end.md"),
        opencode_templates::SESSION_END_MD,
    )?;
    fs::write(
        commands_dir.join("patina-review.md"),
        opencode_templates::PATINA_REVIEW_MD,
    )?;

    Ok(())
}

// =============================================================================
// Helpers
// =============================================================================

/// Write a file and make it executable
fn write_executable(path: &Path, content: &str) -> Result<()> {
    fs::write(path, content)?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(path)?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions(path, perms)?;
    }

    Ok(())
}

/// Recursively copy a directory
fn copy_dir_recursive(src: &Path, dest: &Path) -> Result<()> {
    if !src.exists() {
        anyhow::bail!("Source directory does not exist: {}", src.display());
    }

    fs::create_dir_all(dest)
        .with_context(|| format!("Failed to create directory: {}", dest.display()))?;

    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let src_path = entry.path();
        let dest_path = dest.join(entry.file_name());

        if src_path.is_dir() {
            copy_dir_recursive(&src_path, &dest_path)?;
        } else {
            fs::copy(&src_path, &dest_path).with_context(|| {
                format!(
                    "Failed to copy: {} -> {}",
                    src_path.display(),
                    dest_path.display()
                )
            })?;

            // Preserve executable permissions
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let src_mode = fs::metadata(&src_path)?.permissions().mode();
                if src_mode & 0o111 != 0 {
                    let mut perms = fs::metadata(&dest_path)?.permissions();
                    perms.set_mode(src_mode);
                    fs::set_permissions(&dest_path, perms)?;
                }
            }
        }
    }

    Ok(())
}

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

    #[test]
    fn test_claude_templates_compile() {
        // Verify command definitions are embedded correctly
        assert!(!claude_templates::SESSION_START_MD.is_empty());
        assert!(!claude_templates::SESSION_END_MD.is_empty());
        // Skills
        assert!(!claude_templates::SKILL_EPISTEMIC_BELIEFS_MD.is_empty());
        assert!(!claude_templates::SKILL_EPISTEMIC_BELIEFS_CREATE_SH.is_empty());
        assert!(!claude_templates::SKILL_EPISTEMIC_BELIEFS_EXAMPLE_MD.is_empty());
    }

    #[test]
    fn test_gemini_templates_compile() {
        // Verify command definitions are embedded correctly
        assert!(!gemini_templates::SESSION_START_TOML.is_empty());
        assert!(!gemini_templates::GEMINI_MD.is_empty());
    }

    #[test]
    fn test_wrapper_scripts_content() {
        // Verify wrapper scripts forward to patina session commands
        assert!(WRAPPER_START.contains("patina session start"));
        assert!(WRAPPER_UPDATE.contains("patina session update"));
        assert!(WRAPPER_NOTE.contains("patina session note"));
        assert!(WRAPPER_END.contains("patina session end"));
    }

    #[test]
    fn test_install_claude_templates() {
        let temp = TempDir::new().unwrap();
        install_claude_templates(temp.path()).unwrap();

        // Templates install to .claude/ structure for copy_to_project()
        let templates_dir = temp.path().join("claude/templates");
        assert!(templates_dir.join(".claude/bin/session-start.sh").exists());
        assert!(templates_dir
            .join(".claude/commands/session-start.md")
            .exists());
        assert!(templates_dir
            .join(".claude/commands/patina-review.md")
            .exists());
        // Deprecated commands should not exist
        assert!(!templates_dir.join(".claude/bin/launch.sh").exists());
        assert!(!templates_dir.join(".claude/bin/persona-start.sh").exists());

        // Wrapper scripts should forward to patina session
        let wrapper =
            fs::read_to_string(templates_dir.join(".claude/bin/session-start.sh")).unwrap();
        assert!(wrapper.contains("patina session start"));

        // Skills should be installed
        assert!(templates_dir
            .join(".claude/skills/epistemic-beliefs/SKILL.md")
            .exists());
        assert!(templates_dir
            .join(".claude/skills/epistemic-beliefs/scripts/create-belief.sh")
            .exists());
        assert!(templates_dir
            .join(".claude/skills/epistemic-beliefs/references/belief-example.md")
            .exists());
    }

    #[test]
    fn test_install_gemini_templates() {
        let temp = TempDir::new().unwrap();
        install_gemini_templates(temp.path()).unwrap();

        // Templates install to .gemini/ structure for copy_to_project()
        let templates_dir = temp.path().join("gemini/templates");
        assert!(templates_dir.join(".gemini/bin/session-start.sh").exists());
        assert!(templates_dir
            .join(".gemini/commands/session-start.toml")
            .exists());
        assert!(templates_dir.join("GEMINI.md").exists());

        // Wrapper scripts should forward to patina session
        let wrapper =
            fs::read_to_string(templates_dir.join(".gemini/bin/session-start.sh")).unwrap();
        assert!(wrapper.contains("patina session start"));
    }
}