Skip to content

Waveform Analysis Format and Extensions

WaveInfo automatically selects a reader based on the file extension, with built-in support for FST, VCD, FSDB, and USDB. File listing, signal query, event analysis, and evidence replay all use the same format configuration. This configuration only affects the search and selection of existing waveforms during analysis; it does not change the format generated by the simulator, SetWaveform, or test fixture.

Manual Bug waveform replay in Console

waveform_replay is contributed by the UnitTest plugin through the command registry and is unavailable unless the plugin is active. Console, TUI, and HTTP can submit it through the shared executor, which owns operation state and cancellation. In Console:

1
2
3
4
(UnityChip) waveform_replay
(UnityChip) waveform_replay 600
(UnityChip) waveform_replay --reanalyze 600
(UnityChip) waveform_replay --reanalyze --max-rounds 5 600

waveform_replay [timeout_seconds] uses the unique configured waveform gate with require_current_replay: true, including its dynamic Bug document and test directory, without calling an LLM. The same stage must have one matching DUT test-classification checker before that gate; the final stage of unittest:unittest already satisfies this requirement. The optional argument is a positive integer timeout in seconds for the full test run, defaulting to the resolved cfg.call_time_out. The command works without switching stages and does not record Bugs or advance or complete stages. An active model turn blocks the command before tests or evidence changes begin.

It first runs that classification check, rerunning the full DUT suite and validating failures against BG/TC/CK associations. Correct DUT Bug reproducers remain Fail. Classification failures stop replay. It then replays each unique TC associated with nonzero-confidence dynamic Bugs once. Semantically unchanged records retain their analysis conclusions while current receipts, waveform paths, and viewing settings refresh atomically. Already-current evidence is not rewritten. With no valid dynamic Bugs, it validates the canonical empty document and reports that replay is unnecessary.

Console output and UCAgent logs use the [waveform_replay] prefix for the document, test directory, test timeout, classification result, per-TC progress and status, refresh count, elapsed time, and final SUCCESS, FAILED, or CANCELLED. For local foreground execution, Ctrl+C requests cancellation; cancel HTTP submissions by their returned operation ID, as described in Runtime Control. Missing or ambiguous configuration, classification failures, missing waveforms, invalid receipts, and write failures report the current operation and the complete diagnostic. Follow that diagnostic before retrying.

Changes to a TC's assertions, stimulus, or test source must fail that TC's replay even if its waveform is identical. Preserve its original analysis and re-analyze the associated Bugs. Changed test paths, function names, or parameterized node IDs must not be treated as equivalent automatically. Changes to source code, timelines, signal values, or other signed semantic inputs produce WAVEFORM_SEMANTIC_BATCH_REVIEW_REQUIRED, with requires_bug_reanalysis: true, exact TCs, changed files, and the complete review_batch_call for subsequent analysis. Follow that call to prepare all contexts with ReviewWaveInfoEvidenceBatch, re-analyze every associated Bug against the current TC, specification, source, and waveform evidence, then submit every completed review atomically and run Check once as directed. Other semantically unchanged records may already have refreshed during the failed command, with a separate progress log; each document write still follows the atomic commit contract.

Add --reanalyze to let the configured LLM resolve classification or replay failures: waveform_replay [timeout_seconds] --reanalyze [--max-rounds N]. Model work starts only after a failed check. The default limit is three reanalysis turns; --max-rounds requires --reanalyze and a positive integer. The test timeout applies to each full test run, not to the whole LLM task. Each turn receives the complete diagnostic and the canonical Bug/test guidance, reads Guide_Doc/dut_bug_analysis.md and Guide_Doc/dut_test_case.md, analyzes the current TC against the specification and source, and updates actual artifacts. Skills are optional; ordinary file tools and Guide_Doc provide the same repair path.

Confirmed DUT Bugs keep valid failing reproducers and receive updated BG/ROOT analysis and signed waveform evidence. When correcting an invalid TC proves that an association is no longer a DUT Bug, remove that TC/reference from the disproved association, retain BGs supported by other failing TCs, and remove only unsupported BGs, empty dynamic branches, unreferenced ROOTs, and unused central waveform records. Synchronize stale static dynamic-confirmation links and existing summaries/reports. A partial test report is never grounds for deleting historical findings; valid assertions, coverage, unrelated Bugs, and shared roots must be preserved. If only one association is disproved while the TC still reproduces another Bug, remove only that association and preserve the failing TC and supported findings. When no dynamic Bug remains, keep the canonical empty three-section document.

After every model turn the command reruns full classification and current replay, and validates any configured matching static Bug-link checks. It reports SUCCESS only when all of these checks pass. An LLM's claim of success cannot override failures. Logs include LLM REANALYSIS round i/N, the remaining diagnostics, and the final number of model turns. The command temporarily blocks stage validation/completion/navigation/exit tools and keeps CurrentTips focused on reanalysis, then restores their callbacks and the prior pause state. It does not run the Bug Recorder or publish records. Whenever automatic refresh or LLM work changes the dynamic/static analysis, it reloads every matching Recorder’s document view and invalidates previously accepted records, including after a partial edit followed by failure or cancellation. Submit the current Bugs again through the normal recording stage before publishing. Default replay remains available without model work; reanalysis reports a clear error for a disabled/busy model backend, backend failure, exhausted rounds, or cancellation. Changes already made by the LLM are retained for inspection and retry if validation fails or execution is cancelled.

Default Suffixes for Test Artifacts

The test API template selects the artifact suffix via test_utils.get_default_subfix(dut, sub_type), where sub_type is either "waveform" or "coverage". The returned value does not include a leading dot:

dut.SIMULATOR Waveform Suffix Coverage Suffix
verilator .fst .dat
vcs .fsdb .vdb
uvs .usdb .cdb

This function accepts a DUT instance or class, reads the simulator name from its attribute, and ignores case and leading/trailing whitespace. If the SIMULATOR attribute is missing, it defaults to Verilator. If the attribute is None, an empty string, a non-string, or an unknown name, an error is raised; an invalid sub_type also raises an error.

get_coverage_data_path(request, dut, new_path) and get_waveform_path(request, dut, new_path) return the suffixes used for unique artifact paths for each test. When creating artifacts, use new_path=True; when reporting coverage, use the same DUT with new_path=False to obtain the original path. For VCS, .vdb may be a directory; pass the full path. The fake DUT in the template phase and independent Mock DUTs retain the SIMULATOR declared in the original DUT class without needing to start a real simulator.

When adding a new simulator, add waveform and coverage to _SIMULATOR_DEFAULT_SUFFIXES in ucagent/applications/UnitTest/src/unit_test/test_utils.py and add the corresponding tests; no branches need to be added to the path templates. This mapping only defines naming rules; actual artifacts depend on DUT build and simulator support. New waveform formats still require registration of a reader as described in this page.

Format Priority

The default configuration is located in the UnitTest workflow ucagent/applications/UnitTest/src/unit_test/workflows/unittest.yaml:

runtime_options:
  waveform_analysis_format_priority: [fst, vcd, fsdb, usdb]

This can be overridden in workspace configuration or an explicitly specified configuration file, for example, to prioritize VCD analysis:

runtime_options:
  waveform_analysis_format_priority: [vcd, fst, fsdb, usdb]

The list defines the formats participating in the search: [vcd] searches only for VCD, disabling FST, FSDB, and USDB. The list must be non-empty, extensions must be lowercase and without a dot, and duplicates are not allowed. This configuration follows the normal configuration hierarchy; the parsed value is written to runtime_options in .ucagent/runtime_config.json and is not re-read from environment variables at runtime.

WaveInfo first determines the latest toffee_tmp_* test session, then matches the exact test name and optional numeric dump suffix. Within the same session, it compares format priority first, then numeric suffix, file modification time, and path. Therefore, under default configuration, test_add001.fst takes precedence over test_add999.vcd. It will not use an older session to find a higher-priority format, nor will it replace the test name with a similar one. File extension case does not affect format recognition.

If the selected file is empty, corrupted, or missing parsing dependencies, the tool returns the file's path, format, and recovery suggestions without automatically switching to another format. To switch, first fix waveform generation or explicitly adjust analysis priority, then re-call WaveInfo. The format_priority in the listing and selection results displays the order used for the current analysis.

Backend priority within each format

runtime_options.waveform_analysis_backend_priority independently configures the reader libraries for each format. Defaults:

1
2
3
4
5
6
7
runtime_options:
  waveform_analysis_format_priority: [fst, vcd, fsdb, usdb]
  waveform_analysis_backend_priority:
    fst: [pywellen, wavekit]
    vcd: [pywellen, wavekit]
    fsdb: [wavekit]
    usdb: [uvd]

Format priority selects the waveform file; backend priority then selects an implementation for that same file. Lists must be nonempty, lowercase and distinct. A configured but unregistered backend fails when constructing WaveInfo. Override only vcd: [wavekit] to keep other built-in defaults; a single entry disables library fallback for that format. Values come from resolved cfg.runtime_options, are validated and saved in .ucagent/runtime_config.json, and are never re-read from environment variables during a call.

FST/VCD default to WellenFstReader / WellenVcdReader, with WavekitFstReader / WavekitVcdReader as alternatives. Concrete classes must carry a backend prefix. Dependencies are pywellen>=0.25.7,<0.26, wavekit>=0.7.0,<0.8.0, and the directly declared pylibfst>=0.2.1,<0.3.

Only ImportError/ModuleNotFoundError during factory construction or context entry permits the next backend. Corruption, permission errors, query errors, unsupported advanced options and failures after analysis starts propagate without retrying. Selection never changes the TC, session, file or format. If every backend is unavailable, the tool directs the task to an operator to repair the environment and retry.

The current pywellen Python API omits complete file time bounds and declared bit indices. The VCD implementation additionally scans declarations and timestamp markers without retaining trace data, preserving final timestamps with no signal changes. The FST implementation uses pylibfst only for names, indices and time bounds, then immediately closes that metadata handle. Signal values are decoded by pywellen. It loads selected signals on demand but retains each loaded signal's complete native trace; narrow windows use indexed binary search without copying every Python row. Catalog output is bounded, while native metadata enumeration remains complete. This does not eliminate large-file scanning or memory costs. Digital analysis supports declared indices, ascending/negative ranges, array paths, wide integers and X/Z; real/string variables are excluded from the digital catalog. Contiguous scalar declarations retain their original bit paths. If the binding exposes indistinguishable duplicate names, such as noncontiguous scalar declarations of one bus, analysis fails instead of guessing their correspondence. Native decoding panics become analysis errors with resource cleanup.

Operator logs use the [WaveInfo] prefix. The runtime log records backend_order, each backend_attempt, backend_unavailable reasons, backend_open_failed and backend_selected. Console/runtime analysis_started / analysis_finished entries identify the actual backend, TC, status and elapsed time. They do not dump backend_args. Backend identity is not added to LLM tool results. File inventory does not open a reader and therefore has no selected-backend entry.

FSDB Runtime Dependencies and Online Viewing

FSDB uses WavekitFsdbReader to adapt wavekit. FSDB also requires the Verdi NPI runtime library libNPI.so; configure it before starting UCAgent using one of the following methods:

  • WAVEKIT_NPI_LIB: The full path to libNPI.so.
  • VERDI_HOME: The Verdi installation directory.
  • LD_LIBRARY_PATH: A search path containing the library and its runtime dependencies.

These variables are used by the FSDB runtime library and operate independently of the waveform analysis format priority configuration. If NPI is missing, WaveInfo reports to the verification task that waveform analysis cannot be performed and recovery actions are taken; the underlying exception is written to the UCAgent runtime log. Environment maintainers should check runtime library configuration according to this section. Format, reader, and dependency configurations are managed by environment maintainers. Runtime guides and tool descriptions only require the verification task LLM to call WaveInfo and handle the results.

Metadata-based viewing

Viewing uses /wave/?meta=<workspace-relative JSON path> and pins the actual waveform selected for that analysis. Metadata for a.fsdb is stored beside it as a.fsdb.json. The file browser reads extensions from GET /api/waveform/viewers and posts {"waveform_file":"waves/a.fsdb"} to POST /api/waveform/metadata. This creates missing metadata and preserves existing final evidence settings.

A final WaveInfo tool call publishes metadata. Direct analyze() and replay only compute results. ApplyWaveInfoEvidence synchronizes the selected receipt's view, including repeated Apply calls. Batch refresh/review publishes after all preparation succeeds and rolls metadata back if the document commit fails. Ordinary Check does not write metadata. One current view is stored per waveform; independent signed receipts retain historical snapshots. Removing waveform/JSON files does not invalidate verified historical evidence, while online viewing reports the missing files. Links never search a newer session or substitute another format.

Example waves/a.fsdb.json:

{
  "schema_version": 1,
  "waveform_file": "a.fsdb",
  "signals": ["TOP.dut.clk", "TOP.dut.result"],
  "source_files": ["../rtl/Demo.sv", "../src/Demo.scala"],
  "dut_python_path": "../Demo/__init__.py",
  "test_file": "../unit_test/tests/test_demo.py",
  "test_case": "unit_test/tests/test_demo.py::test_saturation",
  "start": "100",
  "end": "200",
  "cursor": "150",
  "integrity_hmac": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
}

All file paths inside JSON are relative to its directory and use /. Parent references are allowed, but resolved files and symlinks must stay inside the selected workspace. waveform_file is a basename beside the JSON. The first five fields are required; an unresolved Python entry is null and unknown source associations use an empty list. Test association preserves the exact node ID. Final windows contain all three nonnegative decimal-string timestamps in native waveform ticks, avoiding JavaScript integer precision loss. Ordinary viewing can omit the window. Metadata is limited to 1 MiB and 64 unique signals.

Existing main DUT design files, Python entries and exact test sources are associated automatically. WaveInfo(source_files=[...], dut_python_path="...") accepts workspace-relative paths for associations determined by the LLM. Scanned source files are not all added as related material. Invalid explicit paths fail; unresolved optional automatic associations produce warnings rather than invented paths.

Metadata integrity

Stored JSON requires a tool-generated integrity_hmac. The 64 hexadecimal digits above illustrate the format and cannot be copied as a working signature. HMAC-SHA256 authenticates the complete unsigned JSON content together with its workspace-relative destination, using a workspace-specific secret. Changes to signals, timestamps, associated files, test IDs or link targets, and copies to another workspace, fail verification. Whitespace and object-key order do not affect canonical signing; duplicate JSON keys are rejected. Online links must use the resolved workspace-relative JSON path, rather than a symlink alias, so browser and server resolve the same waveform directory.

Keys stay outside the workspace at the service user's ~/.ucagent/waveform_keys/, with directory mode 0700 and key mode 0600. Key filenames derive from SHA-256 of the resolved workspace path. Keys never enter metadata, tool output or runtime configuration. Verification does not recreate missing keys. Republish viewing metadata through the tools after moving a workspace or losing its key.

CMD verifies integrity before dispatch, returning Surfer metadata and creating Xpra sessions. Surfer receives authenticated semantic fields with the signature removed. The default Verdi launcher verifies again immediately before starting the application, catching modifications after opening the page. Missing signatures, mismatches or unavailable keys prevent viewing. Ordinary viewing never re-signs modified JSON. Republish final evidence with WaveInfo/ApplyWaveInfoEvidence; for ordinary viewing, remove the damaged JSON and select the actual waveform again.

Historical receipts independently sign semantic snapshots. Ordinary Check does not need live JSON or its signing key, so deleting waveform/JSON files or losing the viewing key does not invalidate verified history. This mechanism detects metadata changes by parties without the key; it does not authenticate waveform/source contents or protect against someone who can read the same operating-system user's private keys or invoke signing tools.

Viewers and Xpra configuration

ucagent/setting.yaml provides the default cmd_api.waveform_viewers mapping, which can be overridden through the resolved workspace configuration:

cmd_api:
  waveform_viewers:
    fst:
      kind: web
      url: /surfer/
    vcd:
      kind: web
      url: /surfer/
    fsdb:
      kind: xpra
      script: verdi/launch_verdi.py
      args: ["--meta", "{wave_meta}", "--verdi", "verdi"]
      env: {}
      idle_timeout: -1

A web URL is a same-origin page path starting and ending with /, without a query. Redirection passes the same meta. Surfer asynchronously reads GET /api/waveform/metadata?meta=..., loads the exact waveform and restores signals, window and cursor, retaining FST fallback conversion and progress reporting. Configure another extension with its own page or launcher. Unconfigured formats return 415 with a corrective action; invalid configuration returns 503.

An Xpra GET only serves a launch page. The page posts {"wave_meta":"waves/a.fsdb.json"} to the existing POST /api/xpra/sessions. The server validates metadata, builds argv from operator configuration and reuses existing authentication, quotas, ownership and diagnostics. JSON cannot supply commands, scripts or environment variables. Identical metadata contents and viewer configuration reuse a live session; concurrent creation is coalesced and exited sessions can be recreated.

Relative script paths resolve only under the actual running package's ucagent/scripts, including subdirectories. Traversal and symlink escapes are rejected. Working-directory/PATH lookup is not used. Absolute scripts are checked explicitly. Python scripts use UCAgent's sys.executable. args is an argv list; {wave_meta} becomes the validated absolute JSON path at launch and arguments are safely quoted. env is operator configuration. idle_timeout is -1 or positive integer seconds. Pass additional Verdi arguments after "--" in the default launcher's argument list.

The default verdi/launch_verdi.py looks for *.daidir/simv.kdb beside the metadata's DUT Python entry, then beside associated source files. It does not search unrelated design directories. A unique database is loaded with -dbdir, preserving the elaborated VCS design; compile the DUT with -kdb. Without a database, the launcher imports supported Verilog/SystemVerilog sources. Scala remains associated reference material. Ambiguous databases require explicit selection: add "--dbdir", "Adder/libDPIAdder.so.daidir" to cmd_api.waveform_viewers.fsdb.args before any "--" separator. The path is relative to the selected workspace; absolute paths within that workspace are also accepted. The database and its symbolic links must remain inside the selected workspace.

The launcher opens FSDB, adds signals and docks the waveform in the same Verdi window, restoring native-tick positions. Tcl queries wvGetFileTimeUnit and sets wvSetWindowTimeUnit to one native tick before applying timestamps. Unknown time scales fail rather than assuming ns or using log cycles. Temporary Tcl lives until Verdi exits; failures and exit codes reach Xpra diagnostics.

The runtime needs Xpra/X11, Verdi and a valid license. Substitute tests cover argv, paths, Tcl literals, multiple native scales and errors. Actual signal display/time positioning requires integration acceptance in a licensed environment. All interfaces preserve subworkspace selection and both Master task/agent CMD proxy prefixes.

Surfer bus expansion and rebuilds

Multibit digital signals initially show a collapsed aggregate value. Click the triangle beside a signal to expand or collapse its individual bit traces. Labels follow the declared indices, including ascending, nonzero and negative ranges. The aggregate retains its selected number format and individual bits preserve X/Z states. Metadata-loaded and manually added buses share this behavior; scalar, clock, real, string and existing structured decoders keep their normal presentation.

The bundled Surfer is pinned to upstream commit 3ab79e7220f937cb3fadf1117f15d344e5f7e990. Its local native changes and EUPL-1.2 license are in ucagent/scripts/surfer/. bit_expansion.patch integrates bit_expansion.rs with native translators and initially closed compound rows; bit values come directly from waveform data.

Rebuilding requires Rust 1.90+, the wasm32-unknown-unknown target, patch and wasm-bindgen-cli 0.2.113. Clone the pinned upstream revision and initialize its submodules: instruction-decoder at 02bdcbfd5663a72e4a0b1b9d54519412d417fab1 and f128 at e60de395f0d6454c1dc546b87f06a6358425b6b6. Keep the upstream Cargo.lock unchanged, then run:

python ucagent/scripts/surfer/rebuild.py --source /absolute/path/to/surfer

The script validates the lockfile, patched source and binding CLI version, builds with locked dependencies, and updates matching JS/WASM assets and their index.html integrity digests. Use --wasm-bindgen for a specific CLI path or --output for an existing preview bundle directory. Stop the service using that directory before publishing rebuilt assets.

Browser regression uses the real CMD service and bundled WASM to cover VCD/FST, Variables, full names, window/cursor restoration and initially collapsed, independently expandable buses:

UCAGENT_RUN_SURFER_BROWSER_TESTS=1 python -m pytest -q tests/test_surfer_metadata_browser.py

Install Playwright Chromium/WebKit; UCAGENT_SURFER_CHROMIUM_EXECUTABLE can select a local Chrome. Native bit mapping tests are included in bit_expansion.rs. After copying it into patched upstream sources, run cargo test -p libsurfer --no-default-features translation::bit_expansion.

Graphical integration without Verdi

tests/fixtures/fake_verdi.py is a Tk application that executes the actual default launcher's Tcl, draws selected signals/window/cursor, and records remote button or R key input. It accepts only explicitly marked JSON waveform fixtures. The fixture has an .fsdb filename to exercise dispatch; it neither contains nor decodes proprietary FSDB. Xpra, Xvfb, CMD REST, the HTML5 client and WebSocket transport use their real implementations.

On Linux with project test dependencies, Xpra, Xpra HTML5 assets, Xvfb and Python Tk installed, run the following. Containers should use an init process, such as docker run --init, to reap exited application descendants:

UCAGENT_RUN_WAVE_XPRA_INTEGRATION=1 python -m pytest -q tests/test_waveform_xpra_runtime.py

The tests create temporary workspaces and private signing directories. They cover authentication, GET without launch, concurrent session reuse, quota, exit/reopen, process cleanup, metadata tampering and Tcl startup errors. Fixtures include Chinese/space/Tcl-special paths, RTL/Scala associations, a 10fs native scale and timestamps exceeding JavaScript's safe integer range.

For browser acceptance, start a fixture service in the same Linux runtime. Adjust the browser URL to the published port when using a container:

python tests/test_waveform_xpra_runtime.py --serve --host 0.0.0.0 --port 8765 --info /tmp/wave-xpra-info.json

Install Playwright and Chromium/WebKit where browser tests run, then set these variables. Transfer the service info file's password value securely; do not commit the file or credentials.

1
2
3
4
export UCAGENT_WAVE_XPRA_URL=http://127.0.0.1:8765
export UCAGENT_WAVE_XPRA_PASSWORD='<password from the private info file>'
export UCAGENT_WAVE_XPRA_ARTIFACTS=/tmp/wave-xpra-screenshots
python -m pytest -q tests/test_waveform_xpra_browser.py

UCAGENT_XPRA_CHROMIUM_EXECUTABLE can select an installed Chrome executable. Browser tests follow /wave/?meta=... into the application, check rendered pixels and exact restored state, send keyboard input, verify reload/reconnect and repeated-open session reuse, and save screenshots. Interrupting or terminating the fixture service cleans sessions and temporary files. These tests validate transport and launch protocol; actual Verdi FSDB decoding, command compatibility and time positioning still need acceptance in a licensed runtime.

USDB reads

The uvd backend reads .usdb files using usdbaccess and dap. Set UVD_HOME and UVS_HOME to their respective installation roots. Tools are located only in the bin directories under those roots, in that order. Missing or unusable tools produce an analysis error.

Type:Real variables are excluded from digital analysis. This backend has no advanced options. backend_args accepts {} for defaults or "help" for option help.

Opening a USDB waveform link in the web interface starts UVD through Xpra using cmd_api.waveform_viewers.usdb. The CMD server environment needs a working uvd, the UVS/UVD tools, and the Xpra prerequisites. The launcher restores the signals and native-tick time window from the metadata. To select a specific compiled design database, add --dbdir and a workspace-contained database directory to the viewer's args.

USDB is included in the default format priority. To prioritize it ahead of other formats:

1
2
3
4
runtime_options:
  waveform_analysis_format_priority: [usdb, fst, vcd, fsdb]
  waveform_analysis_backend_priority:
    usdb: [uvd]

Registering Other Formats

ucagent/applications/UnitTest/src/unit_test/waveform_formats/ is a Python package. Its public protocols and registry do not depend on a waveform parsing library. Each format implements its reader in a separate file; formats using the same library can share an adapter:

ucagent/applications/UnitTest/src/unit_test/waveform_formats/
├── __init__.py          # Public exports and built-in registration
├── protocols.py         # Reader, factory, scope, signal, and result contracts
├── registry.py          # Priority validation and extension dispatch
├── pagination.py        # Bounded, deterministic signal pages
├── queries.py           # Library-independent signal queries
├── adapter_pywellen.py  # Shared pywellen decoding and advanced options
├── adapter_wavekit.py   # Shared wavekit context and value-loading adapter
├── read_fst.py          # WellenFstReader / WavekitFstReader
├── read_vcd.py          # WellenVcdReader / WavekitVcdReader
├── read_fsdb.py         # WavekitFsdbReader
└── read_usdb.py         # UsdbReader

Import WaveformReader, WaveformReaderFactory, WaveformScope, WaveformSignal, WaveformSignalMatches, and WaveformValueChanges from the package entry point. These use structural typing: a function, callable object, or reader class can satisfy the signatures without inheriting from UCAgent or wavekit. WaveInfo consumes only this public protocol; wavekit's _load_value_changes is called only inside its dedicated adapter.

Factory and reader interface

The following signatures define the essential inputs and outputs. Full method documentation is in protocols.py:

from collections.abc import Iterable, Mapping, Sequence
from contextlib import AbstractContextManager
from typing import Any, Literal, NotRequired, Protocol, TypedDict

BackendArgs = dict[str, Any] | Literal["help"]

class WaveformScope(Protocol):
    @property
    def full_name(self) -> str: ...

class WaveformSignal(Protocol):
    @property
    def full_name(self) -> str: ...
    @property
    def base_name(self) -> str: ...
    @property
    def width(self) -> int: ...

class WaveformSignalMatches(TypedDict):
    signals: Mapping[Any, WaveformSignal]
    total: int
    offset: int
    limit: int
    extensions: NotRequired[dict[str, Any]]

class WaveformValueChanges(TypedDict):
    mapped: Iterable[tuple[int, int]]
    extensions: NotRequired[dict[str, Any]]

class WaveformReader(Protocol):
    @property
    def backend_name(self) -> str: ...
    def configure_backend(self, backend_args: BackendArgs) -> dict[str, Any]: ...
    @property
    def begin_time(self) -> int: ...
    @property
    def end_time(self) -> int: ...
    @property
    def top_scopes(self) -> Sequence[WaveformScope]: ...

    def get_matched_signals(
        self, path: str, *, offset: int = 0, limit: int = 100,
    ) -> WaveformSignalMatches: ...

    def load_value_changes(
        self,
        signal: WaveformSignal,
        value_mapping: Mapping[str, int],
        begin_time: int | None = None,
        end_time: int | None = None,
    ) -> WaveformValueChanges: ...

class WaveformReaderFactory(Protocol):
    def __call__(self, path: str, /) -> AbstractContextManager[WaveformReader]: ...
Interface Input and output contract
factory(path) Takes a file path string, absolute or relative to the caller's current directory, and returns a context manager yielding a WaveformReader. Open exactly that file without substituting a format or searching for another file.
backend_name / configure_backend(backend_args) Return the backend name for operator logs; process options once before queries. Accept {} for defaults and "help" for usage without traces. Reject invalid options with WaveformBackendArgumentError.
begin_time / end_time Return the first and last inclusive timestamps. All times are nonnegative integer native simulation ticks, with full precision; do not convert them to DUT cycles or other time units.
top_scopes Return the real top-level scopes, each exposing its full dotted full_name; return an empty sequence if there are none.
get_matched_signals(path) Support exact dotted paths, *, recursive **, /{regex}/, and brace alternatives/ranges. Accept path and keyword-only offset=0, limit=100. Return signals, the actual match count total, echoed offset / limit, and optional extensions. Sort by full path and return [offset, offset + limit), preserving backend mapping keys. Empty or out-of-range pages have an empty signal map; invalid queries raise without loading traces.
WaveformSignal full_name is the exact full path, including declared bit indices; base_name is the unqualified name; width is a positive integer bit width. Descriptors can carry native handles but must be passed back only to their originating reader and remain valid only within its context.
load_value_changes(...) Takes a signal resolved by this reader, a four-state mapping, and optional window bounds. Returns a dictionary containing mapped and optional extensions, as specified below.
Context exit Release files, native handles, and other resources after both successful and failed analysis. Clean up partially allocated resources if opening fails. Propagate dependency, file, and query errors for operator diagnostics.

value_mapping contains all four lowercase 0, 1, x, and z keys with integer bit values, such as {"0": 0, "1": 1, "x": 0, "z": 0}. Map each source bit and assemble the unsigned integer in declared bit order. mapped is an iterable of ascending (timestamp, mapped_integer) pairs. Retain source transitions even when their mapped values are equal: WaveInfo reads value, X mask, and Z mask separately and aligns their timestamps. An empty signal trace returns an empty iterable.

begin_time=None and end_time=None leave the respective bound unlimited. For a bounded start, retain the latest state at or before begin_time with its original timestamp. The end is exclusive: return only transitions strictly before end_time. This preserves the preceding state when a change occurs at the start of an explicit analysis window. Repeated loads must not modify metadata or interfere with subsequent loads of the same signal.

Paging and summaries for large signal sets

get_matched_signals(path, *, offset=0, limit=100) returns at most 100 signals by default, covering the sorted range [0, 100). offset must be a nonnegative integer and limit an integer from 1 to 1000. total counts all query matches, not the page size. Return exactly min(limit, max(total - offset, 0)) descriptors. Empty queries and out-of-range offsets return an empty signals mapping with the actual total and requested bounds. Sort consistently by full_name within the same file; do not repeat or skip signals or invalidate descriptors from other pages.

Libraries without native paging can use the public paginate_signal_matches(mapping, offset=..., limit=...) helper, preserving keys and descriptor objects. The built-in wavekit adapter uses this helper: it still obtains the underlying library's full match mapping, but returns only the selected page to WaveInfo and the LLM. A library with native paging can implement the same contract directly without building all descriptors. Generate query extensions for the current page instead of placing all omitted hierarchy/relationship details inside extensions.

Local and MCP WaveInfo calls expose three catalog arguments, used when pattern is omitted:

Argument Default Purpose
signal_query "**" Catalog query using exact paths or reader query syntax, such as TOP.dut.**.
signal_offset 0 Starting index in the sorted signal catalog.
signal_limit 100 Maximum signals per page, from 1 to 1000.

For example, request the second page:

1
2
3
4
5
6
result = tool.analyze(
    test_case_name="tests/test_demo.py::test_add",
    signal_query="TOP.dut.**",
    signal_offset=100,
    signal_limit=100,
)

With 250 matches, the catalog summary is as follows. The actual signals field contains the 100 full paths and widths on this page:

signal_catalog:
  query: TOP.dut.**
  total: 250
  offset: 100
  limit: 100
  shown: 100
  end_offset: 200
  remaining: 50
  has_more: true
  next_offset: 200
  truncated: true
  next_call:
    test_case_name: tests/test_demo.py::test_add
    signal_query: TOP.dut.**
    signal_offset: 200
    signal_limit: 100
    include_extensions: false
    backend_args: {}

Pass signal_catalog.next_call directly to WaveInfo; it retains the exact TC, query, page size, extension option and backend_args. Pages are [0, 100), [100, 200), then [200, 250); the final page has no next_call. An out-of-range offset returns an empty page and a recovery call starting at 0. No matches prompt a broader signal_query. waveform_info.signal_count always counts the entire waveform.

signal_query_summary provides the same counts for catalog, clock, event, and context queries. When more matches remain, it supplies a catalog-mode next_call. Clock hints and similar-signal suggestions use only the current bounded catalog page; absence from that page does not prove a signal is missing. Top-level scope names are limited to 100, with top_scope_count, top_scopes_remaining, and top_scopes_truncated describing omitted scopes.

Catalog paging is independent of the event-analysis bound max_signals. Each event query loads at most max_signals + 1 descriptors to detect overflow and uses the actual total to validate the complete match set. The union across patterns, context signals, and clocks must still satisfy max_signals. Overflow returns the true count, a bounded preview, and catalog_call; it cannot report successful analysis of only the first page. Browse and narrow pattern before analyzing events. Nondefault catalog arguments combined with a nonempty pattern fail explicitly. Nondefault catalog arguments also require test_case_name.

Input and output examples for both methods

These examples also appear in the Protocol method docstrings on WaveformReader. First query one signal:

matches = reader.get_matched_signals("TOP.dut.data[7:0]", offset=0, limit=100)

In the representative output, data_signal is a descriptor produced by this reader. The mapping key data illustrates a backend identity. Related signal paths in extensions do not automatically become matches or event triggers:

from types import SimpleNamespace

data_signal = SimpleNamespace(
    full_name="TOP.dut.data[7:0]", base_name="data", width=8,
)
result = {
    "signals": {"data": data_signal},
    "total": 1,
    "offset": 0,
    "limit": 100,
    "extensions": {
        "hierarchy": {"TOP.dut.data[7:0]": {"parent_scope": "TOP.dut"}},
        "related_signals": {"TOP.dut.data[7:0]": ["TOP.dut.valid", "TOP.dut.ready"]},
    },
}

Use the descriptor inside signals to load changes. Assume source states are 0: 8'b00000000, 10: 8'b00000011, 20: 8'b0000xz01, and 30: 8'b11111111:

1
2
3
4
5
6
7
signal = matches["signals"]["data"]
changes = reader.load_value_changes(
    signal,
    {"0": 0, "1": 1, "x": 0, "z": 0},
    begin_time=15,
    end_time=30,
)

The output retains the state at 10 before the requested start of 15 and excludes the end at 30:

1
2
3
4
5
6
7
result = {
    "mapped": [(10, 3), (20, 1)],
    "extensions": {
        "raw_values": [[10, "00000011"], [20, "0000xz01"]],
        "quality": {"source": "native", "gaps": []},
    },
}

With X-mask mapping, the same input produces mapped rows [(10, 0), (20, 8)]; Z-mask mapping produces [(10, 0), (20, 4)]. Without extensions, the methods return {"signals": page, "total": total, "offset": offset, "limit": limit} and {"mapped": rows} respectively; an empty extensions field is not required.

Adapting another library and registering it

The following example belongs in a plugin's read_wlf.py. my_wlf_library is illustrative: assume its metadata and queries satisfy the contract above, read_mapped implements four-state mapping, source-transition retention, and window semantics, query_metadata(path, page_signals) returns JSON-serializable hierarchy/relationship information for only the current page, and signal_quality returns JSON-serializable quality information. Adapt actual library objects and semantics inside the format module. If a library supports only some query forms, implement the remaining forms in the adapter. The backend constructor must clean up partially opened resources when opening fails.

# my_plugin/readers/read_wlf.py

from contextlib import AbstractContextManager
from unit_test.waveform_formats import (
    WaveformSignalMatches, WaveformValueChanges, WaveformBackendArgumentError,
    paginate_signal_matches,
)

class ExampleWlfReader(AbstractContextManager):
    """Adapt the chosen WLF library to the UCAgent reader contract."""

    backend_name = "example"

    def configure_backend(self, backend_args):
        """Accept defaults and describe the supported advanced options."""
        if backend_args == "help":
            return {"options": {}, "examples": [{"backend_args": {}}]}
        if backend_args != {}:
            raise WaveformBackendArgumentError('Use backend_args="help".')
        return {}

    def __init__(self, path: str):
        self.path = path
        self.backend = None

    def __enter__(self):
        from my_wlf_library import Reader

        self.backend = Reader(self.path)
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.backend.close()
        return False

    @property
    def begin_time(self):
        return self.backend.begin_time

    @property
    def end_time(self):
        return self.backend.end_time

    @property
    def top_scopes(self):
        return self.backend.top_scopes

    def get_matched_signals(self, path, *, offset=0, limit=100) -> WaveformSignalMatches:
        page = paginate_signal_matches(
            self.backend.find_signals(path), offset=offset, limit=limit,
        )
        page["extensions"] = self.backend.query_metadata(path, page["signals"])
        return page

    def load_value_changes(
        self, signal, value_mapping, begin_time=None, end_time=None,
    ) -> WaveformValueChanges:
        return {
            "mapped": self.backend.read_mapped(
                signal, value_mapping, begin_time=begin_time, end_time=end_time,
            ),
            "extensions": {"quality": self.backend.signal_quality(signal)},
        }

# Plugin initialization

from unit_test.waveform import WaveInfo
from unit_test.waveform_formats import register_waveform_reader
from my_plugin.readers.read_wlf import ExampleWlfReader

register_waveform_reader("wlf", ExampleWlfReader, backend="example")
tool = WaveInfo(
    workspace="/path/to/workspace",
    test_dir="unit_test/tests",
    format_priority=["fst", "vcd", "fsdb", "wlf"],
    backend_priority={"wlf": ["example"]},
)
result = tool.analyze(test_case_name="test_add")

register_waveform_reader(format_name, factory, *, backend="default") accepts lowercase extension and backend names without a dot. Registration does not open files or import parsing dependencies. Register during application/plugin initialization before constructing WaveInfo. One format can have multiple backend names; duplicate (format_name, backend) entries cannot replace existing implementations. Single-backend plugins can use "default"; other configured names must be registered. Configure both priorities for a full workflow:

1
2
3
4
runtime_options:
  waveform_analysis_format_priority: [fst, vcd, fsdb, usdb, wlf]
  waveform_analysis_backend_priority:
    wlf: [example]

Load optional dependencies only when the factory is called or its context is entered. Default FST/VCD implementations share adapter_pywellen.py; their wavekit alternatives and FSDB share adapter_wavekit.py. Without advanced options, query/load methods return only standard fields. New formats share discovery, analysis, receipt, and replay workflows; registering an analysis reader does not add browser decoding capabilities.

Advanced options and help

Local and MCP backend_args: dict | Literal["help"] defaults to {}. Objects can contain nested JSON data; non-string top-level keys, native objects and NaN/Infinity are rejected. Options apply only to the current reader. They do not select libraries, invoke arbitrary methods/code or change standard evidence semantics. Nonempty options and "help" require test_case_name; omit event pattern for help.

help_result = tool.analyze(
    test_case_name="tests/test_demo.py::test_add",
    backend_args="help",
)
catalog = tool.analyze(
    test_case_name="tests/test_demo.py::test_add",
    signal_query="TOP.dut.**",
    signal_limit=100,
    backend_args={"signal_metadata": True},
    include_extensions=True,
)
analysis = tool.analyze(
    test_case_name="tests/test_demo.py::test_add",
    pattern=[{"signal": "TOP.dut.data[7:0]", "event": "unknown"}],
    start_step=10,
    end_step=30,
    backend_args={"statistics": True},
    include_extensions=True,
)

After entering the selected reader, the tool calls configure_backend() before catalog queries or event analysis. It passes a deep copy; a backend must not affect other calls. "help" returns only status: advanced_help, file selection and usage under extensions.backend. Explicit help is shown even with include_extensions=False and cannot become event evidence. Example pywellen help:

extensions:
  backend:
    options:
      signal_metadata:
        type: boolean
        default: false
        description: Return declaration metadata for the current page.
      statistics:
        type: boolean
        default: false
        description: Return source-state counts for each loaded signal and window.
    examples:
      - backend_args:
          signal_metadata: true
        include_extensions: true
      - backend_args:
          statistics: true
        include_extensions: true

Current pywellen signal_metadata returns parent scope, declaration type, direction, declared/selected indices, enum and VHDL type under extensions.signal_queries[query].signal_metadata for the selected page. When present, enum_type is the array [type_name, [[bit_value, label], ...]]; otherwise it is null. statistics returns source_states, unknown_states, first/last timestamps and load bounds under extensions.value_changes[signal][channel].statistics. Counts include the prior state needed to reconstruct the window start and are not event counts. Both options accept only booleans and default to false. Wavekit currently reports empty help options, accepting only {} and "help".

Ordinary advanced output follows the default-hidden policy: extensions_available announces fields; include_extensions=True reveals contents. Call-scoped configure_backend() results go under extensions.backend; other results retain their query-page/signal/mapping/window scope. Extensions cannot bypass pagination. Unsupported options return invalid_backend_args with a directly callable details.help_call, without switching readers. Pagination, overflow catalog calls, recommended evidence calls, receipts, recovery and replay preserve backend_args. Explicit extension contents participate in semantic comparison.

Plugins must implement backend_name and configure_backend(). A reader without advanced features accepts {} and returns {}, accepts "help" and returns {"options": {}}, and rejects other nonempty dictionaries. A reader with advanced features documents types, defaults, result locations, bounds and usable examples in help; validates and stores options on the current reader; then generates query/load extensions. Never return native handles, secrets or unbounded data.

Extensions and optional output

get_matched_signals requires signals, total, offset, and limit in its result dictionary; load_value_changes requires mapped. Both can omit extensions or return an empty dictionary. Nonempty extensions contain backend-defined fields with string keys at every level and only JSON objects, arrays, scalars, or null as values. Do not include Python tuples, native descriptors, handles, NaN/Infinity, or sensitive information. Query extensions belong to the current query page and can describe its hierarchy/relationships or bounded query-wide facts. Do not bypass pagination by including details for every omitted signal in extensions. Value-change extensions describe the signal, mapping, and read window. Bound their size to their respective scope: max_points limits only the standard timeline and does not truncate extension dictionaries. Malformed output fails the current query or analysis and produces operator diagnostics.

Local analyze() and local/MCP tool calls support include_extensions: bool = False. The default hides extension contents. Nonempty extensions add field names in extensions_available and an extensions_hint so the LLM can decide whether to inspect them. Outputs use the following scope groups, omitting empty groups:

  • backend: call-scoped results or explicit help from configure_backend().
  • signal_queries: extensions from the latest page keyed by the exact query string, including **; page bounds are in signal_query_summary.
  • value_changes: value-change extensions keyed by full signal path and value / x_mask / z_mask channel.

For example, the relevant default output is:

1
2
3
4
5
6
7
extensions_available:
  signal_queries:
    TOP.dut.result: [hierarchy, related_signals]
  value_changes:
    TOP.dut.result:
      value: [quality]
extensions_hint: "Additional signal information is available in the listed fields. If it would help your analysis, repeat this WaveInfo call with the same arguments and include_extensions=true to view its contents."

To inspect the contents, repeat the same TC, signals, window, and other query arguments with include_extensions=true. The result adds extensions under the same groups, retains extensions_available, and omits the viewing hint:

extensions:
  signal_queries:
    TOP.dut.result:
      hierarchy:
        TOP.dut.result:
          parent_scope: TOP.dut
      related_signals:
        TOP.dut.result: [TOP.dut.valid, TOP.dut.ready]
  value_changes:
    TOP.dut.result:
      value:
        quality:
          source: native
          gaps: []

Query extensions come only from queries actually executed and do not require loading signal values, so signal-catalog and other metadata calls can return them. Value-change extensions come only from signals actually loaded, including alignment clocks and context signals. File inventory does not open a reader and has no extensions. An unmatched query can retain related-candidate information without treating candidates as matched signals. If there are no extensions, all three extension-related fields are absent regardless of the option. The option does not change standard events, timeline, or window.

Explicitly returned contents from all groups are stored with the tool call's signed receipt and participate in semantic replay comparison; default calls store only available field names. The central waveform record format in dynamic Bug documents retains its existing contract.

When adding a backend, test registration and analysis without wavekit, query hierarchy/relationships, unmatched queries and metadata without traces, four-state mapping, window boundaries, empty traces, large integers, omitted/optional extension output, and cleanup after exceptions. Relevant regressions:

1
2
3
python -m pytest -q ucagent/applications/UnitTest/tests/test_waveform_backends.py \
  ucagent/applications/UnitTest/tests/test_waveform_formats.py \
  ucagent/applications/UnitTest/tests/test_waveform_tool.py tests/test_waveform_routes.py tests/test_launch_uvd.py