2 Commits
Author SHA1 Message Date
hermes 6d35274f39 Merge pull request 'M5: affected tests at turn end' (#62) from m5-tests into main
ci / check (push) Canceled after 0s
2026-09-30 15:03:30 +00:00
hermes f4e55c8dd3 M5: affected tests at turn end (closes #35 #36 #37 #38 #39 #40 #41)
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s
2026-09-30 15:03:17 +00:00
8 changed files with 1347 additions and 0 deletions

No files matched your search

+7
View File
@@ -31,6 +31,7 @@ mode = "turn_end" # turn_end | agent_end | off
disable = ["clangd"]
enable_runners = ["clippy"] # opt-in (slow): clippy
disable_runners = ["rustfmt"] # any of: ruff, biome, eslint, ast-grep, rustfmt, ruff-format, biome-format
tests = "turn_end" # affected tests: turn_end | agent_end | off
# [[lsp.servers]] # add or override (same id replaces built-in)
# id = "zls"
# language = "zig"
@@ -55,6 +56,12 @@ their changes don't trip the read-guard. Files edited outside hx are picked up a
`diag_mark` lets the model silence a finding (`false_positive` = forever, `defer` = until the file changes),
stored in `~/.hx/projects/<project>/triage.json`. Runner timings go to `~/.hx/latency.log`.
Affected tests run after each tool round that changed files; only failures are injected (plus one
"all pass now" notice after they're fixed). Supported: cargo, pytest, vitest, jest, `go test`. Selection is
a heuristic: Rust runs the changed crate and crates depending on it; Go the changed package and importers;
Python/JS the test files that are changed or import a changed file (up to 3 hops). Rust/Go therefore
over-select (whole crates/packages); dynamic imports, fixtures and data files are not tracked.
Existing Claude Code (`~/.claude/.credentials.json`) and Codex CLI (`~/.codex/auth.json`) logins are picked up automatically.
Credentials are stored in `~/.hx/auth.json` (mode 0600) and refreshed automatically.
+8
View File
@@ -68,6 +68,8 @@ struct LspCfg {
enable_runners: Vec<String>,
/// runner ids to disable (e.g. "rustfmt", "biome-format")
disable_runners: Vec<String>,
/// affected tests: turn_end (default) | agent_end | off
tests: Option<hx_lens::testrun::TestMode>,
}
impl Config {
@@ -268,6 +270,12 @@ async fn main() -> Result<()> {
agent.bus.add(ArcHook(lens.clone()));
agent.tools.add(hx_lens::DiagMark { lens: lens.clone() });
agent.tools.add(hx_lens::LspTool { mgr: mgr.clone() });
let tmode = lcfg.tests.unwrap_or(hx_lens::testrun::TestMode::TurnEnd);
if tmode != hx_lens::testrun::TestMode::Off {
agent
.bus
.add(hx_lens::testrun::TestLens::new(cwd.clone(), tmode));
}
// rust-analyzer & co are slow to index: start servers for languages present at the top level now
let probe: Vec<_> = std::fs::read_dir(&cwd)
.into_iter()
+369
View File
@@ -0,0 +1,369 @@
//! Import graph + reverse deps for Rust (crate level), TS/JS, Python (file level), Go (package dir level).
//!
//! ponytail: line-based import scanning, not tree-sitter. Misses imports built at runtime and multi-line
//! `use {..}` groups spanning many lines (Rust is crate-level anyway). Upgrade to tree-sitter queries if
//! selection misses show up in practice.
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
const SKIP: &[&str] = &[
"target",
"node_modules",
"dist",
"build",
"vendor",
"__pycache__",
"venv",
];
const JS: &[&str] = &["ts", "tsx", "js", "jsx", "mjs", "cjs"];
#[derive(Default, Debug)]
pub struct Graph {
/// node -> nodes that import it. Nodes: files (py/js), package dirs (go), crate roots (rust).
pub rev: HashMap<PathBuf, HashSet<PathBuf>>,
}
pub fn walk(ws: &Path) -> Vec<PathBuf> {
let mut out = vec![];
let mut stack = vec![ws.to_path_buf()];
while let Some(d) = stack.pop() {
for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {
let p = e.path();
let n = e.file_name();
let n = n.to_string_lossy();
if n.starts_with('.') || SKIP.contains(&n.as_ref()) {
continue;
}
match e.file_type() {
Ok(t) if t.is_dir() => stack.push(p),
Ok(t) if t.is_file() => out.push(p),
_ => {}
}
}
}
out.sort();
out
}
/// Graph node for a file: the crate root for .rs, the dir for .go, the file itself otherwise.
pub fn node(file: &Path, ws: &Path) -> PathBuf {
match file.extension().and_then(|e| e.to_str()) {
Some("rs") => crate::runners::marker_root(file, &["Cargo.toml"], ws).unwrap_or(ws.into()),
Some("go") => file.parent().unwrap_or(ws).into(),
_ => file.into(),
}
}
fn quoted(l: &str) -> Vec<&str> {
let mut v = vec![];
for q in ['"', '\''] {
let mut s = l;
while let Some(i) = s.find(q) {
let r = &s[i + 1..];
let Some(j) = r.find(q) else { break };
v.push(&r[..j]);
s = &r[j + 1..];
}
}
v
}
fn resolve_js(from: &Path, spec: &str) -> Option<PathBuf> {
if !spec.starts_with('.') {
return None;
}
let base = from.parent()?.join(spec);
let mut cands = vec![base.clone()];
// TS allows importing "./x.js" for x.ts
let stripped = base.with_extension("");
for e in JS {
cands.push(stripped.with_extension(e));
cands.push(base.join(format!("index.{e}")));
}
cands.into_iter().find(|p| p.is_file()).map(|p| norm(&p))
}
fn norm(p: &Path) -> PathBuf {
let mut out = PathBuf::new();
for c in p.components() {
match c {
std::path::Component::ParentDir => {
out.pop();
}
std::path::Component::CurDir => {}
c => out.push(c),
}
}
out
}
fn resolve_py(from: &Path, module: &str, roots: &[PathBuf]) -> Vec<PathBuf> {
let dots = module.chars().take_while(|c| *c == '.').count();
let rest = &module[dots..];
let bases: Vec<PathBuf> = if dots > 0 {
let mut b = from.parent().map(Path::to_path_buf).unwrap_or_default();
for _ in 1..dots {
b.pop();
}
vec![b]
} else {
roots.to_vec()
};
let rel: PathBuf = rest.split('.').filter(|s| !s.is_empty()).collect();
let mut out = vec![];
for b in bases {
let p = b.join(&rel);
for c in [p.with_extension("py"), p.join("__init__.py")] {
if c.is_file() {
out.push(c);
}
}
}
out
}
fn cargo_name(toml: &str) -> Option<String> {
let pkg = toml.split("[package]").nth(1)?;
pkg.lines()
.find_map(|l| l.trim().strip_prefix("name").map(|r| r.trim_start()))
.and_then(|r| r.strip_prefix('='))
.map(|r| r.trim().trim_matches('"').to_string())
}
pub fn build(ws: &Path) -> Graph {
let files = walk(ws);
let mut g = Graph::default();
let mut add = |dep: PathBuf, user: PathBuf| {
if dep != user {
g.rev.entry(dep).or_default().insert(user);
}
};
// python import roots: workspace, dirs with a pyproject/setup, and `src/` layouts
let mut py_roots: Vec<PathBuf> = vec![ws.into(), ws.join("src")];
// rust crates: name -> root; go modules: module path -> root
let mut crates: HashMap<String, PathBuf> = HashMap::new();
let mut gomods: Vec<(String, PathBuf)> = vec![];
for f in &files {
let dir = f.parent().unwrap_or(ws).to_path_buf();
match f.file_name().and_then(|n| n.to_str()) {
Some("Cargo.toml") => {
if let Some(n) = std::fs::read_to_string(f)
.ok()
.as_deref()
.and_then(cargo_name)
{
crates.insert(n.replace('-', "_"), dir);
}
}
Some("go.mod") => {
let s = std::fs::read_to_string(f).unwrap_or_default();
if let Some(m) = s.lines().find_map(|l| l.strip_prefix("module ")) {
gomods.push((m.trim().to_string(), dir));
}
}
Some("pyproject.toml" | "setup.py" | "setup.cfg") => {
py_roots.push(dir.join("src"));
py_roots.push(dir);
}
_ => {}
}
}
for f in &files {
let ext = f.extension().and_then(|e| e.to_str()).unwrap_or_default();
if !(ext == "py" || ext == "go" || JS.contains(&ext) || f.ends_with("Cargo.toml")) {
continue;
}
let Ok(src) = std::fs::read_to_string(f) else {
continue;
};
if f.ends_with("Cargo.toml") {
// path dependencies: `x = { path = "../x" }`
let me = f.parent().unwrap_or(ws).to_path_buf();
for l in src.lines().filter(|l| l.contains("path")) {
for q in quoted(l) {
let d = norm(&me.join(q));
if d.join("Cargo.toml").is_file() {
add(d, me.clone());
}
}
}
// workspace deps by name: `hx-core.workspace = true` / `hx-core = { workspace = true }`
for l in src.lines() {
let name = l.split(['=', '.']).next().unwrap_or_default().trim();
if let Some(d) = crates.get(&name.replace('-', "_"))
&& l.contains("workspace")
&& *d != me
{
add(d.clone(), me.clone());
}
}
continue;
}
let me = node(f, ws);
for l in src.lines() {
let t = l.trim_start();
match ext {
"py" => {
let m = if let Some(r) = t.strip_prefix("from ") {
r.split_whitespace().next().map(|m| {
// `from . import a, b` -> modules .a, .b
if m.chars().all(|c| c == '.') {
let names = r.split(" import ").nth(1).unwrap_or_default();
names
.split(',')
.map(|n| {
format!(
"{m}{}",
n.split_whitespace().next().unwrap_or_default()
)
})
.collect()
} else {
vec![m.to_string()]
}
})
} else {
t.strip_prefix("import ").map(|r| {
r.split(',')
.filter_map(|x| x.split_whitespace().next())
.map(String::from)
.collect()
})
};
for m in m.unwrap_or_default() {
for d in resolve_py(f, &m, &py_roots) {
add(d, me.clone());
}
}
}
"go" => {
for q in quoted(t) {
for (m, root) in &gomods {
if let Some(r) = q.strip_prefix(m.as_str()) {
add(root.join(r.trim_start_matches('/')), me.clone());
}
}
}
}
_ => {
if t.starts_with("import")
|| t.starts_with("export")
|| t.contains("require(")
|| t.contains("import(")
|| t.starts_with("} from")
{
for q in quoted(t) {
if let Some(d) = resolve_js(f, q) {
add(d, me.clone());
}
}
}
}
}
}
}
g
}
impl Graph {
/// Transitive reverse deps of `node` (excluding itself), breadth-first, capped at `depth`.
pub fn users(&self, node: &Path, depth: usize) -> Vec<PathBuf> {
let mut seen: HashSet<PathBuf> = HashSet::from([node.to_path_buf()]);
let mut frontier = vec![node.to_path_buf()];
let mut out = vec![];
for _ in 0..depth {
let mut next = vec![];
for n in &frontier {
for u in self.rev.get(n).into_iter().flatten() {
if seen.insert(u.clone()) {
out.push(u.clone());
next.push(u.clone());
}
}
}
frontier = next;
}
out.sort();
out
}
}
#[cfg(test)]
mod t {
use super::*;
fn w(ws: &Path, p: &str, s: &str) {
let p = ws.join(p);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, s).unwrap();
}
#[test]
fn reverse_deps() {
let d = tempfile::tempdir().unwrap();
let ws = &std::fs::canonicalize(d.path()).unwrap();
// ts: util <- api <- api.test
w(ws, "web/src/util.ts", "export const x = 1\n");
w(ws, "web/src/api.ts", "import { x } from './util'\n");
w(
ws,
"web/src/api.test.ts",
"import {\n a,\n} from \"./api.js\"\n",
);
w(
ws,
"web/node_modules/z/index.ts",
"import './../../src/util'\n",
);
// py: pkg/core <- pkg/svc (relative) <- tests/test_svc (absolute)
w(ws, "py/pyproject.toml", "");
w(ws, "py/pkg/__init__.py", "");
w(ws, "py/pkg/core.py", "X = 1\n");
w(ws, "py/pkg/svc.py", "from . import core\n");
w(ws, "py/tests/test_svc.py", "import os, pkg.svc\n");
// go: m/a <- m/b
w(ws, "go/go.mod", "module example.com/m\n\ngo 1.22\n");
w(ws, "go/a/a.go", "package a\n");
w(
ws,
"go/b/b.go",
"package b\nimport (\n\t\"fmt\"\n\t\"example.com/m/a\"\n)\n",
);
// rust: core <- app (workspace dep), core <- tool (path dep)
w(ws, "rs/core/Cargo.toml", "[package]\nname = \"my-core\"\n");
w(
ws,
"rs/app/Cargo.toml",
"[package]\nname = \"app\"\n[dependencies]\nmy-core.workspace = true\n",
);
w(
ws,
"rs/tool/Cargo.toml",
"[package]\nname = \"tool\"\n[dependencies]\nx = { path = \"../core\" }\n",
);
let g = build(ws);
assert_eq!(
g.users(&ws.join("web/src/util.ts"), 3),
vec![ws.join("web/src/api.test.ts"), ws.join("web/src/api.ts")]
);
assert_eq!(
g.users(&ws.join("web/src/util.ts"), 1),
vec![ws.join("web/src/api.ts")]
);
assert_eq!(
g.users(&ws.join("py/pkg/core.py"), 3),
vec![ws.join("py/pkg/svc.py"), ws.join("py/tests/test_svc.py")]
);
assert_eq!(
g.users(&node(&ws.join("go/a/a.go"), ws), 3),
vec![ws.join("go/b")]
);
assert_eq!(
g.users(&node(&ws.join("rs/core/src/lib.rs"), ws), 3),
vec![ws.join("rs/app"), ws.join("rs/tool")]
);
assert!(g.users(&ws.join("web/src/api.test.ts"), 3).is_empty());
}
}
+2
View File
@@ -4,10 +4,12 @@
//! touched this turn and injects one compact block (errors first, grouped by file, capped).
//! - `LspTool`: on-demand diagnostics / definition / references / hover / symbols.
pub mod deps;
pub mod lsp;
pub mod manager;
pub mod runners;
pub mod seq;
pub mod testrun;
pub mod triage;
pub mod watch;
+881
View File
@@ -0,0 +1,881 @@
//! Test adapters: detect the framework for a file, run a scoped selection, parse structured output.
//!
//! cargo (libtest output), pytest (JUnit XML), vitest/jest (JSON reporter), go (`go test -json`).
use crate::manager::which;
use crate::runners::marker_root;
use serde_json::Value;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::process::Command;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Adapter {
Cargo,
Pytest,
Vitest,
Jest,
Go,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Failure {
pub name: String,
/// test file, when the framework reports it
pub file: Option<PathBuf>,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Outcome {
pub passed: usize,
pub failures: Vec<Failure>,
}
/// One scoped run: `targets` empty = the whole root (cargo crate), else test files (py/js) or package dirs (go).
#[derive(Debug, Clone, PartialEq)]
pub struct Run {
pub adapter: Adapter,
pub root: PathBuf,
pub targets: Vec<PathBuf>,
}
pub fn is_test_file(p: &Path) -> bool {
let n = p.file_name().and_then(|s| s.to_str()).unwrap_or_default();
let in_tests_dir = p
.components()
.any(|c| matches!(c.as_os_str().to_str(), Some("tests" | "__tests__")));
match p.extension().and_then(|e| e.to_str()).unwrap_or_default() {
"py" => n.starts_with("test_") || n.ends_with("_test.py"),
"go" => n.ends_with("_test.go"),
"js" | "jsx" | "ts" | "tsx" | "mjs" | "cjs" => {
n.contains(".test.") || n.contains(".spec.") || in_tests_dir && n != "index.ts"
}
"rs" => in_tests_dir,
_ => false,
}
}
/// Framework + root for `file`, or None when no supported test setup is found.
pub fn detect(file: &Path, ws: &Path) -> Option<(Adapter, PathBuf)> {
match file.extension().and_then(|e| e.to_str())? {
"rs" => Some((Adapter::Cargo, marker_root(file, &["Cargo.toml"], ws)?)),
"go" => Some((Adapter::Go, marker_root(file, &["go.mod"], ws)?)),
"py" => Some((
Adapter::Pytest,
marker_root(
file,
&[
"pytest.ini",
"pyproject.toml",
"setup.cfg",
"tox.ini",
"conftest.py",
],
ws,
)?,
)),
"js" | "jsx" | "ts" | "tsx" | "mjs" | "cjs" => {
let root = marker_root(file, &["package.json"], ws)?;
let pkg = std::fs::read_to_string(root.join("package.json")).unwrap_or_default();
if pkg.contains("\"vitest\"") {
Some((Adapter::Vitest, root))
} else if pkg.contains("\"jest\"") {
Some((Adapter::Jest, root))
} else {
None
}
}
_ => None,
}
}
pub fn installed(a: Adapter, root: &Path) -> bool {
match a {
Adapter::Cargo => which("cargo"),
Adapter::Go => which("go"),
Adapter::Pytest => which("pytest"),
Adapter::Vitest => root.join("node_modules/.bin/vitest").exists() || which("vitest"),
Adapter::Jest => root.join("node_modules/.bin/jest").exists() || which("jest"),
}
}
/// Execute `run`. Err = could not produce results (timeout, build failure without test output, etc).
pub async fn run(r: &Run, timeout: Duration) -> Result<Outcome, String> {
let tmp = std::env::temp_dir().join(format!(
"hx-test-{}-{}",
std::process::id(),
hx_ai::auth::now_ms()
));
let bin = |b: &str| {
let local = r.root.join("node_modules/.bin").join(b);
if local.exists() {
local
} else {
PathBuf::from(b)
}
};
let mut cmd = match r.adapter {
Adapter::Cargo => {
let mut c = Command::new("cargo");
c.args(["test", "--no-fail-fast", "--color", "never"]);
c
}
Adapter::Pytest => {
let mut c = Command::new("pytest");
c.args(["-q", "-p", "no:cacheprovider", "--junitxml"])
.arg(&tmp)
.args(&r.targets);
c
}
Adapter::Vitest => {
let mut c = Command::new(bin("vitest"));
c.args(["run", "--reporter=json", "--outputFile"])
.arg(&tmp)
.args(&r.targets);
c
}
Adapter::Jest => {
let mut c = Command::new(bin("jest"));
c.args(["--json", "--outputFile"])
.arg(&tmp)
.args(&r.targets);
c
}
Adapter::Go => {
let mut c = Command::new("go");
c.args(["test", "-json"]);
c.args(r.targets.iter().map(|d| {
let rel = d.strip_prefix(&r.root).unwrap_or(d);
format!("./{}", rel.display())
}));
c
}
};
cmd.current_dir(&r.root)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true);
let o = match tokio::time::timeout(timeout, cmd.output()).await {
Err(_) => return Err(format!("timed out after {}s", timeout.as_secs())),
Ok(Err(e)) => return Err(e.to_string()),
Ok(Ok(o)) => o,
};
let stdout = String::from_utf8_lossy(&o.stdout);
let stderr = String::from_utf8_lossy(&o.stderr);
let file = std::fs::read_to_string(&tmp).ok();
let _ = std::fs::remove_file(&tmp);
let res = match r.adapter {
Adapter::Cargo => Ok(parse_libtest(&stdout)),
Adapter::Go => Ok(parse_go(&stdout)),
Adapter::Pytest => file
.as_deref()
.map(|x| parse_junit(x, &r.root))
.ok_or_else(|| "no junit report".to_string()),
Adapter::Vitest | Adapter::Jest => file
.as_deref()
.ok_or_else(|| "no json report".to_string())
.and_then(parse_jest),
};
match res {
Ok(out) if out.passed == 0 && out.failures.is_empty() && !o.status.success() => {
// nothing ran and the command failed: build/collection error
let tail: Vec<&str> = stderr.lines().chain(stdout.lines()).collect();
let tail = tail[tail.len().saturating_sub(8)..].join("\n");
Err(format!("test run failed:\n{tail}"))
}
x => x,
}
}
fn clip(s: &str, lines: usize) -> String {
let v: Vec<&str> = s.trim().lines().collect();
let mut out = v[..v.len().min(lines)].join("\n");
if v.len() > lines {
out.push_str(&format!("\n… {} more lines", v.len() - lines));
}
out
}
/// libtest human output (`cargo test`).
pub fn parse_libtest(s: &str) -> Outcome {
let mut out = Outcome::default();
let mut msgs: HashMap<String, String> = HashMap::new();
let mut cur: Option<(String, String)> = None;
for line in s.lines() {
if let Some(rest) = line.strip_prefix("test ") {
if let Some(name) = rest.strip_suffix(" ... ok") {
let _ = name;
out.passed += 1;
} else if let Some(name) = rest.strip_suffix(" ... FAILED") {
out.failures.push(Failure {
name: name.to_string(),
file: None,
message: String::new(),
});
}
}
if let Some(n) = line
.strip_prefix("---- ")
.and_then(|x| x.strip_suffix(" stdout ----"))
{
if let Some((k, v)) = cur.take() {
msgs.insert(k, v);
}
cur = Some((n.to_string(), String::new()));
continue;
}
if line == "failures:" || line.starts_with("test result:") {
if let Some((k, v)) = cur.take() {
msgs.insert(k, v);
}
continue;
}
if let Some((_, v)) = cur.as_mut()
&& !line.starts_with("note: run with `RUST_BACKTRACE")
{
// drop the per-run thread id: "thread 'x' (1234) panicked" -> "thread 'x' panicked"
let line = match (line.find("' ("), line.find(") panicked")) {
(Some(a), Some(b)) if line.starts_with("thread '") && a < b => {
format!("{}'{}", &line[..a], &line[b + 1..])
}
_ => line.to_string(),
};
v.push_str(&line);
v.push('\n');
}
}
for f in &mut out.failures {
f.message = clip(msgs.get(&f.name).map_or("", |s| s), 12);
}
out
}
fn unescape(s: &str) -> String {
s.replace("&lt;", "<")
.replace("&gt;", ">")
.replace("&quot;", "\"")
.replace("&apos;", "'")
.replace("&#10;", "\n")
.replace("&amp;", "&")
}
fn attr(tag: &str, name: &str) -> Option<String> {
let k = format!(" {name}=\"");
let i = tag.find(&k)? + k.len();
Some(unescape(&tag[i..i + tag[i..].find('"')?]))
}
/// JUnit XML (pytest `--junitxml`, nextest). Hand-rolled: only `<testcase>` + `<failure>`/`<error>`.
pub fn parse_junit(s: &str, root: &Path) -> Outcome {
let mut out = Outcome::default();
let mut rest = s;
while let Some(i) = rest.find("<testcase") {
rest = &rest[i..];
let open_end = rest.find('>').unwrap_or(rest.len() - 1);
let tag = &rest[..=open_end];
let body_end = if tag.ends_with("/>") {
open_end + 1
} else {
rest.find("</testcase>").map_or(rest.len(), |e| e + 11)
};
let body = &rest[open_end + 1..body_end.max(open_end + 1)];
let name = match (attr(tag, "classname"), attr(tag, "name")) {
(Some(c), Some(n)) if !c.is_empty() => format!("{c}::{n}"),
(_, n) => n.unwrap_or_default(),
};
let fail = ["<failure", "<error"].iter().find_map(|t| body.find(t));
match fail {
Some(j) => {
let ftag_end = body[j..].find('>').map_or(body.len(), |e| j + e);
let ftag = &body[j..=ftag_end.min(body.len() - 1)];
let text_end = body[ftag_end..]
.find("</")
.map_or(body.len(), |e| ftag_end + e);
let text = unescape(body.get(ftag_end + 1..text_end).unwrap_or_default());
let msg = if text.trim().is_empty() {
attr(ftag, "message").unwrap_or_default()
} else {
text
};
out.failures.push(Failure {
name,
file: attr(tag, "file").map(|f| root.join(f)),
message: clip(&msg, 12),
});
}
None if body.contains("<skipped") => {}
None => out.passed += 1,
}
rest = &rest[body_end.min(rest.len())..];
}
out
}
/// Jest / vitest JSON reporter.
pub fn parse_jest(s: &str) -> Result<Outcome, String> {
let v: Value = serde_json::from_str(s).map_err(|e| format!("bad json report: {e}"))?;
let mut out = Outcome::default();
for tr in v["testResults"].as_array().into_iter().flatten() {
let file = tr["name"].as_str().map(PathBuf::from);
let asserts = tr["assertionResults"]
.as_array()
.cloned()
.unwrap_or_default();
for a in &asserts {
match a["status"].as_str() {
Some("passed") => out.passed += 1,
Some("failed") => out.failures.push(Failure {
name: a["fullName"].as_str().unwrap_or_default().to_string(),
file: file.clone(),
message: clip(
&a["failureMessages"]
.as_array()
.into_iter()
.flatten()
.filter_map(|m| m.as_str())
.collect::<Vec<_>>()
.join("\n"),
12,
),
}),
_ => {}
}
}
// suite-level failure (syntax error, import error) with no assertions
if asserts.is_empty() && tr["status"] == "failed" {
out.failures.push(Failure {
name: "(suite)".into(),
file: file.clone(),
message: clip(tr["message"].as_str().unwrap_or_default(), 12),
});
}
}
Ok(out)
}
/// `go test -json` event stream.
pub fn parse_go(s: &str) -> Outcome {
let mut out = Outcome::default();
let mut logs: HashMap<(String, String), String> = HashMap::new();
for line in s.lines() {
let Ok(e) = serde_json::from_str::<Value>(line) else {
continue;
};
let pkg = e["Package"].as_str().unwrap_or_default().to_string();
let test = e["Test"].as_str().unwrap_or_default().to_string();
match e["Action"].as_str() {
Some("output") => logs
.entry((pkg, test))
.or_default()
.push_str(e["Output"].as_str().unwrap_or_default()),
Some("pass") if !test.is_empty() => out.passed += 1,
Some("fail") => {
// package-level fail without tests = build failure; with tests it's just the summary
let has_test_fail = out.failures.iter().any(|f| f.name.starts_with(&pkg));
if test.is_empty() && has_test_fail {
continue;
}
let log = logs
.get(&(pkg.clone(), test.clone()))
.cloned()
.unwrap_or_default();
let log: String = log
.lines()
.filter(|l| {
let t = l.trim();
!(t.starts_with("=== ") || t.starts_with("--- FAIL") || t == "FAIL")
})
.map(|l| format!("{l}\n"))
.collect();
out.failures.push(Failure {
name: if test.is_empty() {
pkg
} else {
format!("{pkg}.{test}")
},
file: None,
message: clip(&log, 12),
});
}
_ => {}
}
}
out
}
/// Scoped selection for changed files. Heuristic (v1):
/// - Rust: `cargo test` in the changed file's crate and every crate depending on it (path/workspace deps).
/// - Go: the changed package dir + importing package dirs, one `go test` per module.
/// - Python/JS: changed test files + test files that import a changed file (up to 3 hops).
///
/// Known false positives: Rust/Go run whole crates/packages, not just affected tests. Known misses:
/// dynamic imports, fixtures/conftest changes, tests that load files at runtime (non-code files never
/// select tests).
pub fn select(changed: &[PathBuf], ws: &Path, g: &crate::deps::Graph) -> Vec<Run> {
let mut runs: Vec<Run> = vec![];
let mut push = |adapter: Adapter, root: PathBuf, target: Option<PathBuf>| match runs
.iter_mut()
.find(|r| r.adapter == adapter && r.root == root)
{
Some(r) => {
if let Some(t) = target
&& !r.targets.contains(&t)
{
r.targets.push(t);
}
}
None => runs.push(Run {
adapter,
root,
targets: target.into_iter().collect(),
}),
};
for f in changed {
let Some((a, root)) = detect(f, ws) else {
continue;
};
let node = crate::deps::node(f, ws);
let mut nodes = vec![node.clone()];
nodes.extend(g.users(&node, 3));
for n in nodes {
match a {
Adapter::Cargo => push(a, n, None),
Adapter::Go => push(a, root.clone(), Some(n)),
_ if is_test_file(&n) => {
// a user may live under a different root/framework
if let Some((a2, r2)) = detect(&n, ws) {
push(a2, r2, Some(n));
}
}
_ => {}
}
}
}
runs.sort_by(|a, b| a.root.cmp(&b.root));
runs
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TestMode {
/// after each tool round that changed files (default)
TurnEnd,
/// only when the agent is about to stop; failures make it continue
AgentEnd,
Off,
}
/// Hook: collects files the agent wrote/edited, runs the selected tests, injects failures only.
pub struct TestLens {
pub ws: PathBuf,
pub mode: TestMode,
pub timeout: Duration,
/// max characters injected per report
pub cap: usize,
pending: tokio::sync::Mutex<Vec<PathBuf>>,
/// last report, so an unchanged failure set isn't repeated every turn
last: tokio::sync::Mutex<String>,
}
impl TestLens {
pub fn new(ws: PathBuf, mode: TestMode) -> Self {
Self {
ws,
mode,
timeout: Duration::from_secs(120),
cap: 3000,
pending: Default::default(),
last: Default::default(),
}
}
/// Run tests for pending changes. None = nothing new to say.
pub async fn report(&self) -> Option<String> {
let changed: Vec<PathBuf> = std::mem::take(&mut *self.pending.lock().await);
if changed.is_empty() {
return None;
}
// ponytail: graph rebuilt per report (walk + line scan). Cache keyed by seq if it gets slow on big repos.
let g = crate::deps::build(&self.ws);
let runs = select(&changed, &self.ws, &g);
if runs.is_empty() {
return None;
}
let snap = |fs: &[PathBuf]| fs.iter().map(|f| std::fs::read(f).ok()).collect::<Vec<_>>();
let before = snap(&changed);
let mut fails = vec![];
let mut notes = vec![];
let mut passed = 0;
let mut ran = 0;
for r in &runs {
if !installed(r.adapter, &r.root) {
notes.push(format!("{:?}: not installed", r.adapter));
continue;
}
ran += 1;
let where_ = r
.root
.strip_prefix(&self.ws)
.unwrap_or(&r.root)
.display()
.to_string();
match run(r, self.timeout).await {
Ok(o) => {
passed += o.passed;
fails.extend(o.failures);
}
Err(e) => fails.push(Failure {
name: format!("{:?} in ./{where_}", r.adapter).to_lowercase(),
file: None,
message: clip(&e, 12),
}),
}
}
let stale = snap(&changed) != before;
let mut last = self.last.lock().await;
let body = if fails.is_empty() {
if ran == 0 || last.is_empty() {
// nothing ran, or tests were already green: stay quiet
*last = String::new();
return (!notes.is_empty()).then(|| format!("[lens] tests: {}", notes.join("; ")));
}
format!("[lens] tests: all {passed} selected tests pass now")
} else {
let mut out = format!(
"[lens] {} failing test(s) affected by this turn's changes{}:\n",
fails.len(),
if stale {
" (stale: files changed during the run)"
} else {
""
}
);
for f in &fails {
let file = f
.file
.as_ref()
.map(|p| format!(" ({})", p.strip_prefix(&self.ws).unwrap_or(p).display()))
.unwrap_or_default();
let s = format!("- {}{file}\n{}\n", f.name, indent(&f.message));
if out.len() + s.len() > self.cap {
out.push_str("… (truncated; run the tests with bash for full output)\n");
break;
}
out.push_str(&s);
}
if !notes.is_empty() {
out.push_str(&format!("(notes: {})\n", notes.join("; ")));
}
out.trim_end().to_string()
};
let key = if fails.is_empty() {
String::new()
} else {
body.clone()
};
if !fails.is_empty() && *last == key {
return None;
}
*last = key;
Some(body)
}
}
fn indent(s: &str) -> String {
s.lines()
.map(|l| format!(" {l}"))
.collect::<Vec<_>>()
.join("\n")
}
#[async_trait::async_trait]
impl hx_core::hook::Hook for TestLens {
async fn on(&self, ev: &hx_core::hook::Event) -> hx_core::hook::HookAction {
use hx_core::hook::{Event, HookAction};
match ev {
Event::ToolResult {
name,
args,
is_error: false,
..
} if name == "write" || name == "edit" => {
if let Some(p) = args["path"].as_str() {
let p = self.ws.join(p);
let mut v = self.pending.lock().await;
if !v.contains(&p) {
v.push(p);
}
}
HookAction::Continue
}
Event::TurnEnd if self.mode == TestMode::TurnEnd => self
.report()
.await
.map_or(HookAction::Continue, HookAction::Inject),
Event::AgentEnd if self.mode == TestMode::AgentEnd => match self.report().await {
Some(r) if r.contains("failing test") => HookAction::Inject(r),
_ => HookAction::Continue,
},
_ => HookAction::Continue,
}
}
}
#[cfg(test)]
mod t {
use super::*;
#[test]
fn libtest() {
let s = "running 3 tests\ntest a::ok ... ok\ntest a::bad ... FAILED\ntest b ... ignored\n\nfailures:\n\n---- a::bad stdout ----\n\nthread 'a::bad' panicked at src/lib.rs:9:5:\nassertion `left == right` failed\n left: 5\n right: 4\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n a::bad\n\ntest result: FAILED. 1 passed; 1 failed\n";
let o = parse_libtest(s);
assert_eq!(o.passed, 1);
assert_eq!(o.failures.len(), 1);
assert_eq!(o.failures[0].name, "a::bad");
assert!(
o.failures[0].message.contains("left: 5"),
"{:?}",
o.failures[0]
);
assert!(!o.failures[0].message.contains("RUST_BACKTRACE"));
assert_eq!(
parse_libtest("test x ... ok\ntest result: ok. 1 passed").failures,
vec![]
);
}
#[test]
fn junit() {
let s = r#"<?xml version="1.0"?><testsuites><testsuite name="pytest" tests="3">
<testcase classname="tests.test_m" name="test_ok" file="tests/test_m.py" line="1" time="0.001" />
<testcase classname="tests.test_m" name="test_bad" file="tests/test_m.py" line="4" time="0.001"><failure message="assert 5 == 4">def test_bad():
&gt; assert add(2, 2) == 4
E assert 5 == 4</failure></testcase>
<testcase classname="tests.test_m" name="test_skip" time="0"><skipped message="x"/></testcase>
<testcase classname="tests.test_m" name="test_err" time="0"><error message="fixture &apos;db&apos; not found"/></testcase>
</testsuite></testsuites>"#;
let o = parse_junit(s, Path::new("/r"));
assert_eq!(o.passed, 1);
assert_eq!(o.failures.len(), 2, "{o:?}");
assert_eq!(o.failures[0].name, "tests.test_m::test_bad");
assert_eq!(
o.failures[0].file.as_deref(),
Some(Path::new("/r/tests/test_m.py"))
);
assert!(o.failures[0].message.contains("> ") && o.failures[0].message.contains("5 == 4"));
assert_eq!(o.failures[1].message, "fixture 'db' not found");
}
#[test]
fn jest() {
let s = r#"{"numFailedTests":1,"testResults":[
{"name":"/r/a.test.ts","status":"failed","message":"","assertionResults":[
{"fullName":"add works","status":"passed","failureMessages":[]},
{"fullName":"add fails","status":"failed","failureMessages":["Error: expect(received).toBe(expected)\n\nExpected: 4\nReceived: 5"]}]},
{"name":"/r/b.test.ts","status":"failed","message":"SyntaxError: Unexpected token","assertionResults":[]}]}"#;
let o = parse_jest(s).unwrap();
assert_eq!(o.passed, 1);
assert_eq!(o.failures.len(), 2);
assert!(o.failures[0].message.contains("Received: 5"));
assert_eq!(o.failures[1].name, "(suite)");
assert!(parse_jest("nope").is_err());
}
#[test]
fn go() {
let s = r#"{"Action":"run","Package":"m/p","Test":"TestOk"}
{"Action":"pass","Package":"m/p","Test":"TestOk"}
{"Action":"run","Package":"m/p","Test":"TestBad"}
{"Action":"output","Package":"m/p","Test":"TestBad","Output":"=== RUN TestBad\n"}
{"Action":"output","Package":"m/p","Test":"TestBad","Output":" p_test.go:8: add(2,2) = 5, want 4\n"}
{"Action":"output","Package":"m/p","Test":"TestBad","Output":"--- FAIL: TestBad (0.00s)\n"}
{"Action":"fail","Package":"m/p","Test":"TestBad"}
{"Action":"fail","Package":"m/p"}
{"Action":"output","Package":"m/q","Output":"q.go:3:1: syntax error\n"}
{"Action":"fail","Package":"m/q"}"#;
let o = parse_go(s);
assert_eq!(o.passed, 1);
assert_eq!(o.failures.len(), 2, "{o:?}");
assert_eq!(o.failures[0].name, "m/p.TestBad");
assert_eq!(o.failures[0].message, "p_test.go:8: add(2,2) = 5, want 4");
assert_eq!(o.failures[1].name, "m/q");
assert!(o.failures[1].message.contains("syntax error"));
}
#[test]
fn detection() {
let d = tempfile::tempdir().unwrap();
let ws = d.path();
std::fs::write(
ws.join("package.json"),
r#"{"devDependencies":{"vitest":"1"}}"#,
)
.unwrap();
std::fs::create_dir_all(ws.join("py")).unwrap();
std::fs::write(ws.join("py/pyproject.toml"), "").unwrap();
assert_eq!(
detect(&ws.join("src/a.ts"), ws),
Some((Adapter::Vitest, ws.into()))
);
assert_eq!(
detect(&ws.join("py/m.py"), ws),
Some((Adapter::Pytest, ws.join("py")))
);
assert_eq!(detect(&ws.join("x.go"), ws), None);
assert!(is_test_file(Path::new("a/test_x.py")) && !is_test_file(Path::new("a/x.py")));
assert!(is_test_file(Path::new("a/x.spec.ts")) && is_test_file(Path::new("x_test.go")));
}
#[test]
fn selection() {
let d = tempfile::tempdir().unwrap();
let ws = &std::fs::canonicalize(d.path()).unwrap();
let w = |p: &str, s: &str| {
let p = ws.join(p);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, s).unwrap();
};
w("package.json", r#"{"devDependencies":{"jest":"29"}}"#);
w("src/util.ts", "");
w("src/api.ts", "import './util'\n");
w("src/api.test.ts", "import './api'\n");
w("src/other.test.ts", "");
w("core/Cargo.toml", "[package]\nname = \"core\"\n");
w(
"app/Cargo.toml",
"[package]\nname = \"app\"\n[dependencies]\ncore = { path = \"../core\" }\n",
);
w("docs/x.md", "");
let g = crate::deps::build(ws);
let r = select(
&[
ws.join("src/util.ts"),
ws.join("core/src/lib.rs"),
ws.join("docs/x.md"),
],
ws,
&g,
);
assert_eq!(
r,
vec![
Run {
adapter: Adapter::Jest,
root: ws.clone(),
targets: vec![ws.join("src/api.test.ts")]
},
Run {
adapter: Adapter::Cargo,
root: ws.join("app"),
targets: vec![]
},
Run {
adapter: Adapter::Cargo,
root: ws.join("core"),
targets: vec![]
},
]
);
// a changed non-test file nobody tests selects nothing
assert!(
select(
&[ws.join("src/api.test.ts").with_file_name("lonely.ts")],
ws,
&g
)
.is_empty()
);
}
/// real cargo run: one passing, one failing test
#[tokio::test]
async fn real_cargo() {
let d = tempfile::tempdir().unwrap();
let ws = d.path();
std::fs::create_dir_all(ws.join("src")).unwrap();
std::fs::write(
ws.join("Cargo.toml"),
"[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n[workspace]\n",
)
.unwrap();
std::fs::write(
ws.join("src/lib.rs"),
"pub fn add(a: u32, b: u32) -> u32 { a + b + 1 }\n#[test] fn good() { assert!(add(0, 0) > 0) }\n#[test] fn bad() { assert_eq!(add(2, 2), 4) }\n",
)
.unwrap();
let r = Run {
adapter: Adapter::Cargo,
root: ws.into(),
targets: vec![],
};
let o = run(&r, Duration::from_secs(120)).await.unwrap();
assert_eq!(o.passed, 1, "{o:?}");
assert_eq!(o.failures[0].name, "bad");
assert!(o.failures[0].message.contains("left: 5"), "{o:?}");
std::fs::write(ws.join("src/lib.rs"), "pub fn f( {\n").unwrap();
let e = run(&r, Duration::from_secs(120)).await.unwrap_err();
assert!(e.contains("test run failed"), "{e}");
}
/// hook: failing affected test surfaced at turn end, repeated report suppressed, green reported once
#[tokio::test]
async fn hook_report() {
use hx_core::hook::{Event, Hook, HookAction};
let d = tempfile::tempdir().unwrap();
let ws = std::fs::canonicalize(d.path()).unwrap();
std::fs::create_dir_all(ws.join("src")).unwrap();
std::fs::write(
ws.join("Cargo.toml"),
"[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n[workspace]\n",
)
.unwrap();
let lib = ws.join("src/lib.rs");
let tl = TestLens::new(ws.clone(), TestMode::TurnEnd);
let edit = || Event::ToolResult {
id: "1".into(),
name: "edit".into(),
args: serde_json::json!({"path": "src/lib.rs"}),
content: String::new(),
is_error: false,
};
assert_eq!(tl.on(&Event::TurnEnd).await, HookAction::Continue);
std::fs::write(
&lib,
"pub fn add(a: u32) -> u32 { a + 2 }\n#[test] fn t() { assert_eq!(add(1), 2) }\n",
)
.unwrap();
tl.on(&edit()).await;
let HookAction::Inject(r) = tl.on(&Event::TurnEnd).await else {
panic!("expected failure")
};
assert!(
r.contains("1 failing test") && r.contains("- t\n") && r.contains("left: 3"),
"{r}"
);
tl.on(&edit()).await;
assert_eq!(
tl.on(&Event::TurnEnd).await,
HookAction::Continue,
"same failure repeated"
);
std::fs::write(
&lib,
"pub fn add(a: u32) -> u32 { a + 1 }\n#[test] fn t() { assert_eq!(add(1), 2) }\n",
)
.unwrap();
tl.on(&edit()).await;
let HookAction::Inject(r) = tl.on(&Event::TurnEnd).await else {
panic!("expected green")
};
assert!(r.contains("all 1 selected tests pass"), "{r}");
tl.on(&edit()).await;
assert_eq!(
tl.on(&Event::TurnEnd).await,
HookAction::Continue,
"green only once"
);
}
}
+1
View File
@@ -13,3 +13,4 @@ sh tests/e2e.sh
python3 tests/tui_smoke.py | grep -q FAIL && { echo "tui smoke FAIL"; exit 1; } || echo "tui smoke ok"
sh tests/lens_e2e.sh
sh tests/m4_e2e.sh
sh tests/m5_e2e.sh
+59
View File
@@ -0,0 +1,59 @@
"""M5 e2e: fake model writes a Rust fn with a failing unit test; hx must inject the failing test at turn
end; the fake model only fixes the file if it sees the failure, then expects a green notice.
Usage: python3 tests/fake_m5.py PORT
"""
import http.server, json, sys
LOG = []
BAD = "pub fn add(a: u32) -> u32 {\n a + 2\n}\n#[test]\nfn one() {\n assert_eq!(add(1), 2);\n}\n"
GOOD = BAD.replace("a + 2", "a + 1")
def sse(ev, d):
return f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode()
def last_user_text(body):
m = body["messages"][-1]
return "\n".join(b.get("text", "") for b in m["content"] if b.get("type") == "text")
class H(http.server.BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers["content-length"])))
LOG.append(body)
n = len(LOG)
lens = last_user_text(body)
if n == 1:
turn = ("tool", "Write", {"path": "src/lib.rs", "content": BAD})
elif "failing test" in lens and "one" in lens:
turn = ("tool", "Write", {"path": "src/lib.rs", "content": GOOD})
else:
turn = ("text", "FINISHED tests=" + ("green" if "pass now" in lens else "none"))
self.send_response(200)
self.send_header("content-type", "text/event-stream")
self.end_headers()
w = self.wfile.write
w(sse("message_start", {"message": {"usage": {"input_tokens": 1, "output_tokens": 1}}}))
if turn[0] == "text":
w(sse("content_block_start", {"index": 0, "content_block": {"type": "text", "text": ""}}))
w(sse("content_block_delta", {"index": 0, "delta": {"type": "text_delta", "text": turn[1]}}))
stop = "end_turn"
else:
w(sse("content_block_start", {"index": 0, "content_block": {"type": "tool_use", "id": f"t{n}", "name": turn[1], "input": {}}}))
w(sse("content_block_delta", {"index": 0, "delta": {"type": "input_json_delta", "partial_json": json.dumps(turn[2])}}))
stop = "tool_use"
w(sse("content_block_stop", {"index": 0}))
w(sse("message_delta", {"delta": {"stop_reason": stop}, "usage": {"output_tokens": 1}}))
w(sse("message_stop", {}))
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(json.dumps(LOG).encode())
http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
+20
View File
@@ -0,0 +1,20 @@
#!/bin/sh
# M5 e2e: failing affected test is surfaced at turn end and fixed without prompting; green reported.
set -eu
root=$(cd "$(dirname "$0")/.." && pwd)
tmp=$(mktemp -d)
trap 'kill $srv 2>/dev/null; rm -rf "$tmp"' EXIT
port=$((20000 + $$ % 20000))
python3 "$root/tests/fake_m5.py" $port & srv=$!
mkdir -p "$tmp/home/.hx" "$tmp/repo/src"
echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}' > "$tmp/home/.hx/auth.json"
printf '[lsp]\ndisable = ["rust-analyzer"]\n' > "$tmp/home/.hx/config.toml"
printf '[package]\nname = "t"\nversion = "0.1.0"\nedition = "2021"\n' > "$tmp/repo/Cargo.toml"
sleep 0.5
export RUSTUP_HOME="${RUSTUP_HOME:-$HOME/.rustup}" CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}"
cd "$tmp/repo"
HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port" "$root/target/debug/hx" -p "add f" > "$tmp/out" 2> "$tmp/err" || { cat "$tmp/err"; exit 1; }
grep -q "FINISHED tests=green" "$tmp/out" || { echo "--- out"; cat "$tmp/out"; echo "--- err"; cat "$tmp/err"; exit 1; }
grep -q "a + 1" src/lib.rs
curl -s "http://127.0.0.1:$port/" | grep -q 'left: 3'
echo "m5 e2e ok"