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;
228
229pub fn set_status_line(settings: &str) -> Result<Option<String>, String> {
230    let mut val: serde_json::Value = if settings.trim().is_empty() {
231        serde_json::Value::Object(serde_json::Map::new())
232    } else {
233        serde_json::from_str(settings).map_err(|e| e.to_string())?
234    };
235
236    let Some(obj) = val.as_object_mut() else {
237        return Err("settings must be a JSON object".to_string());
238    };
239
240    if let Some(sl) = obj.get_mut("statusLine").and_then(|v| v.as_object_mut()) {
241        let cmd = sl.get("command").and_then(|c| c.as_str());
242        if let Some(cmd_str) = cmd {
243            if cmd_str.starts_with("blyte statusline") {
244                if sl.get("refreshInterval").is_some_and(|v| !v.is_null()) {
245                    return Ok(None);
246                }
247                sl.insert(
248                    "refreshInterval".to_string(),
249                    serde_json::json!(STATUS_LINE_REFRESH_SECS),
250                );
251                let mut out = serde_json::to_string_pretty(&val).map_err(|e| e.to_string())?;
252                out.push('\n');
253                return Ok(Some(out));
254            }
255        }
256
257        let command_str = match cmd {
258            Some(old) => format!("blyte statusline --after '{}'", old.replace('\'', r"'\''")),
259            None => "blyte statusline".to_string(),
260        };
261
262        sl.insert(
263            "type".to_string(),
264            serde_json::Value::String("command".to_string()),
265        );
266        sl.insert(
267            "command".to_string(),
268            serde_json::Value::String(command_str),
269        );
270        if sl
271            .get("refreshInterval")
272            .is_none_or(serde_json::Value::is_null)
273        {
274            sl.insert(
275                "refreshInterval".to_string(),
276                serde_json::json!(STATUS_LINE_REFRESH_SECS),
277            );
278        }
279    } else {
280        let mut sl_map = serde_json::Map::new();
281        sl_map.insert(
282            "type".to_string(),
283            serde_json::Value::String("command".to_string()),
284        );
285        sl_map.insert(
286            "command".to_string(),
287            serde_json::Value::String("blyte statusline".to_string()),
288        );
289        sl_map.insert(
290            "refreshInterval".to_string(),
291            serde_json::json!(STATUS_LINE_REFRESH_SECS),
292        );
293        obj.insert("statusLine".to_string(), serde_json::Value::Object(sl_map));
294    }
295
296    let mut out = serde_json::to_string_pretty(&val).map_err(|e| e.to_string())?;
297    out.push('\n');
298    Ok(Some(out))
299}
300
301pub fn remove_status_line(settings: &str) -> Result<Option<String>, String> {
302    let mut val: serde_json::Value = if settings.trim().is_empty() {
303        serde_json::Value::Object(serde_json::Map::new())
304    } else {
305        serde_json::from_str(settings).map_err(|e| e.to_string())?
306    };
307
308    let Some(obj) = val.as_object_mut() else {
309        return Err("settings must be a JSON object".to_string());
310    };
311
312    let Some(sl) = obj.get("statusLine") else {
313        return Ok(None);
314    };
315
316    let Some(cmd) = sl.get("command").and_then(|c| c.as_str()) else {
317        return Ok(None);
318    };
319
320    const PREFIX: &str = "blyte statusline --after '";
321    if cmd == "blyte statusline" {
322        obj.remove("statusLine");
323    } else if let Some(rest) = cmd.strip_prefix(PREFIX) {
324        if let Some(inside) = rest.strip_suffix('\'') {
325            let old = inside.replace(r"'\''", "'");
326            if let Some(sl_obj) = obj.get_mut("statusLine").and_then(|v| v.as_object_mut()) {
327                sl_obj.insert("command".to_string(), serde_json::Value::String(old));
328                if sl_obj.get("refreshInterval").and_then(|v| v.as_u64())
329                    == Some(STATUS_LINE_REFRESH_SECS)
330                {
331                    sl_obj.remove("refreshInterval");
332                }
333            } else {
334                return Ok(None);
335            }
336        } else {
337            return Ok(None);
338        }
339    } else {
340        return Ok(None);
341    }
342
343    let mut out = serde_json::to_string_pretty(&val).map_err(|e| e.to_string())?;
344    out.push('\n');
345    Ok(Some(out))
346}
347
348pub fn install_for(
349    harness: Harness,
350    project: bool,
351    force: bool,
352    no_default: bool,
353    no_statusline: bool,
354) -> Result<Vec<PathBuf>, String> {
355    let claude_context_written = if harness == Harness::Claude && !project {
356        let home = home_dir()?;
357        ensure_context_block(&home)?
358    } else {
359        None
360    };
361
362    let dirs = skill_dirs(harness, project)?;
363    let skill_paths: Vec<PathBuf> = dirs.iter().map(|d| d.join("SKILL.md")).collect();
364
365    for skill_path in &skill_paths {
366        if skill_path.exists() {
367            let existing = std::fs::read_to_string(skill_path)
368                .map_err(|e| format!("failed to read {}: {e}", skill_path.display()))?;
369            if existing != SKILL_MD && !force {
370                return Err(format!(
371                    "{} already exists with different content; pass --force to overwrite",
372                    skill_path.display()
373                ));
374            }
375        }
376    }
377
378    let mut written = Vec::new();
379    for (dir, skill_path) in dirs.into_iter().zip(skill_paths) {
380        std::fs::create_dir_all(&dir)
381            .map_err(|e| format!("failed to create directory {}: {e}", dir.display()))?;
382        std::fs::write(&skill_path, SKILL_MD)
383            .map_err(|e| format!("failed to write {}: {e}", skill_path.display()))?;
384        let marker = dir.join(".blyte-installed");
385        std::fs::write(&marker, SKILL_MD)
386            .map_err(|e| format!("failed to write {}: {e}", marker.display()))?;
387        written.push(skill_path);
388    }
389
390    let md_path = instructions_path(harness, project)?;
391    if !no_default {
392        if let Some(parent) = md_path.parent() {
393            std::fs::create_dir_all(parent)
394                .map_err(|e| format!("failed to create directory {}: {e}", parent.display()))?;
395        }
396        let existing = if md_path.exists() {
397            std::fs::read_to_string(&md_path)
398                .map_err(|e| format!("failed to read {}: {e}", md_path.display()))?
399        } else {
400            String::new()
401        };
402        let updated = set_default_block(&existing);
403        std::fs::write(&md_path, updated)
404            .map_err(|e| format!("failed to write {}: {e}", md_path.display()))?;
405        if !written.contains(&md_path) {
406            written.push(md_path);
407        }
408    } else if md_path.exists() {
409        // Switching to "only when asked" drops the default block an earlier install wrote, so it
410        // does not need an uninstall first (2026-09-30).
411        let existing = std::fs::read_to_string(&md_path)
412            .map_err(|e| format!("failed to read {}: {e}", md_path.display()))?;
413        let updated = remove_default_block(&existing);
414        if updated != existing {
415            std::fs::write(&md_path, updated)
416                .map_err(|e| format!("failed to write {}: {e}", md_path.display()))?;
417            if !written.contains(&md_path) {
418                written.push(md_path);
419            }
420        }
421    }
422
423    if let Some(path) = claude_context_written {
424        if !written.contains(&path) {
425            written.push(path);
426        }
427    }
428
429    if harness == Harness::Codex && !project {
430        let rules_path = codex_rules_path()?;
431        if let Some(parent) = rules_path.parent() {
432            std::fs::create_dir_all(parent)
433                .map_err(|e| format!("failed to create directory {}: {e}", parent.display()))?;
434        }
435        std::fs::write(&rules_path, CODEX_RULES)
436            .map_err(|e| format!("failed to write {}: {e}", rules_path.display()))?;
437        written.push(rules_path);
438    }
439
440    if harness == Harness::Claude && !project && !no_statusline {
441        let home = home_dir()?;
442        let claude_dir = home.join(".claude");
443        let settings_path = claude_dir.join("settings.json");
444        let backup_path = claude_dir.join("settings.json.blyte-backup");
445
446        let existing = if settings_path.exists() {
447            match std::fs::read_to_string(&settings_path) {
448                Ok(s) => s,
449                Err(e) => {
450                    return Err(format!("failed to read {}: {e}", settings_path.display()));
451                }
452            }
453        } else {
454            String::new()
455        };
456
457        match set_status_line(&existing) {
458            Ok(Some(updated)) => {
459                if settings_path.exists() && !backup_path.exists() {
460                    std::fs::copy(&settings_path, &backup_path).map_err(|e| {
461                        format!("failed to create backup {}: {e}", backup_path.display())
462                    })?;
463                }
464                if let Some(parent) = settings_path.parent() {
465                    std::fs::create_dir_all(parent).map_err(|e| {
466                        format!("failed to create directory {}: {e}", parent.display())
467                    })?;
468                }
469                std::fs::write(&settings_path, &updated)
470                    .map_err(|e| format!("failed to write {}: {e}", settings_path.display()))?;
471
472                if updated.contains("blyte statusline --after") {
473                    println!("status line: wrapped your status line command");
474                } else {
475                    println!("status line: set to blyte statusline");
476                }
477            }
478            Ok(None) => {}
479            Err(e) => {
480                eprintln!("warning: could not update {}: {e}", settings_path.display());
481            }
482        }
483    }
484
485    Ok(written)
486}
487
488pub fn uninstall_for(harness: Harness, project: bool) -> Result<Vec<PathBuf>, String> {
489    let dirs = skill_dirs(harness, project)?;
490    let mut changed = Vec::new();
491
492    for dir in dirs {
493        let marker = dir.join(".blyte-installed");
494        if marker.exists() {
495            std::fs::remove_file(&marker)
496                .map_err(|e| format!("failed to remove {}: {e}", marker.display()))?;
497        }
498
499        let skill_path = dir.join("SKILL.md");
500        if skill_path.exists() {
501            std::fs::remove_file(&skill_path)
502                .map_err(|e| format!("failed to remove {}: {e}", skill_path.display()))?;
503            changed.push(skill_path);
504        }
505
506        if dir.exists() {
507            if let Ok(mut entries) = std::fs::read_dir(&dir) {
508                if entries.next().is_none() {
509                    let _ = std::fs::remove_dir(&dir);
510                }
511            }
512        }
513    }
514
515    let md_path = instructions_path(harness, project)?;
516    if md_path.exists() {
517        let existing = std::fs::read_to_string(&md_path)
518            .map_err(|e| format!("failed to read {}: {e}", md_path.display()))?;
519        let mut updated = remove_default_block(&existing);
520        if harness == Harness::Claude && !project {
521            updated = remove_block(&updated, CONTEXT_BLOCK);
522        }
523        if updated != existing {
524            std::fs::write(&md_path, updated)
525                .map_err(|e| format!("failed to write {}: {e}", md_path.display()))?;
526            changed.push(md_path);
527        }
528    }
529
530    if harness == Harness::Codex && !project {
531        let rules_path = codex_rules_path()?;
532        if rules_path.exists() {
533            std::fs::remove_file(&rules_path)
534                .map_err(|e| format!("failed to remove {}: {e}", rules_path.display()))?;
535            if let Some(parent) = rules_path.parent() {
536                if parent.exists() {
537                    if let Ok(mut entries) = std::fs::read_dir(parent) {
538                        if entries.next().is_none() {
539                            let _ = std::fs::remove_dir(parent);
540                        }
541                    }
542                }
543            }
544            changed.push(rules_path);
545        }
546    }
547
548    if harness == Harness::Claude && !project {
549        let home = home_dir()?;
550        let settings_path = home.join(".claude/settings.json");
551        if settings_path.exists() {
552            if let Ok(existing) = std::fs::read_to_string(&settings_path) {
553                match remove_status_line(&existing) {
554                    Ok(Some(updated)) => {
555                        std::fs::write(&settings_path, updated).map_err(|e| {
556                            format!("failed to write {}: {e}", settings_path.display())
557                        })?;
558                    }
559                    Ok(None) => {}
560                    Err(e) => {
561                        eprintln!("warning: could not update {}: {e}", settings_path.display());
562                    }
563                }
564            }
565        }
566    }
567
568    Ok(changed)
569}
570
571pub fn install(
572    project: bool,
573    force: bool,
574    no_default: bool,
575    no_statusline: bool,
576) -> Result<PathBuf, String> {
577    let written = install_for(Harness::Claude, project, force, no_default, no_statusline)?;
578    Ok(written.into_iter().next().unwrap())
579}
580
581pub fn uninstall(project: bool) -> Result<Vec<PathBuf>, String> {
582    uninstall_for(Harness::Claude, project)
583}
584
585/// Directories that hold an older, separate `blyte-research` skill superseded by `blyte-implementer`.
586pub fn superseded_skills(home: &Path) -> Vec<PathBuf> {
587    let candidates = [
588        home.join(".claude/skills/blyte-research"),
589        home.join(".codex/skills/blyte-research"),
590        home.join(".agents/skills/blyte-research"),
591    ];
592    let mut found = Vec::new();
593    for p in candidates {
594        if p.exists() && !found.contains(&p) {
595            found.push(p);
596        }
597    }
598    found
599}
600
601pub fn superseded_warning(path: &Path) -> String {
602    format!(
603        "blyte: {} is superseded by the blyte-implementer skill's research section (default 300 turns); remove it: rm -r {}",
604        path.display(),
605        path.display()
606    )
607}
608
609pub fn warn_superseded(home: &Path) {
610    for path in superseded_skills(home) {
611        eprintln!("{}", superseded_warning(&path));
612    }
613}