1use std::fs;
15use std::io;
16use std::path::{Path, PathBuf};
17
18use clap::Parser;
19use dialoguer::{theme::ColorfulTheme, Confirm};
20use serde::Serialize;
21use serde_json::json;
22
23use super::{CmdError, CmdResult, Ctx};
24use crate::envelope::Envelope;
25
26const SKILL_NAME: &str = "taskfast-agent";
27const SOURCE_KIND: &str = "embedded";
28const DEST_ROOTS: &[&str] = &[".claude/skills", ".agents/skills"];
29
30macro_rules! bundled_file {
31 ($path:literal) => {
32 BundledFile {
33 relative_path: $path,
34 contents: include_str!(concat!(
35 env!("CARGO_MANIFEST_DIR"),
36 "/skills/taskfast-agent/",
37 $path
38 )),
39 }
40 };
41}
42
43#[derive(Debug, Parser)]
44pub struct Args {
46 #[arg(long)]
48 pub yes: bool,
49}
50
51#[derive(Debug, Clone, Copy)]
52struct BundledFile {
53 relative_path: &'static str,
54 contents: &'static str,
55}
56
57const BUNDLED_FILES: &[BundledFile] = &[
58 bundled_file!("SKILL.md"),
59 bundled_file!("reference/BOOT.md"),
60 bundled_file!("reference/POSTER.md"),
61 bundled_file!("reference/SETUP.md"),
62 bundled_file!("reference/STATES.md"),
63 bundled_file!("reference/TROUBLESHOOTING.md"),
64 bundled_file!("reference/WORKER.md"),
65];
66
67#[derive(Debug, Serialize)]
68struct InstallTarget {
69 path: PathBuf,
70 status: &'static str,
71}
72
73trait ConfirmPrompter {
74 fn confirm_install(&self, skill_name: &str, destinations: &[PathBuf]) -> io::Result<bool>;
75}
76
77struct DialoguerConfirmPrompter;
78
79impl ConfirmPrompter for DialoguerConfirmPrompter {
80 fn confirm_install(&self, skill_name: &str, destinations: &[PathBuf]) -> io::Result<bool> {
81 eprintln!("Install bundled skill `{skill_name}` into:");
82 for destination in destinations {
83 eprintln!(" - {}", destination.display());
84 }
85
86 Confirm::with_theme(&ColorfulTheme::default())
87 .with_prompt("Proceed")
88 .default(true)
89 .interact()
90 .map_err(dialoguer_err)
91 }
92}
93
94fn dialoguer_err(error: dialoguer::Error) -> io::Error {
95 match error {
96 dialoguer::Error::IO(io) => io,
97 }
98}
99
100#[allow(clippy::unused_async)]
101pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
108 let cwd = std::env::current_dir().map_err(|error| {
109 CmdError::Usage(format!("failed to resolve current directory: {error}"))
110 })?;
111 let interactive = !args.yes && crate::cmd::init_tui::is_interactive();
112 run_with_prompter(ctx, args, &DialoguerConfirmPrompter, interactive, &cwd)
113}
114
115fn run_with_prompter<P: ConfirmPrompter>(
116 ctx: &Ctx,
117 args: Args,
118 prompter: &P,
119 interactive: bool,
120 cwd: &Path,
121) -> CmdResult {
122 let destinations = destination_paths(cwd);
123 if ctx.dry_run {
124 return Ok(status_envelope(
125 ctx,
126 cwd,
127 "dry_run",
128 "no",
129 "would_install",
130 &destinations,
131 ));
132 }
133
134 let (prompted, approval) = if args.yes {
135 ("no", "yes_flag")
136 } else if interactive {
137 let approved = prompter
138 .confirm_install(SKILL_NAME, &destinations)
139 .map_err(|error| CmdError::Usage(format!("install confirmation failed: {error}")))?;
140 if !approved {
141 return Ok(status_envelope(
142 ctx,
143 cwd,
144 "declined",
145 "yes",
146 "skipped",
147 &destinations,
148 ));
149 }
150 ("yes", "prompt")
151 } else {
152 return Err(CmdError::Usage(
153 "refusing to install bundled skills without confirmation: rerun with --yes or use an interactive TTY".into(),
154 ));
155 };
156
157 for destination in &destinations {
158 install_into(destination)?;
159 }
160
161 Ok(Envelope::success(
162 ctx.environment,
163 ctx.dry_run,
164 status_data(cwd, approval, prompted, "installed", &destinations),
165 ))
166}
167
168fn status_envelope(
169 ctx: &Ctx,
170 cwd: &Path,
171 approval: &'static str,
172 prompted: &'static str,
173 status: &'static str,
174 destinations: &[PathBuf],
175) -> Envelope {
176 Envelope::success(
177 ctx.environment,
178 ctx.dry_run,
179 status_data(cwd, approval, prompted, status, destinations),
180 )
181}
182
183fn status_data(
184 cwd: &Path,
185 approval: &'static str,
186 prompted: &'static str,
187 status: &'static str,
188 destinations: &[PathBuf],
189) -> serde_json::Value {
190 json!({
191 "skill": SKILL_NAME,
192 "source": SOURCE_KIND,
193 "cwd": cwd.display().to_string(),
194 "approval": approval,
195 "prompted": prompted,
196 "targets": targets_with_status(destinations, status),
197 })
198}
199
200fn destination_paths(cwd: &Path) -> Vec<PathBuf> {
201 DEST_ROOTS
202 .iter()
203 .map(|root| cwd.join(root).join(SKILL_NAME))
204 .collect()
205}
206
207fn targets_with_status(paths: &[PathBuf], status: &'static str) -> Vec<InstallTarget> {
208 paths
209 .iter()
210 .map(|path| InstallTarget {
211 path: path.clone(),
212 status,
213 })
214 .collect()
215}
216
217fn install_into(destination: &Path) -> Result<(), CmdError> {
218 fs::create_dir_all(destination)
219 .map_err(|error| io_error("create install directory", destination, error))?;
220
221 for file in BUNDLED_FILES {
222 let path = destination.join(file.relative_path);
223 if let Some(parent) = path.parent() {
224 fs::create_dir_all(parent)
225 .map_err(|error| io_error("create install directory", parent, error))?;
226 }
227 fs::write(&path, file.contents)
228 .map_err(|error| io_error("write bundled skill file", &path, error))?;
229 }
230 Ok(())
231}
232
233fn io_error(action: &str, path: &Path, error: io::Error) -> CmdError {
234 CmdError::Usage(format!("{action} `{}`: {error}", path.display()))
235}
236#[cfg(test)]
237mod tests {
238 use super::*;
239 use crate::Environment;
240 use std::cell::Cell;
241 use tempfile::TempDir;
242
243 struct MockPrompter {
244 answer: bool,
245 calls: Cell<usize>,
246 }
247
248 impl MockPrompter {
249 fn approving() -> Self {
250 Self {
251 answer: true,
252 calls: Cell::new(0),
253 }
254 }
255
256 fn declining() -> Self {
257 Self {
258 answer: false,
259 calls: Cell::new(0),
260 }
261 }
262 }
263
264 impl ConfirmPrompter for MockPrompter {
265 fn confirm_install(
266 &self,
267 _skill_name: &str,
268 _destinations: &[PathBuf],
269 ) -> io::Result<bool> {
270 self.calls.set(self.calls.get() + 1);
271 Ok(self.answer)
272 }
273 }
274
275 fn ctx(dry_run: bool) -> Ctx {
276 Ctx {
277 environment: Environment::Local,
278 config_path: PathBuf::from("/dev/null"),
279 dry_run,
280 quiet: true,
281 ..Default::default()
282 }
283 }
284
285 fn args(yes: bool) -> Args {
286 Args { yes }
287 }
288
289 fn target_path(tmp: &TempDir, root: &str) -> PathBuf {
290 tmp.path().join(root).join(SKILL_NAME)
291 }
292
293 fn skill_file(root: &Path, relative_path: &str) -> PathBuf {
294 root.join(relative_path)
295 }
296
297 fn envelope_value(envelope: &Envelope) -> serde_json::Value {
298 serde_json::to_value(envelope).expect("serialize envelope")
299 }
300
301 #[test]
302 fn run_with_prompter_should_fail_closed_when_non_interactive_and_unapproved() {
303 let tmp = TempDir::new().expect("tempdir");
304 let prompter = MockPrompter::approving();
305
306 let error = run_with_prompter(&ctx(false), args(false), &prompter, false, tmp.path())
307 .expect_err("non-interactive install without --yes must fail");
308
309 match error {
310 CmdError::Usage(message) => assert!(message.contains("--yes"), "{message}"),
311 other => panic!("expected usage error, got {other:?}"),
312 }
313 assert_eq!(prompter.calls.get(), 0);
314 }
315
316 #[test]
317 fn run_with_prompter_should_report_dry_run_without_prompting_or_writing() {
318 let tmp = TempDir::new().expect("tempdir");
319 let prompter = MockPrompter::approving();
320
321 let envelope = run_with_prompter(&ctx(true), args(false), &prompter, true, tmp.path())
322 .expect("dry run");
323
324 let value = envelope_value(&envelope);
325 assert_eq!(value["dry_run"], true);
326 assert_eq!(value["data"]["approval"], "dry_run");
327 assert_eq!(value["data"]["targets"][0]["status"], "would_install");
328 assert_eq!(prompter.calls.get(), 0);
329 assert!(!target_path(&tmp, ".claude/skills").exists());
330 assert!(!target_path(&tmp, ".agents/skills").exists());
331 }
332
333 #[test]
334 fn run_with_prompter_should_skip_install_when_prompt_is_declined() {
335 let tmp = TempDir::new().expect("tempdir");
336 let prompter = MockPrompter::declining();
337
338 let envelope = run_with_prompter(&ctx(false), args(false), &prompter, true, tmp.path())
339 .expect("cancelled");
340
341 let value = envelope_value(&envelope);
342 assert_eq!(value["ok"], true);
343 assert_eq!(value["data"]["approval"], "declined");
344 assert_eq!(value["data"]["targets"][1]["status"], "skipped");
345 assert_eq!(prompter.calls.get(), 1);
346 assert!(!target_path(&tmp, ".claude/skills").exists());
347 assert!(!target_path(&tmp, ".agents/skills").exists());
348 }
349
350 #[test]
351 fn run_with_prompter_should_install_bundled_files_into_both_skill_roots() {
352 let tmp = TempDir::new().expect("tempdir");
353 let prompter = MockPrompter::approving();
354
355 let envelope = run_with_prompter(&ctx(false), args(true), &prompter, false, tmp.path())
356 .expect("install");
357
358 let value = envelope_value(&envelope);
359 assert_eq!(value["data"]["approval"], "yes_flag");
360 assert_eq!(value["data"]["targets"][0]["status"], "installed");
361 assert_eq!(prompter.calls.get(), 0);
362
363 for root in [".claude/skills", ".agents/skills"] {
364 let skill_root = target_path(&tmp, root);
365 for bundled in BUNDLED_FILES {
366 let installed = fs::read_to_string(skill_file(&skill_root, bundled.relative_path))
367 .expect("installed bundled file");
368 assert_eq!(installed, bundled.contents);
369 }
370 }
371 }
372
373 #[test]
374 fn bundled_files_should_match_skill_tree_on_disk() {
375 let skill_root =
376 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../skills/taskfast-agent");
377
378 let mut on_disk: Vec<String> = Vec::new();
379 if skill_root.join("SKILL.md").is_file() {
380 on_disk.push("SKILL.md".into());
381 }
382 let reference_dir = skill_root.join("reference");
383 for entry in fs::read_dir(&reference_dir).expect("read skill reference dir") {
384 let entry = entry.expect("skill reference dir entry");
385 let path = entry.path();
386 if path.extension().and_then(|s| s.to_str()) == Some("md") {
387 let name = path
388 .file_name()
389 .and_then(|s| s.to_str())
390 .expect("reference filename")
391 .to_string();
392 on_disk.push(format!("reference/{name}"));
393 }
394 }
395 on_disk.sort();
396
397 let mut bundled: Vec<String> = BUNDLED_FILES
398 .iter()
399 .map(|file| file.relative_path.to_string())
400 .collect();
401 bundled.sort();
402
403 assert_eq!(
404 bundled, on_disk,
405 "BUNDLED_FILES drifted from skills/taskfast-agent/ on disk — update \
406 BUNDLED_FILES in crates/taskfast-cli/src/cmd/skills.rs to match"
407 );
408 }
409
410 #[test]
411 fn run_with_prompter_should_overwrite_bundled_files_and_preserve_unrelated_files() {
412 let tmp = TempDir::new().expect("tempdir");
413 let skill_root = target_path(&tmp, ".claude/skills");
414 let bundled_skill = skill_root.join("SKILL.md");
415 let local_note = skill_root.join("local-note.md");
416 let sibling = tmp.path().join(".claude/skills/other-skill/SKILL.md");
417
418 fs::create_dir_all(skill_root.join("reference")).expect("skill dir");
419 fs::create_dir_all(sibling.parent().expect("sibling parent")).expect("sibling dir");
420 fs::write(&bundled_skill, "stale").expect("seed bundled file");
421 fs::write(&local_note, "keep").expect("seed local file");
422 fs::write(&sibling, "other").expect("seed sibling file");
423
424 run_with_prompter(
425 &ctx(false),
426 args(true),
427 &MockPrompter::approving(),
428 false,
429 tmp.path(),
430 )
431 .expect("install");
432
433 assert_eq!(
434 fs::read_to_string(&bundled_skill).expect("updated bundled file"),
435 BUNDLED_FILES[0].contents
436 );
437 assert_eq!(fs::read_to_string(&local_note).expect("local note"), "keep");
438 assert_eq!(
439 fs::read_to_string(&sibling).expect("sibling skill"),
440 "other"
441 );
442 }
443}