Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
//! `go`: the hot-path loop in one command. Profile the workload, bridge the top portable
//! function (the outermost one, batched where `profile` says so), record it, hand the port to
//! an agent, then build, diff and gate it, and switch it on with `enable` only when all pass.
//! Run it again after porting by hand: every finished step is kept.
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{Context, Result, bail};
use serde::Serialize;
use crate::bridge::Manifest;
use crate::lang::Lang;
use crate::profile::{Hot, Report};
pub const TASK: &str = "TASK.md";
pub struct Options<'a> {
pub root: &'a Path,
pub command: &'a [String],
pub lang: Option<Lang>,
/// `claude`, `codex`, or a command that reads the prompt on stdin; `None` stops at the task.
pub agent: Option<&'a str>,
/// Port this function instead of the profile's pick.
pub function: Option<&'a str>,
/// Generated cases per function.
pub count: usize,
/// Agent turns: the first port, then one per failed diff or gate.
pub rounds: Option<usize>,
/// Recorded cases that did not throw, at least, before `go` hands the port to an agent or
/// switches it on (`DEFAULT_MIN_CASES`).
pub min_cases: usize,
}
/// A port checked against a dozen cases, half of them exceptions, says nothing about the
/// original: below this many recorded cases that did not throw, `go` stops and says so.
pub const DEFAULT_MIN_CASES: usize = 20;
#[derive(Debug, Clone, Serialize)]
pub struct Pick {
pub function: String,
pub file: String,
pub line: u32,
pub total_pct: f64,
/// `function:param` passed to `bridge --batch`.
#[serde(skip_serializing_if = "Option::is_none")]
pub batch: Option<String>,
/// The caller that spends the most time in it: `name` and `file:line`.
#[serde(skip_serializing_if = "Option::is_none")]
pub caller: Option<(String, String)>,
pub why: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Stage {
/// The task is written; port `src/port.rs` and run `go` again.
WaitingForPort,
/// Recorded cases still differ after the agent's turns.
Mismatch,
/// Every case matches but a gate check fails.
GateFailed,
/// Too few recorded cases that did not throw to trust a port against: record more inputs
/// (`rust-anything record --inputs`, `--count`) and run `go` again.
Thin,
/// Everything passed and the unit is switched on.
On,
/// Everything passed; this language is switched with the shadow module instead.
Passed,
/// Everything matches, but `bench` times the port slower than the original as its
/// callers call it, so it stays off.
Slower,
}
#[derive(Debug, Clone, Serialize)]
pub struct RecordingFacts {
pub cases: usize,
/// Cases `record` generated; `None` for a recording kept from an earlier run.
#[serde(skip_serializing_if = "Option::is_none")]
pub generated: Option<usize>,
/// Calls the workload made, recorded as cases; `None` when none were captured (or the
/// recording was kept, or the language has no capture).
#[serde(skip_serializing_if = "Option::is_none")]
pub captured: Option<usize>,
/// Cases whose original threw.
pub threw: usize,
}
#[derive(Debug, Serialize)]
pub struct Outcome {
pub stage: Stage,
pub pick: Pick,
pub crate_dir: PathBuf,
pub task: PathBuf,
#[serde(skip_serializing_if = "Option::is_none")]
pub cases: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub matched: Option<usize>,
/// Where the recorded cases came from: generated by `record`, captured from the workload's
/// own calls (TS/JS and Python only), and how many threw in the original.
#[serde(skip_serializing_if = "Option::is_none")]
pub recording: Option<RecordingFacts>,
/// `bench`'s geometric-mean speedup, call included, once every check passed.
#[serde(skip_serializing_if = "Option::is_none")]
pub speedup: Option<f64>,
pub failed_checks: Vec<String>,
pub steps: Vec<String>,
pub next: String,
}
/// The function to port: the first hot one (most time, so the outermost loop) that is exported
/// by a portable unit, can cross the bridge, and takes arguments to record.
pub fn pick(report: &Report, function: Option<&str>) -> Result<Pick> {
let crosses = |h: &&Hot| {
h.unit.is_some() && h.portable && h.js_only.is_none() && h.exported && !h.params.is_empty()
};
let eligible = |h: &&Hot| crosses(h) && !h.mostly_waits();
if function.is_none()
&& report.child_pct >= 50.0
&& let Some(summary) = report.child_summary()
{
let anyway = if report.hot.iter().any(|h| eligible(&h)) {
" To port a function anyway, name it with `--function`."
} else {
""
};
bail!("{summary} {}{anyway}", crate::profile::CHILD_ADVICE);
}
let hot = match function {
Some(name) => report
.hot
.iter()
.filter(|h| h.name == name)
.find(eligible)
.or_else(|| report.hot.iter().find(|h| h.name == name))
.with_context(|| {
format!("`{name}` is not among the hot functions of this run (see `rust-anything profile`)")
})?,
None => report.hot.iter().find(eligible).with_context(|| {
if report.hot.is_empty() {
return "no hot function to port: the profile found no significant time in the \
repository's own code. Try a workload that spends more time in that code."
.into();
}
if report.hot.iter().any(|h| crosses(&h) && h.mostly_waits()) {
let summary = report
.child_summary()
.map_or_else(String::new, |s| format!(" {s}"));
return format!(
"no hot function to port: the ones that could cross the bridge mostly wait on \
child processes.{summary} {}",
crate::profile::CHILD_ADVICE
);
}
format!(
"no hot function to port: none of the {} is exported by a portable \
unit, can cross the bridge and takes arguments. `rust-anything profile` shows why.",
crate::report::count(report.hot.len(), "hot function")
)
})?,
};
if !eligible(&hot) {
if let Some(reason) = &hot.js_only {
bail!(
"`{}` cannot be bridged: `bridge` keeps it in {}: {reason}",
hot.name,
report.language.name()
);
}
if hot.mostly_waits() {
bail!(
"`{}` spends {:.0}% of its time waiting on child processes. {}",
hot.name,
hot.child_pct.unwrap_or_default(),
crate::profile::CHILD_ADVICE
);
}
bail!("`{}` cannot be bridged: {}", hot.name, hot.advice);
}
let why = match &hot.batch {
Some(spec) => format!(
"{:.0}% of the run; called in a loop by `{}`, so it is bridged with `--batch {spec}`",
hot.total_pct,
hot.callers
.first()
.map_or("its caller", |c| c.name.as_str())
),
None => format!(
"{:.0}% of the run, the outermost portable function",
hot.total_pct
),
};
Ok(Pick {
function: hot.name.clone(),
file: hot.file.clone(),
line: hot.line,
total_pct: hot.total_pct,
batch: hot.batch.clone(),
caller: hot
.callers
.first()
.map(|c| (c.name.clone(), format!("{}:{}", c.file, c.line))),
why,
})
}
/// A crate of this name already exists: it is kept only when it ports the same file and has the
/// function. A function of the same name in another file would otherwise reuse the first one's
/// crate and recorded cases (and be reported as ported from the second file).
fn check_kept_crate(crate_dir: &Path, m: &Manifest, pick: &Pick) -> Result<()> {
let norm = |p: &str| p.replace('\\', "/").trim_start_matches("./").to_string();
if norm(&m.unit) != norm(&pick.file) {
bail!(
"{} ports {}, not {}: a function of the same name in another file does not share its \
crate or its recorded cases. Move that crate aside, or port the function you meant \
with `--function`",
crate_dir.display(),
m.unit,
pick.file
);
}
if !m.exports.iter().any(|f| f.name == pick.function) {
bail!(
"{} exists for other functions ({}); move it aside or pass --function",
crate_dir.display(),
m.exports
.iter()
.map(|f| f.name.as_str())
.collect::<Vec<_>>()
.join(", ")
);
}
Ok(())
}
pub fn crate_name(function: &str) -> String {
format!(
"{}-rs",
crate::bridge::snake_case(function).replace('_', "-")
)
}
/// The other exported functions and classes of the file, kept in the original so the crate ports
/// one. A function `bridge` keeps in the original anyway is left to `bridge`, which records its
/// own reason.
fn others(root: &Path, lang: Lang, file: &str, function: &str) -> Result<Vec<String>> {
let text =
std::fs::read_to_string(root.join(file)).with_context(|| format!("reading {file}"))?;
crate::profile::use_project_types(root, lang);
let classes = if lang == Lang::Ts {
crate::ts::exports::exported_classes(file, &text)
} else {
crate::lang::exports(lang, file, &text).1
};
Ok(crate::profile::exports_judged(root, lang, file, &text)
.into_iter()
.filter(|(_, reason)| reason.is_none())
.map(|(f, _)| f.name)
.chain(classes.into_iter().map(|c| c.name))
.filter(|n| n != function)
.map(|n| format!("{n}: not hot in the profiled run; `go` ports one function"))
.collect())
}
pub fn task(crate_dir: &Path, pick: &Pick, command: &[String]) -> String {
let batch = pick.batch.as_ref().map_or_else(String::new, |spec| {
let function = spec.split(':').next().unwrap_or(&pick.function);
format!(
"\nThe crate also has a batch class for `{spec}`, which runs `{function}` over many \
items kept in Rust. A `{}Index` struct in `src/port.rs` can prepare the items once \
(see the Hot paths section of rust-anything's docs/how-it-works.md); `rust-anything go` runs `rust-anything \
refresh` before building, so the batch class uses it.\n",
crate::codegen_batch::pascal(function)
)
});
let rules = match crate::rules::section(crate_dir) {
r if r.is_empty() => r,
r => format!("{r}\n"),
};
format!(
"# Port `{function}` to Rust\n\n\
`{function}` (`{file}:{line}`) took {pct:.0}% of `{command}`. Port it, and only it, in \
`src/port.rs` of this crate ({dir}). The bindings, the recorded cases and \
`rust-anything.json` are generated: leave them as they are.\n{batch}\n\
## Rules\n\n\
- Match the original exactly on every recorded case in `cases.jsonl`: values, errors and \
their messages, edge cases (empty input, Unicode, large numbers). Read the original \
first; port its behavior, not a cleaner idea of it.\n\
- No `unwrap`, `expect` or `panic!` outside tests; no `unsafe` without a `// SAFETY:` comment.\n\
- Keep helpers private; only the unit's functions are `pub`.
- Do not create or edit `known-diffs.jsonl`, `Cargo.toml`, `build.rs`, `src/lib.rs` or the \
recording: a difference accepted there is not a port, and `go` does not switch a unit on over one.\n\
- Never hard-code recorded outputs or weaken tests; gate checks both.\n\
- Keep the port within 3x the original's lines plus 50 (gate's `size` check). If matching \
the original needs more, say so instead of dropping behavior: only the user can allow \
more, with a `[[size]]` decision; do not write one.\n\n\
{rules}\
## Loop\n\n\
```sh\n\
rust-anything build .\n\
rust-anything diff . # every recorded case must match\n\
rust-anything gate . # fmt, clippy, tests, unsafe, API, diff\n\
```\n\n\
Done when `diff` matches every case and `gate` passes. Do not switch the port on; \
`rust-anything go` does that once both pass.\n",
function = pick.function,
file = pick.file,
line = pick.line,
pct = pick.total_pct,
command = command.join(" "),
dir = crate_dir.display(),
)
}
fn waiting_for_port(
function: &str,
port: &Path,
task: &Path,
agent: Option<&str>,
turns: usize,
) -> (Vec<String>, String) {
match agent {
None => (
Vec::new(),
format!(
"Port `{function}` in {} as {} says (or pass --agent claude), then run the same \
`rust-anything go` again.",
port.display(),
task.display()
),
),
Some(agent) => (
vec![format!(
"{} still has `todo!`, `unimplemented!` or functions that only panic after {} \
of `{agent}`",
port.display(),
crate::report::count(turns, "turn")
)],
format!(
"Finish `{function}` in {} as {} says, then run the same `rust-anything go` \
again (a higher `--rounds` gives `{agent}` more turns).",
port.display(),
task.display()
),
),
}
}
/// The agent's command line: `claude` and `codex` run headless with edits allowed in the crate;
/// anything else runs as given, reading the prompt on stdin.
pub fn agent_command(agent: &str) -> Result<Command> {
let words: Vec<&str> = agent.split_whitespace().collect();
let (program, args) = words.split_first().context("--agent is empty")?;
let mut cmd = Command::new(program);
match *program {
"claude" if args.is_empty() => {
cmd.args([
"-p",
"--permission-mode",
"acceptEdits",
"--allowedTools",
"Bash(cargo:*)",
"Bash(rust-anything:*)",
]);
}
"codex" if args.is_empty() => {
cmd.args(["exec", "--full-auto", "-"]);
}
_ => {
cmd.args(args);
}
}
Ok(cmd)
}
fn say(steps: &mut Vec<String>, line: String) {
eprintln!("go: {line}");
steps.push(line);
}
pub fn go(opts: &Options) -> Result<Outcome> {
if let Some(r) = opts.rounds {
anyhow::ensure!(r >= 1, "`--rounds` must be at least 1");
if opts.agent.is_none() {
anyhow::bail!("`--rounds` needs `--agent`: rounds are agent turns");
}
}
let root = crate::walk::resolve_workload_root(opts.root, "go")?;
let lang = opts.lang.unwrap_or_else(|| Lang::detect(&root));
let mut steps = Vec::new();
// The root as given, so the hints `profile_for` prints name it as the person typed it.
let report = crate::profile::profile_for("go", opts.root, opts.command, Some(lang))?;
let pick = pick(&report, opts.function)?;
say(
&mut steps,
format!(
"profiled `{}` ({:.0} ms): porting `{}` ({}:{}), {}",
opts.command.join(" "),
report.total_ms,
pick.function,
pick.file,
pick.line,
pick.why
),
);
let name = crate_name(&pick.function);
let crate_dir = root.join("rust").join(&name);
if crate_dir.join("rust-anything.json").is_file() {
let m = Manifest::load(&crate_dir)?;
check_kept_crate(&crate_dir, &m, &pick)?;
say(
&mut steps,
format!("kept the crate at {}", crate_dir.display()),
);
} else {
let outcome = crate::bridge::bridge(&crate::bridge::Options {
root: &root,
unit: &pick.file,
kind: None,
out: Some(crate_dir.clone()),
name: Some(name.clone()),
force: false,
keep: others(&root, lang, &pick.file, &pick.function)?,
lang: Some(lang),
batch: pick.batch.iter().cloned().collect(),
as_json: Vec::new(),
allocator: crate::bridge::Allocator::default(),
})?;
say(
&mut steps,
format!(
"bridged {} ({}) at {}",
outcome.exports.join(", "),
outcome.kind.label(),
outcome.crate_dir.display()
),
);
}
let manifest = Manifest::load(&crate_dir)?;
let mut _lock = Some(crate::fuzz::RecordingLock::take_recovered(&crate_dir)?);
let cases = crate_dir.join(crate::harness::CASES);
let stale = crate::recording::stale(&crate_dir, &manifest);
let facts;
if !cases.is_file() || stale.is_some() {
let mut _run_inputs = crate::from_tests::RunInputsGuard::new(&crate_dir);
let mut captured_calls = 0;
let captured = match manifest.language {
Lang::Ts | Lang::Python => {
let c = crate::from_tests::capture(&crate_dir, opts.command)?;
_run_inputs.track(&c.inputs);
crate::from_tests::publish_test_inputs(&crate_dir, &c.inputs)?;
captured_calls = c.per_function.values().sum();
say(&mut steps, captured_line(captured_calls));
if let Some(notice) = c.capped_notice() {
say(&mut steps, notice);
}
(captured_calls > 0).then_some(c.inputs)
}
_ => {
say(
&mut steps,
format!(
"no real calls captured for {}: the recording is generated inputs only",
manifest.language.name()
),
);
None
}
};
let recorded = crate::harness::record(&crate::harness::RecordOptions {
crate_dir: &crate_dir,
count: opts.count,
inputs: captured.as_deref(),
module: None,
resolve_from: None,
node_args: &[],
sandbox: false,
})?;
facts = RecordingFacts {
cases: recorded.cases,
generated: Some(recorded.cases.saturating_sub(captured_calls)),
captured: (captured_calls > 0).then_some(captured_calls),
threw: recorded.errors,
};
say(&mut steps, recorded_line(&facts));
} else {
// A recording kept from an earlier run is believed only while it is the one `record`
// wrote: a missing fingerprint file or an edited case is not "kept", it is refused.
let verified = crate::recording::verify(
&crate_dir,
&manifest,
crate::recording::VerifyOptions::default(),
);
if !verified.ok() {
bail!(
"the recorded cases in {} cannot be kept:\n{}",
crate_dir.display(),
verified.refusal()
);
}
facts = recording_facts(&crate_dir);
say(
&mut steps,
format!(
"kept the recorded cases ({} cases, {} threw in the original)",
facts.cases, facts.threw
),
);
}
let ok_cases = facts.cases.saturating_sub(facts.threw);
if ok_cases < opts.min_cases {
let task_path = crate_dir.join(TASK);
return Ok(Outcome {
stage: Stage::Thin,
pick: pick.clone(),
crate_dir: crate_dir.clone(),
task: task_path,
cases: Some(facts.cases),
matched: None,
recording: Some(facts.clone()),
speedup: None,
failed_checks: vec![format!(
"{} recorded ({} threw in the original), {ok_cases} that did not; at least {} \
are needed: a port checked against so few says little about it.",
crate::report::count(facts.cases, "case"),
facts.threw,
opts.min_cases
)],
steps,
next: format!(
"Record more inputs for `{}`: `rust-anything record {} --inputs <file>` with \
JSONL cases {{\"fn\": \"{}\", \"args\": [...]}} that do not throw (real arguments from \
the workload, edge cases), or a higher `--count`, then run the same `go` again. \
`--min-cases` lowers the bar when the function has few possible inputs.",
pick.function,
crate::app::cli_path(&crate_dir),
pick.function
),
});
}
let task_path = crate_dir.join(TASK);
let task = task(&crate_dir, &pick, opts.command);
std::fs::write(&task_path, &task)
.with_context(|| format!("writing {}", task_path.display()))?;
let outcome = |stage, steps, cases, matched, failed_checks, next: String| Outcome {
stage,
pick: pick.clone(),
crate_dir: crate_dir.clone(),
task: task_path.clone(),
cases,
matched,
recording: Some(facts.clone()),
speedup: None,
failed_checks,
steps,
next,
};
let mut prompt = task.clone();
let rounds = if opts.agent.is_some() {
opts.rounds.unwrap_or(3)
} else {
0
};
let mut round = 0;
let mut need_port = !crate::gate::ported_check(&crate_dir).passed;
let (cases, matched) = loop {
if need_port {
let Some(agent) = opts.agent.filter(|_| round < rounds) else {
say(&mut steps, format!("wrote {}", task_path.display()));
let (failed, next) = waiting_for_port(
&pick.function,
&crate_dir.join("src/port.rs"),
&task_path,
opts.agent.filter(|_| round > 0),
round,
);
return Ok(outcome(
Stage::WaitingForPort,
steps,
None,
None,
failed,
next,
));
};
round += 1;
say(
&mut steps,
format!("handing the port to `{agent}` (turn {round} of {rounds})"),
);
let mut cmd = agent_command(agent)?;
cmd.current_dir(&crate_dir).stdout(std::io::stderr());
_lock = None;
let status = crate::process::status_with_input(
&mut cmd,
prompt.as_bytes(),
crate::process::TESTS,
)?;
_lock = Some(crate::fuzz::RecordingLock::take_recovered(&crate_dir)?);
if !status.success() {
bail!("`{agent}` failed ({status})");
}
if !crate::gate::ported_check(&crate_dir).passed {
say(&mut steps, "the agent left stubs in src/port.rs".into());
prompt = format!(
"{task}\n\nsrc/port.rs still has `todo!`, `unimplemented!` or functions that only panic. Finish them.\n"
);
continue;
}
}
let checked = check(&crate_dir, &mut steps)?;
if checked.problems.is_empty() {
break (checked.cases, checked.matched);
}
if round >= rounds || checked.stop {
let stage = checked
.failed_stage
.unwrap_or(if checked.matched < checked.cases {
Stage::Mismatch
} else {
Stage::GateFailed
});
let next = checked.next.unwrap_or_else(|| {
format!(
"Fix the port ({}), then run the same `rust-anything go` again. The unit stays off.",
task_path.display()
)
});
return Ok(outcome(
stage,
steps,
Some(checked.cases),
Some(checked.matched),
checked.problems,
next,
));
}
prompt = format!(
"{task}\n\nYour last port does not pass yet. Fix it:\n\n{}\n",
checked.problems.join("\n\n")
);
need_port = true;
};
let rows = crate::harness::bench(&crate::harness::BenchOptions {
crate_dir: &crate_dir,
min_ms: 200,
resolve_from: None,
node_args: &[],
})?;
let speedup = crate::harness::verdict(&rows, manifest.language, &crate_dir).speedup;
say(
&mut steps,
format!(
"bench: {} as its callers call it, call included",
times(speedup)
),
);
if speedup < 1.0 {
let next = slower_advice(&pick, speedup);
let mut out = outcome(
Stage::Slower,
steps,
Some(cases),
Some(matched),
Vec::new(),
next,
);
out.speedup = Some(speedup);
return Ok(out);
}
let mut out = if crate::enable::is_supported(&manifest) {
let on = crate::enable::enable(&crate_dir)?;
crate::audit::switched(&crate_dir, "go", &on, None, false, &[]);
say(
&mut steps,
format!(
"switched on: {} {} in Rust now ({}); `rust-anything disable {}` turns it off",
on.functions.join(", "),
if on.functions.len() == 1 {
"runs"
} else {
"run"
},
on.files
.iter()
.map(|f| f.display().to_string())
.collect::<Vec<_>>()
.join(", "),
crate::app::cli_path(&crate_dir)
),
);
outcome(
Stage::On,
steps,
Some(cases),
Some(matched),
Vec::new(),
format!(
"Measure it: `rust-anything report {}` writes REPORT.md and card.svg.",
crate::app::cli_path(&crate_dir)
),
)
} else {
outcome(
Stage::Passed,
steps,
Some(cases),
Some(matched),
Vec::new(),
format!(
"Every case matches and gate passes. Switch it in with the shadow module \
(`rust-anything shadow {}`), then `rust-anything report` it.",
crate::app::cli_path(&crate_dir)
),
)
};
out.speedup = Some(speedup);
Ok(out)
}
pub(crate) use crate::harness::speed_phrase as times;
/// What to do when every case matches but the port, called as its callers call it, loses.
pub fn slower_advice(pick: &Pick, speedup: f64) -> String {
let caller = pick.caller.as_ref().map_or_else(
|| "its caller".to_string(),
|(n, at)| format!("`{n}` ({at})"),
);
let lost = times(speedup);
match &pick.batch {
Some(spec) => {
let function = spec.split(':').next().unwrap_or(&pick.function);
format!(
"Every case matches, but called once per item the port is {lost} than the \
original, so it stays off. The speed is in the batch: in {caller}, build \
`{}Batch` once over the items and call it per query (the crate's type \
declarations list its methods), or port {caller} with it. Then `rust-anything enable` and \
`rust-anything report`.",
crate::codegen_batch::pascal(function)
)
}
None => format!(
"Every case matches, but the port is {lost} than the original as {caller} calls it: \
each call into Rust costs more than its work. It stays off. Port {caller} with it \
(`rust-anything go --function <name>`), or keep it in the original."
),
}
}
struct CheckResult {
cases: usize,
matched: usize,
problems: Vec<String>,
failed_stage: Option<Stage>,
next: Option<String>,
stop: bool,
}
fn diff_failure(diff: &crate::harness::DiffOutcome, crate_dir: &Path) -> Option<CheckResult> {
let has_batch_failure = diff.batches.iter().any(|b| !b.ok());
if diff.failed > 0 || has_batch_failure || !diff.missing.is_empty() || diff.total == 0 {
let has_collision = diff.batches.iter().any(|b| {
b.error
.as_deref()
.is_some_and(|e| e.contains("not generated by rust-anything"))
});
let batch_exec_error_only = diff.failed == 0
&& diff.missing.is_empty()
&& diff.total > 0
&& has_batch_failure
&& diff.batches.iter().all(|b| b.ok() || b.error.is_some());
let (failed_stage, next, stop) = if has_collision {
let advice = format!(
"Move or rename `{}` so custom batch index checks can run, then run the same `rust-anything go` again. The unit stays off.",
crate_dir.join(crate::batch_check::TEST_FILE).display()
);
(Some(Stage::GateFailed), Some(advice), true)
} else if batch_exec_error_only {
let advice = "Resolve the batch index check error above, then run the same `rust-anything go` again. The unit stays off.".into();
(Some(Stage::GateFailed), Some(advice), false)
} else {
(Some(Stage::Mismatch), None, false)
};
return Some(CheckResult {
cases: diff.total,
matched: diff.passed,
problems: vec![differences(diff)],
failed_stage,
next,
stop,
});
}
None
}
/// Build, diff and gate: the cases, how many match, and what still fails.
fn check(crate_dir: &Path, steps: &mut Vec<String>) -> Result<CheckResult> {
if !Manifest::load(crate_dir)?.batches.is_empty()
&& let Err(e) = crate::bridge::refresh(crate_dir)
{
say(steps, "refresh failed".into());
return Ok(CheckResult {
cases: 0,
matched: 0,
problems: vec![format!("`rust-anything refresh` fails:\n{e:#}")],
failed_stage: Some(Stage::GateFailed),
next: None,
stop: false,
});
}
if let Err(e) = crate::harness::build(crate_dir) {
say(steps, "the build failed".into());
return Ok(CheckResult {
cases: 0,
matched: 0,
problems: vec![format!("The build fails:\n{e:#}")],
failed_stage: Some(Stage::GateFailed),
next: None,
stop: false,
});
}
let diff = crate::harness::diff(&crate::harness::DiffOptions {
crate_dir,
module: None,
ignore_key_order: false,
node_args: &[],
float_tolerance: None,
})?;
say(steps, diff_line(&diff));
if let Some(failed) = diff_failure(&diff, crate_dir) {
return Ok(failed);
}
let batch_known = crate::batch_check::used_known_diffs(&diff.batches);
if diff.accepted > 0 || batch_known > 0 {
// A difference somebody accepted is a decision for a person; the port is not switched on
// over it, and an agent that wrote the entries does not get to make it.
let batch_note = match batch_known {
0 => String::new(),
1 => "; the custom batch index checks also accept 1 entry from it".into(),
n => format!("; the custom batch index checks also accept {n} entries from it"),
};
return Ok(CheckResult {
cases: diff.total,
matched: diff.passed - diff.accepted.min(diff.passed),
problems: vec![format!(
"{} of {} cases are accepted as known differences ({}{batch_note}), not matches: \
`go` does not switch a unit on over them. Make the port match, or read the \
entries and run `rust-anything gate` with `--accept-known-diffs {}` and \
`enable` yourself. Do not create or edit {}.",
diff.accepted,
diff.total,
crate::recording::KNOWN_DIFFS,
diff.accepted.max(batch_known),
crate::recording::KNOWN_DIFFS
)],
failed_stage: Some(Stage::Mismatch),
next: None,
stop: false,
});
}
let gate = crate::gate::gate(crate_dir, &[])?;
let failed: Vec<String> = gate
.checks
.iter()
.filter(|c| !c.passed)
.map(|c| format!("gate check `{}` fails: {}", c.name, c.detail))
.collect();
say(steps, gate_line(failed.len()));
let failed_stage = (!failed.is_empty()).then_some(Stage::GateFailed);
Ok(CheckResult {
cases: diff.total,
matched: diff.passed,
problems: failed,
failed_stage,
next: None,
stop: false,
})
}
fn captured_line(calls: usize) -> String {
format!(
"captured {} from the workload",
crate::report::count(calls, "real call")
)
}
fn recorded_line(facts: &RecordingFacts) -> String {
let source = match (facts.generated, facts.captured) {
(Some(g), Some(c)) => format!("{g} generated, {c} captured from the workload"),
(Some(g), None) => format!("{g} generated, none captured from the workload"),
_ => String::new(),
};
format!(
"recorded {} ({}{} threw in the original)",
crate::report::count(facts.cases, "case"),
if source.is_empty() {
String::new()
} else {
format!("{source}; ")
},
facts.threw
)
}
/// How many cases a kept recording holds and how many threw.
fn recording_facts(crate_dir: &Path) -> RecordingFacts {
let text = std::fs::read_to_string(crate_dir.join(crate::harness::CASES)).unwrap_or_default();
let (mut cases, mut threw) = (0, 0);
for line in text.lines().filter(|l| !l.trim().is_empty()) {
cases += 1;
if crate::harness::parse_deep(line)
.is_ok_and(|c| c.get("error").is_some() || c.get("panic").is_some())
{
threw += 1;
}
}
RecordingFacts {
cases,
generated: None,
captured: None,
threw,
}
}
/// The diff's own line: accepted cases are counted apart from the cases that match.
fn diff_line(diff: &crate::harness::DiffOutcome) -> String {
if diff.accepted > 0 {
format!(
"diff: {}/{} cases match exactly, {} accepted as known differences ({})",
diff.passed - diff.accepted.min(diff.passed),
diff.total,
diff.accepted,
crate::recording::KNOWN_DIFFS
)
} else {
format!("diff: {}/{} cases match", diff.passed, diff.total)
}
}
fn gate_line(failed: usize) -> String {
match failed {
0 => "gate passed".into(),
1 => "gate: 1 check fails".into(),
n => format!("gate: {n} checks fail"),
}
}
/// What still differs, for the agent's next attempt: each distinct difference with one example
/// and where it starts, or the first raw mismatches when there are no groups.
fn batch_failure_notes(diff: &crate::harness::DiffOutcome) -> Vec<String> {
let mut notes = Vec::new();
for b in diff.batches.iter().filter(|b| !b.ok()) {
notes.push(crate::batch_check::diff_line(b));
for m in b.mismatches.iter().take(5) {
notes.push(format!(" {}", crate::batch_check::mismatch_line(m)));
}
}
notes
}
fn differences(diff: &crate::harness::DiffOutcome) -> String {
let batch_notes = batch_failure_notes(diff);
if diff.failed == 0 && diff.missing.is_empty() && !batch_notes.is_empty() {
return batch_notes.join("\n");
}
let head = format!(
"{} of {} recorded cases differ{}.",
diff.total - diff.passed,
diff.total,
if diff.missing.is_empty() {
String::new()
} else {
format!("; missing from Rust: {}", diff.missing.join(", "))
}
);
let mut out = if diff.groups.is_empty() {
let shown: Vec<String> = diff
.mismatches
.iter()
.take(5)
.map(|m| serde_json::to_string(m).unwrap_or_default())
.collect();
format!("{head} First mismatches:\n{}", shown.join("\n"))
} else {
let diff_count = crate::report::count(diff.groups.len(), "distinct difference");
let mut s = format!("{head} {diff_count}, most cases first:");
for g in diff.groups.iter().take(5) {
let mut example = g.example.clone();
let at = example
.as_object_mut()
.and_then(|m| m.remove("at"))
.and_then(|at| serde_json::from_value::<crate::mismatch::At>(at).ok());
let cases_count = crate::report::count(g.cases, "case");
s += &format!(
"\n- {} ({cases_count}, id {})\n example: {}",
g.label(),
g.id,
serde_json::to_string(&example).unwrap_or_default()
);
if let Some(at) = at {
s += &format!("\n {}", at.describe());
}
}
s
};
if !batch_notes.is_empty() {
out.push('\n');
out.push_str(&batch_notes.join("\n"));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::profile::Caller;
#[test]
fn the_retry_prompt_shows_each_difference_once_with_where_it_starts() {
let mut diff = crate::harness::DiffOutcome {
total: 10,
passed: 6,
failed: 4,
mismatches: (0..4)
.map(|i| serde_json::json!({ "fn": "count", "args": [format!("a\t{i}")], "expected": { "ok": 1 }, "actual": { "ok": 2 } }))
.collect(),
..Default::default()
};
crate::mismatch::annotate(&mut diff);
diff.groups = crate::mismatch::group_mismatches(&diff.mismatches);
let text = differences(&diff);
assert!(
text.starts_with("4 of 10 recorded cases differ. 1 distinct difference,"),
"{text}"
);
assert!(
text.contains("- count: return $ (value) (4 cases, id "),
"{text}"
);
assert_eq!(text.matches("example:").count(), 1, "{text}");
assert!(
text.contains("at return $ (value): expected 1, got 2"),
"{text}"
);
}
#[test]
fn batch_only_diff_failure_is_classified_as_mismatch() {
let diff = crate::harness::DiffOutcome {
total: 5,
passed: 5,
failed: 0,
batches: vec![crate::batch_check::BatchDiff {
function: "count".into(),
index: "CountIndex".into(),
groups: 1,
cases: 5,
passed: 4,
failed: 1,
..Default::default()
}],
..Default::default()
};
let crate_dir = Path::new("rust/unit");
let checked = diff_failure(&diff, crate_dir).expect("batch failure must fail diff check");
assert_eq!(checked.matched, checked.cases);
assert_eq!(checked.failed_stage, Some(Stage::Mismatch));
assert!(checked.next.is_none());
assert!(!checked.stop);
let exec_only = crate::harness::DiffOutcome {
total: 5,
passed: 5,
failed: 0,
batches: vec![crate::batch_check::BatchDiff {
function: "count".into(),
index: "CountIndex".into(),
error: Some(
"tests/rust_anything_batch.rs exists and was not generated by rust-anything"
.into(),
),
..Default::default()
}],
..Default::default()
};
let checked_exec =
diff_failure(&exec_only, crate_dir).expect("batch exec error must fail check");
assert_eq!(checked_exec.failed_stage, Some(Stage::GateFailed));
assert!(
checked_exec.stop,
"handwritten collision must stop `go --agent` retries immediately"
);
assert!(
checked_exec.problems[0].contains("not generated by rust-anything"),
"{:?}",
checked_exec.problems
);
let advice = checked_exec
.next
.as_deref()
.expect("batch exec error should override port-fix advice");
assert!(
advice.contains(
&crate_dir
.join(crate::batch_check::TEST_FILE)
.display()
.to_string()
) && !advice.contains("src/port.rs"),
"{advice}"
);
let compile_exec = crate::harness::DiffOutcome {
total: 5,
passed: 5,
failed: 0,
batches: vec![crate::batch_check::BatchDiff {
function: "count".into(),
index: "CountIndex".into(),
error: Some("batch index check failed to run (exit status: 101)".into()),
..Default::default()
}],
..Default::default()
};
let checked_compile =
diff_failure(&compile_exec, crate_dir).expect("compile error must fail check");
assert_eq!(checked_compile.failed_stage, Some(Stage::GateFailed));
assert!(
!checked_compile.stop,
"compile failure in Index may be fixable by retrying the agent"
);
assert!(
checked_compile
.next
.as_deref()
.is_some_and(|a| a.contains("Resolve the batch index check error above")
&& !a.contains("src/port.rs")),
"{:?}",
checked_compile.next
);
let mixed = crate::harness::DiffOutcome {
total: 5,
passed: 5,
failed: 0,
batches: vec![
crate::batch_check::BatchDiff {
function: "a".into(),
index: "AIndex".into(),
cases: 2,
passed: 1,
failed: 1,
..Default::default()
},
crate::batch_check::BatchDiff {
function: "b".into(),
index: "BIndex".into(),
error: Some("aborted".into()),
..Default::default()
},
],
..Default::default()
};
let checked_mixed = diff_failure(&mixed, crate_dir).expect("mixed failure must fail check");
assert_eq!(checked_mixed.failed_stage, Some(Stage::Mismatch));
assert!(!checked_mixed.stop);
let scalar_plus_collision = crate::harness::DiffOutcome {
total: 5,
passed: 4,
failed: 1,
batches: vec![crate::batch_check::BatchDiff {
function: "count".into(),
index: "CountIndex".into(),
error: Some(
"tests/rust_anything_batch.rs exists and was not generated by rust-anything"
.into(),
),
..Default::default()
}],
..Default::default()
};
let checked_collision = diff_failure(&scalar_plus_collision, crate_dir)
.expect("scalar mismatch + handwritten collision must fail");
assert_eq!(checked_collision.failed_stage, Some(Stage::GateFailed));
assert!(checked_collision.stop);
assert!(
checked_collision
.next
.as_deref()
.is_some_and(|a| a.contains("tests/rust_anything_batch.rs")),
"{:?}",
checked_collision.next
);
let passing = crate::harness::DiffOutcome {
total: 5,
passed: 5,
failed: 0,
batches: vec![crate::batch_check::BatchDiff {
function: "count".into(),
index: "CountIndex".into(),
groups: 1,
cases: 5,
passed: 5,
failed: 0,
..Default::default()
}],
..Default::default()
};
assert!(diff_failure(&passing, crate_dir).is_none());
}
fn hot(name: &str, pct: f64, unit: bool, params: &[&str], batch: Option<&str>) -> Hot {
Hot {
name: name.into(),
file: "app.py".into(),
line: 1,
unit: unit.then(|| "app.py".into()),
exported: true,
self_ms: 1.0,
total_ms: pct,
total_pct: pct,
calls: None,
ns_per_call: None,
callers: vec![Caller {
name: "main".into(),
file: "app.py".into(),
line: 9,
ms: pct,
calls: None,
}],
advice: "Hot, outside the analyzed units.".into(),
portable: unit,
js_only: None,
params: params.iter().map(|p| p.to_string()).collect(),
batch: batch.map(str::to_string),
child_pct: None,
}
}
fn report(hot: Vec<Hot>) -> Report {
Report {
schema: crate::profile::SCHEMA,
language: Lang::Python,
command: vec!["python3".into(), "app.py".into()],
total_ms: 100.0,
repo_pct: 100.0,
hot,
compiled: Vec::new(),
child_pct: 0.0,
child_processes: Vec::new(),
}
}
#[test]
fn the_outermost_portable_function_with_arguments_wins() {
let r = report(vec![
hot("main", 99.0, true, &[], None),
hot("load", 95.0, false, &["path"], None),
hot("dedupe", 90.0, true, &["names", "limit"], None),
hot(
"levenshtein",
85.0,
true,
&["a", "b"],
Some("levenshtein:b"),
),
]);
let p = pick(&r, None).unwrap();
assert_eq!((p.function.as_str(), p.batch), ("dedupe", None));
assert!(p.why.contains("outermost"), "{}", p.why);
}
#[test]
fn a_loop_the_profile_batches_is_bridged_with_its_batch() {
let r = report(vec![
hot("main", 99.0, true, &[], None),
hot(
"levenshtein",
85.0,
true,
&["a", "b"],
Some("levenshtein:b"),
),
]);
let p = pick(&r, None).unwrap();
assert_eq!(p.batch.as_deref(), Some("levenshtein:b"));
assert!(p.why.contains("--batch levenshtein:b"), "{}", p.why);
}
#[test]
fn a_named_function_must_be_portable() {
let r = report(vec![hot("load", 95.0, false, &["path"], None)]);
assert!(pick(&r, Some("load")).is_err());
assert!(pick(&r, Some("missing")).is_err());
assert!(pick(&r, None).is_err());
}
#[test]
fn a_function_that_mostly_waits_on_child_processes_is_passed_over() {
let waits = || {
let mut h = hot("run_all", 40.0, true, &["n"], None);
h.child_pct = Some(95.0);
h
};
let mut r = report(vec![waits(), hot("main", 99.0, true, &[], None)]);
r.child_pct = 38.0;
r.child_processes = vec![crate::profile::ChildProcess {
command: Some("git".into()),
file: "app.py".into(),
line: 4,
function: "run_all".into(),
ms: 38.0,
share: 38.0,
}];
let none = pick(&r, None).unwrap_err().to_string();
assert!(
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`)."),
"{none}"
);
r.hot.push(hot("parse", 30.0, true, &["text"], None));
assert_eq!(pick(&r, None).unwrap().function, "parse");
}
#[test]
fn a_named_function_bridge_keeps_says_so_even_when_it_waits() {
let mut h = hot("each", 80.0, true, &["items"], None);
h.js_only = Some("takes or returns a function".into());
h.child_pct = Some(70.0);
let named = pick(&report(vec![h]), Some("each"))
.unwrap_err()
.to_string();
assert!(
named.contains("cannot be bridged") && named.contains("takes or returns a function"),
"{named}"
);
}
#[test]
fn empty_profile_suggests_a_workload_that_runs_repository_code() {
let mut r = report(vec![]);
r.repo_pct = 0.0;
let err = pick(&r, None).unwrap_err().to_string();
assert!(
err.contains("the profile found no significant time in the repository's own code"),
"{err}"
);
assert!(
err.contains("Try a workload that spends more time in that code"),
"{err}"
);
}
#[test]
fn none_eligible_message_uses_singular_and_plural_count() {
let r1 = report(vec![hot("main", 99.0, true, &[], None)]);
let err1 = pick(&r1, None).unwrap_err().to_string();
assert!(
err1.contains("none of the 1 hot function is exported"),
"{err1}"
);
let r2 = report(vec![
hot("main", 99.0, true, &[], None),
hot("cli", 80.0, true, &[], None),
]);
let err2 = pick(&r2, None).unwrap_err().to_string();
assert!(
err2.contains("none of the 2 hot functions is exported"),
"{err2}"
);
}
#[test]
fn a_named_function_bridge_keeps_says_why_and_yields_to_one_that_can_cross() {
let kept = || {
let mut h = hot("calc", 60.0, true, &["xs", "cb"], None);
h.js_only = Some("takes or returns a function".into());
h
};
let only = pick(&report(vec![kept()]), Some("calc"))
.unwrap_err()
.to_string();
assert!(
only.contains("`bridge` keeps it in Python: takes or returns a function"),
"{only}"
);
let r = report(vec![kept(), hot("calc", 20.0, true, &["n"], None)]);
assert_eq!(pick(&r, Some("calc")).unwrap().total_pct, 20.0);
}
#[test]
fn functions_bridge_keeps_are_left_to_bridge_for_their_reason() {
let root =
std::env::temp_dir().join(format!("rust-anything-go-others-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
std::fs::write(
root.join("plug.js"),
"export function each(items, visit) { for (const it of items) visit(it); }\n\
export function half(n) { return n / 2; }\n\
export function third(n) { return n / 3; }\n",
)
.unwrap();
std::fs::write(
root.join("plug.d.ts"),
"export declare function each<T>(items: T[], visit: (item: T) => void): void;\n",
)
.unwrap();
let keep = others(&root, Lang::Ts, "plug.js", "half").unwrap();
std::fs::remove_dir_all(&root).unwrap();
assert_eq!(
keep,
["third: not hot in the profiled run; `go` ports one function"]
);
}
#[test]
fn agents_run_headless_and_others_as_given() {
let args = |c: &Command| -> Vec<String> {
c.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect()
};
let claude = agent_command("claude").unwrap();
assert_eq!(claude.get_program(), "claude");
assert_eq!(
args(&claude)[..3],
["-p", "--permission-mode", "acceptEdits"]
);
assert_eq!(
args(&agent_command("codex").unwrap()),
["exec", "--full-auto", "-"]
);
let own = agent_command("my-agent --fast").unwrap();
assert_eq!(
(own.get_program(), args(&own)),
("my-agent".as_ref(), vec!["--fast".to_string()])
);
assert!(agent_command(" ").is_err());
}
#[test]
fn a_slower_port_stays_off_and_says_where_the_speed_is() {
let r = report(vec![hot(
"score",
85.0,
true,
&["q", "text"],
Some("score:text"),
)]);
let batched = slower_advice(&pick(&r, None).unwrap(), 0.13);
assert!(batched.contains("7.7x slower"), "{batched}");
assert!(batched.contains("`ScoreBatch`"), "{batched}");
assert!(batched.contains("`main` (app.py:9)"), "{batched}");
let r = report(vec![hot("dedupe", 85.0, true, &["names"], None)]);
let plain = slower_advice(&pick(&r, None).unwrap(), 0.5);
assert!(
plain.contains("2.0x slower") && plain.contains("--function"),
"{plain}"
);
assert_eq!(times(31.42), "31.4x faster");
// Near parity, on both sides: `1.0x` would read as "no change".
assert_eq!(times(1.04), "1.04x faster");
assert_eq!(times(1.2), "1.2x faster");
// A few percent behind is not "1.0x slower": below 1.05 the second decimal is kept.
assert_eq!(times(0.97), "1.03x slower");
assert_eq!(times(0.96), "1.04x slower");
assert_eq!(times(0.9), "1.1x slower");
assert_eq!(times(0.5), "2.0x slower");
}
#[test]
fn the_other_functions_and_classes_of_the_file_stay_in_the_original() {
let root = std::env::temp_dir().join(format!("ra-go-others-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
std::fs::write(
root.join("lib.py"),
"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",
)
.unwrap();
let kept = others(&root, Lang::Python, "lib.py", "hot").unwrap();
std::fs::remove_dir_all(&root).unwrap();
let names: Vec<&str> = kept.iter().map(|k| k.split(':').next().unwrap()).collect();
assert_eq!(names, ["cold", "Table"], "{kept:?}");
}
#[test]
fn a_crate_of_the_same_name_for_another_file_is_not_kept() {
let manifest = |unit: &str| -> Manifest {
serde_json::from_value(serde_json::json!({
"schema": crate::bridge::SCHEMA,
"root": ".",
"unit": unit,
"crate_name": "score-rs",
"kind": "pyo3",
"language": "python",
"exports": [{"name": "score", "file": unit, "line": 1, "params": [], "returns": "int", "is_async": false}],
}))
.unwrap()
};
let pick = Pick {
function: "score".into(),
file: "pkg/b.py".into(),
line: 1,
total_pct: 75.0,
batch: None,
caller: None,
why: String::new(),
};
let dir = Path::new("rust/score-rs");
// `pkg/a.py::score` made the crate; `pkg/b.py::score` must not reuse it.
let err = check_kept_crate(dir, &manifest("pkg/a.py"), &pick)
.unwrap_err()
.to_string();
assert!(err.contains("ports pkg/a.py, not pkg/b.py"), "{err}");
// The same file, however it is spelled, is kept.
assert!(check_kept_crate(dir, &manifest("pkg/b.py"), &pick).is_ok());
assert!(check_kept_crate(dir, &manifest("./pkg/b.py"), &pick).is_ok());
// The same file without the function is the other refusal.
let mut other = pick.clone();
other.function = "rank".into();
let err = check_kept_crate(dir, &manifest("pkg/b.py"), &other)
.unwrap_err()
.to_string();
assert!(err.contains("exists for other functions"), "{err}");
}
#[test]
fn the_diff_line_never_counts_an_accepted_case_as_a_match() {
// "13/13 cases match" was printed over eight wrong cases, each one accepted by an entry
// in known-diffs.jsonl that the agent had written.
let mut diff = crate::harness::DiffOutcome {
total: 13,
passed: 13,
accepted: 8,
..crate::harness::DiffOutcome::default()
};
assert_eq!(
diff_line(&diff),
"diff: 5/13 cases match exactly, 8 accepted as known differences (known-diffs.jsonl)"
);
diff.accepted = 0;
assert_eq!(diff_line(&diff), "diff: 13/13 cases match");
}
#[test]
fn a_kept_recording_reports_how_many_cases_threw() {
let dir = crate::app::temp_dir("go-facts").unwrap();
std::fs::write(
dir.join(crate::harness::CASES),
"{\"fn\":\"f\",\"args\":[1],\"ok\":1}\n{\"fn\":\"f\",\"args\":[null],\"error\":\"TypeError: x\"}\n\n{\"fn\":\"f\",\"args\":[2],\"ok\":2}\n",
)
.unwrap();
let facts = recording_facts(&dir);
assert_eq!((facts.cases, facts.threw), (3, 1));
assert_eq!((facts.generated, facts.captured), (None, None));
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn crate_names_follow_the_function() {
assert_eq!(crate_name("fuzzyScore"), "fuzzy-score-rs");
assert_eq!(crate_name("dedupe_names"), "dedupe-names-rs");
}
#[test]
fn waiting_for_the_port_after_agent_turns_does_not_ask_for_an_agent() {
let port = Path::new("rust/fx-rs/src/port.rs");
let task = Path::new("rust/fx-rs/TASK.md");
let (failed, next) = waiting_for_port("fx", port, task, None, 0);
assert!(failed.is_empty());
assert!(next.contains("--agent claude"), "{next}");
let (failed, next) = waiting_for_port("fx", port, task, Some("claude"), 3);
assert!(!next.contains("pass --agent"), "{next}");
assert!(next.contains("--rounds"), "{next}");
assert_eq!(failed.len(), 1);
assert!(
failed[0].contains("after 3 turns of `claude`"),
"{}",
failed[0]
);
}
#[test]
fn go_refuses_zero_rounds_and_rounds_without_agent() {
let opts0 = Options {
root: Path::new("."),
command: &[],
lang: None,
agent: None,
function: None,
count: 200,
rounds: Some(0),
min_cases: DEFAULT_MIN_CASES,
};
let err0 = go(&opts0).unwrap_err().to_string();
assert_eq!(err0, "`--rounds` must be at least 1");
let opts_zero_with_agent = Options {
root: Path::new("."),
command: &[],
lang: None,
agent: Some("claude"),
function: None,
count: 200,
rounds: Some(0),
min_cases: DEFAULT_MIN_CASES,
};
let err0_agent = go(&opts_zero_with_agent).unwrap_err().to_string();
assert_eq!(err0_agent, "`--rounds` must be at least 1");
let opts_no_agent = Options {
root: Path::new("."),
command: &[],
lang: None,
agent: None,
function: None,
count: 200,
rounds: Some(2),
min_cases: DEFAULT_MIN_CASES,
};
let err_no_agent = go(&opts_no_agent).unwrap_err().to_string();
assert_eq!(
err_no_agent,
"`--rounds` needs `--agent`: rounds are agent turns"
);
}
#[test]
fn go_progress_formatting_uses_singular_and_plural_counts() {
assert_eq!(captured_line(1), "captured 1 real call from the workload");
assert_eq!(
captured_line(1000),
"captured 1000 real calls from the workload"
);
let facts = |cases, generated, captured, threw| RecordingFacts {
cases,
generated,
captured,
threw,
};
assert_eq!(
recorded_line(&facts(1, None, None, 0)),
"recorded 1 case (0 threw in the original)"
);
assert_eq!(
recorded_line(&facts(1013, Some(13), Some(1000), 2)),
"recorded 1013 cases (13 generated, 1000 captured from the workload; 2 threw in the original)"
);
assert_eq!(
recorded_line(&facts(13, Some(13), None, 5)),
"recorded 13 cases (13 generated, none captured from the workload; 5 threw in the original)"
);
assert_eq!(gate_line(0), "gate passed");
assert_eq!(gate_line(1), "gate: 1 check fails");
assert_eq!(gate_line(2), "gate: 2 checks fail");
}
}