skills 0.0.2

Manage agent skills
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
//! Implementation of the `skills push` command.

use std::{
    fs,
    path::{Path, PathBuf},
};

use inquire::{Confirm, error::InquireError};
use similar::{ChangeTag, TextDiff};

use crate::{
    catalog::Catalog,
    commands::{ColorChoice, init},
    config::Config,
    diagnostics::Diagnostics,
    error::{Error, Result},
    palette::{fmt_label, fmt_skill_name},
    skill::{SKILL_FILE_NAME, SkillTemplate, render_template},
    status::normalize_line_endings,
    tool::{Tool, ToolFilter},
};

/// Execute the push command.
#[allow(clippy::too_many_arguments)]
pub async fn run(
    color: ColorChoice,
    verbose: bool,
    skills: Vec<String>,
    all: bool,
    tool_filter: ToolFilter,
    dry_run: bool,
    force: bool,
    yes: bool,
) -> Result<()> {
    init::ensure().await?;
    let mut diagnostics = Diagnostics::new(verbose);
    let config = Config::load()?;
    let catalog = Catalog::load(&config, &mut diagnostics);
    let use_color = color.enabled();

    let tools = tool_filter.to_tools();

    // Determine which skills to push
    let skill_names: Vec<String> = if all {
        // Push all source skills
        catalog.sources.keys().cloned().collect()
    } else if skills.is_empty() {
        // No skills specified - find out-of-sync skills and confirm
        let out_of_sync = find_out_of_sync_skills(&catalog, &tools, &mut diagnostics);
        if out_of_sync.is_empty() {
            println!("All skills are in sync.");
            return Ok(());
        }
        if !force && !dry_run {
            println!("Skills needing push:");
            for name in &out_of_sync {
                println!("  {}", fmt_skill_name(name, use_color));
            }
            println!();
            let prompt = format!("Push {} skill(s)?", out_of_sync.len());
            if !confirm(&prompt)? {
                println!("Aborted.");
                return Ok(());
            }
            println!();
        }
        out_of_sync
    } else {
        // Validate that all specified skills exist
        for name in &skills {
            if !catalog.sources.contains_key(name) {
                return Err(Error::SkillNotFound { name: name.clone() });
            }
        }
        skills
    };

    if skill_names.is_empty() {
        println!("No skills to push.");
        return Ok(());
    }

    // Sort skills for consistent output
    let mut skill_names = skill_names;
    skill_names.sort_by(|a, b| a.to_lowercase().cmp(&b.to_lowercase()));

    let total = skill_names.len();
    let mut pushed_count = 0;
    let mut skipped_count = 0;

    for name in &skill_names {
        let template = catalog.sources.get(name).unwrap();
        let results = push_skill(&catalog, template, &tools, dry_run, force, yes, use_color, &mut diagnostics)?;

        // Check if any actual push happened
        let any_pushed = results.iter().any(|r| r.marker == '+' || r.marker == '~');
        let any_skipped = results.iter().any(|r| r.marker == '!');

        if any_pushed {
            pushed_count += 1;
        }
        if any_skipped {
            skipped_count += 1;
        }

        // Print results
        println!("{}", fmt_skill_name(name, use_color));
        for result in results {
            println!(
                "    {:<6}: {} ({})",
                result.tool_label, result.marker, result.summary
            );
        }
    }

    println!();
    if dry_run {
        println!(
            "{} {} skill(s) would be pushed.",
            fmt_label("Dry run:", use_color),
            total
        );
    } else {
        println!(
            "{} {} pushed, {} skipped.",
            fmt_label("Done:", use_color),
            pushed_count,
            skipped_count
        );
    }

    diagnostics.print_skipped_summary();
    diagnostics.print_warning_summary();
    Ok(())
}

/// Find skills that are out of sync (source differs from at least one tool).
fn find_out_of_sync_skills(
    catalog: &Catalog,
    tools: &[Tool],
    diagnostics: &mut Diagnostics,
) -> Vec<String> {
    let mut out_of_sync = Vec::new();

    for (name, source) in &catalog.sources {
        for &tool in tools {
            let tool_map = catalog.tools.get(&tool);
            let tool_skill = tool_map.and_then(|skills| skills.get(name));

            // Render the template for this tool
            let rendered = match render_template(&source.contents, tool) {
                Ok(rendered) => rendered,
                Err(error) => {
                    diagnostics.warn_skipped(&source.skill_path, error);
                    continue;
                }
            };

            match tool_skill {
                None => {
                    // Skill missing from tool
                    out_of_sync.push(name.clone());
                    break;
                }
                Some(installed) => {
                    if normalize_line_endings(&rendered)
                        != normalize_line_endings(&installed.contents)
                    {
                        // Skill differs
                        out_of_sync.push(name.clone());
                        break;
                    }
                }
            }
        }
    }

    out_of_sync.sort_by(|a, b| a.to_lowercase().cmp(&b.to_lowercase()));
    out_of_sync
}


/// Push a skill to specified tools.
#[allow(clippy::too_many_arguments)]
fn push_skill(
    catalog: &Catalog,
    skill: &SkillTemplate,
    tools: &[Tool],
    dry_run: bool,
    force: bool,
    yes: bool,
    use_color: bool,
    diagnostics: &mut Diagnostics,
) -> Result<Vec<PushLine>> {
    let mut results = Vec::new();

    for &tool in tools {
        let tool_dir = tool.skills_dir()?;
        let rendered = match render_template(&skill.contents, tool) {
            Ok(rendered) => rendered,
            Err(error) => {
                diagnostics.warn_skipped(&skill.skill_path, error);
                results.push(PushLine {
                    tool_label: tool.id().to_string(),
                    marker: '!',
                    summary: "skipped".to_string(),
                });
                continue;
            }
        };

        let tool_map = catalog.tools.get(&tool);
        let tool_skill = tool_map.and_then(|skills| skills.get(&skill.name));
        let existing = tool_skill.map(|installed| installed.contents.clone());
        let status = match &existing {
            None => PushStatus::New,
            Some(contents) => {
                if normalize_line_endings(&rendered) == normalize_line_endings(contents) {
                    PushStatus::Unchanged
                } else {
                    PushStatus::Modified
                }
            }
        };

        let request = PushRequest {
            skill,
            tool,
            tool_dir: &tool_dir,
            rendered: &rendered,
            existing: existing.as_deref(),
            status,
        };
        let result = apply_push(&request, dry_run, force, yes, use_color)?;

        results.push(PushLine {
            tool_label: tool.id().to_string(),
            marker: result.marker,
            summary: result.summary,
        });
    }

    Ok(results)
}

/// Request parameters for a push operation.
struct PushRequest<'a> {
    /// Source skill template to apply.
    skill: &'a SkillTemplate,
    /// Target tool.
    tool: Tool,
    /// Tool root directory.
    tool_dir: &'a PathBuf,
    /// Rendered template content.
    rendered: &'a str,
    /// Existing content in tool (if any).
    existing: Option<&'a str>,
    /// Precomputed push status.
    status: PushStatus,
}

/// Push status for a tool skill.
#[derive(Debug, Clone, Copy)]
enum PushStatus {
    /// Skill does not exist in the tool.
    New,
    /// Tool skill is already in sync.
    Unchanged,
    /// Tool skill is modified.
    Modified,
}

/// Output line for push summary.
struct PushLine {
    /// Tool label.
    tool_label: String,
    /// Output marker.
    marker: char,
    /// Summary label.
    summary: String,
}

/// Result of applying a push request.
struct PushResult {
    /// Output marker.
    marker: char,
    /// Summary label.
    summary: String,
}

/// Apply push logic and write skill files if needed.
fn apply_push(
    request: &PushRequest<'_>,
    dry_run: bool,
    force: bool,
    yes: bool,
    use_color: bool,
) -> Result<PushResult> {
    match request.status {
        PushStatus::Unchanged => Ok(PushResult {
            marker: '=',
            summary: "unchanged".to_string(),
        }),
        PushStatus::New => {
            if !dry_run {
                write_tool_skill(request.tool_dir, &request.skill.name, request.rendered)?;
            }
            Ok(PushResult {
                marker: '+',
                summary: "new".to_string(),
            })
        }
        PushStatus::Modified => {
            if !dry_run {
                // Always prompt unless --yes is specified
                let skip_prompt = force && yes;

                if !skip_prompt {
                    // Show diff if force is specified (so user sees what's changing)
                    if force {
                        if let Some(existing) = request.existing {
                            println!();
                            println!(
                                "Diff for '{}' in {}:",
                                request.skill.name,
                                request.tool.display_name()
                            );
                            print_diff(existing, request.rendered, use_color);
                        }
                    }

                    let prompt = format!(
                        "Overwrite modified skill '{}' in {}?",
                        request.skill.name,
                        request.tool.display_name()
                    );
                    let confirmed = confirm(&prompt)?;
                    if !confirmed {
                        return Ok(PushResult {
                            marker: '!',
                            summary: "skipped".to_string(),
                        });
                    }
                }

                write_tool_skill(request.tool_dir, &request.skill.name, request.rendered)?;
            }

            Ok(PushResult {
                marker: '~',
                summary: "pushed".to_string(),
            })
        }
    }
}

/// Print a unified diff between two strings.
fn print_diff(old: &str, new: &str, use_color: bool) {
    use owo_colors::OwoColorize;

    let diff = TextDiff::from_lines(old, new);

    for change in diff.iter_all_changes() {
        let sign = match change.tag() {
            ChangeTag::Delete => "-",
            ChangeTag::Insert => "+",
            ChangeTag::Equal => " ",
        };

        if use_color {
            match change.tag() {
                ChangeTag::Delete => print!("{}", format!("{}{}", sign, change).red()),
                ChangeTag::Insert => print!("{}", format!("{}{}", sign, change).green()),
                ChangeTag::Equal => print!(" {}", change),
            }
        } else {
            print!("{}{}", sign, change);
        }
    }
    println!();
}

/// Prompt for confirmation.
fn confirm(message: &str) -> Result<bool> {
    match Confirm::new(message).with_default(false).prompt() {
        Ok(value) => Ok(value),
        Err(InquireError::OperationCanceled) | Err(InquireError::OperationInterrupted) => {
            Err(Error::PromptCanceled)
        }
        Err(error) => Err(Error::PromptFailed {
            message: error.to_string(),
        }),
    }
}

/// Write a rendered skill to the tool directory.
fn write_tool_skill(tool_dir: &Path, name: &str, rendered: &str) -> Result<()> {
    let skill_dir = tool_dir.join(name);
    fs::create_dir_all(&skill_dir).map_err(|error| Error::SkillWrite {
        path: skill_dir.clone(),
        source: error,
    })?;

    let skill_path = skill_dir.join(SKILL_FILE_NAME);
    fs::write(&skill_path, rendered).map_err(|error| Error::SkillWrite {
        path: skill_path,
        source: error,
    })?;

    Ok(())
}