Skip to main content

blyte_cli/
init.rs

1//! `blyte init`: extracts the gate from CI workflows, detects environment settings,
2//! and proves each step in a fresh worktree before writing `blyte.toml`.
3
4use std::collections::{BTreeMap, HashSet, VecDeque};
5use std::path::{Path, PathBuf};
6use std::process::Command;
7use std::time::Duration;
8
9use crate::cli::InitArgs;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum Verdict {
13    Passed,
14    Environment(String),
15    Failed,
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct InitStep {
20    pub command: String,
21    pub source: String,
22    pub verdict: Option<Verdict>,
23}
24
25/// Detect check commands from `.github/workflows/*.yml` and `*.yaml`.
26pub fn detect_ci(root: &Path) -> Vec<String> {
27    drop_overlapping(
28        detect_ci_with_sources(root)
29            .into_iter()
30            .map(|(cmd, _)| cmd)
31            .collect(),
32    )
33}
34
35/// Detect check commands and keep the file name of the workflow where each was first found.
36pub fn detect_ci_with_sources(root: &Path) -> Vec<(String, String)> {
37    let workflows_dir = root.join(".github").join("workflows");
38    if !workflows_dir.is_dir() {
39        return Vec::new();
40    }
41    let mut files = Vec::new();
42    if let Ok(entries) = std::fs::read_dir(&workflows_dir) {
43        for entry in entries.flatten() {
44            let path = entry.path();
45            if path.is_file() {
46                if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
47                    if ext == "yml" || ext == "yaml" {
48                        files.push(path);
49                    }
50                }
51            }
52        }
53    }
54    files.sort_by(|a, b| a.file_name().cmp(&b.file_name()));
55
56    let mut result = Vec::new();
57    let mut seen = HashSet::new();
58
59    for file in files {
60        let file_name = file
61            .file_name()
62            .and_then(|f| f.to_str())
63            .unwrap_or_default()
64            .to_string();
65        if let Ok(content) = std::fs::read_to_string(&file) {
66            let cmds = parse_workflow_commands(&content);
67            for cmd in cmds {
68                if seen.insert(cmd.clone()) {
69                    result.push((cmd, file_name.clone()));
70                }
71            }
72        }
73    }
74    result
75}
76
77#[derive(Debug)]
78struct PytestInfo {
79    prefix: String,
80    runner: String,
81    positional: Vec<String>,
82    narrowness: usize,
83}
84
85fn parse_pytest_step(cmd: &str) -> Option<PytestInfo> {
86    let trimmed = cmd.trim();
87    let prefixes = ["uv run ", "poetry run ", "pdm run ", "pipenv run "];
88    let (prefix, after_prefix) = if let Some(p) = prefixes.iter().find(|&&p| trimmed.starts_with(p))
89    {
90        (*p, &trimmed[p.len()..])
91    } else {
92        ("", trimmed)
93    };
94
95    let runners = ["python3 -m pytest", "python -m pytest", "pytest"];
96    let (runner, rest) = runners.iter().find_map(|&r| {
97        if after_prefix == r {
98            Some((r, ""))
99        } else if let Some(rest) = after_prefix.strip_prefix(r) {
100            if rest.starts_with(char::is_whitespace) {
101                Some((r, rest.trim_start()))
102            } else {
103                None
104            }
105        } else {
106            None
107        }
108    })?;
109
110    let tokens = tokenize(rest);
111    let mut positional = Vec::new();
112    let mut narrowness = 0;
113    let mut i = 0;
114
115    while i < tokens.len() {
116        let tok = &tokens[i];
117        if tok == "--" {
118            i += 1;
119            while i < tokens.len() {
120                positional.push(tokens[i].clone());
121                i += 1;
122            }
123            break;
124        }
125
126        if tok == "-m" || tok == "-k" {
127            narrowness += 1;
128            i += 1;
129            if i < tokens.len() {
130                narrowness += tokens[i].matches(" and ").count();
131                i += 1;
132            }
133        } else if tok.starts_with("-m=") || tok.starts_with("-k=") {
134            narrowness += 1;
135            let val = &tok[3..];
136            narrowness += val.matches(" and ").count();
137            i += 1;
138        } else if tok == "--ignore" || tok == "--deselect" {
139            narrowness += 1;
140            i += 1;
141            if i < tokens.len() {
142                i += 1;
143            }
144        } else if tok.starts_with("--ignore=") || tok.starts_with("--deselect=") {
145            narrowness += 1;
146            i += 1;
147        } else if tok == "-p" {
148            i += 1;
149            if i < tokens.len() {
150                i += 1;
151            }
152        } else if tok.starts_with('-') {
153            i += 1;
154        } else {
155            positional.push(tok.clone());
156            i += 1;
157        }
158    }
159
160    Some(PytestInfo {
161        prefix: prefix.to_string(),
162        runner: runner.to_string(),
163        positional,
164        narrowness,
165    })
166}
167
168/// Drop overlapping pytest steps, keeping only the broader of two that test the same files.
169pub fn drop_overlapping(steps: Vec<String>) -> Vec<String> {
170    let n = steps.len();
171    if n <= 1 {
172        return steps;
173    }
174
175    let parsed: Vec<Option<PytestInfo>> = steps.iter().map(|s| parse_pytest_step(s)).collect();
176
177    let mut adj = vec![Vec::new(); n];
178    for i in 0..n {
179        let Some(ref a) = parsed[i] else { continue };
180        for j in (i + 1)..n {
181            let Some(ref b) = parsed[j] else { continue };
182            if a.prefix == b.prefix
183                && a.runner == b.runner
184                && (a.positional == b.positional
185                    || a.positional.is_empty()
186                    || b.positional.is_empty())
187            {
188                adj[i].push(j);
189                adj[j].push(i);
190            }
191        }
192    }
193
194    let mut visited = vec![false; n];
195    let mut result_slots: Vec<Option<String>> = vec![None; n];
196
197    for i in 0..n {
198        if visited[i] {
199            continue;
200        }
201        visited[i] = true;
202        let mut comp = vec![i];
203        let mut q = VecDeque::new();
204        q.push_back(i);
205        while let Some(u) = q.pop_front() {
206            for &v in &adj[u] {
207                if !visited[v] {
208                    visited[v] = true;
209                    comp.push(v);
210                    q.push_back(v);
211                }
212            }
213        }
214
215        if comp.len() == 1 {
216            result_slots[i] = Some(steps[i].clone());
217        } else {
218            let first_pos = *comp.iter().min().unwrap();
219            let best = *comp
220                .iter()
221                .min_by(|&&a, &&b| {
222                    let na = parsed[a].as_ref().unwrap().narrowness;
223                    let nb = parsed[b].as_ref().unwrap().narrowness;
224                    na.cmp(&nb).then_with(|| a.cmp(&b))
225                })
226                .unwrap();
227            result_slots[first_pos] = Some(steps[best].clone());
228        }
229    }
230
231    result_slots.into_iter().flatten().collect()
232}
233
234fn parse_workflow_commands(content: &str) -> Vec<String> {
235    let lines: Vec<&str> = content.lines().collect();
236    let mut i = 0;
237    let mut candidate_commands = Vec::new();
238
239    while i < lines.len() {
240        let line = lines[i];
241        let trimmed_start = line.trim_start();
242
243        let is_run_key = if let Some(rest) = trimmed_start.strip_prefix("- ") {
244            rest.trim_start().starts_with("run:")
245        } else {
246            trimmed_start.starts_with("run:")
247        };
248
249        // The pre-commit action is a `uses:` step, not a `run:`; its default is every file.
250        let uses = trimmed_start
251            .strip_prefix("- ")
252            .unwrap_or(trimmed_start)
253            .trim_start();
254        if uses.starts_with("uses: pre-commit/action@") {
255            candidate_commands.push("pre-commit run --all-files".to_string());
256        }
257
258        if is_run_key {
259            let run_idx = line.find("run:").unwrap();
260            let after_run = line[run_idx + 4..].trim();
261            let after_run_clean = if let Some(hash) = after_run.find('#') {
262                after_run[..hash].trim()
263            } else {
264                after_run
265            };
266
267            if after_run_clean.starts_with('|') || after_run_clean.starts_with('>') {
268                let mut block_lines = Vec::new();
269                i += 1;
270                while i < lines.len() {
271                    let next_line = lines[i];
272                    let next_trimmed = next_line.trim();
273                    if next_trimmed.is_empty() {
274                        block_lines.push(next_line);
275                        i += 1;
276                        continue;
277                    }
278                    let leading_spaces =
279                        next_line.chars().take_while(|c| c.is_whitespace()).count();
280                    if leading_spaces <= run_idx {
281                        break;
282                    }
283                    block_lines.push(next_line);
284                    i += 1;
285                }
286
287                let joined = join_continuation_lines(&block_lines);
288                for cmd in joined {
289                    candidate_commands.push(cmd);
290                }
291                continue;
292            } else if !after_run_clean.is_empty() {
293                let mut cmd_str = after_run_clean;
294                if (cmd_str.starts_with('"') && cmd_str.ends_with('"'))
295                    || (cmd_str.starts_with('\'') && cmd_str.ends_with('\''))
296                {
297                    cmd_str = &cmd_str[1..cmd_str.len() - 1];
298                }
299                candidate_commands.push(cmd_str.to_string());
300            }
301        }
302        i += 1;
303    }
304
305    // A CI line often chains setup and the check (`mkdir -p out && uv run pytest`): each part
306    // is judged on its own.
307    let mut result = Vec::new();
308    for cmd in candidate_commands {
309        for part in split_chain(&cmd) {
310            if let Some(kept) = filter_and_clean_command(&part) {
311                result.push(kept);
312            }
313        }
314    }
315    result
316}
317
318/// Split a shell line on `&&`, `||` and `;` outside quotes.
319fn split_chain(cmd: &str) -> Vec<String> {
320    let mut parts = Vec::new();
321    let mut current = String::new();
322    let mut quote: Option<char> = None;
323    let chars: Vec<char> = cmd.chars().collect();
324    let mut i = 0;
325    while i < chars.len() {
326        let c = chars[i];
327        if let Some(q) = quote {
328            current.push(c);
329            if c == q {
330                quote = None;
331            }
332        } else if c == '"' || c == '\'' {
333            quote = Some(c);
334            current.push(c);
335        } else if (c == '&' || c == '|') && chars.get(i + 1) == Some(&c) {
336            parts.push(std::mem::take(&mut current));
337            i += 1;
338        } else if c == ';' {
339            parts.push(std::mem::take(&mut current));
340        } else {
341            current.push(c);
342        }
343        i += 1;
344    }
345    parts.push(current);
346    parts
347        .into_iter()
348        .map(|p| p.trim().to_string())
349        .filter(|p| !p.is_empty())
350        .collect()
351}
352
353fn join_continuation_lines(lines: &[&str]) -> Vec<String> {
354    let mut result = Vec::new();
355    let mut current = String::new();
356
357    for line in lines {
358        let trimmed = line.trim();
359        if trimmed.is_empty() {
360            if !current.is_empty() {
361                result.push(current);
362                current = String::new();
363            }
364            continue;
365        }
366
367        if let Some(stripped) = trimmed.strip_suffix('\\') {
368            let without_bs = stripped.trim_end();
369            if current.is_empty() {
370                current.push_str(without_bs);
371            } else {
372                current.push(' ');
373                current.push_str(without_bs);
374            }
375        } else if current.is_empty() {
376            result.push(trimmed.to_string());
377        } else {
378            current.push(' ');
379            current.push_str(trimmed);
380            result.push(current);
381            current = String::new();
382        }
383    }
384    if !current.is_empty() {
385        result.push(current);
386    }
387    result
388}
389
390fn filter_and_clean_command(cmd: &str) -> Option<String> {
391    let trimmed = cmd.trim();
392    let prefixes = [
393        "uv run ",
394        "poetry run ",
395        "pdm run ",
396        "npx ",
397        "pipenv run ",
398        "pnpm exec ",
399        "bunx ",
400    ];
401    let mut stripped = trimmed;
402    for p in &prefixes {
403        if stripped.starts_with(p) {
404            stripped = &stripped[p.len()..];
405            break;
406        }
407    }
408
409    let check_cmds = [
410        "pytest",
411        "python -m pytest",
412        "python3 -m pytest",
413        "python -m unittest",
414        "python3 -m unittest",
415        "tox",
416        "nox",
417        "ruff",
418        "pyright",
419        "mypy",
420        "black",
421        "isort",
422        "pre-commit run",
423        "cargo fmt",
424        "cargo clippy",
425        "cargo test",
426        "go test",
427        "go vet",
428        "golangci-lint",
429        "npm test",
430        "npm run lint",
431        "npm run typecheck",
432        "pnpm test",
433        "pnpm run lint",
434        "yarn test",
435        "yarn lint",
436        "make check",
437        "make lint",
438        "make test",
439        "make typecheck",
440        "make validate",
441        "eslint",
442        "vitest",
443        "jest",
444        "tsc",
445    ];
446
447    let is_check = check_cmds.iter().any(|&c| {
448        if stripped == c {
449            true
450        } else if let Some(rest) = stripped.strip_prefix(c) {
451            rest.starts_with(char::is_whitespace)
452        } else {
453            false
454        }
455    });
456
457    if !is_check {
458        return None;
459    }
460
461    let text = if let Some(idx) = trimmed.find("| tee") {
462        &trimmed[..idx]
463    } else {
464        trimmed
465    };
466
467    // Reporting options go, with their value when it is a separate word (`--cov-report xml:out`).
468    let tokens = tokenize(text);
469    let mut kept_tokens: Vec<String> = Vec::new();
470    let mut iter = tokens.into_iter().peekable();
471    while let Some(tok) = iter.next() {
472        let reporting = ["--cov", "--junitxml", "--junit-xml"]
473            .iter()
474            .any(|o| tok.starts_with(o));
475        if !reporting {
476            kept_tokens.push(tok);
477            continue;
478        }
479        // These always take a value; a bare `--cov` takes one unless it is the last word.
480        let value_follows = iter.peek().is_some_and(|n| !n.starts_with('-'));
481        let always = matches!(tok.as_str(), "--cov-report" | "--junitxml" | "--junit-xml");
482        if value_follows && (always || (tok == "--cov" && iter.len() > 1)) {
483            iter.next();
484        }
485    }
486
487    Some(kept_tokens.join(" "))
488}
489
490fn tokenize(s: &str) -> Vec<String> {
491    let mut tokens = Vec::new();
492    let mut current = String::new();
493    let mut in_quote = None;
494
495    for ch in s.chars() {
496        match in_quote {
497            Some(q) => {
498                current.push(ch);
499                if ch == q {
500                    in_quote = None;
501                }
502            }
503            None => {
504                if ch == '"' || ch == '\'' {
505                    in_quote = Some(ch);
506                    current.push(ch);
507                } else if ch.is_whitespace() {
508                    if !current.is_empty() {
509                        tokens.push(current);
510                        current = String::new();
511                    }
512                } else {
513                    current.push(ch);
514                }
515            }
516        }
517    }
518    if !current.is_empty() {
519        tokens.push(current);
520    }
521    tokens
522}
523
524/// Detect repository environment settings (such as UV_FROZEN and UV_OFFLINE).
525pub fn detect_env(root: &Path) -> BTreeMap<String, String> {
526    let mut map = BTreeMap::new();
527    if root.join("uv.lock").exists() {
528        map.insert("UV_FROZEN".to_string(), "1".to_string());
529        if let Ok(content) = std::fs::read_to_string(root.join("pyproject.toml")) {
530            if let Ok(parsed) = content.parse::<toml::Value>() {
531                if let Some(tool) = parsed.get("tool").and_then(|t| t.get("uv")) {
532                    if let Some(indexes) = tool.get("index").and_then(|i| i.as_array()) {
533                        for idx in indexes {
534                            if let Some(url) = idx.get("url").and_then(|u| u.as_str()) {
535                                if !url.contains("pypi.org") {
536                                    map.insert("UV_OFFLINE".to_string(), "1".to_string());
537                                    break;
538                                }
539                            }
540                        }
541                    }
542                }
543            }
544        }
545    }
546    map
547}
548
549/// Propose a worktree setup command when the repository uses a supported package manager.
550pub fn detect_setup(root: &Path) -> Option<String> {
551    if root.join("uv.lock").exists() {
552        Some("uv sync".to_string())
553    } else {
554        None
555    }
556}
557
558/// Classify step output into Passed, Environment problem, or Failed.
559pub fn classify(output: &str, exit_code: i32) -> Verdict {
560    if exit_code == 0 {
561        return Verdict::Passed;
562    }
563
564    let uv_patterns = [
565        "network connectivity is disabled",
566        "wasn't found in the cache",
567    ];
568
569    // Words, not bare status codes: a test named `test_403_…` is not a 403.
570    let patterns = [
571        "unauthorized",
572        "forbidden",
573        "not found in the package registry",
574        "could not resolve host",
575        "network is unreachable",
576        "connection refused",
577        "operation not permitted",
578        "command not found",
579        "no such file or directory",
580    ];
581
582    for line in output.lines() {
583        // Test ids and result lines (`tests/x.py::test_y PASSED`) name tests, not the environment.
584        if line.contains("::") {
585            continue;
586        }
587        let lower = line.to_ascii_lowercase();
588        let is_uv = uv_patterns.iter().any(|&p| lower.contains(p));
589        if is_uv || patterns.iter().any(|&p| lower.contains(p)) {
590            let trimmed = line.trim();
591            let mut s: String = if trimmed.chars().count() > 120 {
592                trimmed.chars().take(120).collect()
593            } else {
594                trimmed.to_string()
595            };
596            if is_uv {
597                s.push_str(
598                    " (run `uv sync` once online to fill uv's cache, then blyte init again)",
599                );
600            }
601            return Verdict::Environment(s);
602        }
603    }
604
605    Verdict::Failed
606}
607
608/// Render the verified blyte.toml content.
609pub fn render_verified(
610    steps: &[InitStep],
611    env: &BTreeMap<String, String>,
612    setup: Option<&str>,
613    setup_passed: bool,
614) -> String {
615    let mut out = String::new();
616    out.push_str("# blyte.toml: how this repository's work is checked, for `blyte dispatch`.\n");
617
618    let mut kept_steps = Vec::new();
619    for step in steps {
620        let comment_suffix = match &step.verdict {
621            Some(Verdict::Passed) => "passed".to_string(),
622            Some(Verdict::Failed) => "failed on HEAD: fix it before dispatching".to_string(),
623            Some(Verdict::Environment(reason)) => format!("left out: {reason}"),
624            None => "not verified".to_string(),
625        };
626        out.push_str(&format!(
627            "# {}: from {}, {}\n",
628            step.command, step.source, comment_suffix
629        ));
630
631        if !matches!(step.verdict, Some(Verdict::Environment(_))) {
632            kept_steps.push(step.command.as_str());
633        }
634    }
635
636    let mut gate_str = String::new();
637    for step in &kept_steps {
638        gate_str.push_str(step);
639        gate_str.push('\n');
640    }
641
642    out.push_str("[dispatch]\n");
643    if let Some(s) = setup {
644        if setup_passed {
645            out.push_str("# prepares each new worktree before the implementer starts\n");
646            out.push_str(&format!("setup = \"{s}\"\n"));
647        } else {
648            out.push_str(&format!(
649                "# setup = \"{s}\"   # left out: failed in a fresh worktree\n"
650            ));
651        }
652    }
653    out.push_str("gate = \"\"\"\n");
654    out.push_str(&gate_str);
655    out.push_str("\"\"\"\n");
656    out.push_str("# model = \"gemini-3.8-flash-high\"\n");
657    out.push_str("max_seconds = 3600\n");
658    out.push_str("max_turns = 300\n");
659    out.push_str("# max_cost = 2.0\n");
660    out.push_str("# network = \"on\"\n");
661    out.push_str("# fold_budget = 60000\n\n");
662
663    if !env.is_empty() {
664        out.push_str("[dispatch.env]\n");
665        out.push_str("# for every command and the gate; never credentials\n");
666        for (k, v) in env {
667            out.push_str(&format!("{k} = \"{v}\"\n"));
668        }
669    } else {
670        out.push_str("# [dispatch.env]\n");
671        out.push_str(
672            "# UV_FROZEN = \"1\"   # settings for every command and the gate; never credentials\n",
673        );
674    }
675
676    out
677}
678
679/// What to show of a failing step: the test runner's own summary lines when it printed any
680/// (`FAILED …`, `ERROR …`, `== 2 failed, 900 passed ==`), else the last lines. A tail alone can be
681/// all shutdown noise.
682pub fn failure_excerpt(text: &str) -> Vec<&str> {
683    let summary: Vec<&str> = text
684        .lines()
685        .filter(|l| {
686            let t = l.trim_start();
687            // pytest's summary lines name a test file; a logger's `ERROR …` line does not.
688            let names_test = t.contains("::") || t.contains(".py");
689            ((t.starts_with("FAILED ") || t.starts_with("ERROR ")) && names_test)
690                || (t.starts_with('=') && (t.contains(" failed") || t.contains(" error")))
691        })
692        .collect();
693    let lines: Vec<&str> = if summary.is_empty() {
694        text.lines().collect()
695    } else {
696        summary
697    };
698    lines[lines.len().saturating_sub(15)..].to_vec()
699}
700
701/// Remove `.wt/init-<pid>` worktrees left by an init that was killed (its process is gone).
702fn remove_stale_init_worktrees(root: &Path) {
703    let Ok(entries) = std::fs::read_dir(root.join(".wt")) else {
704        return;
705    };
706    for entry in entries.flatten() {
707        let name = entry.file_name().to_string_lossy().to_string();
708        let Some(pid) = name
709            .strip_prefix("init-")
710            .and_then(|p| p.parse::<i32>().ok())
711        else {
712            continue;
713        };
714        if unsafe { libc::kill(pid, 0) } != 0 {
715            let _ = Command::new("git")
716                .args(["worktree", "remove", "--force"])
717                .arg(entry.path())
718                .current_dir(root)
719                .output();
720        }
721    }
722    let _ = Command::new("git")
723        .args(["worktree", "prune"])
724        .current_dir(root)
725        .output();
726}
727
728fn verify_steps(
729    root: &Path,
730    mut steps: Vec<InitStep>,
731    env: &BTreeMap<String, String>,
732    sandbox_on: bool,
733    timeout: Duration,
734    setup: Option<&str>,
735) -> (Vec<InitStep>, bool) {
736    let common_dir_raw = Command::new("git")
737        .args(["rev-parse", "--git-common-dir"])
738        .current_dir(root)
739        .output();
740    let common_dir = if let Ok(out) = common_dir_raw {
741        let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
742        if p.is_absolute() {
743            p
744        } else {
745            root.join(p)
746        }
747    } else {
748        root.join(".git")
749    };
750    let exclude_path = common_dir.join("info").join("exclude");
751    if let Some(parent) = exclude_path.parent() {
752        let _ = std::fs::create_dir_all(parent);
753    }
754    let content = std::fs::read_to_string(&exclude_path).unwrap_or_default();
755    if !content.lines().any(|l| l.trim() == ".wt/") {
756        let mut new_content = content;
757        if !new_content.is_empty() && !new_content.ends_with('\n') {
758            new_content.push('\n');
759        }
760        new_content.push_str(".wt/\n");
761        let _ = std::fs::write(&exclude_path, new_content);
762    }
763
764    remove_stale_init_worktrees(root);
765    let pid = std::process::id();
766    let wt_dir = root.join(".wt").join(format!("init-{}", pid));
767    let _ = std::fs::create_dir_all(root.join(".wt"));
768
769    let add_out = Command::new("git")
770        .args(["worktree", "add", "--detach"])
771        .arg(&wt_dir)
772        .arg("HEAD")
773        .current_dir(root)
774        .output();
775
776    if let Ok(o) = add_out {
777        if !o.status.success() {
778            eprintln!(
779                "warning: git worktree add failed: {}; skipping verification",
780                String::from_utf8_lossy(&o.stderr)
781            );
782            return (steps, false);
783        }
784    } else {
785        eprintln!("warning: failed to run git worktree add; skipping verification");
786        return (steps, false);
787    }
788
789    struct Guard<'a> {
790        root: &'a Path,
791        wt_dir: PathBuf,
792    }
793    impl<'a> Drop for Guard<'a> {
794        fn drop(&mut self) {
795            let _ = Command::new("git")
796                .args(["worktree", "remove", "--force"])
797                .arg(&self.wt_dir)
798                .current_dir(self.root)
799                .output();
800        }
801    }
802    let _guard = Guard {
803        root,
804        wt_dir: wt_dir.clone(),
805    };
806
807    for (k, v) in env {
808        std::env::set_var(k, v);
809    }
810
811    let mut setup_passed = false;
812    if let Some(cmd) = setup {
813        let log_path = wt_dir
814            .parent()
815            .unwrap_or(root)
816            .join(format!("init-{pid}.setup.log"));
817        match crate::setup::run_setup(
818            cmd,
819            &wt_dir,
820            root,
821            env,
822            &log_path,
823            crate::setup::SETUP_TIMEOUT,
824        ) {
825            Ok(()) => {
826                setup_passed = true;
827            }
828            Err(msg) => {
829                eprintln!("warning: setup failed; left out of blyte.toml:\n{msg}");
830            }
831        }
832    }
833
834    use blyte_agent::shell::Shell;
835    let shell = if sandbox_on {
836        let profile = blyte_agent::sandbox::default_profile_net(&wt_dir, &[], true);
837        blyte_agent::shell::LocalShell::sandboxed(profile)
838    } else {
839        blyte_agent::shell::LocalShell::new()
840    };
841
842    for step in &mut steps {
843        let start = std::time::Instant::now();
844        let res = shell.exec(&step.command, &wt_dir, timeout);
845        let elapsed = start.elapsed().as_secs();
846
847        // A run that could not finish (a timeout, say) counts as failing, with its error as output.
848        let (text, code) = match res {
849            Ok(output) => (output.merged(), output.exit_code),
850            Err(e) => (e, 1),
851        };
852        let verdict = classify(&text, code);
853        match &verdict {
854            Verdict::Passed => eprintln!("init: {} ... passed ({}s)", step.command, elapsed),
855            Verdict::Environment(reason) => {
856                eprintln!("init: {} ... left out: {}", step.command, reason)
857            }
858            Verdict::Failed => {
859                eprintln!("init: {} ... failed on HEAD ({}s)", step.command, elapsed);
860                for l in failure_excerpt(&text) {
861                    eprintln!("init:   | {l}");
862                }
863            }
864        }
865        step.verdict = Some(verdict);
866    }
867
868    (steps, setup_passed)
869}
870
871pub fn run(args: &InitArgs) -> i32 {
872    let out = Command::new("git")
873        .args(["rev-parse", "--show-toplevel"])
874        .output();
875    let Ok(out) = out else {
876        eprintln!("error: git not found");
877        return 2;
878    };
879    if !out.status.success() {
880        eprintln!("error: not a git repository");
881        return 2;
882    }
883    let root = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
884    let toml_path = root.join("blyte.toml");
885
886    if !args.print && toml_path.exists() && !args.force {
887        eprintln!("blyte.toml already exists; pass --force to overwrite");
888        return 1;
889    }
890
891    let ci_steps = detect_ci_with_sources(&root);
892    let (steps, from_ci) = if !ci_steps.is_empty() {
893        let commands: Vec<String> = ci_steps.iter().map(|(cmd, _)| cmd.clone()).collect();
894        let kept = drop_overlapping(commands);
895        (
896            kept.into_iter()
897                .map(|cmd| {
898                    let src = ci_steps
899                        .iter()
900                        .find(|(c, _)| c == &cmd)
901                        .map(|(_, s)| s.clone())
902                        .unwrap_or_default();
903                    InitStep {
904                        command: cmd,
905                        source: src,
906                        verdict: None,
907                    }
908                })
909                .collect::<Vec<_>>(),
910            true,
911        )
912    } else {
913        let detected = crate::config::detect(&root);
914        (
915            detected
916                .into_iter()
917                .map(|cmd| InitStep {
918                    command: cmd,
919                    source: "detected".to_string(),
920                    verdict: None,
921                })
922                .collect::<Vec<_>>(),
923            false,
924        )
925    };
926
927    if steps.is_empty() {
928        eprintln!(
929            "no toolchain detected: write blyte.toml by hand (see blyte init --print for the format)"
930        );
931        return 1;
932    }
933
934    let env = detect_env(&root);
935    let setup = detect_setup(&root);
936
937    let (mut verified_steps, mut setup_passed) = if !args.no_verify {
938        verify_steps(
939            &root,
940            steps,
941            &env,
942            args.sandbox == "on",
943            Duration::from_secs(args.step_timeout),
944            setup.as_deref(),
945        )
946    } else {
947        (steps, setup.is_some())
948    };
949
950    if from_ci && !args.no_verify {
951        let any_passed = verified_steps
952            .iter()
953            .any(|s| matches!(s.verdict, Some(Verdict::Passed)));
954        if !any_passed {
955            let detected = crate::config::detect(&root);
956            let not_all_identical = !detected.is_empty()
957                && !detected
958                    .iter()
959                    .all(|d| verified_steps.iter().any(|s| &s.command == d));
960            if not_all_identical {
961                eprintln!(
962                    "init: every step from CI failed or was left out; trying the checks detected from the repository"
963                );
964                let detected_steps: Vec<InitStep> = detected
965                    .into_iter()
966                    .map(|cmd| InitStep {
967                        command: cmd,
968                        source: "detected".to_string(),
969                        verdict: None,
970                    })
971                    .collect();
972                let (verified_detected, detected_setup_passed) = verify_steps(
973                    &root,
974                    detected_steps,
975                    &env,
976                    args.sandbox == "on",
977                    Duration::from_secs(args.step_timeout),
978                    setup.as_deref(),
979                );
980                if verified_detected
981                    .iter()
982                    .any(|s| matches!(s.verdict, Some(Verdict::Passed)))
983                {
984                    verified_steps = verified_detected;
985                    setup_passed = detected_setup_passed;
986                }
987            }
988        }
989    }
990
991    let kept_count = verified_steps
992        .iter()
993        .filter(|s| !matches!(s.verdict, Some(Verdict::Environment(_))))
994        .count();
995
996    if kept_count == 0 {
997        eprintln!("error: every step was left out due to environment issues");
998        for step in &verified_steps {
999            if let Some(Verdict::Environment(ref r)) = step.verdict {
1000                eprintln!("  `{}` left out: {r}", step.command);
1001            }
1002        }
1003        return 1;
1004    }
1005
1006    let rendered = render_verified(&verified_steps, &env, setup.as_deref(), setup_passed);
1007
1008    if args.print {
1009        print!("{rendered}");
1010    } else {
1011        if let Err(e) = std::fs::write(&toml_path, &rendered) {
1012            eprintln!("error writing {}: {e}", toml_path.display());
1013            return 1;
1014        }
1015        println!("wrote {}", toml_path.display());
1016        for step in &verified_steps {
1017            if !matches!(step.verdict, Some(Verdict::Environment(_))) {
1018                println!("{}", step.command);
1019            }
1020        }
1021    }
1022
1023    let any_failed = verified_steps
1024        .iter()
1025        .any(|s| matches!(s.verdict, Some(Verdict::Failed)));
1026
1027    if any_failed {
1028        for s in &verified_steps {
1029            if matches!(s.verdict, Some(Verdict::Failed)) {
1030                eprintln!(
1031                    "warning: step `{}` failed on HEAD: fix it before dispatching",
1032                    s.command
1033                );
1034            }
1035        }
1036        3
1037    } else {
1038        0
1039    }
1040}