M4: lens linters, tests, triage, watch, freshness (closes #27 #28 #29 #30 #31 #32 #33 #34)
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s

This commit is contained in:
hermes committed 2026-09-30 14:13:13 +00:00
1 parent 9b8cf48e21
commit 1637d9274b
12 files changed
+1339 -65

No files matched your search

+1
View File
@@ -14,3 +14,4 @@ jobs:
- run: cargo build && sh tests/e2e.sh - run: cargo build && sh tests/e2e.sh
- run: python3 tests/tui_smoke.py - run: python3 tests/tui_smoke.py
- run: sh tests/lens_e2e.sh - run: sh tests/lens_e2e.sh
- run: pip install ruff && sh tests/m4_e2e.sh
+12 -1
View File
@@ -29,6 +29,8 @@ max_tokens = 16384
[lsp] [lsp]
mode = "turn_end" # turn_end | agent_end | off mode = "turn_end" # turn_end | agent_end | off
disable = ["clangd"] disable = ["clangd"]
enable_runners = ["clippy"] # opt-in (slow): clippy
disable_runners = ["rustfmt"] # any of: ruff, biome, eslint, ast-grep, rustfmt, ruff-format, biome-format
# [[lsp.servers]] # add or override (same id replaces built-in) # [[lsp.servers]] # add or override (same id replaces built-in)
# id = "zls" # id = "zls"
# language = "zig" # language = "zig"
@@ -42,7 +44,16 @@ disable = ["clangd"]
After every tool round, hx asks the language server about files the agent wrote or edited and appends After every tool round, hx asks the language server about files the agent wrote or edited and appends
errors/warnings to the next request, so the model fixes them without being told. Built in: errors/warnings to the next request, so the model fixes them without being told. Built in:
rust-analyzer, typescript-language-server, pyright, gopls, clangd (used when on `PATH`). The `lsp` tool gives rust-analyzer, typescript-language-server, pyright, gopls, clangd (used when on `PATH`). The `lsp` tool gives
the model diagnostics, definition, references, hover and symbols on demand. `/lsp` in the TUI shows server status. the model diagnostics, definition, references, hover and symbols on demand. `/lsp` in the TUI shows server status,
missing tools and triage marks.
Besides the language server, changed files go through (when installed and the project uses them):
ruff (Python), biome (with `biome.json`), eslint (with an eslint config), ast-grep (rules in `.hx/rules/*.yml`),
and clippy (opt-in). Formatters run only when configured for the project (`rustfmt.toml`, `ruff.toml`, `biome.json`);
their changes don't trip the read-guard. Files edited outside hx are picked up at the next turn.
`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`.
Existing Claude Code (`~/.claude/.credentials.json`) and Codex CLI (`~/.codex/auth.json`) logins are picked up automatically. 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. Credentials are stored in `~/.hx/auth.json` (mode 0600) and refreshed automatically.
+50 -6
View File
@@ -64,6 +64,10 @@ struct LspCfg {
servers: Vec<hx_lens::manager::ServerCfg>, servers: Vec<hx_lens::manager::ServerCfg>,
/// built-in server ids to disable /// built-in server ids to disable
disable: Vec<String>, disable: Vec<String>,
/// runner ids to enable in addition to defaults (e.g. "clippy")
enable_runners: Vec<String>,
/// runner ids to disable (e.g. "rustfmt", "biome-format")
disable_runners: Vec<String>,
} }
impl Config { impl Config {
@@ -166,6 +170,15 @@ impl Hook for Printer {
} }
} }
/// Lets an `Arc`-shared hook sit on the bus while tools hold the same instance.
struct ArcHook<H>(Arc<H>);
#[async_trait::async_trait]
impl<H: Hook> Hook for ArcHook<H> {
async fn on(&self, ev: &Event) -> HookAction {
self.0.on(ev).await
}
}
fn session_dir(cwd: &std::path::Path) -> std::path::PathBuf { fn session_dir(cwd: &std::path::Path) -> std::path::PathBuf {
let slug: String = cwd let slug: String = cwd
.to_string_lossy() .to_string_lossy()
@@ -236,11 +249,24 @@ async fn main() -> Result<()> {
servers.retain(|s| !lcfg.disable.contains(&s.id) && !lcfg.servers.iter().any(|o| o.id == s.id)); servers.retain(|s| !lcfg.disable.contains(&s.id) && !lcfg.servers.iter().any(|o| o.id == s.id));
servers.extend(lcfg.servers); servers.extend(lcfg.servers);
let mgr = Arc::new(hx_lens::manager::Manager::new(cwd.clone(), servers)); let mgr = Arc::new(hx_lens::manager::Manager::new(cwd.clone(), servers));
let mut lens_ref: Option<Arc<hx_lens::Lens>> = None;
let mode = lcfg.mode.unwrap_or(hx_lens::Mode::TurnEnd); let mode = lcfg.mode.unwrap_or(hx_lens::Mode::TurnEnd);
if mode != hx_lens::Mode::Off { if mode != hx_lens::Mode::Off {
agent let slug = dir
.bus .file_name()
.add(hx_lens::Lens::new(mgr.clone(), Default::default(), mode)); .map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let data = context::hx_home().join("projects").join(slug);
let mut lens = hx_lens::Lens::new(mgr.clone(), Default::default(), mode);
lens.triage = Arc::new(hx_lens::triage::Triage::open(data.join("triage.json")));
lens.latency_log = Some(context::hx_home().join("latency.log"));
lens.runners.retain(|r| !lcfg.disable_runners.contains(r));
lens.runners.extend(lcfg.enable_runners.iter().cloned());
let _ = lens.state.set(agent.cx.state.clone());
let lens = Arc::new(lens);
lens_ref = Some(lens.clone());
agent.bus.add(ArcHook(lens.clone()));
agent.tools.add(hx_lens::DiagMark { lens: lens.clone() });
agent.tools.add(hx_lens::LspTool { mgr: mgr.clone() }); agent.tools.add(hx_lens::LspTool { mgr: mgr.clone() });
// rust-analyzer & co are slow to index: start servers for languages present at the top level now // 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) let probe: Vec<_> = std::fs::read_dir(&cwd)
@@ -272,10 +298,28 @@ async fn main() -> Result<()> {
default_model, default_model,
pricing, pricing,
lsp_status: { lsp_status: {
let m = mgr.clone(); let (m, l) = (mgr.clone(), lens_ref.clone());
Box::new(move || { Box::new(move || {
let m = m.clone(); let (m, l) = (m.clone(), l.clone());
Box::pin(async move { m.status().await }) Box::pin(async move {
let mut v = m.status().await;
if let Some(l) = l {
v.extend(
l.notes
.lock()
.unwrap_or_else(|e| e.into_inner())
.iter()
.cloned(),
);
v.extend(
l.triage.list().into_iter().map(|(k, e)| {
format!("marked {:?}: {k} ({})", e.mark, e.reason)
}),
);
v.push(format!("runners: {}", l.runners.join(", ")));
}
v
})
}) })
}, },
}) })
+326 -47
View File
@@ -6,7 +6,10 @@
pub mod lsp; pub mod lsp;
pub mod manager; pub mod manager;
pub mod runners;
pub mod seq; pub mod seq;
pub mod triage;
pub mod watch;
use async_trait::async_trait; use async_trait::async_trait;
use hx_ai::ToolSpec; use hx_ai::ToolSpec;
@@ -14,12 +17,14 @@ use hx_core::hook::{Event, Hook, HookAction};
use hx_core::tool::{Tool, ToolCtx, ToolResult}; use hx_core::tool::{Tool, ToolCtx, ToolResult};
use lsp::{Diag, path_of}; use lsp::{Diag, path_of};
use manager::Manager; use manager::Manager;
use runners::{Finding, Kind, RUNNERS};
use seq::{SeqLog, Source}; use seq::{SeqLog, Source};
use serde_json::{Value, json}; use serde_json::{Value, json};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use tokio::sync::Mutex; use tokio::sync::Mutex;
use triage::{Entry, Mark, Triage};
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
@@ -34,14 +39,24 @@ pub enum Mode {
pub struct Lens { pub struct Lens {
pub mgr: Arc<Manager>, pub mgr: Arc<Manager>,
pub seq: Arc<SeqLog>, pub seq: Arc<SeqLog>,
pub triage: Arc<Triage>,
pub mode: Mode, pub mode: Mode,
pub timeout: Duration, pub timeout: Duration,
/// max characters injected per report /// max characters injected per report
pub cap: usize, pub cap: usize,
/// enabled runner ids (lint + format). Default: all except opt-in ones.
pub runners: Vec<String>,
/// NDJSON per-runner timings; None = off
pub latency_log: Option<PathBuf>,
/// seq at the last report; changes after it are "this turn" /// seq at the last report; changes after it are "this turn"
reported: Mutex<u64>, reported: Mutex<u64>,
/// last injected report per file, so unchanged findings aren't repeated every turn /// last injected report per file, so unchanged findings aren't repeated every turn
last: Mutex<std::collections::HashMap<PathBuf, String>>, last: Mutex<std::collections::HashMap<PathBuf, String>>,
/// runners whose binary is missing, reported once
pub notes: std::sync::Mutex<Vec<String>>,
/// agent tool state, for refreshing the read-guard after formatting
pub state: std::sync::OnceLock<Arc<hx_core::State>>,
pub watch: Arc<watch::Watch>,
} }
impl Lens { impl Lens {
@@ -49,14 +64,143 @@ impl Lens {
Self { Self {
mgr, mgr,
seq, seq,
triage: Default::default(),
mode, mode,
timeout: Duration::from_secs(20), timeout: Duration::from_secs(20),
cap: 4000, cap: 4000,
runners: RUNNERS
.iter()
.map(|r| r.id.to_string())
.filter(|id| !runners::OPT_IN.contains(&id.as_str()))
.collect(),
latency_log: None,
reported: Mutex::new(0), reported: Mutex::new(0),
last: Default::default(), last: Default::default(),
notes: Default::default(),
state: Default::default(),
watch: Default::default(),
} }
} }
fn note(&self, s: String) {
let mut n = self.notes.lock().unwrap_or_else(|e| e.into_inner());
if !n.contains(&s) {
n.push(s);
}
}
fn log_latency(&self, runner: &str, files: usize, took: Duration, err: Option<&str>) {
let Some(p) = &self.latency_log else { return };
let line = json!({"ts": hx_ai::auth::now_ms(), "runner": runner, "files": files, "ms": took.as_millis() as u64, "error": err});
if let Some(d) = p.parent() {
let _ = std::fs::create_dir_all(d);
}
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(p)
{
use std::io::Write;
let _ = writeln!(f, "{line}");
}
}
/// Format changed files with configured formatters; bumps seq with Source::Format and refreshes the
/// read-guard state so the agent's next edit isn't blocked by our own change.
async fn format(&self, files: &[PathBuf], state: Option<&hx_core::State>) {
for (r, root, fs) in self.plan(files, Kind::Format) {
let o = runners::run(r, &root, &fs, self.timeout).await;
self.log_latency(r.id, fs.len(), o.took, o.error.as_deref());
for f in o.changed {
self.seq.bump(&f, Source::Format);
self.watch.track(f.clone());
if let Some(st) = state {
st.mark_seen(&f);
}
}
}
}
/// Group files by (runner, root) for enabled + installed runners of `kind`.
fn plan(
&self,
files: &[PathBuf],
kind: Kind,
) -> Vec<(&'static runners::Runner, PathBuf, Vec<PathBuf>)> {
let mut plan: Vec<(&runners::Runner, PathBuf, Vec<PathBuf>)> = vec![];
for r in RUNNERS
.iter()
.filter(|r| r.kind == kind && self.runners.iter().any(|x| x == r.id))
{
for f in files {
let Some(root) = runners::applies(r, f, &self.mgr.workspace) else {
continue;
};
if !runners::installed(r) {
self.note(format!("{}: `{}` not installed", r.id, r.bin));
continue;
}
match plan
.iter_mut()
.find(|(x, rt, _)| x.id == r.id && *rt == root)
{
Some((_, _, v)) => v.push(f.clone()),
None => plan.push((r, root, vec![f.clone()])),
}
}
}
plan
}
/// Diagnostics (LSP) + lint findings for `files`, all runners in parallel. Returns (findings, errors).
pub async fn collect(&self, files: &[PathBuf]) -> (Vec<Finding>, Vec<String>) {
let lsp_files: Vec<&PathBuf> = files
.iter()
.filter(|f| self.mgr.server_for(f).is_some())
.collect();
let lsp = futures::future::join_all(lsp_files.iter().map(|f| async move {
let t = std::time::Instant::now();
let r = self.mgr.diagnostics(f, self.timeout).await;
(f, r, t.elapsed())
}));
let plan = self.plan(files, Kind::Lint);
let lint = futures::future::join_all(plan.iter().map(|(r, root, fs)| async move {
(
r.id,
fs.len(),
runners::run(r, root, fs, self.timeout).await,
)
}));
let (lsp, lint) = tokio::join!(lsp, lint);
let mut out = vec![];
let mut errs = vec![];
for (f, r, took) in lsp {
match r {
Some(Ok(d)) => {
self.log_latency("lsp", 1, took, None);
out.extend(
d.into_iter()
.filter(|x| x.severity <= 2)
.map(|x| diag_finding(f, x)),
);
}
Some(Err(e)) => {
self.log_latency("lsp", 1, took, Some(&e));
errs.push(format!("{}: lsp unavailable: {e}", self.rel(f)));
}
None => {}
}
}
for (id, n, o) in lint {
self.log_latency(id, n, o.took, o.error.as_deref());
match o.error {
Some(e) => errs.push(format!("{id}: {e}")),
None => out.extend(o.findings),
}
}
(out, errs)
}
fn resolve(&self, p: &str) -> PathBuf { fn resolve(&self, p: &str) -> PathBuf {
let p = Path::new(p); let p = Path::new(p);
if p.is_absolute() { if p.is_absolute() {
@@ -66,46 +210,68 @@ impl Lens {
} }
} }
/// Diagnostics report for files changed since the last report. None = nothing to say. /// Report for files changed since the last report. None = nothing to say.
pub async fn report(&self) -> Option<String> { pub async fn report(&self, state: Option<&hx_core::State>) -> Option<String> {
let since = { let since = { *self.reported.lock().await };
let mut r = self.reported.lock().await; let files: Vec<PathBuf> = self
let s = *r; .seq
*r = self.seq.project(); .since(since)
s
};
let files = self.seq.since(since);
let files: Vec<PathBuf> = files
.into_iter() .into_iter()
.filter(|f| self.mgr.server_for(f).is_some() && f.exists()) .filter(|f| f.exists())
.collect(); .collect();
if files.is_empty() { if files.is_empty() {
*self.reported.lock().await = self.seq.project();
return None; return None;
} }
let results = self.format(&files, state).await;
futures::future::join_all(files.iter().map(|f| self.mgr.diagnostics(f, self.timeout))) let start_seq = self.seq.project();
.await; let (findings, errs) = self.collect(&files).await;
let mut sections = vec![]; *self.reported.lock().await = start_seq;
let mut last = self.last.lock().await; let mut last = self.last.lock().await;
for (f, r) in files.iter().zip(results) { let mut sections = vec![];
let body = match r { for f in &files {
Some(Ok(d)) => format_diags(&d), let rel = PathBuf::from(self.rel(f));
Some(Err(e)) => format!(" (lsp unavailable: {e})"), let fseq = self.seq.file(f);
None => continue, let mut mine: Vec<&Finding> = findings
}; .iter()
let clean = body.is_empty(); .filter(|x| &x.path == f && !self.triage.hidden(&Triage::key(&rel, x), fseq))
.collect();
mine.sort_by_key(|x| (x.severity, x.line, x.col));
mine.dedup_by(|a, b| a.line == b.line && a.message == b.message);
let body = format_findings(&mine);
// freshness gate: file changed on disk while we were checking -> label, don't trust
let stale = self.seq.file(f) > start_seq;
let prev = last.insert(f.clone(), body.clone()); let prev = last.insert(f.clone(), body.clone());
// report "now clean" once after errors; stay silent for clean files otherwise if body.is_empty() {
if clean {
if prev.is_some_and(|p| !p.is_empty()) { if prev.is_some_and(|p| !p.is_empty()) {
sections.push((0, format!("{}: no problems", self.rel(f)))); sections.push((0, format!("{}: no problems", rel.display())));
} }
continue; continue;
} }
let errors = body.matches("error").count(); if prev.as_deref() == Some(body.as_str()) {
sections.push((usize::MAX - errors, format!("{}:\n{body}", self.rel(f)))); continue;
}
let errors = mine.iter().filter(|x| x.severity == 1).count();
let tag = if stale {
" (stale: file changed during check)"
} else {
""
};
sections.push((
usize::MAX - errors,
format!("{}{tag}:\n{body}", rel.display()),
));
} }
if sections.is_empty() { drop(last);
let mut notes: Vec<String> = errs;
notes.extend(
self.notes
.lock()
.unwrap_or_else(|e| e.into_inner())
.drain(..),
);
if sections.is_empty() && notes.is_empty() {
return None; return None;
} }
sections.sort_by_key(|s| s.0); sections.sort_by_key(|s| s.0);
@@ -118,6 +284,9 @@ impl Lens {
out.push_str(&s); out.push_str(&s);
out.push('\n'); out.push('\n');
} }
if !notes.is_empty() {
out.push_str(&format!("(lens notes: {})\n", notes.join("; ")));
}
Some(out.trim_end().to_string()) Some(out.trim_end().to_string())
} }
@@ -129,23 +298,50 @@ impl Lens {
} }
} }
fn diag_finding(f: &Path, d: Diag) -> Finding {
Finding {
path: f.into(),
line: d.line + 1,
col: d.col + 1,
severity: d.severity,
rule: d.code,
message: d.message.lines().next().unwrap_or_default().to_string(),
source: if d.source.is_empty() {
"lsp".into()
} else {
d.source
},
}
}
/// Errors and warnings only (info/hints are noise for the agent), max 20 per file. /// Errors and warnings only (info/hints are noise for the agent), max 20 per file.
pub fn format_diags(d: &[Diag]) -> String { pub fn format_diags(d: &[Diag]) -> String {
let mut v: Vec<&Diag> = d.iter().filter(|x| x.severity <= 2).collect(); let f: Vec<Finding> = d
v.sort_by_key(|x| (x.severity, x.line, x.col)); .iter()
.filter(|x| x.severity <= 2)
.map(|x| diag_finding(Path::new(""), x.clone()))
.collect();
let mut r: Vec<&Finding> = f.iter().collect();
r.sort_by_key(|x| (x.severity, x.line, x.col));
format_findings(&r)
}
pub fn format_findings(v: &[&Finding]) -> String {
let n = v.len(); let n = v.len();
let mut s: String = v let mut s: String = v
.iter() .iter()
.take(20) .take(20)
.map(|x| { .map(|x| {
let sev = if x.severity == 1 { "error" } else { "warning" }; let sev = if x.severity == 1 { "error" } else { "warning" };
let code = if x.code.is_empty() { let code = if x.rule.is_empty() {
String::new() String::new()
} else { } else {
format!("[{}] ", x.code) format!("[{}] ", x.rule)
}; };
let msg = x.message.lines().next().unwrap_or_default(); format!(
format!(" {}:{} {sev}: {code}{msg}\n", x.line + 1, x.col + 1) " {}:{} {sev}: {code}{} ({})\n",
x.line, x.col, x.message, x.source
)
}) })
.collect(); .collect();
if n > 20 { if n > 20 {
@@ -163,30 +359,113 @@ impl Hook for Lens {
args, args,
is_error: false, is_error: false,
.. ..
} if name == "write" || name == "edit" => { } if name == "write" || name == "edit" || name == "read" => {
if let Some(p) = args["path"].as_str() { if let Some(p) = args["path"].as_str() {
let src = if name == "write" { let p = self.resolve(p);
Source::AgentWrite match name.as_str() {
} else { "write" => {
Source::AgentEdit self.seq.bump(&p, Source::AgentWrite);
}; }
self.seq.bump(&self.resolve(p), src); "edit" => {
self.seq.bump(&p, Source::AgentEdit);
}
_ => {}
}
// re-baseline so our own change isn't seen as external
self.watch.track(p);
} }
HookAction::Continue HookAction::Continue
} }
Event::TurnStart => {
// edits made outside hx while the model was thinking
self.watch.scan(&self.seq);
HookAction::Continue
}
Event::TurnEnd if self.mode == Mode::TurnEnd => self Event::TurnEnd if self.mode == Mode::TurnEnd => self
.report() .report(self.state.get().map(|s| s.as_ref()))
.await .await
.map_or(HookAction::Continue, HookAction::Inject), .map_or(HookAction::Continue, HookAction::Inject),
Event::AgentEnd if self.mode == Mode::AgentEnd => match self.report().await { Event::AgentEnd if self.mode == Mode::AgentEnd => {
Some(r) if r.contains(" error: ") => HookAction::Inject(r), match self.report(self.state.get().map(|s| s.as_ref())).await {
_ => HookAction::Continue, Some(r) if r.contains(" error: ") => HookAction::Inject(r),
}, _ => HookAction::Continue,
}
}
_ => HookAction::Continue, _ => HookAction::Continue,
} }
} }
} }
/// Triage tool: mark a finding false-positive or defer it.
pub struct DiagMark {
pub lens: Arc<Lens>,
}
#[async_trait]
impl Tool for DiagMark {
fn spec(&self) -> ToolSpec {
ToolSpec {
name: "diag_mark".into(),
description: "Silence a lens finding. mark=false_positive hides it permanently; mark=defer hides it until the file changes again; \
mark=clear removes marks for the file. Identify the finding by path + line (as shown in the lens report). Give a reason."
.into(),
input_schema: json!({"type":"object","properties":{
"path":{"type":"string"},
"line":{"type":"integer"},
"mark":{"type":"string","enum":["false_positive","defer","clear"]},
"reason":{"type":"string"}},
"required":["path","mark"]}),
}
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let p = cx.cwd.join(a["path"].as_str().unwrap_or_default());
let rel = PathBuf::from(self.lens.rel(&p));
let mark = a["mark"].as_str().unwrap_or_default();
if mark == "clear" {
return match self
.lens
.triage
.remove_prefix(&format!("{}|", rel.display()))
{
Ok(n) => ToolResult::ok(format!("cleared {n} marks for {}", rel.display())),
Err(e) => ToolResult::err(e.to_string()),
};
}
let Some(line) = a["line"].as_u64() else {
return ToolResult::err("line is required");
};
let (found, _) = self.lens.collect(std::slice::from_ref(&p)).await;
let hits: Vec<&Finding> = found.iter().filter(|f| f.line as u64 == line).collect();
if hits.is_empty() {
return ToolResult::err(format!("no current finding at {}:{line}", rel.display()));
}
let mark = if mark == "defer" {
Mark::Defer
} else {
Mark::FalsePositive
};
let reason = a["reason"].as_str().unwrap_or_default().to_string();
for f in &hits {
let e = Entry {
mark,
reason: reason.clone(),
seq: self.lens.seq.file(&p),
};
if let Err(e) = self.lens.triage.set(Triage::key(&rel, f), e) {
return ToolResult::err(e.to_string());
}
}
// force the next report to re-render this file
self.lens.last.lock().await.remove(&p);
let what: Vec<String> = hits
.iter()
.map(|f| format!("[{}] {}", f.source, f.message))
.collect();
ToolResult::ok(format!("marked {mark:?}: {}", what.join("; ")))
}
}
pub struct LspTool { pub struct LspTool {
pub mgr: Arc<Manager>, pub mgr: Arc<Manager>,
} }
@@ -340,7 +619,7 @@ mod tests {
d(3, 1, "bad type\ndetail"), d(3, 1, "bad type\ndetail"),
d(1, 4, "hint"), d(1, 4, "hint"),
]); ]);
assert_eq!(s, " 4:1 error: bad type\n 10:1 warning: unused"); assert_eq!(s, " 4:1 error: bad type (x)\n 10:1 warning: unused (x)");
let many: Vec<Diag> = (0..25).map(|i| d(i, 1, "e")).collect(); let many: Vec<Diag> = (0..25).map(|i| d(i, 1, "e")).collect();
assert!(format_diags(&many).ends_with("… 5 more")); assert!(format_diags(&many).ends_with("… 5 more"));
} }
+34 -5
View File
@@ -36,6 +36,11 @@ pub struct Client {
pub alive: Arc<std::sync::atomic::AtomicBool>, pub alive: Arc<std::sync::atomic::AtomicBool>,
/// active `$/progress` tokens + (rust-analyzer) not-quiescent; 0 = idle /// active `$/progress` tokens + (rust-analyzer) not-quiescent; 0 = idle
pub busy: Arc<AtomicI64>, pub busy: Arc<AtomicI64>,
/// completed on-save checks (rust-analyzer flycheck). Diagnostics after a save are final once this advances.
pub checks_done: Arc<AtomicI64>,
pub checks_active: Arc<std::sync::atomic::AtomicBool>,
/// Incremented on every `textDocument/publishDiagnostics` notification.
pub diag_seq: Arc<AtomicI64>,
pub root: PathBuf, pub root: PathBuf,
pub capabilities: std::sync::OnceLock<Value>, pub capabilities: std::sync::OnceLock<Value>,
} }
@@ -119,16 +124,22 @@ impl Client {
let notify = Arc::new(Notify::new()); let notify = Arc::new(Notify::new());
let alive = Arc::new(std::sync::atomic::AtomicBool::new(true)); let alive = Arc::new(std::sync::atomic::AtomicBool::new(true));
let busy = Arc::new(AtomicI64::new(0)); let busy = Arc::new(AtomicI64::new(0));
let checks_done = Arc::new(AtomicI64::new(0));
let checks_active = Arc::new(std::sync::atomic::AtomicBool::new(false));
let diag_seq = Arc::new(AtomicI64::new(0));
let (stdin_tx, mut stdin_rx) = tokio::sync::mpsc::unbounded_channel::<Value>(); let (stdin_tx, mut stdin_rx) = tokio::sync::mpsc::unbounded_channel::<Value>();
// reader: responses, diagnostics, and server->client requests (answered via stdin_tx) // reader: responses, diagnostics, and server->client requests (answered via stdin_tx)
{ {
let (pending, diags, notify, alive, busy) = ( let (pending, diags, notify, alive, busy, checks_done, checks_active, diag_seq) = (
pending.clone(), pending.clone(),
diags.clone(), diags.clone(),
notify.clone(), notify.clone(),
alive.clone(), alive.clone(),
busy.clone(), busy.clone(),
checks_done.clone(),
checks_active.clone(),
diag_seq.clone(),
); );
tokio::spawn(async move { tokio::spawn(async move {
let mut r = BufReader::new(stdout); let mut r = BufReader::new(stdout);
@@ -186,7 +197,7 @@ impl Client {
} }
(None, Some(method)) if method == "textDocument/publishDiagnostics" => { (None, Some(method)) if method == "textDocument/publishDiagnostics" => {
let p = &m["params"]; let p = &m["params"];
let list = p["diagnostics"] let list: Vec<Diag> = p["diagnostics"]
.as_array() .as_array()
.map(|a| a.iter().map(parse_diag).collect()) .map(|a| a.iter().map(parse_diag).collect())
.unwrap_or_default(); .unwrap_or_default();
@@ -194,13 +205,28 @@ impl Client {
p["uri"].as_str().unwrap_or_default().to_string(), p["uri"].as_str().unwrap_or_default().to_string(),
(p["version"].as_i64(), list), (p["version"].as_i64(), list),
); );
diag_seq.fetch_add(1, Ordering::SeqCst);
notify.notify_waiters(); notify.notify_waiters();
} }
(None, Some(method)) if method == "$/progress" => { (None, Some(method)) if method == "$/progress" => {
let is_flycheck = m["params"]["token"]
.as_str()
.is_some_and(|t| t.contains("flycheck"));
match m["params"]["value"]["kind"].as_str() { match m["params"]["value"]["kind"].as_str() {
Some("begin") => busy.fetch_add(1, Ordering::SeqCst), Some("begin") => {
Some("end") => busy.fetch_sub(1, Ordering::SeqCst), if is_flycheck {
_ => 0, checks_active.store(true, Ordering::SeqCst);
}
busy.fetch_add(1, Ordering::SeqCst);
}
Some("end") => {
if is_flycheck {
checks_active.store(false, Ordering::SeqCst);
checks_done.fetch_add(1, Ordering::SeqCst);
}
busy.fetch_sub(1, Ordering::SeqCst);
}
_ => {}
}; };
notify.notify_waiters(); notify.notify_waiters();
} }
@@ -226,6 +252,9 @@ impl Client {
diag_notify: notify, diag_notify: notify,
alive, alive,
busy, busy,
checks_done,
checks_active,
diag_seq,
root: root.to_path_buf(), root: root.to_path_buf(),
capabilities: Default::default(), capabilities: Default::default(),
}); });
+49 -6
View File
@@ -240,6 +240,9 @@ impl Manager {
let _ = cl let _ = cl
.notify("textDocument/didOpen", json!({"textDocument": {"uri": u, "languageId": language_for(&c, file), "version": 1, "text": text}})) .notify("textDocument/didOpen", json!({"textDocument": {"uri": u, "languageId": language_for(&c, file), "version": 1, "text": text}}))
.await; .await;
let _ = cl
.notify("textDocument/didSave", json!({"textDocument": {"uri": u}}))
.await;
1 1
} }
Some(v) => { Some(v) => {
@@ -266,25 +269,65 @@ impl Manager {
timeout: Duration, timeout: Duration,
) -> Option<Result<Vec<Diag>, String>> { ) -> Option<Result<Vec<Diag>, String>> {
let before = self.client(file).await.map(|(c, ..)| c)?; let before = self.client(file).await.map(|(c, ..)| c)?;
let is_rust = self
.server_for(file)
.is_some_and(|c| c.id == "rust-analyzer");
let deadline = Instant::now() + timeout;
// If a check is already running from an earlier turn/startup, wait for it to finish first:
if is_rust {
while before.checks_active.load(Ordering::SeqCst) {
if Instant::now() >= deadline
|| tokio::time::timeout(
Duration::from_millis(500),
before.diag_notify.notified(),
)
.await
.is_err()
{
break;
}
}
}
let u = uri(file); let u = uri(file);
let stale = before.diagnostics(&u).await; let stale = before.diagnostics(&u).await;
let (cl, v) = self.sync(file).await?; let (cl, v) = self.sync(file).await?;
let deadline = Instant::now() + timeout; // count checks from after our save: a check still ending from an earlier save carries stale results
let checks_before = cl.checks_done.load(Ordering::SeqCst)
+ i64::from(cl.checks_active.load(Ordering::SeqCst));
let fresh = |d: &Option<(Option<i64>, Vec<Diag>)>| match d { let fresh = |d: &Option<(Option<i64>, Vec<Diag>)>| match d {
Some((Some(rv), _)) => *rv >= v, Some((Some(rv), _)) => *rv >= v,
Some((None, _)) => d != &stale || v == 1, Some((None, _)) => d != &stale || v == 1,
None => false, None => false,
}; };
// Accept once the report is fresh AND the server is idle (not indexing), then settle briefly: // For rust-analyzer, didSave triggers a flycheck. Wait until either:
// servers often publish early (syntax only / empty while indexing) and refine later. // - A flycheck completes (checks_done > checks_before and !checks_active), OR
// - 5s passes without flycheck ever starting (e.g. non-cargo file or checkOnSave disabled).
let settle_for = Duration::from_millis(300);
// rust-analyzer publishes flycheck results after progress `end`: once the check ends,
// wait (max 3s) for a publish that arrives after it.
let mut after_end: Option<(i64, Instant)> = None;
let check_wait_deadline = Instant::now() + Duration::from_secs(5);
loop { loop {
let n = cl.diag_notify.notified(); let n = cl.diag_notify.notified();
let cur = cl.diagnostics(&u).await; let cur = cl.diagnostics(&u).await;
if fresh(&cur) && cl.busy.load(Ordering::SeqCst) <= 0 { let check_finished = cl.checks_done.load(Ordering::SeqCst) > checks_before
&& !cl.checks_active.load(Ordering::SeqCst);
let check_never_started = cl.checks_done.load(Ordering::SeqCst) == checks_before
&& !cl.checks_active.load(Ordering::SeqCst)
&& Instant::now() >= check_wait_deadline;
if check_finished && after_end.is_none() {
after_end = Some((cl.diag_seq.load(Ordering::SeqCst), Instant::now()));
}
let published = after_end.is_some_and(|(seq, t)| {
cl.diag_seq.load(Ordering::SeqCst) > seq || t.elapsed() >= Duration::from_secs(3)
});
let checked = !is_rust || (check_finished && published) || check_never_started;
if fresh(&cur) && checked && cl.busy.load(Ordering::SeqCst) <= 0 {
loop { loop {
let settle = cl.diag_notify.notified(); let settle = cl.diag_notify.notified();
let left = deadline.saturating_duration_since(Instant::now()); let left = deadline.saturating_duration_since(Instant::now());
if tokio::time::timeout(Duration::from_millis(500).min(left), settle) if tokio::time::timeout(settle_for.min(left), settle)
.await .await
.is_err() .is_err()
{ {
@@ -313,7 +356,7 @@ impl Manager {
_ => Err(format!("no diagnostics within {}s", timeout.as_secs())), _ => Err(format!("no diagnostics within {}s", timeout.as_secs())),
}); });
} }
let _ = tokio::time::timeout(left, n).await; let _ = tokio::time::timeout(left.min(Duration::from_millis(500)), n).await;
} }
} }
+525
View File
@@ -0,0 +1,525 @@
//! Non-LSP runners: linters, formatter, ast-grep rules. Each runs a CLI and parses its JSON.
//!
//! All runners report `Finding`s; the dispatcher runs the applicable ones in parallel with a timeout.
use crate::manager::which;
use serde_json::Value;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use tokio::process::Command;
#[derive(Debug, Clone, PartialEq)]
pub struct Finding {
pub path: PathBuf,
/// 1-based
pub line: u32,
pub col: u32,
/// 1 error, 2 warning
pub severity: u8,
pub rule: String,
pub message: String,
/// runner id
pub source: String,
}
impl Finding {
/// Stable identity for triage marks: survives line shifts.
pub fn key(&self) -> String {
format!("{}|{}|{}", self.source, self.rule, self.message)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Lint,
Format,
}
#[derive(Debug, Clone)]
pub struct Runner {
pub id: &'static str,
pub kind: Kind,
pub extensions: &'static [&'static str],
/// project marker files; any present (at a root between file and workspace) enables the runner
pub markers: &'static [&'static str],
pub bin: &'static str,
}
/// Runners not run unless enabled in config.
pub const OPT_IN: &[&str] = &["clippy"];
pub const RUNNERS: &[Runner] = &[
Runner {
id: "clippy",
kind: Kind::Lint,
extensions: &["rs"],
markers: &["Cargo.toml"],
bin: "cargo",
},
Runner {
id: "ruff",
kind: Kind::Lint,
extensions: &["py", "pyi"],
markers: &[],
bin: "ruff",
},
Runner {
id: "biome",
kind: Kind::Lint,
extensions: &["js", "jsx", "ts", "tsx", "json", "mjs", "cjs"],
markers: &["biome.json", "biome.jsonc"],
bin: "biome",
},
Runner {
id: "eslint",
kind: Kind::Lint,
extensions: &["js", "jsx", "ts", "tsx", "mjs", "cjs"],
markers: &[
"eslint.config.js",
"eslint.config.mjs",
"eslint.config.cjs",
".eslintrc.json",
".eslintrc.js",
".eslintrc.cjs",
],
bin: "eslint",
},
Runner {
id: "ast-grep",
kind: Kind::Lint,
extensions: &[],
markers: &[".hx/rules"],
bin: "ast-grep",
},
Runner {
id: "rustfmt",
kind: Kind::Format,
extensions: &["rs"],
markers: &["rustfmt.toml", ".rustfmt.toml"],
bin: "rustfmt",
},
Runner {
id: "ruff-format",
kind: Kind::Format,
extensions: &["py", "pyi"],
markers: &["ruff.toml", ".ruff.toml"],
bin: "ruff",
},
Runner {
id: "biome-format",
kind: Kind::Format,
extensions: &["js", "jsx", "ts", "tsx", "json"],
markers: &["biome.json", "biome.jsonc"],
bin: "biome",
},
];
/// Nearest dir (file..=ws) containing any marker; ws when markers are empty.
pub fn marker_root(file: &Path, markers: &[&str], ws: &Path) -> Option<PathBuf> {
if markers.is_empty() {
return Some(ws.to_path_buf());
}
for d in file.ancestors().skip(1) {
if markers.iter().any(|m| d.join(m).exists()) {
return Some(d.to_path_buf());
}
if d == ws {
break;
}
}
None
}
/// Root the runner would run in for `file`, ignoring whether its binary is installed.
pub fn applies(r: &Runner, file: &Path, ws: &Path) -> Option<PathBuf> {
let ext = file
.extension()
.and_then(|e| e.to_str())
.unwrap_or_default();
if !r.extensions.is_empty() && !r.extensions.contains(&ext) {
return None;
}
let root = marker_root(file, r.markers, ws)?;
// ast-grep: any extension, but only if rules exist
if r.id == "ast-grep"
&& std::fs::read_dir(root.join(".hx/rules")).is_ok_and(|mut d| d.next().is_none())
{
return None;
}
Some(root)
}
pub fn installed(r: &Runner) -> bool {
which(r.bin)
}
pub struct Output {
pub findings: Vec<Finding>,
pub took: Duration,
/// set when the runner could not produce results
pub error: Option<String>,
/// files the formatter changed
pub changed: Vec<PathBuf>,
}
async fn exec(cmd: &mut Command, timeout: Duration) -> Result<(Vec<u8>, Option<i32>), String> {
cmd.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true);
match tokio::time::timeout(timeout, cmd.output()).await {
Err(_) => Err(format!("timed out after {}s", timeout.as_secs())),
Ok(Err(e)) => Err(e.to_string()),
Ok(Ok(o)) => Ok((o.stdout, o.status.code())),
}
}
fn rel_to(root: &Path, p: &str) -> PathBuf {
let p = Path::new(p);
if p.is_absolute() {
p.into()
} else {
root.join(p)
}
}
/// Run `r` once for all `files` under `root`. Findings are limited to `files`.
pub async fn run(r: &Runner, root: &Path, files: &[PathBuf], timeout: Duration) -> Output {
let t = Instant::now();
let mut out = Output {
findings: vec![],
took: Duration::ZERO,
error: None,
changed: vec![],
};
let before: Vec<Option<Vec<u8>>> = if r.kind == Kind::Format {
files.iter().map(|f| std::fs::read(f).ok()).collect()
} else {
vec![]
};
let res = match r.id {
"clippy" => clippy(root, timeout).await,
"ruff" => ruff(root, files, timeout).await,
"biome" => biome(root, files, timeout).await,
"eslint" => eslint(root, files, timeout).await,
"ast-grep" => ast_grep(root, files, timeout).await,
"rustfmt" => exec(
Command::new("rustfmt")
.args(["--edition", "2024"])
.args(files)
.current_dir(root),
timeout,
)
.await
.map(|_| vec![]),
"ruff-format" => exec(
Command::new("ruff")
.args(["format", "--quiet"])
.args(files)
.current_dir(root),
timeout,
)
.await
.map(|_| vec![]),
"biome-format" => exec(
Command::new("biome")
.args(["format", "--write"])
.args(files)
.current_dir(root),
timeout,
)
.await
.map(|_| vec![]),
_ => Err(format!("unknown runner {}", r.id)),
};
match res {
Ok(f) => out.findings = f.into_iter().filter(|x| files.contains(&x.path)).collect(),
Err(e) => out.error = Some(e),
}
for (f, b) in files.iter().zip(before) {
if b.is_some() && std::fs::read(f).ok() != b {
out.changed.push(f.clone());
}
}
out.took = t.elapsed();
out
}
/// clippy checks the whole crate; `run` filters to changed files.
async fn clippy(root: &Path, timeout: Duration) -> Result<Vec<Finding>, String> {
let (o, _) = exec(
Command::new("cargo")
.args([
"clippy",
"--quiet",
"--message-format=json",
"--all-targets",
])
.current_dir(root),
timeout,
)
.await?;
let mut v = vec![];
for l in String::from_utf8_lossy(&o).lines() {
let Ok(m) = serde_json::from_str::<Value>(l) else {
continue;
};
if m["reason"] != "compiler-message" {
continue;
}
let mm = &m["message"];
let Some(sp) = mm["spans"]
.as_array()
.and_then(|a| a.iter().find(|s| s["is_primary"] == true))
else {
continue;
};
// cargo reports paths relative to the workspace root, which may be above `root`
let p = sp["file_name"].as_str().unwrap_or_default();
let Some(file) = root.ancestors().map(|r| rel_to(r, p)).find(|c| c.exists()) else {
continue;
};
let severity = match mm["level"].as_str() {
Some("error") => 1,
Some("warning") => 2,
_ => continue,
};
v.push(Finding {
path: file,
line: sp["line_start"].as_u64().unwrap_or(1) as u32,
col: sp["column_start"].as_u64().unwrap_or(1) as u32,
severity,
rule: mm["code"]["code"].as_str().unwrap_or_default().to_string(),
message: mm["message"].as_str().unwrap_or_default().to_string(),
source: "clippy".into(),
});
}
Ok(v)
}
async fn ruff(root: &Path, files: &[PathBuf], timeout: Duration) -> Result<Vec<Finding>, String> {
let (o, _) = exec(
Command::new("ruff")
.args(["check", "--output-format=json", "--no-fix", "--quiet"])
.args(files)
.current_dir(root),
timeout,
)
.await?;
let a: Vec<Value> = serde_json::from_slice(&o).map_err(|e| format!("ruff output: {e}"))?;
Ok(a.iter()
.map(|x| Finding {
path: rel_to(root, x["filename"].as_str().unwrap_or_default()),
line: x["location"]["row"].as_u64().unwrap_or(1) as u32,
col: x["location"]["column"].as_u64().unwrap_or(1) as u32,
// ruff has no severities; syntax errors: code null (old) or "invalid-syntax" (new)
severity: if x["code"].is_null() || x["code"] == "invalid-syntax" {
1
} else {
2
},
rule: x["code"].as_str().unwrap_or("syntax").to_string(),
message: x["message"].as_str().unwrap_or_default().to_string(),
source: "ruff".into(),
})
.collect())
}
async fn biome(root: &Path, files: &[PathBuf], timeout: Duration) -> Result<Vec<Finding>, String> {
let (o, _) = exec(
Command::new("biome")
.args(["lint", "--reporter=json"])
.args(files)
.current_dir(root),
timeout,
)
.await?;
let v: Value = serde_json::from_slice(&o).map_err(|e| format!("biome output: {e}"))?;
Ok(v["diagnostics"]
.as_array()
.into_iter()
.flatten()
.filter_map(|x| {
let severity = match x["severity"].as_str()? {
"error" | "fatal" => 1,
"warning" => 2,
_ => return None,
};
Some(Finding {
path: rel_to(root, x["location"]["path"].as_str().unwrap_or_default()),
line: x["location"]["start"]["line"].as_u64().unwrap_or(1) as u32,
col: x["location"]["start"]["column"].as_u64().unwrap_or(1) as u32,
severity,
rule: x["category"].as_str().unwrap_or_default().to_string(),
message: x["message"].as_str().unwrap_or_default().to_string(),
source: "biome".into(),
})
})
.collect())
}
async fn eslint(root: &Path, files: &[PathBuf], timeout: Duration) -> Result<Vec<Finding>, String> {
let (o, _) = exec(
Command::new("eslint")
.args(["--format", "json"])
.args(files)
.current_dir(root),
timeout,
)
.await?;
let a: Vec<Value> = serde_json::from_slice(&o).map_err(|e| format!("eslint output: {e}"))?;
Ok(a.iter()
.flat_map(|f| {
let p = rel_to(root, f["filePath"].as_str().unwrap_or_default());
f["messages"]
.as_array()
.cloned()
.unwrap_or_default()
.into_iter()
.map(move |m| (p.clone(), m))
})
.map(|(p, m)| Finding {
path: p,
line: m["line"].as_u64().unwrap_or(1) as u32,
col: m["column"].as_u64().unwrap_or(1) as u32,
severity: if m["severity"] == 2 { 1 } else { 2 },
rule: m["ruleId"].as_str().unwrap_or_default().to_string(),
message: m["message"].as_str().unwrap_or_default().to_string(),
source: "eslint".into(),
})
.collect())
}
async fn ast_grep(
root: &Path,
files: &[PathBuf],
timeout: Duration,
) -> Result<Vec<Finding>, String> {
let mut rules = vec![];
let mut paths: Vec<_> = std::fs::read_dir(root.join(".hx/rules"))
.map_err(|e| e.to_string())?
.flatten()
.map(|e| e.path())
.collect();
paths.sort();
for p in paths
.iter()
.filter(|p| matches!(p.extension().and_then(|e| e.to_str()), Some("yml" | "yaml")))
{
rules.push(std::fs::read_to_string(p).map_err(|e| e.to_string())?);
}
if rules.is_empty() {
return Ok(vec![]);
}
let (o, _) = exec(
Command::new("ast-grep")
.args(["scan", "--json=compact", "--inline-rules"])
.arg(rules.join("\n---\n"))
.args(files)
.current_dir(root),
timeout,
)
.await?;
let a: Vec<Value> = serde_json::from_slice(&o).map_err(|e| format!("ast-grep output: {e}"))?;
Ok(a.iter()
.filter_map(|x| {
let severity = match x["severity"].as_str().unwrap_or("error") {
"error" => 1,
"warning" => 2,
_ => return None,
};
Some(Finding {
path: rel_to(root, x["file"].as_str().unwrap_or_default()),
line: x["range"]["start"]["line"].as_u64().unwrap_or(0) as u32 + 1,
col: x["range"]["start"]["column"].as_u64().unwrap_or(0) as u32 + 1,
severity,
rule: x["ruleId"].as_str().unwrap_or_default().to_string(),
message: x["message"].as_str().unwrap_or_default().to_string(),
source: "ast-grep".into(),
})
})
.collect())
}
#[cfg(test)]
mod tests {
use super::*;
fn runner(id: &str) -> &'static Runner {
RUNNERS.iter().find(|r| r.id == id).unwrap()
}
#[test]
fn applicability() {
let d = tempfile::tempdir().unwrap();
let ws = d.path();
std::fs::create_dir_all(ws.join("web/src")).unwrap();
std::fs::write(ws.join("web/biome.json"), "{}").unwrap();
let f = ws.join("web/src/a.ts");
assert_eq!(
marker_root(&f, &["biome.json"], ws).as_deref(),
Some(ws.join("web").as_path())
);
assert_eq!(marker_root(&ws.join("x.ts"), &["biome.json"], ws), None);
assert_eq!(marker_root(&f, &[], ws).as_deref(), Some(ws));
// empty rules dir: ast-grep off
std::fs::create_dir_all(ws.join(".hx/rules")).unwrap();
assert!(applies(runner("ast-grep"), &f, ws).is_none());
// wrong extension
assert!(applies(runner("ruff"), &f, ws).is_none());
}
#[tokio::test]
async fn real_tools() {
let d = tempfile::tempdir().unwrap();
let ws = d.path().to_path_buf();
let t = Duration::from_secs(60);
if which("ruff") {
let f = ws.join("p.py");
std::fs::write(&f, "import os\nx = (\n").unwrap();
let o = run(runner("ruff"), &ws, std::slice::from_ref(&f), t).await;
assert!(o.error.is_none(), "{:?}", o.error);
assert!(
o.findings.iter().any(|x| x.severity == 1),
"{:?}",
o.findings
);
std::fs::write(&f, "x = 1\n").unwrap();
let o = run(runner("ruff-format"), &ws, std::slice::from_ref(&f), t).await;
assert!(o.changed == [f.clone()] && std::fs::read_to_string(&f).unwrap() == "x = 1\n");
}
if which("biome") {
std::fs::write(ws.join("biome.json"), "{}").unwrap();
let f = ws.join("a.js");
std::fs::write(&f, "if (x == 2) { debugger; }\n").unwrap();
let o = run(runner("biome"), &ws, std::slice::from_ref(&f), t).await;
assert!(
o.findings
.iter()
.any(|x| x.rule == "lint/suspicious/noDebugger" && x.line == 1),
"{:?} {:?}",
o.findings,
o.error
);
}
if which("ast-grep") {
std::fs::create_dir_all(ws.join(".hx/rules")).unwrap();
std::fs::write(ws.join(".hx/rules/u.yml"), "id: no-unwrap\nlanguage: rust\nseverity: warning\nmessage: avoid unwrap\nrule:\n pattern: $A.unwrap()\n").unwrap();
let f = ws.join("m.rs");
std::fs::write(&f, "fn main() {\n let v = Some(1).unwrap();\n}\n").unwrap();
assert!(applies(runner("ast-grep"), &f, &ws).is_some());
let other = ws.join("n.rs");
std::fs::write(&other, "fn g() { None::<u8>.unwrap(); }\n").unwrap();
let o = run(runner("ast-grep"), &ws, std::slice::from_ref(&f), t).await;
assert_eq!(o.findings.len(), 1, "{:?}", o.error);
assert_eq!(
(
o.findings[0].line,
o.findings[0].col,
o.findings[0].severity
),
(2, 13, 2)
);
}
}
}
+142
View File
@@ -0,0 +1,142 @@
//! Triage marks: findings the user/agent marked false-positive or deferred. Persisted per project.
use crate::runners::Finding;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Mark {
/// never report again
FalsePositive,
/// hide until the file changes again
Defer,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Entry {
pub mark: Mark,
pub reason: String,
/// for Defer: file seq at mark time
#[serde(default)]
pub seq: u64,
}
/// key: "<relative path>|<finding key>"
#[derive(Default)]
pub struct Triage {
path: Option<PathBuf>,
marks: Mutex<BTreeMap<String, Entry>>,
}
impl Triage {
/// Load `<dir>/triage.json` (dir created on first save).
pub fn open(path: PathBuf) -> Self {
let marks = std::fs::read(&path)
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or_default();
Self {
path: Some(path),
marks: Mutex::new(marks),
}
}
pub fn key(rel: &Path, f: &Finding) -> String {
format!("{}|{}", rel.display(), f.key())
}
pub fn set(&self, key: String, e: Entry) -> std::io::Result<()> {
let mut m = self.marks.lock().unwrap_or_else(|e| e.into_inner());
m.insert(key, e);
self.save(&m)
}
pub fn remove_prefix(&self, prefix: &str) -> std::io::Result<usize> {
let mut m = self.marks.lock().unwrap_or_else(|e| e.into_inner());
let n = m.len();
m.retain(|k, _| !k.starts_with(prefix));
let removed = n - m.len();
self.save(&m)?;
Ok(removed)
}
fn save(&self, m: &BTreeMap<String, Entry>) -> std::io::Result<()> {
let Some(p) = &self.path else { return Ok(()) };
if let Some(d) = p.parent() {
std::fs::create_dir_all(d)?;
}
std::fs::write(
p,
serde_json::to_vec_pretty(m).map_err(std::io::Error::other)?,
)
}
/// Hidden if false-positive, or deferred and the file hasn't changed since.
pub fn hidden(&self, key: &str, file_seq: u64) -> bool {
match self
.marks
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(key)
{
Some(Entry {
mark: Mark::FalsePositive,
..
}) => true,
Some(Entry {
mark: Mark::Defer,
seq,
..
}) => file_seq <= *seq,
None => false,
}
}
pub fn list(&self) -> Vec<(String, Entry)> {
self.marks
.lock()
.unwrap_or_else(|e| e.into_inner())
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn marks_persist() {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("x/triage.json");
let t = Triage::open(p.clone());
t.set(
"a|k".into(),
Entry {
mark: Mark::FalsePositive,
reason: "r".into(),
seq: 0,
},
)
.unwrap();
t.set(
"b|k".into(),
Entry {
mark: Mark::Defer,
reason: "later".into(),
seq: 5,
},
)
.unwrap();
let t = Triage::open(p);
assert!(t.hidden("a|k", 99));
assert!(t.hidden("b|k", 5) && !t.hidden("b|k", 6));
assert!(!t.hidden("c|k", 0));
assert_eq!(t.remove_prefix("a|").unwrap(), 1);
assert_eq!(t.list().len(), 1);
}
}
+86
View File
@@ -0,0 +1,86 @@
//! External change watcher: polls mtimes of files the lens knows about and records changes made outside hx
//! (editor saves, git checkout) as `Source::External`, so the next report re-checks them.
//!
//! ponytail: mtime polling of tracked files only (no `notify` dependency, no new-file discovery).
//! Switch to `notify` if tracking whole trees becomes necessary.
use crate::seq::{SeqLog, Source};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};
#[derive(Default)]
pub struct Watch {
mtimes: Mutex<HashMap<PathBuf, Option<SystemTime>>>,
}
fn mtime(p: &PathBuf) -> Option<SystemTime> {
std::fs::metadata(p).and_then(|m| m.modified()).ok()
}
impl Watch {
/// Start tracking (or re-baseline after our own write) without recording a change.
pub fn track(&self, p: PathBuf) {
let m = mtime(&p);
self.mtimes
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(p, m);
}
/// Record files whose mtime changed since last seen. Returns them.
pub fn scan(&self, seq: &SeqLog) -> Vec<PathBuf> {
let mut map = self.mtimes.lock().unwrap_or_else(|e| e.into_inner());
let mut changed = vec![];
for (p, old) in map.iter_mut() {
let now = mtime(p);
if now != *old {
*old = now;
seq.bump(p, Source::External);
changed.push(p.clone());
}
}
changed
}
pub fn spawn(
self: &Arc<Self>,
seq: Arc<SeqLog>,
every: Duration,
) -> tokio::task::JoinHandle<()> {
let w = self.clone();
tokio::spawn(async move {
let mut t = tokio::time::interval(every);
loop {
t.tick().await;
w.scan(&seq);
}
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn external_bumps_once() {
let d = tempfile::tempdir().unwrap();
let f = d.path().join("a.rs");
std::fs::write(&f, "1").unwrap();
let (w, s) = (Watch::default(), SeqLog::default());
w.track(f.clone());
assert!(w.scan(&s).is_empty());
std::thread::sleep(Duration::from_millis(20));
std::fs::write(&f, "2").unwrap();
assert_eq!(w.scan(&s), std::slice::from_ref(&f));
assert!(w.scan(&s).is_empty());
assert_eq!(s.project(), 1);
// our own write: re-baseline, no bump
std::thread::sleep(Duration::from_millis(20));
std::fs::write(&f, "3").unwrap();
w.track(f);
assert!(w.scan(&s).is_empty());
}
}
Executable
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# Full local check: fmt, clippy, unit tests, all e2e scripts.
cd "$(dirname "$0")/.."
export PATH="$HOME/.local/bin:$PATH"
set -e
cargo fmt --all --check
cargo clippy -q --workspace --all-targets -- -D warnings
log=$(mktemp)
cargo test -q --workspace >"$log" 2>&1 || { grep -E 'FAILED|panicked' -A4 "$log"; exit 1; }
grep -oE 'ok. [0-9]+ passed' "$log" | awk '{s+=$2} END {print s" unit tests ok"}'
cargo build -q
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
+66
View File
@@ -0,0 +1,66 @@
"""M4 e2e fake model (python project):
turn 1: write badly formatted p.py with an unused import -> expect ruff F401 in lens report, file formatted
turn 2: edit p.py (must not be blocked by the formatter's change: read-guard refreshed)
turn 3: diag_mark the remaining finding as false positive
turn 4: finish; report what it saw
Usage: python3 tests/fake_m4.py PORT
"""
import http.server, json, sys
LOG = []
def sse(ev, d):
return f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode()
def texts(msg):
out = []
for b in msg["content"]:
if b.get("type") == "text":
out.append(b["text"])
if b.get("type") == "tool_result":
out.append(("ERR:" if b.get("is_error") else "OK:") + b["content"])
return "\n".join(out)
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(texts(body["messages"][-1]))
n = len(LOG)
if n == 1:
turn = ("Write", {"path": "p.py", "content": "import os\nx = 1\nprint( x )\n"})
elif n == 2:
turn = ("Edit", {"path": "p.py", "old_string": "x = 1", "new_string": "x = 2"})
elif n == 3:
turn = ("diag_mark", {"path": "p.py", "line": 1, "mark": "false_positive", "reason": "needed for side effects"})
else:
turn = 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 is None:
w(sse("content_block_start", {"index": 0, "content_block": {"type": "text", "text": ""}}))
w(sse("content_block_delta", {"index": 0, "delta": {"type": "text_delta", "text": "FINISHED"}}))
stop = "end_turn"
else:
w(sse("content_block_start", {"index": 0, "content_block": {"type": "tool_use", "id": f"t{n}", "name": turn[0], "input": {}}}))
w(sse("content_block_delta", {"index": 0, "delta": {"type": "input_json_delta", "partial_json": json.dumps(turn[1])}}))
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()
+33
View File
@@ -0,0 +1,33 @@
#!/bin/sh
# M4 e2e: ruff lint findings reach the model, ruff-format runs without tripping the read-guard,
# diag_mark persists and hides the finding.
set -eu
command -v ruff >/dev/null || { echo "skip: ruff not installed"; exit 0; }
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_m4.py" $port & srv=$!
mkdir -p "$tmp/home/.hx" "$tmp/repo"
echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}' > "$tmp/home/.hx/auth.json"
# ruff.toml enables ruff-format (formatters only run when configured)
echo 'line-length = 100' > "$tmp/repo/ruff.toml"
printf '[lsp]\ndisable = ["pyright"]\n' > "$tmp/home/.hx/config.toml"
sleep 0.5
cd "$tmp/repo"
HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port" "$root/target/debug/hx" -p "go" > "$tmp/out" 2> "$tmp/err" || { cat "$tmp/err"; exit 1; }
log="$tmp/log.json"
curl -s "http://127.0.0.1:$port/" > "$log"
fail() { echo "FAIL: $1"; echo "--- log"; python3 -m json.tool < "$log"; echo "--- err"; cat "$tmp/err"; exit 1; }
chk() { python3 -c "import json,sys; l=json.load(open(sys.argv[1])); $1" "$log"; }
grep -q FINISHED "$tmp/out" || fail "no finish"
# turn 2 request carries lens report with ruff F401
chk 'assert "[F401]" in l[1] and "(ruff)" in l[1], l[1]' || fail "no ruff finding"
# formatter applied, and the following edit was not blocked
grep -qx "x = 2" p.py && grep -qx "print(x)" p.py || fail "format/edit: $(cat p.py)"
chk 'assert l[2].startswith("OK:edited"), l[2]' || fail "edit blocked"
# diag_mark succeeded and persisted
chk 'assert "OK:marked FalsePositive" in l[3], l[3]' || fail "mark"
grep -q F401 "$tmp"/home/.hx/projects/*/triage.json || fail "triage not persisted"
[ -s "$tmp/home/.hx/latency.log" ] || fail "no latency log"
echo "m4 e2e ok"