tincan-cli 0.3.0

Preserve development plans, decisions, learnings, and progress in workspace-local Markdown
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
use dialoguer::{Confirm, MultiSelect, theme::ColorfulTheme};
use std::collections::BTreeSet;
use std::fs;
use std::io::{self, IsTerminal};
use std::path::{Path, PathBuf};

use crate::util::display_path;

const SKILL: &str = include_str!("../skills/tincan/SKILL.md");
const OPENAI_METADATA: &str = include_str!("../skills/tincan/agents/openai.yaml");
const PICKER_HELP: &str =
    "[↑↓ move, Space select/unselect, A toggle all/none, Enter continue, Esc cancel]";

#[derive(Debug)]
pub enum InstallOutcome {
    Installed(PathBuf),
    AlreadyCurrent(PathBuf),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SkillRoot {
    pub name: String,
    pub path: PathBuf,
}

pub fn detect_roots() -> Vec<SkillRoot> {
    let home = nonempty_env("USERPROFILE")
        .or_else(|| nonempty_env("HOME"))
        .map(PathBuf::from);
    let codex_home = nonempty_env("CODEX_HOME").map(PathBuf::from);
    detect_roots_from(home.as_deref(), codex_home.as_deref())
}

pub fn offer_updates() -> Result<(), String> {
    if !io::stderr().is_terminal() {
        return Ok(());
    }
    let roots = detect_roots();
    let outdated = outdated_roots(&roots);
    if outdated.is_empty() {
        return Ok(());
    }
    eprintln!("Tincan Agent Skill update available.");
    eprintln!();
    eprintln!("The following installations can be updated:");
    for root in &outdated {
        eprintln!(
            "  - {}: {}",
            root.name,
            display_user_path(&root.path.join("tincan"))
        );
    }
    eprintln!();
    let confirmed = Confirm::with_theme(&ColorfulTheme::default())
        .with_prompt("Update them now?")
        .default(false)
        .wait_for_newline(true)
        .interact()
        .map_err(|error| format!("cannot read skill update confirmation: {error}"))?;
    if !confirmed {
        return Ok(());
    }
    let paths: Vec<_> = outdated.iter().map(|root| root.path.clone()).collect();
    for outcome in install_many(&paths, true)? {
        match outcome {
            InstallOutcome::Installed(path) => {
                eprintln!("Updated Tincan skill at {}", display_user_path(&path));
            }
            InstallOutcome::AlreadyCurrent(path) => {
                eprintln!(
                    "Tincan skill is already current at {}",
                    display_user_path(&path)
                );
            }
        }
    }
    eprintln!("Restart or reload the agent harness to discover the update.\n");
    Ok(())
}

fn outdated_roots(roots: &[SkillRoot]) -> Vec<&SkillRoot> {
    roots
        .iter()
        .filter(|root| {
            let destination = root.path.join("tincan");
            let skill = destination.join("SKILL.md");
            let metadata = destination.join("agents").join("openai.yaml");
            destination.is_dir()
                && (read(&skill).ok().as_deref() != Some(SKILL)
                    || read(&metadata).ok().as_deref() != Some(OPENAI_METADATA))
        })
        .collect()
}

pub fn choose_interactively(roots: &[SkillRoot]) -> Result<Option<Vec<PathBuf>>, String> {
    let labels = picker_labels(roots);
    let defaults = default_selections(roots);
    let theme = ColorfulTheme::default();
    loop {
        let Some(indices) = MultiSelect::with_theme(&theme)
            .with_prompt("Select user-wide Agent Skills destinations")
            .items(&labels)
            .defaults(&defaults)
            .report(false)
            .interact_opt()
            .map_err(|error| format!("cannot read skill destination selection: {error}"))?
        else {
            return Ok(None);
        };
        let selected = selected_paths(roots, &indices);
        if selected.is_empty() {
            eprintln!("No destinations selected. Select at least one or press Escape to cancel.");
            continue;
        }
        println!("✔ Select user-wide Agent Skills destinations");
        println!("The Tincan skill will be installed in:");
        for index in &indices {
            if let Some(root) = roots.get(*index) {
                println!("  - {}: {}", root.name, display_user_path(&root.path));
            }
        }
        let confirmed = Confirm::with_theme(&theme)
            .with_prompt(format!(
                "Install Tincan in {} selected destination{}?",
                selected.len(),
                if selected.len() == 1 { "" } else { "s" }
            ))
            .default(false)
            .wait_for_newline(true)
            .interact()
            .map_err(|error| format!("cannot read skill installation confirmation: {error}"))?;
        return Ok(confirmed.then_some(selected));
    }
}

pub fn install_many(roots: &[PathBuf], force: bool) -> Result<Vec<InstallOutcome>, String> {
    let plans = roots
        .iter()
        .map(|root| install_plan(root, force))
        .collect::<Result<Vec<_>, _>>()?;
    plans.into_iter().map(apply_install_plan).collect()
}

fn install_plan(skills: &Path, force: bool) -> Result<InstallPlan, String> {
    let destination = skills.join("tincan");
    let skill_path = destination.join("SKILL.md");
    let metadata_path = destination.join("agents").join("openai.yaml");

    if skill_path.is_file()
        && metadata_path.is_file()
        && read(&skill_path)? == SKILL
        && read(&metadata_path)? == OPENAI_METADATA
    {
        return Ok(InstallPlan::Current(destination));
    }
    if destination.exists() && !force {
        return Err(format!(
            "{} already exists and differs from this Tincan version; rerun with --force to update Tincan-owned files",
            destination.display()
        ));
    }

    Ok(InstallPlan::Write(destination))
}

fn apply_install_plan(plan: InstallPlan) -> Result<InstallOutcome, String> {
    let destination = match plan {
        InstallPlan::Current(destination) => {
            return Ok(InstallOutcome::AlreadyCurrent(destination));
        }
        InstallPlan::Write(destination) => destination,
    };
    let skill_path = destination.join("SKILL.md");
    let metadata_path = destination.join("agents").join("openai.yaml");
    fs::create_dir_all(destination.join("agents")).map_err(|error| {
        format!(
            "cannot create skill directory {}: {error}",
            destination.display()
        )
    })?;
    fs::write(&skill_path, SKILL)
        .map_err(|error| format!("cannot write {}: {error}", skill_path.display()))?;
    fs::write(&metadata_path, OPENAI_METADATA)
        .map_err(|error| format!("cannot write {}: {error}", metadata_path.display()))?;
    Ok(InstallOutcome::Installed(destination))
}

enum InstallPlan {
    Current(PathBuf),
    Write(PathBuf),
}

fn detect_roots_from(home: Option<&Path>, codex_home: Option<&Path>) -> Vec<SkillRoot> {
    let mut roots = Vec::new();
    let mut seen = BTreeSet::new();

    if let Some(codex_home) = codex_home {
        add_detected_root(
            &mut roots,
            &mut seen,
            "Codex",
            codex_home,
            &codex_home.join("skills"),
        );
    }

    if let Some(home) = home {
        for (name, directory) in [
            ("Agent Skills", ".agents"),
            ("Claude Code", ".claude"),
            ("Codex", ".codex"),
            ("Cursor", ".cursor"),
            ("Gemini CLI", ".gemini"),
        ] {
            let marker = home.join(directory);
            add_detected_root(&mut roots, &mut seen, name, &marker, &marker.join("skills"));
        }
        let opencode = home.join(".config").join("opencode");
        add_detected_root(
            &mut roots,
            &mut seen,
            "OpenCode",
            &opencode,
            &opencode.join("skills"),
        );
    }

    roots
}

fn add_detected_root(
    roots: &mut Vec<SkillRoot>,
    seen: &mut BTreeSet<String>,
    name: &str,
    marker: &Path,
    skills: &Path,
) {
    if !marker.is_dir() {
        return;
    }
    let mut key = skills.to_string_lossy().replace('\\', "/");
    if cfg!(windows) {
        key.make_ascii_lowercase();
    }
    if seen.insert(key) {
        roots.push(SkillRoot {
            name: name.to_string(),
            path: skills.to_path_buf(),
        });
    }
}

fn selection_labels(roots: &[SkillRoot]) -> Vec<String> {
    roots
        .iter()
        .map(|root| {
            format!(
                "{}: {}",
                root.name,
                root.path.to_string_lossy().replace(['\n', '\r'], " ")
            )
        })
        .collect()
}

fn picker_labels(roots: &[SkillRoot]) -> Vec<String> {
    let mut labels = selection_labels(roots);
    if let Some(last) = labels.last_mut() {
        last.push_str("\n\n");
        last.push_str(PICKER_HELP);
    }
    labels
}

pub fn display_user_path(path: &Path) -> String {
    let home = nonempty_env("USERPROFILE")
        .or_else(|| nonempty_env("HOME"))
        .map(PathBuf::from);
    if let Some(relative) = home
        .as_deref()
        .and_then(|home| path.strip_prefix(home).ok())
    {
        if relative.as_os_str().is_empty() {
            return "~".to_string();
        }
        return format!("~/{}", display_path(relative));
    }
    display_path(path)
}

fn default_selections(roots: &[SkillRoot]) -> Vec<bool> {
    vec![true; roots.len()]
}

fn selected_paths(roots: &[SkillRoot], indices: &[usize]) -> Vec<PathBuf> {
    indices
        .iter()
        .filter_map(|index| roots.get(*index))
        .map(|root| root.path.clone())
        .collect()
}

fn nonempty_env(name: &str) -> Option<String> {
    std::env::var(name).ok().filter(|value| !value.is_empty())
}

fn read(path: &Path) -> Result<String, String> {
    fs::read_to_string(path).map_err(|error| format!("cannot read {}: {error}", path.display()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    #[test]
    fn installs_idempotently_and_protects_different_content() {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let root = std::env::temp_dir().join(format!("tincan-skill-install-{unique}"));

        assert!(matches!(
            install_many(std::slice::from_ref(&root), false).unwrap()[0],
            InstallOutcome::Installed(ref path) if path == &root.join("tincan")
        ));
        assert_eq!(
            fs::read_to_string(root.join("tincan").join("SKILL.md")).unwrap(),
            SKILL
        );
        assert!(matches!(
            install_many(std::slice::from_ref(&root), false).unwrap()[0],
            InstallOutcome::AlreadyCurrent(ref path) if path == &root.join("tincan")
        ));

        fs::write(root.join("tincan").join("SKILL.md"), "local edit").unwrap();
        assert!(install_many(std::slice::from_ref(&root), false).is_err());
        assert!(install_many(std::slice::from_ref(&root), true).is_ok());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn detects_only_harnesses_present_on_the_machine() {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let root = std::env::temp_dir().join(format!("tincan-skill-detect-{unique}"));
        let home = root.join("home");
        fs::create_dir_all(home.join(".claude")).unwrap();
        fs::create_dir_all(home.join(".cursor")).unwrap();

        let roots = detect_roots_from(Some(&home), None);
        assert_eq!(roots.len(), 2);
        assert!(roots.iter().any(|root| root.name == "Claude Code"));
        assert!(roots.iter().any(|root| root.name == "Cursor"));
        assert!(!roots.iter().any(|root| root.name.contains("Codex")));
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn renders_each_destination_on_one_line_and_maps_selections() {
        let roots = vec![
            SkillRoot {
                name: "First".to_string(),
                path: PathBuf::from("first/skills"),
            },
            SkillRoot {
                name: "Second".to_string(),
                path: PathBuf::from("second/skills"),
            },
        ];
        let labels = selection_labels(&roots);
        assert_eq!(labels.len(), 2);
        assert!(labels[0].contains("First: first/skills"));
        assert!(labels.iter().all(|label| !label.contains('\n')));
        let selected = selected_paths(&roots, &[1]);
        assert_eq!(selected, vec![PathBuf::from("second/skills")]);
    }

    #[test]
    fn selects_every_detected_destination_by_default() {
        let roots = vec![SkillRoot {
            name: "Only harness".to_string(),
            path: PathBuf::from("only/skills"),
        }];
        assert_eq!(default_selections(&roots), vec![true]);
    }

    #[test]
    fn picker_help_explains_every_available_action() {
        for instruction in [
            "↑↓ move",
            "Space select/unselect",
            "A toggle all/none",
            "Enter continue",
            "Esc cancel",
        ] {
            assert!(PICKER_HELP.contains(instruction));
        }
        let roots = vec![SkillRoot {
            name: "Only harness".to_string(),
            path: PathBuf::from("only/skills"),
        }];
        let labels = picker_labels(&roots);
        assert!(labels[0].ends_with(PICKER_HELP));
        assert_eq!(labels[0].matches(PICKER_HELP).count(), 1);
    }

    #[test]
    fn bundled_skill_offers_initialization_without_assuming_consent() {
        assert!(SKILL.contains("user-question tool"));
        assert!(SKILL.contains("user-question"));
        assert!(SKILL.contains("Initialize Tincan"));
        assert!(SKILL.contains("Not now"));
        assert!(SKILL.contains("Never run"));
        assert!(SKILL.contains("without the user's explicit confirmation"));
    }

    #[test]
    fn validates_every_destination_before_writing_any() {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let root = std::env::temp_dir().join(format!("tincan-skill-atomic-{unique}"));
        let first = root.join("first");
        let second = root.join("second");
        fs::create_dir_all(second.join("tincan")).unwrap();
        fs::write(second.join("tincan").join("SKILL.md"), "owned elsewhere").unwrap();

        assert!(install_many(&[first.clone(), second], false).is_err());
        assert!(!first.join("tincan").exists());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn detects_outdated_installed_skills_without_treating_missing_skills_as_updates() {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let root = std::env::temp_dir().join(format!("tincan-skill-update-{unique}"));
        let installed = root.join("installed");
        let missing = root.join("missing");
        fs::create_dir_all(installed.join("tincan")).unwrap();
        fs::write(installed.join("tincan").join("SKILL.md"), "older skill").unwrap();
        let roots = vec![
            SkillRoot {
                name: "Installed".to_string(),
                path: installed,
            },
            SkillRoot {
                name: "Missing".to_string(),
                path: missing,
            },
        ];

        let outdated = outdated_roots(&roots);
        assert_eq!(outdated.len(), 1);
        assert_eq!(outdated[0].name, "Installed");
        fs::remove_dir_all(root).unwrap();
    }
}