blyte 0.75.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
use std::path::{Path, PathBuf};
use std::process::Command;

pub const SKILL_MD: &str = include_str!("../assets/blyte-implementer/SKILL.md");

pub const DEFAULT_BLOCK: &str = "\
<!-- blyte:default -->
## Implementation: delegate to blyte, in parallel

For code changes in a git repository that has a check command (tests, lint), plan and review
the work yourself and delegate the implementation to blyte with the `blyte-implementer` skill.
Split the work into independent tasks and dispatch them in parallel (`blyte dispatch`, one
worktree each); run tasks one after another only when one depends on another. Keep for
yourself: design decisions, ambiguous requirements, one-line edits, and anything with no check.

Worktrees of your own (not blyte runs) go inside the repository at `.wt/plan-<topic>`,
branched from the default branch: `git worktree add .wt/plan-<topic> -b <branch> origin/<default>`.
Never next to the repository or in a temp or scratchpad folder. Remove it after its PR merges
if you are still running; otherwise `blyte clean` removes it once the branch is merged and it
has no changes.
<!-- /blyte:default -->";

pub const CONTEXT_BLOCK: &str = "\
<!-- blyte:context -->
## Context: keep this session small

Everything a tool returns stays in the conversation and is re-read on every turn, so it is most of
what a session costs.
- Trim command output at the source: `| tail -n 20`, `grep` for the lines you need, `sed -n`
  ranges, `--quiet`/`-q`; `git diff --stat` before any full diff.
- Read files by range (offset and limit), not whole, once you know where to look.
- For a dispatched run, read `blyte review <id>` and the JSON fields you need
  (`jq -r .outcome .wt/<id>.json`), not the whole summary or log; search `.wt/<id>.log` with
  `grep`/`tail` only for what `== checks` flags.
- Write tasks as `### Task <ID>` sections of the plan and dispatch with `--plan`/`--plan-task`;
  do not write task files that copy the plan.
- An investigation needing more than about five file reads goes to `blyte dispatch --research`;
  read its report, not the files.
- One session per piece of work. When the status line shows the context past about 60% of its
  window, tell the user to `/compact` or start a new session before going on.
<!-- /blyte:context -->";

pub const CODEX_RULES: &str = "\
# Written by `blyte skill install --harness codex`; removed by `blyte skill uninstall --harness codex`.
# blyte dispatch needs the network and applies its own sandbox, so it runs outside Codex's.
prefix_rule(pattern=[\"blyte\", \"dispatch\"], decision=\"allow\")
prefix_rule(pattern=[\"blyte\", \"review\"], decision=\"allow\")
";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Harness {
    Claude,
    Codex,
}

impl Harness {
    pub fn parse_all(s: &str) -> Result<Vec<Self>, String> {
        match s {
            "claude" => Ok(vec![Harness::Claude]),
            "codex" => Ok(vec![Harness::Codex]),
            "all" => Ok(vec![Harness::Claude, Harness::Codex]),
            other => Err(format!("unknown harness: {other}")),
        }
    }
}

fn repo_root() -> Result<PathBuf, String> {
    let out = Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .map_err(|e| format!("failed to execute git: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "not a git repository: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        ));
    }
    Ok(PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()))
}

pub fn home_dir() -> Result<PathBuf, String> {
    let home = std::env::var("HOME")
        .map_err(|_| "HOME environment variable is unset or empty".to_string())?;
    if home.trim().is_empty() {
        return Err("HOME environment variable is unset or empty".to_string());
    }
    Ok(PathBuf::from(home))
}

pub fn skill_dir(project: bool) -> Result<PathBuf, String> {
    if project {
        Ok(repo_root()?.join(".claude/skills/blyte-implementer"))
    } else {
        Ok(home_dir()?.join(".claude/skills/blyte-implementer"))
    }
}

pub fn claude_md_path(project: bool) -> Result<PathBuf, String> {
    if project {
        Ok(repo_root()?.join("CLAUDE.md"))
    } else {
        Ok(home_dir()?.join(".claude/CLAUDE.md"))
    }
}

pub fn skill_dirs(harness: Harness, project: bool) -> Result<Vec<PathBuf>, String> {
    match harness {
        Harness::Claude => Ok(vec![skill_dir(project)?]),
        Harness::Codex => {
            if project {
                Ok(vec![repo_root()?.join(".agents/skills/blyte-implementer")])
            } else {
                let home = home_dir()?;
                Ok(vec![
                    home.join(".agents/skills/blyte-implementer"),
                    home.join(".codex/skills/blyte-implementer"),
                ])
            }
        }
    }
}

pub fn instructions_path(harness: Harness, project: bool) -> Result<PathBuf, String> {
    match harness {
        Harness::Claude => claude_md_path(project),
        Harness::Codex => {
            if project {
                Ok(repo_root()?.join("AGENTS.md"))
            } else {
                Ok(home_dir()?.join(".codex/AGENTS.md"))
            }
        }
    }
}

pub fn codex_rules_path() -> Result<PathBuf, String> {
    Ok(home_dir()?.join(".codex/rules/blyte.rules"))
}

pub fn set_block(text: &str, block: &str) -> String {
    let start_marker = block.lines().next().unwrap_or("");
    let end_marker = block.lines().last().unwrap_or("");

    if !start_marker.is_empty() && !end_marker.is_empty() {
        if let Some(start) = text.find(start_marker) {
            if let Some(end_rel) = text[start..].find(end_marker) {
                let end = start + end_rel + end_marker.len();
                let mut result = format!("{}{block}{}", &text[..start], &text[end..]);
                while result.ends_with("\n\n") {
                    result.pop();
                }
                if !result.ends_with('\n') {
                    result.push('\n');
                }
                return result;
            }
        }
    }

    if text.is_empty() {
        format!("{block}\n")
    } else if text.ends_with('\n') {
        format!("{text}\n{block}\n")
    } else {
        format!("{text}\n\n{block}\n")
    }
}

pub fn remove_block(text: &str, block: &str) -> String {
    let start_marker = block.lines().next().unwrap_or("");
    let end_marker = block.lines().last().unwrap_or("");

    if start_marker.is_empty() || end_marker.is_empty() {
        return text.to_string();
    }

    let Some(start) = text.find(start_marker) else {
        return text.to_string();
    };
    let Some(end_rel) = text[start..].find(end_marker) else {
        return text.to_string();
    };
    let end = start + end_rel + end_marker.len();

    let prefix = &text[..start];
    let prefix_clean = if prefix.ends_with("\n\n") {
        &prefix[..prefix.len() - 1]
    } else if prefix == "\n" {
        ""
    } else {
        prefix
    };

    let suffix = if text[end..].starts_with('\n') {
        &text[end + 1..]
    } else {
        &text[end..]
    };

    format!("{prefix_clean}{suffix}")
}

pub fn set_default_block(text: &str) -> String {
    set_block(text, DEFAULT_BLOCK)
}

pub fn remove_default_block(text: &str) -> String {
    remove_block(text, DEFAULT_BLOCK)
}

pub fn ensure_context_block(home: &Path) -> Result<Option<PathBuf>, String> {
    let claude_dir = home.join(".claude");
    if !claude_dir.exists() {
        return Ok(None);
    }
    let claude_md = claude_dir.join("CLAUDE.md");
    let existing = if claude_md.exists() {
        std::fs::read_to_string(&claude_md)
            .map_err(|e| format!("failed to read {}: {e}", claude_md.display()))?
    } else {
        String::new()
    };
    let updated = set_block(&existing, CONTEXT_BLOCK);
    if updated != existing {
        std::fs::write(&claude_md, updated)
            .map_err(|e| format!("failed to write {}: {e}", claude_md.display()))?;
        Ok(Some(claude_md))
    } else {
        Ok(None)
    }
}

pub const STATUS_LINE_REFRESH_SECS: u64 = 30;
pub const AUTO_COMPACT_WINDOW: u64 = 200_000;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AutoCompact {
    Kept { key: String, value: String },
    Set(String),
}

fn json_value_display(v: &serde_json::Value) -> String {
    match v.as_str() {
        Some(s) => s.to_string(),
        None => v.to_string(),
    }
}

pub fn set_auto_compact_window(settings: &str) -> Result<AutoCompact, String> {
    let mut val: serde_json::Value = if settings.trim().is_empty() {
        serde_json::Value::Object(serde_json::Map::new())
    } else {
        serde_json::from_str(settings).map_err(|e| e.to_string())?
    };

    let Some(obj) = val.as_object_mut() else {
        return Err("settings must be a JSON object".to_string());
    };

    if let Some(v) = obj.get("autoCompactWindow").filter(|v| !v.is_null()) {
        return Ok(AutoCompact::Kept {
            key: "autoCompactWindow".to_string(),
            value: json_value_display(v),
        });
    }

    if let Some(models) = obj.get("modelSettings").and_then(|v| v.as_object()) {
        for (model, model_obj) in models {
            if let Some(v) = model_obj
                .as_object()
                .and_then(|m| m.get("autoCompactWindow"))
                .filter(|v| !v.is_null())
            {
                return Ok(AutoCompact::Kept {
                    key: format!("modelSettings.{model}.autoCompactWindow"),
                    value: json_value_display(v),
                });
            }
        }
    }

    if let Some(v) = obj
        .get("env")
        .and_then(|e| e.as_object())
        .and_then(|e| e.get("CLAUDE_CODE_AUTO_COMPACT_WINDOW"))
        .filter(|v| !v.is_null())
    {
        return Ok(AutoCompact::Kept {
            key: "env.CLAUDE_CODE_AUTO_COMPACT_WINDOW".to_string(),
            value: json_value_display(v),
        });
    }

    obj.insert(
        "autoCompactWindow".to_string(),
        serde_json::json!(AUTO_COMPACT_WINDOW),
    );
    let mut out = serde_json::to_string_pretty(&val).map_err(|e| e.to_string())?;
    out.push('\n');
    Ok(AutoCompact::Set(out))
}

pub fn remove_auto_compact_window(settings: &str) -> Result<Option<String>, String> {
    let mut val: serde_json::Value = if settings.trim().is_empty() {
        serde_json::Value::Object(serde_json::Map::new())
    } else {
        serde_json::from_str(settings).map_err(|e| e.to_string())?
    };

    let Some(obj) = val.as_object_mut() else {
        return Err("settings must be a JSON object".to_string());
    };

    if obj.get("autoCompactWindow").and_then(|v| v.as_u64()) != Some(AUTO_COMPACT_WINDOW) {
        return Ok(None);
    }

    obj.remove("autoCompactWindow");
    let mut out = serde_json::to_string_pretty(&val).map_err(|e| e.to_string())?;
    out.push('\n');
    Ok(Some(out))
}

fn autocompact_marker_path() -> Result<PathBuf, String> {
    let dir = crate::registry::state_dir().ok_or_else(|| {
        "cannot determine state directory: none of BLYTE_STATE_DIR, XDG_STATE_HOME, or HOME is set"
            .to_string()
    })?;
    Ok(dir.join("autocompact-window"))
}

pub fn set_status_line(settings: &str) -> Result<Option<String>, String> {
    let mut val: serde_json::Value = if settings.trim().is_empty() {
        serde_json::Value::Object(serde_json::Map::new())
    } else {
        serde_json::from_str(settings).map_err(|e| e.to_string())?
    };

    let Some(obj) = val.as_object_mut() else {
        return Err("settings must be a JSON object".to_string());
    };

    if let Some(sl) = obj.get_mut("statusLine").and_then(|v| v.as_object_mut()) {
        let cmd = sl.get("command").and_then(|c| c.as_str());
        if let Some(cmd_str) = cmd {
            if cmd_str.starts_with("blyte statusline") {
                if sl.get("refreshInterval").is_some_and(|v| !v.is_null()) {
                    return Ok(None);
                }
                sl.insert(
                    "refreshInterval".to_string(),
                    serde_json::json!(STATUS_LINE_REFRESH_SECS),
                );
                let mut out = serde_json::to_string_pretty(&val).map_err(|e| e.to_string())?;
                out.push('\n');
                return Ok(Some(out));
            }
        }

        let command_str = match cmd {
            Some(old) => format!("blyte statusline --after '{}'", old.replace('\'', r"'\''")),
            None => "blyte statusline".to_string(),
        };

        sl.insert(
            "type".to_string(),
            serde_json::Value::String("command".to_string()),
        );
        sl.insert(
            "command".to_string(),
            serde_json::Value::String(command_str),
        );
        if sl
            .get("refreshInterval")
            .is_none_or(serde_json::Value::is_null)
        {
            sl.insert(
                "refreshInterval".to_string(),
                serde_json::json!(STATUS_LINE_REFRESH_SECS),
            );
        }
    } else {
        let mut sl_map = serde_json::Map::new();
        sl_map.insert(
            "type".to_string(),
            serde_json::Value::String("command".to_string()),
        );
        sl_map.insert(
            "command".to_string(),
            serde_json::Value::String("blyte statusline".to_string()),
        );
        sl_map.insert(
            "refreshInterval".to_string(),
            serde_json::json!(STATUS_LINE_REFRESH_SECS),
        );
        obj.insert("statusLine".to_string(), serde_json::Value::Object(sl_map));
    }

    let mut out = serde_json::to_string_pretty(&val).map_err(|e| e.to_string())?;
    out.push('\n');
    Ok(Some(out))
}

pub fn remove_status_line(settings: &str) -> Result<Option<String>, String> {
    let mut val: serde_json::Value = if settings.trim().is_empty() {
        serde_json::Value::Object(serde_json::Map::new())
    } else {
        serde_json::from_str(settings).map_err(|e| e.to_string())?
    };

    let Some(obj) = val.as_object_mut() else {
        return Err("settings must be a JSON object".to_string());
    };

    let Some(sl) = obj.get("statusLine") else {
        return Ok(None);
    };

    let Some(cmd) = sl.get("command").and_then(|c| c.as_str()) else {
        return Ok(None);
    };

    const PREFIX: &str = "blyte statusline --after '";
    if cmd == "blyte statusline" {
        obj.remove("statusLine");
    } else if let Some(rest) = cmd.strip_prefix(PREFIX) {
        if let Some(inside) = rest.strip_suffix('\'') {
            let old = inside.replace(r"'\''", "'");
            if let Some(sl_obj) = obj.get_mut("statusLine").and_then(|v| v.as_object_mut()) {
                sl_obj.insert("command".to_string(), serde_json::Value::String(old));
                if sl_obj.get("refreshInterval").and_then(|v| v.as_u64())
                    == Some(STATUS_LINE_REFRESH_SECS)
                {
                    sl_obj.remove("refreshInterval");
                }
            } else {
                return Ok(None);
            }
        } else {
            return Ok(None);
        }
    } else {
        return Ok(None);
    }

    let mut out = serde_json::to_string_pretty(&val).map_err(|e| e.to_string())?;
    out.push('\n');
    Ok(Some(out))
}

pub fn install_for(
    harness: Harness,
    project: bool,
    force: bool,
    no_default: bool,
    no_statusline: bool,
    no_autocompact: bool,
) -> Result<Vec<PathBuf>, String> {
    let claude_context_written = if harness == Harness::Claude && !project {
        let home = home_dir()?;
        ensure_context_block(&home)?
    } else {
        None
    };

    let dirs = skill_dirs(harness, project)?;
    let skill_paths: Vec<PathBuf> = dirs.iter().map(|d| d.join("SKILL.md")).collect();

    for skill_path in &skill_paths {
        if skill_path.exists() {
            let existing = std::fs::read_to_string(skill_path)
                .map_err(|e| format!("failed to read {}: {e}", skill_path.display()))?;
            if existing != SKILL_MD && !force {
                return Err(format!(
                    "{} already exists with different content; pass --force to overwrite",
                    skill_path.display()
                ));
            }
        }
    }

    let mut written = Vec::new();
    for (dir, skill_path) in dirs.into_iter().zip(skill_paths) {
        std::fs::create_dir_all(&dir)
            .map_err(|e| format!("failed to create directory {}: {e}", dir.display()))?;
        std::fs::write(&skill_path, SKILL_MD)
            .map_err(|e| format!("failed to write {}: {e}", skill_path.display()))?;
        let marker = dir.join(".blyte-installed");
        std::fs::write(&marker, SKILL_MD)
            .map_err(|e| format!("failed to write {}: {e}", marker.display()))?;
        written.push(skill_path);
    }

    let md_path = instructions_path(harness, project)?;
    if !no_default {
        if let Some(parent) = md_path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| format!("failed to create directory {}: {e}", parent.display()))?;
        }
        let existing = if md_path.exists() {
            std::fs::read_to_string(&md_path)
                .map_err(|e| format!("failed to read {}: {e}", md_path.display()))?
        } else {
            String::new()
        };
        let updated = set_default_block(&existing);
        std::fs::write(&md_path, updated)
            .map_err(|e| format!("failed to write {}: {e}", md_path.display()))?;
        if !written.contains(&md_path) {
            written.push(md_path);
        }
    } else if md_path.exists() {
        // Switching to "only when asked" drops the default block an earlier install wrote, so it
        // does not need an uninstall first (2026-09-30).
        let existing = std::fs::read_to_string(&md_path)
            .map_err(|e| format!("failed to read {}: {e}", md_path.display()))?;
        let updated = remove_default_block(&existing);
        if updated != existing {
            std::fs::write(&md_path, updated)
                .map_err(|e| format!("failed to write {}: {e}", md_path.display()))?;
            if !written.contains(&md_path) {
                written.push(md_path);
            }
        }
    }

    if let Some(path) = claude_context_written {
        if !written.contains(&path) {
            written.push(path);
        }
    }

    if harness == Harness::Codex && !project {
        let rules_path = codex_rules_path()?;
        if let Some(parent) = rules_path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| format!("failed to create directory {}: {e}", parent.display()))?;
        }
        std::fs::write(&rules_path, CODEX_RULES)
            .map_err(|e| format!("failed to write {}: {e}", rules_path.display()))?;
        written.push(rules_path);
    }

    if harness == Harness::Claude && !project && (!no_statusline || !no_autocompact) {
        let home = home_dir()?;
        let claude_dir = home.join(".claude");
        let settings_path = claude_dir.join("settings.json");
        let backup_path = claude_dir.join("settings.json.blyte-backup");

        let existing = if settings_path.exists() {
            std::fs::read_to_string(&settings_path)
                .map_err(|e| format!("failed to read {}: {e}", settings_path.display()))?
        } else {
            String::new()
        };

        let mut current = existing;
        let mut settings_changed = false;
        let mut statusline_msg: Option<&'static str> = None;

        if !no_statusline {
            let updated = set_status_line(&current)
                .map_err(|e| format!("failed to update {}: {e}", settings_path.display()))?;
            if let Some(updated) = updated {
                if updated.contains("blyte statusline --after") {
                    statusline_msg = Some("status line: wrapped your status line command");
                } else {
                    statusline_msg = Some("status line: set to blyte statusline");
                }
                current = updated;
                settings_changed = true;
            }
        }

        let mut autocompact_action: Option<(AutoCompact, PathBuf)> = None;
        if !no_autocompact {
            let marker = autocompact_marker_path()?;
            if !marker.exists() {
                let res = set_auto_compact_window(&current)
                    .map_err(|e| format!("failed to update {}: {e}", settings_path.display()))?;
                if let AutoCompact::Set(ref updated) = res {
                    current = updated.clone();
                    settings_changed = true;
                }
                autocompact_action = Some((res, marker));
            }
        }

        if settings_changed {
            if settings_path.exists() && !backup_path.exists() {
                std::fs::copy(&settings_path, &backup_path).map_err(|e| {
                    format!("failed to create backup {}: {e}", backup_path.display())
                })?;
            }
            if let Some(parent) = settings_path.parent() {
                std::fs::create_dir_all(parent)
                    .map_err(|e| format!("failed to create directory {}: {e}", parent.display()))?;
            }
            std::fs::write(&settings_path, &current)
                .map_err(|e| format!("failed to write {}: {e}", settings_path.display()))?;
        }

        if let Some(msg) = statusline_msg {
            println!("{msg}");
        }

        if let Some((action, marker)) = autocompact_action {
            match action {
                AutoCompact::Set(_) => {
                    if let Some(parent) = marker.parent() {
                        std::fs::create_dir_all(parent).map_err(|e| {
                            format!(
                                "failed to write {}: {e} (autoCompactWindow was set in {}, but uninstall will not remove it)",
                                marker.display(),
                                settings_path.display()
                            )
                        })?;
                    }
                    std::fs::write(&marker, AUTO_COMPACT_WINDOW.to_string()).map_err(|e| {
                        format!(
                            "failed to write {}: {e} (autoCompactWindow was set in {}, but uninstall will not remove it)",
                            marker.display(),
                            settings_path.display()
                        )
                    })?;
                    println!(
                        "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)"
                    );
                }
                AutoCompact::Kept { key, value } => {
                    println!("auto-compact: keeping your {key} ({value})");
                }
            }
        }
    }

    Ok(written)
}

pub fn uninstall_for(harness: Harness, project: bool) -> Result<Vec<PathBuf>, String> {
    let dirs = skill_dirs(harness, project)?;
    let mut changed = Vec::new();

    for dir in dirs {
        let marker = dir.join(".blyte-installed");
        if marker.exists() {
            std::fs::remove_file(&marker)
                .map_err(|e| format!("failed to remove {}: {e}", marker.display()))?;
        }

        let skill_path = dir.join("SKILL.md");
        if skill_path.exists() {
            std::fs::remove_file(&skill_path)
                .map_err(|e| format!("failed to remove {}: {e}", skill_path.display()))?;
            changed.push(skill_path);
        }

        if dir.exists() {
            if let Ok(mut entries) = std::fs::read_dir(&dir) {
                if entries.next().is_none() {
                    let _ = std::fs::remove_dir(&dir);
                }
            }
        }
    }

    let md_path = instructions_path(harness, project)?;
    if md_path.exists() {
        let existing = std::fs::read_to_string(&md_path)
            .map_err(|e| format!("failed to read {}: {e}", md_path.display()))?;
        let mut updated = remove_default_block(&existing);
        if harness == Harness::Claude && !project {
            updated = remove_block(&updated, CONTEXT_BLOCK);
        }
        if updated != existing {
            std::fs::write(&md_path, updated)
                .map_err(|e| format!("failed to write {}: {e}", md_path.display()))?;
            changed.push(md_path);
        }
    }

    if harness == Harness::Codex && !project {
        let rules_path = codex_rules_path()?;
        if rules_path.exists() {
            std::fs::remove_file(&rules_path)
                .map_err(|e| format!("failed to remove {}: {e}", rules_path.display()))?;
            if let Some(parent) = rules_path.parent() {
                if parent.exists() {
                    if let Ok(mut entries) = std::fs::read_dir(parent) {
                        if entries.next().is_none() {
                            let _ = std::fs::remove_dir(parent);
                        }
                    }
                }
            }
            changed.push(rules_path);
        }
    }

    if harness == Harness::Claude && !project {
        let home = home_dir()?;
        let settings_path = home.join(".claude/settings.json");
        let marker = autocompact_marker_path()?;
        let marker_exists = marker.exists();

        if settings_path.exists() {
            let existing = std::fs::read_to_string(&settings_path)
                .map_err(|e| format!("failed to read {}: {e}", settings_path.display()))?;
            let mut current = existing;
            let mut settings_changed = false;

            if let Some(updated) = remove_status_line(&current)
                .map_err(|e| format!("failed to update {}: {e}", settings_path.display()))?
            {
                current = updated;
                settings_changed = true;
            }

            if marker_exists {
                if let Some(updated) = remove_auto_compact_window(&current)
                    .map_err(|e| format!("failed to update {}: {e}", settings_path.display()))?
                {
                    current = updated;
                    settings_changed = true;
                }
            }

            if settings_changed {
                std::fs::write(&settings_path, current)
                    .map_err(|e| format!("failed to write {}: {e}", settings_path.display()))?;
            }
        }

        if marker_exists {
            std::fs::remove_file(&marker)
                .map_err(|e| format!("failed to remove {}: {e}", marker.display()))?;
        }
    }

    Ok(changed)
}

pub fn install(
    project: bool,
    force: bool,
    no_default: bool,
    no_statusline: bool,
    no_autocompact: bool,
) -> Result<PathBuf, String> {
    let written = install_for(
        Harness::Claude,
        project,
        force,
        no_default,
        no_statusline,
        no_autocompact,
    )?;
    Ok(written.into_iter().next().unwrap())
}

pub fn uninstall(project: bool) -> Result<Vec<PathBuf>, String> {
    uninstall_for(Harness::Claude, project)
}

/// Directories that hold an older, separate `blyte-research` skill superseded by `blyte-implementer`.
pub fn superseded_skills(home: &Path) -> Vec<PathBuf> {
    let candidates = [
        home.join(".claude/skills/blyte-research"),
        home.join(".codex/skills/blyte-research"),
        home.join(".agents/skills/blyte-research"),
    ];
    let mut found = Vec::new();
    for p in candidates {
        if p.exists() && !found.contains(&p) {
            found.push(p);
        }
    }
    found
}

pub fn superseded_warning(path: &Path) -> String {
    format!(
        "blyte: {} is superseded by the blyte-implementer skill's research section (default 300 turns); remove it: rm -r {}",
        path.display(),
        path.display()
    )
}

pub fn warn_superseded(home: &Path) {
    for path in superseded_skills(home) {
        eprintln!("{}", superseded_warning(&path));
    }
}

pub const RECOMMENDED_MODEL: &str = "gemini-4-neon";
pub const FLASH_MODEL: &str = "gemini-3.8-flash-high";
pub const ARGON_TIMEOUT_SECS: &str = "600";

fn parse_model_choice(input: &str) -> Option<String> {
    let s = input.trim();
    if s.is_empty() || s == "1" {
        return Some(RECOMMENDED_MODEL.to_string());
    }
    if s == "2" {
        return Some(FLASH_MODEL.to_string());
    }
    if s.len() < 2 || s.chars().all(|c| c.is_ascii_digit()) {
        return None;
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '/' | ':' | '.'))
    {
        return None;
    }
    Some(s.to_string())
}

/// Prompts for the default model on `writer` and reads the answer from `reader`. Re-asks once on
/// an answer that is not `1`, `2`, empty, or a valid model id.
pub fn prompt_model<R: std::io::BufRead, W: std::io::Write>(
    reader: &mut R,
    writer: &mut W,
) -> Result<String, String> {
    write!(
        writer,
        "Default implementer model:\n  \
         1) {RECOMMENDED_MODEL} (recommended: best results in the 2026-11 trial at the lowest total cost)\n  \
         2) {FLASH_MODEL} (cheaper per token, more turns)\n  \
         3) any other model id, typed in\n\
         Choice [1]: "
    )
    .and_then(|_| writer.flush())
    .map_err(|e| e.to_string())?;

    let mut line = String::new();
    reader.read_line(&mut line).map_err(|e| e.to_string())?;
    if let Some(chosen) = parse_model_choice(&line) {
        return Ok(chosen);
    }

    write!(
        writer,
        "Enter 1, 2, or a model id (default {RECOMMENDED_MODEL}) [1]: "
    )
    .and_then(|_| writer.flush())
    .map_err(|e| e.to_string())?;

    line.clear();
    reader.read_line(&mut line).map_err(|e| e.to_string())?;
    Ok(parse_model_choice(&line).unwrap_or_else(|| RECOMMENDED_MODEL.to_string()))
}

fn write_model_env<W: std::io::Write>(
    env_path: &Path,
    model: &str,
    writer: &mut W,
) -> Result<(), String> {
    if model.to_ascii_lowercase().contains("argon") {
        crate::env_file::set(
            env_path,
            &[
                ("BLYTE_MODEL", model),
                ("BLYTE_MODEL_TIMEOUT_SECS", ARGON_TIMEOUT_SECS),
            ],
        )?;
        writeln!(
            writer,
            "wrote BLYTE_MODEL={model} and BLYTE_MODEL_TIMEOUT_SECS={ARGON_TIMEOUT_SECS} to {}",
            env_path.display()
        )
        .map_err(|e| e.to_string())?;
    } else {
        crate::env_file::set(env_path, &[("BLYTE_MODEL", model)])?;
        writeln!(
            writer,
            "wrote BLYTE_MODEL={model} to {}",
            env_path.display()
        )
        .map_err(|e| e.to_string())?;
    }
    Ok(())
}

/// Sets or reports the default implementer model in `env_path` during `blyte skill install`.
pub fn configure_model<R: std::io::BufRead, W: std::io::Write>(
    env_path: &Path,
    model_flag: Option<&str>,
    is_terminal: bool,
    reader: &mut R,
    writer: &mut W,
) -> Result<Option<String>, String> {
    if let Some(model) = model_flag {
        let model = model.trim();
        if model.is_empty() {
            return Err("--model cannot be empty".to_string());
        }
        write_model_env(env_path, model, writer)?;
        return Ok(Some(model.to_string()));
    }

    if let Some(existing) = crate::env_file::get(env_path, "BLYTE_MODEL")? {
        writeln!(writer, "BLYTE_MODEL={existing} (in {})", env_path.display())
            .map_err(|e| e.to_string())?;
        return Ok(Some(existing));
    }

    if !is_terminal {
        return Ok(None);
    }

    let chosen = prompt_model(reader, writer)?;
    write_model_env(env_path, &chosen, writer)?;
    Ok(Some(chosen))
}