diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index f3295c0..96006b4 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -14,3 +14,4 @@ jobs: - run: cargo build && sh tests/e2e.sh - run: python3 tests/tui_smoke.py - run: sh tests/lens_e2e.sh + - run: pip install ruff && sh tests/m4_e2e.sh diff --git a/README.md b/README.md index 4c38ae2..7bbc1ac 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,8 @@ max_tokens = 16384 [lsp] 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 # [[lsp.servers]] # add or override (same id replaces built-in) # id = "zls" # 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 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 -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//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. Credentials are stored in `~/.hx/auth.json` (mode 0600) and refreshed automatically. diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 4266b78..b7643ac 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -64,6 +64,10 @@ struct LspCfg { servers: Vec, /// built-in server ids to disable disable: Vec, + /// runner ids to enable in addition to defaults (e.g. "clippy") + enable_runners: Vec, + /// runner ids to disable (e.g. "rustfmt", "biome-format") + disable_runners: Vec, } 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(Arc); +#[async_trait::async_trait] +impl Hook for ArcHook { + async fn on(&self, ev: &Event) -> HookAction { + self.0.on(ev).await + } +} + fn session_dir(cwd: &std::path::Path) -> std::path::PathBuf { let slug: String = cwd .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.extend(lcfg.servers); let mgr = Arc::new(hx_lens::manager::Manager::new(cwd.clone(), servers)); + let mut lens_ref: Option> = None; let mode = lcfg.mode.unwrap_or(hx_lens::Mode::TurnEnd); if mode != hx_lens::Mode::Off { - agent - .bus - .add(hx_lens::Lens::new(mgr.clone(), Default::default(), mode)); + let slug = dir + .file_name() + .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() }); // 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) @@ -272,10 +298,28 @@ async fn main() -> Result<()> { default_model, pricing, lsp_status: { - let m = mgr.clone(); + let (m, l) = (mgr.clone(), lens_ref.clone()); Box::new(move || { - let m = m.clone(); - Box::pin(async move { m.status().await }) + let (m, l) = (m.clone(), l.clone()); + 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 + }) }) }, }) diff --git a/crates/hx-lens/src/lib.rs b/crates/hx-lens/src/lib.rs index 78c20c2..3e5f85f 100644 --- a/crates/hx-lens/src/lib.rs +++ b/crates/hx-lens/src/lib.rs @@ -6,7 +6,10 @@ pub mod lsp; pub mod manager; +pub mod runners; pub mod seq; +pub mod triage; +pub mod watch; use async_trait::async_trait; use hx_ai::ToolSpec; @@ -14,12 +17,14 @@ use hx_core::hook::{Event, Hook, HookAction}; use hx_core::tool::{Tool, ToolCtx, ToolResult}; use lsp::{Diag, path_of}; use manager::Manager; +use runners::{Finding, Kind, RUNNERS}; use seq::{SeqLog, Source}; use serde_json::{Value, json}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; use tokio::sync::Mutex; +use triage::{Entry, Mark, Triage}; #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)] #[serde(rename_all = "snake_case")] @@ -34,14 +39,24 @@ pub enum Mode { pub struct Lens { pub mgr: Arc, pub seq: Arc, + pub triage: Arc, pub mode: Mode, pub timeout: Duration, /// max characters injected per report pub cap: usize, + /// enabled runner ids (lint + format). Default: all except opt-in ones. + pub runners: Vec, + /// NDJSON per-runner timings; None = off + pub latency_log: Option, /// seq at the last report; changes after it are "this turn" reported: Mutex, /// last injected report per file, so unchanged findings aren't repeated every turn last: Mutex>, + /// runners whose binary is missing, reported once + pub notes: std::sync::Mutex>, + /// agent tool state, for refreshing the read-guard after formatting + pub state: std::sync::OnceLock>, + pub watch: Arc, } impl Lens { @@ -49,14 +64,143 @@ impl Lens { Self { mgr, seq, + triage: Default::default(), mode, timeout: Duration::from_secs(20), 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), 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)> { + let mut plan: Vec<(&runners::Runner, PathBuf, Vec)> = 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, Vec) { + 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 { let p = Path::new(p); if p.is_absolute() { @@ -66,46 +210,68 @@ impl Lens { } } - /// Diagnostics report for files changed since the last report. None = nothing to say. - pub async fn report(&self) -> Option { - let since = { - let mut r = self.reported.lock().await; - let s = *r; - *r = self.seq.project(); - s - }; - let files = self.seq.since(since); - let files: Vec = files + /// Report for files changed since the last report. None = nothing to say. + pub async fn report(&self, state: Option<&hx_core::State>) -> Option { + let since = { *self.reported.lock().await }; + let files: Vec = self + .seq + .since(since) .into_iter() - .filter(|f| self.mgr.server_for(f).is_some() && f.exists()) + .filter(|f| f.exists()) .collect(); if files.is_empty() { + *self.reported.lock().await = self.seq.project(); return None; } - let results = - futures::future::join_all(files.iter().map(|f| self.mgr.diagnostics(f, self.timeout))) - .await; - let mut sections = vec![]; + self.format(&files, state).await; + let start_seq = self.seq.project(); + let (findings, errs) = self.collect(&files).await; + *self.reported.lock().await = start_seq; + let mut last = self.last.lock().await; - for (f, r) in files.iter().zip(results) { - let body = match r { - Some(Ok(d)) => format_diags(&d), - Some(Err(e)) => format!(" (lsp unavailable: {e})"), - None => continue, - }; - let clean = body.is_empty(); + let mut sections = vec![]; + for f in &files { + let rel = PathBuf::from(self.rel(f)); + let fseq = self.seq.file(f); + let mut mine: Vec<&Finding> = findings + .iter() + .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()); - // report "now clean" once after errors; stay silent for clean files otherwise - if clean { + if body.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; } - let errors = body.matches("error").count(); - sections.push((usize::MAX - errors, format!("{}:\n{body}", self.rel(f)))); + if prev.as_deref() == Some(body.as_str()) { + 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 = errs; + notes.extend( + self.notes + .lock() + .unwrap_or_else(|e| e.into_inner()) + .drain(..), + ); + if sections.is_empty() && notes.is_empty() { return None; } sections.sort_by_key(|s| s.0); @@ -118,6 +284,9 @@ impl Lens { out.push_str(&s); out.push('\n'); } + if !notes.is_empty() { + out.push_str(&format!("(lens notes: {})\n", notes.join("; "))); + } 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. pub fn format_diags(d: &[Diag]) -> String { - let mut v: Vec<&Diag> = d.iter().filter(|x| x.severity <= 2).collect(); - v.sort_by_key(|x| (x.severity, x.line, x.col)); + let f: Vec = d + .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 mut s: String = v .iter() .take(20) .map(|x| { 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() } else { - format!("[{}] ", x.code) + format!("[{}] ", x.rule) }; - let msg = x.message.lines().next().unwrap_or_default(); - format!(" {}:{} {sev}: {code}{msg}\n", x.line + 1, x.col + 1) + format!( + " {}:{} {sev}: {code}{} ({})\n", + x.line, x.col, x.message, x.source + ) }) .collect(); if n > 20 { @@ -163,30 +359,113 @@ impl Hook for Lens { args, is_error: false, .. - } if name == "write" || name == "edit" => { + } if name == "write" || name == "edit" || name == "read" => { if let Some(p) = args["path"].as_str() { - let src = if name == "write" { - Source::AgentWrite - } else { - Source::AgentEdit - }; - self.seq.bump(&self.resolve(p), src); + let p = self.resolve(p); + match name.as_str() { + "write" => { + self.seq.bump(&p, Source::AgentWrite); + } + "edit" => { + self.seq.bump(&p, Source::AgentEdit); + } + _ => {} + } + // re-baseline so our own change isn't seen as external + self.watch.track(p); } 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 - .report() + .report(self.state.get().map(|s| s.as_ref())) .await .map_or(HookAction::Continue, HookAction::Inject), - Event::AgentEnd if self.mode == Mode::AgentEnd => match self.report().await { - Some(r) if r.contains(" error: ") => HookAction::Inject(r), - _ => HookAction::Continue, - }, + Event::AgentEnd if self.mode == Mode::AgentEnd => { + match self.report(self.state.get().map(|s| s.as_ref())).await { + Some(r) if r.contains(" error: ") => HookAction::Inject(r), + _ => HookAction::Continue, + } + } _ => HookAction::Continue, } } } +/// Triage tool: mark a finding false-positive or defer it. +pub struct DiagMark { + pub lens: Arc, +} + +#[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 = hits + .iter() + .map(|f| format!("[{}] {}", f.source, f.message)) + .collect(); + ToolResult::ok(format!("marked {mark:?}: {}", what.join("; "))) + } +} + pub struct LspTool { pub mgr: Arc, } @@ -340,7 +619,7 @@ mod tests { d(3, 1, "bad type\ndetail"), 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 = (0..25).map(|i| d(i, 1, "e")).collect(); assert!(format_diags(&many).ends_with("… 5 more")); } diff --git a/crates/hx-lens/src/lsp.rs b/crates/hx-lens/src/lsp.rs index c4643d6..1bc2724 100644 --- a/crates/hx-lens/src/lsp.rs +++ b/crates/hx-lens/src/lsp.rs @@ -36,6 +36,11 @@ pub struct Client { pub alive: Arc, /// active `$/progress` tokens + (rust-analyzer) not-quiescent; 0 = idle pub busy: Arc, + /// completed on-save checks (rust-analyzer flycheck). Diagnostics after a save are final once this advances. + pub checks_done: Arc, + pub checks_active: Arc, + /// Incremented on every `textDocument/publishDiagnostics` notification. + pub diag_seq: Arc, pub root: PathBuf, pub capabilities: std::sync::OnceLock, } @@ -119,16 +124,22 @@ impl Client { let notify = Arc::new(Notify::new()); let alive = Arc::new(std::sync::atomic::AtomicBool::new(true)); 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::(); // 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(), diags.clone(), notify.clone(), alive.clone(), busy.clone(), + checks_done.clone(), + checks_active.clone(), + diag_seq.clone(), ); tokio::spawn(async move { let mut r = BufReader::new(stdout); @@ -186,7 +197,7 @@ impl Client { } (None, Some(method)) if method == "textDocument/publishDiagnostics" => { let p = &m["params"]; - let list = p["diagnostics"] + let list: Vec = p["diagnostics"] .as_array() .map(|a| a.iter().map(parse_diag).collect()) .unwrap_or_default(); @@ -194,13 +205,28 @@ impl Client { p["uri"].as_str().unwrap_or_default().to_string(), (p["version"].as_i64(), list), ); + diag_seq.fetch_add(1, Ordering::SeqCst); notify.notify_waiters(); } (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() { - Some("begin") => busy.fetch_add(1, Ordering::SeqCst), - Some("end") => busy.fetch_sub(1, Ordering::SeqCst), - _ => 0, + Some("begin") => { + if is_flycheck { + 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(); } @@ -226,6 +252,9 @@ impl Client { diag_notify: notify, alive, busy, + checks_done, + checks_active, + diag_seq, root: root.to_path_buf(), capabilities: Default::default(), }); diff --git a/crates/hx-lens/src/manager.rs b/crates/hx-lens/src/manager.rs index 99906f2..13214e9 100644 --- a/crates/hx-lens/src/manager.rs +++ b/crates/hx-lens/src/manager.rs @@ -240,6 +240,9 @@ impl Manager { let _ = cl .notify("textDocument/didOpen", json!({"textDocument": {"uri": u, "languageId": language_for(&c, file), "version": 1, "text": text}})) .await; + let _ = cl + .notify("textDocument/didSave", json!({"textDocument": {"uri": u}})) + .await; 1 } Some(v) => { @@ -266,25 +269,65 @@ impl Manager { timeout: Duration, ) -> Option, String>> { 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 stale = before.diagnostics(&u).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, Vec)>| match d { Some((Some(rv), _)) => *rv >= v, Some((None, _)) => d != &stale || v == 1, None => false, }; - // Accept once the report is fresh AND the server is idle (not indexing), then settle briefly: - // servers often publish early (syntax only / empty while indexing) and refine later. + // For rust-analyzer, didSave triggers a flycheck. Wait until either: + // - 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 { let n = cl.diag_notify.notified(); 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 { let settle = cl.diag_notify.notified(); 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 .is_err() { @@ -313,7 +356,7 @@ impl Manager { _ => 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; } } diff --git a/crates/hx-lens/src/runners.rs b/crates/hx-lens/src/runners.rs new file mode 100644 index 0000000..4de6ebc --- /dev/null +++ b/crates/hx-lens/src/runners.rs @@ -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 { + 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 { + 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, + pub took: Duration, + /// set when the runner could not produce results + pub error: Option, + /// files the formatter changed + pub changed: Vec, +} + +async fn exec(cmd: &mut Command, timeout: Duration) -> Result<(Vec, Option), 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>> = 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, 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::(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, 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 = 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, 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, String> { + let (o, _) = exec( + Command::new("eslint") + .args(["--format", "json"]) + .args(files) + .current_dir(root), + timeout, + ) + .await?; + let a: Vec = 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, 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 = 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::.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) + ); + } + } +} diff --git a/crates/hx-lens/src/triage.rs b/crates/hx-lens/src/triage.rs new file mode 100644 index 0000000..f448bc7 --- /dev/null +++ b/crates/hx-lens/src/triage.rs @@ -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: "|" +#[derive(Default)] +pub struct Triage { + path: Option, + marks: Mutex>, +} + +impl Triage { + /// Load `/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 { + 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) -> 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); + } +} diff --git a/crates/hx-lens/src/watch.rs b/crates/hx-lens/src/watch.rs new file mode 100644 index 0000000..940d26f --- /dev/null +++ b/crates/hx-lens/src/watch.rs @@ -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>>, +} + +fn mtime(p: &PathBuf) -> Option { + 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 { + 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, + seq: Arc, + 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()); + } +} diff --git a/tests/all.sh b/tests/all.sh new file mode 100755 index 0000000..d2f8a5a --- /dev/null +++ b/tests/all.sh @@ -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 diff --git a/tests/fake_m4.py b/tests/fake_m4.py new file mode 100644 index 0000000..e5bb648 --- /dev/null +++ b/tests/fake_m4.py @@ -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() diff --git a/tests/m4_e2e.sh b/tests/m4_e2e.sh new file mode 100755 index 0000000..617be4c --- /dev/null +++ b/tests/m4_e2e.sh @@ -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"