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(
364                    &mut steps,
365                    format!("captured {n} real call(s) from the workload"),
366                );
367                (n > 0).then_some(c.inputs)
368            }
369            _ => None,
370        };
371        let recorded = crate::harness::record(&crate::harness::RecordOptions {
372            crate_dir: &crate_dir,
373            count: opts.count,
374            inputs: captured.as_deref(),
375            module: None,
376            resolve_from: None,
377            node_args: &[],
378        })?;
379        say(
380            &mut steps,
381            format!(
382                "recorded {} case(s) ({} throw in the original)",
383                recorded.cases, recorded.errors
384            ),
385        );
386    } else {
387        say(&mut steps, "kept the recorded cases".into());
388    }
389
390    let task_path = crate_dir.join(TASK);
391    let task = task(&crate_dir, &pick, opts.command);
392    std::fs::write(&task_path, &task)
393        .with_context(|| format!("writing {}", task_path.display()))?;
394    let outcome = |stage, steps, cases, matched, failed_checks, next: String| Outcome {
395        stage,
396        pick: pick.clone(),
397        crate_dir: crate_dir.clone(),
398        task: task_path.clone(),
399        cases,
400        matched,
401        speedup: None,
402        failed_checks,
403        steps,
404        next,
405    };
406
407    let mut prompt = task.clone();
408    let rounds = if opts.agent.is_some() {
409        opts.rounds.unwrap_or(3)
410    } else {
411        0
412    };
413    let mut round = 0;
414    let mut need_port = !crate::gate::ported_check(&crate_dir).passed;
415    let (cases, matched) = loop {
416        if need_port {
417            let Some(agent) = opts.agent.filter(|_| round < rounds) else {
418                say(&mut steps, format!("wrote {}", task_path.display()));
419                return Ok(outcome(
420                    Stage::WaitingForPort,
421                    steps,
422                    None,
423                    None,
424                    Vec::new(),
425                    format!(
426                        "Port `{}` in {} as {} says (or pass --agent claude), then run the same \
427                         `rust-anything go` again.",
428                        pick.function,
429                        crate_dir.join("src/port.rs").display(),
430                        task_path.display()
431                    ),
432                ));
433            };
434            round += 1;
435            say(
436                &mut steps,
437                format!("handing the port to `{agent}` (turn {round} of {rounds})"),
438            );
439            let mut cmd = agent_command(agent)?;
440            cmd.current_dir(&crate_dir).stdout(std::io::stderr());
441            let status = crate::process::status_with_input(
442                &mut cmd,
443                prompt.as_bytes(),
444                crate::process::TESTS,
445            )?;
446            if !status.success() {
447                bail!("`{agent}` failed ({status})");
448            }
449            if !crate::gate::ported_check(&crate_dir).passed {
450                say(&mut steps, "the agent left stubs in src/port.rs".into());
451                prompt = format!(
452                    "{task}\n\nsrc/port.rs still has `todo!`, `unimplemented!` or functions that only panic. Finish them.\n"
453                );
454                continue;
455            }
456        }
457
458        let (cases, matched, problems) = check(&crate_dir, &mut steps)?;
459        if problems.is_empty() {
460            break (cases, matched);
461        }
462        if round >= rounds {
463            let stage = if matched < cases {
464                Stage::Mismatch
465            } else {
466                Stage::GateFailed
467            };
468            return Ok(outcome(
469                stage,
470                steps,
471                Some(cases),
472                Some(matched),
473                problems,
474                format!(
475                    "Fix the port ({}), then run the same `rust-anything go` again. The unit stays off.",
476                    task_path.display()
477                ),
478            ));
479        }
480        prompt = format!(
481            "{task}\n\nYour last port does not pass yet. Fix it:\n\n{}\n",
482            problems.join("\n\n")
483        );
484        need_port = true;
485    };
486
487    let rows = crate::harness::bench(&crate::harness::BenchOptions {
488        crate_dir: &crate_dir,
489        min_ms: 200,
490        resolve_from: None,
491        node_args: &[],
492    })?;
493    let speedup = crate::harness::verdict(&rows, manifest.language).speedup;
494    say(
495        &mut steps,
496        format!(
497            "bench: {} as its callers call it, call included",
498            times(speedup)
499        ),
500    );
501    if speedup < 1.0 {
502        let next = slower_advice(&pick, speedup);
503        let mut out = outcome(
504            Stage::Slower,
505            steps,
506            Some(cases),
507            Some(matched),
508            Vec::new(),
509            next,
510        );
511        out.speedup = Some(speedup);
512        return Ok(out);
513    }
514
515    let mut out = if crate::enable::is_supported(&manifest) {
516        let on = crate::enable::enable(&crate_dir)?;
517        say(
518            &mut steps,
519            format!(
520                "switched on: {} {} in Rust now ({}); `rust-anything disable {}` turns it off",
521                on.functions.join(", "),
522                if on.functions.len() == 1 {
523                    "runs"
524                } else {
525                    "run"
526                },
527                on.files
528                    .iter()
529                    .map(|f| f.display().to_string())
530                    .collect::<Vec<_>>()
531                    .join(", "),
532                crate_dir.display()
533            ),
534        );
535        outcome(
536            Stage::On,
537            steps,
538            Some(cases),
539            Some(matched),
540            Vec::new(),
541            format!(
542                "Measure it: `rust-anything report {}` writes REPORT.md and card.svg.",
543                crate_dir.display()
544            ),
545        )
546    } else {
547        outcome(
548            Stage::Passed,
549            steps,
550            Some(cases),
551            Some(matched),
552            Vec::new(),
553            format!(
554                "Every case matches and gate passes. Switch it in with the shadow module \
555                 (`rust-anything shadow {}`), then `rust-anything report` it.",
556                crate_dir.display()
557            ),
558        )
559    };
560    out.speedup = Some(speedup);
561    Ok(out)
562}
563
564pub(crate) use crate::harness::speed_phrase as times;
565
566/// What to do when every case matches but the port, called as its callers call it, loses.
567pub fn slower_advice(pick: &Pick, speedup: f64) -> String {
568    let caller = pick.caller.as_ref().map_or_else(
569        || "its caller".to_string(),
570        |(n, at)| format!("`{n}` ({at})"),
571    );
572    let lost = times(speedup);
573    match &pick.batch {
574        Some(spec) => {
575            let function = spec.split(':').next().unwrap_or(&pick.function);
576            format!(
577                "Every case matches, but called once per item the port is {lost} than the \
578                 original, so it stays off. The speed is in the batch: in {caller}, build \
579                 `{}Batch` once over the items and call it per query (the crate's type \
580                 declarations list its methods), or port {caller} with it. Then `rust-anything enable` and \
581                 `rust-anything report`.",
582                crate::codegen_batch::pascal(function)
583            )
584        }
585        None => format!(
586            "Every case matches, but the port is {lost} than the original as {caller} calls it: \
587             each call into Rust costs more than its work. It stays off. Port {caller} with it \
588             (`rust-anything go --function <name>`), or keep it in the original."
589        ),
590    }
591}
592
593/// Build, diff and gate: the cases, how many match, and what still fails.
594fn check(crate_dir: &Path, steps: &mut Vec<String>) -> Result<(usize, usize, Vec<String>)> {
595    if !Manifest::load(crate_dir)?.batches.is_empty()
596        && let Err(e) = crate::bridge::refresh(crate_dir)
597    {
598        say(steps, "refresh failed".into());
599        return Ok((0, 0, vec![format!("`rust-anything refresh` fails:\n{e:#}")]));
600    }
601    if let Err(e) = crate::harness::build(crate_dir) {
602        say(steps, "the build failed".into());
603        return Ok((0, 0, vec![format!("The build fails:\n{e:#}")]));
604    }
605    let diff = crate::harness::diff(&crate::harness::DiffOptions {
606        crate_dir,
607        module: None,
608        ignore_key_order: false,
609        node_args: &[],
610        float_tolerance: None,
611    })?;
612    say(
613        steps,
614        format!("diff: {}/{} cases match", diff.passed, diff.total),
615    );
616    if diff.failed > 0 || !diff.missing.is_empty() || diff.total == 0 {
617        return Ok((diff.total, diff.passed, vec![differences(&diff)]));
618    }
619    let gate = crate::gate::gate(crate_dir, &[])?;
620    let failed: Vec<String> = gate
621        .checks
622        .iter()
623        .filter(|c| !c.passed)
624        .map(|c| format!("gate check `{}` fails: {}", c.name, c.detail))
625        .collect();
626    say(
627        steps,
628        if failed.is_empty() {
629            "gate passed".into()
630        } else {
631            format!("gate: {} check(s) fail", failed.len())
632        },
633    );
634    Ok((diff.total, diff.passed, failed))
635}
636
637/// What still differs, for the agent's next attempt: each distinct difference with one example
638/// and where it starts, or the first raw mismatches when there are no groups.
639fn differences(diff: &crate::harness::DiffOutcome) -> String {
640    let head = format!(
641        "{} of {} recorded cases differ{}.",
642        diff.total - diff.passed,
643        diff.total,
644        if diff.missing.is_empty() {
645            String::new()
646        } else {
647            format!("; missing from Rust: {}", diff.missing.join(", "))
648        }
649    );
650    if diff.groups.is_empty() {
651        let shown: Vec<String> = diff
652            .mismatches
653            .iter()
654            .take(5)
655            .map(|m| serde_json::to_string(m).unwrap_or_default())
656            .collect();
657        return format!("{head} First mismatches:\n{}", shown.join("\n"));
658    }
659    let mut out = format!(
660        "{head} {} distinct difference(s), most cases first:",
661        diff.groups.len()
662    );
663    for g in diff.groups.iter().take(5) {
664        let mut example = g.example.clone();
665        let at = example
666            .as_object_mut()
667            .and_then(|m| m.remove("at"))
668            .and_then(|at| serde_json::from_value::<crate::mismatch::At>(at).ok());
669        out += &format!(
670            "\n- {} ({} case(s), id {})\n  example: {}",
671            g.label(),
672            g.cases,
673            g.id,
674            serde_json::to_string(&example).unwrap_or_default()
675        );
676        if let Some(at) = at {
677            out += &format!("\n  {}", at.describe());
678        }
679    }
680    out
681}
682
683#[cfg(test)]
684mod tests {
685    use super::*;
686    use crate::profile::Caller;
687
688    #[test]
689    fn the_retry_prompt_shows_each_difference_once_with_where_it_starts() {
690        let mut diff = crate::harness::DiffOutcome {
691            total: 10,
692            passed: 6,
693            failed: 4,
694            mismatches: (0..4)
695                .map(|i| serde_json::json!({ "fn": "count", "args": [format!("a\t{i}")], "expected": { "ok": 1 }, "actual": { "ok": 2 } }))
696                .collect(),
697            ..Default::default()
698        };
699        crate::mismatch::annotate(&mut diff);
700        diff.groups = crate::mismatch::group_mismatches(&diff.mismatches);
701        let text = differences(&diff);
702        assert!(
703            text.starts_with("4 of 10 recorded cases differ. 1 distinct difference(s)"),
704            "{text}"
705        );
706        assert!(
707            text.contains("- count: return $ (value) (4 case(s), id "),
708            "{text}"
709        );
710        assert_eq!(text.matches("example:").count(), 1, "{text}");
711        assert!(
712            text.contains("at return $ (value): expected 1, got 2"),
713            "{text}"
714        );
715    }
716
717    fn hot(name: &str, pct: f64, unit: bool, params: &[&str], batch: Option<&str>) -> Hot {
718        Hot {
719            name: name.into(),
720            file: "app.py".into(),
721            line: 1,
722            unit: unit.then(|| "app.py".into()),
723            exported: true,
724            self_ms: 1.0,
725            total_ms: pct,
726            total_pct: pct,
727            calls: None,
728            ns_per_call: None,
729            callers: vec![Caller {
730                name: "main".into(),
731                file: "app.py".into(),
732                line: 9,
733                ms: pct,
734                calls: None,
735            }],
736            advice: "Hot, outside the analyzed units.".into(),
737            portable: unit,
738            js_only: None,
739            params: params.iter().map(|p| p.to_string()).collect(),
740            batch: batch.map(str::to_string),
741            child_pct: None,
742        }
743    }
744
745    fn report(hot: Vec<Hot>) -> Report {
746        Report {
747            schema: crate::profile::SCHEMA,
748            language: Lang::Python,
749            command: vec!["python3".into(), "app.py".into()],
750            total_ms: 100.0,
751            repo_pct: 100.0,
752            hot,
753            compiled: Vec::new(),
754            child_pct: 0.0,
755            child_processes: Vec::new(),
756        }
757    }
758
759    #[test]
760    fn the_outermost_portable_function_with_arguments_wins() {
761        let r = report(vec![
762            hot("main", 99.0, true, &[], None),
763            hot("load", 95.0, false, &["path"], None),
764            hot("dedupe", 90.0, true, &["names", "limit"], None),
765            hot(
766                "levenshtein",
767                85.0,
768                true,
769                &["a", "b"],
770                Some("levenshtein:b"),
771            ),
772        ]);
773        let p = pick(&r, None).unwrap();
774        assert_eq!((p.function.as_str(), p.batch), ("dedupe", None));
775        assert!(p.why.contains("outermost"), "{}", p.why);
776    }
777
778    #[test]
779    fn a_loop_the_profile_batches_is_bridged_with_its_batch() {
780        let r = report(vec![
781            hot("main", 99.0, true, &[], None),
782            hot(
783                "levenshtein",
784                85.0,
785                true,
786                &["a", "b"],
787                Some("levenshtein:b"),
788            ),
789        ]);
790        let p = pick(&r, None).unwrap();
791        assert_eq!(p.batch.as_deref(), Some("levenshtein:b"));
792        assert!(p.why.contains("--batch levenshtein:b"), "{}", p.why);
793    }
794
795    #[test]
796    fn a_named_function_must_be_portable() {
797        let r = report(vec![hot("load", 95.0, false, &["path"], None)]);
798        assert!(pick(&r, Some("load")).is_err());
799        assert!(pick(&r, Some("missing")).is_err());
800        assert!(pick(&r, None).is_err());
801    }
802
803    #[test]
804    fn a_function_that_mostly_waits_on_child_processes_is_passed_over() {
805        let waits = || {
806            let mut h = hot("run_all", 40.0, true, &["n"], None);
807            h.child_pct = Some(95.0);
808            h
809        };
810        let mut r = report(vec![waits(), hot("main", 99.0, true, &[], None)]);
811        r.child_pct = 38.0;
812        r.child_processes = vec![crate::profile::ChildProcess {
813            command: Some("git".into()),
814            file: "app.py".into(),
815            line: 4,
816            function: "run_all".into(),
817            ms: 38.0,
818            share: 38.0,
819        }];
820        let none = pick(&r, None).unwrap_err().to_string();
821        assert!(
822            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`)."),
823            "{none}"
824        );
825        r.hot.push(hot("parse", 30.0, true, &["text"], None));
826        assert_eq!(pick(&r, None).unwrap().function, "parse");
827    }
828
829    #[test]
830    fn a_named_function_bridge_keeps_says_so_even_when_it_waits() {
831        let mut h = hot("each", 80.0, true, &["items"], None);
832        h.js_only = Some("takes or returns a function".into());
833        h.child_pct = Some(70.0);
834        let named = pick(&report(vec![h]), Some("each"))
835            .unwrap_err()
836            .to_string();
837        assert!(
838            named.contains("cannot be bridged") && named.contains("takes or returns a function"),
839            "{named}"
840        );
841    }
842
843    #[test]
844    fn none_eligible_message_uses_singular_and_plural_count() {
845        let r1 = report(vec![hot("main", 99.0, true, &[], None)]);
846        let err1 = pick(&r1, None).unwrap_err().to_string();
847        assert!(
848            err1.contains("none of the 1 hot function is exported"),
849            "{err1}"
850        );
851
852        let r2 = report(vec![
853            hot("main", 99.0, true, &[], None),
854            hot("cli", 80.0, true, &[], None),
855        ]);
856        let err2 = pick(&r2, None).unwrap_err().to_string();
857        assert!(
858            err2.contains("none of the 2 hot functions is exported"),
859            "{err2}"
860        );
861    }
862
863    #[test]
864    fn a_named_function_bridge_keeps_says_why_and_yields_to_one_that_can_cross() {
865        let kept = || {
866            let mut h = hot("calc", 60.0, true, &["xs", "cb"], None);
867            h.js_only = Some("takes or returns a function".into());
868            h
869        };
870        let only = pick(&report(vec![kept()]), Some("calc"))
871            .unwrap_err()
872            .to_string();
873        assert!(
874            only.contains("`bridge` keeps it in Python: takes or returns a function"),
875            "{only}"
876        );
877        let r = report(vec![kept(), hot("calc", 20.0, true, &["n"], None)]);
878        assert_eq!(pick(&r, Some("calc")).unwrap().total_pct, 20.0);
879    }
880
881    #[test]
882    fn functions_bridge_keeps_are_left_to_bridge_for_their_reason() {
883        let root =
884            std::env::temp_dir().join(format!("rust-anything-go-others-{}", std::process::id()));
885        let _ = std::fs::remove_dir_all(&root);
886        std::fs::create_dir_all(&root).unwrap();
887        std::fs::write(
888            root.join("plug.js"),
889            "export function each(items, visit) { for (const it of items) visit(it); }\n\
890             export function half(n) { return n / 2; }\n\
891             export function third(n) { return n / 3; }\n",
892        )
893        .unwrap();
894        std::fs::write(
895            root.join("plug.d.ts"),
896            "export declare function each<T>(items: T[], visit: (item: T) => void): void;\n",
897        )
898        .unwrap();
899        let keep = others(&root, Lang::Ts, "plug.js", "half").unwrap();
900        std::fs::remove_dir_all(&root).unwrap();
901        assert_eq!(
902            keep,
903            ["third: not hot in the profiled run; `go` ports one function"]
904        );
905    }
906
907    #[test]
908    fn agents_run_headless_and_others_as_given() {
909        let args = |c: &Command| -> Vec<String> {
910            c.get_args()
911                .map(|a| a.to_string_lossy().into_owned())
912                .collect()
913        };
914        let claude = agent_command("claude").unwrap();
915        assert_eq!(claude.get_program(), "claude");
916        assert_eq!(
917            args(&claude)[..3],
918            ["-p", "--permission-mode", "acceptEdits"]
919        );
920        assert_eq!(
921            args(&agent_command("codex").unwrap()),
922            ["exec", "--full-auto", "-"]
923        );
924        let own = agent_command("my-agent --fast").unwrap();
925        assert_eq!(
926            (own.get_program(), args(&own)),
927            ("my-agent".as_ref(), vec!["--fast".to_string()])
928        );
929        assert!(agent_command("  ").is_err());
930    }
931
932    #[test]
933    fn a_slower_port_stays_off_and_says_where_the_speed_is() {
934        let r = report(vec![hot(
935            "score",
936            85.0,
937            true,
938            &["q", "text"],
939            Some("score:text"),
940        )]);
941        let batched = slower_advice(&pick(&r, None).unwrap(), 0.13);
942        assert!(batched.contains("7.7x slower"), "{batched}");
943        assert!(batched.contains("`ScoreBatch`"), "{batched}");
944        assert!(batched.contains("`main` (app.py:9)"), "{batched}");
945        let r = report(vec![hot("dedupe", 85.0, true, &["names"], None)]);
946        let plain = slower_advice(&pick(&r, None).unwrap(), 0.5);
947        assert!(
948            plain.contains("2.0x slower") && plain.contains("--function"),
949            "{plain}"
950        );
951        assert_eq!(times(31.42), "31.4x faster");
952        // Near parity, on both sides: `1.0x` would read as "no change".
953        assert_eq!(times(1.04), "1.04x faster");
954        assert_eq!(times(1.2), "1.2x faster");
955        // A few percent behind is not "1.0x slower": below 1.05 the second decimal is kept.
956        assert_eq!(times(0.97), "1.03x slower");
957        assert_eq!(times(0.96), "1.04x slower");
958        assert_eq!(times(0.9), "1.1x slower");
959        assert_eq!(times(0.5), "2.0x slower");
960    }
961
962    #[test]
963    fn the_other_functions_and_classes_of_the_file_stay_in_the_original() {
964        let root = std::env::temp_dir().join(format!("ra-go-others-{}", std::process::id()));
965        let _ = std::fs::remove_dir_all(&root);
966        std::fs::create_dir_all(&root).unwrap();
967        std::fs::write(
968            root.join("lib.py"),
969            "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",
970        )
971        .unwrap();
972        let kept = others(&root, Lang::Python, "lib.py", "hot").unwrap();
973        std::fs::remove_dir_all(&root).unwrap();
974        let names: Vec<&str> = kept.iter().map(|k| k.split(':').next().unwrap()).collect();
975        assert_eq!(names, ["cold", "Table"], "{kept:?}");
976    }
977
978    #[test]
979    fn crate_names_follow_the_function() {
980        assert_eq!(crate_name("fuzzyScore"), "fuzzy-score-rs");
981        assert_eq!(crate_name("dedupe_names"), "dedupe-names-rs");
982    }
983
984    #[test]
985    fn go_refuses_zero_rounds_and_rounds_without_agent() {
986        let opts0 = Options {
987            root: Path::new("."),
988            command: &[],
989            lang: None,
990            agent: None,
991            function: None,
992            count: 200,
993            rounds: Some(0),
994        };
995        let err0 = go(&opts0).unwrap_err().to_string();
996        assert_eq!(err0, "`--rounds` must be at least 1");
997
998        let opts_zero_with_agent = Options {
999            root: Path::new("."),
1000            command: &[],
1001            lang: None,
1002            agent: Some("claude"),
1003            function: None,
1004            count: 200,
1005            rounds: Some(0),
1006        };
1007        let err0_agent = go(&opts_zero_with_agent).unwrap_err().to_string();
1008        assert_eq!(err0_agent, "`--rounds` must be at least 1");
1009
1010        let opts_no_agent = Options {
1011            root: Path::new("."),
1012            command: &[],
1013            lang: None,
1014            agent: None,
1015            function: None,
1016            count: 200,
1017            rounds: Some(2),
1018        };
1019        let err_no_agent = go(&opts_no_agent).unwrap_err().to_string();
1020        assert_eq!(
1021            err_no_agent,
1022            "`--rounds` needs `--agent`: rounds are agent turns"
1023        );
1024    }
1025}