Skip to content

feat(cli): add diff, assert and live protocol-event early stop - #84

Merged
HalfSweet merged 99 commits into
mainfrom
feat/cli-verify
Dec 1, 2026
Merged

HalfSweet merged 99 commits into
mainfrom
feat/cli-verify

Conversation

@HalfSweet

@HalfSweet HalfSweet commented Nov 29, 2026 •

Copy link
Copy Markdown
Owner

Summary

Stacked on #83 (feat/hsync-mcp, which stacks on #82 feat/hsync-cli).

Adds closed-loop hardware verification primitives to hsync-cli and hsync-cli mcp: before/after capture diff, declarative assert gates, and live software protocol-event early stop ("protocol trigger") powered by uiharu's streaming decode engine.

What's included

  • Before/after regression diff (hsync-cli diff / MCP capture_diff)
    • Compares two captures (.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).
  • Declarative assertions (hsync-cli assert / MCP capture_assert)
    • Evaluates repeatable CLI checks or --rules <file.json> (AssertionSpec array): noErrors, minEvents, maxEvents, expectEvent, forbidEvent, frequencyRange, channelActivity (--active / --constant-high / --constant-low), noGlitches (floor-rounded duration bounds so wider pulses never false-trigger), and deltaBound.
    • Exits with code 0 when all assertions pass or 4 (cli.assertionFailed) when any check fails, printing structured expected/actual evidence per check.
  • Live software protocol-event early stop (crates/hsync-cli/src/stop_on.rs, capture.rs, mcp/session.rs)
    • Evaluates uiharu's live DecodeSet incrementally during acquisition and stops automatically once a decoded condition hits:
      • --stop-on-error / stopOnError (any EventRole::Error event)
      • --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)
    • Enables continuous ring-buffer looping on devices with can_loop == true so pre-event and post-event samples around intermittent faults are captured cleanly, and reports endReason: "protocolTrigger" + protocolTrigger hit evidence (or exit code 3 on unmet timeout).
  • Tests & Docs
    • Expanded crates/hsync-cli/tests/cli.rs and crates/hsync-cli/tests/mcp.rs covering identical/diverged diffs, passing/failing assertions (including exit code 4 and --rules JSON), and live protocol-event early stop + unmet timeout across both CLI and MCP stdio.
    • Updated docs/cli.md, skills/hsync-cli/SKILL.md, README.md, and README.zh-CN.md.

Review follow-up

  • Merged the feat(cli): add stateful stdio MCP server in hsync-cli mcp #83 fixes. The protocol stop is a watch hook on the shared capture loop and works with MCP cancellation; cli.assertionFailed is the CliError::AssertionFailed variant (exit code 4).
  • Stop matching reads only events settled since the last poll in each stream (settled_since, for_each_match_starting), counts across ring prunes, keeps the original hit and flags evictedFromBuffer; endReason: "protocolTrigger" appears only when the watch stopped the capture.
  • --stop-after-events N together with --stop-on-event/--stop-where stops at the Nth match (matchCount); 0, and --stop-stream/--post-trigger without a stop condition, are usage errors.
  • A decoder that fails, or an unknown --stop-stream (cli.unknownStopStream), ends the capture at once; a device error takes precedence over the trigger-timeout verdict.
  • diff: identical no longer requires untruncated streams; truncated is reported separately, the human output says when a comparison was partial, and streams are read in one pass.
  • assert: deltaBound checks every edge pair (for_each_edge_delta); rule fields are camelCase (minHz, maxHz, maxWidth) and unknown fields are rejected; channelActivity.expected is an enum; stream checks share one label-or-stream rule; upper-bound checks fail when the owning decoder failed.
  • Demo captures keep the device's channel names under explicit --name bindings.

Verification

  • cargo fmt --all -- --check
  • cargo clippy --workspace --all-targets -- -D warnings
  • cargo 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 --check on the changed docs

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.
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
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.
@HalfSweet
HalfSweet changed the base branch from feat/hsync-mcp to main December 1, 2026 05:02
@HalfSweet
HalfSweet merged commit 40d5499 into main Dec 1, 2026
@github-actions github-actions Bot mentioned this pull request Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant