{
  "markdown": "<!-- mcp-name: io.github.MohibShaikh/hwcontract -->\n\n# hwcontract\n\nYour firmware is correct on paper and wrong on the wire.\n\nCoding agents write WS2812 drivers, ESC bitstreams, and boot logs that pass\nreview and then fail the moment the signal hits a real chip. hwcontract closes\nthat loop. It captures what the hardware *actually* did and returns a verdict you\ncan act on:\n\n- **pass**: within spec\n- **marginal**: in spec but too close to a rail. Works on your bench, dies on a\n  cold board in the field. It fails the verdict: the judge will not ship it.\n- **fail**: out of spec, with the measured value and how far off it is\n\nTwo things a green verdict gives you beyond the table:\n\n- **Every pulse is judged, not just the median.** Captures carry the full\n  pulse distribution; a glitchy tail that a median hides comes back as\n  marginal or fail, with the violating-pulse count in the hint.\n- **Evidence on every verdict:** contract hash, capture hash, capture\n  parameters, tool version, timestamp. A green build in CI traces back to the\n  exact bytes that produced it.\n\nNo hardware in your hand? The demo below runs the whole thing on a real recorded\nsignal, so you can see exactly what you get before wiring anything up.\n\n![hwcontract judging a real WS2812B capture, a DMA-broken SPI trace, and a serial boot log](https://raw.githubusercontent.com/MohibShaikh/hwcontract/main/demo/hwcontract.gif)\n\n## See it work in 30 seconds\n\n```bash\npip install hwcontract\npython3 -m hwcontract.judge --demo\n```\n\nThat judges a real 24-LED NeoPixel capture against two contracts. Same signal,\ntwo verdicts:\n\n```\nmeasured on the real WS2812B signal (300000 samples @24MHz):\n  T0H 333 ns   T1H 833 ns   T1L 417 ns   T0L 917 ns   RESET 992250 ns\n\n=== generic WS2812 contract -> FAIL ===\n  T0H     350   333  PASS\n  T0L     800   917  MARGINAL  only 33ns from max; nudge toward typ 800\n  T1H     700   833  MARGINAL  only 17ns from max; nudge toward typ 700\n  T1L     600   417  FAIL      183ns short (typ 600)\n  RESET 50000    -  PASS\n\n=== matching WS2812B contract -> PASS ===\n  (all five edges PASS)\n```\n\nSame hardware, two contracts: the generic one fails, the chip-specific one\npasses. A WS2812B isn't a WS2812. Measure the real signal, hold it to a spec, and\nmatch the contract to the actual chip.\n\n## See the temporal engine catch a DMA bug\n\n```bash\npython3 demo/spi_dma_temporal.py\n```\n\n100 synthesized SPI frames as raw CS/SCK/MOSI waveforms at 100MHz, reduced to\npin edges and judged against the bundled `spi-frame` contract. Frame 77 has\nthe Zephyr LPSPI DMA fault: chip-select asserts after the clock starts. Frame\n42 settles MOSI 10ns before the sampling edge. Both come back with exact\ntimestamps, and the same broken edges are re-imported as sigrok-style B/E\njsontrace annotations:\n\n```\ncs-precedes-first-clock  800  1  FAIL  trigger at 1540310ns: no gpio.cs.falling\n                                          in [1530310ns, 1540310ns] (first of 1)\nmosi-setup               800  1  FAIL  forbidden spi.mosi.* at 843300ns is 10ns\n                                          before spi.sck.rising at 843310ns\n```\n\nThe data is perfect in all 100 frames; a loopback test passes. The ordering is\nbroken in two, and only a cross-signal assertion notices.\n\n## What you get\n\n- **28 bundled contracts** for the parts people actually use: WS2812/WS2813/\n  SK6812 NeoPixels, DShot ESCs (150/300/600/1200), servos, I2C, NEC IR remotes,\n  DS18B20, DHT11/DHT22, HC-SR04, A4988/DRV8825 stepper drivers, PWM fans, plus\n  serial boot logs for ESP32, ESP8266, Zephyr, MicroPython, Raspberry Pi, U-Boot,\n  and STM32 bootloaders. Each one has the datasheet's real min/typ/max numbers.\n- **Temporal assertions between decoded events.** SVA-style cross-signal checks\n  (ordering, setup windows, forbidden states) on sigrok jsontrace output, judged\n  for every occurrence with latency percentiles and first-failure timestamps.\n- **Add a protocol by dropping in one YAML file.** No code change.\n- **An MCP server** your agent can call, or plain CLI commands you can run by hand.\n- **Evidence on every verdict:** contract hash, capture hash, capture parameters,\n  tool version, timestamp. A green build traces back to the exact bytes.\n- **Reasonable by default:** timing edges are all measured in nanoseconds, serial\n  contracts are Python regex, verdicts come back with the measured value and the\n  delta so an agent knows exactly what to fix.\n\n## Install\n\n```bash\npip install hwcontract              # judge + logic-analyzer adapter\npip install \"hwcontract[serial]\"    # + live serial capture (pyserial)\npip install \"hwcontract[untrusted]\" # + google-re2 (ReDoS-immune, for untrusted contracts)\npip install \"hwcontract[all]\"       # everything\n```\n\nLive logic-analyzer capture (`check_ws2812` / `check_dshot`) also needs\n`sigrok-cli` on PATH. Judge-only tools (`judge_contract`, `judge_serial`) need\nnothing extra.\n\n## Wire it into an agent\n\nOne stanza per client, add it once. After install, the `hwcontract` command is\non your PATH.\n\n**Claude Code**\n```bash\nclaude mcp add hwcontract -- hwcontract\n```\n\n**Codex CLI:** `~/.codex/config.toml`\n```toml\n[mcp_servers.hwcontract]\ncommand = \"hwcontract\"\n```\n\n**opencode / Cursor / Gemini / any stdio MCP client**\n```json\n{ \"mcpServers\": { \"hwcontract\": { \"command\": \"hwcontract\" } } }\n```\n\n> Transport is **stdio** by default (local, no auth surface). For remote-only\n> clients (e.g. ChatGPT connectors), run `hwcontract --http 8791` and expose it\n> via a tunnel with `HWCONTRACT_TOKEN` set for bearer auth.\n>\n> Speaks MCP 2026-07-28, the stateless revision: per-request `_meta`,\n> `server/discover`, no handshake. Clients that still open with `initialize` get\n> the old shape back. Each request picks its own era, so nothing to configure.\n\n### If the client can't find `hwcontract` (PATH issues)\n\nGUI apps and some agents don't inherit your shell `PATH`, so a bare `hwcontract`\ncan fail with \"command not found\". Two robust fixes:\n\n- Use the **absolute path**: `which hwcontract` → put that full path in `command`.\n- Or invoke via Python (no PATH lookup for the script): `command: \"python3\"`,\n  `args: [\"-m\", \"hwcontract.server\"]`. Works from any directory once installed.\n\n**Contract paths:** pass an **absolute** `contract_path`, or set `HWCONTRACT_ROOT`\nto your contracts folder. Relative paths resolve against it, defaulting to the\nprocess's working directory, which the client controls and may not be your\nproject. Paths outside the root are rejected. Bundled examples install with the\npackage under `hwcontract/examples/`.\n\n## The tools\n\n| Tool | Hardware? | What it does |\n|------|-----------|--------------|\n| `judge_contract` | no | Judge given observations against a timing contract. Replay / testing. |\n| `judge_serial` | no | Judge a given log string against a serial contract's expect/forbid. |\n| `judge_events` | no | Judge decoded events against temporal assertions (when/require/within, forbid/while/before). |\n| `check_ws2812` | yes | Capture a live WS2812 line **and** judge it, one call. |\n| `check_dshot` | yes | Same, for a DShot600 ESC signal. |\n| `capture_ws2812` | yes | Just capture → observations (no judging). |\n| `check_serial` | yes | Read a serial port for N seconds and judge the log. |\n\nEvent contracts are the SVA-style layer: relationships between decoded\nevents, checked for every occurrence, with latency distributions and\nfirst-failure timestamps. Feed them `sigrok-cli --protocol-decoder-jsontrace`\noutput and judge from the CLI:\n\n```bash\npython3 -m hwcontract.temporal spi-frame.contract.yaml trace.json\n```\n\nThe bundled `spi-frame.contract.yaml` catches the Zephyr LPSPI class of bug\n(CS asserting after SCK starts, MOSI setup collapse) that loopback tests\ncannot see.\n\nPrefer plain pytest over MCP? [`pytest-hwcontract`](pytest-hwcontract/) is a\nplugin that turns verdicts into tests: a FAIL, MARGINAL or MISSING edge fails\nthe test with the verdict table in the message, JUnit included.\n\n## Gate CI on it\n\nThe repo ships a GitHub Action, so captures checked into the repo get judged\non every PR:\n\n```yaml\n- uses: MohibShaikh/hwcontract@action-v0\n  with:\n    timing: \"ws2812b=captures/strip.csv\"     # contract=capture-glob, bundled names work\n    serial: \"boot=logs/boot.log\"\n    samplerate: 24000000                     # for CSV captures (0/1 per line)\n    junit: hwcontract-junit.xml              # shows in the tests tab\n```\n\nA FAIL, MARGINAL or MISSING edge fails the step, annotates the failing line,\nand writes JUnit. The action self-tests on every push to this repo with one\nclean and one deliberately broken capture.\n\n## How it fits together\n\n```\n  observers (capture)                  judge (this repo)\n  ─────────────────────                ─────────────────\n  logic analyzer  ─ pulse widths ─┐\n  serial port     ─ log text ─────┼─►  contract × observation  ─►  pass/marginal/fail\n  sigrok jsontrace ─ events ──────┘         (judge.py / temporal.py)\n```\n\n- **`judge.py`.** The pure judge for timing and serial, plus contract validation. No hardware, no framework, cached.\n- **`temporal.py`.** Cross-event temporal assertions: selectors, signed windows, latency distributions, first-failure timestamps.\n- **`jsontrace.py`.** Imports sigrok-cli's Google Trace Event JSON into normalized events.\n- **`sigrok_adapter.py`.** Turns a logic-analyzer capture into pulse-width distributions for WS2812 and DShot.\n- **`serial_adapter.py`.** Captures a serial log, or replays a saved one.\n- **`server.py`.** The MCP server, stdio and HTTP JSON-RPC, stdlib only.\n- **`*.contract.yaml`.** What \"correct\" looks like. Human-editable, and they double as regression tests.\n\n## The contract format\n\nTiming (`ws2812.contract.yaml`, `dshot.contract.yaml`): pulse widths in ns\n```yaml\ncontract: ws2812\nheadroom_pct: 20         # in-spec but within 20% of a rail => \"marginal\"\nedges:\n  - {name: T0H, min: 200, typ: 350, max: 500}   # '0' bit high time\n```\n\nSerial (`boot.contract.yaml`) uses Python regex:\n```yaml\ncontract: boot\nkind: serial\nexpect: [\"IMU init OK\", \"boot v\\\\d+\"]\nforbid: [\"panic\", \"Guru Meditation\", \"\\\\bnan\\\\b\"]\n```\n\nEvents (`spi-frame.contract.yaml`) assert relationships between decoded\nevents — SVA-style temporal checks on raw pin edges or sigrok annotations:\n```yaml\ncontract: spi-frame\nkind: events\nassertions:\n  - {name: cs-precedes-first-clock, when: spi.sck.rising,\n     require: gpio.cs.falling, within: [-10us, 0ns]}\n  - {name: mosi-setup, when: spi.sck.rising,\n     forbid: spi.mosi.*, before: 20ns}\n```\n\nAdd a protocol = drop a new YAML. No code change for another timing signal.\n\n## Kill switch\n\nInstantly disable every hardware-touching tool (captures) while leaving the pure\njudge tools working:\n\n```bash\nexport HWCONTRACT_SAFE=1          # env, or:\ntouch /home/tsd/projects/hardware/KILLSWITCH   # file next to server.py\n```\n\n## Security\n\nEvery tool argument is treated as hostile, since the caller is an LLM that can be\nprompt-injected. Contract paths are confined to the server dir, `HWCONTRACT_ROOT`\noverrides that. `driver`/`channel`/`port` are charset-validated,\n`samples`/`seconds`/`samplerate` are clamped, `sigrok-cli` runs with a timeout,\nYAML is `safe_load`. Do not expose this server over the network without adding\nauthentication.\n\n## Self-tests: no hardware, run from anywhere\n\n```bash\nhwcontract --selftest                       # full MCP round-trip\npython3 -m hwcontract.judge --demo\npython3 -m hwcontract.sigrok_adapter --demo\npython3 -m hwcontract.serial_adapter --demo\npytest                                      # the tests/ suite; pip install -e .[dev]\n```\n\nCI runs the suite on every push and PR, and the PyPI publish job waits for it.\n",
  "bytes": 11645,
  "sha": "c53cbd619a8897c9354af1dab464ab2cc8b038906dc9b473b07b41038f9d4e8b",
  "repo_slug": "mohibshaikh/hwcontract",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_mohibshaikh_hwcontract_b9bd662b/readme"
}