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