Skip to content

feat(cli): add standalone agent-friendly hsync-cli - #82

Merged
HalfSweet merged 32 commits into
mainfrom
feat/hsync-cli
Dec 1, 2026
Merged

HalfSweet merged 32 commits into
mainfrom
feat/hsync-cli

Conversation

@HalfSweet

@HalfSweet HalfSweet commented Nov 29, 2026 •

Copy link
Copy Markdown
Owner

Summary

Introduces hsync-cli, a standalone, agent-friendly command-line interface for HSync logic analyzers, capture files and protocol decoding, while keeping uiharu-cli focused as an independent Apache-2.0 raw-binary decoder.

What's included

  • Reusable library primitives (pure structured types, zero natural language)
    • hsync-capture: channel profiling (profile_channel, profile_analog), lossless multi-channel transitions, narrow-pulse find_glitches, and cross-channel measure_edge_deltas.
    • hsync-uiharu & hsync-session: StreamSummary (counts by kind/role/error + leading error rows), EventFilter / FieldFilter (range, kind, role, needle and field predicates), and DecodeSet::wait / summary / filter.
  • Standalone hsync-cli binary (crates/hsync-cli)
    • Human-readable compact output by default plus global --json mode (dual sample/time coordinates and structured error envelopes with code, message, retryable, and actionable hint).
    • Distinct exit codes: 0 success, 1 runtime/hardware/IO error, 2 usage/config/memory-limit error, 3 trigger timeout.
    • External firmware & demo discovery (--firmware-dir, HSYNC_FIRMWARE_DIR, bundle/install/dev fallback) without embedding vendor firmware into the binary.
    • Commands:
      • doctor, devices [info <id>], catalog [show <proto>]
      • capture: declarative hardware/demo setup (rate-tier auto-selection, --dry-run, --max-memory, --trigger-timeout, --fallback-instant, --exec arm-then-act stimulus runner, -o save/export, inline --inspect & --decoder)
      • inspect (L0 signal triage + bursts + frequency/baud hints)
      • decode (L1 summary, L2 protocol-aware transcript for I²C/SPI/UART/CAN + generic fallback, rows, ndjson, shorthand auto-wired --decoder, --where, --errors-only, --ir, --save)
      • transitions, wave (Unicode timing diagram), measure (--pulse, --edges, --glitches, --delta), search (--pattern / --query), export
  • Tests & Documentation
    • Unit tests across hsync-capture, hsync-uiharu, and hsync-cli, plus end-to-end integration tests (crates/hsync-cli/tests/cli.rs) exercising protocol.dsl and virtual-demo.
    • Added docs/cli.md, official Agent Skill skills/hsync-cli/SKILL.md, and updated README.md, README.zh-CN.md, AGENTS.md, and commitlint.config.js.

Review follow-up

  • CliError is now a thiserror enum (Usage, Runtime, TriggerTimeout) whose details keep the source error; exit codes, the JSON envelope and the stderr text are unchanged.
  • AGENTS.md: hsync-cli (and its MCP server) is exempt from the i18n-keys-only rule and prints English; the library crates still return only keys and parameters.
  • Capture: a buffer-mode trigger that has fired (hardware_triggered or a trigger sample) no longer counts as a trigger timeout; waits after stop are bounded (cli.captureTimeout), and the fallback snapshot sends stop once.
  • --exec: new --exec-grace <dur> (default 10 s) before the command is killed once the capture ends; no hang when a background process keeps the pipes open; on Windows the command reaches cmd /C verbatim.
  • The default --timeout scales with the requested length (×1.5, plus the trigger timeout, plus 10 s, at least 60 s); raw --option rate/samples apply before --duration is sized, and conflicting rate or sample settings are usage errors.
  • decode --view ndjson --all reads each stream in one pass (for_each_match in hsync-uiharu); decode --save keeps the file's view session.
  • measure --pulse reports startIsEdge, endIsEdge and truncated, and omits period, frequency and duty for a pulse cut off at the capture start.
  • wave clamps its width to the window's sample count; search --pattern rejects unknown channels; writing to a closed pipe exits 0 instead of panicking.

Verification

  • cargo fmt --all -- --check
  • cargo clippy --workspace --all-targets -- -D warnings
  • cargo test -p hsync-cli -p hsync-uiharu -p hsync-session (hsync-cli: 12 unit + 12 CLI integration tests)
  • cargo check -p hsync-cli --target x86_64-pc-windows-msvc for the Windows --exec path
  • 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.
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.
In buffer mode DSLogic and ATK-Logic stay Waiting until the filled
buffer uploads, so a trigger that fired early still hit
--trigger-timeout and the capture was thrown away with exit code 3.
The trigger now counts as fired once the hardware reports it.

Once stop was sent the loop waited for the capture to end with no limit,
and the fallback snapshot re-sent stop every 25 ms forever. Both now
give up after a 10 s grace period with cli.captureTimeout.
When the --exec command left a background process holding its stdout or
stderr (openocd &, nohup server &), the output readers waited for an EOF
that never came and hsync-cli never exited. After the command exits the
readers now get 500 ms to drain and are then left behind.
A stimulus still running when the capture ended was killed after 2 s,
which could abort a flash or reset script part-way through. The new
--exec-grace option (default 10 s) sets how long it may keep running.
Command::args escapes inner double quotes MSVC-style as \", which
cmd.exe does not understand, so any --exec command with quoted paths ran
with mangled arguments. The command now follows /C through raw_arg.
--option overrides ran last, after --duration had been turned into a
sample count at the old rate, so --option rate=10MHz --duration 10ms
captured 1 ms. Raw options now apply before the sample limit, and
setting the rate or the sample count both ways is a usage error.
The fixed 60 s default stopped longer captures such as --duration 2m
half-way and still exited 0. Without an explicit --timeout the limit is
now the requested length plus half again, the trigger timeout when a
trigger is armed and 10 s, never below 60 s.
Store::filter scans the whole stream on every call to count the
matches, so reading a long stream page by page cost a full scan per
page. Store, Decoder and DecodeSet gain for_each_match, which visits the
matching rows in order after a skip and stops when told to, in a single
pass. filter keeps its behaviour and now shares the matching code.
decode --view ndjson --all fetched pages of 1024 rows, and every page
rescanned the whole stream (and JSON-parsed it with --where), so a 2M
event stream took hours. It now writes rows straight from
DecodeSet::for_each_match.
decode --save wrote an empty session, so re-saving an .hsync file from
the app dropped its cursors, groups and layout. The session read from
the opened file is now written back.
measure --pulse measured a run that starts at sample 0 from the capture
start, reporting a short width and a wrong period, frequency and duty
cycle. The output now carries startIsEdge, endIsEdge and truncated, and
leaves out the period, frequency and duty cycle when the pulse has no
start edge.
When the window held fewer samples than --width columns, the empty
columns were drawn as spaces scattered through the diagram. wave now
draws at most one column per sample and reports that width.
search --pattern 'D20=R' on a 16-channel capture printed 0 hits and
exited 0, so a typo read as an edge that never happens. It now fails
with error.session.unknownChannel like the other commands.
Rust ignores SIGPIPE, so println! panicked when a reader closed the
pipe: decode --view ndjson | head ended with a panic and exit code 101.
Commands now write through out!/outln!, which end the process with exit
code 0 on a broken pipe and report other write failures with exit
code 1.
Checks that for_each_match visits the same rows as filter's pages, in
order, honours the skip and the early stop, reports the matches it saw
and respects the scope.
Unit tests for the buffer-mode trigger that fires while still Waiting,
giving up on a stopped capture that never ends, the default --timeout
derived from the request, an --exec command whose background child
keeps its pipes open, and the --exec-grace window.
End-to-end tests for a raw sample rate sizing --duration and the
conflicting-option errors, decode --save keeping an .hsync session,
truncated pulses without a period, wave in windows narrower than
--width, search patterns on missing channels, a reader closing stdout
early and --exec running within --exec-grace.
Describe in docs/cli.md and the hsync-cli skill the --exec-grace window,
the derived default --timeout and cli.captureTimeout, the order raw
--option overrides apply in, buffer-mode triggers, wave's one column per
sample, truncated pulses and the quiet exit on a closed pipe.
@HalfSweet
HalfSweet merged commit 212677d into main Dec 1, 2026
4 checks passed
@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