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