Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,17 @@ workflow. Hardware example tests
use Icarus Verilog (`iverilog` and `vvp`); the iCE40 implementation tests also
use Yosys, nextpnr-ice40 and IceStorm (`icepack`). CI installs these tools so
documented RTL and native implementation are executed, not only linted.
The opt-in digital CDC/reset tests use native Yosys extraction and Icarus traces,
including bad stage counts, intermediate fanout, wrong clocks, asynchronous
release and raw-reset paths that digital simulation alone may miss. Keep the
legacy full verification workflow unchanged; CDC-only work has an explicit
profile and original specification. Preserve failing design evidence and valid
negative diagnoses, test fresh native replay and Store-only profile checking,
and do not claim metastability/MTBF or complete CDC/RDC sign-off.
CDC follow-up tests must show that swapped independently declared data inputs
produce trace mismatches, not just structural failures, and that detailed native
findings survive recomputation. Check live output-budget enforcement, terminated
command exits and owned process cleanup; never weaken a threshold to pass.
Analog references additionally require `ngspice`, also installed in CI. They
execute native operating-point, DC, AC and transient analyses and compare
waveform measurements against independent circuit equations. Keep parser-only
Expand Down
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,12 @@ The existing `chip_design` architecture model remains accelerator-oriented in
this batch; a general control-SoC model and independent physical/DFT execution
are still separate work, not capabilities implied by the taxonomy.

The digital verification specialty also offers an opt-in CDC/reset profile:
native Yosys structural checks and Icarus clock/phase traces for explicitly
declared single-bit level/reset adapters. It preserves valid negative diagnosis
and requires a passing result when composed into FPGA design verification.
It is not complete CDC/RDC sign-off or a multiclock FPGA implementation backend.

| entry point | module | purpose (as shown in the Manager's menu) | skill parents |
|---|---|---|---|
| `ale_last_exam` | `argus_verticals.ale_last_exam` | Agents' Last Exam long-horizon professional workflow in a real sandbox with hidden-reference, artifact-first GUI+CLI delivery | |
Expand All @@ -114,7 +120,7 @@ are still separate work, not capabilities implied by the taxonomy.
| `classical_poetry` | `argus_verticals.classical_poetry` | compose or check classical Chinese 近体诗/古体/词 with reproducible 押韵/平仄 prosody and literary review | |
| `digital_circuit` | `argus_verticals.digital_circuit` | Verilog/SystemVerilog RTL, testbenches, formal verification, FPGA/ASIC synthesis, timing, and sign-off | |
| `digital_circuit_benchmark` | `argus_verticals.digital_circuit.benchmark` | single-stage fixed-harness RTL benchmark: interface, RTL, local verification, pre-score elaboration, and attempt handoff | `digital_circuit` |
| `digital_circuit_verification` | `argus_verticals.digital_circuit.verification` | independent configuration/scenario regression and nonvacuous formal checks | `digital_circuit` |
| `digital_circuit_verification` | `argus_verticals.digital_circuit.verification` | independent regressions, declared CDC/reset adapter checks and nonvacuous formal checks | `digital_circuit` |
| `fpga_design` | `argus_verticals.fpga_design` | scoped FPGA work with single-clock iCE40 implementation and measured board acceptance | `digital_circuit`, `digital_circuit_verification` |
| `fiction_writing` | `argus_verticals.fiction_writing` | write or continue original fiction narrative prose while preserving characters, world, and timeline; not a literature review or research task | |
| `kernelbench` | `argus_verticals.kernelbench` | maximize correctness-checked SOL score/speedup for GPU kernels on B200 SOL-ExecBench/KernelBench | `kernel_engineering` (Argus built-in) |
Expand Down
34 changes: 32 additions & 2 deletions argus_verticals/digital_circuit/verification/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,39 @@ an explicit upgrade message.
| `plan` | plan | Requirement/case/configuration matrix for existing sources |
| `simulation` | simulation | Executed matrix with nonzero independent comparisons |
| `formal` | formal | Declared bounded/inductive checks plus reached cover traces |
| `cdc` | simulation | Native declared single-bit level/reset structures and finite clock/phase traces |
| `full` | plan, simulation, formal, review | Both methods and a review of their limits |

Custom combinations use the existing Argus scope mechanism. Simulation and
formal goals require a valid plan manifest. Reuse an applicable existing plan;
when absent, prepare the manifest from the supplied requirements within the
selected execution stage, without adding a standalone plan stage. Review requires
both methods; choose a narrower scope rather than inventing N/A formal results.
This specialty does not establish CDC structural safety, STA closure, DFT
coverage, analog behavior, or certification.
The optional `cdc` profile instead uses `verification/CDC_PLAN.json` and a
separate original specification; it does not require general matrix/formal
records. It checks a bounded, completely declared synchronizer adapter, not all
crossings in an arbitrary design. The legacy `full` profile stays unchanged.
No profile establishes complete CDC/RDC sign-off, STA closure, DFT coverage,
analog behavior, metastability/MTBF qualification or certification.

With native Yosys and Icarus Verilog installed, the separate CDC/reset reference
is runnable in a new directory:

```bash
python -m argus_verticals.digital_circuit.verification.run_cdc_reference /tmp/new-cdc-study
```

It checks source-faster, destination-faster and coincident-edge schedules, native
stage counts and fanout, asynchronous reset assertion and domain-local release.
Multiple data paths also receive independently held high/low patterns so swapped
inputs cannot hide behind identical stimuli. Structural findings name the native
cell/bit and expected versus observed clock/reset connection, and keep inspecting
remaining direct stages after a defect. Native time/output limits are monitored
during execution; terminated commands retain their actual exits and reasons.
The canonical contract below defines the two/three-stage adapter boundary,
diagnosis versus design goals, independent raw traces and native replay. Use
`"cdc": true` in an existing general/FPGA verification plan only when explicitly
composing this additional work; composition requires a passing CDC result.

## Runnable reference

Expand Down Expand Up @@ -68,3 +92,9 @@ they cannot establish that an arbitrary testbench is independent, that manually
supplied logs are authentic, or that assumptions describe the intended system.
Argus's independent review remains required. The bundled runnable example is
simulation-based; it is not evidence that a formal toolchain was installed.
# Review-boundary compatibility

Only an explicit `cdc: true` in the general verification plan composes CDC into
simulation, formal checks and final review. An unused `CDC_PLAN.json` does not
opt a legacy workflow in. Invalid native JSON shapes and unreadable trace text
are reported as evidence errors, not unhandled validation exceptions.
227 changes: 227 additions & 0 deletions argus_verticals/digital_circuit/verification/cdc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
"""Execute and replay original-input-bound CDC/reset adapter studies."""
from __future__ import annotations

import argparse
import json
import os
import shutil
import signal
import subprocess
import tempfile
import time
from pathlib import Path

from argus_verticals.hardware.shared.evidence import (
EvidenceError,
command_result,
current_files,
project_file,
record,
)

from . import cdc_simulation
from .cdc_model import ASSESSMENT, DIRECTORY, LIMITS, RESULTS, resolve, structure

OUTPUT_BUDGET = 128 * 1024 * 1024
COMMAND_TIMEOUT = 30
EXECUTION_TIMEOUT = 180


def _write(path: Path, payload: dict) -> None:
path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")


def _commands(spec: dict) -> list[tuple[str, list[str]]]:
script = "read_verilog -sv -noautowire " + " ".join(spec["sources"])
script += f"; hierarchy -check -top {spec['top']}; proc; flatten; opt_clean; check -assert; write_json {DIRECTORY}/netlist.json"
commands = [("yosys", ["yosys", "-Q", "-T", "-p", script])]
for name in spec["configurations"]:
commands += [
(f"{name}.compile", ["iverilog", "-g2012", "-s", "cdc_tb", "-o", f"{DIRECTORY}/{name}.vvp",
*spec["sources"], f"{DIRECTORY}/{name}.sv"]),
(f"{name}.simulate", ["vvp", f"{DIRECTORY}/{name}.vvp"]),
]
return commands


def _execute(root: Path, spec: dict, result: dict) -> None:
deadline = time.monotonic() + EXECUTION_TIMEOUT

def limit(command_deadline: float) -> str:
if time.monotonic() >= command_deadline:
return "CDC native command or study exceeded its allowed seconds"
if sum(p.stat().st_size for p in (root / DIRECTORY).iterdir() if p.is_file()) > OUTPUT_BUDGET:
return f"CDC generated output exceeded {OUTPUT_BUDGET} bytes"
return ""

for name, configuration in spec["configurations"].items():
frames = cdc_simulation.stimulus(spec, configuration)
(root / DIRECTORY / f"{name}.sv").write_text(cdc_simulation.testbench(spec, frames), encoding="utf-8")
if stopped := limit(deadline):
raise EvidenceError(stopped)
for name, command in _commands(spec):
log = f"{DIRECTORY}/{name}.log"
row = {"step": name, "command": command, "exit_code": None, "log": log}
result["commands"].append(row)
_write(root / RESULTS, result)
command_deadline = min(deadline, time.monotonic() + COMMAND_TIMEOUT)
if stopped := limit(command_deadline):
row["stop_reason"] = stopped
_write(root / RESULTS, result)
raise EvidenceError(stopped)
with (root / log).open("w", encoding="utf-8") as stream:
stream.write("$ " + json.dumps(command) + "\n")
stream.flush()
try:
with subprocess.Popen(
command, cwd=root, stdout=stream, stderr=subprocess.STDOUT,
start_new_session=os.name == "posix",
) as process:
while process.poll() is None:
if stopped := limit(command_deadline):
if os.name == "posix":
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
process.wait()
else:
process.kill()
break
time.sleep(0.05)
row["exit_code"] = process.wait()
except OSError as exc:
raise EvidenceError(f"{name}: native command could not finish: {exc}") from exc
stopped = stopped or limit(command_deadline)
if stopped:
row["stop_reason"] = stopped
_write(root / RESULTS, result)
if stopped or row["exit_code"] != 0:
reason = stopped or f"native command exited {row['exit_code']}"
raise EvidenceError(f"{name}: {reason}; retained {log}")


def _assessment(root: Path, spec: dict) -> dict:
structural = structure(spec, record(root, f"{DIRECTORY}/netlist.json"))
simulations = {}
for name, configuration in spec["configurations"].items():
path = project_file(root, f"{DIRECTORY}/{name}.simulate.log")
try:
trace = path.read_text(encoding="utf-8")
except (OSError, UnicodeError) as exc:
raise EvidenceError(f"{name}: cannot read CDC trace: {exc}") from exc
simulations[name] = cdc_simulation.measure(spec, configuration, trace)
passed = structural["passed"] and all(row["passed"] for row in simulations.values())
return {
"goal": spec["goal"], "status": "passed" if passed else "failed",
"conclusion_valid": True, "task_accepted": passed or spec["goal"] == "diagnose",
"scope": LIMITS, "structure": structural, "simulations": simulations,
}


def run(root: Path) -> dict:
root = root.resolve()
spec, inputs = resolve(root)
for tool in ("yosys", "iverilog", "vvp"):
if shutil.which(tool) is None:
raise EvidenceError(f"{tool} is required for actual CDC/reset execution")
destination = root / DIRECTORY
destination.mkdir(parents=True, exist_ok=False)
copies = {}
for relative in inputs:
snapshot = f"{DIRECTORY}/inputs/{relative}"
target = root / snapshot
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(project_file(root, relative), target)
copies[relative] = snapshot
result = {"operation": "yosys-icarus-cdc-reset", "status": "running", "inputs": copies, "commands": [], "outputs": {}}
_write(root / RESULTS, result)
try:
if resolve(root)[0] != spec:
raise EvidenceError("CDC original specification changed during input capture")
current_files(root, result, inputs)
_execute(root, spec, result)
assessment = _assessment(root, spec)
_write(root / ASSESSMENT, assessment)
for path in sorted(destination.iterdir()):
if path.is_file() and path.name != "RESULTS.json":
relative = path.relative_to(root).as_posix()
copy = f"{DIRECTORY}/retained/{path.name}"
(root / copy).parent.mkdir(exist_ok=True)
shutil.copyfile(path, root / copy)
result["outputs"][relative] = copy
current_files(root, result, inputs)
result["status"] = "complete"
_write(root / RESULTS, result)
if not assessment["task_accepted"]:
raise EvidenceError("CDC design violates the original structural or finite-trace requirements; diagnosis retained")
return assessment
except EvidenceError as exc:
result["status"] = "failed"
result["error"] = str(exc)
_write(root / RESULTS, result)
raise


def validate(root: Path, *, require_pass: bool = False) -> dict:
root = root.resolve()
spec, inputs = resolve(root)
result = record(root, RESULTS)
if result.get("operation") != "yosys-icarus-cdc-reset" or result.get("status") != "complete":
raise EvidenceError("CDC needs a complete native execution record")
if result.get("inputs") != {p: f"{DIRECTORY}/inputs/{p}" for p in inputs}:
raise EvidenceError("CDC input copies must match the entire original specification/source list")
current_files(root, result, inputs)
paths = [ASSESSMENT, f"{DIRECTORY}/netlist.json"]
for name in spec["configurations"]:
paths += [f"{DIRECTORY}/{name}.{extension}" for extension in ("sv", "vvp")]
commands = result.get("commands")
expected_commands = _commands(spec)
if not isinstance(commands, list) or len(commands) != len(expected_commands):
raise EvidenceError("CDC commands must cover native extraction and every original configuration")
for row, (step, command) in zip(commands, expected_commands):
log = f"{DIRECTORY}/{step}.log"
if not isinstance(row, dict) or row.get("step") != step or row.get("command") != command or row.get("log") != log:
raise EvidenceError("CDC command, configuration or log differs from the declared native flow")
command_result(root, row)
paths.append(log)
outputs = {p: f"{DIRECTORY}/retained/{Path(p).name}" for p in paths}
if result.get("outputs") != outputs:
raise EvidenceError("CDC must retain every generated model, executable, trace, testbench and assessment")
current_files(root, result, paths, field="outputs")
measured = _assessment(root, spec)
if record(root, ASSESSMENT) != measured or not measured["task_accepted"]:
raise EvidenceError("CDC saved assessment differs from raw structural/trace evidence or is not accepted")
if require_pass and measured["status"] != "passed":
raise EvidenceError("CDC diagnosis may finish with findings, but a composed design verification must pass")
with tempfile.TemporaryDirectory(prefix="argus-cdc-check-") as directory:
temporary = Path(directory)
for relative in inputs:
target = temporary / relative
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(project_file(root, relative), target)
fresh = run(temporary)
if fresh != measured or record(temporary, f"{DIRECTORY}/netlist.json") != record(root, f"{DIRECTORY}/netlist.json"):
raise EvidenceError("CDC saved native model or measurements disagree with a fresh native replay")
for name in spec["configurations"]:
for suffix in ("sv", "simulate.log"):
relative = f"{DIRECTORY}/{name}.{suffix}"
if (temporary / relative).read_bytes() != project_file(root, relative).read_bytes():
raise EvidenceError("CDC saved stimulus or raw trace differs from fresh execution")
current_files(root, result, inputs)
current_files(root, result, paths, field="outputs")
return measured


def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("project", type=Path)
args = parser.parse_args()
try:
assessment = run(args.project)
except (EvidenceError, FileExistsError) as exc:
parser.exit(1, f"CDC execution failed: {exc}\n")
print(f"CDC task accepted: goal={assessment['goal']}, engineering_status={assessment['status']}. {LIMITS}")


if __name__ == "__main__":
main()
Loading
Loading