hyderhusainarastu/hardware-mod-toolkit/framed-serial-protocol
Claude Code and agent skill by hyderhusainarastu/hardware-mod-toolkit
- community
Checking that the SKILL.md file is still in the repository.
Design a framed request/response protocol over a serial or CDC link: CRC, sequence numbers, ACK/NACK codes, resync, timeouts, mock transport, exclusive port ownership. Use when building host tooling for custom firmware or debugging desync, duplicate frames or port contention.
Install
npx vskill@latest install hyderhusainarastu/hardware-mod-toolkit/framed-serial-protocolSKILL.md
The same SKILL.md was published earlier as hyderhusainarastu/hardware-mod-toolkit/framed-serial-protocol.
framed-serial-protocol
A byte stream has no message boundaries of its own. Everything in this skill exists to answer one question honestly: what does the receiver do with the next byte when it has no idea what it means? A protocol that only has an answer for the happy path is not finished — it is untested.
Two rules below were not designed in up front. They were extracted from a real incident where a protocol that was specified correctly on paper still crashed a production host, because the code implementing it did not agree with the spec at every layer. Read §4 and §5 first if you read nothing else.
Placeholders used throughout: <DEVICE>, <PRODUCT_STRING>, <PORT_GLOB>, <REPO>.
The full spec template lives at ${CLAUDE_PLUGIN_ROOT}/templates/protocol-spec.md (plugin install) or templates/protocol-spec.md (repo checkout) — this skill explains why each section of that template is shaped the way it is; fill the template in for your own device rather than duplicating its structure here.
1. Frame layout
Fix these once, in a spec document, before writing a line of code:
- A magic (2 bytes is enough — e.g.
'M','D') that anchors resync. It must not be a byte
sequence that occurs constantly in ordinary payloads.
- VERSION (1 byte). A receiver that sees an unknown version rejects the frame and resyncs — it
does not guess, and it does not try to parse a frame shaped by a version it doesn't speak.
- TYPE (1 byte), FLAGS (1 byte, bitmap — reserved bits sent
0, ignored on receipt so a
future flag doesn't break an old receiver), SEQ (u16 LE, wraps), LEN (u16 LE, payload length, with a hard maximum below any plausible single-allocation size).
- PAYLOAD (
LENbytes, type-specific — the frame layer does not know or care what's in it). - CRC32, LE, computed over an exactly specified span. Say explicitly whether the magic and
version are inside the CRC or not — a worked example below is the reference implementation's own header (9 bytes: magic·2 + version·1 + type·1 + flags·1 + seq·2 + len·2) plus payload, CRC field itself excluded.
Pin the CRC to a named, standard implementation and prove it, don't just cite it. State the exact algorithm (poly, init, reflection, final XOR) in the spec, then in the same document give a Python one-liner that computes it (zlib.crc32 implements IEEE 802.3 / zlib CRC-32 exactly: reflected poly 0xEDB88320, init 0xFFFFFFFF, input/output reflected, final XOR 0xFFFFFFFF) and a matching call for whatever the firmware side actually uses (ESP-IDF: esp_rom_crc.h's esp_crc32_le(0xFFFFFFFF, buf, len) ^ 0xFFFFFFFF). Then generate a shared table of test vectors (§12-style) from one implementation and assert the other reproduces every value byte-for-byte in a unit test — see references/frame-worked-example.md for the exact vector format and a worked example. "The host library and the firmware agree on CRC" is a claim a test proves, not a design document asserts.
Publish the size arithmetic once you've picked the payload cap, so nobody has to recompute it: frame size = header + payload + CRC (e.g. 9 + LEN + 4); min frame = header + 0 + CRC; max frame = header + max-payload + CRC.
2. The decoder is a state machine, not a length-prefixed read
Do not write read(9) then read(length) and call it a parser. A serial link truncates at arbitrary points, may start mid-frame (the host attaches to a device that's already running), and delivers bytes in whatever chunk sizes the OS feels like. The decoder must be fed bytes — one at a time or in arbitrary chunks, with an identical result either way — and never block waiting for more than are actually available.
States: HUNT (scan for the magic, discard everything before it) → HEADER (accumulate the fixed header, reject on bad version or over-length) → PAYLOAD (accumulate LEN bytes) → CRC (accumulate the CRC field, verify, dispatch or reject) → back to HUNT either way.
A magic byte sequence appearing inside a payload is not a bug to guard against with escaping — HUNT is only entered when the receiver is not already inside a frame, and a frame's extent is fixed by its own LEN. A stray magic can only be latched onto after a corruption has already happened, and the CRC check that follows rejects it. Don't add byte-stuffing/escaping to work around a problem the state machine + CRC combination doesn't have; it only adds a second thing that can be implemented wrong.
The decoder deliberately does not know what payload length is correct for a given message type. "Length is wrong for this type" is a dispatch-layer concern (checked after a structurally valid frame is already decoded), not a framing-layer one — keep that boundary. This also means a generic "bad length" error code has two different reasons behind it (over the wire cap vs. wrong for this specific type) and both should be distinguishable if you want good diagnostics.
Track a resync_events counter on both sides and log it. A rising count is the first visible symptom of a transport-level bug (a badly wired handshake, a driver dropping bytes, DTR/RTS mishandling) — it will show up before anything else does, so surface it somewhere a human will actually see it (a status field, a periodic log line), not just as an internal counter nobody reads.
3. Sequence numbers
- One counter per originator,
u16, wrapping through zero, incremented per frame that
originates from that side. Host and device each own an independent counter — they are not shared, and a reply does not need one of its own: a reply echoes the request's SEQ instead of consuming a new value from the responder's counter. State this explicitly, because it's the detail most likely to get "fixed" incorrectly by someone who assumes every outbound frame burns a sequence number.
- What resets the expectation: the handshake does. When a host (re)connects and sends its
hello/reset message, the device treats that as the start of a new session — it must forget whatever sequence state it had for the previous session's peer. Make this an explicit, named operation in the implementation (not just "it happens to work because the counter starts over") — a receiver that's about to re-issue a hello should call it before waiting for the reply, not rely on the far side inferring a reset from a value that merely looks small.
- Duplicate detection: keep a window of the last N (8 is a reasonable, cheap default) distinct
sequence numbers seen from a peer. An idempotent message type (anything without side effects that depend on being applied exactly once — a query, a "set X" command, a draw command) whose SEQ is in that window is dropped without re-executing it, and its previous reply is re-sent if one was requested. A non-idempotent, chunked/streaming message type (a data chunk addressed by its own offset, for instance) must be exempted from that dedup — retransmitting a chunk is a legitimate recovery action, not a duplicate to be silently swallowed.
- A forward jump far larger than any plausible retry gap is a new session, not damage. Pick a
threshold well above your normal timeout/retry envelope (the reference implementation uses 1024 against a window of 8) and when a peer's SEQ jumps that far forward, clear the duplicate window and carry on rather than reporting a few hundred "missing" frames that were never sent. This covers a reconnect that, for whatever reason, didn't get an explicit session-reset call first.
- What must NOT consume a sequence number: anything the responder didn't originate as a fresh,
trackable, request-shaped frame. If your device also emits unsolicited, fire-and-forget notifications (button presses, log lines, status pushes) that are never acknowledged and never retried, decide up front whether they share the sender's normal counter or need their own space, and write the answer down — don't leave it implicit. (The worked example's device emits events from its own normal counter, which works cleanly there specifically because replies already don't consume a counter value, so the only other device-originated traffic is events — if your device also originates non-reply, non-event frames, that reasoning doesn't automatically transfer and needs its own decision.)
4. Informational vs. fatal NACKs — the lesson that cost a production crash
Classify every single error/NACK code as fatal or informational, in the spec, in a table, before you write the client. A fatal code means the request failed and the caller should treat it as an error. An informational code means "something noteworthy happened, and the real answer is still coming" — the receiver processed the request anyway and a normal reply follows.
The canonical informational case is a sequence-gap notice: the receiver noticed it missed some number of frames from this peer, but per §3 it doesn't try to repair the gap — it just reports it (for logging/telemetry) and then processes the frame that arrived as if nothing were wrong, because there is no retransmission machinery forcing it to do otherwise. That means the peer that sent the frame gets two things back: the gap notice, and the actual reply — and if your transport naively treats "the first reply carrying this frame's sequence number" as the answer, it will hand the gap notice to the caller instead of the real reply.
This exact bug shipped and crashed a production dashboard loop. The chain was:
- A second process opened the same serial port (see §5 — this should have been impossible, but
wasn't yet), sent its own hello, and reset the device's sequence-tracking state.
- The first process's next frame landed far ahead of the device's freshly-reset expectation. The
device correctly reported a sequence-gap notice — informational, by spec — and then correctly processed and replied to the frame anyway, exactly as the spec said it should.
- The host's transport layer treated "first reply matching this SEQ" as the request's answer. The
gap notice is such a reply. It got returned as if it were the response.
- The code path that turns a NACK-shaped reply into an exception did so unconditionally — it had no
idea this particular NACK code was supposed to be harmless.
- The one call site that could have caught that exception and recovered gracefully only caught a
narrower exception type than what was actually raised, so nothing did, and the process died.
Every one of those five links was independently a small, locally-reasonable design choice. No single line "looks wrong" in isolation. That's exactly why a spec being correct on paper is not enough: the fix has to exist at every layer that could otherwise disagree with it —
- The transport's response-matching logic must special-case every informational code by name:
on seeing one, log/count it, then keep waiting (within the same request's timeout budget) for the real reply that the spec already promises follows it. Do not treat it as the answer.
- The exception hierarchy must make "this was a NACK" and "this was fatal" separable — either a
distinct exception subclass per fatal-vs-informational, or (simpler) never surface an informational code as an exception at all, since the transport layer above already absorbed it.
- Any `except SomeBroadType` around a send/request call site needs to actually catch whatever
exception type your NACK-to-exception path raises — a narrower catch than that is a silent gap that turns "log a warning and recover" into "the process dies," and it will not show up in testing unless the informational path is specifically exercised.
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/framed-serial-protocol/SKILL.md
Popularity
- Repository stars
- 1
- 7-day trend score
- 3
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/hyderhusainarastu/hardware-mod-toolkit/framed-serial-protocol)