Repository navigation
feat(cli): add diff, assert and live protocol-event early stop - #84
Merged
Merged
Conversation
Add the cli scope to commitlint.config.js for the standalone hsync-cli crate.
Add structured signal profiling, lossless multi-channel transitions, glitch scanning and cross-channel edge-delta measurement primitives to hsync-capture.
…haru Add StreamSummary, EventFilter and FieldFilter over decoded event stores so callers can aggregate kind/role/error counts and filter by range, kind, role, needle query or payload field predicates.
Add DecodeSet::wait, DecodeSet::summary and DecodeSet::filter and re-export capture profiling and decoded filter types from hsync-session.
Add crates/hsync-cli providing headless hardware/demo capture, L0 signal inspection, L1/L2 protocol decoding with shorthand auto-wired pipelines and compact transcripts, L3 transition/wave/measure/search queries, export, firmware discovery and structured --json output.
Test doctor, devices, catalog, inspect, decode, transitions, wave, measure, search, export and demo capture flows (dry-run, memory limit, --exec, save/export round-trip and trigger timeout exit code 3).
Add docs/cli.md and skills/hsync-cli/SKILL.md and update README.md, README.zh-CN.md and AGENTS.md to describe the standalone CLI.
Iterate d.received with iter_mut().enumerate().take(width) in the SD card decoder so Rust 1.100 clippy -D warnings passes cleanly.
Use VecDeque::range and slice iter_mut().enumerate() in AnalogData::extent and Summary::drop_front_chunks so Rust 1.100 clippy -D warnings passes.
HalfSweet
force-pushed
the
feat/hsync-mcp
branch
from
November 30, 2026 04:43
81dfac1 to
384411a
Compare
HalfSweet
force-pushed
the
feat/cli-verify
branch
from
November 30, 2026 04:43
4da48e9 to
ba51bf9
Compare
Use an internal Mutex on Decoder::thread so DecodeSet::wait only holds a shared read lock and cannot deadlock advance() or cancel(). Preserve exact 64-bit integer comparisons, array path indexing, and empty-range semantics in Store::filter, and guard empty/overflowing spans in AnalogData::bins.
Address code review findings across hsync-cli:
- Reject unknown long/short flags during Args::parse and honor --version anywhere
- Interpolate {code} in UiError fallbacks and map config/slogic/file codes
- Guard parse_duration/parse_count/parse_bytes overflow and SI sample counts
- Make --exec child processes killable on timeout and restore fallback SampleLimit
- Fix DSLogic fixed threshold matching, --duration range check and rate-tier match
- Propagate explicit decoder failures, fix leftmost --where split and NDJSON offset
- Fix empty-range edges, pulse@end, floor glitch width, search bounds, channel checks
Verify --fallback-instant output, killable blocking --exec commands, unknown flag rejection, empty edge ranges, pulse@end, channel checks, bounded decoded search and explicit decoder error propagation.
Extract declarative device configuration, doctor report, catalog filtering and parser helpers in hsync-cli so CLI commands and the stateful MCP server share one implementation.
Add a zero-dependency stdio JSON-RPC 2.0 MCP server under hsync-cli mcp supporting persistent open USB devices, multi-capture in-memory handles, two-phase capture_arm/capture_collect, runtime IR module loading, L0-L3 analysis tools and embedded skill/CLI resources.
Verify MCP handshake, tool/resource discovery, stateful multi-turn L0-L3 analysis, persistent open device and two-phase capture_arm and capture_collect over stdio pipes.
Document the stateful stdio MCP server, client configuration and two-phase arm-then-act workflow in docs/cli.md, skills/hsync-cli, README.md and README.zh-CN.md.
Address code review findings in hsync-cli mcp: - Validate capture_collect args before taking self.armed to avoid orphaned captures - Guard double capture_arm and wait for acquisition stop in capture_stop - Use killable ExecHandle on capture timeouts and include outputFile on fallback - Support JSON-RPC 2.0 batch arrays, reject non-object tools/call arguments and match requestId on notifications/cancelled - Strictly type-check string arrays/objects so decode_set never silently clears - Align capture_measure/search/inspect/save channel checks, pulse@end, floor glitch width, bounded query search and numeric captureId ordering on capture_close
Verify JSON-RPC 2.0 batch handling, non-object argument rejection, recoverable capture_collect validation errors, cli.noDecoders on capture_search and strict decode_set type checking.
Add closed-loop verification primitives to hsync-cli: - diff: compare signal profiles and decoded transcripts to pinpoint first divergence - assert: declarative signal/timing/protocol checks (--rules JSON, exit code 4) - capture: live software protocol-event early stop (--stop-on-error, --stop-on-event, --stop-where, --stop-after-events, --stop-stream, --post-trigger)
Add capture_diff and capture_assert tools to hsync-cli mcp and wire live software protocol-event early stop options (stopOnError, stopOnEvent, stopWhere, stopAfterEvents, stopStream, postTrigger) into MCP capture.
Cover identical/diverged diff reports, passing/failing assertions (including exit code 4 and --rules JSON), and live protocol-event early stop across both CLI commands and the stdio MCP server.
Update docs/cli.md, skills/hsync-cli/SKILL.md, README.md and README.zh-CN.md with diff, assert (exit code 4, --rules JSON), live software protocol-event triggers and their MCP equivalents.
- Restrict Demo protocol-stop decoder bypass to pattern=protocol - Re-anchor protocol stop hits after compaction and flag ring evictions - Report elapsed ms and distinct hints when finite captures end unmatched - Include rising/falling edges, initial level and duty in diff comparisons - Page diff transcripts past 4096 rows and mark truncated streams non-identical - Fail assert on decoder startup errors, missing forbid streams and bad channels
HalfSweet
force-pushed
the
feat/cli-verify
branch
from
November 30, 2026 07:46
ba51bf9 to
f0c983a
Compare
HalfSweet
force-pushed
the
feat/hsync-mcp
branch
from
November 30, 2026 07:46
384411a to
e1e9674
Compare
The standalone CLI and its MCP server are read by shells and agents, not by the localized interface, so they print English directly. Library crates still return only i18n keys and parameters; the CLI translates them in error.rs.
AGENTS.md asks for error enums defined with thiserror. CliError's variants are now its exit classes (Usage, Runtime, TriggerTimeout), each carrying the shared ErrorDetails: code, English message, params, retryability, hint and the underlying error as its source. Callers read it through code(), message(), hint(), kind() and exit_code(); the existing constructors stay. The JSON envelope and the stderr text are unchanged.
The protocol stop never looked at the decoders' state. A decoder that could not start (missing channels, an invalid pipeline) exposes no streams, and one that failed mid-run adds no error event, so --stop-on-error, --stop-on-event and --stop-after-events could never fire: the capture ran to the full --timeout and then reported a trigger timeout without the decoder's own error. An unknown --stop-stream name did the same. The matcher now fails when no decoder it watches is running: with the decoder's own error, with cli.unknownStopStream (listing the decoded streams) for a --stop-stream naming nothing, and once every watched decoder has failed after its settled events were read. The capture loop stops at once and the command returns that error. --stop-stream also accepts a decoder label, as the assertions do.
With a protocol stop condition, a capture that ended because the analyzer failed or was unplugged went through the protocol-stop recheck first, which turned the missing match into cli.triggerTimeout (exit 3) with a hint about decoder configuration, so the real error.device.detached was never shown and agents retried with a longer timeout instead of reconnecting. The CLI and MCP capture paths now return the capture's device error before judging the protocol stop.
A match first found in the last look after the capture had ended, such as one that settled while --timeout stopped the capture, was reported with endReason protocolTrigger although the timeout had stopped it and no post-trigger window was recorded. The capture loop now tells whether its watch hook sent the stop, and the CLI and MCP report protocolTrigger only then; such a late match still appears as protocolTrigger evidence beside the real end reason.
--stop-after-events 0 passed validation and matched on the first look, so a typo or templated 0 stopped the capture at once with an almost empty buffer and triggered: true. --stop-stream or --post-trigger given without a stop condition were silently dropped, so a user who forgot --stop-on-error got a normal fixed-length capture and exit 0, as if the fault never happened. Both are now usage errors (exit 2), in the CLI and in MCP capture.
Add Instrument::device_preset, the channel names and decoders the open device suggests for a capture, so that a caller replacing the decoders can keep the device's channel names.
Attaching explicit decoders at the start of a capture, which live protocol stops need, built a preset from the --name bindings alone, replacing the Demo device's whole preset: a protocol capture with --decoder came back with numbered channels instead of SCL and SDA, unlike before. The CLI and MCP capture now lay the --name (names) bindings over the open device's own channel names and replace only its decoders.
#84 gave the capture's workspace a clone of the event sink, so the status channel could never disconnect and a capture thread that died without sending its end left the loop spinning after the timeout stop. The shared capture loop now gets a workspace without an event sink (the protocol stop polls the decoders instead of waiting on their progress events), so the channel closes when the capture thread goes away. When it closes before the capture has ended, drive_capture now reports the capture as failed with error.device.lost instead of carrying on as if it had ended normally.
A stream over 100,000 events or 25,000 transcript lines was always reported as diverged, even when both captures were byte-identical: identical required the stream not to be truncated, so a regression gate built on diff failed on every long capture with no firstDivergence to show for it. identical now follows from equal totals and error counts and no divergence in the transcript lines compared; truncated stays as its own flag on the stream and, new, on the report, and the human output says the comparison was partial.
diff fetched a stream's events in pages of 4,096, and every page rescanned the whole stream to count matches, so reading a long stream cost time quadratic in its length, as decode --view ndjson did before. It now reads the events in one for_each_match pass, stopping at the raw-event limit.
Pull the pairing of reference and target edges out of measure_edge_deltas into for_each_edge_delta, which visits every pair without the DEFAULT_PROFILE_EDGE_LIMIT cap or a buffer, so that a check over all pairs does not have to collect them. measure_edge_deltas keeps its behaviour on top of it.
deltaBound looked only at the min and max of measure_edge_deltas, which stops after 65,536 pairs, and ignored its truncated flag, so a violation past that point passed: a long SPI capture whose pair #80,000 broke the bound reported PASS. The check now visits every pair through for_each_edge_delta, fails on the first one outside the bounds and reports it as evidence (firstViolation) with the pair count and the overall min and max.
rename_all on the tagged AssertionSpec enum renamed only the kinds, so the
fields of frequencyRange and noGlitches stayed min_hz, max_hz and max_width
in --rules files and MCP capture_assert while every other key of the JSON
API is camelCase; {"kind": "noGlitches", "maxWidth": "200ns"} failed with
a missing field, and nothing documented the field names.
The fields are now camelCase (minHz, maxHz, maxWidth) and unknown fields are
rejected, and the capture_assert schema lists each kind's fields.
channelActivity.expected was free text compared case-insensitively, so a rules file saying "high", "toggling" or "constant_high" produced a failed assertion (exit 4) rather than a usage error, and a HIL gate went red over a typo instead of a DUT fault. expected is now ChannelActivity itself (active, constantHigh, constantLow, empty, for which hsync-capture derives Deserialize); anything else is a usage error, and the MCP schema lists the four values.
noErrors matched a decoder by its label but counted streams by stream name only, so --no-errors --stream <label> reported "no matching decoded stream found"; the other stream checks knew only stream names. Every assertion that names a stream now selects, and counts, streams by the same rule: the stream's name or its decoder's label, case-insensitively. minEvents and maxEvents add up the streams selected.
Only noErrors looked at the decoders' errors. forbidEvent, maxEvents and minEvents treated a decoder that stopped part-way through the capture as healthy, so forbidEvent and maxEvents could pass on results that ended early: a pipeline failing at 10% of the capture let --forbid-event pass with 0 matches although the forbidden traffic came later. An upper bound (maxEvents, forbidEvent without a match) now fails when a decoder it selects has failed, and a lower bound (minEvents, expectEvent) that is not met names the failure; a lower bound already met still passes. The outcome carries the decoder and its error as evidence.
The CLI and MCP capture paths each turned a finished protocol watch into a hit or an unmet-stop error, after checking the device error themselves. Move that verdict into ProtocolWatch::judge, which checks the capture's device error before the match, so the order the device-failure fix relies on lives beside the watch and can be tested there.
Move the comparison of one stream's transcripts, counts and verdict out of compute_diff's loop into diff_stream, so the verdict can be tested on its own without decoding captures long enough to be truncated.
Checks that consecutive start windows visit every event once in store order, a long event in the window of its start, that skip, filter and the match count apply within a window, and that pruning the front does not move the windows.
…reset Checks that a settled window over an ended stream holds every event once, the same rows as its listing, that reading on from its end finds nothing and that splitting it repeats nothing; and that the Demo device offers the protocol pattern's channel names and decoders through device_preset.
Checks that for_each_edge_delta visits all of more than 65,536 pairs, including a wide pulse at the end, while measure_edge_deltas stops at the cap; that the visitor stops when asked; and that a missing channel gives None.
Covers the protocol stop matcher on the Demo protocol capture (the Nth event counted once, the Nth match with a filter, an unknown stream, a decoder label, a decoder missing its channels), the device error coming before an unmet stop, a kept hit placed in the final capture, the rejected option combinations, the capture loop's watch hook and a status channel closing early; the diff verdict on long equal streams; and assertions in camelCase, deltaBound past the profile cap, label-selected streams and upper bounds on a decoder that failed.
Runs the CLI on the Demo device: --stop-after-events past what a 32 Ki-sample ring holds, the Nth match with --stop-where, failing at once on a decoder missing its channels and on an unknown --stop-stream, the rejected stray options, and the Demo pattern's channel names kept with an explicit decoder; and assert --rules in camelCase. Over MCP stdio it cancels a running protocol-stop capture and checks the stop and assertion arguments.
Describe in docs/cli.md and the hsync-cli skill how live protocol stops count events across ring prunes, stop at the Nth match with a filter, fail at once when they can never match, report device failures and protocolTrigger, and keep the device's channel names; when diff calls a long stream identical and truncated; and the camelCase fields of each assertion kind, stream selection by name or label, deltaBound over every pair and assertions on a decoder that failed. The --stop-stream and assert --stream help, the MCP stopStream description and the eventCount rustdoc say the same.
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds closed-loop hardware verification primitives to
hsync-cliandhsync-cli mcp: before/after capturediff, declarativeassertgates, and live software protocol-event early stop ("protocol trigger") powered byuiharu's streaming decode engine.What's included
hsync-cli diff/ MCPcapture_diff).hsync,.dsl,.vcd,.fst,.ghw, or in-memory MCP capture handles) across per-channel signal metrics (activity, rising/falling edge deltas, duty cycle, frequency delta %) and decoded protocol streams (event counts, error counts, and the exact first transcript divergence with configurable--context).hsync-cli assert/ MCPcapture_assert)--rules <file.json>(AssertionSpecarray):noErrors,minEvents,maxEvents,expectEvent,forbidEvent,frequencyRange,channelActivity(--active/--constant-high/--constant-low),noGlitches(floor-rounded duration bounds so wider pulses never false-trigger), anddeltaBound.0when all assertions pass or4(cli.assertionFailed) when any check fails, printing structured expected/actual evidence per check.crates/hsync-cli/src/stop_on.rs,capture.rs,mcp/session.rs)uiharu's liveDecodeSetincrementally during acquisition and stops automatically once a decoded condition hits:--stop-on-error/stopOnError(anyEventRole::Errorevent)--stop-on-event <query>/stopOnEvent(Needle query)--stop-where <expr>/stopWhere(structured payload predicates, e.g.address=0x62)--stop-after-events <N>/stopAfterEvents--stop-stream <name>/stopStream--post-trigger <dur>/postTrigger(trailing recording window after the match)can_loop == trueso pre-event and post-event samples around intermittent faults are captured cleanly, and reportsendReason: "protocolTrigger"+protocolTriggerhit evidence (or exit code3on unmet timeout).crates/hsync-cli/tests/cli.rsandcrates/hsync-cli/tests/mcp.rscovering identical/diverged diffs, passing/failing assertions (including exit code4and--rulesJSON), and live protocol-event early stop + unmet timeout across both CLI and MCP stdio.docs/cli.md,skills/hsync-cli/SKILL.md,README.md, andREADME.zh-CN.md.Review follow-up
cli.assertionFailedis theCliError::AssertionFailedvariant (exit code 4).settled_since,for_each_match_starting), counts across ring prunes, keeps the original hit and flagsevictedFromBuffer;endReason: "protocolTrigger"appears only when the watch stopped the capture.--stop-after-events Ntogether with--stop-on-event/--stop-wherestops at the Nth match (matchCount);0, and--stop-stream/--post-triggerwithout a stop condition, are usage errors.--stop-stream(cli.unknownStopStream), ends the capture at once; a device error takes precedence over the trigger-timeout verdict.diff:identicalno longer requires untruncated streams;truncatedis reported separately, the human output says when a comparison was partial, and streams are read in one pass.assert:deltaBoundchecks every edge pair (for_each_edge_delta); rule fields are camelCase (minHz,maxHz,maxWidth) and unknown fields are rejected;channelActivity.expectedis an enum; stream checks share one label-or-stream rule; upper-bound checks fail when the owning decoder failed.--namebindings.Verification
cargo fmt --all -- --checkcargo clippy --workspace --all-targets -- -D warningscargo test -p hsync-cli -p hsync-uiharu -p hsync-session -p hsync-capture(hsync-cli: 36 unit + 21 CLI integration + 15 MCP stdio integration tests)pnpm exec prettier --checkon the changed docs