Skip to main content

blyte_cli/
skill.rs

1use std::path::{Path, PathBuf};
2use std::process::Command;
3
4pub const SKILL_MD: &str = include_str!("../assets/blyte-implementer/SKILL.md");
5
6pub const DEFAULT_BLOCK: &str = "\
7<!-- blyte:default -->
8## Implementation: delegate to blyte, in parallel
9
10For code changes in a git repository that has a check command (tests, lint), plan and review
11the work yourself and delegate the implementation to blyte with the `blyte-implementer` skill.
12Split the work into independent tasks and dispatch them in parallel (`blyte dispatch`, one
13worktree each); run tasks one after another only when one depends on another. Keep for
14yourself: design decisions, ambiguous requirements, one-line edits, and anything with no check.
15<!-- /blyte:default -->";
16
17pub const CONTEXT_BLOCK: &str = "\
18<!-- blyte:context -->
19## Context: keep this session small
20
21Everything a tool returns stays in the conversation and is re-read on every turn, so it is most of
22what a session costs.
23- Trim command output at the source: `| tail -n 20`, `grep` for the lines you need, `sed -n`
24  ranges, `--quiet`/`-q`; `git diff --stat` before any full diff.
25- Read files by range (offset and limit), not whole, once you know where to look.
26- For a dispatched run, read `blyte review <id>` and the JSON fields you need
27  (`jq -r .outcome .wt/<id>.json`), not the whole summary or log; search `.wt/<id>.log` with
28  `grep`/`tail` only for what `== checks` flags.
29- Write tasks as `### Task <ID>` sections of the plan and dispatch with `--plan`/`--plan-task`;
30  do not write task files that copy the plan.
31- An investigation needing more than about five file reads goes to `blyte dispatch --research`;
32  read its report, not the files.
33- One session per piece of work. When the status line shows the context past about 60% of its
34  window, tell the user to `/compact` or start a new session before going on.
35<!-- /blyte:context -->";
36
37pub const CODEX_RULES: &str = "\
38# Written by `blyte skill install --harness codex`; removed by `blyte skill uninstall --harness codex`.
39# blyte dispatch needs the network and applies its own sandbox, so it runs outside Codex's.
40prefix_rule(pattern=[\"blyte\", \"dispatch\"], decision=\"allow\")
41prefix_rule(pattern=[\"blyte\", \"review\"], decision=\"allow\")
42";
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum Harness {
46    Claude,
47    Codex,
48}
49
50impl Harness {
51    pub fn parse_all(s: &str) -> Result<Vec<Self>, String> {
52        match s {
53            "claude" => Ok(vec![Harness::Claude]),
54            "codex" => Ok(vec![Harness::Codex]),
55            "all" => Ok(vec![Harness::Claude, Harness::Codex]),
56            other => Err(format!("unknown harness: {other}")),
57        }
58    }
59}
60
61fn repo_root() -> Result<PathBuf, String> {
62    let out = Command::new("git")
63        .args(["rev-parse", "--show-toplevel"])
64        .output()
65        .map_err(|e| format!("failed to execute git: {e}"))?;
66    if !out.status.success() {
67        return Err(format!(
68            "not a git repository: {}",
69            String::from_utf8_lossy(&out.stderr).trim()
70        ));
71    }
72    Ok(PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()))
73}
74
75pub fn home_dir() -> Result<PathBuf, String> {
76    let home = std::env::var("HOME")
77        .map_err(|_| "HOME environment variable is unset or empty".to_string())?;
78    if home.trim().is_empty() {
79        return Err("HOME environment variable is unset or empty".to_string());
80    }
81    Ok(PathBuf::from(home))
82}
83
84pub fn skill_dir(project: bool) -> Result<PathBuf, String> {
85    if project {
86        Ok(repo_root()?.join(".claude/skills/blyte-implementer"))
87    } else {
88        Ok(home_dir()?.join(".claude/skills/blyte-implementer"))
89    }
90}
91
92pub fn claude_md_path(project: bool) -> Result<PathBuf, String> {
93    if project {
94        Ok(repo_root()?.join("CLAUDE.md"))
95    } else {
96        Ok(home_dir()?.join(".claude/CLAUDE.md"))
97    }
98}
99
100pub fn skill_dirs(harness: Harness, project: bool) -> Result<Vec<PathBuf>, String> {
101    match harness {
102        Harness::Claude => Ok(vec![skill_dir(project)?]),
103        Harness::Codex => {
104            if project {
105                Ok(vec![repo_root()?.join(".agents/skills/blyte-implementer")])
106            } else {
107                let home = home_dir()?;
108                Ok(vec![
109                    home.join(".agents/skills/blyte-implementer"),
110                    home.join(".codex/skills/blyte-implementer"),
111                ])
112            }
113        }
114    }
115}
116
117pub fn instructions_path(harness: Harness, project: bool) -> Result<PathBuf, String> {
118    match harness {
119        Harness::Claude => claude_md_path(project),
120        Harness::Codex => {
121            if project {
122                Ok(repo_root()?.join("AGENTS.md"))
123            } else {
124                Ok(home_dir()?.join(".codex/AGENTS.md"))
125            }
126        }
127    }
128}
129
130pub fn codex_rules_path() -> Result<PathBuf, String> {
131    Ok(home_dir()?.join(".codex/rules/blyte.rules"))
132}
133
134pub fn set_block(text: &str, block: &str) -> String {
135    let start_marker = block.lines().next().unwrap_or("");
136    let end_marker = block.lines().last().unwrap_or("");
137
138    if !start_marker.is_empty() && !end_marker.is_empty() {
139        if let Some(start) = text.find(start_marker) {
140            if let Some(end_rel) = text[start..].find(end_marker) {
141                let end = start + end_rel + end_marker.len();
142                let mut result = format!("{}{block}{}", &text[..start], &text[end..]);
143                while result.ends_with("\n\n") {
144                    result.pop();
145                }
146                if !result.ends_with('\n') {
147                    result.push('\n');
148                }
149                return result;
150            }
151        }
152    }
153
154    if text.is_empty() {
155        format!("{block}\n")
156    } else if text.ends_with('\n') {
157        format!("{text}\n{block}\n")
158    } else {
159        format!("{text}\n\n{block}\n")
160    }
161}
162
163pub fn remove_block(text: &str, block: &str) -> String {
164    let start_marker = block.lines().next().unwrap_or("");
165    let end_marker = block.lines().last().unwrap_or("");
166
167    if start_marker.is_empty() || end_marker.is_empty() {
168        return text.to_string();
169    }
170
171    let Some(start) = text.find(start_marker) else {
172        return text.to_string();
173    };
174    let Some(end_rel) = text[start..].find(end_marker) else {
175        return text.to_string();
176    };
177    let end = start + end_rel + end_marker.len();
178
179    let prefix = &text[..start];
180    let prefix_clean = if prefix.ends_with("\n\n") {
181        &prefix[..prefix.len() - 1]
182    } else if prefix == "\n" {
183        ""
184    } else {
185        prefix
186    };
187
188    let suffix = if text[end..].starts_with('\n') {
189        &text[end + 1..]
190    } else {
191        &text[end..]
192    };
193
194    format!("{prefix_clean}{suffix}")
195}
196
197pub fn set_default_block(text: &str) -> String {
198    set_block(text, DEFAULT_BLOCK)
199}
200
201pub fn remove_default_block(text: &str) -> String {
202    remove_block(text, DEFAULT_BLOCK)
203}
204
205pub fn ensure_context_block(home: &Path) -> Result<Option<PathBuf>, String> {
206    let claude_dir = home.join(".claude");
207    if !claude_dir.exists() {
208        return Ok(None);
209    }
210    let claude_md = claude_dir.join("CLAUDE.md");
211    let existing = if claude_md.exists() {
212        std::fs::read_to_string(&claude_md)
213            .map_err(|e| format!("failed to read {}: {e}", claude_md.display()))?
214    } else {
215        String::new()
216    };
217    let updated = set_block(&existing, CONTEXT_BLOCK);
218    if updated != existing {
219        std::fs::write(&claude_md, updated)
220            .map_err(|e| format!("failed to write {}: {e}", claude_md.display()))?;
221        Ok(Some(claude_md))
222    } else {
223        Ok(None)
224    }
225}
226
227pub const STATUS_LINE_REFRESH_SECS: u64 = 30;
228pub const AUTO_COMPACT_WINDOW: u64 = 200_000;
229
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub enum AutoCompact {
232    Kept { key: String, value: String },
233    Set(String),
234}
235
236fn json_value_display(v: &serde_json::Value) -> String {
237    match v.as_str() {
238        Some(s) => s.to_string(),
239        None => v.to_string(),
240    }
241}
242
243pub fn set_auto_compact_window(settings: &str) -> Result<AutoCompact, String> {
244    let mut val: serde_json::Value = if settings.trim().is_empty() {
245        serde_json::Value::Object(serde_json::Map::new())
246    } else {
247        serde_json::from_str(settings).map_err(|e| e.to_string())?
248    };
249
250    let Some(obj) = val.as_object_mut() else {
251        return Err("settings must be a JSON object".to_string());
252    };
253
254    if let Some(v) = obj.get("autoCompactWindow").filter(|v| !v.is_null()) {
255        return Ok(AutoCompact::Kept {
256            key: "autoCompactWindow".to_string(),
257            value: json_value_display(v),
258        });
259    }
260
261    if let Some(models) = obj.get("modelSettings").and_then(|v| v.as_object()) {
262        for (model, model_obj) in models {
263            if let Some(v) = model_obj
264                .as_object()
265                .and_then(|m| m.get("autoCompactWindow"))
266                .filter(|v| !v.is_null())
267            {
268                return Ok(AutoCompact::Kept {
269                    key: format!("modelSettings.{model}.autoCompactWindow"),
270                    value: json_value_display(v),
271                });
272            }
273        }
274    }
275
276    if let Some(v) = obj
277        .get("env")
278        .and_then(|e| e.as_object())
279        .and_then(|e| e.get("CLAUDE_CODE_AUTO_COMPACT_WINDOW"))
280        .filter(|v| !v.is_null())
281    {
282        return Ok(AutoCompact::Kept {
283            key: "env.CLAUDE_CODE_AUTO_COMPACT_WINDOW".to_string(),
284            value: json_value_display(v),
285        });
286    }
287
288    obj.insert(
289        "autoCompactWindow".to_string(),
290        serde_json::json!(AUTO_COMPACT_WINDOW),
291    );
292    let mut out = serde_json::to_string_pretty(&val).map_err(|e| e.to_string())?;
293    out.push('\n');
294    Ok(AutoCompact::Set(out))
295}
296
297pub fn remove_auto_compact_window(settings: &str) -> Result<Option<String>, String> {
298    let mut val: serde_json::Value = if settings.trim().is_empty() {
299        serde_json::Value::Object(serde_json::Map::new())
300    } else {
301        serde_json::from_str(settings).map_err(|e| e.to_string())?
302    };
303
304    let Some(obj) = val.as_object_mut() else {
305        return Err("settings must be a JSON object".to_string());
306    };
307
308    if obj.get("autoCompactWindow").and_then(|v| v.as_u64()) != Some(AUTO_COMPACT_WINDOW) {
309        return Ok(None);
310    }
311
312    obj.remove("autoCompactWindow");
313    let mut out = serde_json::to_string_pretty(&val).map_err(|e| e.to_string())?;
314    out.push('\n');
315    Ok(Some(out))
316}
317
318fn autocompact_marker_path() -> Result<PathBuf, String> {
319    let dir = crate::registry::state_dir().ok_or_else(|| {
320        "cannot determine state directory: none of BLYTE_STATE_DIR, XDG_STATE_HOME, or HOME is set"
321            .to_string()
322    })?;
323    Ok(dir.join("autocompact-window"))
324}
325
326pub fn set_status_line(settings: &str) -> Result<Option<String>, String> {
327    let mut val: serde_json::Value = if settings.trim().is_empty() {
328        serde_json::Value::Object(serde_json::Map::new())
329    } else {
330        serde_json::from_str(settings).map_err(|e| e.to_string())?
331    };
332
333    let Some(obj) = val.as_object_mut() else {
334        return Err("settings must be a JSON object".to_string());
335    };
336
337    if let Some(sl) = obj.get_mut("statusLine").and_then(|v| v.as_object_mut()) {
338        let cmd = sl.get("command").and_then(|c| c.as_str());
339        if let Some(cmd_str) = cmd {
340            if cmd_str.starts_with("blyte statusline") {
341                if sl.get("refreshInterval").is_some_and(|v| !v.is_null()) {
342                    return Ok(None);
343                }
344                sl.insert(
345                    "refreshInterval".to_string(),
346                    serde_json::json!(STATUS_LINE_REFRESH_SECS),
347                );
348                let mut out = serde_json::to_string_pretty(&val).map_err(|e| e.to_string())?;
349                out.push('\n');
350                return Ok(Some(out));
351            }
352        }
353
354        let command_str = match cmd {
355            Some(old) => format!("blyte statusline --after '{}'", old.replace('\'', r"'\''")),
356            None => "blyte statusline".to_string(),
357        };
358
359        sl.insert(
360            "type".to_string(),
361            serde_json::Value::String("command".to_string()),
362        );
363        sl.insert(
364            "command".to_string(),
365            serde_json::Value::String(command_str),
366        );
367        if sl
368            .get("refreshInterval")
369            .is_none_or(serde_json::Value::is_null)
370        {
371            sl.insert(
372                "refreshInterval".to_string(),
373                serde_json::json!(STATUS_LINE_REFRESH_SECS),
374            );
375        }
376    } else {
377        let mut sl_map = serde_json::Map::new();
378        sl_map.insert(
379            "type".to_string(),
380            serde_json::Value::String("command".to_string()),
381        );
382        sl_map.insert(
383            "command".to_string(),
384            serde_json::Value::String("blyte statusline".to_string()),
385        );
386        sl_map.insert(
387            "refreshInterval".to_string(),
388            serde_json::json!(STATUS_LINE_REFRESH_SECS),
389        );
390        obj.insert("statusLine".to_string(), serde_json::Value::Object(sl_map));
391    }
392
393    let mut out = serde_json::to_string_pretty(&val).map_err(|e| e.to_string())?;
394    out.push('\n');
395    Ok(Some(out))
396}
397
398pub fn remove_status_line(settings: &str) -> Result<Option<String>, String> {
399    let mut val: serde_json::Value = if settings.trim().is_empty() {
400        serde_json::Value::Object(serde_json::Map::new())
401    } else {
402        serde_json::from_str(settings).map_err(|e| e.to_string())?
403    };
404
405    let Some(obj) = val.as_object_mut() else {
406        return Err("settings must be a JSON object".to_string());
407    };
408
409    let Some(sl) = obj.get("statusLine") else {
410        return Ok(None);
411    };
412
413    let Some(cmd) = sl.get("command").and_then(|c| c.as_str()) else {
414        return Ok(None);
415    };
416
417    const PREFIX: &str = "blyte statusline --after '";
418    if cmd == "blyte statusline" {
419        obj.remove("statusLine");
420    } else if let Some(rest) = cmd.strip_prefix(PREFIX) {
421        if let Some(inside) = rest.strip_suffix('\'') {
422            let old = inside.replace(r"'\''", "'");
423            if let Some(sl_obj) = obj.get_mut("statusLine").and_then(|v| v.as_object_mut()) {
424                sl_obj.insert("command".to_string(), serde_json::Value::String(old));
425                if sl_obj.get("refreshInterval").and_then(|v| v.as_u64())
426                    == Some(STATUS_LINE_REFRESH_SECS)
427                {
428                    sl_obj.remove("refreshInterval");
429                }
430            } else {
431                return Ok(None);
432            }
433        } else {
434            return Ok(None);
435        }
436    } else {
437        return Ok(None);
438    }
439
440    let mut out = serde_json::to_string_pretty(&val).map_err(|e| e.to_string())?;
441    out.push('\n');
442    Ok(Some(out))
443}
444
445pub fn install_for(
446    harness: Harness,
447    project: bool,
448    force: bool,
449    no_default: bool,
450    no_statusline: bool,
451    no_autocompact: bool,
452) -> Result<Vec<PathBuf>, String> {
453    let claude_context_written = if harness == Harness::Claude && !project {
454        let home = home_dir()?;
455        ensure_context_block(&home)?
456    } else {
457        None
458    };
459
460    let dirs = skill_dirs(harness, project)?;
461    let skill_paths: Vec<PathBuf> = dirs.iter().map(|d| d.join("SKILL.md")).collect();
462
463    for skill_path in &skill_paths {
464        if skill_path.exists() {
465            let existing = std::fs::read_to_string(skill_path)
466                .map_err(|e| format!("failed to read {}: {e}", skill_path.display()))?;
467            if existing != SKILL_MD && !force {
468                return Err(format!(
469                    "{} already exists with different content; pass --force to overwrite",
470                    skill_path.display()
471                ));
472            }
473        }
474    }
475
476    let mut written = Vec::new();
477    for (dir, skill_path) in dirs.into_iter().zip(skill_paths) {
478        std::fs::create_dir_all(&dir)
479            .map_err(|e| format!("failed to create directory {}: {e}", dir.display()))?;
480        std::fs::write(&skill_path, SKILL_MD)
481            .map_err(|e| format!("failed to write {}: {e}", skill_path.display()))?;
482        let marker = dir.join(".blyte-installed");
483        std::fs::write(&marker, SKILL_MD)
484            .map_err(|e| format!("failed to write {}: {e}", marker.display()))?;
485        written.push(skill_path);
486    }
487
488    let md_path = instructions_path(harness, project)?;
489    if !no_default {
490        if let Some(parent) = md_path.parent() {
491            std::fs::create_dir_all(parent)
492                .map_err(|e| format!("failed to create directory {}: {e}", parent.display()))?;
493        }
494        let existing = if md_path.exists() {
495            std::fs::read_to_string(&md_path)
496                .map_err(|e| format!("failed to read {}: {e}", md_path.display()))?
497        } else {
498            String::new()
499        };
500        let updated = set_default_block(&existing);
501        std::fs::write(&md_path, updated)
502            .map_err(|e| format!("failed to write {}: {e}", md_path.display()))?;
503        if !written.contains(&md_path) {
504            written.push(md_path);
505        }
506    } else if md_path.exists() {
507        // Switching to "only when asked" drops the default block an earlier install wrote, so it
508        // does not need an uninstall first (2026-09-30).
509        let existing = std::fs::read_to_string(&md_path)
510            .map_err(|e| format!("failed to read {}: {e}", md_path.display()))?;
511        let updated = remove_default_block(&existing);
512        if updated != existing {
513            std::fs::write(&md_path, updated)
514                .map_err(|e| format!("failed to write {}: {e}", md_path.display()))?;
515            if !written.contains(&md_path) {
516                written.push(md_path);
517            }
518        }
519    }
520
521    if let Some(path) = claude_context_written {
522        if !written.contains(&path) {
523            written.push(path);
524        }
525    }
526
527    if harness == Harness::Codex && !project {
528        let rules_path = codex_rules_path()?;
529        if let Some(parent) = rules_path.parent() {
530            std::fs::create_dir_all(parent)
531                .map_err(|e| format!("failed to create directory {}: {e}", parent.display()))?;
532        }
533        std::fs::write(&rules_path, CODEX_RULES)
534            .map_err(|e| format!("failed to write {}: {e}", rules_path.display()))?;
535        written.push(rules_path);
536    }
537
538    if harness == Harness::Claude && !project && (!no_statusline || !no_autocompact) {
539        let home = home_dir()?;
540        let claude_dir = home.join(".claude");
541        let settings_path = claude_dir.join("settings.json");
542        let backup_path = claude_dir.join("settings.json.blyte-backup");
543
544        let existing = if settings_path.exists() {
545            std::fs::read_to_string(&settings_path)
546                .map_err(|e| format!("failed to read {}: {e}", settings_path.display()))?
547        } else {
548            String::new()
549        };
550
551        let mut current = existing;
552        let mut settings_changed = false;
553        let mut statusline_msg: Option<&'static str> = None;
554
555        if !no_statusline {
556            let updated = set_status_line(&current)
557                .map_err(|e| format!("failed to update {}: {e}", settings_path.display()))?;
558            if let Some(updated) = updated {
559                if updated.contains("blyte statusline --after") {
560                    statusline_msg = Some("status line: wrapped your status line command");
561                } else {
562                    statusline_msg = Some("status line: set to blyte statusline");
563                }
564                current = updated;
565                settings_changed = true;
566            }
567        }
568
569        let mut autocompact_action: Option<(AutoCompact, PathBuf)> = None;
570        if !no_autocompact {
571            let marker = autocompact_marker_path()?;
572            if !marker.exists() {
573                let res = set_auto_compact_window(&current)
574                    .map_err(|e| format!("failed to update {}: {e}", settings_path.display()))?;
575                if let AutoCompact::Set(ref updated) = res {
576                    current = updated.clone();
577                    settings_changed = true;
578                }
579                autocompact_action = Some((res, marker));
580            }
581        }
582
583        if settings_changed {
584            if settings_path.exists() && !backup_path.exists() {
585                std::fs::copy(&settings_path, &backup_path).map_err(|e| {
586                    format!("failed to create backup {}: {e}", backup_path.display())
587                })?;
588            }
589            if let Some(parent) = settings_path.parent() {
590                std::fs::create_dir_all(parent)
591                    .map_err(|e| format!("failed to create directory {}: {e}", parent.display()))?;
592            }
593            std::fs::write(&settings_path, &current)
594                .map_err(|e| format!("failed to write {}: {e}", settings_path.display()))?;
595        }
596
597        if let Some(msg) = statusline_msg {
598            println!("{msg}");
599        }
600
601        if let Some((action, marker)) = autocompact_action {
602            match action {
603                AutoCompact::Set(_) => {
604                    if let Some(parent) = marker.parent() {
605                        std::fs::create_dir_all(parent).map_err(|e| {
606                            format!(
607                                "failed to write {}: {e} (autoCompactWindow was set in {}, but uninstall will not remove it)",
608                                marker.display(),
609                                settings_path.display()
610                            )
611                        })?;
612                    }
613                    std::fs::write(&marker, AUTO_COMPACT_WINDOW.to_string()).map_err(|e| {
614                        format!(
615                            "failed to write {}: {e} (autoCompactWindow was set in {}, but uninstall will not remove it)",
616                            marker.display(),
617                            settings_path.display()
618                        )
619                    })?;
620                    println!(
621                        "auto-compact: set autoCompactWindow to {AUTO_COMPACT_WINDOW} in ~/.claude/settings.json (Claude Code compacts at 200k tokens; delete the key to use the model's full window)"
622                    );
623                }
624                AutoCompact::Kept { key, value } => {
625                    println!("auto-compact: keeping your {key} ({value})");
626                }
627            }
628        }
629    }
630
631    Ok(written)
632}
633
634pub fn uninstall_for(harness: Harness, project: bool) -> Result<Vec<PathBuf>, String> {
635    let dirs = skill_dirs(harness, project)?;
636    let mut changed = Vec::new();
637
638    for dir in dirs {
639        let marker = dir.join(".blyte-installed");
640        if marker.exists() {
641            std::fs::remove_file(&marker)
642                .map_err(|e| format!("failed to remove {}: {e}", marker.display()))?;
643        }
644
645        let skill_path = dir.join("SKILL.md");
646        if skill_path.exists() {
647            std::fs::remove_file(&skill_path)
648                .map_err(|e| format!("failed to remove {}: {e}", skill_path.display()))?;
649            changed.push(skill_path);
650        }
651
652        if dir.exists() {
653            if let Ok(mut entries) = std::fs::read_dir(&dir) {
654                if entries.next().is_none() {
655                    let _ = std::fs::remove_dir(&dir);
656                }
657            }
658        }
659    }
660
661    let md_path = instructions_path(harness, project)?;
662    if md_path.exists() {
663        let existing = std::fs::read_to_string(&md_path)
664            .map_err(|e| format!("failed to read {}: {e}", md_path.display()))?;
665        let mut updated = remove_default_block(&existing);
666        if harness == Harness::Claude && !project {
667            updated = remove_block(&updated, CONTEXT_BLOCK);
668        }
669        if updated != existing {
670            std::fs::write(&md_path, updated)
671                .map_err(|e| format!("failed to write {}: {e}", md_path.display()))?;
672            changed.push(md_path);
673        }
674    }
675
676    if harness == Harness::Codex && !project {
677        let rules_path = codex_rules_path()?;
678        if rules_path.exists() {
679            std::fs::remove_file(&rules_path)
680                .map_err(|e| format!("failed to remove {}: {e}", rules_path.display()))?;
681            if let Some(parent) = rules_path.parent() {
682                if parent.exists() {
683                    if let Ok(mut entries) = std::fs::read_dir(parent) {
684                        if entries.next().is_none() {
685                            let _ = std::fs::remove_dir(parent);
686                        }
687                    }
688                }
689            }
690            changed.push(rules_path);
691        }
692    }
693
694    if harness == Harness::Claude && !project {
695        let home = home_dir()?;
696        let settings_path = home.join(".claude/settings.json");
697        let marker = autocompact_marker_path()?;
698        let marker_exists = marker.exists();
699
700        if settings_path.exists() {
701            let existing = std::fs::read_to_string(&settings_path)
702                .map_err(|e| format!("failed to read {}: {e}", settings_path.display()))?;
703            let mut current = existing;
704            let mut settings_changed = false;
705
706            if let Some(updated) = remove_status_line(&current)
707                .map_err(|e| format!("failed to update {}: {e}", settings_path.display()))?
708            {
709                current = updated;
710                settings_changed = true;
711            }
712
713            if marker_exists {
714                if let Some(updated) = remove_auto_compact_window(&current)
715                    .map_err(|e| format!("failed to update {}: {e}", settings_path.display()))?
716                {
717                    current = updated;
718                    settings_changed = true;
719                }
720            }
721
722            if settings_changed {
723                std::fs::write(&settings_path, current)
724                    .map_err(|e| format!("failed to write {}: {e}", settings_path.display()))?;
725            }
726        }
727
728        if marker_exists {
729            std::fs::remove_file(&marker)
730                .map_err(|e| format!("failed to remove {}: {e}", marker.display()))?;
731        }
732    }
733
734    Ok(changed)
735}
736
737pub fn install(
738    project: bool,
739    force: bool,
740    no_default: bool,
741    no_statusline: bool,
742    no_autocompact: bool,
743) -> Result<PathBuf, String> {
744    let written = install_for(
745        Harness::Claude,
746        project,
747        force,
748        no_default,
749        no_statusline,
750        no_autocompact,
751    )?;
752    Ok(written.into_iter().next().unwrap())
753}
754
755pub fn uninstall(project: bool) -> Result<Vec<PathBuf>, String> {
756    uninstall_for(Harness::Claude, project)
757}
758
759/// Directories that hold an older, separate `blyte-research` skill superseded by `blyte-implementer`.
760pub fn superseded_skills(home: &Path) -> Vec<PathBuf> {
761    let candidates = [
762        home.join(".claude/skills/blyte-research"),
763        home.join(".codex/skills/blyte-research"),
764        home.join(".agents/skills/blyte-research"),
765    ];
766    let mut found = Vec::new();
767    for p in candidates {
768        if p.exists() && !found.contains(&p) {
769            found.push(p);
770        }
771    }
772    found
773}
774
775pub fn superseded_warning(path: &Path) -> String {
776    format!(
777        "blyte: {} is superseded by the blyte-implementer skill's research section (default 300 turns); remove it: rm -r {}",
778        path.display(),
779        path.display()
780    )
781}
782
783pub fn warn_superseded(home: &Path) {
784    for path in superseded_skills(home) {
785        eprintln!("{}", superseded_warning(&path));
786    }
787}
788
789pub const RECOMMENDED_MODEL: &str = "gemini-4-argon";
790pub const FLASH_MODEL: &str = "gemini-3.8-flash-high";
791pub const ARGON_TIMEOUT_SECS: &str = "600";
792
793fn parse_model_choice(input: &str) -> Option<String> {
794    let s = input.trim();
795    if s.is_empty() || s == "1" {
796        return Some(RECOMMENDED_MODEL.to_string());
797    }
798    if s == "2" {
799        return Some(FLASH_MODEL.to_string());
800    }
801    if s.len() < 2 || s.chars().all(|c| c.is_ascii_digit()) {
802        return None;
803    }
804    if !s
805        .chars()
806        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '/' | ':' | '.'))
807    {
808        return None;
809    }
810    Some(s.to_string())
811}
812
813/// Prompts for the default model on `writer` and reads the answer from `reader`. Re-asks once on
814/// an answer that is not `1`, `2`, empty, or a valid model id.
815pub fn prompt_model<R: std::io::BufRead, W: std::io::Write>(
816    reader: &mut R,
817    writer: &mut W,
818) -> Result<String, String> {
819    write!(
820        writer,
821        "Default implementer model:\n  \
822         1) {RECOMMENDED_MODEL} (recommended: passes more gates in fewer turns and lower total cost)\n  \
823         2) {FLASH_MODEL} (cheaper per token, more turns)\n  \
824         3) any other model id, typed in\n\
825         Choice [1]: "
826    )
827    .and_then(|_| writer.flush())
828    .map_err(|e| e.to_string())?;
829
830    let mut line = String::new();
831    reader.read_line(&mut line).map_err(|e| e.to_string())?;
832    if let Some(chosen) = parse_model_choice(&line) {
833        return Ok(chosen);
834    }
835
836    write!(
837        writer,
838        "Enter 1, 2, or a model id (default {RECOMMENDED_MODEL}) [1]: "
839    )
840    .and_then(|_| writer.flush())
841    .map_err(|e| e.to_string())?;
842
843    line.clear();
844    reader.read_line(&mut line).map_err(|e| e.to_string())?;
845    Ok(parse_model_choice(&line).unwrap_or_else(|| RECOMMENDED_MODEL.to_string()))
846}
847
848fn write_model_env<W: std::io::Write>(
849    env_path: &Path,
850    model: &str,
851    writer: &mut W,
852) -> Result<(), String> {
853    if model.to_ascii_lowercase().contains("argon") {
854        crate::env_file::set(
855            env_path,
856            &[
857                ("BLYTE_MODEL", model),
858                ("BLYTE_MODEL_TIMEOUT_SECS", ARGON_TIMEOUT_SECS),
859            ],
860        )?;
861        writeln!(
862            writer,
863            "wrote BLYTE_MODEL={model} and BLYTE_MODEL_TIMEOUT_SECS={ARGON_TIMEOUT_SECS} to {}",
864            env_path.display()
865        )
866        .map_err(|e| e.to_string())?;
867    } else {
868        crate::env_file::set(env_path, &[("BLYTE_MODEL", model)])?;
869        writeln!(
870            writer,
871            "wrote BLYTE_MODEL={model} to {}",
872            env_path.display()
873        )
874        .map_err(|e| e.to_string())?;
875    }
876    Ok(())
877}
878
879/// Sets or reports the default implementer model in `env_path` during `blyte skill install`.
880pub fn configure_model<R: std::io::BufRead, W: std::io::Write>(
881    env_path: &Path,
882    model_flag: Option<&str>,
883    is_terminal: bool,
884    reader: &mut R,
885    writer: &mut W,
886) -> Result<Option<String>, String> {
887    if let Some(model) = model_flag {
888        let model = model.trim();
889        if model.is_empty() {
890            return Err("--model cannot be empty".to_string());
891        }
892        write_model_env(env_path, model, writer)?;
893        return Ok(Some(model.to_string()));
894    }
895
896    if let Some(existing) = crate::env_file::get(env_path, "BLYTE_MODEL")? {
897        writeln!(writer, "BLYTE_MODEL={existing} (in {})", env_path.display())
898            .map_err(|e| e.to_string())?;
899        return Ok(Some(existing));
900    }
901
902    if !is_terminal {
903        return Ok(None);
904    }
905
906    let chosen = prompt_model(reader, writer)?;
907    write_model_env(env_path, &chosen, writer)?;
908    Ok(Some(chosen))
909}