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 mut result = Vec::new();
38    let mut seen = HashSet::new();
39
40    for (file_name, content) in read_workflow_files(root) {
41        let (cmds, _, _) = parse_workflow(&content);
42        for cmd in cmds {
43            if seen.insert(cmd.clone()) {
44                result.push((cmd, file_name.clone()));
45            }
46        }
47    }
48    result
49}
50
51/// Detect per-directory `uv sync` setup commands from `.github/workflows/*.yml` and `*.yaml`.
52pub fn detect_ci_setup(root: &Path) -> Vec<String> {
53    let mut result = Vec::new();
54    let mut seen = HashSet::new();
55
56    for (_, content) in read_workflow_files(root) {
57        let (_, setup_cmds, _) = parse_workflow(&content);
58        for cmd in setup_cmds {
59            if seen.insert(cmd.clone()) {
60                result.push(cmd);
61            }
62        }
63    }
64    result
65}
66
67/// Detect check commands that were left out because they depend on CI expressions or unknown matrix keys.
68pub fn detect_ci_left_out(root: &Path) -> Vec<(String, String, String)> {
69    let mut result = Vec::new();
70    let mut seen = HashSet::new();
71
72    for (file_name, content) in read_workflow_files(root) {
73        let (_, _, left_out) = parse_workflow(&content);
74        for (cmd, reason) in left_out {
75            if seen.insert(cmd.clone()) {
76                result.push((cmd, file_name.clone(), reason));
77            }
78        }
79    }
80    result
81}
82
83fn read_workflow_files(root: &Path) -> Vec<(String, String)> {
84    let workflows_dir = root.join(".github").join("workflows");
85    if !workflows_dir.is_dir() {
86        return Vec::new();
87    }
88    let mut files = Vec::new();
89    if let Ok(entries) = std::fs::read_dir(&workflows_dir) {
90        for entry in entries.flatten() {
91            let path = entry.path();
92            if path.is_file() {
93                if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
94                    if ext == "yml" || ext == "yaml" {
95                        files.push(path);
96                    }
97                }
98            }
99        }
100    }
101    files.sort_by(|a, b| a.file_name().cmp(&b.file_name()));
102
103    let mut out = Vec::new();
104    for file in files {
105        let file_name = file
106            .file_name()
107            .and_then(|f| f.to_str())
108            .unwrap_or_default()
109            .to_string();
110        if let Ok(content) = std::fs::read_to_string(&file) {
111            out.push((file_name, content));
112        }
113    }
114    out
115}
116
117#[derive(Debug)]
118struct PytestInfo {
119    prefix: String,
120    runner: String,
121    positional: Vec<String>,
122    narrowness: usize,
123}
124
125fn parse_pytest_step(cmd: &str) -> Option<PytestInfo> {
126    let trimmed = cmd.trim();
127    let prefixes = ["uv run ", "poetry run ", "pdm run ", "pipenv run "];
128    let (prefix, after_prefix) = if let Some(p) = prefixes.iter().find(|&&p| trimmed.starts_with(p))
129    {
130        (*p, &trimmed[p.len()..])
131    } else {
132        ("", trimmed)
133    };
134
135    let runners = ["python3 -m pytest", "python -m pytest", "pytest"];
136    let (runner, rest) = runners.iter().find_map(|&r| {
137        if after_prefix == r {
138            Some((r, ""))
139        } else if let Some(rest) = after_prefix.strip_prefix(r) {
140            if rest.starts_with(char::is_whitespace) {
141                Some((r, rest.trim_start()))
142            } else {
143                None
144            }
145        } else {
146            None
147        }
148    })?;
149
150    let tokens = tokenize(rest);
151    let mut positional = Vec::new();
152    let mut narrowness = 0;
153    let mut i = 0;
154
155    while i < tokens.len() {
156        let tok = &tokens[i];
157        if tok == "--" {
158            i += 1;
159            while i < tokens.len() {
160                positional.push(tokens[i].clone());
161                i += 1;
162            }
163            break;
164        }
165
166        if tok == "-m" || tok == "-k" {
167            narrowness += 1;
168            i += 1;
169            if i < tokens.len() {
170                narrowness += tokens[i].matches(" and ").count();
171                i += 1;
172            }
173        } else if tok.starts_with("-m=") || tok.starts_with("-k=") {
174            narrowness += 1;
175            let val = &tok[3..];
176            narrowness += val.matches(" and ").count();
177            i += 1;
178        } else if tok == "--ignore" || tok == "--deselect" {
179            narrowness += 1;
180            i += 1;
181            if i < tokens.len() {
182                i += 1;
183            }
184        } else if tok.starts_with("--ignore=") || tok.starts_with("--deselect=") {
185            narrowness += 1;
186            i += 1;
187        } else if tok == "-p" {
188            i += 1;
189            if i < tokens.len() {
190                i += 1;
191            }
192        } else if tok.starts_with('-') {
193            i += 1;
194        } else {
195            positional.push(tok.clone());
196            i += 1;
197        }
198    }
199
200    Some(PytestInfo {
201        prefix: prefix.to_string(),
202        runner: runner.to_string(),
203        positional,
204        narrowness,
205    })
206}
207
208/// Drop overlapping pytest steps, keeping only the broader of two that test the same files.
209pub fn drop_overlapping(steps: Vec<String>) -> Vec<String> {
210    let n = steps.len();
211    if n <= 1 {
212        return steps;
213    }
214
215    let parsed: Vec<Option<PytestInfo>> = steps.iter().map(|s| parse_pytest_step(s)).collect();
216
217    let mut adj = vec![Vec::new(); n];
218    for i in 0..n {
219        let Some(ref a) = parsed[i] else { continue };
220        for j in (i + 1)..n {
221            let Some(ref b) = parsed[j] else { continue };
222            if a.prefix == b.prefix
223                && a.runner == b.runner
224                && (a.positional == b.positional
225                    || a.positional.is_empty()
226                    || b.positional.is_empty())
227            {
228                adj[i].push(j);
229                adj[j].push(i);
230            }
231        }
232    }
233
234    let mut visited = vec![false; n];
235    let mut result_slots: Vec<Option<String>> = vec![None; n];
236
237    for i in 0..n {
238        if visited[i] {
239            continue;
240        }
241        visited[i] = true;
242        let mut comp = vec![i];
243        let mut q = VecDeque::new();
244        q.push_back(i);
245        while let Some(u) = q.pop_front() {
246            for &v in &adj[u] {
247                if !visited[v] {
248                    visited[v] = true;
249                    comp.push(v);
250                    q.push_back(v);
251                }
252            }
253        }
254
255        if comp.len() == 1 {
256            result_slots[i] = Some(steps[i].clone());
257        } else {
258            let first_pos = *comp.iter().min().unwrap();
259            let best = *comp
260                .iter()
261                .min_by(|&&a, &&b| {
262                    let na = parsed[a].as_ref().unwrap().narrowness;
263                    let nb = parsed[b].as_ref().unwrap().narrowness;
264                    na.cmp(&nb).then_with(|| a.cmp(&b))
265                })
266                .unwrap();
267            result_slots[first_pos] = Some(steps[best].clone());
268        }
269    }
270
271    result_slots.into_iter().flatten().collect()
272}
273
274#[derive(Default)]
275struct JobContext {
276    matrix: Vec<(String, Vec<String>)>,
277    working_dir: Option<String>,
278    env: BTreeMap<String, String>,
279}
280
281#[derive(Default)]
282struct StepCandidate {
283    job_id: usize,
284    working_dir: Option<String>,
285    env: BTreeMap<String, String>,
286    commands: Vec<String>,
287}
288
289#[derive(Clone, Copy, PartialEq, Eq)]
290enum EnvScope {
291    Workflow,
292    Job,
293    Step,
294}
295
296#[derive(Clone, Copy, PartialEq, Eq)]
297enum DefaultsScope {
298    Workflow,
299    Job,
300}
301
302fn parse_workflow(content: &str) -> (Vec<String>, Vec<String>, Vec<(String, String)>) {
303    let lines: Vec<&str> = content.lines().collect();
304    let mut i = 0;
305    let mut in_jobs = false;
306    let mut job_indent: Option<usize> = None;
307    let mut job_sub_indent: Option<usize> = None;
308    let mut current_job: usize = 0;
309    let mut jobs: Vec<JobContext> = vec![JobContext::default()];
310    let mut workflow_working_dir: Option<String> = None;
311    let mut workflow_env: BTreeMap<String, String> = BTreeMap::new();
312
313    let mut matrix_indent: Option<usize> = None;
314    let mut matrix_key_indent: Option<usize> = None;
315    let mut current_block_key: Option<String> = None;
316
317    let mut steps_indent: Option<usize> = None;
318    let mut current_step_indent: Option<usize> = None;
319    let mut current_step: Option<StepCandidate> = None;
320    let mut candidates: Vec<StepCandidate> = Vec::new();
321
322    let mut env_ctx: Option<(usize, EnvScope)> = None;
323    let mut defaults_ctx: Option<(usize, DefaultsScope, Option<usize>)> = None;
324
325    while i < lines.len() {
326        let line = lines[i];
327        let trimmed_start = line.trim_start();
328        if trimmed_start.is_empty() || trimmed_start.starts_with('#') {
329            i += 1;
330            continue;
331        }
332        let indent = line.chars().take_while(|c| c.is_whitespace()).count();
333        let clean_line = strip_yaml_comment(trimmed_start);
334
335        if let Some((e_indent, _)) = env_ctx {
336            if indent <= e_indent {
337                env_ctx = None;
338            }
339        }
340        if let Some((d_indent, scope, r_indent)) = defaults_ctx {
341            if indent <= d_indent {
342                defaults_ctx = None;
343            } else if let Some(ri) = r_indent {
344                if indent <= ri {
345                    defaults_ctx = Some((d_indent, scope, None));
346                }
347            }
348        }
349        if let Some(s_indent) = steps_indent {
350            if indent < s_indent || (indent == s_indent && !clean_line.starts_with('-')) {
351                if let Some(step) = current_step.take() {
352                    candidates.push(step);
353                }
354                current_step_indent = None;
355                steps_indent = None;
356            }
357        }
358        if let Some(cs_indent) = current_step_indent {
359            if indent < cs_indent || (indent == cs_indent && clean_line.starts_with('-')) {
360                if let Some(step) = current_step.take() {
361                    candidates.push(step);
362                }
363                current_step_indent = None;
364            }
365        }
366
367        if indent == 0 {
368            matrix_indent = None;
369            matrix_key_indent = None;
370            current_block_key = None;
371            if clean_line == "jobs:" {
372                in_jobs = true;
373                job_indent = None;
374                job_sub_indent = None;
375                i += 1;
376                continue;
377            } else {
378                in_jobs = false;
379                job_indent = None;
380                job_sub_indent = None;
381                if let Some(rest) = clean_line.strip_prefix("env:") {
382                    let rest = rest.trim();
383                    if rest.is_empty() {
384                        env_ctx = Some((indent, EnvScope::Workflow));
385                    } else if rest.starts_with('{') && rest.ends_with('}') {
386                        parse_flow_map(&rest[1..rest.len() - 1], &mut workflow_env);
387                    }
388                    i += 1;
389                    continue;
390                } else if clean_line == "defaults:" {
391                    defaults_ctx = Some((indent, DefaultsScope::Workflow, None));
392                    i += 1;
393                    continue;
394                }
395            }
396        } else if in_jobs {
397            if job_indent.is_none() && !clean_line.starts_with('-') && clean_line.contains(':') {
398                job_indent = Some(indent);
399            }
400            if Some(indent) == job_indent
401                && !clean_line.starts_with('-')
402                && clean_line.contains(':')
403            {
404                if let Some(step) = current_step.take() {
405                    candidates.push(step);
406                }
407                current_step_indent = None;
408                steps_indent = None;
409                job_sub_indent = None;
410                current_job += 1;
411                jobs.push(JobContext::default());
412                matrix_indent = None;
413                matrix_key_indent = None;
414                current_block_key = None;
415                i += 1;
416                continue;
417            }
418            if let Some(j_indent) = job_indent {
419                if indent > j_indent
420                    && job_sub_indent.is_none()
421                    && !clean_line.starts_with('-')
422                    && clean_line.contains(':')
423                {
424                    job_sub_indent = Some(indent);
425                }
426            }
427        }
428
429        if let Some((d_indent, scope, r_indent)) = defaults_ctx {
430            if indent > d_indent {
431                if r_indent.is_none() && clean_line == "run:" {
432                    defaults_ctx = Some((d_indent, scope, Some(indent)));
433                } else if let Some(ri) = r_indent {
434                    if indent > ri {
435                        if let Some((k, v)) = clean_line.split_once(':') {
436                            if k.trim() == "working-directory" {
437                                let wd = unquote(v.trim()).to_string();
438                                match scope {
439                                    DefaultsScope::Workflow => workflow_working_dir = Some(wd),
440                                    DefaultsScope::Job => jobs[current_job].working_dir = Some(wd),
441                                }
442                            }
443                        }
444                    }
445                }
446                i += 1;
447                continue;
448            }
449        }
450
451        if let Some((e_indent, scope)) = env_ctx {
452            if indent > e_indent {
453                if !clean_line.starts_with('-') {
454                    if let Some((k, v)) = clean_line.split_once(':') {
455                        let key = k.trim();
456                        let val = unquote(v.trim()).to_string();
457                        if !key.is_empty() {
458                            match scope {
459                                EnvScope::Workflow => {
460                                    workflow_env.insert(key.to_string(), val);
461                                }
462                                EnvScope::Job => {
463                                    jobs[current_job].env.insert(key.to_string(), val);
464                                }
465                                EnvScope::Step => {
466                                    if let Some(ref mut step) = current_step {
467                                        step.env.insert(key.to_string(), val);
468                                    }
469                                }
470                            }
471                        }
472                    }
473                }
474                i += 1;
475                continue;
476            }
477        }
478
479        if let Some(m_indent) = matrix_indent {
480            if indent <= m_indent {
481                matrix_indent = None;
482                matrix_key_indent = None;
483                current_block_key = None;
484            } else {
485                if matrix_key_indent.is_none()
486                    && !clean_line.starts_with('-')
487                    && clean_line.contains(':')
488                {
489                    matrix_key_indent = Some(indent);
490                }
491                if Some(indent) == matrix_key_indent && !clean_line.starts_with('-') {
492                    current_block_key = None;
493                    if let Some((raw_key, raw_val)) = clean_line.split_once(':') {
494                        let key = raw_key.trim();
495                        let val = raw_val.trim();
496                        if key != "include" && key != "exclude" && !key.is_empty() {
497                            if val.starts_with('[') && val.ends_with(']') {
498                                let items = parse_flow_list(&val[1..val.len() - 1]);
499                                set_matrix_key(&mut jobs[current_job].matrix, key, items);
500                            } else if val.is_empty() {
501                                set_matrix_key(&mut jobs[current_job].matrix, key, Vec::new());
502                                current_block_key = Some(key.to_string());
503                            } else {
504                                set_matrix_key(&mut jobs[current_job].matrix, key, Vec::new());
505                            }
506                        }
507                    }
508                    i += 1;
509                    continue;
510                } else if let Some(k_indent) = matrix_key_indent {
511                    if indent >= k_indent {
512                        if let Some(ref key) = current_block_key {
513                            if let Some(item_str) = clean_line.strip_prefix('-') {
514                                let item = item_str.trim();
515                                if !item.is_empty() && !is_yaml_mapping_or_expr(item) {
516                                    let val = unquote(item).to_string();
517                                    push_matrix_val(&mut jobs[current_job].matrix, key, val);
518                                } else {
519                                    set_matrix_key(&mut jobs[current_job].matrix, key, Vec::new());
520                                    current_block_key = None;
521                                }
522                            } else {
523                                set_matrix_key(&mut jobs[current_job].matrix, key, Vec::new());
524                                current_block_key = None;
525                            }
526                        }
527                        i += 1;
528                        continue;
529                    }
530                }
531            }
532        }
533
534        if in_jobs && Some(indent) == job_sub_indent {
535            if let Some(rest) = clean_line.strip_prefix("env:") {
536                let rest = rest.trim();
537                if rest.is_empty() {
538                    env_ctx = Some((indent, EnvScope::Job));
539                } else if rest.starts_with('{') && rest.ends_with('}') {
540                    parse_flow_map(&rest[1..rest.len() - 1], &mut jobs[current_job].env);
541                }
542                i += 1;
543                continue;
544            } else if clean_line == "defaults:" {
545                defaults_ctx = Some((indent, DefaultsScope::Job, None));
546                i += 1;
547                continue;
548            } else if clean_line == "steps:" {
549                steps_indent = Some(indent);
550                i += 1;
551                continue;
552            }
553        }
554
555        if matrix_indent.is_none() && in_jobs && clean_line == "matrix:" {
556            matrix_indent = Some(indent);
557            matrix_key_indent = None;
558            current_block_key = None;
559            i += 1;
560            continue;
561        }
562
563        if steps_indent.is_some() && clean_line.starts_with('-') {
564            let after_dash = clean_line[1..].trim_start();
565            let dash_offset = clean_line.len() - after_dash.len();
566            let step_key_indent = indent + dash_offset;
567            current_step_indent = Some(step_key_indent);
568            current_step = Some(StepCandidate {
569                job_id: current_job,
570                ..Default::default()
571            });
572        }
573
574        let step_clean = if Some(indent) == current_step_indent {
575            Some(clean_line)
576        } else if current_step_indent.is_some() && clean_line.starts_with('-') {
577            let after_dash = clean_line[1..].trim_start();
578            Some(after_dash)
579        } else {
580            None
581        };
582
583        if let Some(sc) = step_clean {
584            if let Some(rest) = sc.strip_prefix("working-directory:") {
585                if let Some(ref mut step) = current_step {
586                    step.working_dir = Some(unquote(rest.trim()).to_string());
587                }
588                i += 1;
589                continue;
590            } else if let Some(rest) = sc.strip_prefix("env:") {
591                let rest = rest.trim();
592                let key_indent = current_step_indent.unwrap_or(indent);
593                if rest.is_empty() {
594                    env_ctx = Some((key_indent, EnvScope::Step));
595                } else if rest.starts_with('{') && rest.ends_with('}') {
596                    if let Some(ref mut step) = current_step {
597                        parse_flow_map(&rest[1..rest.len() - 1], &mut step.env);
598                    }
599                }
600                i += 1;
601                continue;
602            }
603        }
604
605        let is_run_key = if let Some(rest) = trimmed_start.strip_prefix("- ") {
606            rest.trim_start().starts_with("run:")
607        } else {
608            trimmed_start.starts_with("run:")
609        };
610
611        // The pre-commit action is a `uses:` step, not a `run:`; its default is every file.
612        let uses = trimmed_start
613            .strip_prefix("- ")
614            .unwrap_or(trimmed_start)
615            .trim_start();
616        if uses.starts_with("uses: pre-commit/action@") {
617            let cmd = "pre-commit run --all-files".to_string();
618            if let Some(ref mut step) = current_step {
619                step.commands.push(cmd);
620            } else {
621                candidates.push(StepCandidate {
622                    job_id: current_job,
623                    commands: vec![cmd],
624                    ..Default::default()
625                });
626            }
627        }
628
629        if is_run_key {
630            let run_idx = line.find("run:").unwrap();
631            let after_run = line[run_idx + 4..].trim();
632            let after_run_clean = if let Some(hash) = after_run.find('#') {
633                after_run[..hash].trim()
634            } else {
635                after_run
636            };
637
638            if after_run_clean.starts_with('|') || after_run_clean.starts_with('>') {
639                let mut block_lines = Vec::new();
640                i += 1;
641                while i < lines.len() {
642                    let next_line = lines[i];
643                    let next_trimmed = next_line.trim();
644                    if next_trimmed.is_empty() {
645                        block_lines.push(next_line);
646                        i += 1;
647                        continue;
648                    }
649                    let leading_spaces =
650                        next_line.chars().take_while(|c| c.is_whitespace()).count();
651                    if leading_spaces <= run_idx {
652                        break;
653                    }
654                    block_lines.push(next_line);
655                    i += 1;
656                }
657
658                let joined = join_continuation_lines(&block_lines);
659                if let Some(ref mut step) = current_step {
660                    step.commands.extend(joined);
661                } else {
662                    candidates.push(StepCandidate {
663                        job_id: current_job,
664                        commands: joined,
665                        ..Default::default()
666                    });
667                }
668                continue;
669            } else if !after_run_clean.is_empty() {
670                let cmd_str = unquote(after_run_clean).to_string();
671                if let Some(ref mut step) = current_step {
672                    step.commands.push(cmd_str);
673                } else {
674                    candidates.push(StepCandidate {
675                        job_id: current_job,
676                        commands: vec![cmd_str],
677                        ..Default::default()
678                    });
679                }
680            }
681        }
682        i += 1;
683    }
684
685    if let Some(step) = current_step.take() {
686        candidates.push(step);
687    }
688
689    let mut result = Vec::new();
690    let mut seen = HashSet::new();
691    let mut setup_cmds = Vec::new();
692    let mut seen_setup = HashSet::new();
693    let mut left_out = Vec::new();
694    let mut seen_left_out = HashSet::new();
695
696    for cand in candidates {
697        let job = &jobs[cand.job_id];
698        let matrix = &job.matrix;
699
700        let effective_wd = cand
701            .working_dir
702            .as_ref()
703            .or(job.working_dir.as_ref())
704            .or(workflow_working_dir.as_ref())
705            .cloned();
706
707        let mut effective_env = workflow_env.clone();
708        for (k, v) in &job.env {
709            effective_env.insert(k.clone(), v.clone());
710        }
711        for (k, v) in &cand.env {
712            effective_env.insert(k.clone(), v.clone());
713        }
714
715        for raw_cmd in &cand.commands {
716            let combos =
717                expand_step_combinations(raw_cmd, effective_wd.as_deref(), &effective_env, matrix);
718            for (exp_cmd, exp_wd, exp_env) in combos {
719                for part in split_chain(&exp_cmd) {
720                    if let Some(uv_sync) = filter_uv_sync_command(&part) {
721                        if is_non_root_wd(exp_wd.as_deref()) {
722                            if let Some(reason) =
723                                check_left_out_reason(&uv_sync, exp_wd.as_deref(), &exp_env, matrix)
724                            {
725                                if seen_left_out.insert(uv_sync.clone()) {
726                                    left_out.push((uv_sync, reason));
727                                }
728                            } else {
729                                let rendered = format!(
730                                    "({})",
731                                    render_step_command(&uv_sync, exp_wd.as_deref(), &exp_env)
732                                );
733                                if seen_setup.insert(rendered.clone()) {
734                                    setup_cmds.push(rendered);
735                                }
736                            }
737                        }
738                        continue;
739                    }
740                    let Some(kept) = filter_and_clean_command(&part) else {
741                        continue;
742                    };
743                    if let Some(reason) =
744                        check_left_out_reason(&kept, exp_wd.as_deref(), &exp_env, matrix)
745                    {
746                        if seen_left_out.insert(kept.clone()) {
747                            left_out.push((kept, reason));
748                        }
749                    } else {
750                        let rendered = render_step_command(&kept, exp_wd.as_deref(), &exp_env);
751                        if seen.insert(rendered.clone()) {
752                            result.push(rendered);
753                        }
754                    }
755                }
756            }
757        }
758    }
759
760    (result, setup_cmds, left_out)
761}
762
763fn strip_yaml_comment(s: &str) -> &str {
764    let mut quote: Option<char> = None;
765    let mut prev_ws = true;
766    for (idx, c) in s.char_indices() {
767        if let Some(q) = quote {
768            if c == q {
769                quote = None;
770            }
771        } else if c == '"' || c == '\'' {
772            quote = Some(c);
773        } else if c == '#' && prev_ws {
774            return s[..idx].trim_end();
775        }
776        prev_ws = c.is_whitespace();
777    }
778    s.trim_end()
779}
780
781fn unquote(s: &str) -> &str {
782    if s.len() >= 2
783        && ((s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')))
784    {
785        &s[1..s.len() - 1]
786    } else {
787        s
788    }
789}
790
791fn is_yaml_mapping_or_expr(s: &str) -> bool {
792    if s.len() >= 2
793        && ((s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')))
794    {
795        return false;
796    }
797    s.starts_with('{')
798        || s.starts_with('[')
799        || s.starts_with("${{")
800        || s.ends_with(':')
801        || s.contains(": ")
802}
803
804fn parse_flow_list(inner: &str) -> Vec<String> {
805    let mut items = Vec::new();
806    let mut current = String::new();
807    let mut quote: Option<char> = None;
808    for c in inner.chars() {
809        if let Some(q) = quote {
810            current.push(c);
811            if c == q {
812                quote = None;
813            }
814        } else if c == '"' || c == '\'' {
815            quote = Some(c);
816            current.push(c);
817        } else if c == ',' {
818            let trimmed = current.trim();
819            if !trimmed.is_empty() {
820                if is_yaml_mapping_or_expr(trimmed) {
821                    return Vec::new();
822                }
823                items.push(unquote(trimmed).to_string());
824            }
825            current.clear();
826        } else {
827            current.push(c);
828        }
829    }
830    let trimmed = current.trim();
831    if !trimmed.is_empty() {
832        if is_yaml_mapping_or_expr(trimmed) {
833            return Vec::new();
834        }
835        items.push(unquote(trimmed).to_string());
836    }
837    items
838}
839
840fn parse_flow_map(inner: &str, out: &mut BTreeMap<String, String>) {
841    let mut entries = Vec::new();
842    let mut current = String::new();
843    let mut quote: Option<char> = None;
844    let mut brace_depth: usize = 0;
845    for c in inner.chars() {
846        if let Some(q) = quote {
847            current.push(c);
848            if c == q {
849                quote = None;
850            }
851        } else if c == '"' || c == '\'' {
852            quote = Some(c);
853            current.push(c);
854        } else if c == '{' {
855            brace_depth += 1;
856            current.push(c);
857        } else if c == '}' {
858            brace_depth = brace_depth.saturating_sub(1);
859            current.push(c);
860        } else if c == ',' && brace_depth == 0 {
861            entries.push(std::mem::take(&mut current));
862        } else {
863            current.push(c);
864        }
865    }
866    entries.push(current);
867    for entry in entries {
868        let trimmed = entry.trim();
869        if let Some((k, v)) = trimmed.split_once(':') {
870            let key = k.trim();
871            let val = unquote(v.trim()).to_string();
872            if !key.is_empty() {
873                out.insert(key.to_string(), val);
874            }
875        }
876    }
877}
878
879fn set_matrix_key(matrix: &mut Vec<(String, Vec<String>)>, key: &str, values: Vec<String>) {
880    if let Some(entry) = matrix.iter_mut().find(|(k, _)| k == key) {
881        entry.1 = values;
882    } else {
883        matrix.push((key.to_string(), values));
884    }
885}
886
887fn push_matrix_val(matrix: &mut Vec<(String, Vec<String>)>, key: &str, val: String) {
888    if let Some(entry) = matrix.iter_mut().find(|(k, _)| k == key) {
889        entry.1.push(val);
890    } else {
891        matrix.push((key.to_string(), vec![val]));
892    }
893}
894
895fn expand_step_combinations(
896    cmd: &str,
897    wd: Option<&str>,
898    env: &BTreeMap<String, String>,
899    matrix: &[(String, Vec<String>)],
900) -> Vec<(String, Option<String>, BTreeMap<String, String>)> {
901    let mut expanded = vec![(cmd.to_string(), wd.map(String::from), env.clone())];
902    for (key, values) in matrix {
903        if values.is_empty() {
904            continue;
905        }
906        let mut next = Vec::new();
907        for (c, w, e) in &expanded {
908            let uses_key = replace_matrix_key(c, key, "").is_some()
909                || w.as_deref()
910                    .is_some_and(|ws| replace_matrix_key(ws, key, "").is_some())
911                || e.values()
912                    .any(|ev| replace_matrix_key(ev, key, "").is_some());
913            if uses_key {
914                for v in values {
915                    let nc = replace_matrix_key(c, key, v).unwrap_or_else(|| c.clone());
916                    let nw = w
917                        .as_ref()
918                        .map(|ws| replace_matrix_key(ws, key, v).unwrap_or_else(|| ws.clone()));
919                    let ne = e
920                        .iter()
921                        .map(|(ek, ev)| {
922                            (
923                                ek.clone(),
924                                replace_matrix_key(ev, key, v).unwrap_or_else(|| ev.clone()),
925                            )
926                        })
927                        .collect();
928                    next.push((nc, nw, ne));
929                }
930            } else {
931                next.push((c.clone(), w.clone(), e.clone()));
932            }
933        }
934        expanded = next;
935    }
936    expanded
937}
938
939fn replace_matrix_key(s: &str, target_key: &str, val: &str) -> Option<String> {
940    let mut out = String::new();
941    let mut cursor = 0;
942    let mut replaced = false;
943    while cursor < s.len() {
944        let rest = &s[cursor..];
945        let Some(rel_start) = rest.find("${{") else {
946            out.push_str(rest);
947            break;
948        };
949        let start = cursor + rel_start;
950        let after_open = &s[start + 3..];
951        let Some(rel_end) = after_open.find("}}") else {
952            out.push_str(rest);
953            break;
954        };
955        let end = start + 3 + rel_end + 2;
956        let inner = after_open[..rel_end].trim();
957        if inner.strip_prefix("matrix.") == Some(target_key) {
958            out.push_str(&s[cursor..start]);
959            out.push_str(val);
960            replaced = true;
961            cursor = end;
962        } else {
963            out.push_str(&s[cursor..start + 3]);
964            cursor = start + 3;
965        }
966    }
967    if replaced {
968        Some(out)
969    } else {
970        None
971    }
972}
973
974fn first_unexpanded_matrix_key(s: &str) -> Option<String> {
975    let mut cursor = 0;
976    while let Some(rel) = s[cursor..].find("${{") {
977        let start = cursor + rel + 3;
978        let after = &s[start..];
979        if let Some(rel_end) = after.find("}}") {
980            let inner = after[..rel_end].trim();
981            if let Some(key) = inner.strip_prefix("matrix.") {
982                return Some(key.trim().to_string());
983            }
984            cursor = start + rel_end + 2;
985        } else {
986            let inner = after.trim_start();
987            if let Some(rest) = inner.strip_prefix("matrix.") {
988                let key = rest.split_whitespace().next().unwrap_or("");
989                return Some(key.to_string());
990            }
991            break;
992        }
993    }
994    None
995}
996
997fn check_left_out_reason(
998    cmd: &str,
999    wd: Option<&str>,
1000    env: &BTreeMap<String, String>,
1001    matrix: &[(String, Vec<String>)],
1002) -> Option<String> {
1003    if let Some(key) = first_unexpanded_matrix_key(cmd) {
1004        if matrix.iter().any(|(k, _)| k == &key) {
1005            return Some(format!("matrix key {key} has no plain values"));
1006        } else {
1007            return Some(format!("unknown matrix key {key}"));
1008        }
1009    }
1010    for (k, v) in env {
1011        if v.contains("${{") {
1012            return Some(format!("env {k} is set from a CI expression"));
1013        }
1014    }
1015    if let Some(w) = wd {
1016        if w.contains("${{") {
1017            return Some("working-directory is a CI expression".to_string());
1018        }
1019    }
1020    None
1021}
1022
1023fn shell_quote_if_needed(s: &str) -> String {
1024    let is_safe = !s.is_empty()
1025        && s.chars().all(|c| {
1026            c.is_ascii_alphanumeric()
1027                || matches!(c, '_' | '.' | '/' | ',' | ':' | '@' | '%' | '+' | '=' | '-')
1028        });
1029    if is_safe {
1030        s.to_string()
1031    } else {
1032        format!("'{}'", s.replace('\'', "'\\''"))
1033    }
1034}
1035
1036fn is_non_root_wd(wd: Option<&str>) -> bool {
1037    wd.is_some_and(|dir| !dir.is_empty() && dir != "." && dir != "./")
1038}
1039
1040fn filter_uv_sync_command(cmd: &str) -> Option<String> {
1041    let tokens = tokenize(cmd.trim());
1042    if tokens.first().map(String::as_str) == Some("uv")
1043        && tokens.get(1).map(String::as_str) == Some("sync")
1044    {
1045        Some(tokens.join(" "))
1046    } else {
1047        None
1048    }
1049}
1050
1051fn render_step_command(cmd: &str, wd: Option<&str>, env: &BTreeMap<String, String>) -> String {
1052    let mut out = String::new();
1053    if let Some(dir) = wd {
1054        if is_non_root_wd(Some(dir)) {
1055            out.push_str("cd ");
1056            out.push_str(&shell_quote_if_needed(dir));
1057            out.push_str(" && ");
1058        }
1059    }
1060    if !env.is_empty() {
1061        out.push_str("env ");
1062        for (k, v) in env {
1063            out.push_str(k);
1064            out.push('=');
1065            out.push_str(&shell_quote_if_needed(v));
1066            out.push(' ');
1067        }
1068    }
1069    out.push_str(cmd);
1070    out
1071}
1072
1073/// Split a shell line on `&&`, `||` and `;` outside quotes.
1074fn split_chain(cmd: &str) -> Vec<String> {
1075    let mut parts = Vec::new();
1076    let mut current = String::new();
1077    let mut quote: Option<char> = None;
1078    let chars: Vec<char> = cmd.chars().collect();
1079    let mut i = 0;
1080    while i < chars.len() {
1081        let c = chars[i];
1082        if let Some(q) = quote {
1083            current.push(c);
1084            if c == q {
1085                quote = None;
1086            }
1087        } else if c == '"' || c == '\'' {
1088            quote = Some(c);
1089            current.push(c);
1090        } else if (c == '&' || c == '|') && chars.get(i + 1) == Some(&c) {
1091            parts.push(std::mem::take(&mut current));
1092            i += 1;
1093        } else if c == ';' {
1094            parts.push(std::mem::take(&mut current));
1095        } else {
1096            current.push(c);
1097        }
1098        i += 1;
1099    }
1100    parts.push(current);
1101    parts
1102        .into_iter()
1103        .map(|p| p.trim().to_string())
1104        .filter(|p| !p.is_empty())
1105        .collect()
1106}
1107
1108fn join_continuation_lines(lines: &[&str]) -> Vec<String> {
1109    let mut result = Vec::new();
1110    let mut current = String::new();
1111
1112    for line in lines {
1113        let trimmed = line.trim();
1114        if trimmed.is_empty() {
1115            if !current.is_empty() {
1116                result.push(current);
1117                current = String::new();
1118            }
1119            continue;
1120        }
1121
1122        if let Some(stripped) = trimmed.strip_suffix('\\') {
1123            let without_bs = stripped.trim_end();
1124            if current.is_empty() {
1125                current.push_str(without_bs);
1126            } else {
1127                current.push(' ');
1128                current.push_str(without_bs);
1129            }
1130        } else if current.is_empty() {
1131            result.push(trimmed.to_string());
1132        } else {
1133            current.push(' ');
1134            current.push_str(trimmed);
1135            result.push(current);
1136            current = String::new();
1137        }
1138    }
1139    if !current.is_empty() {
1140        result.push(current);
1141    }
1142    result
1143}
1144
1145fn filter_and_clean_command(cmd: &str) -> Option<String> {
1146    let trimmed = cmd.trim();
1147    let prefixes = [
1148        "uv run ",
1149        "poetry run ",
1150        "pdm run ",
1151        "npx ",
1152        "pipenv run ",
1153        "pnpm exec ",
1154        "bunx ",
1155    ];
1156    let mut stripped = trimmed;
1157    let mut had_prefix = false;
1158    for p in &prefixes {
1159        if stripped.starts_with(p) {
1160            stripped = stripped[p.len()..].trim_start();
1161            had_prefix = true;
1162            break;
1163        }
1164    }
1165    if had_prefix {
1166        while stripped.starts_with('-') {
1167            let Some((flag, rest)) = stripped.split_once(char::is_whitespace) else {
1168                break;
1169            };
1170            stripped = rest.trim_start();
1171            if matches!(
1172                flag,
1173                "--python" | "-p" | "--package" | "--directory" | "--group" | "--extra" | "--with"
1174            ) {
1175                if let Some((_, after_val)) = stripped.split_once(char::is_whitespace) {
1176                    stripped = after_val.trim_start();
1177                } else {
1178                    break;
1179                }
1180            }
1181        }
1182    }
1183
1184    let check_cmds = [
1185        "pytest",
1186        "python -m pytest",
1187        "python3 -m pytest",
1188        "python -m unittest",
1189        "python3 -m unittest",
1190        "tox",
1191        "nox",
1192        "ruff",
1193        "pyright",
1194        "mypy",
1195        "black",
1196        "isort",
1197        "pre-commit run",
1198        "cargo fmt",
1199        "cargo clippy",
1200        "cargo test",
1201        "go test",
1202        "go vet",
1203        "golangci-lint",
1204        "npm test",
1205        "npm run lint",
1206        "npm run typecheck",
1207        "pnpm test",
1208        "pnpm run lint",
1209        "yarn test",
1210        "yarn lint",
1211        "make check",
1212        "make lint",
1213        "make test",
1214        "make typecheck",
1215        "make validate",
1216        "eslint",
1217        "vitest",
1218        "jest",
1219        "tsc",
1220    ];
1221
1222    let text = if let Some(idx) = trimmed.find("| tee") {
1223        &trimmed[..idx]
1224    } else {
1225        trimmed
1226    };
1227
1228    let is_check = check_cmds.iter().any(|&c| {
1229        if stripped == c {
1230            true
1231        } else if let Some(rest) = stripped.strip_prefix(c) {
1232            rest.starts_with(char::is_whitespace)
1233        } else {
1234            false
1235        }
1236    }) || is_make_check(text);
1237
1238    if !is_check {
1239        return None;
1240    }
1241
1242    // Reporting options go, with their value when it is a separate word (`--cov-report xml:out`).
1243    let tokens = tokenize(text);
1244    let mut kept_tokens: Vec<String> = Vec::new();
1245    let mut iter = tokens.into_iter().peekable();
1246    while let Some(tok) = iter.next() {
1247        let reporting = ["--cov", "--junitxml", "--junit-xml"]
1248            .iter()
1249            .any(|o| tok.starts_with(o));
1250        if !reporting {
1251            kept_tokens.push(tok);
1252            continue;
1253        }
1254        // These always take a value; a bare `--cov` takes one unless it is the last word.
1255        let value_follows = iter.peek().is_some_and(|n| !n.starts_with('-'));
1256        let always = matches!(tok.as_str(), "--cov-report" | "--junitxml" | "--junit-xml");
1257        if value_follows && (always || (tok == "--cov" && iter.len() > 1)) {
1258            iter.next();
1259        }
1260    }
1261
1262    Some(kept_tokens.join(" "))
1263}
1264
1265fn is_make_check(cmd: &str) -> bool {
1266    let tokens = tokenize(cmd);
1267    if tokens.first().map(String::as_str) != Some("make") {
1268        return false;
1269    }
1270    let mut targets = Vec::new();
1271    let mut i = 1;
1272    while i < tokens.len() {
1273        let tok = tokens[i].as_str();
1274        if tok == "-C" || tok == "--directory" {
1275            if i + 1 >= tokens.len() || tokens[i + 1].is_empty() {
1276                return false;
1277            }
1278            i += 2;
1279        } else if (tok.starts_with("-C") && tok.len() > 2)
1280            || (tok.starts_with("--directory=") && tok.len() > "--directory=".len())
1281            || matches!(tok, "-s" | "--no-print-directory" | "-k")
1282        {
1283            i += 1;
1284        } else if tok.starts_with('-') || tok.contains('=') {
1285            return false;
1286        } else {
1287            targets.push(tok);
1288            i += 1;
1289        }
1290    }
1291    if targets.len() != 1 {
1292        return false;
1293    }
1294    let target = targets[0];
1295    matches!(target, "check" | "lint" | "test" | "typecheck" | "validate")
1296        || target.starts_with("test-")
1297        || target.starts_with("test_")
1298}
1299
1300fn tokenize(s: &str) -> Vec<String> {
1301    let mut tokens = Vec::new();
1302    let mut current = String::new();
1303    let mut in_quote = None;
1304    let chars: Vec<char> = s.chars().collect();
1305    let mut i = 0;
1306
1307    while i < chars.len() {
1308        let ch = chars[i];
1309        match in_quote {
1310            Some(q) => {
1311                current.push(ch);
1312                if ch == q {
1313                    in_quote = None;
1314                }
1315                i += 1;
1316            }
1317            None => {
1318                if ch == '$' && chars.get(i + 1) == Some(&'{') && chars.get(i + 2) == Some(&'{') {
1319                    current.push_str("${{");
1320                    i += 3;
1321                    while i < chars.len() {
1322                        if chars[i] == '}' && chars.get(i + 1) == Some(&'}') {
1323                            current.push_str("}}");
1324                            i += 2;
1325                            break;
1326                        }
1327                        current.push(chars[i]);
1328                        i += 1;
1329                    }
1330                } else if ch == '"' || ch == '\'' {
1331                    in_quote = Some(ch);
1332                    current.push(ch);
1333                    i += 1;
1334                } else if ch.is_whitespace() {
1335                    if !current.is_empty() {
1336                        tokens.push(current);
1337                        current = String::new();
1338                    }
1339                    i += 1;
1340                } else {
1341                    current.push(ch);
1342                    i += 1;
1343                }
1344            }
1345        }
1346    }
1347    if !current.is_empty() {
1348        tokens.push(current);
1349    }
1350    tokens
1351}
1352
1353/// Detect repository environment settings (such as UV_FROZEN and UV_OFFLINE).
1354pub fn detect_env(root: &Path) -> BTreeMap<String, String> {
1355    let mut map = BTreeMap::new();
1356    if root.join("uv.lock").exists() {
1357        map.insert("UV_FROZEN".to_string(), "1".to_string());
1358        if let Ok(content) = std::fs::read_to_string(root.join("pyproject.toml")) {
1359            if let Ok(parsed) = content.parse::<toml::Value>() {
1360                if let Some(tool) = parsed.get("tool").and_then(|t| t.get("uv")) {
1361                    if let Some(indexes) = tool.get("index").and_then(|i| i.as_array()) {
1362                        for idx in indexes {
1363                            if let Some(url) = idx.get("url").and_then(|u| u.as_str()) {
1364                                if !url.contains("pypi.org") {
1365                                    map.insert("UV_OFFLINE".to_string(), "1".to_string());
1366                                    break;
1367                                }
1368                            }
1369                        }
1370                    }
1371                }
1372            }
1373        }
1374    }
1375    map
1376}
1377
1378/// Propose a worktree setup command when the repository uses a supported package manager.
1379pub fn detect_setup(root: &Path) -> Option<String> {
1380    if root.join("uv.lock").exists() {
1381        Some("uv sync".to_string())
1382    } else {
1383        None
1384    }
1385}
1386
1387/// Classify step output into Passed, Environment problem, or Failed.
1388pub fn classify(output: &str, exit_code: i32) -> Verdict {
1389    if exit_code == 0 {
1390        return Verdict::Passed;
1391    }
1392
1393    let uv_patterns = [
1394        "network connectivity is disabled",
1395        "wasn't found in the cache",
1396    ];
1397
1398    // Words, not bare status codes: a test named `test_403_…` is not a 403.
1399    let patterns = [
1400        "unauthorized",
1401        "forbidden",
1402        "not found in the package registry",
1403        "could not resolve host",
1404        "network is unreachable",
1405        "connection refused",
1406        "operation not permitted",
1407        "command not found",
1408        "no such file or directory",
1409    ];
1410
1411    for line in output.lines() {
1412        // Test ids and result lines (`tests/x.py::test_y PASSED`) name tests, not the environment.
1413        if line.contains("::") {
1414            continue;
1415        }
1416        let lower = line.to_ascii_lowercase();
1417        let is_uv = uv_patterns.iter().any(|&p| lower.contains(p));
1418        if is_uv || patterns.iter().any(|&p| lower.contains(p)) {
1419            let trimmed = line.trim();
1420            let mut s: String = if trimmed.chars().count() > 120 {
1421                trimmed.chars().take(120).collect()
1422            } else {
1423                trimmed.to_string()
1424            };
1425            if is_uv {
1426                s.push_str(
1427                    " (run `uv sync` once online to fill uv's cache, then blyte init again)",
1428                );
1429            }
1430            return Verdict::Environment(s);
1431        }
1432    }
1433
1434    Verdict::Failed
1435}
1436
1437/// Render the verified blyte.toml content.
1438pub fn render_verified(
1439    steps: &[InitStep],
1440    env: &BTreeMap<String, String>,
1441    setup: Option<&str>,
1442    setup_passed: bool,
1443) -> String {
1444    let mut out = String::new();
1445    out.push_str("# blyte.toml: how this repository's work is checked, for `blyte dispatch`.\n");
1446
1447    let mut kept_steps = Vec::new();
1448    for step in steps {
1449        let comment_suffix = match &step.verdict {
1450            Some(Verdict::Passed) => "passed".to_string(),
1451            Some(Verdict::Failed) => "failed on HEAD: fix it before dispatching".to_string(),
1452            Some(Verdict::Environment(reason)) => format!("left out: {reason}"),
1453            None => "not verified".to_string(),
1454        };
1455        out.push_str(&format!(
1456            "# {}: from {}, {}\n",
1457            step.command, step.source, comment_suffix
1458        ));
1459
1460        if !matches!(step.verdict, Some(Verdict::Environment(_))) {
1461            kept_steps.push(step.command.as_str());
1462        }
1463    }
1464
1465    let mut gate_str = String::new();
1466    for step in &kept_steps {
1467        gate_str.push_str(step);
1468        gate_str.push('\n');
1469    }
1470
1471    out.push_str("[dispatch]\n");
1472    if let Some(s) = setup {
1473        let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
1474        if setup_passed {
1475            out.push_str("# prepares each new worktree before the implementer starts\n");
1476            out.push_str(&format!("setup = \"{escaped}\"\n"));
1477        } else {
1478            out.push_str(&format!(
1479                "# setup = \"{escaped}\"   # left out: failed in a fresh worktree\n"
1480            ));
1481        }
1482    }
1483    out.push_str("gate = \"\"\"\n");
1484    out.push_str(&gate_str);
1485    out.push_str("\"\"\"\n");
1486    out.push_str("# model = \"gemini-3.8-flash-high\"\n");
1487    out.push_str("max_seconds = 3600\n");
1488    out.push_str("max_turns = 300\n");
1489    out.push_str("# max_cost = 8.0\n");
1490    out.push_str("# network = \"on\"\n");
1491    out.push_str("# fold_budget = 60000\n\n");
1492
1493    if !env.is_empty() {
1494        out.push_str("[dispatch.env]\n");
1495        out.push_str("# for every command and the gate; never credentials\n");
1496        for (k, v) in env {
1497            out.push_str(&format!("{k} = \"{v}\"\n"));
1498        }
1499    } else {
1500        out.push_str("# [dispatch.env]\n");
1501        out.push_str(
1502            "# UV_FROZEN = \"1\"   # settings for every command and the gate; never credentials\n",
1503        );
1504    }
1505
1506    out
1507}
1508
1509/// What to show of a failing step: the test runner's own summary lines when it printed any
1510/// (`FAILED …`, `ERROR …`, `== 2 failed, 900 passed ==`), else the last lines. A tail alone can be
1511/// all shutdown noise.
1512pub fn failure_excerpt(text: &str) -> Vec<&str> {
1513    let summary: Vec<&str> = text
1514        .lines()
1515        .filter(|l| {
1516            let t = l.trim_start();
1517            // pytest's summary lines name a test file; a logger's `ERROR …` line does not.
1518            let names_test = t.contains("::") || t.contains(".py");
1519            ((t.starts_with("FAILED ") || t.starts_with("ERROR ")) && names_test)
1520                || (t.starts_with('=') && (t.contains(" failed") || t.contains(" error")))
1521        })
1522        .collect();
1523    let lines: Vec<&str> = if summary.is_empty() {
1524        text.lines().collect()
1525    } else {
1526        summary
1527    };
1528    lines[lines.len().saturating_sub(15)..].to_vec()
1529}
1530
1531/// Remove `.wt/init-<pid>` worktrees left by an init that was killed (its process is gone).
1532fn remove_stale_init_worktrees(root: &Path) {
1533    let Ok(entries) = std::fs::read_dir(root.join(".wt")) else {
1534        return;
1535    };
1536    for entry in entries.flatten() {
1537        let name = entry.file_name().to_string_lossy().to_string();
1538        let Some(pid) = name
1539            .strip_prefix("init-")
1540            .and_then(|p| p.parse::<i32>().ok())
1541        else {
1542            continue;
1543        };
1544        if unsafe { libc::kill(pid, 0) } != 0 {
1545            let _ = Command::new("git")
1546                .args(["worktree", "remove", "--force"])
1547                .arg(entry.path())
1548                .current_dir(root)
1549                .output();
1550        }
1551    }
1552    let _ = Command::new("git")
1553        .args(["worktree", "prune"])
1554        .current_dir(root)
1555        .output();
1556}
1557
1558fn verify_steps(
1559    root: &Path,
1560    mut steps: Vec<InitStep>,
1561    env: &BTreeMap<String, String>,
1562    sandbox_on: bool,
1563    timeout: Duration,
1564    setup: Option<&str>,
1565) -> (Vec<InitStep>, bool) {
1566    let common_dir_raw = Command::new("git")
1567        .args(["rev-parse", "--git-common-dir"])
1568        .current_dir(root)
1569        .output();
1570    let common_dir = if let Ok(out) = common_dir_raw {
1571        let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
1572        if p.is_absolute() {
1573            p
1574        } else {
1575            root.join(p)
1576        }
1577    } else {
1578        root.join(".git")
1579    };
1580    let exclude_path = common_dir.join("info").join("exclude");
1581    if let Some(parent) = exclude_path.parent() {
1582        let _ = std::fs::create_dir_all(parent);
1583    }
1584    let content = std::fs::read_to_string(&exclude_path).unwrap_or_default();
1585    if !content.lines().any(|l| l.trim() == ".wt/") {
1586        let mut new_content = content;
1587        if !new_content.is_empty() && !new_content.ends_with('\n') {
1588            new_content.push('\n');
1589        }
1590        new_content.push_str(".wt/\n");
1591        let _ = std::fs::write(&exclude_path, new_content);
1592    }
1593
1594    remove_stale_init_worktrees(root);
1595    let pid = std::process::id();
1596    let wt_dir = root.join(".wt").join(format!("init-{}", pid));
1597    let _ = std::fs::create_dir_all(root.join(".wt"));
1598
1599    let add_out = Command::new("git")
1600        .args(["worktree", "add", "--detach"])
1601        .arg(&wt_dir)
1602        .arg("HEAD")
1603        .current_dir(root)
1604        .output();
1605
1606    if let Ok(o) = add_out {
1607        if !o.status.success() {
1608            eprintln!(
1609                "warning: git worktree add failed: {}; skipping verification",
1610                String::from_utf8_lossy(&o.stderr)
1611            );
1612            return (steps, false);
1613        }
1614    } else {
1615        eprintln!("warning: failed to run git worktree add; skipping verification");
1616        return (steps, false);
1617    }
1618
1619    struct Guard<'a> {
1620        root: &'a Path,
1621        wt_dir: PathBuf,
1622    }
1623    impl<'a> Drop for Guard<'a> {
1624        fn drop(&mut self) {
1625            let _ = Command::new("git")
1626                .args(["worktree", "remove", "--force"])
1627                .arg(&self.wt_dir)
1628                .current_dir(self.root)
1629                .output();
1630        }
1631    }
1632    let _guard = Guard {
1633        root,
1634        wt_dir: wt_dir.clone(),
1635    };
1636
1637    for (k, v) in env {
1638        std::env::set_var(k, v);
1639    }
1640
1641    let mut setup_passed = false;
1642    if let Some(cmd) = setup {
1643        let log_path = wt_dir
1644            .parent()
1645            .unwrap_or(root)
1646            .join(format!("init-{pid}.setup.log"));
1647        match crate::setup::run_setup(
1648            cmd,
1649            &wt_dir,
1650            root,
1651            env,
1652            &log_path,
1653            crate::setup::SETUP_TIMEOUT,
1654        ) {
1655            Ok(()) => {
1656                setup_passed = true;
1657            }
1658            Err(msg) => {
1659                eprintln!("warning: setup failed; left out of blyte.toml:\n{msg}");
1660            }
1661        }
1662    }
1663
1664    use blyte_agent::shell::Shell;
1665    let shell = if sandbox_on {
1666        let profile = blyte_agent::sandbox::default_profile_net(&wt_dir, &[], true);
1667        blyte_agent::shell::LocalShell::sandboxed(profile)
1668    } else {
1669        blyte_agent::shell::LocalShell::new()
1670    };
1671
1672    for step in &mut steps {
1673        let start = std::time::Instant::now();
1674        let res = shell.exec(&step.command, &wt_dir, timeout);
1675        let elapsed = start.elapsed().as_secs();
1676
1677        // A run that could not finish (a timeout, say) counts as failing, with its error as output.
1678        let (text, code) = match res {
1679            Ok(output) => (output.merged(), output.exit_code),
1680            Err(e) => (e, 1),
1681        };
1682        let verdict = classify(&text, code);
1683        match &verdict {
1684            Verdict::Passed => eprintln!("init: {} ... passed ({}s)", step.command, elapsed),
1685            Verdict::Environment(reason) => {
1686                eprintln!("init: {} ... left out: {}", step.command, reason)
1687            }
1688            Verdict::Failed => {
1689                eprintln!("init: {} ... failed on HEAD ({}s)", step.command, elapsed);
1690                for l in failure_excerpt(&text) {
1691                    eprintln!("init:   | {l}");
1692                }
1693            }
1694        }
1695        step.verdict = Some(verdict);
1696    }
1697
1698    (steps, setup_passed)
1699}
1700
1701pub fn run(args: &InitArgs) -> i32 {
1702    let out = Command::new("git")
1703        .args(["rev-parse", "--show-toplevel"])
1704        .output();
1705    let Ok(out) = out else {
1706        eprintln!("error: git not found");
1707        return 2;
1708    };
1709    if !out.status.success() {
1710        eprintln!("error: not a git repository");
1711        return 2;
1712    }
1713    let root = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
1714    let toml_path = root.join("blyte.toml");
1715
1716    if !args.print && toml_path.exists() && !args.force {
1717        eprintln!("blyte.toml already exists; pass --force to overwrite");
1718        return 1;
1719    }
1720
1721    let ci_steps = detect_ci_with_sources(&root);
1722    let ci_left_out = detect_ci_left_out(&root);
1723    for (cmd, _, reason) in &ci_left_out {
1724        eprintln!("init: {cmd} ... left out: {reason}");
1725    }
1726    let left_out_init_steps: Vec<InitStep> = ci_left_out
1727        .into_iter()
1728        .map(|(cmd, src, reason)| InitStep {
1729            command: cmd,
1730            source: src,
1731            verdict: Some(Verdict::Environment(reason)),
1732        })
1733        .collect();
1734
1735    let (steps, from_ci) = if !ci_steps.is_empty() {
1736        let commands: Vec<String> = ci_steps.iter().map(|(cmd, _)| cmd.clone()).collect();
1737        let kept = drop_overlapping(commands);
1738        (
1739            kept.into_iter()
1740                .map(|cmd| {
1741                    let src = ci_steps
1742                        .iter()
1743                        .find(|(c, _)| c == &cmd)
1744                        .map(|(_, s)| s.clone())
1745                        .unwrap_or_default();
1746                    InitStep {
1747                        command: cmd,
1748                        source: src,
1749                        verdict: None,
1750                    }
1751                })
1752                .collect::<Vec<_>>(),
1753            true,
1754        )
1755    } else {
1756        let detected = crate::config::detect(&root);
1757        (
1758            detected
1759                .into_iter()
1760                .map(|cmd| InitStep {
1761                    command: cmd,
1762                    source: "detected".to_string(),
1763                    verdict: None,
1764                })
1765                .collect::<Vec<_>>(),
1766            false,
1767        )
1768    };
1769
1770    if steps.is_empty() && left_out_init_steps.is_empty() {
1771        eprintln!(
1772            "no toolchain detected: write blyte.toml by hand (see blyte init --print for the format)"
1773        );
1774        return 1;
1775    }
1776
1777    let env = detect_env(&root);
1778    let mut setup_parts = Vec::new();
1779    if let Some(root_setup) = detect_setup(&root) {
1780        setup_parts.push(root_setup);
1781    }
1782    setup_parts.extend(detect_ci_setup(&root));
1783    let setup = if setup_parts.is_empty() {
1784        None
1785    } else {
1786        Some(setup_parts.join(" && "))
1787    };
1788
1789    let (mut verified_steps, mut setup_passed) = if !args.no_verify && !steps.is_empty() {
1790        verify_steps(
1791            &root,
1792            steps,
1793            &env,
1794            args.sandbox == "on",
1795            Duration::from_secs(args.step_timeout),
1796            setup.as_deref(),
1797        )
1798    } else {
1799        (steps, setup.is_some())
1800    };
1801
1802    if from_ci && !args.no_verify {
1803        let any_passed = verified_steps
1804            .iter()
1805            .any(|s| matches!(s.verdict, Some(Verdict::Passed)));
1806        if !any_passed {
1807            let detected = crate::config::detect(&root);
1808            let not_all_identical = !detected.is_empty()
1809                && !detected
1810                    .iter()
1811                    .all(|d| verified_steps.iter().any(|s| &s.command == d));
1812            if not_all_identical {
1813                eprintln!(
1814                    "init: every step from CI failed or was left out; trying the checks detected from the repository"
1815                );
1816                let detected_steps: Vec<InitStep> = detected
1817                    .into_iter()
1818                    .map(|cmd| InitStep {
1819                        command: cmd,
1820                        source: "detected".to_string(),
1821                        verdict: None,
1822                    })
1823                    .collect();
1824                let (verified_detected, detected_setup_passed) = verify_steps(
1825                    &root,
1826                    detected_steps,
1827                    &env,
1828                    args.sandbox == "on",
1829                    Duration::from_secs(args.step_timeout),
1830                    setup.as_deref(),
1831                );
1832                if verified_detected
1833                    .iter()
1834                    .any(|s| matches!(s.verdict, Some(Verdict::Passed)))
1835                {
1836                    verified_steps = verified_detected;
1837                    setup_passed = detected_setup_passed;
1838                }
1839            }
1840        }
1841    }
1842
1843    verified_steps.extend(left_out_init_steps);
1844
1845    let kept_count = verified_steps
1846        .iter()
1847        .filter(|s| !matches!(s.verdict, Some(Verdict::Environment(_))))
1848        .count();
1849
1850    if kept_count == 0 {
1851        eprintln!("error: every step was left out due to environment issues");
1852        for step in &verified_steps {
1853            if let Some(Verdict::Environment(ref r)) = step.verdict {
1854                eprintln!("  `{}` left out: {r}", step.command);
1855            }
1856        }
1857        return 1;
1858    }
1859
1860    let rendered = render_verified(&verified_steps, &env, setup.as_deref(), setup_passed);
1861
1862    if args.print {
1863        print!("{rendered}");
1864    } else {
1865        if let Err(e) = std::fs::write(&toml_path, &rendered) {
1866            eprintln!("error writing {}: {e}", toml_path.display());
1867            return 1;
1868        }
1869        println!("wrote {}", toml_path.display());
1870        for step in &verified_steps {
1871            if !matches!(step.verdict, Some(Verdict::Environment(_))) {
1872                println!("{}", step.command);
1873            }
1874        }
1875    }
1876
1877    let any_failed = verified_steps
1878        .iter()
1879        .any(|s| matches!(s.verdict, Some(Verdict::Failed)));
1880
1881    if any_failed {
1882        for s in &verified_steps {
1883            if matches!(s.verdict, Some(Verdict::Failed)) {
1884                eprintln!(
1885                    "warning: step `{}` failed on HEAD: fix it before dispatching",
1886                    s.command
1887                );
1888            }
1889        }
1890        3
1891    } else {
1892        0
1893    }
1894}