Skip to main content

rust_anything/
go.rs

1//! `go`: the hot-path loop in one command. Profile the workload, bridge the top portable
2//! function (the outermost one, batched where `profile` says so), record it, hand the port to
3//! an agent, then build, diff and gate it, and switch it on with `enable` only when all pass.
4//! Run it again after porting by hand: every finished step is kept.
5
6use std::path::{Path, PathBuf};
7use std::process::Command;
8
9use anyhow::{Context, Result, bail};
10use serde::Serialize;
11
12use crate::bridge::Manifest;
13use crate::lang::Lang;
14use crate::profile::{Hot, Report};
15use crate::walk::Canonical;
16
17pub const TASK: &str = "TASK.md";
18
19pub struct Options<'a> {
20    pub root: &'a Path,
21    pub command: &'a [String],
22    pub lang: Option<Lang>,
23    /// `claude`, `codex`, or a command that reads the prompt on stdin; `None` stops at the task.
24    pub agent: Option<&'a str>,
25    /// Port this function instead of the profile's pick.
26    pub function: Option<&'a str>,
27    /// Generated cases per function.
28    pub count: usize,
29    /// Agent turns: the first port, then one per failed diff or gate.
30    pub rounds: Option<usize>,
31}
32
33#[derive(Debug, Clone, Serialize)]
34pub struct Pick {
35    pub function: String,
36    pub file: String,
37    pub line: u32,
38    pub total_pct: f64,
39    /// `function:param` passed to `bridge --batch`.
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub batch: Option<String>,
42    /// The caller that spends the most time in it: `name` and `file:line`.
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub caller: Option<(String, String)>,
45    pub why: String,
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
49#[serde(rename_all = "snake_case")]
50pub enum Stage {
51    /// The task is written; port `src/port.rs` and run `go` again.
52    WaitingForPort,
53    /// Recorded cases still differ after the agent's turns.
54    Mismatch,
55    /// Every case matches but a gate check fails.
56    GateFailed,
57    /// Everything passed and the unit is switched on.
58    On,
59    /// Everything passed; this language is switched with the shadow module instead.
60    Passed,
61    /// Everything matches, but `bench` times the port slower than the original as its
62    /// callers call it, so it stays off.
63    Slower,
64}
65
66#[derive(Debug, Serialize)]
67pub struct Outcome {
68    pub stage: Stage,
69    pub pick: Pick,
70    pub crate_dir: PathBuf,
71    pub task: PathBuf,
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub cases: Option<usize>,
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub matched: Option<usize>,
76    /// `bench`'s geometric-mean speedup, call included, once every check passed.
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub speedup: Option<f64>,
79    pub failed_checks: Vec<String>,
80    pub steps: Vec<String>,
81    pub next: String,
82}
83
84/// The function to port: the first hot one (most time, so the outermost loop) that is exported
85/// by a portable unit, can cross the bridge, and takes arguments to record.
86pub fn pick(report: &Report, function: Option<&str>) -> Result<Pick> {
87    let crosses = |h: &&Hot| {
88        h.unit.is_some() && h.portable && h.js_only.is_none() && h.exported && !h.params.is_empty()
89    };
90    let eligible = |h: &&Hot| crosses(h) && !h.mostly_waits();
91    if function.is_none()
92        && report.child_pct >= 50.0
93        && let Some(summary) = report.child_summary()
94    {
95        let anyway = if report.hot.iter().any(|h| eligible(&h)) {
96            " To port a function anyway, name it with `--function`."
97        } else {
98            ""
99        };
100        bail!("{summary} {}{anyway}", crate::profile::CHILD_ADVICE);
101    }
102    let hot = match function {
103        Some(name) => report
104            .hot
105            .iter()
106            .filter(|h| h.name == name)
107            .find(eligible)
108            .or_else(|| report.hot.iter().find(|h| h.name == name))
109            .with_context(|| {
110                format!("`{name}` is not among the hot functions of this run (see `rust-anything profile`)")
111            })?,
112        None => report.hot.iter().find(eligible).with_context(|| {
113            if report.hot.iter().any(|h| crosses(&h) && h.mostly_waits()) {
114                let summary = report
115                    .child_summary()
116                    .map_or_else(String::new, |s| format!(" {s}"));
117                return format!(
118                    "no hot function to port: the ones that could cross the bridge mostly wait on \
119                     child processes.{summary} {}",
120                    crate::profile::CHILD_ADVICE
121                );
122            }
123            format!(
124                "no hot function to port: none of the {} is exported by a portable \
125                 unit, can cross the bridge and takes arguments. `rust-anything profile` shows why.",
126                crate::report::count(report.hot.len(), "hot function")
127            )
128        })?,
129    };
130    if !eligible(&hot) {
131        if let Some(reason) = &hot.js_only {
132            bail!(
133                "`{}` cannot be bridged: `bridge` keeps it in {}: {reason}",
134                hot.name,
135                report.language.name()
136            );
137        }
138        if hot.mostly_waits() {
139            bail!(
140                "`{}` spends {:.0}% of its time waiting on child processes. {}",
141                hot.name,
142                hot.child_pct.unwrap_or_default(),
143                crate::profile::CHILD_ADVICE
144            );
145        }
146        bail!("`{}` cannot be bridged: {}", hot.name, hot.advice);
147    }
148    let why = match &hot.batch {
149        Some(spec) => format!(
150            "{:.0}% of the run; called in a loop by `{}`, so it is bridged with `--batch {spec}`",
151            hot.total_pct,
152            hot.callers
153                .first()
154                .map_or("its caller", |c| c.name.as_str())
155        ),
156        None => format!(
157            "{:.0}% of the run, the outermost portable function",
158            hot.total_pct
159        ),
160    };
161    Ok(Pick {
162        function: hot.name.clone(),
163        file: hot.file.clone(),
164        line: hot.line,
165        total_pct: hot.total_pct,
166        batch: hot.batch.clone(),
167        caller: hot
168            .callers
169            .first()
170            .map(|c| (c.name.clone(), format!("{}:{}", c.file, c.line))),
171        why,
172    })
173}
174
175pub fn crate_name(function: &str) -> String {
176    format!(
177        "{}-rs",
178        crate::bridge::snake_case(function).replace('_', "-")
179    )
180}
181
182/// The other exported functions and classes of the file, kept in the original so the crate ports
183/// one. A function `bridge` keeps in the original anyway is left to `bridge`, which records its
184/// own reason.
185fn others(root: &Path, lang: Lang, file: &str, function: &str) -> Result<Vec<String>> {
186    let text =
187        std::fs::read_to_string(root.join(file)).with_context(|| format!("reading {file}"))?;
188    crate::profile::use_project_types(root, lang);
189    let classes = if lang == Lang::Ts {
190        crate::ts::exports::exported_classes(file, &text)
191    } else {
192        crate::lang::exports(lang, file, &text).1
193    };
194    Ok(crate::profile::exports_judged(root, lang, file, &text)
195        .into_iter()
196        .filter(|(_, reason)| reason.is_none())
197        .map(|(f, _)| f.name)
198        .chain(classes.into_iter().map(|c| c.name))
199        .filter(|n| n != function)
200        .map(|n| format!("{n}: not hot in the profiled run; `go` ports one function"))
201        .collect())
202}
203
204pub fn task(crate_dir: &Path, pick: &Pick, command: &[String]) -> String {
205    let batch = pick.batch.as_ref().map_or_else(String::new, |spec| {
206        let function = spec.split(':').next().unwrap_or(&pick.function);
207        format!(
208            "\nThe crate also has a batch class for `{spec}`, which runs `{function}` over many \
209             items kept in Rust. A `{}Index` struct in `src/port.rs` can prepare the items once \
210             (see the Hot paths section of rust-anything's docs/how-it-works.md); `rust-anything go` runs `rust-anything \
211             refresh` before building, so the batch class uses it.\n",
212            crate::codegen_batch::pascal(function)
213        )
214    });
215    let rules = match crate::rules::section(crate_dir) {
216        r if r.is_empty() => r,
217        r => format!("{r}\n"),
218    };
219    format!(
220        "# Port `{function}` to Rust\n\n\
221         `{function}` (`{file}:{line}`) took {pct:.0}% of `{command}`. Port it, and only it, in \
222         `src/port.rs` of this crate ({dir}). The bindings, the recorded cases and \
223         `rust-anything.json` are generated: leave them as they are.\n{batch}\n\
224         ## Rules\n\n\
225         - Match the original exactly on every recorded case in `cases.jsonl`: values, errors and \
226           their messages, edge cases (empty input, Unicode, large numbers). Read the original \
227           first; port its behavior, not a cleaner idea of it.\n\
228         - No `unwrap`, `expect` or `panic!` outside tests; no `unsafe` without a `// SAFETY:` comment.\n\
229         - Keep helpers private; only the unit's functions are `pub`.\n\
230         - Never hard-code recorded outputs or weaken tests; gate checks both.\n\n\
231         {rules}\
232         ## Loop\n\n\
233         ```sh\n\
234         rust-anything build .\n\
235         rust-anything diff .     # every recorded case must match\n\
236         rust-anything gate .     # fmt, clippy, tests, unsafe, API, diff\n\
237         ```\n\n\
238         Done when `diff` matches every case and `gate` passes. Do not switch the port on; \
239         `rust-anything go` does that once both pass.\n",
240        function = pick.function,
241        file = pick.file,
242        line = pick.line,
243        pct = pick.total_pct,
244        command = command.join(" "),
245        dir = crate_dir.display(),
246    )
247}
248
249/// The agent's command line: `claude` and `codex` run headless with edits allowed in the crate;
250/// anything else runs as given, reading the prompt on stdin.
251pub fn agent_command(agent: &str) -> Result<Command> {
252    let words: Vec<&str> = agent.split_whitespace().collect();
253    let (program, args) = words.split_first().context("--agent is empty")?;
254    let mut cmd = Command::new(program);
255    match *program {
256        "claude" if args.is_empty() => {
257            cmd.args([
258                "-p",
259                "--permission-mode",
260                "acceptEdits",
261                "--allowedTools",
262                "Bash(cargo:*)",
263                "Bash(rust-anything:*)",
264            ]);
265        }
266        "codex" if args.is_empty() => {
267            cmd.args(["exec", "--full-auto", "-"]);
268        }
269        _ => {
270            cmd.args(args);
271        }
272    }
273    Ok(cmd)
274}
275
276fn say(steps: &mut Vec<String>, line: String) {
277    eprintln!("go: {line}");
278    steps.push(line);
279}
280
281pub fn go(opts: &Options) -> Result<Outcome> {
282    if let Some(r) = opts.rounds {
283        anyhow::ensure!(r >= 1, "`--rounds` must be at least 1");
284        if opts.agent.is_none() {
285            anyhow::bail!("`--rounds` needs `--agent`: rounds are agent turns");
286        }
287    }
288
289    let root = opts
290        .root
291        .canonical()
292        .with_context(|| format!("resolving {}", opts.root.display()))?;
293    let lang = opts.lang.unwrap_or_else(|| Lang::detect(&root));
294    let mut steps = Vec::new();
295
296    let report = crate::profile::profile(&root, opts.command, Some(lang))?;
297    let pick = pick(&report, opts.function)?;
298    say(
299        &mut steps,
300        format!(
301            "profiled `{}` ({:.0} ms): porting `{}` ({}:{}), {}",
302            opts.command.join(" "),
303            report.total_ms,
304            pick.function,
305            pick.file,
306            pick.line,
307            pick.why
308        ),
309    );
310
311    let name = crate_name(&pick.function);
312    let crate_dir = root.join("rust").join(&name);
313    if crate_dir.join("rust-anything.json").is_file() {
314        let m = Manifest::load(&crate_dir)?;
315        if !m.exports.iter().any(|f| f.name == pick.function) {
316            bail!(
317                "{} exists for other functions ({}); move it aside or pass --function",
318                crate_dir.display(),
319                m.exports
320                    .iter()
321                    .map(|f| f.name.as_str())
322                    .collect::<Vec<_>>()
323                    .join(", ")
324            );
325        }
326        say(
327            &mut steps,
328            format!("kept the crate at {}", crate_dir.display()),
329        );
330    } else {
331        let outcome = crate::bridge::bridge(&crate::bridge::Options {
332            root: &root,
333            unit: &pick.file,
334            kind: None,
335            out: Some(crate_dir.clone()),
336            name: Some(name.clone()),
337            force: false,
338            keep: others(&root, lang, &pick.file, &pick.function)?,
339            lang: Some(lang),
340            batch: pick.batch.iter().cloned().collect(),
341            as_json: Vec::new(),
342            allocator: crate::bridge::Allocator::default(),
343        })?;
344        say(
345            &mut steps,
346            format!(
347                "bridged {} ({}) at {}",
348                outcome.exports.join(", "),
349                outcome.kind.label(),
350                outcome.crate_dir.display()
351            ),
352        );
353    }
354    let manifest = Manifest::load(&crate_dir)?;
355
356    let cases = crate_dir.join(crate::harness::CASES);
357    let stale = crate::recording::stale(&crate_dir, &manifest);
358    if !cases.is_file() || stale.is_some() {
359        let captured = match manifest.language {
360            Lang::Ts | Lang::Python => {
361                let c = crate::from_tests::capture(&crate_dir, opts.command)?;
362                let n: usize = c.per_function.values().sum();
363                say(&mut steps, captured_line(n));
364                (n > 0).then_some(c.inputs)
365            }
366            _ => None,
367        };
368        let recorded = crate::harness::record(&crate::harness::RecordOptions {
369            crate_dir: &crate_dir,
370            count: opts.count,
371            inputs: captured.as_deref(),
372            module: None,
373            resolve_from: None,
374            node_args: &[],
375        })?;
376        say(&mut steps, recorded_line(recorded.cases, recorded.errors));
377    } else {
378        say(&mut steps, "kept the recorded cases".into());
379    }
380
381    let task_path = crate_dir.join(TASK);
382    let task = task(&crate_dir, &pick, opts.command);
383    std::fs::write(&task_path, &task)
384        .with_context(|| format!("writing {}", task_path.display()))?;
385    let outcome = |stage, steps, cases, matched, failed_checks, next: String| Outcome {
386        stage,
387        pick: pick.clone(),
388        crate_dir: crate_dir.clone(),
389        task: task_path.clone(),
390        cases,
391        matched,
392        speedup: None,
393        failed_checks,
394        steps,
395        next,
396    };
397
398    let mut prompt = task.clone();
399    let rounds = if opts.agent.is_some() {
400        opts.rounds.unwrap_or(3)
401    } else {
402        0
403    };
404    let mut round = 0;
405    let mut need_port = !crate::gate::ported_check(&crate_dir).passed;
406    let (cases, matched) = loop {
407        if need_port {
408            let Some(agent) = opts.agent.filter(|_| round < rounds) else {
409                say(&mut steps, format!("wrote {}", task_path.display()));
410                return Ok(outcome(
411                    Stage::WaitingForPort,
412                    steps,
413                    None,
414                    None,
415                    Vec::new(),
416                    format!(
417                        "Port `{}` in {} as {} says (or pass --agent claude), then run the same \
418                         `rust-anything go` again.",
419                        pick.function,
420                        crate_dir.join("src/port.rs").display(),
421                        task_path.display()
422                    ),
423                ));
424            };
425            round += 1;
426            say(
427                &mut steps,
428                format!("handing the port to `{agent}` (turn {round} of {rounds})"),
429            );
430            let mut cmd = agent_command(agent)?;
431            cmd.current_dir(&crate_dir).stdout(std::io::stderr());
432            let status = crate::process::status_with_input(
433                &mut cmd,
434                prompt.as_bytes(),
435                crate::process::TESTS,
436            )?;
437            if !status.success() {
438                bail!("`{agent}` failed ({status})");
439            }
440            if !crate::gate::ported_check(&crate_dir).passed {
441                say(&mut steps, "the agent left stubs in src/port.rs".into());
442                prompt = format!(
443                    "{task}\n\nsrc/port.rs still has `todo!`, `unimplemented!` or functions that only panic. Finish them.\n"
444                );
445                continue;
446            }
447        }
448
449        let (cases, matched, problems) = check(&crate_dir, &mut steps)?;
450        if problems.is_empty() {
451            break (cases, matched);
452        }
453        if round >= rounds {
454            let stage = if matched < cases {
455                Stage::Mismatch
456            } else {
457                Stage::GateFailed
458            };
459            return Ok(outcome(
460                stage,
461                steps,
462                Some(cases),
463                Some(matched),
464                problems,
465                format!(
466                    "Fix the port ({}), then run the same `rust-anything go` again. The unit stays off.",
467                    task_path.display()
468                ),
469            ));
470        }
471        prompt = format!(
472            "{task}\n\nYour last port does not pass yet. Fix it:\n\n{}\n",
473            problems.join("\n\n")
474        );
475        need_port = true;
476    };
477
478    let rows = crate::harness::bench(&crate::harness::BenchOptions {
479        crate_dir: &crate_dir,
480        min_ms: 200,
481        resolve_from: None,
482        node_args: &[],
483    })?;
484    let speedup = crate::harness::verdict(&rows, manifest.language).speedup;
485    say(
486        &mut steps,
487        format!(
488            "bench: {} as its callers call it, call included",
489            times(speedup)
490        ),
491    );
492    if speedup < 1.0 {
493        let next = slower_advice(&pick, speedup);
494        let mut out = outcome(
495            Stage::Slower,
496            steps,
497            Some(cases),
498            Some(matched),
499            Vec::new(),
500            next,
501        );
502        out.speedup = Some(speedup);
503        return Ok(out);
504    }
505
506    let mut out = if crate::enable::is_supported(&manifest) {
507        let on = crate::enable::enable(&crate_dir)?;
508        say(
509            &mut steps,
510            format!(
511                "switched on: {} {} in Rust now ({}); `rust-anything disable {}` turns it off",
512                on.functions.join(", "),
513                if on.functions.len() == 1 {
514                    "runs"
515                } else {
516                    "run"
517                },
518                on.files
519                    .iter()
520                    .map(|f| f.display().to_string())
521                    .collect::<Vec<_>>()
522                    .join(", "),
523                crate_dir.display()
524            ),
525        );
526        outcome(
527            Stage::On,
528            steps,
529            Some(cases),
530            Some(matched),
531            Vec::new(),
532            format!(
533                "Measure it: `rust-anything report {}` writes REPORT.md and card.svg.",
534                crate_dir.display()
535            ),
536        )
537    } else {
538        outcome(
539            Stage::Passed,
540            steps,
541            Some(cases),
542            Some(matched),
543            Vec::new(),
544            format!(
545                "Every case matches and gate passes. Switch it in with the shadow module \
546                 (`rust-anything shadow {}`), then `rust-anything report` it.",
547                crate_dir.display()
548            ),
549        )
550    };
551    out.speedup = Some(speedup);
552    Ok(out)
553}
554
555pub(crate) use crate::harness::speed_phrase as times;
556
557/// What to do when every case matches but the port, called as its callers call it, loses.
558pub fn slower_advice(pick: &Pick, speedup: f64) -> String {
559    let caller = pick.caller.as_ref().map_or_else(
560        || "its caller".to_string(),
561        |(n, at)| format!("`{n}` ({at})"),
562    );
563    let lost = times(speedup);
564    match &pick.batch {
565        Some(spec) => {
566            let function = spec.split(':').next().unwrap_or(&pick.function);
567            format!(
568                "Every case matches, but called once per item the port is {lost} than the \
569                 original, so it stays off. The speed is in the batch: in {caller}, build \
570                 `{}Batch` once over the items and call it per query (the crate's type \
571                 declarations list its methods), or port {caller} with it. Then `rust-anything enable` and \
572                 `rust-anything report`.",
573                crate::codegen_batch::pascal(function)
574            )
575        }
576        None => format!(
577            "Every case matches, but the port is {lost} than the original as {caller} calls it: \
578             each call into Rust costs more than its work. It stays off. Port {caller} with it \
579             (`rust-anything go --function <name>`), or keep it in the original."
580        ),
581    }
582}
583
584/// Build, diff and gate: the cases, how many match, and what still fails.
585fn check(crate_dir: &Path, steps: &mut Vec<String>) -> Result<(usize, usize, Vec<String>)> {
586    if !Manifest::load(crate_dir)?.batches.is_empty()
587        && let Err(e) = crate::bridge::refresh(crate_dir)
588    {
589        say(steps, "refresh failed".into());
590        return Ok((0, 0, vec![format!("`rust-anything refresh` fails:\n{e:#}")]));
591    }
592    if let Err(e) = crate::harness::build(crate_dir) {
593        say(steps, "the build failed".into());
594        return Ok((0, 0, vec![format!("The build fails:\n{e:#}")]));
595    }
596    let diff = crate::harness::diff(&crate::harness::DiffOptions {
597        crate_dir,
598        module: None,
599        ignore_key_order: false,
600        node_args: &[],
601        float_tolerance: None,
602    })?;
603    say(
604        steps,
605        format!("diff: {}/{} cases match", diff.passed, diff.total),
606    );
607    if diff.failed > 0 || !diff.missing.is_empty() || diff.total == 0 {
608        return Ok((diff.total, diff.passed, vec![differences(&diff)]));
609    }
610    let gate = crate::gate::gate(crate_dir, &[])?;
611    let failed: Vec<String> = gate
612        .checks
613        .iter()
614        .filter(|c| !c.passed)
615        .map(|c| format!("gate check `{}` fails: {}", c.name, c.detail))
616        .collect();
617    say(steps, gate_line(failed.len()));
618    Ok((diff.total, diff.passed, failed))
619}
620
621fn captured_line(calls: usize) -> String {
622    format!(
623        "captured {} from the workload",
624        crate::report::count(calls, "real call")
625    )
626}
627
628fn recorded_line(cases: usize, errors: usize) -> String {
629    format!(
630        "recorded {} ({errors} threw in the original)",
631        crate::report::count(cases, "case")
632    )
633}
634
635fn gate_line(failed: usize) -> String {
636    match failed {
637        0 => "gate passed".into(),
638        1 => "gate: 1 check fails".into(),
639        n => format!("gate: {n} checks fail"),
640    }
641}
642
643/// What still differs, for the agent's next attempt: each distinct difference with one example
644/// and where it starts, or the first raw mismatches when there are no groups.
645fn differences(diff: &crate::harness::DiffOutcome) -> String {
646    let head = format!(
647        "{} of {} recorded cases differ{}.",
648        diff.total - diff.passed,
649        diff.total,
650        if diff.missing.is_empty() {
651            String::new()
652        } else {
653            format!("; missing from Rust: {}", diff.missing.join(", "))
654        }
655    );
656    if diff.groups.is_empty() {
657        let shown: Vec<String> = diff
658            .mismatches
659            .iter()
660            .take(5)
661            .map(|m| serde_json::to_string(m).unwrap_or_default())
662            .collect();
663        return format!("{head} First mismatches:\n{}", shown.join("\n"));
664    }
665    let diff_count = crate::report::count(diff.groups.len(), "distinct difference");
666    let mut out = format!("{head} {diff_count}, most cases first:");
667    for g in diff.groups.iter().take(5) {
668        let mut example = g.example.clone();
669        let at = example
670            .as_object_mut()
671            .and_then(|m| m.remove("at"))
672            .and_then(|at| serde_json::from_value::<crate::mismatch::At>(at).ok());
673        let cases_count = crate::report::count(g.cases, "case");
674        out += &format!(
675            "\n- {} ({cases_count}, id {})\n  example: {}",
676            g.label(),
677            g.id,
678            serde_json::to_string(&example).unwrap_or_default()
679        );
680        if let Some(at) = at {
681            out += &format!("\n  {}", at.describe());
682        }
683    }
684    out
685}
686
687#[cfg(test)]
688mod tests {
689    use super::*;
690    use crate::profile::Caller;
691
692    #[test]
693    fn the_retry_prompt_shows_each_difference_once_with_where_it_starts() {
694        let mut diff = crate::harness::DiffOutcome {
695            total: 10,
696            passed: 6,
697            failed: 4,
698            mismatches: (0..4)
699                .map(|i| serde_json::json!({ "fn": "count", "args": [format!("a\t{i}")], "expected": { "ok": 1 }, "actual": { "ok": 2 } }))
700                .collect(),
701            ..Default::default()
702        };
703        crate::mismatch::annotate(&mut diff);
704        diff.groups = crate::mismatch::group_mismatches(&diff.mismatches);
705        let text = differences(&diff);
706        assert!(
707            text.starts_with("4 of 10 recorded cases differ. 1 distinct difference,"),
708            "{text}"
709        );
710        assert!(
711            text.contains("- count: return $ (value) (4 cases, id "),
712            "{text}"
713        );
714        assert_eq!(text.matches("example:").count(), 1, "{text}");
715        assert!(
716            text.contains("at return $ (value): expected 1, got 2"),
717            "{text}"
718        );
719    }
720
721    fn hot(name: &str, pct: f64, unit: bool, params: &[&str], batch: Option<&str>) -> Hot {
722        Hot {
723            name: name.into(),
724            file: "app.py".into(),
725            line: 1,
726            unit: unit.then(|| "app.py".into()),
727            exported: true,
728            self_ms: 1.0,
729            total_ms: pct,
730            total_pct: pct,
731            calls: None,
732            ns_per_call: None,
733            callers: vec![Caller {
734                name: "main".into(),
735                file: "app.py".into(),
736                line: 9,
737                ms: pct,
738                calls: None,
739            }],
740            advice: "Hot, outside the analyzed units.".into(),
741            portable: unit,
742            js_only: None,
743            params: params.iter().map(|p| p.to_string()).collect(),
744            batch: batch.map(str::to_string),
745            child_pct: None,
746        }
747    }
748
749    fn report(hot: Vec<Hot>) -> Report {
750        Report {
751            schema: crate::profile::SCHEMA,
752            language: Lang::Python,
753            command: vec!["python3".into(), "app.py".into()],
754            total_ms: 100.0,
755            repo_pct: 100.0,
756            hot,
757            compiled: Vec::new(),
758            child_pct: 0.0,
759            child_processes: Vec::new(),
760        }
761    }
762
763    #[test]
764    fn the_outermost_portable_function_with_arguments_wins() {
765        let r = report(vec![
766            hot("main", 99.0, true, &[], None),
767            hot("load", 95.0, false, &["path"], None),
768            hot("dedupe", 90.0, true, &["names", "limit"], None),
769            hot(
770                "levenshtein",
771                85.0,
772                true,
773                &["a", "b"],
774                Some("levenshtein:b"),
775            ),
776        ]);
777        let p = pick(&r, None).unwrap();
778        assert_eq!((p.function.as_str(), p.batch), ("dedupe", None));
779        assert!(p.why.contains("outermost"), "{}", p.why);
780    }
781
782    #[test]
783    fn a_loop_the_profile_batches_is_bridged_with_its_batch() {
784        let r = report(vec![
785            hot("main", 99.0, true, &[], None),
786            hot(
787                "levenshtein",
788                85.0,
789                true,
790                &["a", "b"],
791                Some("levenshtein:b"),
792            ),
793        ]);
794        let p = pick(&r, None).unwrap();
795        assert_eq!(p.batch.as_deref(), Some("levenshtein:b"));
796        assert!(p.why.contains("--batch levenshtein:b"), "{}", p.why);
797    }
798
799    #[test]
800    fn a_named_function_must_be_portable() {
801        let r = report(vec![hot("load", 95.0, false, &["path"], None)]);
802        assert!(pick(&r, Some("load")).is_err());
803        assert!(pick(&r, Some("missing")).is_err());
804        assert!(pick(&r, None).is_err());
805    }
806
807    #[test]
808    fn a_function_that_mostly_waits_on_child_processes_is_passed_over() {
809        let waits = || {
810            let mut h = hot("run_all", 40.0, true, &["n"], None);
811            h.child_pct = Some(95.0);
812            h
813        };
814        let mut r = report(vec![waits(), hot("main", 99.0, true, &[], None)]);
815        r.child_pct = 38.0;
816        r.child_processes = vec![crate::profile::ChildProcess {
817            command: Some("git".into()),
818            file: "app.py".into(),
819            line: 4,
820            function: "run_all".into(),
821            ms: 38.0,
822            share: 38.0,
823        }];
824        let none = pick(&r, None).unwrap_err().to_string();
825        assert!(
826            none.starts_with("no hot function to port: the ones that could cross the bridge mostly wait on child processes. 38% of the run waits on child processes (`git` from `app.py:4`)."),
827            "{none}"
828        );
829        r.hot.push(hot("parse", 30.0, true, &["text"], None));
830        assert_eq!(pick(&r, None).unwrap().function, "parse");
831    }
832
833    #[test]
834    fn a_named_function_bridge_keeps_says_so_even_when_it_waits() {
835        let mut h = hot("each", 80.0, true, &["items"], None);
836        h.js_only = Some("takes or returns a function".into());
837        h.child_pct = Some(70.0);
838        let named = pick(&report(vec![h]), Some("each"))
839            .unwrap_err()
840            .to_string();
841        assert!(
842            named.contains("cannot be bridged") && named.contains("takes or returns a function"),
843            "{named}"
844        );
845    }
846
847    #[test]
848    fn none_eligible_message_uses_singular_and_plural_count() {
849        let r1 = report(vec![hot("main", 99.0, true, &[], None)]);
850        let err1 = pick(&r1, None).unwrap_err().to_string();
851        assert!(
852            err1.contains("none of the 1 hot function is exported"),
853            "{err1}"
854        );
855
856        let r2 = report(vec![
857            hot("main", 99.0, true, &[], None),
858            hot("cli", 80.0, true, &[], None),
859        ]);
860        let err2 = pick(&r2, None).unwrap_err().to_string();
861        assert!(
862            err2.contains("none of the 2 hot functions is exported"),
863            "{err2}"
864        );
865    }
866
867    #[test]
868    fn a_named_function_bridge_keeps_says_why_and_yields_to_one_that_can_cross() {
869        let kept = || {
870            let mut h = hot("calc", 60.0, true, &["xs", "cb"], None);
871            h.js_only = Some("takes or returns a function".into());
872            h
873        };
874        let only = pick(&report(vec![kept()]), Some("calc"))
875            .unwrap_err()
876            .to_string();
877        assert!(
878            only.contains("`bridge` keeps it in Python: takes or returns a function"),
879            "{only}"
880        );
881        let r = report(vec![kept(), hot("calc", 20.0, true, &["n"], None)]);
882        assert_eq!(pick(&r, Some("calc")).unwrap().total_pct, 20.0);
883    }
884
885    #[test]
886    fn functions_bridge_keeps_are_left_to_bridge_for_their_reason() {
887        let root =
888            std::env::temp_dir().join(format!("rust-anything-go-others-{}", std::process::id()));
889        let _ = std::fs::remove_dir_all(&root);
890        std::fs::create_dir_all(&root).unwrap();
891        std::fs::write(
892            root.join("plug.js"),
893            "export function each(items, visit) { for (const it of items) visit(it); }\n\
894             export function half(n) { return n / 2; }\n\
895             export function third(n) { return n / 3; }\n",
896        )
897        .unwrap();
898        std::fs::write(
899            root.join("plug.d.ts"),
900            "export declare function each<T>(items: T[], visit: (item: T) => void): void;\n",
901        )
902        .unwrap();
903        let keep = others(&root, Lang::Ts, "plug.js", "half").unwrap();
904        std::fs::remove_dir_all(&root).unwrap();
905        assert_eq!(
906            keep,
907            ["third: not hot in the profiled run; `go` ports one function"]
908        );
909    }
910
911    #[test]
912    fn agents_run_headless_and_others_as_given() {
913        let args = |c: &Command| -> Vec<String> {
914            c.get_args()
915                .map(|a| a.to_string_lossy().into_owned())
916                .collect()
917        };
918        let claude = agent_command("claude").unwrap();
919        assert_eq!(claude.get_program(), "claude");
920        assert_eq!(
921            args(&claude)[..3],
922            ["-p", "--permission-mode", "acceptEdits"]
923        );
924        assert_eq!(
925            args(&agent_command("codex").unwrap()),
926            ["exec", "--full-auto", "-"]
927        );
928        let own = agent_command("my-agent --fast").unwrap();
929        assert_eq!(
930            (own.get_program(), args(&own)),
931            ("my-agent".as_ref(), vec!["--fast".to_string()])
932        );
933        assert!(agent_command("  ").is_err());
934    }
935
936    #[test]
937    fn a_slower_port_stays_off_and_says_where_the_speed_is() {
938        let r = report(vec![hot(
939            "score",
940            85.0,
941            true,
942            &["q", "text"],
943            Some("score:text"),
944        )]);
945        let batched = slower_advice(&pick(&r, None).unwrap(), 0.13);
946        assert!(batched.contains("7.7x slower"), "{batched}");
947        assert!(batched.contains("`ScoreBatch`"), "{batched}");
948        assert!(batched.contains("`main` (app.py:9)"), "{batched}");
949        let r = report(vec![hot("dedupe", 85.0, true, &["names"], None)]);
950        let plain = slower_advice(&pick(&r, None).unwrap(), 0.5);
951        assert!(
952            plain.contains("2.0x slower") && plain.contains("--function"),
953            "{plain}"
954        );
955        assert_eq!(times(31.42), "31.4x faster");
956        // Near parity, on both sides: `1.0x` would read as "no change".
957        assert_eq!(times(1.04), "1.04x faster");
958        assert_eq!(times(1.2), "1.2x faster");
959        // A few percent behind is not "1.0x slower": below 1.05 the second decimal is kept.
960        assert_eq!(times(0.97), "1.03x slower");
961        assert_eq!(times(0.96), "1.04x slower");
962        assert_eq!(times(0.9), "1.1x slower");
963        assert_eq!(times(0.5), "2.0x slower");
964    }
965
966    #[test]
967    fn the_other_functions_and_classes_of_the_file_stay_in_the_original() {
968        let root = std::env::temp_dir().join(format!("ra-go-others-{}", std::process::id()));
969        let _ = std::fs::remove_dir_all(&root);
970        std::fs::create_dir_all(&root).unwrap();
971        std::fs::write(
972            root.join("lib.py"),
973            "def hot(xs):\n    return xs\n\n\ndef cold(x):\n    return x\n\n\nclass Table:\n    def __init__(self, n):\n        self.n = n\n\n    def render(self):\n        return str(self.n)\n",
974        )
975        .unwrap();
976        let kept = others(&root, Lang::Python, "lib.py", "hot").unwrap();
977        std::fs::remove_dir_all(&root).unwrap();
978        let names: Vec<&str> = kept.iter().map(|k| k.split(':').next().unwrap()).collect();
979        assert_eq!(names, ["cold", "Table"], "{kept:?}");
980    }
981
982    #[test]
983    fn crate_names_follow_the_function() {
984        assert_eq!(crate_name("fuzzyScore"), "fuzzy-score-rs");
985        assert_eq!(crate_name("dedupe_names"), "dedupe-names-rs");
986    }
987
988    #[test]
989    fn go_refuses_zero_rounds_and_rounds_without_agent() {
990        let opts0 = Options {
991            root: Path::new("."),
992            command: &[],
993            lang: None,
994            agent: None,
995            function: None,
996            count: 200,
997            rounds: Some(0),
998        };
999        let err0 = go(&opts0).unwrap_err().to_string();
1000        assert_eq!(err0, "`--rounds` must be at least 1");
1001
1002        let opts_zero_with_agent = Options {
1003            root: Path::new("."),
1004            command: &[],
1005            lang: None,
1006            agent: Some("claude"),
1007            function: None,
1008            count: 200,
1009            rounds: Some(0),
1010        };
1011        let err0_agent = go(&opts_zero_with_agent).unwrap_err().to_string();
1012        assert_eq!(err0_agent, "`--rounds` must be at least 1");
1013
1014        let opts_no_agent = Options {
1015            root: Path::new("."),
1016            command: &[],
1017            lang: None,
1018            agent: None,
1019            function: None,
1020            count: 200,
1021            rounds: Some(2),
1022        };
1023        let err_no_agent = go(&opts_no_agent).unwrap_err().to_string();
1024        assert_eq!(
1025            err_no_agent,
1026            "`--rounds` needs `--agent`: rounds are agent turns"
1027        );
1028    }
1029
1030    #[test]
1031    fn go_progress_formatting_uses_singular_and_plural_counts() {
1032        assert_eq!(captured_line(1), "captured 1 real call from the workload");
1033        assert_eq!(
1034            captured_line(1000),
1035            "captured 1000 real calls from the workload"
1036        );
1037        assert_eq!(
1038            recorded_line(1, 0),
1039            "recorded 1 case (0 threw in the original)"
1040        );
1041        assert_eq!(
1042            recorded_line(1013, 2),
1043            "recorded 1013 cases (2 threw in the original)"
1044        );
1045        assert_eq!(gate_line(0), "gate passed");
1046        assert_eq!(gate_line(1), "gate: 1 check fails");
1047        assert_eq!(gate_line(2), "gate: 2 checks fail");
1048    }
1049}