diff --git a/README.md b/README.md index 7cb1174..9d52dfb 100644 --- a/README.md +++ b/README.md @@ -102,8 +102,8 @@ Sipeed has given strong support to HSync's work on its SLogic analyzers. ### Command line & automation (`hsync-cli`) -- **Standalone headless CLI (`hsync-cli`)** for scripts, hardware-in-the-loop tests and AI coding agents: `doctor`, `devices`, `catalog`, declarative `capture` (with `--trigger-timeout`, `--fallback-instant`, memory guardrails and `--exec` arm-then-act DUT stimulation), L0 signal `inspect`, L1/L2 `decode` (shorthand pipelines, summaries, structured `--where` filters, compact protocol transcripts and NDJSON), L3 `transitions`, Unicode `wave`, `measure` (pulses, edges, glitches, cross-channel deltas), `search` and `export`. -- **Built-in stateful MCP server (`hsync-cli mcp`)** over stdio JSON-RPC 2.0: keeps USB analyzers and captures open in memory across multi-turn agent sessions, exposes two-phase `capture_arm` / `capture_collect` and hot-loading custom `uiharu` DSL IR modules. +- **Standalone headless CLI (`hsync-cli`)** for scripts, hardware-in-the-loop tests and AI coding agents: `doctor`, `devices`, `catalog`, declarative `capture` (with `--trigger-timeout`, `--fallback-instant`, memory guardrails, `--exec` arm-then-act DUT stimulation and live software protocol-event early stop via `--stop-on-error` / `--stop-on-event` / `--post-trigger`), L0 signal `inspect`, L1/L2 `decode` (shorthand pipelines, summaries, structured `--where` filters, compact protocol transcripts and NDJSON), L3 `transitions`, Unicode `wave`, `measure` (pulses, edges, glitches, cross-channel deltas), `search`, before/after `diff`, declarative `assert` and `export`. +- **Built-in stateful MCP server (`hsync-cli mcp`)** over stdio JSON-RPC 2.0: keeps USB analyzers and captures open in memory across multi-turn agent sessions, exposes two-phase `capture_arm` / `capture_collect`, live protocol-event early stop, `capture_diff`, `capture_assert` and hot-loading custom `uiharu` DSL IR modules. - **Structured `--json` mode** across every command (including dual sample/time coordinates and actionable error hints) plus a ready-to-use Agent Skill in [skills/hsync-cli/SKILL.md](skills/hsync-cli/SKILL.md). See the [CLI guide](docs/cli.md). ## Download diff --git a/README.zh-CN.md b/README.zh-CN.md index 4b0c14d..b876771 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -101,8 +101,8 @@ SLogic 系列逻辑分析仪的适配得到了矽速科技(Sipeed)的大力 ### 命令行与自动化(`hsync-cli`) -- **独立无头命令行工具(`hsync-cli`)**,面向脚本、硬件在环测试与 AI Agent:涵盖 `doctor`、`devices`、`catalog`、声明式 `capture`(支持 `--trigger-timeout`、`--fallback-instant`、内存护栏与 `--exec` 先武装后激励协同)、L0 信号体检 `inspect`、L1/L2 `decode`(简写流水线、解码摘要、结构化 `--where` 过滤、紧凑协议视图与 NDJSON)、L3 `transitions` / Unicode `wave` / `measure`(脉宽、边沿、毛刺、跨通道延迟)、`search` 与 `export`。 -- **内置有状态 MCP 服务器(`hsync-cli mcp`)**(stdio JSON-RPC 2.0):在多轮 Agent 会话期间保持 USB 逻辑分析仪常驻与采集数据驻留内存,提供两阶段 `capture_arm` / `capture_collect` 与自定义 `uiharu` DSL IR 模块热加载。 +- **独立无头命令行工具(`hsync-cli`)**,面向脚本、硬件在环测试与 AI Agent:涵盖 `doctor`、`devices`、`catalog`、声明式 `capture`(支持 `--trigger-timeout`、`--fallback-instant`、内存护栏、`--exec` 先武装后激励协同,以及基于 `--stop-on-error` / `--stop-on-event` / `--post-trigger` 的实时协议事件软件触发早停)、L0 信号体检 `inspect`、L1/L2 `decode`(简写流水线、解码摘要、结构化 `--where` 过滤、紧凑协议视图与 NDJSON)、L3 `transitions` / Unicode `wave` / `measure`(脉宽、边沿、毛刺、跨通道延迟)、`search`、前后对照 `diff`、声明式断言 `assert` 与 `export`。 +- **内置有状态 MCP 服务器(`hsync-cli mcp`)**(stdio JSON-RPC 2.0):在多轮 Agent 会话期间保持 USB 逻辑分析仪常驻与采集数据驻留内存,提供两阶段 `capture_arm` / `capture_collect`、实时协议事件早停、`capture_diff`、`capture_assert` 与自定义 `uiharu` DSL IR 模块热加载。 - **全局 `--json` 结构化输出**(统一双坐标系与可恢复错误提示),并在 [skills/hsync-cli/SKILL.md](skills/hsync-cli/SKILL.md) 提供官方 Agent Skill。参见[命令行指南(英文)](docs/cli.md)。 ## 下载 diff --git a/crates/hsync-capture/src/profile.rs b/crates/hsync-capture/src/profile.rs index e5f0906..1c05cde 100644 --- a/crates/hsync-capture/src/profile.rs +++ b/crates/hsync-capture/src/profile.rs @@ -7,7 +7,7 @@ use std::ops::Range; use hsync_core::{ChannelIndex, SampleIndex}; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use crate::capture::LogicCapture; use crate::channel::ChannelData; @@ -19,7 +19,7 @@ pub const DEFAULT_PROFILE_EDGE_LIMIT: usize = 65_536; pub const DEFAULT_MAX_BURSTS: usize = 32; /// High-level state of a logic channel over an inspected range. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum ChannelActivity { /// The inspected range holds no samples. @@ -601,43 +601,25 @@ impl LogicCapture { Some((rows, false)) } - /// Measures delays from each `from_edge` on `from_edge.0` inside `range` to the first - /// subsequent `to_edge` on `to_edge.0` (at or after the reference edge, within `range` and - /// optional `max_delta`). - pub fn measure_edge_deltas( + /// Visits, in order, the delay from each `from_edge` on `from_edge.0` inside `range` to the + /// first subsequent `to_edge` on `to_edge.0` (at or after the reference edge, within `range` + /// and optional `max_delta`), until `visit` returns `false`. Every pair is visited, however + /// many there are; `None` when either channel is missing. + pub fn for_each_edge_delta( &self, from_edge: (ChannelIndex, EdgeKind), to_edge: (ChannelIndex, EdgeKind), range: Range, max_delta: Option, - limit: usize, - ) -> Option { + mut visit: impl FnMut(EdgeDeltaHit) -> bool, + ) -> Option<()> { let (ch_a, edge_a) = from_edge; let (ch_b, edge_b) = to_edge; let data_a = self.channel(ch_a)?; let data_b = self.channel(ch_b)?; let to = range.end.min(self.len()); let from = range.start.min(to); - if from >= to { - return Some(EdgeDeltaSummary { - count: 0, - min: None, - p5: None, - median: None, - p95: None, - max: None, - mean: None, - hits: Vec::new(), - truncated: false, - }); - } - - let mut deltas = Vec::new(); - let mut hits = Vec::new(); - let mut truncated = false; let mut cursor = from; - let cap = DEFAULT_PROFILE_EDGE_LIMIT; - while let Some(sample_a) = next_matching_edge(data_a, cursor, to, edge_a) { cursor = sample_a; let search_end = max_delta @@ -654,24 +636,48 @@ impl LogicCapture { } else { next_matching_edge(data_b, sample_a, search_end, edge_b) }; - if let Some(sample_b) = target { - let delta = sample_b - sample_a; - if deltas.len() >= cap { - truncated = true; - break; - } - deltas.push(delta); - if hits.len() < limit { - hits.push(EdgeDeltaHit { - from_sample: sample_a, - to_sample: sample_b, - delta, - }); - } else { - truncated = true; - } + if let Some(sample_b) = target + && !visit(EdgeDeltaHit { + from_sample: sample_a, + to_sample: sample_b, + delta: sample_b - sample_a, + }) + { + break; } } + Some(()) + } + + /// Measures delays from each `from_edge` on `from_edge.0` inside `range` to the first + /// subsequent `to_edge` on `to_edge.0` (at or after the reference edge, within `range` and + /// optional `max_delta`). At most [`DEFAULT_PROFILE_EDGE_LIMIT`] pairs are measured; use + /// [`Self::for_each_edge_delta`] to look at every one. + pub fn measure_edge_deltas( + &self, + from_edge: (ChannelIndex, EdgeKind), + to_edge: (ChannelIndex, EdgeKind), + range: Range, + max_delta: Option, + limit: usize, + ) -> Option { + let mut deltas = Vec::new(); + let mut hits = Vec::new(); + let mut truncated = false; + let cap = DEFAULT_PROFILE_EDGE_LIMIT; + self.for_each_edge_delta(from_edge, to_edge, range, max_delta, |hit| { + if deltas.len() >= cap { + truncated = true; + return false; + } + deltas.push(hit.delta); + if hits.len() < limit { + hits.push(hit); + } else { + truncated = true; + } + true + })?; let dist = summarize_distribution(deltas, truncated); Some(EdgeDeltaSummary { @@ -840,4 +846,54 @@ mod tests { }] ); } + + #[test] + fn for_each_edge_delta_visits_every_pair_past_the_profile_cap() { + // 2,188 words of one-sample high pulses (bits 1010…, 70,016 pulses), then one + // 12-sample pulse. + let mut words = vec![0x5555_5555_5555_5555u64; 2_188]; + words.push(0x0000_0000_0000_FFF0); + let mut capture = LogicCapture::new(1_000_000, [0]); + capture + .channel_mut(0) + .expect("channel") + .append_words(&words); + let len = capture.len(); + let rise = (0, EdgeKind::Rise); + let fall = (0, EdgeKind::Fall); + + let mut count = 0u64; + let mut widest = 0u64; + capture + .for_each_edge_delta(rise, fall, 0..len, None, |hit| { + count += 1; + widest = widest.max(hit.delta); + true + }) + .expect("channel exists"); + // The first pulse starts at sample 0, which is no edge; the wide one makes up for it. + assert_eq!(count, 2_188 * 32); + assert_eq!(widest, 12); + + // The capped summary stops short of the wide pulse. + let capped = capture + .measure_edge_deltas(rise, fall, 0..len, None, 5) + .expect("channel exists"); + assert_eq!(capped.count, DEFAULT_PROFILE_EDGE_LIMIT as u64); + assert!(capped.truncated); + assert_eq!(capped.max, Some(1)); + + // The visitor stops when asked, and a missing channel is `None`. + let mut visited = 0; + capture.for_each_edge_delta(rise, fall, 0..len, None, |_| { + visited += 1; + visited < 3 + }); + assert_eq!(visited, 3); + assert!( + capture + .for_each_edge_delta((9, EdgeKind::Rise), fall, 0..len, None, |_| true) + .is_none() + ); + } } diff --git a/crates/hsync-cli/src/commands/assert.rs b/crates/hsync-cli/src/commands/assert.rs new file mode 100644 index 0000000..b2336c0 --- /dev/null +++ b/crates/hsync-cli/src/commands/assert.rs @@ -0,0 +1,977 @@ +//! `hsync-cli assert`: declarative verification checks over a capture's signal profiles, +//! timing bounds and decoded protocol events for automated agent & HIL regression loops. + +use std::fs; +use std::path::Path; + +use hsync_capture::{ChannelActivity, ProfileOptions}; +use hsync_session::{EventFilter, Workspace}; +use hsync_uiharu::Needle; +use serde::{Deserialize, Serialize}; + +use crate::args::Args; +use crate::commands::decode::{DecoderSummaryReport, StreamSummaryReport, collect_summaries}; +use crate::commands::inspect; +use crate::commands::measure::parse_delta_spec; +use crate::error::CliError; +use crate::open::{channel_name_map, open_capture_file}; +use crate::pipeline::{load_graph_file, parse_decoder_spec}; +use crate::units::{ + Timestamp, format_freq_hz, format_ns_clean, parse_frequency_hz, parse_span_samples, + parse_span_samples_floor, resolve_channel, +}; + +pub const FLAGS: &[&str] = &["no-errors"]; + +pub const USAGE: &str = "\ +hsync-cli assert [checks...] [options] + + Evaluates declarative assertions against a capture (.hsync, .dsl, .vcd, .fst, .ghw). + Exits 0 if every assertion passes, or 4 if any assertion fails. + + Checks (repeatable, or load a JSON array with --rules ): + --no-errors Assert 0 decoded error events across all (or --stream) streams + --min-events = Assert stream produced at least N decoded events + --max-events = Assert stream produced at most N decoded events + --expect-event Assert at least one decoded event matches query (or stream:query) + --forbid-event Assert no decoded event matches query (or stream:query) + --freq =.. Assert channel frequency lies in [min, max] (e.g. SCL=95kHz..105kHz) + --active Assert channel has transitions + --constant-high Assert channel stays high (1) + --constant-low Assert channel stays low (0) + --no-glitches : Assert no pulse on is <= (e.g. D0:200ns) + --delta-bound =.. + Assert cross-channel delta stays within [min, max] + (e.g. CS:fall..CLK:rise=100ns..50us) + --rules Load assertions from a JSON array of AssertionSpec objects + + Shared options: + --decoder Attach decoder shorthand before asserting (repeatable) + --graph Attach decoder pipeline JSON file (repeatable) + --ir Load custom uiharu DSL IR JSON module (repeatable) + --stream Limit --no-errors to this stream, or to the streams of the + decoder with this label (repeatable) + --json Emit structured JSON report +"; + +/// One declarative assertion check (usable via CLI flags, `--rules` JSON or MCP). In JSON the +/// `kind` tag and every field are camelCase (`{"kind": "frequencyRange", "minHz": …}`), like +/// the rest of the CLI's JSON; unknown fields are rejected. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde( + tag = "kind", + rename_all = "camelCase", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +pub enum AssertionSpec { + NoErrors { + #[serde(default)] + stream: Option, + }, + MinEvents { + stream: String, + min: u64, + }, + MaxEvents { + stream: String, + max: u64, + }, + ExpectEvent { + #[serde(default)] + stream: Option, + query: String, + }, + ForbidEvent { + #[serde(default)] + stream: Option, + query: String, + }, + FrequencyRange { + channel: String, + min_hz: f64, + max_hz: f64, + }, + ChannelActivity { + channel: String, + /// `active`, `constantHigh`, `constantLow` or `empty`. + expected: ChannelActivity, + }, + NoGlitches { + channel: String, + max_width: String, + }, + DeltaBound { + delta: String, + min: String, + max: String, + }, +} + +/// Evaluation outcome of one [`AssertionSpec`]. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AssertionOutcome { + pub check: String, + pub passed: bool, + pub expected: String, + pub actual: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub evidence: Option, +} + +/// Aggregate report returned by `hsync-cli assert` and MCP `capture_assert`. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AssertReport { + pub passed: bool, + pub passed_count: usize, + pub failed_count: usize, + pub checks: Vec, +} + +pub fn run(args: &Args, json: bool) -> Result<(), CliError> { + args.only(&[ + "no-errors", + "min-events", + "max-events", + "expect-event", + "forbid-event", + "freq", + "active", + "constant-high", + "constant-low", + "no-glitches", + "delta-bound", + "rules", + "decoder", + "graph", + "ir", + "stream", + ])?; + let file = args + .positional() + .get(1) + .ok_or_else(|| CliError::usage("assert requires "))?; + + let specs = collect_cli_specs(args)?; + if specs.is_empty() { + return Err(CliError::usage( + "assert requires at least one check flag (e.g. --no-errors, --freq, --expect-event) or --rules ", + )); + } + + let mut workspace = Workspace::new(); + for ir in args.values("ir") { + workspace.load_module(Path::new(ir))?; + } + let summary = open_capture_file(&mut workspace, Path::new(file))?; + let names = channel_name_map(&summary); + let catalog = workspace.catalog(); + + let dec_specs = args.values("decoder"); + let graphs = args.values("graph"); + if !dec_specs.is_empty() || !graphs.is_empty() { + let mut entries = Vec::new(); + for s in dec_specs { + entries.push(parse_decoder_spec(s, &catalog, &names)?); + } + for p in graphs { + entries.push(load_graph_file(Path::new(p))?); + } + let values: Vec = entries + .iter() + .map(serde_json::to_value) + .collect::, _>>() + .map_err(|e| CliError::runtime("cli.json", e.to_string(), false, None))?; + workspace.set_decoders(summary.id, serde_json::Value::Array(values))?; + } + + let report = evaluate_assertions(&workspace, summary.id, &specs)?; + + if json { + outln!( + "{}", + serde_json::to_string_pretty(&report).map_err(|e| CliError::runtime( + "cli.json", + e.to_string(), + false, + None + ))? + ); + } else { + outln!( + "Assertions: {} ({} passed, {} failed)", + if report.passed { "PASS" } else { "FAIL" }, + report.passed_count, + report.failed_count + ); + for c in &report.checks { + let mark = if c.passed { "PASS" } else { "FAIL" }; + outln!( + " [{mark}] {}: expected {}, actual {}", + c.check, + c.expected, + c.actual + ); + } + } + + if report.passed { + Ok(()) + } else { + Err(CliError::assertion_failed(report.failed_count)) + } +} + +/// Evaluates `specs` against capture `capture_id` inside `workspace`. +pub fn evaluate_assertions( + workspace: &Workspace, + capture_id: u64, + specs: &[AssertionSpec], +) -> Result { + let summary = workspace.summary().ok_or_else(|| { + CliError::runtime("error.session.noCapture", "capture missing", false, None) + })?; + let cap_arc = workspace.capture(capture_id)?; + let capture = cap_arc.read(); + let names = channel_name_map(&summary); + let rate = capture.samplerate(); + let trig = capture.trigger_sample(); + let decoding = workspace.decoding(capture_id)?; + decoding.wait(); + let decoder_summaries = collect_summaries(&decoding, &summary, 5); + + let mut checks = Vec::with_capacity(specs.len()); + for spec in specs { + let outcome = match spec { + AssertionSpec::NoErrors { stream } => { + let mut total_errors = 0u64; + let mut first_error = None; + let mut matched_any_stream = false; + let mut failed_decoder: Option<(String, CliError)> = None; + for dec in &decoder_summaries { + // A decoder that failed to start has no streams: its label still selects it. + let dec_matches = stream + .as_deref() + .is_none_or(|w| w.eq_ignore_ascii_case(&dec.label)) + || dec + .streams + .iter() + .any(|st| selects(stream.as_deref(), dec, st)); + if dec_matches + && failed_decoder.is_none() + && let Some(err) = &dec.error + { + failed_decoder = Some((dec.label.clone(), err.clone())); + } + for st in &dec.streams { + if !selects(stream.as_deref(), dec, st) { + continue; + } + matched_any_stream = true; + total_errors += st.error_count; + if first_error.is_none() + && let Some(err) = st.sample_errors.first() + { + first_error = Some(serde_json::json!({ + "stream": st.name, + "event": err, + })); + } + } + } + let label = match stream { + Some(s) => format!("noErrors({s})"), + None => "noErrors".into(), + }; + if let Some((dec_label, err)) = failed_decoder { + AssertionOutcome { + check: label, + passed: false, + expected: "0 errors and healthy decoders".into(), + actual: format!("decoder '{dec_label}' failed: {}", err.message()), + evidence: Some(serde_json::json!({ + "decoder": dec_label, + "error": err, + })), + } + } else if !matched_any_stream { + AssertionOutcome { + check: label, + passed: false, + expected: "at least one decoded stream with 0 errors".into(), + actual: "no matching decoded stream found".into(), + evidence: None, + } + } else { + AssertionOutcome { + check: label, + passed: total_errors == 0, + expected: "0 errors".into(), + actual: format!("{total_errors} errors"), + evidence: first_error, + } + } + } + // A decoder that failed decoded only part of the capture: a lower bound it met + // still holds, but an upper bound (maxEvents, forbidEvent) cannot pass on it, and a + // check that fails names the failure. + AssertionSpec::MinEvents { stream, min } => { + let actual = stream_event_count(&decoder_summaries, stream); + let check = format!("minEvents({stream})"); + let expected = format!(">= {min} events"); + let passed = actual.is_some_and(|n| n >= *min); + match failed_decoder(&decoder_summaries, Some(stream)) { + Some(failed) if !passed => failed.outcome(check, expected, actual), + _ => AssertionOutcome { + check, + passed, + expected, + actual: actual + .map(|n| format!("{n} events")) + .unwrap_or_else(|| "stream not found".into()), + evidence: None, + }, + } + } + AssertionSpec::MaxEvents { stream, max } => { + let actual = stream_event_count(&decoder_summaries, stream); + let check = format!("maxEvents({stream})"); + let expected = format!("<= {max} events"); + match failed_decoder(&decoder_summaries, Some(stream)) { + Some(failed) => failed.outcome(check, expected, actual), + None => AssertionOutcome { + check, + passed: actual.is_some_and(|n| n <= *max), + expected, + actual: actual + .map(|n| format!("{n} events")) + .unwrap_or_else(|| "stream not found".into()), + evidence: None, + }, + } + } + AssertionSpec::ExpectEvent { stream, query } => { + let (matched_streams, hit) = find_first_matching_event( + &decoding, + &decoder_summaries, + stream.as_deref(), + query, + rate, + trig, + )?; + let check = format!("expectEvent({query})"); + let expected = format!("at least 1 event matching '{query}'"); + match failed_decoder(&decoder_summaries, stream.as_deref()) { + Some(failed) if hit.is_none() => failed.outcome(check, expected, None), + _ => { + let actual = if !matched_streams { + "no matching decoded stream found".into() + } else if hit.is_some() { + "matched".into() + } else { + "0 matches".into() + }; + AssertionOutcome { + check, + passed: matched_streams && hit.is_some(), + expected, + actual, + evidence: hit, + } + } + } + } + AssertionSpec::ForbidEvent { stream, query } => { + let (matched_streams, hit) = find_first_matching_event( + &decoding, + &decoder_summaries, + stream.as_deref(), + query, + rate, + trig, + )?; + let check = format!("forbidEvent({query})"); + let expected = format!("0 events matching '{query}'"); + match failed_decoder(&decoder_summaries, stream.as_deref()) { + Some(failed) if hit.is_none() => failed.outcome(check, expected, None), + _ => { + let (passed, actual) = if !matched_streams { + (false, "no matching decoded stream found".into()) + } else if hit.is_some() { + (false, "found forbidden event".into()) + } else { + (true, "0 matches".into()) + }; + AssertionOutcome { + check, + passed, + expected, + actual, + evidence: hit, + } + } + } + } + AssertionSpec::FrequencyRange { + channel, + min_hz, + max_hz, + } => { + let ch = resolve_channel(channel, &names)?; + let profile = capture + .profile_channel(ch, 0..capture.len(), ProfileOptions::default()) + .ok_or_else(|| { + CliError::config( + "error.session.unknownChannel", + format!("capture has no channel D{ch}"), + None, + ) + })?; + let actual_hz = profile.estimated_frequency_hz; + let passed = actual_hz.is_some_and(|f| f >= *min_hz && f <= *max_hz); + AssertionOutcome { + check: format!("freq({channel})"), + passed, + expected: format!("{}..{}", format_freq_hz(*min_hz), format_freq_hz(*max_hz)), + actual: actual_hz + .map(format_freq_hz) + .unwrap_or_else(|| "no periodic clock".into()), + evidence: actual_hz.map(|f| serde_json::json!({ "channel": ch, "hz": f })), + } + } + AssertionSpec::ChannelActivity { channel, expected } => { + let ch = resolve_channel(channel, &names)?; + if capture.channel(ch).is_none() { + return Err(CliError::config( + "error.session.unknownChannel", + format!("capture has no channel D{ch}"), + None, + )); + } + let report = inspect::build_report( + &capture, + &summary, + Some(&[ch]), + 0..capture.len(), + ProfileOptions::default(), + ); + let act = report + .channels + .first() + .map(|c| c.activity) + .unwrap_or(ChannelActivity::Empty); + AssertionOutcome { + check: format!("activity({channel})"), + passed: act == *expected, + expected: activity_name(*expected).into(), + actual: activity_name(act).into(), + evidence: report + .channels + .first() + .map(|c| serde_json::json!({ "rising": c.rising, "falling": c.falling })), + } + } + AssertionSpec::NoGlitches { channel, max_width } => { + let ch = resolve_channel(channel, &names)?; + let max_samples = parse_span_samples_floor(max_width, rate)?; + let data = capture.channel(ch).ok_or_else(|| { + CliError::config( + "error.session.unknownChannel", + format!("capture has no channel D{ch}"), + None, + ) + })?; + let (hits, truncated) = data.find_glitches(0..capture.len(), max_samples, 5); + let passed = hits.is_empty(); + let evidence = hits.first().map(|g| { + serde_json::json!({ + "start": Timestamp::of(g.start, rate, trig), + "widthSamples": g.width, + "widthNs": (rate > 0).then(|| g.width as f64 * 1e9 / rate as f64), + "high": g.high, + "more": truncated, + }) + }); + AssertionOutcome { + check: format!("noGlitches({channel}<={max_width})"), + passed, + expected: "0 glitches".into(), + actual: if passed { + "0 glitches".into() + } else if truncated { + format!(">{} glitches", hits.len()) + } else { + format!("{} glitch(es)", hits.len()) + }, + evidence, + } + } + AssertionSpec::DeltaBound { delta, min, max } => { + let (ch_a, edge_a, ch_b, edge_b) = parse_delta_spec(delta, &names)?; + let min_s = parse_span_samples(min, rate)?; + let max_s = parse_span_samples(max, rate)?; + // Every pair counts: one outside the bounds anywhere fails the check. + let mut count = 0u64; + let mut lo: Option = None; + let mut hi: Option = None; + let mut violation = None; + capture + .for_each_edge_delta( + (ch_a, edge_a), + (ch_b, edge_b), + 0..capture.len(), + None, + |hit| { + count += 1; + lo = Some(lo.map_or(hit.delta, |v| v.min(hit.delta))); + hi = Some(hi.map_or(hit.delta, |v| v.max(hit.delta))); + if violation.is_none() && (hit.delta < min_s || hit.delta > max_s) { + violation = Some(hit); + } + true + }, + ) + .ok_or_else(|| { + CliError::config( + "error.session.unknownChannel", + "one of the channels in deltaBound does not exist in capture", + None, + ) + })?; + let passed = count > 0 && violation.is_none(); + let fmt = |s: u64| { + if rate > 0 { + format_ns_clean(s as f64 * 1e9 / rate as f64) + } else { + format!("@{s}") + } + }; + let actual = match (lo, hi) { + (Some(lo), Some(hi)) => { + format!("{}..{} ({} pairs)", fmt(lo), fmt(hi), count) + } + _ => "0 edge pairs measured".into(), + }; + AssertionOutcome { + check: format!("deltaBound({delta})"), + passed, + expected: format!("{min}..{max}"), + actual, + evidence: Some(serde_json::json!({ + "count": count, + "minSamples": lo, + "maxSamples": hi, + "firstViolation": violation.map(|hit| serde_json::json!({ + "from": Timestamp::of(hit.from_sample, rate, trig), + "to": Timestamp::of(hit.to_sample, rate, trig), + "deltaSamples": hit.delta, + })), + })), + } + } + }; + checks.push(outcome); + } + + let passed_count = checks.iter().filter(|c| c.passed).count(); + let failed_count = checks.len() - passed_count; + Ok(AssertReport { + passed: failed_count == 0, + passed_count, + failed_count, + checks, + }) +} + +/// The JSON name of `activity`, as `channelActivity.expected` takes it. +fn activity_name(activity: ChannelActivity) -> &'static str { + match activity { + ChannelActivity::Empty => "empty", + ChannelActivity::ConstantLow => "constantLow", + ChannelActivity::ConstantHigh => "constantHigh", + ChannelActivity::Active => "active", + } +} + +/// Whether `want` selects stream `stream` of decoder `dec`: by the stream's name or by the +/// decoder's label, case-insensitively; with no `want`, every stream. Every check that names +/// a stream selects (and counts) streams by this one rule. +fn selects(want: Option<&str>, dec: &DecoderSummaryReport, stream: &StreamSummaryReport) -> bool { + want.is_none_or(|w| w.eq_ignore_ascii_case(&stream.name) || w.eq_ignore_ascii_case(&dec.label)) +} + +/// A decoder that failed, selected by a check (see [`failed_decoder`]). +struct FailedDecoder<'a> { + label: &'a str, + error: &'a CliError, +} + +impl FailedDecoder<'_> { + /// The failed outcome of `check`, naming the failure and the events counted before it. + fn outcome(&self, check: String, expected: String, events: Option) -> AssertionOutcome { + let counted = events.map_or_else(String::new, |n| format!(" after {n} events")); + AssertionOutcome { + check, + passed: false, + expected, + actual: format!( + "decoder '{}' failed{counted}: {}", + self.label, + self.error.message() + ), + evidence: Some(serde_json::json!({ + "decoder": self.label, + "error": self.error, + })), + } + } +} + +/// The first decoder `want` selects (by its label or one of its streams; every decoder with +/// no `want`) that failed to start or stopped part-way. +fn failed_decoder<'a>( + decoders: &'a [DecoderSummaryReport], + want: Option<&str>, +) -> Option> { + decoders.iter().find_map(|dec| { + let error = dec.error.as_ref()?; + let selected = want.is_none_or(|w| w.eq_ignore_ascii_case(&dec.label)) + || dec.streams.iter().any(|st| selects(want, dec, st)); + selected.then_some(FailedDecoder { + label: &dec.label, + error, + }) + }) +} + +/// The events of the streams `stream` selects (see [`selects`]); `None` when it selects none. +fn stream_event_count(decoders: &[DecoderSummaryReport], stream: &str) -> Option { + decoders + .iter() + .flat_map(|dec| dec.streams.iter().map(move |st| (dec, st))) + .filter(|(dec, st)| selects(Some(stream), dec, st)) + .map(|(_, st)| st.total) + .reduce(|a, b| a + b) +} + +fn find_first_matching_event( + decoding: &hsync_session::DecodeSet, + decoders: &[DecoderSummaryReport], + stream_filter: Option<&str>, + query: &str, + rate: u64, + trig: Option, +) -> Result<(bool, Option), CliError> { + let needle = Needle::parse(query) + .ok_or_else(|| CliError::usage(format!("blank event query '{query}'")))?; + let filter = EventFilter { + needle: Some(needle), + ..EventFilter::default() + }; + let mut matched_any_stream = false; + for dec in decoders { + for st in &dec.streams { + if !selects(stream_filter, dec, st) { + continue; + } + matched_any_stream = true; + if let Some(page) = decoding.filter(dec.index, st.index, &filter, 0, 1) + && let Some(row) = page.rows.into_iter().next() + { + return Ok(( + true, + Some(serde_json::json!({ + "stream": st.name, + "row": row.index, + "start": Timestamp::of(row.start, rate, trig), + "end": Timestamp::of(row.end, rate, trig), + "kind": row.kind, + "role": row.role, + "payload": row.payload, + })), + )); + } + } + } + Ok((matched_any_stream, None)) +} + +fn collect_cli_specs(args: &Args) -> Result, CliError> { + let mut specs = Vec::new(); + if let Some(path) = args.value("rules") { + let text = fs::read_to_string(path)?; + let loaded: Vec = serde_json::from_str(&text) + .map_err(|e| CliError::usage(format!("invalid --rules '{path}': {e}")))?; + specs.extend(loaded); + } + let streams = args.values("stream"); + if args.flag("no-errors") { + if streams.is_empty() { + specs.push(AssertionSpec::NoErrors { stream: None }); + } else { + for s in &streams { + specs.push(AssertionSpec::NoErrors { + stream: Some((*s).to_owned()), + }); + } + } + } + for raw in args.values("min-events") { + let (st, n) = parse_stream_count(raw, "--min-events")?; + specs.push(AssertionSpec::MinEvents { stream: st, min: n }); + } + for raw in args.values("max-events") { + let (st, n) = parse_stream_count(raw, "--max-events")?; + specs.push(AssertionSpec::MaxEvents { stream: st, max: n }); + } + for raw in args.values("expect-event") { + let (stream, query) = split_optional_stream(raw); + specs.push(AssertionSpec::ExpectEvent { stream, query }); + } + for raw in args.values("forbid-event") { + let (stream, query) = split_optional_stream(raw); + specs.push(AssertionSpec::ForbidEvent { stream, query }); + } + for raw in args.values("freq") { + let (ch, range) = raw.split_once('=').ok_or_else(|| { + CliError::usage(format!( + "invalid --freq '{raw}': expected CH=MIN..MAX (e.g. SCL=95kHz..105kHz)" + )) + })?; + let (min_s, max_s) = range.split_once("..").ok_or_else(|| { + CliError::usage(format!("invalid --freq range '{range}': expected MIN..MAX")) + })?; + let min_hz = parse_frequency_hz(min_s)? as f64; + let max_hz = parse_frequency_hz(max_s)? as f64; + specs.push(AssertionSpec::FrequencyRange { + channel: ch.trim().to_owned(), + min_hz: min_hz.min(max_hz), + max_hz: min_hz.max(max_hz), + }); + } + for ch in args.values("active") { + specs.push(AssertionSpec::ChannelActivity { + channel: ch.to_owned(), + expected: ChannelActivity::Active, + }); + } + for ch in args.values("constant-high") { + specs.push(AssertionSpec::ChannelActivity { + channel: ch.to_owned(), + expected: ChannelActivity::ConstantHigh, + }); + } + for ch in args.values("constant-low") { + specs.push(AssertionSpec::ChannelActivity { + channel: ch.to_owned(), + expected: ChannelActivity::ConstantLow, + }); + } + for raw in args.values("no-glitches") { + let (ch, w) = raw.split_once(':').ok_or_else(|| { + CliError::usage(format!( + "invalid --no-glitches '{raw}': expected CH:MAX_WIDTH (e.g. D0:200ns)" + )) + })?; + specs.push(AssertionSpec::NoGlitches { + channel: ch.trim().to_owned(), + max_width: w.trim().to_owned(), + }); + } + for raw in args.values("delta-bound") { + let (delta, range) = raw.split_once('=').ok_or_else(|| { + CliError::usage(format!( + "invalid --delta-bound '{raw}': expected CH_A:EDGE..CH_B:EDGE=MIN..MAX" + )) + })?; + let (min, max) = range.split_once("..").ok_or_else(|| { + CliError::usage(format!( + "invalid --delta-bound range '{range}': expected MIN..MAX" + )) + })?; + specs.push(AssertionSpec::DeltaBound { + delta: delta.trim().to_owned(), + min: min.trim().to_owned(), + max: max.trim().to_owned(), + }); + } + Ok(specs) +} + +fn parse_stream_count(raw: &str, flag: &str) -> Result<(String, u64), CliError> { + let (st, num) = raw + .split_once('=') + .ok_or_else(|| CliError::usage(format!("invalid {flag} '{raw}': expected STREAM=COUNT")))?; + let count: u64 = num + .trim() + .parse() + .map_err(|_| CliError::usage(format!("invalid count '{num}' in {flag}")))?; + Ok((st.trim().to_owned(), count)) +} + +fn split_optional_stream(raw: &str) -> (Option, String) { + let trimmed = raw.trim(); + if let Some(literal) = trimmed.strip_prefix(':') { + return (None, literal.trim().to_owned()); + } + if let Some((left, right)) = trimmed.split_once(':') + && !left.trim().is_empty() + && !left.contains(' ') + && !right.trim().is_empty() + { + return (Some(left.trim().to_owned()), right.trim().to_owned()); + } + (None, trimmed.to_owned()) +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use hsync_capture::LogicCapture; + use hsync_session::CaptureSource; + use serde_json::json; + + use super::*; + + fn protocol_capture() -> (Workspace, u64) { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../src-tauri/resources/demo/protocol.dsl"); + let mut workspace = Workspace::new(); + let summary = workspace.open_demo(&path).expect("opens protocol.dsl"); + (workspace, summary.id) + } + + fn check(workspace: &Workspace, id: u64, spec: AssertionSpec) -> AssertionOutcome { + evaluate_assertions(workspace, id, &[spec]) + .expect("evaluates") + .checks + .remove(0) + } + + #[test] + fn assertion_fields_are_camel_case_and_checked() { + let specs: Vec = serde_json::from_value(json!([ + { "kind": "frequencyRange", "channel": "D0", "minHz": 1.0, "maxHz": 2.0 }, + { "kind": "noGlitches", "channel": "D0", "maxWidth": "200ns" }, + { "kind": "channelActivity", "channel": "D0", "expected": "constantHigh" }, + ])) + .expect("camelCase fields"); + assert!(matches!( + specs[2], + AssertionSpec::ChannelActivity { + expected: ChannelActivity::ConstantHigh, + .. + } + )); + for bad in [ + json!({ "kind": "frequencyRange", "channel": "D0", "min_hz": 1.0, "max_hz": 2.0 }), + json!({ "kind": "noGlitches", "channel": "D0", "maxWidth": "1us", "extra": 1 }), + json!({ "kind": "channelActivity", "channel": "D0", "expected": "toggling" }), + ] { + assert!( + serde_json::from_value::(bad.clone()).is_err(), + "{bad}" + ); + } + } + + #[test] + fn delta_bound_fails_on_a_pair_past_the_profile_cap() { + // 70,016 one-sample high pulses, then a 12-sample one. + let mut words = vec![0x5555_5555_5555_5555u64; 2_188]; + words.push(0x0000_0000_0000_FFF0); + let mut capture = LogicCapture::new(1_000_000, [0]); + capture + .channel_mut(0) + .expect("channel") + .append_words(&words); + let mut workspace = Workspace::new(); + let id = workspace + .begin_live(CaptureSource::Demo, capture, false, None) + .summary + .id; + let outcome = check( + &workspace, + id, + AssertionSpec::DeltaBound { + delta: "D0:rise..D0:fall".into(), + min: "0s".into(), + max: "5us".into(), + }, + ); + assert!(!outcome.passed, "{outcome:?}"); + let evidence = outcome.evidence.expect("evidence"); + assert_eq!(evidence["count"], 2_188 * 32); + assert_eq!(evidence["firstViolation"]["deltaSamples"], 12); + } + + #[test] + fn a_decoder_label_selects_and_counts_its_streams() { + let (workspace, id) = protocol_capture(); + let no_errors = check( + &workspace, + id, + AssertionSpec::NoErrors { + stream: Some("I²C".into()), + }, + ); + assert!(no_errors.passed, "{no_errors:?}"); + assert_eq!(no_errors.actual, "0 errors"); + // The I²C decoder's i2c (45 events) and eeprom24xx (none) streams. + let min = check( + &workspace, + id, + AssertionSpec::MinEvents { + stream: "I²C".into(), + min: 45, + }, + ); + assert!(min.passed, "{min:?}"); + } + + #[test] + fn upper_bounds_fail_on_a_decoder_that_failed() { + let (mut workspace, id) = protocol_capture(); + let catalog = workspace.catalog(); + let entries = vec![ + parse_decoder_spec("uart(line=5,baud=115200)", &catalog, &BTreeMap::new()) + .expect("uart"), + parse_decoder_spec("i2c(scl=40,sda=41)", &catalog, &BTreeMap::new()).expect("i2c"), + ]; + workspace + .set_decoders(id, serde_json::to_value(entries).expect("JSON")) + .expect("sets decoders"); + let forbid = check( + &workspace, + id, + AssertionSpec::ForbidEvent { + stream: Some("i2c".into()), + query: "address 0x7F".into(), + }, + ); + assert!(!forbid.passed); + assert!(forbid.actual.contains("failed"), "{forbid:?}"); + let max = check( + &workspace, + id, + AssertionSpec::MaxEvents { + stream: "i2c".into(), + max: 1_000, + }, + ); + assert!(!max.passed); + // A healthy decoder is unaffected. + let uart = check( + &workspace, + id, + AssertionSpec::MaxEvents { + stream: "uart".into(), + max: 1_000, + }, + ); + assert!(uart.passed, "{uart:?}"); + } +} diff --git a/crates/hsync-cli/src/commands/capture.rs b/crates/hsync-cli/src/commands/capture.rs index d3886d5..ce6f032 100644 --- a/crates/hsync-cli/src/commands/capture.rs +++ b/crates/hsync-cli/src/commands/capture.rs @@ -15,8 +15,8 @@ use std::time::{Duration, Instant}; use parking_lot::Mutex; use hsync_capture::ProfileOptions; -use hsync_core::{ANALOG_BASE, ChannelIndex}; -use hsync_driver::{AdvancedTrigger, OptionKey, OptionKind, OptionValue}; +use hsync_core::{ANALOG_BASE, ChannelIndex, UiError}; +use hsync_driver::{AdvancedTrigger, CapturePreset, OptionKey, OptionKind, OptionValue}; use hsync_session::{ CaptureRequest, DeviceState, EndKind, EventSink, ExportKind, ExportRequest, Instrument, LivePhase, LiveStatus, SessionEvent, Workspace, @@ -30,6 +30,7 @@ use crate::commands::inspect::{self, InspectReport}; use crate::error::CliError; use crate::pipeline::{load_graph_file, parse_decoder_spec}; use crate::resources::Resources; +use crate::stop_on::{ProtocolStopHit, ProtocolStopMatcher, ProtocolStopSpec, ProtocolWatch}; use crate::units::{ Timestamp, format_bytes, format_freq_hz, format_samples_time, parse_bytes, parse_channel_list, parse_count, parse_duration, parse_duration_ns, parse_frequency_hz, parse_trigger_spec, @@ -58,6 +59,7 @@ pub const FLAGS: &[&str] = &[ "inspect", "fallback-instant", "every-sample", + "stop-on-error", ]; pub const USAGE: &str = "\ @@ -92,6 +94,14 @@ hsync-cli capture [options] (its stdin is empty) --exec-grace