Repository navigation
Expand file tree
/
Copy pathpunctim_wire_qwen.jsonl
More file actions
6 lines (6 loc) · 169 KB
/
Copy pathpunctim_wire_qwen.jsonl
File metadata and controls
6 lines (6 loc) · 169 KB
1
2
3
4
5
6
{"messages": [{"role": "system", "content": "You are an expert DCF (DeMoD Communication Framework) wire protocol implementer. You write byte-certified codecs for the 17-byte DeModFrame across multiple languages.\n\nTHE WIRE QUANTUM:\n- 17 bytes: sync(0xD3) | flags[ver|type] | seq | src | dst | payload(4B) | ts24 | crc16\n- Version nibble = 1 (always)\n- CRC-16/CCITT-FALSE over bytes [0..14], anchors: CRC(\"123456789\")=0x29B1, CRC(0^15)=0x4EC3\n- Valid iff sync byte + version nibble + CRC match\n\nCONVENTIONS:\n- Encode: take fields → pack into 17-byte buffer → compute CRC → write CRC at [15..16]\n- Decode: verify sync + version + CRC → unpack fields → return struct or error\n- All implementations MUST produce byte-identical output for identical input\n- Use big-endian for multi-byte fields (network byte order)\n- CRC polynomial: 0x1021, init: 0xFFFF, no final XOR\n- Test against golden_vectors.json (246 vectors: 109 encode + 137 syndrome)\n"}, {"role": "user", "content": "Implement the DCF wire codec in C.\n\nSpecification:\n# DCF Wire Quantum — Canonical Specification\n\n**Version 1** · DeMoD LLC · This document is normative.\n\nThe DCF wire protocol has exactly **one** wire format: the 17-byte `DeModFrame`\n(version nibble = 1). All other formats (the proto-message UDP header, the C\nSDK's `DCFMessageHeader`) are **adapters** over this quantum and must be\nexplicitly documented as such.\n\n## Wire Layout\n\n```\n Byte Field Width Description\n ──── ────────── ───── ─────────────────────────────────────────\n 0 sync 1 B Fixed 0xD3 (first validity gate)\n 1 flags 1 B [7:4] version (currently 1) | [3:0] type (0–3)\n 2–3 seq 2 B Big-endian u16, rolling sequence counter\n 4–5 src_id 2 B Big-endian u16, source node ID\n 6–7 dst_id 2 B Big-endian u16, destination (0xFFFF = broadcast)\n 8–11 payload 4 B Application data\n 12–14 timestamp 3 B 24-bit µs offset, big-endian, wraps ~16.7 s\n 15–16 crc16 2 B CRC-16/CCITT-FALSE over bytes [0..14]\n```\n\n**Total: 17 bytes = 136 bits.** The free field data is 108 bits (4+16+16+16+32+24).\n\n## Frame Types\n\n| Value | Name | Purpose |\n|-------|--------|-----------------------------|\n| 0 | DATA | Application payload |\n| 1 | ACK | Acknowledgement |\n| 2 | BEACON | Clock sync / broadcast |\n| 3 | CTRL | Control / fragmented audio |\n\n## Validity\n\nA frame is valid iff:\n1. `frame[0] == 0xD3` (sync byte)\n2. `(frame[1] >> 4) == 1` (version nibble)\n3. `CRC-16/CCITT-FALSE(frame[0..14]) == (frame[15] << 8) | frame[16]` (CRC)\n\nFor a random byte stream, the probability of a 17-byte window passing all three\nchecks is 2⁻²⁸ (Theorem 2.1, `wire_quanta_category.md`).\n\n## CRC-16/CCITT-FALSE\n\n- Polynomial: `0x1021`\n- Init: `0xFFFF`\n- RefIn/RefOut: `false`\n- XorOut: `0x0000`\n- Check value: `CRC(\"123456789\") = 0x29B1`\n\n## Anchors\n\n| Quantity | Value | Source |\n|----------|-------|--------|\n| CRC(\"123456789\") | `0x29B1` | Reference check value |\n| CRC(0¹⁵) | `0x4EC3` | Affine offset c |\n| CRC(exampleFrame body) | `0xA963` | Cross-language anchor |\n| exampleFrame | `D31312340001FFFFDEADBEEFAB12CD24C0` | type=CTRL, seq=0x1234, src=1, dst=0xFFFF, payload=DEADBEEF, ts=AB12CD |\n\n## Formal Properties\n\nThe frame is a **cemented retract** (Theorem 1, `wire_quanta_category.md`):\n- `encode` is injective with a left inverse `decode` (decode∘encode = id)\n- `encode` is a bijection onto the set of valid words\n- `decode` is the unique decoder satisfying the spec\n\nThe 246-vector finite certificate (Theorem 4) proves that any implementation\nmatching the 109 encode-basis + 137 syndrome-basis vectors equals the reference\non all 2¹⁰⁸ frames and classifies all 2¹³⁶ words identically. See\n`Documentation/golden_vectors.json`.\n\n## Reference Implementations\n\n| Language | File | Functions |\n|----------|------|-----------|\n| C | `codec/demod_frame.h` | `dcf_frame_encode`, `dcf_frame_decode`, `dcf_frame_crc` |\n| Rust | `codec/frame.rs` | `Frame::encode`, `Frame::decode` |\n| Python | `python/MCP/wirelab_core.py` | `encode`, `decode`, `syndrome`, `crc16_ccitt` |\n| Lua | `GUI/wirelab.lua` | `encode`, `decode`, `crc16` |\n\n## Certification\n\nTo certify a new SDK against the reference:\n\n```sh\npython3 python/MCP/certify_sdk.py --selftest # reference self-test\npython3 python/MCP/certify_sdk.py --sdk-json SDK.json # certify an external SDK\n```\n\nAll CI gates run `python/MCP/verify_laws.py` and `python/MCP/certify_sdk.py --selftest`.\nUnder Theorem 4, passing the 246-vector test is equivalent to agreement on the\nentire 2¹⁰⁸ × 2¹³⁶ input space.\n\n## Other Wire Formats ARE Adapters\n\n| Format | Status | Relationship to DeModFrame |\n|--------|--------|----------------------------|\n| Proto-message UDP header (C SDK) | Adapter | Must marshal to/from DeModFrame for wire |\n| `DCFMessageHeader` (C SDK) | Internal | In-process struct; must not appear on the wire |\n| Haskell `FrameSpec` | Implemented | `haskell/src/DCF/Transport/FrameSpec.hs` — encodeFrame / decodeFrame |\n\nAny new transport MUST emit and consume DeModFrame v1 on the wire. Internal\nrepresentations are free to differ but MUST be convertible to/from DeModFrame\nwithout loss.\n\nGolden vectors (sample):\n{\n \"encode_basis\": [\n {\n \"input_bits\": \"000000000000000000000000000\",\n \"frame\": \"d310000000000000000000000000005b80\"\n },\n {\n \"input_bit\": 0,\n \"frame\": \"d3110000000000000000000000000020e1\"\n },\n {\n \"input_bit\": 1,\n \"frame\": \"d31200000000000000000000000000ad42\"\n },\n {\n \"input_bit\": 2,\n \"frame\": \"d31400000000000000000000000000a625\"\n },\n {\n \"input_bit\": 3,\n \"frame\": \"d31800000000000000000000000000b0eb\"\n },\n {\n \"input_bit\": 4,\n \"frame\": \"d3100001000000000000000000000058f5\"\n },\n {\n \"input_bit\": 5,\n \"frame\": \"d310000200000000000000000000005d6a\"\n },\n {\n \"input_bit\": 6,\n \"frame\": \"d310000400000000000000000000005654\"\n },\n {\n \"input_bit\": 7,\n \"frame\": \"d310000800000000000000000000004028\"\n },\n {\n \"input_bit\": 8,\n \"frame\": \"d310001000000000000000000000006cd0\"\n }\n ],\n \"syndrome_basis\": [\n {\n \"word\": \"0000000000000000000000000000000000\",\n \"syndrome\": 20163\n },\n {\n \"bit\": 0,\n \"syndrome\": 6865\n },\n {\n \"bit\": 1,\n \"syndrome\": 25802\n },\n {\n \"bit\": 2,\n \"syndrome\": 54231\n },\n {\n \"bit\": 3,\n \"syndrome\": 73\n },\n {\n \"bit\": 4,\n \"syndrome\": 27014\n },\n {\n \"bit\": 5,\n \"syndrome\": 54641\n },\n {\n \"bit\": 6,\n \"syndrome\": 794\n },\n {\n \"bit\": 7,\n \"syndrome\": 57407\n },\n {\n \"bit\": 8,\n \"syndrome\": 6589\n }\n ]\n}\n\nProvide the complete implementation with encode/decode functions."}, {"role": "assistant", "content": "// SPDX-License-Identifier: LGPL-3.0-only\n/*\n * transport/dcf_frame.h — DeMoD 17-byte transport frame codec\n * DeMoD LLC | GPL-3.0\n *\n * Single-header, zero-dependency C99 implementation.\n * Drop-in for any C/C++ target including embedded (RP2040, STM32, bare-metal).\n *\n * Wire layout (17 bytes = 136 bits, all multi-byte fields big-endian):\n *\n * Byte Field Width Notes\n * ──── ─────────── ───── ─────────────────────────────────────────────────\n * 0 sync 1 B Fixed 0xD3 — first validity gate\n * 1 flags 1 B [7:4] version (0–15) | [3:0] frame type (0–15)\n * 2-3 seq 2 B Rolling sequence counter, big-endian uint16\n * 4-5 src_id 2 B Source node ID, big-endian uint16\n * 6-7 dst_id 2 B Destination node ID (0xFFFF = broadcast)\n * 8-11 payload 4 B Application data\n * 12-14 timestamp 3 B 24-bit µs offset, big-endian, wraps ~16.7 s\n * 15-16 crc16 2 B CRC-CCITT(poly=0x1021, init=0xFFFF) over [0..14]\n *\n * Frame types:\n * 0 = DATA — application payload\n * 1 = ACK — acknowledgement\n * 2 = BEACON — clock sync / broadcast beacon\n * 3 = CTRL — control / fragmented audio\n *\n * CRC covers bytes [0..14] (everything except the CRC field itself).\n * A frame is valid iff sync == 0xD3 AND crc16([0..14]) == frame[15..16].\n *\n * Cross-language parity:\n * Haskell DCF.Transport.Frame encodeFrame / decodeFrame\n * C transport/dcf_frame.h dcf_frame_encode / dcf_frame_decode\n * Rust transport/dcf_frame.rs Frame::encode / Frame::decode\n * Lisp punctim.lisp encode-dcf-frame / decode-dcf-frame\n */\n\n#pragma once\n#include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <string.h>\n\n/* ── Constants ────────────────────────────────────────────────────────────── */\n\n#define DCF_FRAME_SIZE 17u /* total wire size in bytes */\n#define DCF_FRAME_CRC_COVER 15u /* bytes covered by CRC: [0..14] */\n#define DCF_SYNC_BYTE 0xD3u /* fixed preamble / first validity gate */\n#define DCF_BROADCAST 0xFFFFu\n\n/* Bit-field positions inside flags byte */\n#define DCF_VERSION_SHIFT 4u\n#define DCF_VERSION_MASK 0xF0u\n#define DCF_TYPE_MASK 0x0Fu\n\n/* ── Frame type enum ─────────────────────────────────────────────────────── */\n\ntypedef enum {\n DCF_TYPE_DATA = 0,\n DCF_TYPE_ACK = 1,\n DCF_TYPE_BEACON = 2,\n DCF_TYPE_CTRL = 3,\n} dcf_frame_type_t;\n\n/* ── Decoded frame (host-order, field-by-field) ──────────────────────────── */\n\ntypedef struct {\n uint8_t version; /* 4-bit, 0–15 */\n dcf_frame_type_t type; /* 4-bit nibble */\n uint16_t seq; /* rolling counter */\n uint16_t src_id; /* source node */\n uint16_t dst_id; /* dest node (DCF_BROADCAST = all) */\n uint8_t payload[4]; /* application bytes */\n uint32_t timestamp_us; /* 24-bit µs, stored as uint32 (top byte 0) */\n} dcf_frame_t;\n\n/* ── CRC-CCITT ───────────────────────────────────────────────────────────── */\n/*\n * Poly 0x1021, init 0xFFFF.\n * Identical algorithm used in Haskell (crc16ccitt), Rust (crc16_ccitt),\n * and Lisp (crc16-ccitt). All implementations must produce the same output\n * for the same input bytes — this is the cross-language compatibility gate.\n */\nstatic inline uint16_t dcf_crc16(const uint8_t *data, size_t len) {\n uint16_t crc = 0xFFFFu;\n for (size_t i = 0; i < len; i++) {\n crc ^= (uint16_t)((uint16_t)data[i] << 8);\n for (int b = 0; b < 8; b++)\n crc = (crc & 0x8000u)\n ? (uint16_t)(((uint16_t)(crc << 1)) ^ 0x1021u)\n : (uint16_t)((uint16_t)(crc << 1));\n }\n return crc;\n}\n\n/* ── Encode ──────────────────────────────────────────────────────────────── */\n/*\n * Serialise a dcf_frame_t into exactly DCF_FRAME_SIZE bytes.\n * buf must point to at least 17 bytes of writable memory.\n * Returns buf for convenience.\n *\n * All multi-byte fields are written big-endian regardless of host byte order.\n * The CRC is computed over buf[0..14] and written to buf[15..16].\n */\nstatic inline uint8_t *dcf_frame_encode(const dcf_frame_t *f, uint8_t *buf) {\n /* [0] sync */\n buf[0] = DCF_SYNC_BYTE;\n\n /* [1] flags: version[7:4] | type[3:0] */\n buf[1] = (uint8_t)(((f->version & 0x0Fu) << DCF_VERSION_SHIFT)\n | (f->type & 0x0Fu));\n\n /* [2-3] seq, big-endian */\n buf[2] = (uint8_t)((f->seq >> 8) & 0xFFu);\n buf[3] = (uint8_t)( f->seq & 0xFFu);\n\n /* [4-5] src_id, big-endian */\n buf[4] = (uint8_t)((f->src_id >> 8) & 0xFFu);\n buf[5] = (uint8_t)( f->src_id & 0xFFu);\n\n /* [6-7] dst_id, big-endian */\n buf[6] = (uint8_t)((f->dst_id >> 8) & 0xFFu);\n buf[7] = (uint8_t)( f->dst_id & 0xFFu);\n\n /* [8-11] payload, verbatim */\n memcpy(buf + 8, f->payload, 4);\n\n /* [12-14] timestamp, 24-bit big-endian */\n buf[12] = (uint8_t)((f->timestamp_us >> 16) & 0xFFu);\n buf[13] = (uint8_t)((f->timestamp_us >> 8) & 0xFFu);\n buf[14] = (uint8_t)( f->timestamp_us & 0xFFu);\n\n /* [15-16] CRC-CCITT over [0..14], big-endian */\n uint16_t crc = dcf_crc16(buf, DCF_FRAME_CRC_COVER);\n buf[15] = (uint8_t)((crc >> 8) & 0xFFu);\n buf[16] = (uint8_t)( crc & 0xFFu);\n\n return buf;\n}\n\n/* ── Decode ──────────────────────────────────────────────────────────────── */\n/*\n * Parse DCF_FRAME_SIZE bytes into a dcf_frame_t.\n * Returns true on success, false if sync byte or CRC is wrong.\n * *out is written only on success; it is not touched on failure.\n */\nstatic inline bool dcf_frame_decode(const uint8_t *buf, dcf_frame_t *out) {\n /* First gate: sync byte */\n if (buf[0] != DCF_SYNC_BYTE) return false;\n\n /* Second gate: CRC over [0..14] must match [15..16] */\n uint16_t crc_calc = dcf_crc16(buf, DCF_FRAME_CRC_COVER);\n uint16_t crc_stored = (uint16_t)(((uint16_t)buf[15] << 8) | buf[16]);\n if (crc_calc != crc_stored) return false;\n\n out->version = (buf[1] & DCF_VERSION_MASK) >> DCF_VERSION_SHIFT;\n out->type = (dcf_frame_type_t)(buf[1] & DCF_TYPE_MASK);\n out->seq = (uint16_t)(((uint16_t)buf[2] << 8) | buf[3]);\n out->src_id = (uint16_t)(((uint16_t)buf[4] << 8) | buf[5]);\n out->dst_id = (uint16_t)(((uint16_t)buf[6] << 8) | buf[7]);\n memcpy(out->payload, buf + 8, 4);\n out->timestamp_us = ((uint32_t)buf[12] << 16)\n | ((uint32_t)buf[13] << 8)\n | (uint32_t)buf[14];\n return true;\n}\n\n/* ── Validate (non-destructive, no decode) ───────────────────────────────── */\n/*\n * Returns true iff buf[0..16] is a well-formed frame.\n * Safe to call on any 17-byte buffer — does not access out-of-bounds memory.\n */\nstatic inline bool dcf_frame_valid(const uint8_t *buf) {\n if (buf[0] != DCF_SYNC_BYTE) return false;\n uint16_t crc_calc = dcf_crc16(buf, DCF_FRAME_CRC_COVER);\n uint16_t crc_stored = (uint16_t)(((uint16_t)buf[15] << 8) | buf[16]);\n return crc_calc == crc_stored;\n}\n\n/* ── Convenience initialiser ─────────────────────────────────────────────── */\n/*\n * Zero-initialise a dcf_frame_t and set the structural fields.\n * Caller must set payload[] and timestamp_us, then call dcf_frame_encode().\n */\nstatic inline void dcf_frame_init(dcf_frame_t *f,\n uint8_t version,\n dcf_frame_type_t type,\n uint16_t seq,\n uint16_t src_id,\n uint16_t dst_id) {\n memset(f, 0, sizeof(*f));\n f->version = version;\n f->type = type;\n f->seq = seq;\n f->src_id = src_id;\n f->dst_id = dst_id;\n}\n\n/* ── Reference test vectors ─────────────────────────────────────────────── */\n/*\n * These byte sequences are used as cross-language test fixtures.\n * The same vectors appear in Haskell FrameSpec.hs (exampleFrame),\n * the Rust #[cfg(test)] block, and the Lisp fiveam dcf-frame-roundtrip-test.\n *\n * Vector A — DATA frame, seq=0x0001, src=0x0001, dst=0xFFFF,\n * payload=0xDEADBEEF, ts=0x000000, version=1\n *\n * Byte: D3 10 00 01 00 01 FF FF DE AD BE EF 00 00 00 XX XX\n * ── ── ───── ───── ───── ────────────── ────── ─────\n * sync flg seq src dst payload ts crc\n *\n * Expected CRC (computed offline): verify with dcf_crc16(buf, 15).\n *\n * To compute the CRC for documentation purposes:\n * uint8_t body[15] = {\n * 0xD3, 0x10, 0x00, 0x01, 0x00, 0x01, 0xFF, 0xFF,\n * 0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x00, 0x00\n * };\n * uint16_t crc = dcf_crc16(body, 15); // → deterministic value\n */\n"}], "text": "<|im_start|>\nsystem\nYou are an expert DCF (DeMoD Communication Framework) wire protocol implementer. You write byte-certified codecs for the 17-byte DeModFrame across multiple languages.\n\nTHE WIRE QUANTUM:\n- 17 bytes: sync(0xD3) | flags[ver|type] | seq | src | dst | payload(4B) | ts24 | crc16\n- Version nibble = 1 (always)\n- CRC-16/CCITT-FALSE over bytes [0..14], anchors: CRC(\"123456789\")=0x29B1, CRC(0^15)=0x4EC3\n- Valid iff sync byte + version nibble + CRC match\n\nCONVENTIONS:\n- Encode: take fields → pack into 17-byte buffer → compute CRC → write CRC at [15..16]\n- Decode: verify sync + version + CRC → unpack fields → return struct or error\n- All implementations MUST produce byte-identical output for identical input\n- Use big-endian for multi-byte fields (network byte order)\n- CRC polynomial: 0x1021, init: 0xFFFF, no final XOR\n- Test against golden_vectors.json (246 vectors: 109 encode + 137 syndrome)\n\n<|im_start|>\nuser\nImplement the DCF wire codec in C.\n\nSpecification:\n# DCF Wire Quantum — Canonical Specification\n\n**Version 1** · DeMoD LLC · This document is normative.\n\nThe DCF wire protocol has exactly **one** wire format: the 17-byte `DeModFrame`\n(version nibble = 1). All other formats (the proto-message UDP header, the C\nSDK's `DCFMessageHeader`) are **adapters** over this quantum and must be\nexplicitly documented as such.\n\n## Wire Layout\n\n```\n Byte Field Width Description\n ──── ────────── ───── ─────────────────────────────────────────\n 0 sync 1 B Fixed 0xD3 (first validity gate)\n 1 flags 1 B [7:4] version (currently 1) | [3:0] type (0–3)\n 2–3 seq 2 B Big-endian u16, rolling sequence counter\n 4–5 src_id 2 B Big-endian u16, source node ID\n 6–7 dst_id 2 B Big-endian u16, destination (0xFFFF = broadcast)\n 8–11 payload 4 B Application data\n 12–14 timestamp 3 B 24-bit µs offset, big-endian, wraps ~16.7 s\n 15–16 crc16 2 B CRC-16/CCITT-FALSE over bytes [0..14]\n```\n\n**Total: 17 bytes = 136 bits.** The free field data is 108 bits (4+16+16+16+32+24).\n\n## Frame Types\n\n| Value | Name | Purpose |\n|-------|--------|-----------------------------|\n| 0 | DATA | Application payload |\n| 1 | ACK | Acknowledgement |\n| 2 | BEACON | Clock sync / broadcast |\n| 3 | CTRL | Control / fragmented audio |\n\n## Validity\n\nA frame is valid iff:\n1. `frame[0] == 0xD3` (sync byte)\n2. `(frame[1] >> 4) == 1` (version nibble)\n3. `CRC-16/CCITT-FALSE(frame[0..14]) == (frame[15] << 8) | frame[16]` (CRC)\n\nFor a random byte stream, the probability of a 17-byte window passing all three\nchecks is 2⁻²⁸ (Theorem 2.1, `wire_quanta_category.md`).\n\n## CRC-16/CCITT-FALSE\n\n- Polynomial: `0x1021`\n- Init: `0xFFFF`\n- RefIn/RefOut: `false`\n- XorOut: `0x0000`\n- Check value: `CRC(\"123456789\") = 0x29B1`\n\n## Anchors\n\n| Quantity | Value | Source |\n|----------|-------|--------|\n| CRC(\"123456789\") | `0x29B1` | Reference check value |\n| CRC(0¹⁵) | `0x4EC3` | Affine offset c |\n| CRC(exampleFrame body) | `0xA963` | Cross-language anchor |\n| exampleFrame | `D31312340001FFFFDEADBEEFAB12CD24C0` | type=CTRL, seq=0x1234, src=1, dst=0xFFFF, payload=DEADBEEF, ts=AB12CD |\n\n## Formal Properties\n\nThe frame is a **cemented retract** (Theorem 1, `wire_quanta_category.md`):\n- `encode` is injective with a left inverse `decode` (decode∘encode = id)\n- `encode` is a bijection onto the set of valid words\n- `decode` is the unique decoder satisfying the spec\n\nThe 246-vector finite certificate (Theorem 4) proves that any implementation\nmatching the 109 encode-basis + 137 syndrome-basis vectors equals the reference\non all 2¹⁰⁸ frames and classifies all 2¹³⁶ words identically. See\n`Documentation/golden_vectors.json`.\n\n## Reference Implementations\n\n| Language | File | Functions |\n|----------|------|-----------|\n| C | `codec/demod_frame.h` | `dcf_frame_encode`, `dcf_frame_decode`, `dcf_frame_crc` |\n| Rust | `codec/frame.rs` | `Frame::encode`, `Frame::decode` |\n| Python | `python/MCP/wirelab_core.py` | `encode`, `decode`, `syndrome`, `crc16_ccitt` |\n| Lua | `GUI/wirelab.lua` | `encode`, `decode`, `crc16` |\n\n## Certification\n\nTo certify a new SDK against the reference:\n\n```sh\npython3 python/MCP/certify_sdk.py --selftest # reference self-test\npython3 python/MCP/certify_sdk.py --sdk-json SDK.json # certify an external SDK\n```\n\nAll CI gates run `python/MCP/verify_laws.py` and `python/MCP/certify_sdk.py --selftest`.\nUnder Theorem 4, passing the 246-vector test is equivalent to agreement on the\nentire 2¹⁰⁸ × 2¹³⁶ input space.\n\n## Other Wire Formats ARE Adapters\n\n| Format | Status | Relationship to DeModFrame |\n|--------|--------|----------------------------|\n| Proto-message UDP header (C SDK) | Adapter | Must marshal to/from DeModFrame for wire |\n| `DCFMessageHeader` (C SDK) | Internal | In-process struct; must not appear on the wire |\n| Haskell `FrameSpec` | Implemented | `haskell/src/DCF/Transport/FrameSpec.hs` — encodeFrame / decodeFrame |\n\nAny new transport MUST emit and consume DeModFrame v1 on the wire. Internal\nrepresentations are free to differ but MUST be convertible to/from DeModFrame\nwithout loss.\n\nGolden vectors (sample):\n{\n \"encode_basis\": [\n {\n \"input_bits\": \"000000000000000000000000000\",\n \"frame\": \"d310000000000000000000000000005b80\"\n },\n {\n \"input_bit\": 0,\n \"frame\": \"d3110000000000000000000000000020e1\"\n },\n {\n \"input_bit\": 1,\n \"frame\": \"d31200000000000000000000000000ad42\"\n },\n {\n \"input_bit\": 2,\n \"frame\": \"d31400000000000000000000000000a625\"\n },\n {\n \"input_bit\": 3,\n \"frame\": \"d31800000000000000000000000000b0eb\"\n },\n {\n \"input_bit\": 4,\n \"frame\": \"d3100001000000000000000000000058f5\"\n },\n {\n \"input_bit\": 5,\n \"frame\": \"d310000200000000000000000000005d6a\"\n },\n {\n \"input_bit\": 6,\n \"frame\": \"d310000400000000000000000000005654\"\n },\n {\n \"input_bit\": 7,\n \"frame\": \"d310000800000000000000000000004028\"\n },\n {\n \"input_bit\": 8,\n \"frame\": \"d310001000000000000000000000006cd0\"\n }\n ],\n \"syndrome_basis\": [\n {\n \"word\": \"0000000000000000000000000000000000\",\n \"syndrome\": 20163\n },\n {\n \"bit\": 0,\n \"syndrome\": 6865\n },\n {\n \"bit\": 1,\n \"syndrome\": 25802\n },\n {\n \"bit\": 2,\n \"syndrome\": 54231\n },\n {\n \"bit\": 3,\n \"syndrome\": 73\n },\n {\n \"bit\": 4,\n \"syndrome\": 27014\n },\n {\n \"bit\": 5,\n \"syndrome\": 54641\n },\n {\n \"bit\": 6,\n \"syndrome\": 794\n },\n {\n \"bit\": 7,\n \"syndrome\": 57407\n },\n {\n \"bit\": 8,\n \"syndrome\": 6589\n }\n ]\n}\n\nProvide the complete implementation with encode/decode functions.\n<|im_start|>\nassistant\n// SPDX-License-Identifier: LGPL-3.0-only\n/*\n * transport/dcf_frame.h — DeMoD 17-byte transport frame codec\n * DeMoD LLC | GPL-3.0\n *\n * Single-header, zero-dependency C99 implementation.\n * Drop-in for any C/C++ target including embedded (RP2040, STM32, bare-metal).\n *\n * Wire layout (17 bytes = 136 bits, all multi-byte fields big-endian):\n *\n * Byte Field Width Notes\n * ──── ─────────── ───── ─────────────────────────────────────────────────\n * 0 sync 1 B Fixed 0xD3 — first validity gate\n * 1 flags 1 B [7:4] version (0–15) | [3:0] frame type (0–15)\n * 2-3 seq 2 B Rolling sequence counter, big-endian uint16\n * 4-5 src_id 2 B Source node ID, big-endian uint16\n * 6-7 dst_id 2 B Destination node ID (0xFFFF = broadcast)\n * 8-11 payload 4 B Application data\n * 12-14 timestamp 3 B 24-bit µs offset, big-endian, wraps ~16.7 s\n * 15-16 crc16 2 B CRC-CCITT(poly=0x1021, init=0xFFFF) over [0..14]\n *\n * Frame types:\n * 0 = DATA — application payload\n * 1 = ACK — acknowledgement\n * 2 = BEACON — clock sync / broadcast beacon\n * 3 = CTRL — control / fragmented audio\n *\n * CRC covers bytes [0..14] (everything except the CRC field itself).\n * A frame is valid iff sync == 0xD3 AND crc16([0..14]) == frame[15..16].\n *\n * Cross-language parity:\n * Haskell DCF.Transport.Frame encodeFrame / decodeFrame\n * C transport/dcf_frame.h dcf_frame_encode / dcf_frame_decode\n * Rust transport/dcf_frame.rs Frame::encode / Frame::decode\n * Lisp punctim.lisp encode-dcf-frame / decode-dcf-frame\n */\n\n#pragma once\n#include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <string.h>\n\n/* ── Constants ────────────────────────────────────────────────────────────── */\n\n#define DCF_FRAME_SIZE 17u /* total wire size in bytes */\n#define DCF_FRAME_CRC_COVER 15u /* bytes covered by CRC: [0..14] */\n#define DCF_SYNC_BYTE 0xD3u /* fixed preamble / first validity gate */\n#define DCF_BROADCAST 0xFFFFu\n\n/* Bit-field positions inside flags byte */\n#define DCF_VERSION_SHIFT 4u\n#define DCF_VERSION_MASK 0xF0u\n#define DCF_TYPE_MASK 0x0Fu\n\n/* ── Frame type enum ─────────────────────────────────────────────────────── */\n\ntypedef enum {\n DCF_TYPE_DATA = 0,\n DCF_TYPE_ACK = 1,\n DCF_TYPE_BEACON = 2,\n DCF_TYPE_CTRL = 3,\n} dcf_frame_type_t;\n\n/* ── Decoded frame (host-order, field-by-field) ──────────────────────────── */\n\ntypedef struct {\n uint8_t version; /* 4-bit, 0–15 */\n dcf_frame_type_t type; /* 4-bit nibble */\n uint16_t seq; /* rolling counter */\n uint16_t src_id; /* source node */\n uint16_t dst_id; /* dest node (DCF_BROADCAST = all) */\n uint8_t payload[4]; /* application bytes */\n uint32_t timestamp_us; /* 24-bit µs, stored as uint32 (top byte 0) */\n} dcf_frame_t;\n\n/* ── CRC-CCITT ───────────────────────────────────────────────────────────── */\n/*\n * Poly 0x1021, init 0xFFFF.\n * Identical algorithm used in Haskell (crc16ccitt), Rust (crc16_ccitt),\n * and Lisp (crc16-ccitt). All implementations must produce the same output\n * for the same input bytes — this is the cross-language compatibility gate.\n */\nstatic inline uint16_t dcf_crc16(const uint8_t *data, size_t len) {\n uint16_t crc = 0xFFFFu;\n for (size_t i = 0; i < len; i++) {\n crc ^= (uint16_t)((uint16_t)data[i] << 8);\n for (int b = 0; b < 8; b++)\n crc = (crc & 0x8000u)\n ? (uint16_t)(((uint16_t)(crc << 1)) ^ 0x1021u)\n : (uint16_t)((uint16_t)(crc << 1));\n }\n return crc;\n}\n\n/* ── Encode ──────────────────────────────────────────────────────────────── */\n/*\n * Serialise a dcf_frame_t into exactly DCF_FRAME_SIZE bytes.\n * buf must point to at least 17 bytes of writable memory.\n * Returns buf for convenience.\n *\n * All multi-byte fields are written big-endian regardless of host byte order.\n * The CRC is computed over buf[0..14] and written to buf[15..16].\n */\nstatic inline uint8_t *dcf_frame_encode(const dcf_frame_t *f, uint8_t *buf) {\n /* [0] sync */\n buf[0] = DCF_SYNC_BYTE;\n\n /* [1] flags: version[7:4] | type[3:0] */\n buf[1] = (uint8_t)(((f->version & 0x0Fu) << DCF_VERSION_SHIFT)\n | (f->type & 0x0Fu));\n\n /* [2-3] seq, big-endian */\n buf[2] = (uint8_t)((f->seq >> 8) & 0xFFu);\n buf[3] = (uint8_t)( f->seq & 0xFFu);\n\n /* [4-5] src_id, big-endian */\n buf[4] = (uint8_t)((f->src_id >> 8) & 0xFFu);\n buf[5] = (uint8_t)( f->src_id & 0xFFu);\n\n /* [6-7] dst_id, big-endian */\n buf[6] = (uint8_t)((f->dst_id >> 8) & 0xFFu);\n buf[7] = (uint8_t)( f->dst_id & 0xFFu);\n\n /* [8-11] payload, verbatim */\n memcpy(buf + 8, f->payload, 4);\n\n /* [12-14] timestamp, 24-bit big-endian */\n buf[12] = (uint8_t)((f->timestamp_us >> 16) & 0xFFu);\n buf[13] = (uint8_t)((f->timestamp_us >> 8) & 0xFFu);\n buf[14] = (uint8_t)( f->timestamp_us & 0xFFu);\n\n /* [15-16] CRC-CCITT over [0..14], big-endian */\n uint16_t crc = dcf_crc16(buf, DCF_FRAME_CRC_COVER);\n buf[15] = (uint8_t)((crc >> 8) & 0xFFu);\n buf[16] = (uint8_t)( crc & 0xFFu);\n\n return buf;\n}\n\n/* ── Decode ──────────────────────────────────────────────────────────────── */\n/*\n * Parse DCF_FRAME_SIZE bytes into a dcf_frame_t.\n * Returns true on success, false if sync byte or CRC is wrong.\n * *out is written only on success; it is not touched on failure.\n */\nstatic inline bool dcf_frame_decode(const uint8_t *buf, dcf_frame_t *out) {\n /* First gate: sync byte */\n if (buf[0] != DCF_SYNC_BYTE) return false;\n\n /* Second gate: CRC over [0..14] must match [15..16] */\n uint16_t crc_calc = dcf_crc16(buf, DCF_FRAME_CRC_COVER);\n uint16_t crc_stored = (uint16_t)(((uint16_t)buf[15] << 8) | buf[16]);\n if (crc_calc != crc_stored) return false;\n\n out->version = (buf[1] & DCF_VERSION_MASK) >> DCF_VERSION_SHIFT;\n out->type = (dcf_frame_type_t)(buf[1] & DCF_TYPE_MASK);\n out->seq = (uint16_t)(((uint16_t)buf[2] << 8) | buf[3]);\n out->src_id = (uint16_t)(((uint16_t)buf[4] << 8) | buf[5]);\n out->dst_id = (uint16_t)(((uint16_t)buf[6] << 8) | buf[7]);\n memcpy(out->payload, buf + 8, 4);\n out->timestamp_us = ((uint32_t)buf[12] << 16)\n | ((uint32_t)buf[13] << 8)\n | (uint32_t)buf[14];\n return true;\n}\n\n/* ── Validate (non-destructive, no decode) ───────────────────────────────── */\n/*\n * Returns true iff buf[0..16] is a well-formed frame.\n * Safe to call on any 17-byte buffer — does not access out-of-bounds memory.\n */\nstatic inline bool dcf_frame_valid(const uint8_t *buf) {\n if (buf[0] != DCF_SYNC_BYTE) return false;\n uint16_t crc_calc = dcf_crc16(buf, DCF_FRAME_CRC_COVER);\n uint16_t crc_stored = (uint16_t)(((uint16_t)buf[15] << 8) | buf[16]);\n return crc_calc == crc_stored;\n}\n\n/* ── Convenience initialiser ─────────────────────────────────────────────── */\n/*\n * Zero-initialise a dcf_frame_t and set the structural fields.\n * Caller must set payload[] and timestamp_us, then call dcf_frame_encode().\n */\nstatic inline void dcf_frame_init(dcf_frame_t *f,\n uint8_t version,\n dcf_frame_type_t type,\n uint16_t seq,\n uint16_t src_id,\n uint16_t dst_id) {\n memset(f, 0, sizeof(*f));\n f->version = version;\n f->type = type;\n f->seq = seq;\n f->src_id = src_id;\n f->dst_id = dst_id;\n}\n\n/* ── Reference test vectors ─────────────────────────────────────────────── */\n/*\n * These byte sequences are used as cross-language test fixtures.\n * The same vectors appear in Haskell FrameSpec.hs (exampleFrame),\n * the Rust #[cfg(test)] block, and the Lisp fiveam dcf-frame-roundtrip-test.\n *\n * Vector A — DATA frame, seq=0x0001, src=0x0001, dst=0xFFFF,\n * payload=0xDEADBEEF, ts=0x000000, version=1\n *\n * Byte: D3 10 00 01 00 01 FF FF DE AD BE EF 00 00 00 XX XX\n * ── ── ───── ───── ───── ────────────── ────── ─────\n * sync flg seq src dst payload ts crc\n *\n * Expected CRC (computed offline): verify with dcf_crc16(buf, 15).\n *\n * To compute the CRC for documentation purposes:\n * uint8_t body[15] = {\n * 0xD3, 0x10, 0x00, 0x01, 0x00, 0x01, 0xFF, 0xFF,\n * 0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x00, 0x00\n * };\n * uint16_t crc = dcf_crc16(body, 15); // → deterministic value\n */\n\n"}
{"messages": [{"role": "system", "content": "You are an expert DCF (DeMoD Communication Framework) wire protocol implementer. You write byte-certified codecs for the 17-byte DeModFrame across multiple languages.\n\nTHE WIRE QUANTUM:\n- 17 bytes: sync(0xD3) | flags[ver|type] | seq | src | dst | payload(4B) | ts24 | crc16\n- Version nibble = 1 (always)\n- CRC-16/CCITT-FALSE over bytes [0..14], anchors: CRC(\"123456789\")=0x29B1, CRC(0^15)=0x4EC3\n- Valid iff sync byte + version nibble + CRC match\n\nCONVENTIONS:\n- Encode: take fields → pack into 17-byte buffer → compute CRC → write CRC at [15..16]\n- Decode: verify sync + version + CRC → unpack fields → return struct or error\n- All implementations MUST produce byte-identical output for identical input\n- Use big-endian for multi-byte fields (network byte order)\n- CRC polynomial: 0x1021, init: 0xFFFF, no final XOR\n- Test against golden_vectors.json (246 vectors: 109 encode + 137 syndrome)\n"}, {"role": "user", "content": "Implement the DCF wire codec in Rust.\n\nSpecification:\n# DCF Wire Quantum — Canonical Specification\n\n**Version 1** · DeMoD LLC · This document is normative.\n\nThe DCF wire protocol has exactly **one** wire format: the 17-byte `DeModFrame`\n(version nibble = 1). All other formats (the proto-message UDP header, the C\nSDK's `DCFMessageHeader`) are **adapters** over this quantum and must be\nexplicitly documented as such.\n\n## Wire Layout\n\n```\n Byte Field Width Description\n ──── ────────── ───── ─────────────────────────────────────────\n 0 sync 1 B Fixed 0xD3 (first validity gate)\n 1 flags 1 B [7:4] version (currently 1) | [3:0] type (0–3)\n 2–3 seq 2 B Big-endian u16, rolling sequence counter\n 4–5 src_id 2 B Big-endian u16, source node ID\n 6–7 dst_id 2 B Big-endian u16, destination (0xFFFF = broadcast)\n 8–11 payload 4 B Application data\n 12–14 timestamp 3 B 24-bit µs offset, big-endian, wraps ~16.7 s\n 15–16 crc16 2 B CRC-16/CCITT-FALSE over bytes [0..14]\n```\n\n**Total: 17 bytes = 136 bits.** The free field data is 108 bits (4+16+16+16+32+24).\n\n## Frame Types\n\n| Value | Name | Purpose |\n|-------|--------|-----------------------------|\n| 0 | DATA | Application payload |\n| 1 | ACK | Acknowledgement |\n| 2 | BEACON | Clock sync / broadcast |\n| 3 | CTRL | Control / fragmented audio |\n\n## Validity\n\nA frame is valid iff:\n1. `frame[0] == 0xD3` (sync byte)\n2. `(frame[1] >> 4) == 1` (version nibble)\n3. `CRC-16/CCITT-FALSE(frame[0..14]) == (frame[15] << 8) | frame[16]` (CRC)\n\nFor a random byte stream, the probability of a 17-byte window passing all three\nchecks is 2⁻²⁸ (Theorem 2.1, `wire_quanta_category.md`).\n\n## CRC-16/CCITT-FALSE\n\n- Polynomial: `0x1021`\n- Init: `0xFFFF`\n- RefIn/RefOut: `false`\n- XorOut: `0x0000`\n- Check value: `CRC(\"123456789\") = 0x29B1`\n\n## Anchors\n\n| Quantity | Value | Source |\n|----------|-------|--------|\n| CRC(\"123456789\") | `0x29B1` | Reference check value |\n| CRC(0¹⁵) | `0x4EC3` | Affine offset c |\n| CRC(exampleFrame body) | `0xA963` | Cross-language anchor |\n| exampleFrame | `D31312340001FFFFDEADBEEFAB12CD24C0` | type=CTRL, seq=0x1234, src=1, dst=0xFFFF, payload=DEADBEEF, ts=AB12CD |\n\n## Formal Properties\n\nThe frame is a **cemented retract** (Theorem 1, `wire_quanta_category.md`):\n- `encode` is injective with a left inverse `decode` (decode∘encode = id)\n- `encode` is a bijection onto the set of valid words\n- `decode` is the unique decoder satisfying the spec\n\nThe 246-vector finite certificate (Theorem 4) proves that any implementation\nmatching the 109 encode-basis + 137 syndrome-basis vectors equals the reference\non all 2¹⁰⁸ frames and classifies all 2¹³⁶ words identically. See\n`Documentation/golden_vectors.json`.\n\n## Reference Implementations\n\n| Language | File | Functions |\n|----------|------|-----------|\n| C | `codec/demod_frame.h` | `dcf_frame_encode`, `dcf_frame_decode`, `dcf_frame_crc` |\n| Rust | `codec/frame.rs` | `Frame::encode`, `Frame::decode` |\n| Python | `python/MCP/wirelab_core.py` | `encode`, `decode`, `syndrome`, `crc16_ccitt` |\n| Lua | `GUI/wirelab.lua` | `encode`, `decode`, `crc16` |\n\n## Certification\n\nTo certify a new SDK against the reference:\n\n```sh\npython3 python/MCP/certify_sdk.py --selftest # reference self-test\npython3 python/MCP/certify_sdk.py --sdk-json SDK.json # certify an external SDK\n```\n\nAll CI gates run `python/MCP/verify_laws.py` and `python/MCP/certify_sdk.py --selftest`.\nUnder Theorem 4, passing the 246-vector test is equivalent to agreement on the\nentire 2¹⁰⁸ × 2¹³⁶ input space.\n\n## Other Wire Formats ARE Adapters\n\n| Format | Status | Relationship to DeModFrame |\n|--------|--------|----------------------------|\n| Proto-message UDP header (C SDK) | Adapter | Must marshal to/from DeModFrame for wire |\n| `DCFMessageHeader` (C SDK) | Internal | In-process struct; must not appear on the wire |\n| Haskell `FrameSpec` | Implemented | `haskell/src/DCF/Transport/FrameSpec.hs` — encodeFrame / decodeFrame |\n\nAny new transport MUST emit and consume DeModFrame v1 on the wire. Internal\nrepresentations are free to differ but MUST be convertible to/from DeModFrame\nwithout loss.\n\nGolden vectors (sample):\n{\n \"encode_basis\": [\n {\n \"input_bits\": \"000000000000000000000000000\",\n \"frame\": \"d310000000000000000000000000005b80\"\n },\n {\n \"input_bit\": 0,\n \"frame\": \"d3110000000000000000000000000020e1\"\n },\n {\n \"input_bit\": 1,\n \"frame\": \"d31200000000000000000000000000ad42\"\n },\n {\n \"input_bit\": 2,\n \"frame\": \"d31400000000000000000000000000a625\"\n },\n {\n \"input_bit\": 3,\n \"frame\": \"d31800000000000000000000000000b0eb\"\n },\n {\n \"input_bit\": 4,\n \"frame\": \"d3100001000000000000000000000058f5\"\n },\n {\n \"input_bit\": 5,\n \"frame\": \"d310000200000000000000000000005d6a\"\n },\n {\n \"input_bit\": 6,\n \"frame\": \"d310000400000000000000000000005654\"\n },\n {\n \"input_bit\": 7,\n \"frame\": \"d310000800000000000000000000004028\"\n },\n {\n \"input_bit\": 8,\n \"frame\": \"d310001000000000000000000000006cd0\"\n }\n ],\n \"syndrome_basis\": [\n {\n \"word\": \"0000000000000000000000000000000000\",\n \"syndrome\": 20163\n },\n {\n \"bit\": 0,\n \"syndrome\": 6865\n },\n {\n \"bit\": 1,\n \"syndrome\": 25802\n },\n {\n \"bit\": 2,\n \"syndrome\": 54231\n },\n {\n \"bit\": 3,\n \"syndrome\": 73\n },\n {\n \"bit\": 4,\n \"syndrome\": 27014\n },\n {\n \"bit\": 5,\n \"syndrome\": 54641\n },\n {\n \"bit\": 6,\n \"syndrome\": 794\n },\n {\n \"bit\": 7,\n \"syndrome\": 57407\n },\n {\n \"bit\": 8,\n \"syndrome\": 6589\n }\n ]\n}\n\nProvide the complete implementation with encode/decode functions."}, {"role": "assistant", "content": "// SPDX-License-Identifier: LGPL-3.0-only\n#[path = \"../frame.rs\"]\nmod frame;\n\npub use frame::{crc16_ccitt, Frame, FrameError, FrameType, BROADCAST, FRAME_SIZE, SYNC_BYTE};\n\npub mod audio;\npub mod fec;\npub mod game;\npub mod mesh;\npub mod modulation;\npub mod monitor;\npub mod snake;\npub mod sstv;\npub mod superpack;\npub mod text;"}], "text": "<|im_start|>\nsystem\nYou are an expert DCF (DeMoD Communication Framework) wire protocol implementer. You write byte-certified codecs for the 17-byte DeModFrame across multiple languages.\n\nTHE WIRE QUANTUM:\n- 17 bytes: sync(0xD3) | flags[ver|type] | seq | src | dst | payload(4B) | ts24 | crc16\n- Version nibble = 1 (always)\n- CRC-16/CCITT-FALSE over bytes [0..14], anchors: CRC(\"123456789\")=0x29B1, CRC(0^15)=0x4EC3\n- Valid iff sync byte + version nibble + CRC match\n\nCONVENTIONS:\n- Encode: take fields → pack into 17-byte buffer → compute CRC → write CRC at [15..16]\n- Decode: verify sync + version + CRC → unpack fields → return struct or error\n- All implementations MUST produce byte-identical output for identical input\n- Use big-endian for multi-byte fields (network byte order)\n- CRC polynomial: 0x1021, init: 0xFFFF, no final XOR\n- Test against golden_vectors.json (246 vectors: 109 encode + 137 syndrome)\n\n<|im_start|>\nuser\nImplement the DCF wire codec in Rust.\n\nSpecification:\n# DCF Wire Quantum — Canonical Specification\n\n**Version 1** · DeMoD LLC · This document is normative.\n\nThe DCF wire protocol has exactly **one** wire format: the 17-byte `DeModFrame`\n(version nibble = 1). All other formats (the proto-message UDP header, the C\nSDK's `DCFMessageHeader`) are **adapters** over this quantum and must be\nexplicitly documented as such.\n\n## Wire Layout\n\n```\n Byte Field Width Description\n ──── ────────── ───── ─────────────────────────────────────────\n 0 sync 1 B Fixed 0xD3 (first validity gate)\n 1 flags 1 B [7:4] version (currently 1) | [3:0] type (0–3)\n 2–3 seq 2 B Big-endian u16, rolling sequence counter\n 4–5 src_id 2 B Big-endian u16, source node ID\n 6–7 dst_id 2 B Big-endian u16, destination (0xFFFF = broadcast)\n 8–11 payload 4 B Application data\n 12–14 timestamp 3 B 24-bit µs offset, big-endian, wraps ~16.7 s\n 15–16 crc16 2 B CRC-16/CCITT-FALSE over bytes [0..14]\n```\n\n**Total: 17 bytes = 136 bits.** The free field data is 108 bits (4+16+16+16+32+24).\n\n## Frame Types\n\n| Value | Name | Purpose |\n|-------|--------|-----------------------------|\n| 0 | DATA | Application payload |\n| 1 | ACK | Acknowledgement |\n| 2 | BEACON | Clock sync / broadcast |\n| 3 | CTRL | Control / fragmented audio |\n\n## Validity\n\nA frame is valid iff:\n1. `frame[0] == 0xD3` (sync byte)\n2. `(frame[1] >> 4) == 1` (version nibble)\n3. `CRC-16/CCITT-FALSE(frame[0..14]) == (frame[15] << 8) | frame[16]` (CRC)\n\nFor a random byte stream, the probability of a 17-byte window passing all three\nchecks is 2⁻²⁸ (Theorem 2.1, `wire_quanta_category.md`).\n\n## CRC-16/CCITT-FALSE\n\n- Polynomial: `0x1021`\n- Init: `0xFFFF`\n- RefIn/RefOut: `false`\n- XorOut: `0x0000`\n- Check value: `CRC(\"123456789\") = 0x29B1`\n\n## Anchors\n\n| Quantity | Value | Source |\n|----------|-------|--------|\n| CRC(\"123456789\") | `0x29B1` | Reference check value |\n| CRC(0¹⁵) | `0x4EC3` | Affine offset c |\n| CRC(exampleFrame body) | `0xA963` | Cross-language anchor |\n| exampleFrame | `D31312340001FFFFDEADBEEFAB12CD24C0` | type=CTRL, seq=0x1234, src=1, dst=0xFFFF, payload=DEADBEEF, ts=AB12CD |\n\n## Formal Properties\n\nThe frame is a **cemented retract** (Theorem 1, `wire_quanta_category.md`):\n- `encode` is injective with a left inverse `decode` (decode∘encode = id)\n- `encode` is a bijection onto the set of valid words\n- `decode` is the unique decoder satisfying the spec\n\nThe 246-vector finite certificate (Theorem 4) proves that any implementation\nmatching the 109 encode-basis + 137 syndrome-basis vectors equals the reference\non all 2¹⁰⁸ frames and classifies all 2¹³⁶ words identically. See\n`Documentation/golden_vectors.json`.\n\n## Reference Implementations\n\n| Language | File | Functions |\n|----------|------|-----------|\n| C | `codec/demod_frame.h` | `dcf_frame_encode`, `dcf_frame_decode`, `dcf_frame_crc` |\n| Rust | `codec/frame.rs` | `Frame::encode`, `Frame::decode` |\n| Python | `python/MCP/wirelab_core.py` | `encode`, `decode`, `syndrome`, `crc16_ccitt` |\n| Lua | `GUI/wirelab.lua` | `encode`, `decode`, `crc16` |\n\n## Certification\n\nTo certify a new SDK against the reference:\n\n```sh\npython3 python/MCP/certify_sdk.py --selftest # reference self-test\npython3 python/MCP/certify_sdk.py --sdk-json SDK.json # certify an external SDK\n```\n\nAll CI gates run `python/MCP/verify_laws.py` and `python/MCP/certify_sdk.py --selftest`.\nUnder Theorem 4, passing the 246-vector test is equivalent to agreement on the\nentire 2¹⁰⁸ × 2¹³⁶ input space.\n\n## Other Wire Formats ARE Adapters\n\n| Format | Status | Relationship to DeModFrame |\n|--------|--------|----------------------------|\n| Proto-message UDP header (C SDK) | Adapter | Must marshal to/from DeModFrame for wire |\n| `DCFMessageHeader` (C SDK) | Internal | In-process struct; must not appear on the wire |\n| Haskell `FrameSpec` | Implemented | `haskell/src/DCF/Transport/FrameSpec.hs` — encodeFrame / decodeFrame |\n\nAny new transport MUST emit and consume DeModFrame v1 on the wire. Internal\nrepresentations are free to differ but MUST be convertible to/from DeModFrame\nwithout loss.\n\nGolden vectors (sample):\n{\n \"encode_basis\": [\n {\n \"input_bits\": \"000000000000000000000000000\",\n \"frame\": \"d310000000000000000000000000005b80\"\n },\n {\n \"input_bit\": 0,\n \"frame\": \"d3110000000000000000000000000020e1\"\n },\n {\n \"input_bit\": 1,\n \"frame\": \"d31200000000000000000000000000ad42\"\n },\n {\n \"input_bit\": 2,\n \"frame\": \"d31400000000000000000000000000a625\"\n },\n {\n \"input_bit\": 3,\n \"frame\": \"d31800000000000000000000000000b0eb\"\n },\n {\n \"input_bit\": 4,\n \"frame\": \"d3100001000000000000000000000058f5\"\n },\n {\n \"input_bit\": 5,\n \"frame\": \"d310000200000000000000000000005d6a\"\n },\n {\n \"input_bit\": 6,\n \"frame\": \"d310000400000000000000000000005654\"\n },\n {\n \"input_bit\": 7,\n \"frame\": \"d310000800000000000000000000004028\"\n },\n {\n \"input_bit\": 8,\n \"frame\": \"d310001000000000000000000000006cd0\"\n }\n ],\n \"syndrome_basis\": [\n {\n \"word\": \"0000000000000000000000000000000000\",\n \"syndrome\": 20163\n },\n {\n \"bit\": 0,\n \"syndrome\": 6865\n },\n {\n \"bit\": 1,\n \"syndrome\": 25802\n },\n {\n \"bit\": 2,\n \"syndrome\": 54231\n },\n {\n \"bit\": 3,\n \"syndrome\": 73\n },\n {\n \"bit\": 4,\n \"syndrome\": 27014\n },\n {\n \"bit\": 5,\n \"syndrome\": 54641\n },\n {\n \"bit\": 6,\n \"syndrome\": 794\n },\n {\n \"bit\": 7,\n \"syndrome\": 57407\n },\n {\n \"bit\": 8,\n \"syndrome\": 6589\n }\n ]\n}\n\nProvide the complete implementation with encode/decode functions.\n<|im_start|>\nassistant\n// SPDX-License-Identifier: LGPL-3.0-only\n#[path = \"../frame.rs\"]\nmod frame;\n\npub use frame::{crc16_ccitt, Frame, FrameError, FrameType, BROADCAST, FRAME_SIZE, SYNC_BYTE};\n\npub mod audio;\npub mod fec;\npub mod game;\npub mod mesh;\npub mod modulation;\npub mod monitor;\npub mod snake;\npub mod sstv;\npub mod superpack;\npub mod text;\n"}
{"messages": [{"role": "system", "content": "You are an expert DCF (DeMoD Communication Framework) wire protocol implementer. You write byte-certified codecs for the 17-byte DeModFrame across multiple languages.\n\nTHE WIRE QUANTUM:\n- 17 bytes: sync(0xD3) | flags[ver|type] | seq | src | dst | payload(4B) | ts24 | crc16\n- Version nibble = 1 (always)\n- CRC-16/CCITT-FALSE over bytes [0..14], anchors: CRC(\"123456789\")=0x29B1, CRC(0^15)=0x4EC3\n- Valid iff sync byte + version nibble + CRC match\n\nCONVENTIONS:\n- Encode: take fields → pack into 17-byte buffer → compute CRC → write CRC at [15..16]\n- Decode: verify sync + version + CRC → unpack fields → return struct or error\n- All implementations MUST produce byte-identical output for identical input\n- Use big-endian for multi-byte fields (network byte order)\n- CRC polynomial: 0x1021, init: 0xFFFF, no final XOR\n- Test against golden_vectors.json (246 vectors: 109 encode + 137 syndrome)\n"}, {"role": "user", "content": "Implement the DCF wire codec in Python.\n\nSpecification:\n# DCF Wire Quantum — Canonical Specification\n\n**Version 1** · DeMoD LLC · This document is normative.\n\nThe DCF wire protocol has exactly **one** wire format: the 17-byte `DeModFrame`\n(version nibble = 1). All other formats (the proto-message UDP header, the C\nSDK's `DCFMessageHeader`) are **adapters** over this quantum and must be\nexplicitly documented as such.\n\n## Wire Layout\n\n```\n Byte Field Width Description\n ──── ────────── ───── ─────────────────────────────────────────\n 0 sync 1 B Fixed 0xD3 (first validity gate)\n 1 flags 1 B [7:4] version (currently 1) | [3:0] type (0–3)\n 2–3 seq 2 B Big-endian u16, rolling sequence counter\n 4–5 src_id 2 B Big-endian u16, source node ID\n 6–7 dst_id 2 B Big-endian u16, destination (0xFFFF = broadcast)\n 8–11 payload 4 B Application data\n 12–14 timestamp 3 B 24-bit µs offset, big-endian, wraps ~16.7 s\n 15–16 crc16 2 B CRC-16/CCITT-FALSE over bytes [0..14]\n```\n\n**Total: 17 bytes = 136 bits.** The free field data is 108 bits (4+16+16+16+32+24).\n\n## Frame Types\n\n| Value | Name | Purpose |\n|-------|--------|-----------------------------|\n| 0 | DATA | Application payload |\n| 1 | ACK | Acknowledgement |\n| 2 | BEACON | Clock sync / broadcast |\n| 3 | CTRL | Control / fragmented audio |\n\n## Validity\n\nA frame is valid iff:\n1. `frame[0] == 0xD3` (sync byte)\n2. `(frame[1] >> 4) == 1` (version nibble)\n3. `CRC-16/CCITT-FALSE(frame[0..14]) == (frame[15] << 8) | frame[16]` (CRC)\n\nFor a random byte stream, the probability of a 17-byte window passing all three\nchecks is 2⁻²⁸ (Theorem 2.1, `wire_quanta_category.md`).\n\n## CRC-16/CCITT-FALSE\n\n- Polynomial: `0x1021`\n- Init: `0xFFFF`\n- RefIn/RefOut: `false`\n- XorOut: `0x0000`\n- Check value: `CRC(\"123456789\") = 0x29B1`\n\n## Anchors\n\n| Quantity | Value | Source |\n|----------|-------|--------|\n| CRC(\"123456789\") | `0x29B1` | Reference check value |\n| CRC(0¹⁵) | `0x4EC3` | Affine offset c |\n| CRC(exampleFrame body) | `0xA963` | Cross-language anchor |\n| exampleFrame | `D31312340001FFFFDEADBEEFAB12CD24C0` | type=CTRL, seq=0x1234, src=1, dst=0xFFFF, payload=DEADBEEF, ts=AB12CD |\n\n## Formal Properties\n\nThe frame is a **cemented retract** (Theorem 1, `wire_quanta_category.md`):\n- `encode` is injective with a left inverse `decode` (decode∘encode = id)\n- `encode` is a bijection onto the set of valid words\n- `decode` is the unique decoder satisfying the spec\n\nThe 246-vector finite certificate (Theorem 4) proves that any implementation\nmatching the 109 encode-basis + 137 syndrome-basis vectors equals the reference\non all 2¹⁰⁸ frames and classifies all 2¹³⁶ words identically. See\n`Documentation/golden_vectors.json`.\n\n## Reference Implementations\n\n| Language | File | Functions |\n|----------|------|-----------|\n| C | `codec/demod_frame.h` | `dcf_frame_encode`, `dcf_frame_decode`, `dcf_frame_crc` |\n| Rust | `codec/frame.rs` | `Frame::encode`, `Frame::decode` |\n| Python | `python/MCP/wirelab_core.py` | `encode`, `decode`, `syndrome`, `crc16_ccitt` |\n| Lua | `GUI/wirelab.lua` | `encode`, `decode`, `crc16` |\n\n## Certification\n\nTo certify a new SDK against the reference:\n\n```sh\npython3 python/MCP/certify_sdk.py --selftest # reference self-test\npython3 python/MCP/certify_sdk.py --sdk-json SDK.json # certify an external SDK\n```\n\nAll CI gates run `python/MCP/verify_laws.py` and `python/MCP/certify_sdk.py --selftest`.\nUnder Theorem 4, passing the 246-vector test is equivalent to agreement on the\nentire 2¹⁰⁸ × 2¹³⁶ input space.\n\n## Other Wire Formats ARE Adapters\n\n| Format | Status | Relationship to DeModFrame |\n|--------|--------|----------------------------|\n| Proto-message UDP header (C SDK) | Adapter | Must marshal to/from DeModFrame for wire |\n| `DCFMessageHeader` (C SDK) | Internal | In-process struct; must not appear on the wire |\n| Haskell `FrameSpec` | Implemented | `haskell/src/DCF/Transport/FrameSpec.hs` — encodeFrame / decodeFrame |\n\nAny new transport MUST emit and consume DeModFrame v1 on the wire. Internal\nrepresentations are free to differ but MUST be convertible to/from DeModFrame\nwithout loss.\n\nGolden vectors (sample):\n{\n \"encode_basis\": [\n {\n \"input_bits\": \"000000000000000000000000000\",\n \"frame\": \"d310000000000000000000000000005b80\"\n },\n {\n \"input_bit\": 0,\n \"frame\": \"d3110000000000000000000000000020e1\"\n },\n {\n \"input_bit\": 1,\n \"frame\": \"d31200000000000000000000000000ad42\"\n },\n {\n \"input_bit\": 2,\n \"frame\": \"d31400000000000000000000000000a625\"\n },\n {\n \"input_bit\": 3,\n \"frame\": \"d31800000000000000000000000000b0eb\"\n },\n {\n \"input_bit\": 4,\n \"frame\": \"d3100001000000000000000000000058f5\"\n },\n {\n \"input_bit\": 5,\n \"frame\": \"d310000200000000000000000000005d6a\"\n },\n {\n \"input_bit\": 6,\n \"frame\": \"d310000400000000000000000000005654\"\n },\n {\n \"input_bit\": 7,\n \"frame\": \"d310000800000000000000000000004028\"\n },\n {\n \"input_bit\": 8,\n \"frame\": \"d310001000000000000000000000006cd0\"\n }\n ],\n \"syndrome_basis\": [\n {\n \"word\": \"0000000000000000000000000000000000\",\n \"syndrome\": 20163\n },\n {\n \"bit\": 0,\n \"syndrome\": 6865\n },\n {\n \"bit\": 1,\n \"syndrome\": 25802\n },\n {\n \"bit\": 2,\n \"syndrome\": 54231\n },\n {\n \"bit\": 3,\n \"syndrome\": 73\n },\n {\n \"bit\": 4,\n \"syndrome\": 27014\n },\n {\n \"bit\": 5,\n \"syndrome\": 54641\n },\n {\n \"bit\": 6,\n \"syndrome\": 794\n },\n {\n \"bit\": 7,\n \"syndrome\": 57407\n },\n {\n \"bit\": 8,\n \"syndrome\": 6589\n }\n ]\n}\n\nProvide the complete implementation with encode/decode functions."}, {"role": "assistant", "content": "# SPDX-License-Identifier: LGPL-3.0-only\n\"\"\"DCF WireLab core — reference codec for the 17-byte DeModFrame (wire quantum).\nLayout (big-endian):\n [0] sync = 0xD3\n [1] flags: version[7:4]=1 | frame_type[3:0]\n [2-3] seq u16\n [4-5] src u16\n [6-7] dst u16\n [8-11] payload 4 bytes\n [12-14] ts_us u24\n [15-16] CRC-16/CCITT-FALSE over bytes [0..14]\n\"\"\"\nSYNC, VERSION, FRAME_LEN = 0xD3, 1, 17\nFRAME_TYPES = {0: \"FData\", 1: \"FAck\", 2: \"FBeacon\", 3: \"FCtrl\"}\n\ndef crc16_ccitt(data: bytes) -> int:\n crc = 0xFFFF\n for b in data:\n crc ^= b << 8\n for _ in range(8):\n crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF\n return crc\n\ndef encode(frame_type: int, seq: int, src: int, dst: int, payload: bytes, ts_us: int) -> bytes:\n if not (0 <= frame_type < 16): raise ValueError(\"frame_type must be a nibble\")\n if len(payload) != 4: raise ValueError(\"payload must be exactly 4 bytes\")\n if not (0 <= seq < 1 << 16 and 0 <= src < 1 << 16 and 0 <= dst < 1 << 16):\n raise ValueError(\"seq/src/dst must be u16\")\n b = bytearray(FRAME_LEN)\n b[0] = SYNC\n b[1] = (VERSION << 4) | frame_type\n b[2:4] = seq.to_bytes(2, \"big\"); b[4:6] = src.to_bytes(2, \"big\"); b[6:8] = dst.to_bytes(2, \"big\")\n b[8:12] = payload\n b[12:15] = (ts_us & 0xFFFFFF).to_bytes(3, \"big\")\n b[15:17] = crc16_ccitt(bytes(b[:15])).to_bytes(2, \"big\")\n return bytes(b)\n\ndef syndrome(word: bytes) -> int:\n \"\"\"Affine validity map L: B^17 -> B^16; word valid w.r.t. CRC iff syndrome==0.\"\"\"\n if len(word) != FRAME_LEN: raise ValueError(\"need 17 bytes\")\n return crc16_ccitt(word[:15]) ^ int.from_bytes(word[15:17], \"big\")\n\ndef decode(word: bytes):\n \"\"\"Returns (fields dict) or raises ValueError with reason.\"\"\"\n if len(word) != FRAME_LEN: raise ValueError(f\"length {len(word)} != 17\")\n if word[0] != SYNC: raise ValueError(\"bad sync byte\")\n if word[1] >> 4 != VERSION: raise ValueError(\"bad version nibble\")\n if syndrome(word) != 0: raise ValueError(\"CRC mismatch\")\n return {\n \"frame_type\": word[1] & 0x0F,\n \"frame_type_name\": FRAME_TYPES.get(word[1] & 0x0F, f\"0x{word[1] & 0x0F:X}\"),\n \"seq\": int.from_bytes(word[2:4], \"big\"),\n \"src\": int.from_bytes(word[4:6], \"big\"),\n \"dst\": int.from_bytes(word[6:8], \"big\"),\n \"payload\": word[8:12].hex(),\n \"ts_us\": int.from_bytes(word[12:15], \"big\"),\n \"crc\": int.from_bytes(word[15:17], \"big\"),\n }\n"}], "text": "<|im_start|>\nsystem\nYou are an expert DCF (DeMoD Communication Framework) wire protocol implementer. You write byte-certified codecs for the 17-byte DeModFrame across multiple languages.\n\nTHE WIRE QUANTUM:\n- 17 bytes: sync(0xD3) | flags[ver|type] | seq | src | dst | payload(4B) | ts24 | crc16\n- Version nibble = 1 (always)\n- CRC-16/CCITT-FALSE over bytes [0..14], anchors: CRC(\"123456789\")=0x29B1, CRC(0^15)=0x4EC3\n- Valid iff sync byte + version nibble + CRC match\n\nCONVENTIONS:\n- Encode: take fields → pack into 17-byte buffer → compute CRC → write CRC at [15..16]\n- Decode: verify sync + version + CRC → unpack fields → return struct or error\n- All implementations MUST produce byte-identical output for identical input\n- Use big-endian for multi-byte fields (network byte order)\n- CRC polynomial: 0x1021, init: 0xFFFF, no final XOR\n- Test against golden_vectors.json (246 vectors: 109 encode + 137 syndrome)\n\n<|im_start|>\nuser\nImplement the DCF wire codec in Python.\n\nSpecification:\n# DCF Wire Quantum — Canonical Specification\n\n**Version 1** · DeMoD LLC · This document is normative.\n\nThe DCF wire protocol has exactly **one** wire format: the 17-byte `DeModFrame`\n(version nibble = 1). All other formats (the proto-message UDP header, the C\nSDK's `DCFMessageHeader`) are **adapters** over this quantum and must be\nexplicitly documented as such.\n\n## Wire Layout\n\n```\n Byte Field Width Description\n ──── ────────── ───── ─────────────────────────────────────────\n 0 sync 1 B Fixed 0xD3 (first validity gate)\n 1 flags 1 B [7:4] version (currently 1) | [3:0] type (0–3)\n 2–3 seq 2 B Big-endian u16, rolling sequence counter\n 4–5 src_id 2 B Big-endian u16, source node ID\n 6–7 dst_id 2 B Big-endian u16, destination (0xFFFF = broadcast)\n 8–11 payload 4 B Application data\n 12–14 timestamp 3 B 24-bit µs offset, big-endian, wraps ~16.7 s\n 15–16 crc16 2 B CRC-16/CCITT-FALSE over bytes [0..14]\n```\n\n**Total: 17 bytes = 136 bits.** The free field data is 108 bits (4+16+16+16+32+24).\n\n## Frame Types\n\n| Value | Name | Purpose |\n|-------|--------|-----------------------------|\n| 0 | DATA | Application payload |\n| 1 | ACK | Acknowledgement |\n| 2 | BEACON | Clock sync / broadcast |\n| 3 | CTRL | Control / fragmented audio |\n\n## Validity\n\nA frame is valid iff:\n1. `frame[0] == 0xD3` (sync byte)\n2. `(frame[1] >> 4) == 1` (version nibble)\n3. `CRC-16/CCITT-FALSE(frame[0..14]) == (frame[15] << 8) | frame[16]` (CRC)\n\nFor a random byte stream, the probability of a 17-byte window passing all three\nchecks is 2⁻²⁸ (Theorem 2.1, `wire_quanta_category.md`).\n\n## CRC-16/CCITT-FALSE\n\n- Polynomial: `0x1021`\n- Init: `0xFFFF`\n- RefIn/RefOut: `false`\n- XorOut: `0x0000`\n- Check value: `CRC(\"123456789\") = 0x29B1`\n\n## Anchors\n\n| Quantity | Value | Source |\n|----------|-------|--------|\n| CRC(\"123456789\") | `0x29B1` | Reference check value |\n| CRC(0¹⁵) | `0x4EC3` | Affine offset c |\n| CRC(exampleFrame body) | `0xA963` | Cross-language anchor |\n| exampleFrame | `D31312340001FFFFDEADBEEFAB12CD24C0` | type=CTRL, seq=0x1234, src=1, dst=0xFFFF, payload=DEADBEEF, ts=AB12CD |\n\n## Formal Properties\n\nThe frame is a **cemented retract** (Theorem 1, `wire_quanta_category.md`):\n- `encode` is injective with a left inverse `decode` (decode∘encode = id)\n- `encode` is a bijection onto the set of valid words\n- `decode` is the unique decoder satisfying the spec\n\nThe 246-vector finite certificate (Theorem 4) proves that any implementation\nmatching the 109 encode-basis + 137 syndrome-basis vectors equals the reference\non all 2¹⁰⁸ frames and classifies all 2¹³⁶ words identically. See\n`Documentation/golden_vectors.json`.\n\n## Reference Implementations\n\n| Language | File | Functions |\n|----------|------|-----------|\n| C | `codec/demod_frame.h` | `dcf_frame_encode`, `dcf_frame_decode`, `dcf_frame_crc` |\n| Rust | `codec/frame.rs` | `Frame::encode`, `Frame::decode` |\n| Python | `python/MCP/wirelab_core.py` | `encode`, `decode`, `syndrome`, `crc16_ccitt` |\n| Lua | `GUI/wirelab.lua` | `encode`, `decode`, `crc16` |\n\n## Certification\n\nTo certify a new SDK against the reference:\n\n```sh\npython3 python/MCP/certify_sdk.py --selftest # reference self-test\npython3 python/MCP/certify_sdk.py --sdk-json SDK.json # certify an external SDK\n```\n\nAll CI gates run `python/MCP/verify_laws.py` and `python/MCP/certify_sdk.py --selftest`.\nUnder Theorem 4, passing the 246-vector test is equivalent to agreement on the\nentire 2¹⁰⁸ × 2¹³⁶ input space.\n\n## Other Wire Formats ARE Adapters\n\n| Format | Status | Relationship to DeModFrame |\n|--------|--------|----------------------------|\n| Proto-message UDP header (C SDK) | Adapter | Must marshal to/from DeModFrame for wire |\n| `DCFMessageHeader` (C SDK) | Internal | In-process struct; must not appear on the wire |\n| Haskell `FrameSpec` | Implemented | `haskell/src/DCF/Transport/FrameSpec.hs` — encodeFrame / decodeFrame |\n\nAny new transport MUST emit and consume DeModFrame v1 on the wire. Internal\nrepresentations are free to differ but MUST be convertible to/from DeModFrame\nwithout loss.\n\nGolden vectors (sample):\n{\n \"encode_basis\": [\n {\n \"input_bits\": \"000000000000000000000000000\",\n \"frame\": \"d310000000000000000000000000005b80\"\n },\n {\n \"input_bit\": 0,\n \"frame\": \"d3110000000000000000000000000020e1\"\n },\n {\n \"input_bit\": 1,\n \"frame\": \"d31200000000000000000000000000ad42\"\n },\n {\n \"input_bit\": 2,\n \"frame\": \"d31400000000000000000000000000a625\"\n },\n {\n \"input_bit\": 3,\n \"frame\": \"d31800000000000000000000000000b0eb\"\n },\n {\n \"input_bit\": 4,\n \"frame\": \"d3100001000000000000000000000058f5\"\n },\n {\n \"input_bit\": 5,\n \"frame\": \"d310000200000000000000000000005d6a\"\n },\n {\n \"input_bit\": 6,\n \"frame\": \"d310000400000000000000000000005654\"\n },\n {\n \"input_bit\": 7,\n \"frame\": \"d310000800000000000000000000004028\"\n },\n {\n \"input_bit\": 8,\n \"frame\": \"d310001000000000000000000000006cd0\"\n }\n ],\n \"syndrome_basis\": [\n {\n \"word\": \"0000000000000000000000000000000000\",\n \"syndrome\": 20163\n },\n {\n \"bit\": 0,\n \"syndrome\": 6865\n },\n {\n \"bit\": 1,\n \"syndrome\": 25802\n },\n {\n \"bit\": 2,\n \"syndrome\": 54231\n },\n {\n \"bit\": 3,\n \"syndrome\": 73\n },\n {\n \"bit\": 4,\n \"syndrome\": 27014\n },\n {\n \"bit\": 5,\n \"syndrome\": 54641\n },\n {\n \"bit\": 6,\n \"syndrome\": 794\n },\n {\n \"bit\": 7,\n \"syndrome\": 57407\n },\n {\n \"bit\": 8,\n \"syndrome\": 6589\n }\n ]\n}\n\nProvide the complete implementation with encode/decode functions.\n<|im_start|>\nassistant\n# SPDX-License-Identifier: LGPL-3.0-only\n\"\"\"DCF WireLab core — reference codec for the 17-byte DeModFrame (wire quantum).\nLayout (big-endian):\n [0] sync = 0xD3\n [1] flags: version[7:4]=1 | frame_type[3:0]\n [2-3] seq u16\n [4-5] src u16\n [6-7] dst u16\n [8-11] payload 4 bytes\n [12-14] ts_us u24\n [15-16] CRC-16/CCITT-FALSE over bytes [0..14]\n\"\"\"\nSYNC, VERSION, FRAME_LEN = 0xD3, 1, 17\nFRAME_TYPES = {0: \"FData\", 1: \"FAck\", 2: \"FBeacon\", 3: \"FCtrl\"}\n\ndef crc16_ccitt(data: bytes) -> int:\n crc = 0xFFFF\n for b in data:\n crc ^= b << 8\n for _ in range(8):\n crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF\n return crc\n\ndef encode(frame_type: int, seq: int, src: int, dst: int, payload: bytes, ts_us: int) -> bytes:\n if not (0 <= frame_type < 16): raise ValueError(\"frame_type must be a nibble\")\n if len(payload) != 4: raise ValueError(\"payload must be exactly 4 bytes\")\n if not (0 <= seq < 1 << 16 and 0 <= src < 1 << 16 and 0 <= dst < 1 << 16):\n raise ValueError(\"seq/src/dst must be u16\")\n b = bytearray(FRAME_LEN)\n b[0] = SYNC\n b[1] = (VERSION << 4) | frame_type\n b[2:4] = seq.to_bytes(2, \"big\"); b[4:6] = src.to_bytes(2, \"big\"); b[6:8] = dst.to_bytes(2, \"big\")\n b[8:12] = payload\n b[12:15] = (ts_us & 0xFFFFFF).to_bytes(3, \"big\")\n b[15:17] = crc16_ccitt(bytes(b[:15])).to_bytes(2, \"big\")\n return bytes(b)\n\ndef syndrome(word: bytes) -> int:\n \"\"\"Affine validity map L: B^17 -> B^16; word valid w.r.t. CRC iff syndrome==0.\"\"\"\n if len(word) != FRAME_LEN: raise ValueError(\"need 17 bytes\")\n return crc16_ccitt(word[:15]) ^ int.from_bytes(word[15:17], \"big\")\n\ndef decode(word: bytes):\n \"\"\"Returns (fields dict) or raises ValueError with reason.\"\"\"\n if len(word) != FRAME_LEN: raise ValueError(f\"length {len(word)} != 17\")\n if word[0] != SYNC: raise ValueError(\"bad sync byte\")\n if word[1] >> 4 != VERSION: raise ValueError(\"bad version nibble\")\n if syndrome(word) != 0: raise ValueError(\"CRC mismatch\")\n return {\n \"frame_type\": word[1] & 0x0F,\n \"frame_type_name\": FRAME_TYPES.get(word[1] & 0x0F, f\"0x{word[1] & 0x0F:X}\"),\n \"seq\": int.from_bytes(word[2:4], \"big\"),\n \"src\": int.from_bytes(word[4:6], \"big\"),\n \"dst\": int.from_bytes(word[6:8], \"big\"),\n \"payload\": word[8:12].hex(),\n \"ts_us\": int.from_bytes(word[12:15], \"big\"),\n \"crc\": int.from_bytes(word[15:17], \"big\"),\n }\n\n"}
{"messages": [{"role": "system", "content": "You are an expert DCF (DeMoD Communication Framework) wire protocol implementer. You write byte-certified codecs for the 17-byte DeModFrame across multiple languages.\n\nTHE WIRE QUANTUM:\n- 17 bytes: sync(0xD3) | flags[ver|type] | seq | src | dst | payload(4B) | ts24 | crc16\n- Version nibble = 1 (always)\n- CRC-16/CCITT-FALSE over bytes [0..14], anchors: CRC(\"123456789\")=0x29B1, CRC(0^15)=0x4EC3\n- Valid iff sync byte + version nibble + CRC match\n\nCONVENTIONS:\n- Encode: take fields → pack into 17-byte buffer → compute CRC → write CRC at [15..16]\n- Decode: verify sync + version + CRC → unpack fields → return struct or error\n- All implementations MUST produce byte-identical output for identical input\n- Use big-endian for multi-byte fields (network byte order)\n- CRC polynomial: 0x1021, init: 0xFFFF, no final XOR\n- Test against golden_vectors.json (246 vectors: 109 encode + 137 syndrome)\n"}, {"role": "user", "content": "Implement the DCF wire codec in Lua.\n\nSpecification:\n# DCF Wire Quantum — Canonical Specification\n\n**Version 1** · DeMoD LLC · This document is normative.\n\nThe DCF wire protocol has exactly **one** wire format: the 17-byte `DeModFrame`\n(version nibble = 1). All other formats (the proto-message UDP header, the C\nSDK's `DCFMessageHeader`) are **adapters** over this quantum and must be\nexplicitly documented as such.\n\n## Wire Layout\n\n```\n Byte Field Width Description\n ──── ────────── ───── ─────────────────────────────────────────\n 0 sync 1 B Fixed 0xD3 (first validity gate)\n 1 flags 1 B [7:4] version (currently 1) | [3:0] type (0–3)\n 2–3 seq 2 B Big-endian u16, rolling sequence counter\n 4–5 src_id 2 B Big-endian u16, source node ID\n 6–7 dst_id 2 B Big-endian u16, destination (0xFFFF = broadcast)\n 8–11 payload 4 B Application data\n 12–14 timestamp 3 B 24-bit µs offset, big-endian, wraps ~16.7 s\n 15–16 crc16 2 B CRC-16/CCITT-FALSE over bytes [0..14]\n```\n\n**Total: 17 bytes = 136 bits.** The free field data is 108 bits (4+16+16+16+32+24).\n\n## Frame Types\n\n| Value | Name | Purpose |\n|-------|--------|-----------------------------|\n| 0 | DATA | Application payload |\n| 1 | ACK | Acknowledgement |\n| 2 | BEACON | Clock sync / broadcast |\n| 3 | CTRL | Control / fragmented audio |\n\n## Validity\n\nA frame is valid iff:\n1. `frame[0] == 0xD3` (sync byte)\n2. `(frame[1] >> 4) == 1` (version nibble)\n3. `CRC-16/CCITT-FALSE(frame[0..14]) == (frame[15] << 8) | frame[16]` (CRC)\n\nFor a random byte stream, the probability of a 17-byte window passing all three\nchecks is 2⁻²⁸ (Theorem 2.1, `wire_quanta_category.md`).\n\n## CRC-16/CCITT-FALSE\n\n- Polynomial: `0x1021`\n- Init: `0xFFFF`\n- RefIn/RefOut: `false`\n- XorOut: `0x0000`\n- Check value: `CRC(\"123456789\") = 0x29B1`\n\n## Anchors\n\n| Quantity | Value | Source |\n|----------|-------|--------|\n| CRC(\"123456789\") | `0x29B1` | Reference check value |\n| CRC(0¹⁵) | `0x4EC3` | Affine offset c |\n| CRC(exampleFrame body) | `0xA963` | Cross-language anchor |\n| exampleFrame | `D31312340001FFFFDEADBEEFAB12CD24C0` | type=CTRL, seq=0x1234, src=1, dst=0xFFFF, payload=DEADBEEF, ts=AB12CD |\n\n## Formal Properties\n\nThe frame is a **cemented retract** (Theorem 1, `wire_quanta_category.md`):\n- `encode` is injective with a left inverse `decode` (decode∘encode = id)\n- `encode` is a bijection onto the set of valid words\n- `decode` is the unique decoder satisfying the spec\n\nThe 246-vector finite certificate (Theorem 4) proves that any implementation\nmatching the 109 encode-basis + 137 syndrome-basis vectors equals the reference\non all 2¹⁰⁸ frames and classifies all 2¹³⁶ words identically. See\n`Documentation/golden_vectors.json`.\n\n## Reference Implementations\n\n| Language | File | Functions |\n|----------|------|-----------|\n| C | `codec/demod_frame.h` | `dcf_frame_encode`, `dcf_frame_decode`, `dcf_frame_crc` |\n| Rust | `codec/frame.rs` | `Frame::encode`, `Frame::decode` |\n| Python | `python/MCP/wirelab_core.py` | `encode`, `decode`, `syndrome`, `crc16_ccitt` |\n| Lua | `GUI/wirelab.lua` | `encode`, `decode`, `crc16` |\n\n## Certification\n\nTo certify a new SDK against the reference:\n\n```sh\npython3 python/MCP/certify_sdk.py --selftest # reference self-test\npython3 python/MCP/certify_sdk.py --sdk-json SDK.json # certify an external SDK\n```\n\nAll CI gates run `python/MCP/verify_laws.py` and `python/MCP/certify_sdk.py --selftest`.\nUnder Theorem 4, passing the 246-vector test is equivalent to agreement on the\nentire 2¹⁰⁸ × 2¹³⁶ input space.\n\n## Other Wire Formats ARE Adapters\n\n| Format | Status | Relationship to DeModFrame |\n|--------|--------|----------------------------|\n| Proto-message UDP header (C SDK) | Adapter | Must marshal to/from DeModFrame for wire |\n| `DCFMessageHeader` (C SDK) | Internal | In-process struct; must not appear on the wire |\n| Haskell `FrameSpec` | Implemented | `haskell/src/DCF/Transport/FrameSpec.hs` — encodeFrame / decodeFrame |\n\nAny new transport MUST emit and consume DeModFrame v1 on the wire. Internal\nrepresentations are free to differ but MUST be convertible to/from DeModFrame\nwithout loss.\n\nGolden vectors (sample):\n{\n \"encode_basis\": [\n {\n \"input_bits\": \"000000000000000000000000000\",\n \"frame\": \"d310000000000000000000000000005b80\"\n },\n {\n \"input_bit\": 0,\n \"frame\": \"d3110000000000000000000000000020e1\"\n },\n {\n \"input_bit\": 1,\n \"frame\": \"d31200000000000000000000000000ad42\"\n },\n {\n \"input_bit\": 2,\n \"frame\": \"d31400000000000000000000000000a625\"\n },\n {\n \"input_bit\": 3,\n \"frame\": \"d31800000000000000000000000000b0eb\"\n },\n {\n \"input_bit\": 4,\n \"frame\": \"d3100001000000000000000000000058f5\"\n },\n {\n \"input_bit\": 5,\n \"frame\": \"d310000200000000000000000000005d6a\"\n },\n {\n \"input_bit\": 6,\n \"frame\": \"d310000400000000000000000000005654\"\n },\n {\n \"input_bit\": 7,\n \"frame\": \"d310000800000000000000000000004028\"\n },\n {\n \"input_bit\": 8,\n \"frame\": \"d310001000000000000000000000006cd0\"\n }\n ],\n \"syndrome_basis\": [\n {\n \"word\": \"0000000000000000000000000000000000\",\n \"syndrome\": 20163\n },\n {\n \"bit\": 0,\n \"syndrome\": 6865\n },\n {\n \"bit\": 1,\n \"syndrome\": 25802\n },\n {\n \"bit\": 2,\n \"syndrome\": 54231\n },\n {\n \"bit\": 3,\n \"syndrome\": 73\n },\n {\n \"bit\": 4,\n \"syndrome\": 27014\n },\n {\n \"bit\": 5,\n \"syndrome\": 54641\n },\n {\n \"bit\": 6,\n \"syndrome\": 794\n },\n {\n \"bit\": 7,\n \"syndrome\": 57407\n },\n {\n \"bit\": 8,\n \"syndrome\": 6589\n }\n ]\n}\n\nProvide the complete implementation with encode/decode functions."}, {"role": "assistant", "content": "-- ============================================================================\n-- DCF WIRELAB — DeMoD UI front panel for the 17-byte wire quantum (DeModFrame)\n-- Run: ./demod-ui wirelab.lua\n--\n-- Pure-Lua reference codec (CRC-16/CCITT-FALSE, poly 0x1021, init 0xFFFF),\n-- bit-identical to wirelab_core.py / the fixed Punctim crc16-ccitt / the\n-- Haskell crc16ccitt. Self-certifies on launch against the golden anchors:\n-- crc(\"123456789\") = 0x29B1\n-- crc(exampleFrame body) = 0xA963\n-- full exampleFrame = D31012340001FFFFDEADBEEFAB12CDA963\n-- Companion: wirelab_mcp.py (agent face), golden_vectors.json (certificate).\n-- ============================================================================\n\n-- ---------------------------------------------------------------- codec ----\nlocal SYNC, VERSION, FRAME_LEN = 0xD3, 1, 17\n\nlocal function crc16(bytes, n)\n local crc = 0xFFFF\n for i = 1, n do\n crc = (crc ~ ((bytes[i] & 0xFF) << 8)) & 0xFFFF\n for _ = 1, 8 do\n if (crc & 0x8000) ~= 0 then crc = ((crc << 1) ~ 0x1021) & 0xFFFF\n else crc = (crc << 1) & 0xFFFF end\n end\n end\n return crc\nend\n\nlocal function encode(ftype, seq, src, dst, payload, ts)\n local w = {}\n w[1] = SYNC\n w[2] = ((VERSION & 0xF) << 4) | (ftype & 0xF)\n w[3] = (seq >> 8) & 0xFF; w[4] = seq & 0xFF\n w[5] = (src >> 8) & 0xFF; w[6] = src & 0xFF\n w[7] = (dst >> 8) & 0xFF; w[8] = dst & 0xFF\n for i = 1, 4 do w[8 + i] = payload[i] & 0xFF end\n w[13] = (ts >> 16) & 0xFF; w[14] = (ts >> 8) & 0xFF; w[15] = ts & 0xFF\n local c = crc16(w, 15)\n w[16] = (c >> 8) & 0xFF; w[17] = c & 0xFF\n return w\nend\n\n-- returns fields-table or nil, reason\nlocal function decode(w)\n if #w ~= FRAME_LEN then return nil, (\"length %d != 17\"):format(#w) end\n if w[1] ~= SYNC then return nil, \"bad sync byte\" end\n if (w[2] >> 4) ~= VERSION then return nil, \"bad version nibble\" end\n if crc16(w, 15) ~= ((w[16] << 8) | w[17]) then return nil, \"CRC mismatch\" end\n return { ftype = w[2] & 0xF,\n seq = (w[3] << 8) | w[4], src = (w[5] << 8) | w[6],\n dst = (w[7] << 8) | w[8],\n payload = { w[9], w[10], w[11], w[12] },\n ts = (w[13] << 16) | (w[14] << 8) | w[15],\n crc = (w[16] << 8) | w[17] }\nend\n\nlocal function frame_to_hex(w)\n local t = {}\n for i = 1, #w do t[i] = (\"%02X\"):format(w[i]) end\n return table.concat(t)\nend\n\nlocal function hex_to_frame(s)\n s = s:gsub(\"[%s:,]\", \"\"):gsub(\"0[xX]\", \"\")\n if #s ~= 34 or s:find(\"%X\") then return nil end\n local w = {}\n for i = 1, 17 do w[i] = tonumber(s:sub(i * 2 - 1, i * 2), 16) end\n return w\nend\n\n-- ------------------------------------------------------------ self-cert ----\nlocal CERTIFIED = false\ndo\n local anchor = {}\n for i = 1, 9 do anchor[i] = string.byte(\"123456789\", i) end\n local ex = encode(0, 0x1234, 0x0001, 0xFFFF, {0xDE, 0xAD, 0xBE, 0xEF}, 0xAB12CD)\n CERTIFIED = crc16(anchor, 9) == 0x29B1\n and frame_to_hex(ex) == \"D31012340001FFFFDEADBEEFAB12CDA963\"\n and decode(ex) ~= nil\nend\n\n-- ------------------------------------------------------------------- ui ----\nlocal TYPE_NAMES = { [0] = \"FData\", [1] = \"FAck\", [2] = \"FBeacon\", [3] = \"FCtrl\" }\nlocal S = { frame = nil, fields = nil, status = \"\", lamp = \"idle\", audit = nil }\n\nlocal root = dm.root()\nroot:set_layout(\"vbox\", 6, 12)\n\nlocal title = dm.label(\"title\", \"DCF WIRELAB // 17-BYTE WIRE QUANTUM\")\ntitle:set_fg(0x8B, 0x5C, 0xF6); title:set_bounds(0, 0, 0, 28)\nroot:add_child(title)\n\nlocal sub = dm.label(\"sub\", CERTIFIED and \"codec CERTIFIED: 0x29B1 / 0xA963 anchors hold\"\n or \"CODEC SELF-TEST FAILED — do not trust output\")\nsub:set_fg(CERTIFIED and 0x4C or 0xFF, CERTIFIED and 0xFF or 0x4C,\n CERTIFIED and 0x82 or 0x6A)\nsub:set_bounds(0, 0, 0, 18)\nroot:add_child(sub)\n\n-- field inputs ---------------------------------------------------------------\nlocal row1 = dm.panel(\"row1\"); row1:set_layout(\"hbox\", 6, 4); row1:set_bounds(0, 0, 0, 40)\nrow1:set_bg(0x1A, 0x1A, 0x2E)\nlocal dd_type = dm.dropdown(\"ftype\", \"type\")\nfor i = 0, 3 do dd_type:add_item((\"%d %s\"):format(i, TYPE_NAMES[i])) end\nlocal in_seq = dm.text_input(\"seq\", \"seq hex (1234)\")\nlocal in_src = dm.text_input(\"src\", \"src hex (0001)\")\nlocal in_dst = dm.text_input(\"dst\", \"dst hex (FFFF)\")\nfor _, w in ipairs({ dd_type, in_seq, in_src, in_dst }) do\n w:set_bounds(0, 0, 150, 32); row1:add_child(w)\nend\nroot:add_child(row1)\n\nlocal row2 = dm.panel(\"row2\"); row2:set_layout(\"hbox\", 6, 4); row2:set_bounds(0, 0, 0, 40)\nrow2:set_bg(0x1A, 0x1A, 0x2E)\nlocal in_pay = dm.text_input(\"pay\", \"payload 8 hex (DEADBEEF)\")\nlocal in_ts = dm.text_input(\"ts\", \"ts_us 24-bit hex (AB12CD)\")\nin_pay:set_bounds(0, 0, 230, 32); in_ts:set_bounds(0, 0, 230, 32)\nrow2:add_child(in_pay); row2:add_child(in_ts)\nroot:add_child(row2)\n\nlocal hexio = dm.text_input(\"hexio\", \"frame hex in/out (34 chars)\")\nhexio:set_bounds(0, 0, 0, 32)\nroot:add_child(hexio)\n\nlocal status = dm.label(\"status\", \"ready\")\nstatus:set_fg(0xE8, 0xE8, 0xF0); status:set_bounds(0, 0, 0, 20)\nroot:add_child(status)\n\nlocal function set_status(text, kind)\n S.status, S.lamp = text, kind\n status:set_text(text)\n if kind == \"ok\" then status:set_fg(0x4C, 0xFF, 0x82)\n elseif kind == \"err\" then status:set_fg(0xFF, 0x4C, 0x6A)\n else status:set_fg(0xFF, 0xD9, 0x4C) end\n dm.redraw()\nend\n\nlocal function read_hex(widget, bits, default)\n local v = tonumber((widget:get_value() or \"\"):gsub(\"%s\", \"\"), 16)\n if v == nil then return default end\n return v & ((1 << bits) - 1)\nend\n\n-- buttons --------------------------------------------------------------------\nlocal row3 = dm.panel(\"row3\"); row3:set_layout(\"hbox\", 6, 4); row3:set_bounds(0, 0, 0, 44)\nrow3:set_bg(0x1A, 0x1A, 0x2E)\n\nlocal function do_encode()\n local pv, pay = (in_pay:get_value() or \"\"):gsub(\"%s\", \"\"), { 0, 0, 0, 0 }\n if #pv > 0 then\n if #pv ~= 8 or pv:find(\"%X\") then return set_status(\"payload must be 8 hex chars\", \"err\") end\n for i = 1, 4 do pay[i] = tonumber(pv:sub(i * 2 - 1, i * 2), 16) end\n end\n local item = dd_type:get_value()\n local ftype = tonumber(type(item) == \"string\" and item:match(\"^%d\") or item) or 0\n S.frame = encode(ftype, read_hex(in_seq, 16, 0), read_hex(in_src, 16, 0),\n read_hex(in_dst, 16, 0xFFFF), pay, read_hex(in_ts, 24, 0))\n S.fields, S.audit = decode(S.frame), nil\n hexio:set_text(frame_to_hex(S.frame))\n set_status((\"encoded %s seq=%04X crc=%04X\"):format(\n TYPE_NAMES[S.fields.ftype] or \"?\", S.fields.seq, S.fields.crc), \"ok\")\nend\n\nlocal function do_decode()\n local w = hex_to_frame(hexio:get_value() or \"\")\n if not w then return set_status(\"need exactly 17 bytes of hex\", \"err\") end\n S.frame, S.audit = w, nil\n local f, reason = decode(w)\n S.fields = f\n if f then\n set_status((\"VALID %s seq=%04X %04X->%04X ts=%06X\"):format(\n TYPE_NAMES[f.ftype] or (\"type \" .. f.ftype), f.seq, f.src, f.dst, f.ts), \"ok\")\n else\n set_status(\"REJECTED: \" .. reason, \"err\")\n end\nend\n\nlocal function do_audit()\n if not (S.frame and S.fields) then return set_status(\"encode or decode a valid frame first\", \"err\") end\n local accepted = 0\n for bit = 0, FRAME_LEN * 8 - 1 do\n local bad = {}\n for i = 1, FRAME_LEN do bad[i] = S.frame[i] end\n local bi = (bit // 8) + 1\n bad[bi] = bad[bi] ~ (1 << (7 - bit % 8))\n if decode(bad) then accepted = accepted + 1 end\n end\n S.audit = accepted\n if accepted == 0 then set_status(\"AUDIT: all 136 single-bit corruptions rejected\", \"ok\")\n else set_status((\"AUDIT FAILED: %d corruptions accepted\"):format(accepted), \"err\") end\nend\n\nlocal function do_example()\n hexio:set_text(\"D31012340001FFFFDEADBEEFAB12CDA963\")\n do_decode()\nend\n\nlocal buttons = { { \"ENCODE\", do_encode }, { \"DECODE\", do_decode },\n { \"AUDIT 136\", do_audit }, { \"EXAMPLE\", do_example } }\nfor _, spec in ipairs(buttons) do\n local b = dm.button(\"btn_\" .. spec[1], spec[1])\n b:set_bounds(0, 0, 140, 36)\n b:on_click(function() spec[2]() end)\n row3:add_child(b)\nend\nroot:add_child(row3)\n\n-- ------------------------------------------------------- custom overlay ----\n-- field spans (byte index 1..17) -> color; CRC cells flip green/red live\nlocal FIELD_SPANS = {\n { 1, 1, 0x8B, 0x5C, 0xF6, \"SYNC\" }, { 2, 2, 0x8B, 0x5C, 0xF6, \"VER|TYPE\" },\n { 3, 4, 0x00, 0xF5, 0xD4, \"SEQ\" }, { 5, 6, 0x4C, 0xFF, 0x82, \"SRC\" },\n { 7, 8, 0xFF, 0xD9, 0x4C, \"DST\" }, { 9, 12, 0xE8, 0xE8, 0xF0, \"PAYLOAD\" },\n { 13, 15, 0x8B, 0x5C, 0xF6, \"TS_US\" }, { 16, 17, 0x00, 0xF5, 0xD4, \"CRC16\" },\n}\n\nfunction on_update(dt)\n dm.redraw() -- lamp pulse + grid stay live (demod-ui needs explicit redraws)\nend\n\nfunction on_draw()\n local gx, gy = 16, 248\n local cell, gap = 38, 4\n -- byte grid\n for i = 1, FRAME_LEN do\n local x = gx + (i - 1) * (cell + gap)\n local r, g, b = 0x2A, 0x2A, 0x3E\n for _, sp in ipairs(FIELD_SPANS) do\n if i >= sp[1] and i <= sp[2] then r, g, b = sp[3], sp[4], sp[5] end\n end\n if i >= 16 and S.frame then\n if S.fields then r, g, b = 0x4C, 0xFF, 0x82 else r, g, b = 0xFF, 0x4C, 0x6A end\n end\n dm.draw.rect(x, gy, cell, 30, 0x1A, 0x1A, 0x2E)\n dm.draw.rect(x, gy + 30, cell, 3, r, g, b)\n local txt = S.frame and (\"%02X\"):format(S.frame[i]) or \"--\"\n dm.draw.text(x + 11, gy + 8, txt, r, g, b)\n dm.draw.text(x + 11, gy + 38, (\"%02d\"):format(i - 1), 0x2A + 0x40, 0x2A + 0x40, 0x3E + 0x40)\n end\n -- legend\n local lx = gx\n for _, sp in ipairs(FIELD_SPANS) do\n dm.draw.rect(lx, gy + 58, 10, 10, sp[3], sp[4], sp[5])\n dm.draw.text(lx + 14, gy + 56, sp[6], 0xE8, 0xE8, 0xF0)\n lx = lx + 14 + 9 * #sp[6] + 16\n end\n -- validity lamp (pulse when valid)\n local pulse = 0.5 + 0.5 * math.sin(dm.time() * 4.0)\n local lampx, lampy = dm.width() - 120, gy + 4\n if S.lamp == \"ok\" then\n dm.draw.circle(lampx, lampy + 10, 9 + 3 * pulse, 0x4C, 0xFF, 0x82, 90)\n dm.draw.circle(lampx, lampy + 10, 7, 0x4C, 0xFF, 0x82)\n elseif S.lamp == \"err\" then\n dm.draw.circle(lampx, lampy + 10, 7, 0xFF, 0x4C, 0x6A)\n else\n dm.draw.circle(lampx, lampy + 10, 7, 0xFF, 0xD9, 0x4C)\n end\n -- Sierpinski Trinity seal, glow keyed to certification (depth 3: real-time safe)\n local sxc, syc = dm.width() - 70, 64\n dm.draw.sierpinski_glow(sxc - 34, syc + 30, sxc + 34, syc + 30, sxc, syc - 30, 3,\n { 0x0A, 0x0A, 0x0F, 255 },\n { 0x8B, 0x5C, 0xF6, 255 },\n CERTIFIED and { 0x00, 0xF5, 0xD4, 255 } or { 0xFF, 0x4C, 0x6A, 255 },\n math.floor(4 + 3 * pulse))\nend\n"}], "text": "<|im_start|>\nsystem\nYou are an expert DCF (DeMoD Communication Framework) wire protocol implementer. You write byte-certified codecs for the 17-byte DeModFrame across multiple languages.\n\nTHE WIRE QUANTUM:\n- 17 bytes: sync(0xD3) | flags[ver|type] | seq | src | dst | payload(4B) | ts24 | crc16\n- Version nibble = 1 (always)\n- CRC-16/CCITT-FALSE over bytes [0..14], anchors: CRC(\"123456789\")=0x29B1, CRC(0^15)=0x4EC3\n- Valid iff sync byte + version nibble + CRC match\n\nCONVENTIONS:\n- Encode: take fields → pack into 17-byte buffer → compute CRC → write CRC at [15..16]\n- Decode: verify sync + version + CRC → unpack fields → return struct or error\n- All implementations MUST produce byte-identical output for identical input\n- Use big-endian for multi-byte fields (network byte order)\n- CRC polynomial: 0x1021, init: 0xFFFF, no final XOR\n- Test against golden_vectors.json (246 vectors: 109 encode + 137 syndrome)\n\n<|im_start|>\nuser\nImplement the DCF wire codec in Lua.\n\nSpecification:\n# DCF Wire Quantum — Canonical Specification\n\n**Version 1** · DeMoD LLC · This document is normative.\n\nThe DCF wire protocol has exactly **one** wire format: the 17-byte `DeModFrame`\n(version nibble = 1). All other formats (the proto-message UDP header, the C\nSDK's `DCFMessageHeader`) are **adapters** over this quantum and must be\nexplicitly documented as such.\n\n## Wire Layout\n\n```\n Byte Field Width Description\n ──── ────────── ───── ─────────────────────────────────────────\n 0 sync 1 B Fixed 0xD3 (first validity gate)\n 1 flags 1 B [7:4] version (currently 1) | [3:0] type (0–3)\n 2–3 seq 2 B Big-endian u16, rolling sequence counter\n 4–5 src_id 2 B Big-endian u16, source node ID\n 6–7 dst_id 2 B Big-endian u16, destination (0xFFFF = broadcast)\n 8–11 payload 4 B Application data\n 12–14 timestamp 3 B 24-bit µs offset, big-endian, wraps ~16.7 s\n 15–16 crc16 2 B CRC-16/CCITT-FALSE over bytes [0..14]\n```\n\n**Total: 17 bytes = 136 bits.** The free field data is 108 bits (4+16+16+16+32+24).\n\n## Frame Types\n\n| Value | Name | Purpose |\n|-------|--------|-----------------------------|\n| 0 | DATA | Application payload |\n| 1 | ACK | Acknowledgement |\n| 2 | BEACON | Clock sync / broadcast |\n| 3 | CTRL | Control / fragmented audio |\n\n## Validity\n\nA frame is valid iff:\n1. `frame[0] == 0xD3` (sync byte)\n2. `(frame[1] >> 4) == 1` (version nibble)\n3. `CRC-16/CCITT-FALSE(frame[0..14]) == (frame[15] << 8) | frame[16]` (CRC)\n\nFor a random byte stream, the probability of a 17-byte window passing all three\nchecks is 2⁻²⁸ (Theorem 2.1, `wire_quanta_category.md`).\n\n## CRC-16/CCITT-FALSE\n\n- Polynomial: `0x1021`\n- Init: `0xFFFF`\n- RefIn/RefOut: `false`\n- XorOut: `0x0000`\n- Check value: `CRC(\"123456789\") = 0x29B1`\n\n## Anchors\n\n| Quantity | Value | Source |\n|----------|-------|--------|\n| CRC(\"123456789\") | `0x29B1` | Reference check value |\n| CRC(0¹⁵) | `0x4EC3` | Affine offset c |\n| CRC(exampleFrame body) | `0xA963` | Cross-language anchor |\n| exampleFrame | `D31312340001FFFFDEADBEEFAB12CD24C0` | type=CTRL, seq=0x1234, src=1, dst=0xFFFF, payload=DEADBEEF, ts=AB12CD |\n\n## Formal Properties\n\nThe frame is a **cemented retract** (Theorem 1, `wire_quanta_category.md`):\n- `encode` is injective with a left inverse `decode` (decode∘encode = id)\n- `encode` is a bijection onto the set of valid words\n- `decode` is the unique decoder satisfying the spec\n\nThe 246-vector finite certificate (Theorem 4) proves that any implementation\nmatching the 109 encode-basis + 137 syndrome-basis vectors equals the reference\non all 2¹⁰⁸ frames and classifies all 2¹³⁶ words identically. See\n`Documentation/golden_vectors.json`.\n\n## Reference Implementations\n\n| Language | File | Functions |\n|----------|------|-----------|\n| C | `codec/demod_frame.h` | `dcf_frame_encode`, `dcf_frame_decode`, `dcf_frame_crc` |\n| Rust | `codec/frame.rs` | `Frame::encode`, `Frame::decode` |\n| Python | `python/MCP/wirelab_core.py` | `encode`, `decode`, `syndrome`, `crc16_ccitt` |\n| Lua | `GUI/wirelab.lua` | `encode`, `decode`, `crc16` |\n\n## Certification\n\nTo certify a new SDK against the reference:\n\n```sh\npython3 python/MCP/certify_sdk.py --selftest # reference self-test\npython3 python/MCP/certify_sdk.py --sdk-json SDK.json # certify an external SDK\n```\n\nAll CI gates run `python/MCP/verify_laws.py` and `python/MCP/certify_sdk.py --selftest`.\nUnder Theorem 4, passing the 246-vector test is equivalent to agreement on the\nentire 2¹⁰⁸ × 2¹³⁶ input space.\n\n## Other Wire Formats ARE Adapters\n\n| Format | Status | Relationship to DeModFrame |\n|--------|--------|----------------------------|\n| Proto-message UDP header (C SDK) | Adapter | Must marshal to/from DeModFrame for wire |\n| `DCFMessageHeader` (C SDK) | Internal | In-process struct; must not appear on the wire |\n| Haskell `FrameSpec` | Implemented | `haskell/src/DCF/Transport/FrameSpec.hs` — encodeFrame / decodeFrame |\n\nAny new transport MUST emit and consume DeModFrame v1 on the wire. Internal\nrepresentations are free to differ but MUST be convertible to/from DeModFrame\nwithout loss.\n\nGolden vectors (sample):\n{\n \"encode_basis\": [\n {\n \"input_bits\": \"000000000000000000000000000\",\n \"frame\": \"d310000000000000000000000000005b80\"\n },\n {\n \"input_bit\": 0,\n \"frame\": \"d3110000000000000000000000000020e1\"\n },\n {\n \"input_bit\": 1,\n \"frame\": \"d31200000000000000000000000000ad42\"\n },\n {\n \"input_bit\": 2,\n \"frame\": \"d31400000000000000000000000000a625\"\n },\n {\n \"input_bit\": 3,\n \"frame\": \"d31800000000000000000000000000b0eb\"\n },\n {\n \"input_bit\": 4,\n \"frame\": \"d3100001000000000000000000000058f5\"\n },\n {\n \"input_bit\": 5,\n \"frame\": \"d310000200000000000000000000005d6a\"\n },\n {\n \"input_bit\": 6,\n \"frame\": \"d310000400000000000000000000005654\"\n },\n {\n \"input_bit\": 7,\n \"frame\": \"d310000800000000000000000000004028\"\n },\n {\n \"input_bit\": 8,\n \"frame\": \"d310001000000000000000000000006cd0\"\n }\n ],\n \"syndrome_basis\": [\n {\n \"word\": \"0000000000000000000000000000000000\",\n \"syndrome\": 20163\n },\n {\n \"bit\": 0,\n \"syndrome\": 6865\n },\n {\n \"bit\": 1,\n \"syndrome\": 25802\n },\n {\n \"bit\": 2,\n \"syndrome\": 54231\n },\n {\n \"bit\": 3,\n \"syndrome\": 73\n },\n {\n \"bit\": 4,\n \"syndrome\": 27014\n },\n {\n \"bit\": 5,\n \"syndrome\": 54641\n },\n {\n \"bit\": 6,\n \"syndrome\": 794\n },\n {\n \"bit\": 7,\n \"syndrome\": 57407\n },\n {\n \"bit\": 8,\n \"syndrome\": 6589\n }\n ]\n}\n\nProvide the complete implementation with encode/decode functions.\n<|im_start|>\nassistant\n-- ============================================================================\n-- DCF WIRELAB — DeMoD UI front panel for the 17-byte wire quantum (DeModFrame)\n-- Run: ./demod-ui wirelab.lua\n--\n-- Pure-Lua reference codec (CRC-16/CCITT-FALSE, poly 0x1021, init 0xFFFF),\n-- bit-identical to wirelab_core.py / the fixed Punctim crc16-ccitt / the\n-- Haskell crc16ccitt. Self-certifies on launch against the golden anchors:\n-- crc(\"123456789\") = 0x29B1\n-- crc(exampleFrame body) = 0xA963\n-- full exampleFrame = D31012340001FFFFDEADBEEFAB12CDA963\n-- Companion: wirelab_mcp.py (agent face), golden_vectors.json (certificate).\n-- ============================================================================\n\n-- ---------------------------------------------------------------- codec ----\nlocal SYNC, VERSION, FRAME_LEN = 0xD3, 1, 17\n\nlocal function crc16(bytes, n)\n local crc = 0xFFFF\n for i = 1, n do\n crc = (crc ~ ((bytes[i] & 0xFF) << 8)) & 0xFFFF\n for _ = 1, 8 do\n if (crc & 0x8000) ~= 0 then crc = ((crc << 1) ~ 0x1021) & 0xFFFF\n else crc = (crc << 1) & 0xFFFF end\n end\n end\n return crc\nend\n\nlocal function encode(ftype, seq, src, dst, payload, ts)\n local w = {}\n w[1] = SYNC\n w[2] = ((VERSION & 0xF) << 4) | (ftype & 0xF)\n w[3] = (seq >> 8) & 0xFF; w[4] = seq & 0xFF\n w[5] = (src >> 8) & 0xFF; w[6] = src & 0xFF\n w[7] = (dst >> 8) & 0xFF; w[8] = dst & 0xFF\n for i = 1, 4 do w[8 + i] = payload[i] & 0xFF end\n w[13] = (ts >> 16) & 0xFF; w[14] = (ts >> 8) & 0xFF; w[15] = ts & 0xFF\n local c = crc16(w, 15)\n w[16] = (c >> 8) & 0xFF; w[17] = c & 0xFF\n return w\nend\n\n-- returns fields-table or nil, reason\nlocal function decode(w)\n if #w ~= FRAME_LEN then return nil, (\"length %d != 17\"):format(#w) end\n if w[1] ~= SYNC then return nil, \"bad sync byte\" end\n if (w[2] >> 4) ~= VERSION then return nil, \"bad version nibble\" end\n if crc16(w, 15) ~= ((w[16] << 8) | w[17]) then return nil, \"CRC mismatch\" end\n return { ftype = w[2] & 0xF,\n seq = (w[3] << 8) | w[4], src = (w[5] << 8) | w[6],\n dst = (w[7] << 8) | w[8],\n payload = { w[9], w[10], w[11], w[12] },\n ts = (w[13] << 16) | (w[14] << 8) | w[15],\n crc = (w[16] << 8) | w[17] }\nend\n\nlocal function frame_to_hex(w)\n local t = {}\n for i = 1, #w do t[i] = (\"%02X\"):format(w[i]) end\n return table.concat(t)\nend\n\nlocal function hex_to_frame(s)\n s = s:gsub(\"[%s:,]\", \"\"):gsub(\"0[xX]\", \"\")\n if #s ~= 34 or s:find(\"%X\") then return nil end\n local w = {}\n for i = 1, 17 do w[i] = tonumber(s:sub(i * 2 - 1, i * 2), 16) end\n return w\nend\n\n-- ------------------------------------------------------------ self-cert ----\nlocal CERTIFIED = false\ndo\n local anchor = {}\n for i = 1, 9 do anchor[i] = string.byte(\"123456789\", i) end\n local ex = encode(0, 0x1234, 0x0001, 0xFFFF, {0xDE, 0xAD, 0xBE, 0xEF}, 0xAB12CD)\n CERTIFIED = crc16(anchor, 9) == 0x29B1\n and frame_to_hex(ex) == \"D31012340001FFFFDEADBEEFAB12CDA963\"\n and decode(ex) ~= nil\nend\n\n-- ------------------------------------------------------------------- ui ----\nlocal TYPE_NAMES = { [0] = \"FData\", [1] = \"FAck\", [2] = \"FBeacon\", [3] = \"FCtrl\" }\nlocal S = { frame = nil, fields = nil, status = \"\", lamp = \"idle\", audit = nil }\n\nlocal root = dm.root()\nroot:set_layout(\"vbox\", 6, 12)\n\nlocal title = dm.label(\"title\", \"DCF WIRELAB // 17-BYTE WIRE QUANTUM\")\ntitle:set_fg(0x8B, 0x5C, 0xF6); title:set_bounds(0, 0, 0, 28)\nroot:add_child(title)\n\nlocal sub = dm.label(\"sub\", CERTIFIED and \"codec CERTIFIED: 0x29B1 / 0xA963 anchors hold\"\n or \"CODEC SELF-TEST FAILED — do not trust output\")\nsub:set_fg(CERTIFIED and 0x4C or 0xFF, CERTIFIED and 0xFF or 0x4C,\n CERTIFIED and 0x82 or 0x6A)\nsub:set_bounds(0, 0, 0, 18)\nroot:add_child(sub)\n\n-- field inputs ---------------------------------------------------------------\nlocal row1 = dm.panel(\"row1\"); row1:set_layout(\"hbox\", 6, 4); row1:set_bounds(0, 0, 0, 40)\nrow1:set_bg(0x1A, 0x1A, 0x2E)\nlocal dd_type = dm.dropdown(\"ftype\", \"type\")\nfor i = 0, 3 do dd_type:add_item((\"%d %s\"):format(i, TYPE_NAMES[i])) end\nlocal in_seq = dm.text_input(\"seq\", \"seq hex (1234)\")\nlocal in_src = dm.text_input(\"src\", \"src hex (0001)\")\nlocal in_dst = dm.text_input(\"dst\", \"dst hex (FFFF)\")\nfor _, w in ipairs({ dd_type, in_seq, in_src, in_dst }) do\n w:set_bounds(0, 0, 150, 32); row1:add_child(w)\nend\nroot:add_child(row1)\n\nlocal row2 = dm.panel(\"row2\"); row2:set_layout(\"hbox\", 6, 4); row2:set_bounds(0, 0, 0, 40)\nrow2:set_bg(0x1A, 0x1A, 0x2E)\nlocal in_pay = dm.text_input(\"pay\", \"payload 8 hex (DEADBEEF)\")\nlocal in_ts = dm.text_input(\"ts\", \"ts_us 24-bit hex (AB12CD)\")\nin_pay:set_bounds(0, 0, 230, 32); in_ts:set_bounds(0, 0, 230, 32)\nrow2:add_child(in_pay); row2:add_child(in_ts)\nroot:add_child(row2)\n\nlocal hexio = dm.text_input(\"hexio\", \"frame hex in/out (34 chars)\")\nhexio:set_bounds(0, 0, 0, 32)\nroot:add_child(hexio)\n\nlocal status = dm.label(\"status\", \"ready\")\nstatus:set_fg(0xE8, 0xE8, 0xF0); status:set_bounds(0, 0, 0, 20)\nroot:add_child(status)\n\nlocal function set_status(text, kind)\n S.status, S.lamp = text, kind\n status:set_text(text)\n if kind == \"ok\" then status:set_fg(0x4C, 0xFF, 0x82)\n elseif kind == \"err\" then status:set_fg(0xFF, 0x4C, 0x6A)\n else status:set_fg(0xFF, 0xD9, 0x4C) end\n dm.redraw()\nend\n\nlocal function read_hex(widget, bits, default)\n local v = tonumber((widget:get_value() or \"\"):gsub(\"%s\", \"\"), 16)\n if v == nil then return default end\n return v & ((1 << bits) - 1)\nend\n\n-- buttons --------------------------------------------------------------------\nlocal row3 = dm.panel(\"row3\"); row3:set_layout(\"hbox\", 6, 4); row3:set_bounds(0, 0, 0, 44)\nrow3:set_bg(0x1A, 0x1A, 0x2E)\n\nlocal function do_encode()\n local pv, pay = (in_pay:get_value() or \"\"):gsub(\"%s\", \"\"), { 0, 0, 0, 0 }\n if #pv > 0 then\n if #pv ~= 8 or pv:find(\"%X\") then return set_status(\"payload must be 8 hex chars\", \"err\") end\n for i = 1, 4 do pay[i] = tonumber(pv:sub(i * 2 - 1, i * 2), 16) end\n end\n local item = dd_type:get_value()\n local ftype = tonumber(type(item) == \"string\" and item:match(\"^%d\") or item) or 0\n S.frame = encode(ftype, read_hex(in_seq, 16, 0), read_hex(in_src, 16, 0),\n read_hex(in_dst, 16, 0xFFFF), pay, read_hex(in_ts, 24, 0))\n S.fields, S.audit = decode(S.frame), nil\n hexio:set_text(frame_to_hex(S.frame))\n set_status((\"encoded %s seq=%04X crc=%04X\"):format(\n TYPE_NAMES[S.fields.ftype] or \"?\", S.fields.seq, S.fields.crc), \"ok\")\nend\n\nlocal function do_decode()\n local w = hex_to_frame(hexio:get_value() or \"\")\n if not w then return set_status(\"need exactly 17 bytes of hex\", \"err\") end\n S.frame, S.audit = w, nil\n local f, reason = decode(w)\n S.fields = f\n if f then\n set_status((\"VALID %s seq=%04X %04X->%04X ts=%06X\"):format(\n TYPE_NAMES[f.ftype] or (\"type \" .. f.ftype), f.seq, f.src, f.dst, f.ts), \"ok\")\n else\n set_status(\"REJECTED: \" .. reason, \"err\")\n end\nend\n\nlocal function do_audit()\n if not (S.frame and S.fields) then return set_status(\"encode or decode a valid frame first\", \"err\") end\n local accepted = 0\n for bit = 0, FRAME_LEN * 8 - 1 do\n local bad = {}\n for i = 1, FRAME_LEN do bad[i] = S.frame[i] end\n local bi = (bit // 8) + 1\n bad[bi] = bad[bi] ~ (1 << (7 - bit % 8))\n if decode(bad) then accepted = accepted + 1 end\n end\n S.audit = accepted\n if accepted == 0 then set_status(\"AUDIT: all 136 single-bit corruptions rejected\", \"ok\")\n else set_status((\"AUDIT FAILED: %d corruptions accepted\"):format(accepted), \"err\") end\nend\n\nlocal function do_example()\n hexio:set_text(\"D31012340001FFFFDEADBEEFAB12CDA963\")\n do_decode()\nend\n\nlocal buttons = { { \"ENCODE\", do_encode }, { \"DECODE\", do_decode },\n { \"AUDIT 136\", do_audit }, { \"EXAMPLE\", do_example } }\nfor _, spec in ipairs(buttons) do\n local b = dm.button(\"btn_\" .. spec[1], spec[1])\n b:set_bounds(0, 0, 140, 36)\n b:on_click(function() spec[2]() end)\n row3:add_child(b)\nend\nroot:add_child(row3)\n\n-- ------------------------------------------------------- custom overlay ----\n-- field spans (byte index 1..17) -> color; CRC cells flip green/red live\nlocal FIELD_SPANS = {\n { 1, 1, 0x8B, 0x5C, 0xF6, \"SYNC\" }, { 2, 2, 0x8B, 0x5C, 0xF6, \"VER|TYPE\" },\n { 3, 4, 0x00, 0xF5, 0xD4, \"SEQ\" }, { 5, 6, 0x4C, 0xFF, 0x82, \"SRC\" },\n { 7, 8, 0xFF, 0xD9, 0x4C, \"DST\" }, { 9, 12, 0xE8, 0xE8, 0xF0, \"PAYLOAD\" },\n { 13, 15, 0x8B, 0x5C, 0xF6, \"TS_US\" }, { 16, 17, 0x00, 0xF5, 0xD4, \"CRC16\" },\n}\n\nfunction on_update(dt)\n dm.redraw() -- lamp pulse + grid stay live (demod-ui needs explicit redraws)\nend\n\nfunction on_draw()\n local gx, gy = 16, 248\n local cell, gap = 38, 4\n -- byte grid\n for i = 1, FRAME_LEN do\n local x = gx + (i - 1) * (cell + gap)\n local r, g, b = 0x2A, 0x2A, 0x3E\n for _, sp in ipairs(FIELD_SPANS) do\n if i >= sp[1] and i <= sp[2] then r, g, b = sp[3], sp[4], sp[5] end\n end\n if i >= 16 and S.frame then\n if S.fields then r, g, b = 0x4C, 0xFF, 0x82 else r, g, b = 0xFF, 0x4C, 0x6A end\n end\n dm.draw.rect(x, gy, cell, 30, 0x1A, 0x1A, 0x2E)\n dm.draw.rect(x, gy + 30, cell, 3, r, g, b)\n local txt = S.frame and (\"%02X\"):format(S.frame[i]) or \"--\"\n dm.draw.text(x + 11, gy + 8, txt, r, g, b)\n dm.draw.text(x + 11, gy + 38, (\"%02d\"):format(i - 1), 0x2A + 0x40, 0x2A + 0x40, 0x3E + 0x40)\n end\n -- legend\n local lx = gx\n for _, sp in ipairs(FIELD_SPANS) do\n dm.draw.rect(lx, gy + 58, 10, 10, sp[3], sp[4], sp[5])\n dm.draw.text(lx + 14, gy + 56, sp[6], 0xE8, 0xE8, 0xF0)\n lx = lx + 14 + 9 * #sp[6] + 16\n end\n -- validity lamp (pulse when valid)\n local pulse = 0.5 + 0.5 * math.sin(dm.time() * 4.0)\n local lampx, lampy = dm.width() - 120, gy + 4\n if S.lamp == \"ok\" then\n dm.draw.circle(lampx, lampy + 10, 9 + 3 * pulse, 0x4C, 0xFF, 0x82, 90)\n dm.draw.circle(lampx, lampy + 10, 7, 0x4C, 0xFF, 0x82)\n elseif S.lamp == \"err\" then\n dm.draw.circle(lampx, lampy + 10, 7, 0xFF, 0x4C, 0x6A)\n else\n dm.draw.circle(lampx, lampy + 10, 7, 0xFF, 0xD9, 0x4C)\n end\n -- Sierpinski Trinity seal, glow keyed to certification (depth 3: real-time safe)\n local sxc, syc = dm.width() - 70, 64\n dm.draw.sierpinski_glow(sxc - 34, syc + 30, sxc + 34, syc + 30, sxc, syc - 30, 3,\n { 0x0A, 0x0A, 0x0F, 255 },\n { 0x8B, 0x5C, 0xF6, 255 },\n CERTIFIED and { 0x00, 0xF5, 0xD4, 255 } or { 0xFF, 0x4C, 0x6A, 255 },\n math.floor(4 + 3 * pulse))\nend\n\n"}
{"messages": [{"role": "system", "content": "You are an expert DCF (DeMoD Communication Framework) wire protocol implementer. You write byte-certified codecs for the 17-byte DeModFrame across multiple languages.\n\nTHE WIRE QUANTUM:\n- 17 bytes: sync(0xD3) | flags[ver|type] | seq | src | dst | payload(4B) | ts24 | crc16\n- Version nibble = 1 (always)\n- CRC-16/CCITT-FALSE over bytes [0..14], anchors: CRC(\"123456789\")=0x29B1, CRC(0^15)=0x4EC3\n- Valid iff sync byte + version nibble + CRC match\n\nCONVENTIONS:\n- Encode: take fields → pack into 17-byte buffer → compute CRC → write CRC at [15..16]\n- Decode: verify sync + version + CRC → unpack fields → return struct or error\n- All implementations MUST produce byte-identical output for identical input\n- Use big-endian for multi-byte fields (network byte order)\n- CRC polynomial: 0x1021, init: 0xFFFF, no final XOR\n- Test against golden_vectors.json (246 vectors: 109 encode + 137 syndrome)\n"}, {"role": "user", "content": "Implement the DCF wire codec in Haskell.\n\nSpecification:\n# DCF Wire Quantum — Canonical Specification\n\n**Version 1** · DeMoD LLC · This document is normative.\n\nThe DCF wire protocol has exactly **one** wire format: the 17-byte `DeModFrame`\n(version nibble = 1). All other formats (the proto-message UDP header, the C\nSDK's `DCFMessageHeader`) are **adapters** over this quantum and must be\nexplicitly documented as such.\n\n## Wire Layout\n\n```\n Byte Field Width Description\n ──── ────────── ───── ─────────────────────────────────────────\n 0 sync 1 B Fixed 0xD3 (first validity gate)\n 1 flags 1 B [7:4] version (currently 1) | [3:0] type (0–3)\n 2–3 seq 2 B Big-endian u16, rolling sequence counter\n 4–5 src_id 2 B Big-endian u16, source node ID\n 6–7 dst_id 2 B Big-endian u16, destination (0xFFFF = broadcast)\n 8–11 payload 4 B Application data\n 12–14 timestamp 3 B 24-bit µs offset, big-endian, wraps ~16.7 s\n 15–16 crc16 2 B CRC-16/CCITT-FALSE over bytes [0..14]\n```\n\n**Total: 17 bytes = 136 bits.** The free field data is 108 bits (4+16+16+16+32+24).\n\n## Frame Types\n\n| Value | Name | Purpose |\n|-------|--------|-----------------------------|\n| 0 | DATA | Application payload |\n| 1 | ACK | Acknowledgement |\n| 2 | BEACON | Clock sync / broadcast |\n| 3 | CTRL | Control / fragmented audio |\n\n## Validity\n\nA frame is valid iff:\n1. `frame[0] == 0xD3` (sync byte)\n2. `(frame[1] >> 4) == 1` (version nibble)\n3. `CRC-16/CCITT-FALSE(frame[0..14]) == (frame[15] << 8) | frame[16]` (CRC)\n\nFor a random byte stream, the probability of a 17-byte window passing all three\nchecks is 2⁻²⁸ (Theorem 2.1, `wire_quanta_category.md`).\n\n## CRC-16/CCITT-FALSE\n\n- Polynomial: `0x1021`\n- Init: `0xFFFF`\n- RefIn/RefOut: `false`\n- XorOut: `0x0000`\n- Check value: `CRC(\"123456789\") = 0x29B1`\n\n## Anchors\n\n| Quantity | Value | Source |\n|----------|-------|--------|\n| CRC(\"123456789\") | `0x29B1` | Reference check value |\n| CRC(0¹⁵) | `0x4EC3` | Affine offset c |\n| CRC(exampleFrame body) | `0xA963` | Cross-language anchor |\n| exampleFrame | `D31312340001FFFFDEADBEEFAB12CD24C0` | type=CTRL, seq=0x1234, src=1, dst=0xFFFF, payload=DEADBEEF, ts=AB12CD |\n\n## Formal Properties\n\nThe frame is a **cemented retract** (Theorem 1, `wire_quanta_category.md`):\n- `encode` is injective with a left inverse `decode` (decode∘encode = id)\n- `encode` is a bijection onto the set of valid words\n- `decode` is the unique decoder satisfying the spec\n\nThe 246-vector finite certificate (Theorem 4) proves that any implementation\nmatching the 109 encode-basis + 137 syndrome-basis vectors equals the reference\non all 2¹⁰⁸ frames and classifies all 2¹³⁶ words identically. See\n`Documentation/golden_vectors.json`.\n\n## Reference Implementations\n\n| Language | File | Functions |\n|----------|------|-----------|\n| C | `codec/demod_frame.h` | `dcf_frame_encode`, `dcf_frame_decode`, `dcf_frame_crc` |\n| Rust | `codec/frame.rs` | `Frame::encode`, `Frame::decode` |\n| Python | `python/MCP/wirelab_core.py` | `encode`, `decode`, `syndrome`, `crc16_ccitt` |\n| Lua | `GUI/wirelab.lua` | `encode`, `decode`, `crc16` |\n\n## Certification\n\nTo certify a new SDK against the reference:\n\n```sh\npython3 python/MCP/certify_sdk.py --selftest # reference self-test\npython3 python/MCP/certify_sdk.py --sdk-json SDK.json # certify an external SDK\n```\n\nAll CI gates run `python/MCP/verify_laws.py` and `python/MCP/certify_sdk.py --selftest`.\nUnder Theorem 4, passing the 246-vector test is equivalent to agreement on the\nentire 2¹⁰⁸ × 2¹³⁶ input space.\n\n## Other Wire Formats ARE Adapters\n\n| Format | Status | Relationship to DeModFrame |\n|--------|--------|----------------------------|\n| Proto-message UDP header (C SDK) | Adapter | Must marshal to/from DeModFrame for wire |\n| `DCFMessageHeader` (C SDK) | Internal | In-process struct; must not appear on the wire |\n| Haskell `FrameSpec` | Implemented | `haskell/src/DCF/Transport/FrameSpec.hs` — encodeFrame / decodeFrame |\n\nAny new transport MUST emit and consume DeModFrame v1 on the wire. Internal\nrepresentations are free to differ but MUST be convertible to/from DeModFrame\nwithout loss.\n\nGolden vectors (sample):\n{\n \"encode_basis\": [\n {\n \"input_bits\": \"000000000000000000000000000\",\n \"frame\": \"d310000000000000000000000000005b80\"\n },\n {\n \"input_bit\": 0,\n \"frame\": \"d3110000000000000000000000000020e1\"\n },\n {\n \"input_bit\": 1,\n \"frame\": \"d31200000000000000000000000000ad42\"\n },\n {\n \"input_bit\": 2,\n \"frame\": \"d31400000000000000000000000000a625\"\n },\n {\n \"input_bit\": 3,\n \"frame\": \"d31800000000000000000000000000b0eb\"\n },\n {\n \"input_bit\": 4,\n \"frame\": \"d3100001000000000000000000000058f5\"\n },\n {\n \"input_bit\": 5,\n \"frame\": \"d310000200000000000000000000005d6a\"\n },\n {\n \"input_bit\": 6,\n \"frame\": \"d310000400000000000000000000005654\"\n },\n {\n \"input_bit\": 7,\n \"frame\": \"d310000800000000000000000000004028\"\n },\n {\n \"input_bit\": 8,\n \"frame\": \"d310001000000000000000000000006cd0\"\n }\n ],\n \"syndrome_basis\": [\n {\n \"word\": \"0000000000000000000000000000000000\",\n \"syndrome\": 20163\n },\n {\n \"bit\": 0,\n \"syndrome\": 6865\n },\n {\n \"bit\": 1,\n \"syndrome\": 25802\n },\n {\n \"bit\": 2,\n \"syndrome\": 54231\n },\n {\n \"bit\": 3,\n \"syndrome\": 73\n },\n {\n \"bit\": 4,\n \"syndrome\": 27014\n },\n {\n \"bit\": 5,\n \"syndrome\": 54641\n },\n {\n \"bit\": 6,\n \"syndrome\": 794\n },\n {\n \"bit\": 7,\n \"syndrome\": 57407\n },\n {\n \"bit\": 8,\n \"syndrome\": 6589\n }\n ]\n}\n\nProvide the complete implementation with encode/decode functions."}, {"role": "assistant", "content": "-- SPDX-License-Identifier: LGPL-3.0-only\n{-|\nModule : DCF.Transport.FrameSpec\nDescription : DeMoD 17-byte transport frame codec — Haskell reference implementation\nCopyright : (c) DeMoD LLC\nLicense : LGPL-3.0\nMaintainer : info@demodllc.example\n\nThe canonical Haskell implementation of the DeMoD wire quantum.\n\nWire layout (17 bytes = 136 bits, all multi-byte fields big-endian):\n\n Byte Field Notes\n ───── ─────────── ──────────────────────────────────────────────────────\n 0 sync Fixed 0xD3 — first validity gate\n 1 flags [7:4] version (4-bit) | [3:0] frame type (4-bit)\n 2-3 seq Big-endian u16, rolling counter\n 4-5 src_id Big-endian u16, source node\n 6-7 dst_id Big-endian u16, 0xFFFF = broadcast\n 8-11 payload 4 raw application bytes\n 12-14 timestamp 24-bit big-endian µs offset, wraps ~16.7 s\n 15-16 crc16 CRC-CCITT(poly=0x1021, init=0xFFFF) over bytes [0..14]\n\nCross-language parity:\n C transport/dcf_frame.h dcf_frame_encode / dcf_frame_decode\n Haskell DCF.Transport.Frame encodeFrame / decodeFrame ← this file\n Lisp punctim.lisp encode-dcf-frame / decode-dcf-frame\n Rust dcf/rust/src/frame.rs Frame::encode / Frame::decode\n Python wirelab_core.py encode / decode\n\n-}\nmodule DCF.Transport.FrameSpec\n ( -- * Types\n FrameType(..)\n , Frame(..)\n , FrameError(..)\n -- * Constants\n , frameSize\n , syncByte\n , broadcast\n -- * Codec\n , encodeFrame\n , decodeFrame\n , isValidFrame\n -- * CRC\n , crc16ccitt\n -- * Reference test vector\n , exampleFrame\n , exampleFrameBytes\n ) where\n\nimport Prelude hiding (seq)\nimport Data.Bits (Bits, shiftL, shiftR, (.|.), (.&.), xor)\nimport Data.Word (Word8, Word16, Word32)\n\n-- ── Constants ──────────────────────────────────────────────────────────────\n\nframeSize :: Int\nframeSize = 17\n\nsyncByte :: Word8\nsyncByte = 0xD3\n\nbroadcast :: Word16\nbroadcast = 0xFFFF\n\ncrcCover :: Int\ncrcCover = 15\n\n-- ── Frame type ─────────────────────────────────────────────────────────────\n\ndata FrameType = Data | Ack | Beacon | Ctrl\n deriving (Eq, Show, Read, Enum, Bounded)\n\nframeTypeToNibble :: FrameType -> Word8\nframeTypeToNibble Data = 0\nframeTypeToNibble Ack = 1\nframeTypeToNibble Beacon = 2\nframeTypeToNibble Ctrl = 3\n\nnibbleToFrameType :: Word8 -> Maybe FrameType\nnibbleToFrameType n = case n .&. 0x0F of\n 0 -> Just Data\n 1 -> Just Ack\n 2 -> Just Beacon\n 3 -> Just Ctrl\n _ -> Nothing\n\n-- ── Frame (decoded, host-order fields) ─────────────────────────────────────\n\ndata Frame = Frame\n { version :: !Word8 -- ^ 4-bit, 0–15\n , frameType :: !FrameType\n , seq :: !Word16 -- ^ rolling counter\n , srcId :: !Word16 -- ^ source node\n , dstId :: !Word16 -- ^ dest node (broadcast = 0xFFFF)\n , payload :: !(Word8, Word8, Word8, Word8)\n , timestampUs :: !Word32 -- ^ 24-bit µs (top byte always 0)\n } deriving (Eq, Show)\n\n-- ── Decode error ───────────────────────────────────────────────────────────\n\ndata FrameError\n = BadLength\n | BadSync\n | BadCrc\n | UnknownType !Word8\n deriving (Eq, Show)\n\n-- ── CRC-CCITT ──────────────────────────────────────────────────────────────\n--\n-- Poly 0x1021, init 0xFFFF.\n-- Identical algorithm in C (dcf_crc16), Rust (crc16_ccitt), Python (crc16_ccitt).\n-- All four implementations must return the same value for the same input.\n\ncrc16ccitt :: [Word8] -> Word16\ncrc16ccitt = go 0xFFFF\n where\n go crc [] = crc\n go crc (b:bs) = go (step8 (crc `xor` (fromIntegral b `shiftL` 8))) bs\n\nstep8 :: Word16 -> Word16\nstep8 crc = foldl (\\c _ -> if c .&. 0x8000 /= 0\n then (c `shiftL` 1) `xor` 0x1021\n else c `shiftL` 1) crc [(0::Int)..7]\n\n-- ── Encode ────────────────────────────────────────────────────────────────\n--\n-- Serialise a Frame into exactly 17 bytes (big-endian).\n-- CRC is computed and appended automatically.\n\nencodeFrame :: Frame -> [Word8]\nencodeFrame f = take frameSize $ buf ++ [hi crc, lo crc]\n where\n buf = [ syncByte\n , ((version f .&. 0x0F) `shiftL` 4) .|. frameTypeToNibble (frameType f)\n , hi (seq f), lo (seq f)\n , hi (srcId f), lo (srcId f)\n , hi (dstId f), lo (dstId f)\n , a, b, c, d\n , fromIntegral ((timestampUs f `shiftR` 16) .&. 0xFF)\n , fromIntegral ((timestampUs f `shiftR` 8) .&. 0xFF)\n , fromIntegral ( timestampUs f .&. 0xFF)\n ]\n (a, b, c, d) = payload f\n crc = crc16ccitt (take crcCover buf)\n\nhi, lo :: (Integral a, Bits a, Num b) => a -> b\nhi w = fromIntegral (w `shiftR` 8)\nlo w = fromIntegral (w .&. 0xFF)\n\n-- ── Decode ────────────────────────────────────────────────────────────────\n--\n-- Parse a 17-byte wire buffer.\n-- Returns Left on invalid sync, CRC mismatch, or unknown frame type.\n\ndecodeFrame :: [Word8] -> Either FrameError Frame\ndecodeFrame buf\n | length buf /= frameSize = Left BadLength\n | head buf /= syncByte = Left BadSync\n | crc16ccitt (take crcCover buf) /= storedCrc = Left BadCrc\n | otherwise = case nibbleToFrameType (buf !! 1 .&. 0x0F) of\n Nothing -> Left (UnknownType (buf !! 1 .&. 0x0F))\n Just ft -> Right Frame\n { version = (buf !! 1 `shiftR` 4) .&. 0x0F\n , frameType = ft\n , seq = makeW16 (buf !! 2) (buf !! 3)\n , srcId = makeW16 (buf !! 4) (buf !! 5)\n , dstId = makeW16 (buf !! 6) (buf !! 7)\n , payload = (buf !! 8, buf !! 9, buf !! 10, buf !! 11)\n , timestampUs = makeW24 (buf !! 12) (buf !! 13) (buf !! 14)\n }\n where\n storedCrc = makeW16 (buf !! 15) (buf !! 16)\n\nmakeW16 :: Word8 -> Word8 -> Word16\nmakeW16 hi8 lo8 = fromIntegral hi8 `shiftL` 8 .|. fromIntegral lo8\n\nmakeW24 :: Word8 -> Word8 -> Word8 -> Word32\nmakeW24 a b c = fromIntegral a `shiftL` 16 .|. fromIntegral b `shiftL` 8 .|. fromIntegral c\n\n-- ── Validate (non-destructive) ─────────────────────────────────────────────\n\nisValidFrame :: [Word8] -> Bool\nisValidFrame buf\n | length buf /= frameSize = False\n | head buf /= syncByte = False\n | otherwise = crc16ccitt (take crcCover buf) == makeW16 (buf !! 15) (buf !! 16)\n\n-- ── Reference test vector ─────────────────────────────────────────────────\n--\n-- Matches the C dcf_frame.h reference, the Rust Frame::tests::reference_frame,\n-- and the Python wirelab_core anchors.\n-- version=1, FData, seq=1, src=1, dst=0xFFFF, payload=0xDEADBEEF, ts=0\n\nexampleFrame :: Frame\nexampleFrame = Frame\n { version = 1\n , frameType = Data\n , seq = 1\n , srcId = 1\n , dstId = broadcast\n , payload = (0xDE, 0xAD, 0xBE, 0xEF)\n , timestampUs = 0\n }\n\n-- | The encoded bytes of 'exampleFrame', for cross-language pinning tests.\n-- CRC computed as 0x42DD over bytes [0..14].\nexampleFrameBytes :: [Word8]\nexampleFrameBytes = encodeFrame exampleFrame"}], "text": "<|im_start|>\nsystem\nYou are an expert DCF (DeMoD Communication Framework) wire protocol implementer. You write byte-certified codecs for the 17-byte DeModFrame across multiple languages.\n\nTHE WIRE QUANTUM:\n- 17 bytes: sync(0xD3) | flags[ver|type] | seq | src | dst | payload(4B) | ts24 | crc16\n- Version nibble = 1 (always)\n- CRC-16/CCITT-FALSE over bytes [0..14], anchors: CRC(\"123456789\")=0x29B1, CRC(0^15)=0x4EC3\n- Valid iff sync byte + version nibble + CRC match\n\nCONVENTIONS:\n- Encode: take fields → pack into 17-byte buffer → compute CRC → write CRC at [15..16]\n- Decode: verify sync + version + CRC → unpack fields → return struct or error\n- All implementations MUST produce byte-identical output for identical input\n- Use big-endian for multi-byte fields (network byte order)\n- CRC polynomial: 0x1021, init: 0xFFFF, no final XOR\n- Test against golden_vectors.json (246 vectors: 109 encode + 137 syndrome)\n\n<|im_start|>\nuser\nImplement the DCF wire codec in Haskell.\n\nSpecification:\n# DCF Wire Quantum — Canonical Specification\n\n**Version 1** · DeMoD LLC · This document is normative.\n\nThe DCF wire protocol has exactly **one** wire format: the 17-byte `DeModFrame`\n(version nibble = 1). All other formats (the proto-message UDP header, the C\nSDK's `DCFMessageHeader`) are **adapters** over this quantum and must be\nexplicitly documented as such.\n\n## Wire Layout\n\n```\n Byte Field Width Description\n ──── ────────── ───── ─────────────────────────────────────────\n 0 sync 1 B Fixed 0xD3 (first validity gate)\n 1 flags 1 B [7:4] version (currently 1) | [3:0] type (0–3)\n 2–3 seq 2 B Big-endian u16, rolling sequence counter\n 4–5 src_id 2 B Big-endian u16, source node ID\n 6–7 dst_id 2 B Big-endian u16, destination (0xFFFF = broadcast)\n 8–11 payload 4 B Application data\n 12–14 timestamp 3 B 24-bit µs offset, big-endian, wraps ~16.7 s\n 15–16 crc16 2 B CRC-16/CCITT-FALSE over bytes [0..14]\n```\n\n**Total: 17 bytes = 136 bits.** The free field data is 108 bits (4+16+16+16+32+24).\n\n## Frame Types\n\n| Value | Name | Purpose |\n|-------|--------|-----------------------------|\n| 0 | DATA | Application payload |\n| 1 | ACK | Acknowledgement |\n| 2 | BEACON | Clock sync / broadcast |\n| 3 | CTRL | Control / fragmented audio |\n\n## Validity\n\nA frame is valid iff:\n1. `frame[0] == 0xD3` (sync byte)\n2. `(frame[1] >> 4) == 1` (version nibble)\n3. `CRC-16/CCITT-FALSE(frame[0..14]) == (frame[15] << 8) | frame[16]` (CRC)\n\nFor a random byte stream, the probability of a 17-byte window passing all three\nchecks is 2⁻²⁸ (Theorem 2.1, `wire_quanta_category.md`).\n\n## CRC-16/CCITT-FALSE\n\n- Polynomial: `0x1021`\n- Init: `0xFFFF`\n- RefIn/RefOut: `false`\n- XorOut: `0x0000`\n- Check value: `CRC(\"123456789\") = 0x29B1`\n\n## Anchors\n\n| Quantity | Value | Source |\n|----------|-------|--------|\n| CRC(\"123456789\") | `0x29B1` | Reference check value |\n| CRC(0¹⁵) | `0x4EC3` | Affine offset c |\n| CRC(exampleFrame body) | `0xA963` | Cross-language anchor |\n| exampleFrame | `D31312340001FFFFDEADBEEFAB12CD24C0` | type=CTRL, seq=0x1234, src=1, dst=0xFFFF, payload=DEADBEEF, ts=AB12CD |\n\n## Formal Properties\n\nThe frame is a **cemented retract** (Theorem 1, `wire_quanta_category.md`):\n- `encode` is injective with a left inverse `decode` (decode∘encode = id)\n- `encode` is a bijection onto the set of valid words\n- `decode` is the unique decoder satisfying the spec\n\nThe 246-vector finite certificate (Theorem 4) proves that any implementation\nmatching the 109 encode-basis + 137 syndrome-basis vectors equals the reference\non all 2¹⁰⁸ frames and classifies all 2¹³⁶ words identically. See\n`Documentation/golden_vectors.json`.\n\n## Reference Implementations\n\n| Language | File | Functions |\n|----------|------|-----------|\n| C | `codec/demod_frame.h` | `dcf_frame_encode`, `dcf_frame_decode`, `dcf_frame_crc` |\n| Rust | `codec/frame.rs` | `Frame::encode`, `Frame::decode` |\n| Python | `python/MCP/wirelab_core.py` | `encode`, `decode`, `syndrome`, `crc16_ccitt` |\n| Lua | `GUI/wirelab.lua` | `encode`, `decode`, `crc16` |\n\n## Certification\n\nTo certify a new SDK against the reference:\n\n```sh\npython3 python/MCP/certify_sdk.py --selftest # reference self-test\npython3 python/MCP/certify_sdk.py --sdk-json SDK.json # certify an external SDK\n```\n\nAll CI gates run `python/MCP/verify_laws.py` and `python/MCP/certify_sdk.py --selftest`.\nUnder Theorem 4, passing the 246-vector test is equivalent to agreement on the\nentire 2¹⁰⁸ × 2¹³⁶ input space.\n\n## Other Wire Formats ARE Adapters\n\n| Format | Status | Relationship to DeModFrame |\n|--------|--------|----------------------------|\n| Proto-message UDP header (C SDK) | Adapter | Must marshal to/from DeModFrame for wire |\n| `DCFMessageHeader` (C SDK) | Internal | In-process struct; must not appear on the wire |\n| Haskell `FrameSpec` | Implemented | `haskell/src/DCF/Transport/FrameSpec.hs` — encodeFrame / decodeFrame |\n\nAny new transport MUST emit and consume DeModFrame v1 on the wire. Internal\nrepresentations are free to differ but MUST be convertible to/from DeModFrame\nwithout loss.\n\nGolden vectors (sample):\n{\n \"encode_basis\": [\n {\n \"input_bits\": \"000000000000000000000000000\",\n \"frame\": \"d310000000000000000000000000005b80\"\n },\n {\n \"input_bit\": 0,\n \"frame\": \"d3110000000000000000000000000020e1\"\n },\n {\n \"input_bit\": 1,\n \"frame\": \"d31200000000000000000000000000ad42\"\n },\n {\n \"input_bit\": 2,\n \"frame\": \"d31400000000000000000000000000a625\"\n },\n {\n \"input_bit\": 3,\n \"frame\": \"d31800000000000000000000000000b0eb\"\n },\n {\n \"input_bit\": 4,\n \"frame\": \"d3100001000000000000000000000058f5\"\n },\n {\n \"input_bit\": 5,\n \"frame\": \"d310000200000000000000000000005d6a\"\n },\n {\n \"input_bit\": 6,\n \"frame\": \"d310000400000000000000000000005654\"\n },\n {\n \"input_bit\": 7,\n \"frame\": \"d310000800000000000000000000004028\"\n },\n {\n \"input_bit\": 8,\n \"frame\": \"d310001000000000000000000000006cd0\"\n }\n ],\n \"syndrome_basis\": [\n {\n \"word\": \"0000000000000000000000000000000000\",\n \"syndrome\": 20163\n },\n {\n \"bit\": 0,\n \"syndrome\": 6865\n },\n {\n \"bit\": 1,\n \"syndrome\": 25802\n },\n {\n \"bit\": 2,\n \"syndrome\": 54231\n },\n {\n \"bit\": 3,\n \"syndrome\": 73\n },\n {\n \"bit\": 4,\n \"syndrome\": 27014\n },\n {\n \"bit\": 5,\n \"syndrome\": 54641\n },\n {\n \"bit\": 6,\n \"syndrome\": 794\n },\n {\n \"bit\": 7,\n \"syndrome\": 57407\n },\n {\n \"bit\": 8,\n \"syndrome\": 6589\n }\n ]\n}\n\nProvide the complete implementation with encode/decode functions.\n<|im_start|>\nassistant\n-- SPDX-License-Identifier: LGPL-3.0-only\n{-|\nModule : DCF.Transport.FrameSpec\nDescription : DeMoD 17-byte transport frame codec — Haskell reference implementation\nCopyright : (c) DeMoD LLC\nLicense : LGPL-3.0\nMaintainer : info@demodllc.example\n\nThe canonical Haskell implementation of the DeMoD wire quantum.\n\nWire layout (17 bytes = 136 bits, all multi-byte fields big-endian):\n\n Byte Field Notes\n ───── ─────────── ──────────────────────────────────────────────────────\n 0 sync Fixed 0xD3 — first validity gate\n 1 flags [7:4] version (4-bit) | [3:0] frame type (4-bit)\n 2-3 seq Big-endian u16, rolling counter\n 4-5 src_id Big-endian u16, source node\n 6-7 dst_id Big-endian u16, 0xFFFF = broadcast\n 8-11 payload 4 raw application bytes\n 12-14 timestamp 24-bit big-endian µs offset, wraps ~16.7 s\n 15-16 crc16 CRC-CCITT(poly=0x1021, init=0xFFFF) over bytes [0..14]\n\nCross-language parity:\n C transport/dcf_frame.h dcf_frame_encode / dcf_frame_decode\n Haskell DCF.Transport.Frame encodeFrame / decodeFrame ← this file\n Lisp punctim.lisp encode-dcf-frame / decode-dcf-frame\n Rust dcf/rust/src/frame.rs Frame::encode / Frame::decode\n Python wirelab_core.py encode / decode\n\n-}\nmodule DCF.Transport.FrameSpec\n ( -- * Types\n FrameType(..)\n , Frame(..)\n , FrameError(..)\n -- * Constants\n , frameSize\n , syncByte\n , broadcast\n -- * Codec\n , encodeFrame\n , decodeFrame\n , isValidFrame\n -- * CRC\n , crc16ccitt\n -- * Reference test vector\n , exampleFrame\n , exampleFrameBytes\n ) where\n\nimport Prelude hiding (seq)\nimport Data.Bits (Bits, shiftL, shiftR, (.|.), (.&.), xor)\nimport Data.Word (Word8, Word16, Word32)\n\n-- ── Constants ──────────────────────────────────────────────────────────────\n\nframeSize :: Int\nframeSize = 17\n\nsyncByte :: Word8\nsyncByte = 0xD3\n\nbroadcast :: Word16\nbroadcast = 0xFFFF\n\ncrcCover :: Int\ncrcCover = 15\n\n-- ── Frame type ─────────────────────────────────────────────────────────────\n\ndata FrameType = Data | Ack | Beacon | Ctrl\n deriving (Eq, Show, Read, Enum, Bounded)\n\nframeTypeToNibble :: FrameType -> Word8\nframeTypeToNibble Data = 0\nframeTypeToNibble Ack = 1\nframeTypeToNibble Beacon = 2\nframeTypeToNibble Ctrl = 3\n\nnibbleToFrameType :: Word8 -> Maybe FrameType\nnibbleToFrameType n = case n .&. 0x0F of\n 0 -> Just Data\n 1 -> Just Ack\n 2 -> Just Beacon\n 3 -> Just Ctrl\n _ -> Nothing\n\n-- ── Frame (decoded, host-order fields) ─────────────────────────────────────\n\ndata Frame = Frame\n { version :: !Word8 -- ^ 4-bit, 0–15\n , frameType :: !FrameType\n , seq :: !Word16 -- ^ rolling counter\n , srcId :: !Word16 -- ^ source node\n , dstId :: !Word16 -- ^ dest node (broadcast = 0xFFFF)\n , payload :: !(Word8, Word8, Word8, Word8)\n , timestampUs :: !Word32 -- ^ 24-bit µs (top byte always 0)\n } deriving (Eq, Show)\n\n-- ── Decode error ───────────────────────────────────────────────────────────\n\ndata FrameError\n = BadLength\n | BadSync\n | BadCrc\n | UnknownType !Word8\n deriving (Eq, Show)\n\n-- ── CRC-CCITT ──────────────────────────────────────────────────────────────\n--\n-- Poly 0x1021, init 0xFFFF.\n-- Identical algorithm in C (dcf_crc16), Rust (crc16_ccitt), Python (crc16_ccitt).\n-- All four implementations must return the same value for the same input.\n\ncrc16ccitt :: [Word8] -> Word16\ncrc16ccitt = go 0xFFFF\n where\n go crc [] = crc\n go crc (b:bs) = go (step8 (crc `xor` (fromIntegral b `shiftL` 8))) bs\n\nstep8 :: Word16 -> Word16\nstep8 crc = foldl (\\c _ -> if c .&. 0x8000 /= 0\n then (c `shiftL` 1) `xor` 0x1021\n else c `shiftL` 1) crc [(0::Int)..7]\n\n-- ── Encode ────────────────────────────────────────────────────────────────\n--\n-- Serialise a Frame into exactly 17 bytes (big-endian).\n-- CRC is computed and appended automatically.\n\nencodeFrame :: Frame -> [Word8]\nencodeFrame f = take frameSize $ buf ++ [hi crc, lo crc]\n where\n buf = [ syncByte\n , ((version f .&. 0x0F) `shiftL` 4) .|. frameTypeToNibble (frameType f)\n , hi (seq f), lo (seq f)\n , hi (srcId f), lo (srcId f)\n , hi (dstId f), lo (dstId f)\n , a, b, c, d\n , fromIntegral ((timestampUs f `shiftR` 16) .&. 0xFF)\n , fromIntegral ((timestampUs f `shiftR` 8) .&. 0xFF)\n , fromIntegral ( timestampUs f .&. 0xFF)\n ]\n (a, b, c, d) = payload f\n crc = crc16ccitt (take crcCover buf)\n\nhi, lo :: (Integral a, Bits a, Num b) => a -> b\nhi w = fromIntegral (w `shiftR` 8)\nlo w = fromIntegral (w .&. 0xFF)\n\n-- ── Decode ────────────────────────────────────────────────────────────────\n--\n-- Parse a 17-byte wire buffer.\n-- Returns Left on invalid sync, CRC mismatch, or unknown frame type.\n\ndecodeFrame :: [Word8] -> Either FrameError Frame\ndecodeFrame buf\n | length buf /= frameSize = Left BadLength\n | head buf /= syncByte = Left BadSync\n | crc16ccitt (take crcCover buf) /= storedCrc = Left BadCrc\n | otherwise = case nibbleToFrameType (buf !! 1 .&. 0x0F) of\n Nothing -> Left (UnknownType (buf !! 1 .&. 0x0F))\n Just ft -> Right Frame\n { version = (buf !! 1 `shiftR` 4) .&. 0x0F\n , frameType = ft\n , seq = makeW16 (buf !! 2) (buf !! 3)\n , srcId = makeW16 (buf !! 4) (buf !! 5)\n , dstId = makeW16 (buf !! 6) (buf !! 7)\n , payload = (buf !! 8, buf !! 9, buf !! 10, buf !! 11)\n , timestampUs = makeW24 (buf !! 12) (buf !! 13) (buf !! 14)\n }\n where\n storedCrc = makeW16 (buf !! 15) (buf !! 16)\n\nmakeW16 :: Word8 -> Word8 -> Word16\nmakeW16 hi8 lo8 = fromIntegral hi8 `shiftL` 8 .|. fromIntegral lo8\n\nmakeW24 :: Word8 -> Word8 -> Word8 -> Word32\nmakeW24 a b c = fromIntegral a `shiftL` 16 .|. fromIntegral b `shiftL` 8 .|. fromIntegral c\n\n-- ── Validate (non-destructive) ─────────────────────────────────────────────\n\nisValidFrame :: [Word8] -> Bool\nisValidFrame buf\n | length buf /= frameSize = False\n | head buf /= syncByte = False\n | otherwise = crc16ccitt (take crcCover buf) == makeW16 (buf !! 15) (buf !! 16)\n\n-- ── Reference test vector ─────────────────────────────────────────────────\n--\n-- Matches the C dcf_frame.h reference, the Rust Frame::tests::reference_frame,\n-- and the Python wirelab_core anchors.\n-- version=1, FData, seq=1, src=1, dst=0xFFFF, payload=0xDEADBEEF, ts=0\n\nexampleFrame :: Frame\nexampleFrame = Frame\n { version = 1\n , frameType = Data\n , seq = 1\n , srcId = 1\n , dstId = broadcast\n , payload = (0xDE, 0xAD, 0xBE, 0xEF)\n , timestampUs = 0\n }\n\n-- | The encoded bytes of 'exampleFrame', for cross-language pinning tests.\n-- CRC computed as 0x42DD over bytes [0..14].\nexampleFrameBytes :: [Word8]\nexampleFrameBytes = encodeFrame exampleFrame\n"}
{"messages": [{"role": "system", "content": "You are an expert DCF (DeMoD Communication Framework) wire protocol implementer. You write byte-certified codecs for the 17-byte DeModFrame across multiple languages.\n\nTHE WIRE QUANTUM:\n- 17 bytes: sync(0xD3) | flags[ver|type] | seq | src | dst | payload(4B) | ts24 | crc16\n- Version nibble = 1 (always)\n- CRC-16/CCITT-FALSE over bytes [0..14], anchors: CRC(\"123456789\")=0x29B1, CRC(0^15)=0x4EC3\n- Valid iff sync byte + version nibble + CRC match\n\nCONVENTIONS:\n- Encode: take fields → pack into 17-byte buffer → compute CRC → write CRC at [15..16]\n- Decode: verify sync + version + CRC → unpack fields → return struct or error\n- All implementations MUST produce byte-identical output for identical input\n- Use big-endian for multi-byte fields (network byte order)\n- CRC polynomial: 0x1021, init: 0xFFFF, no final XOR\n- Test against golden_vectors.json (246 vectors: 109 encode + 137 syndrome)\n"}, {"role": "user", "content": "Implement the DCF wire codec in Lisp.\n\nSpecification:\n# DCF Wire Quantum — Canonical Specification\n\n**Version 1** · DeMoD LLC · This document is normative.\n\nThe DCF wire protocol has exactly **one** wire format: the 17-byte `DeModFrame`\n(version nibble = 1). All other formats (the proto-message UDP header, the C\nSDK's `DCFMessageHeader`) are **adapters** over this quantum and must be\nexplicitly documented as such.\n\n## Wire Layout\n\n```\n Byte Field Width Description\n ──── ────────── ───── ─────────────────────────────────────────\n 0 sync 1 B Fixed 0xD3 (first validity gate)\n 1 flags 1 B [7:4] version (currently 1) | [3:0] type (0–3)\n 2–3 seq 2 B Big-endian u16, rolling sequence counter\n 4–5 src_id 2 B Big-endian u16, source node ID\n 6–7 dst_id 2 B Big-endian u16, destination (0xFFFF = broadcast)\n 8–11 payload 4 B Application data\n 12–14 timestamp 3 B 24-bit µs offset, big-endian, wraps ~16.7 s\n 15–16 crc16 2 B CRC-16/CCITT-FALSE over bytes [0..14]\n```\n\n**Total: 17 bytes = 136 bits.** The free field data is 108 bits (4+16+16+16+32+24).\n\n## Frame Types\n\n| Value | Name | Purpose |\n|-------|--------|-----------------------------|\n| 0 | DATA | Application payload |\n| 1 | ACK | Acknowledgement |\n| 2 | BEACON | Clock sync / broadcast |\n| 3 | CTRL | Control / fragmented audio |\n\n## Validity\n\nA frame is valid iff:\n1. `frame[0] == 0xD3` (sync byte)\n2. `(frame[1] >> 4) == 1` (version nibble)\n3. `CRC-16/CCITT-FALSE(frame[0..14]) == (frame[15] << 8) | frame[16]` (CRC)\n\nFor a random byte stream, the probability of a 17-byte window passing all three\nchecks is 2⁻²⁸ (Theorem 2.1, `wire_quanta_category.md`).\n\n## CRC-16/CCITT-FALSE\n\n- Polynomial: `0x1021`\n- Init: `0xFFFF`\n- RefIn/RefOut: `false`\n- XorOut: `0x0000`\n- Check value: `CRC(\"123456789\") = 0x29B1`\n\n## Anchors\n\n| Quantity | Value | Source |\n|----------|-------|--------|\n| CRC(\"123456789\") | `0x29B1` | Reference check value |\n| CRC(0¹⁵) | `0x4EC3` | Affine offset c |\n| CRC(exampleFrame body) | `0xA963` | Cross-language anchor |\n| exampleFrame | `D31312340001FFFFDEADBEEFAB12CD24C0` | type=CTRL, seq=0x1234, src=1, dst=0xFFFF, payload=DEADBEEF, ts=AB12CD |\n\n## Formal Properties\n\nThe frame is a **cemented retract** (Theorem 1, `wire_quanta_category.md`):\n- `encode` is injective with a left inverse `decode` (decode∘encode = id)\n- `encode` is a bijection onto the set of valid words\n- `decode` is the unique decoder satisfying the spec\n\nThe 246-vector finite certificate (Theorem 4) proves that any implementation\nmatching the 109 encode-basis + 137 syndrome-basis vectors equals the reference\non all 2¹⁰⁸ frames and classifies all 2¹³⁶ words identically. See\n`Documentation/golden_vectors.json`.\n\n## Reference Implementations\n\n| Language | File | Functions |\n|----------|------|-----------|\n| C | `codec/demod_frame.h` | `dcf_frame_encode`, `dcf_frame_decode`, `dcf_frame_crc` |\n| Rust | `codec/frame.rs` | `Frame::encode`, `Frame::decode` |\n| Python | `python/MCP/wirelab_core.py` | `encode`, `decode`, `syndrome`, `crc16_ccitt` |\n| Lua | `GUI/wirelab.lua` | `encode`, `decode`, `crc16` |\n\n## Certification\n\nTo certify a new SDK against the reference:\n\n```sh\npython3 python/MCP/certify_sdk.py --selftest # reference self-test\npython3 python/MCP/certify_sdk.py --sdk-json SDK.json # certify an external SDK\n```\n\nAll CI gates run `python/MCP/verify_laws.py` and `python/MCP/certify_sdk.py --selftest`.\nUnder Theorem 4, passing the 246-vector test is equivalent to agreement on the\nentire 2¹⁰⁸ × 2¹³⁶ input space.\n\n## Other Wire Formats ARE Adapters\n\n| Format | Status | Relationship to DeModFrame |\n|--------|--------|----------------------------|\n| Proto-message UDP header (C SDK) | Adapter | Must marshal to/from DeModFrame for wire |\n| `DCFMessageHeader` (C SDK) | Internal | In-process struct; must not appear on the wire |\n| Haskell `FrameSpec` | Implemented | `haskell/src/DCF/Transport/FrameSpec.hs` — encodeFrame / decodeFrame |\n\nAny new transport MUST emit and consume DeModFrame v1 on the wire. Internal\nrepresentations are free to differ but MUST be convertible to/from DeModFrame\nwithout loss.\n\nGolden vectors (sample):\n{\n \"encode_basis\": [\n {\n \"input_bits\": \"000000000000000000000000000\",\n \"frame\": \"d310000000000000000000000000005b80\"\n },\n {\n \"input_bit\": 0,\n \"frame\": \"d3110000000000000000000000000020e1\"\n },\n {\n \"input_bit\": 1,\n \"frame\": \"d31200000000000000000000000000ad42\"\n },\n {\n \"input_bit\": 2,\n \"frame\": \"d31400000000000000000000000000a625\"\n },\n {\n \"input_bit\": 3,\n \"frame\": \"d31800000000000000000000000000b0eb\"\n },\n {\n \"input_bit\": 4,\n \"frame\": \"d3100001000000000000000000000058f5\"\n },\n {\n \"input_bit\": 5,\n \"frame\": \"d310000200000000000000000000005d6a\"\n },\n {\n \"input_bit\": 6,\n \"frame\": \"d310000400000000000000000000005654\"\n },\n {\n \"input_bit\": 7,\n \"frame\": \"d310000800000000000000000000004028\"\n },\n {\n \"input_bit\": 8,\n \"frame\": \"d310001000000000000000000000006cd0\"\n }\n ],\n \"syndrome_basis\": [\n {\n \"word\": \"0000000000000000000000000000000000\",\n \"syndrome\": 20163\n },\n {\n \"bit\": 0,\n \"syndrome\": 6865\n },\n {\n \"bit\": 1,\n \"syndrome\": 25802\n },\n {\n \"bit\": 2,\n \"syndrome\": 54231\n },\n {\n \"bit\": 3,\n \"syndrome\": 73\n },\n {\n \"bit\": 4,\n \"syndrome\": 27014\n },\n {\n \"bit\": 5,\n \"syndrome\": 54641\n },\n {\n \"bit\": 6,\n \"syndrome\": 794\n },\n {\n \"bit\": 7,\n \"syndrome\": 57407\n },\n {\n \"bit\": 8,\n \"syndrome\": 6589\n }\n ]\n}\n\nProvide the complete implementation with encode/decode functions."}, {"role": "assistant", "content": ";;;; SPDX-License-Identifier: LGPL-3.0-only\n;;;; lisp/src/wire.lisp — dependency-free DeModFrame wire codec + self-cert.\n;;;;\n;;;; Loadable under bare SBCL (no Quicklisp, no CFFI). The certify-lisp CI loads\n;;;; this file and exits non-zero unless the cross-language anchors match — the\n;;;; Lisp analogue of the dependency-free C cert (C_SDK/tests/test_wire_certify.c).\n;;;; The full SDK codec lives in punctim.lisp (its crc16-ccitt is identical and\n;;;; self-certifies on load); this file lets CI prove the wire algorithm without\n;;;; pulling the SDK's Quicklisp dependency graph.\n\n(defpackage :dcf-wire\n (:use :cl)\n (:export :crc16-ccitt :encode-frame :decode-frame :syndrome :certify\n :pack-super :unpack-super :superpackp))\n(in-package :dcf-wire)\n\n(defconstant +sync+ #xD3)\n(defconstant +version+ 1)\n(defconstant +frame-size+ 17)\n(defconstant +crc-cover+ 15)\n\n;; DCF SuperPack: a 32-byte container carrying two 17-byte frames under one joint\n;; CRC (34 -> 32 bytes). A frame pair ships as a single datagram instead of two —\n;; one packet, one IP/UDP header, one syscall — so paired traffic has strictly\n;; lower per-pair overhead and latency. The unpacked frames are ordinary valid\n;; DeModFrames, so the 246-vector wire certificate is untouched.\n(defconstant +super-type+ #x05)\n(defconstant +super-len+ 32)\n(defconstant +super-core-len+ 14)\n(defconstant +super-sflags+ (logior (ash +version+ 4) +super-type+))\n\n(defun crc16-ccitt (vec &optional (start 0) (end (length vec)))\n \"CRC-16/CCITT-FALSE (poly #x1021, init #xFFFF) over VEC[START..END).\"\n (let ((crc #xFFFF))\n (loop for i from start below end do\n (setf crc (logand #xFFFF (logxor crc (ash (aref vec i) 8))))\n (loop repeat 8 do\n (setf crc (if (logbitp 15 crc)\n (logand (logxor (ash crc 1) #x1021) #xFFFF)\n (logand (ash crc 1) #xFFFF)))))\n crc))\n\n(defun u16 (hi lo) (logior (ash hi 8) lo))\n\n(defun encode-frame (&key (version 1) (type 0) (seq 0) (src 0) (dst 0)\n (payload #(0 0 0 0)) (ts-us 0))\n \"Serialise into a 17-byte (unsigned-byte 8) vector with an appended CRC.\"\n (let ((b (make-array +frame-size+ :element-type '(unsigned-byte 8)\n :initial-element 0)))\n (setf (aref b 0) +sync+\n (aref b 1) (logior (ash (logand version #x0F) 4) (logand type #x0F))\n (aref b 2) (logand (ash seq -8) #xFF) (aref b 3) (logand seq #xFF)\n (aref b 4) (logand (ash src -8) #xFF) (aref b 5) (logand src #xFF)\n (aref b 6) (logand (ash dst -8) #xFF) (aref b 7) (logand dst #xFF))\n (dotimes (i 4) (setf (aref b (+ 8 i)) (aref payload i)))\n (setf (aref b 12) (logand (ash ts-us -16) #xFF)\n (aref b 13) (logand (ash ts-us -8) #xFF)\n (aref b 14) (logand ts-us #xFF))\n (let ((crc (crc16-ccitt b 0 +crc-cover+)))\n (setf (aref b 15) (logand (ash crc -8) #xFF)\n (aref b 16) (logand crc #xFF)))\n b))\n\n(defun syndrome (w)\n \"Affine validity syndrome: W is CRC-valid iff this returns 0.\"\n (logxor (crc16-ccitt w 0 +crc-cover+) (u16 (aref w 15) (aref w 16))))\n\n(defun decode-frame (w)\n \"Return a plist of fields, or NIL if W is not a valid 17-byte frame.\"\n (when (and (= (length w) +frame-size+)\n (= (aref w 0) +sync+)\n (= (ash (aref w 1) -4) +version+)\n (zerop (syndrome w)))\n (list :version (ash (aref w 1) -4)\n :type (logand (aref w 1) #x0F)\n :seq (u16 (aref w 2) (aref w 3))\n :src (u16 (aref w 4) (aref w 5))\n :dst (u16 (aref w 6) (aref w 7))\n :payload (subseq w 8 12)\n :ts-us (logior (ash (aref w 12) 16) (ash (aref w 13) 8) (aref w 14)))))\n\n(defun %frame-core (f)\n \"The 14 reconstructable bytes of a 17-byte frame, or NIL if F is not valid.\"\n (when (and (= (length f) +frame-size+)\n (= (aref f 0) +sync+)\n (= (ash (aref f 1) -4) +version+)\n (= (crc16-ccitt f 0 +crc-cover+) (u16 (aref f 15) (aref f 16))))\n (subseq f 1 15)))\n\n(defun %rebuild-frame (core)\n \"Rebuild a full 17-byte frame from its 14-byte CORE (sync + recomputed crc).\"\n (let ((f (make-array +frame-size+ :element-type '(unsigned-byte 8) :initial-element 0)))\n (setf (aref f 0) +sync+)\n (dotimes (i +super-core-len+) (setf (aref f (+ 1 i)) (aref core i)))\n (let ((crc (crc16-ccitt f 0 +crc-cover+)))\n (setf (aref f 15) (logand (ash crc -8) #xFF)\n (aref f 16) (logand crc #xFF)))\n f))\n\n(defun pack-super (a b)\n \"Combine two valid 17-byte frames into one 32-byte SuperPack, or NIL on failure.\"\n (let ((ca (%frame-core a)) (cb (%frame-core b)))\n (when (and ca cb)\n (let ((out (make-array +super-len+ :element-type '(unsigned-byte 8) :initial-element 0)))\n (setf (aref out 0) +sync+ (aref out 1) +super-sflags+)\n (dotimes (i +super-core-len+)\n (setf (aref out (+ 2 i)) (aref ca i)\n (aref out (+ 2 +super-core-len+ i)) (aref cb i)))\n (let ((crc (crc16-ccitt out 0 30)))\n (setf (aref out 30) (logand (ash crc -8) #xFF)\n (aref out 31) (logand crc #xFF)))\n out))))\n\n(defun superpackp (buf)\n \"True iff BUF looks like a SuperPack (length + sync + version/type tag).\"\n (and (= (length buf) +super-len+)\n (= (aref buf 0) +sync+)\n (= (aref buf 1) +super-sflags+)))\n\n(defun unpack-super (buf)\n \"Split a 32-byte SuperPack into (values frame-a frame-b), or NIL on failure.\"\n (when (and (= (length buf) +super-len+)\n (= (aref buf 0) +sync+)\n (= (ash (aref buf 1) -4) +version+)\n (= (logand (aref buf 1) #x0F) +super-type+)\n (= (crc16-ccitt buf 0 30) (u16 (aref buf 30) (aref buf 31))))\n (let ((a (%rebuild-frame (subseq buf 2 16)))\n (b (%rebuild-frame (subseq buf 16 30))))\n (when (and (decode-frame a) (decode-frame b))\n (values a b)))))\n\n(defun certify ()\n \"Self-cert against the cross-language anchors; returns :CERTIFIED or signals.\"\n (let ((anchor (map '(vector (unsigned-byte 8)) #'char-code \"123456789\"))\n (zeros (make-array 15 :element-type '(unsigned-byte 8) :initial-element 0))\n (want (coerce #(#xD3 #x13 #x12 #x34 #x00 #x01 #xFF #xFF\n #xDE #xAD #xBE #xEF #xAB #x12 #xCD #x24 #xC0)\n '(vector (unsigned-byte 8)))))\n (assert (= (crc16-ccitt anchor) #x29B1) ()\n \"crc16(\\\"123456789\\\")=#x~4,'0X, want #x29B1\" (crc16-ccitt anchor))\n (assert (= (crc16-ccitt zeros) #x4EC3) ()\n \"crc16(0^15)=#x~4,'0X, want #x4EC3\" (crc16-ccitt zeros))\n ;; golden exampleFrame_full: Ctrl(3) seq #x1234 src 1 dst #xFFFF DEADBEEF ts #xAB12CD\n (let ((ex (encode-frame :version 1 :type 3 :seq #x1234 :src 1 :dst #xFFFF\n :payload #(#xDE #xAD #xBE #xEF) :ts-us #xAB12CD)))\n (assert (equalp ex want) () \"exampleFrame_full mismatch\")\n (let ((d (decode-frame ex)))\n (assert d () \"exampleFrame failed to decode\")\n (assert (= (getf d :seq) #x1234) () \"exampleFrame seq mismatch\")\n (assert (equalp (getf d :payload) #(#xDE #xAD #xBE #xEF)) () \"payload mismatch\"))\n (let ((bad (copy-seq ex)))\n (setf (aref bad 9) (logxor (aref bad 9) 1))\n (assert (null (decode-frame bad)) () \"corrupted frame was ACCEPTED\")))\n ;; SuperPack container vectors (subset embedded from superpack_vectors.json).\n (flet ((hx (s)\n (let ((v (make-array (/ (length s) 2) :element-type '(unsigned-byte 8))))\n (dotimes (i (length v) v)\n (setf (aref v i)\n (parse-integer s :start (* 2 i) :end (+ 2 (* 2 i)) :radix 16))))))\n (dolist (c '((\"d310000000000000000000000000005b80\" \"d31312340001ffffdeadbeefab12cd24c0\"\n \"d31510000000000000000000000000001312340001ffffdeadbeefab12cd2435\")\n (\"d310010203040506cafebabe010203f4af\" \"d3117fffa1a100b270696e670000ff93b3\"\n \"d31510010203040506cafebabe010203117fffa1a100b270696e670000ff2ea0\")\n (\"d31200a010002000ff00ff00ffffffb630\" \"d313ffffffffffffffffffffffffff00fc\"\n \"d3151200a010002000ff00ff00ffffff13ffffffffffffffffffffffffff02d4\")))\n (destructuring-bind (ah bh sh) c\n (let ((a (hx ah)) (b (hx bh)) (sp (hx sh)))\n (assert (equalp (pack-super a b) sp) () \"superpack pack mismatch\")\n (assert (superpackp sp) () \"superpack not recognised\")\n (multiple-value-bind (ra rb) (unpack-super sp)\n (assert (and (equalp ra a) (equalp rb b)) () \"superpack unpack mismatch\")))))\n ;; zero-core joint CRC anchor = #x5B75\n (let* ((zero (encode-frame :version 1 :type 0))\n (spz (pack-super zero zero)))\n (assert (= (u16 (aref spz 30) (aref spz 31)) #x5B75) ()\n \"superpack zero-core joint CRC anchor\")))\n :certified))\n\n;; Self-certify on load (the certify-lisp CI just loads this file).\n(eval-when (:load-toplevel :execute)\n (handler-case\n (progn (certify)\n (format t \"~&;; dcf-wire (lisp): CERTIFIED — crc16 #x29B1 / #x4EC3, exampleFrame + SuperPack OK~%\"))\n (error (e)\n (format *error-output* \"~&;; dcf-wire (lisp): FAILED — ~A~%\" e)\n #+sbcl (sb-ext:exit :code 1))))\n"}], "text": "<|im_start|>\nsystem\nYou are an expert DCF (DeMoD Communication Framework) wire protocol implementer. You write byte-certified codecs for the 17-byte DeModFrame across multiple languages.\n\nTHE WIRE QUANTUM:\n- 17 bytes: sync(0xD3) | flags[ver|type] | seq | src | dst | payload(4B) | ts24 | crc16\n- Version nibble = 1 (always)\n- CRC-16/CCITT-FALSE over bytes [0..14], anchors: CRC(\"123456789\")=0x29B1, CRC(0^15)=0x4EC3\n- Valid iff sync byte + version nibble + CRC match\n\nCONVENTIONS:\n- Encode: take fields → pack into 17-byte buffer → compute CRC → write CRC at [15..16]\n- Decode: verify sync + version + CRC → unpack fields → return struct or error\n- All implementations MUST produce byte-identical output for identical input\n- Use big-endian for multi-byte fields (network byte order)\n- CRC polynomial: 0x1021, init: 0xFFFF, no final XOR\n- Test against golden_vectors.json (246 vectors: 109 encode + 137 syndrome)\n\n<|im_start|>\nuser\nImplement the DCF wire codec in Lisp.\n\nSpecification:\n# DCF Wire Quantum — Canonical Specification\n\n**Version 1** · DeMoD LLC · This document is normative.\n\nThe DCF wire protocol has exactly **one** wire format: the 17-byte `DeModFrame`\n(version nibble = 1). All other formats (the proto-message UDP header, the C\nSDK's `DCFMessageHeader`) are **adapters** over this quantum and must be\nexplicitly documented as such.\n\n## Wire Layout\n\n```\n Byte Field Width Description\n ──── ────────── ───── ─────────────────────────────────────────\n 0 sync 1 B Fixed 0xD3 (first validity gate)\n 1 flags 1 B [7:4] version (currently 1) | [3:0] type (0–3)\n 2–3 seq 2 B Big-endian u16, rolling sequence counter\n 4–5 src_id 2 B Big-endian u16, source node ID\n 6–7 dst_id 2 B Big-endian u16, destination (0xFFFF = broadcast)\n 8–11 payload 4 B Application data\n 12–14 timestamp 3 B 24-bit µs offset, big-endian, wraps ~16.7 s\n 15–16 crc16 2 B CRC-16/CCITT-FALSE over bytes [0..14]\n```\n\n**Total: 17 bytes = 136 bits.** The free field data is 108 bits (4+16+16+16+32+24).\n\n## Frame Types\n\n| Value | Name | Purpose |\n|-------|--------|-----------------------------|\n| 0 | DATA | Application payload |\n| 1 | ACK | Acknowledgement |\n| 2 | BEACON | Clock sync / broadcast |\n| 3 | CTRL | Control / fragmented audio |\n\n## Validity\n\nA frame is valid iff:\n1. `frame[0] == 0xD3` (sync byte)\n2. `(frame[1] >> 4) == 1` (version nibble)\n3. `CRC-16/CCITT-FALSE(frame[0..14]) == (frame[15] << 8) | frame[16]` (CRC)\n\nFor a random byte stream, the probability of a 17-byte window passing all three\nchecks is 2⁻²⁸ (Theorem 2.1, `wire_quanta_category.md`).\n\n## CRC-16/CCITT-FALSE\n\n- Polynomial: `0x1021`\n- Init: `0xFFFF`\n- RefIn/RefOut: `false`\n- XorOut: `0x0000`\n- Check value: `CRC(\"123456789\") = 0x29B1`\n\n## Anchors\n\n| Quantity | Value | Source |\n|----------|-------|--------|\n| CRC(\"123456789\") | `0x29B1` | Reference check value |\n| CRC(0¹⁵) | `0x4EC3` | Affine offset c |\n| CRC(exampleFrame body) | `0xA963` | Cross-language anchor |\n| exampleFrame | `D31312340001FFFFDEADBEEFAB12CD24C0` | type=CTRL, seq=0x1234, src=1, dst=0xFFFF, payload=DEADBEEF, ts=AB12CD |\n\n## Formal Properties\n\nThe frame is a **cemented retract** (Theorem 1, `wire_quanta_category.md`):\n- `encode` is injective with a left inverse `decode` (decode∘encode = id)\n- `encode` is a bijection onto the set of valid words\n- `decode` is the unique decoder satisfying the spec\n\nThe 246-vector finite certificate (Theorem 4) proves that any implementation\nmatching the 109 encode-basis + 137 syndrome-basis vectors equals the reference\non all 2¹⁰⁸ frames and classifies all 2¹³⁶ words identically. See\n`Documentation/golden_vectors.json`.\n\n## Reference Implementations\n\n| Language | File | Functions |\n|----------|------|-----------|\n| C | `codec/demod_frame.h` | `dcf_frame_encode`, `dcf_frame_decode`, `dcf_frame_crc` |\n| Rust | `codec/frame.rs` | `Frame::encode`, `Frame::decode` |\n| Python | `python/MCP/wirelab_core.py` | `encode`, `decode`, `syndrome`, `crc16_ccitt` |\n| Lua | `GUI/wirelab.lua` | `encode`, `decode`, `crc16` |\n\n## Certification\n\nTo certify a new SDK against the reference:\n\n```sh\npython3 python/MCP/certify_sdk.py --selftest # reference self-test\npython3 python/MCP/certify_sdk.py --sdk-json SDK.json # certify an external SDK\n```\n\nAll CI gates run `python/MCP/verify_laws.py` and `python/MCP/certify_sdk.py --selftest`.\nUnder Theorem 4, passing the 246-vector test is equivalent to agreement on the\nentire 2¹⁰⁸ × 2¹³⁶ input space.\n\n## Other Wire Formats ARE Adapters\n\n| Format | Status | Relationship to DeModFrame |\n|--------|--------|----------------------------|\n| Proto-message UDP header (C SDK) | Adapter | Must marshal to/from DeModFrame for wire |\n| `DCFMessageHeader` (C SDK) | Internal | In-process struct; must not appear on the wire |\n| Haskell `FrameSpec` | Implemented | `haskell/src/DCF/Transport/FrameSpec.hs` — encodeFrame / decodeFrame |\n\nAny new transport MUST emit and consume DeModFrame v1 on the wire. Internal\nrepresentations are free to differ but MUST be convertible to/from DeModFrame\nwithout loss.\n\nGolden vectors (sample):\n{\n \"encode_basis\": [\n {\n \"input_bits\": \"000000000000000000000000000\",\n \"frame\": \"d310000000000000000000000000005b80\"\n },\n {\n \"input_bit\": 0,\n \"frame\": \"d3110000000000000000000000000020e1\"\n },\n {\n \"input_bit\": 1,\n \"frame\": \"d31200000000000000000000000000ad42\"\n },\n {\n \"input_bit\": 2,\n \"frame\": \"d31400000000000000000000000000a625\"\n },\n {\n \"input_bit\": 3,\n \"frame\": \"d31800000000000000000000000000b0eb\"\n },\n {\n \"input_bit\": 4,\n \"frame\": \"d3100001000000000000000000000058f5\"\n },\n {\n \"input_bit\": 5,\n \"frame\": \"d310000200000000000000000000005d6a\"\n },\n {\n \"input_bit\": 6,\n \"frame\": \"d310000400000000000000000000005654\"\n },\n {\n \"input_bit\": 7,\n \"frame\": \"d310000800000000000000000000004028\"\n },\n {\n \"input_bit\": 8,\n \"frame\": \"d310001000000000000000000000006cd0\"\n }\n ],\n \"syndrome_basis\": [\n {\n \"word\": \"0000000000000000000000000000000000\",\n \"syndrome\": 20163\n },\n {\n \"bit\": 0,\n \"syndrome\": 6865\n },\n {\n \"bit\": 1,\n \"syndrome\": 25802\n },\n {\n \"bit\": 2,\n \"syndrome\": 54231\n },\n {\n \"bit\": 3,\n \"syndrome\": 73\n },\n {\n \"bit\": 4,\n \"syndrome\": 27014\n },\n {\n \"bit\": 5,\n \"syndrome\": 54641\n },\n {\n \"bit\": 6,\n \"syndrome\": 794\n },\n {\n \"bit\": 7,\n \"syndrome\": 57407\n },\n {\n \"bit\": 8,\n \"syndrome\": 6589\n }\n ]\n}\n\nProvide the complete implementation with encode/decode functions.\n<|im_start|>\nassistant\n;;;; SPDX-License-Identifier: LGPL-3.0-only\n;;;; lisp/src/wire.lisp — dependency-free DeModFrame wire codec + self-cert.\n;;;;\n;;;; Loadable under bare SBCL (no Quicklisp, no CFFI). The certify-lisp CI loads\n;;;; this file and exits non-zero unless the cross-language anchors match — the\n;;;; Lisp analogue of the dependency-free C cert (C_SDK/tests/test_wire_certify.c).\n;;;; The full SDK codec lives in punctim.lisp (its crc16-ccitt is identical and\n;;;; self-certifies on load); this file lets CI prove the wire algorithm without\n;;;; pulling the SDK's Quicklisp dependency graph.\n\n(defpackage :dcf-wire\n (:use :cl)\n (:export :crc16-ccitt :encode-frame :decode-frame :syndrome :certify\n :pack-super :unpack-super :superpackp))\n(in-package :dcf-wire)\n\n(defconstant +sync+ #xD3)\n(defconstant +version+ 1)\n(defconstant +frame-size+ 17)\n(defconstant +crc-cover+ 15)\n\n;; DCF SuperPack: a 32-byte container carrying two 17-byte frames under one joint\n;; CRC (34 -> 32 bytes). A frame pair ships as a single datagram instead of two —\n;; one packet, one IP/UDP header, one syscall — so paired traffic has strictly\n;; lower per-pair overhead and latency. The unpacked frames are ordinary valid\n;; DeModFrames, so the 246-vector wire certificate is untouched.\n(defconstant +super-type+ #x05)\n(defconstant +super-len+ 32)\n(defconstant +super-core-len+ 14)\n(defconstant +super-sflags+ (logior (ash +version+ 4) +super-type+))\n\n(defun crc16-ccitt (vec &optional (start 0) (end (length vec)))\n \"CRC-16/CCITT-FALSE (poly #x1021, init #xFFFF) over VEC[START..END).\"\n (let ((crc #xFFFF))\n (loop for i from start below end do\n (setf crc (logand #xFFFF (logxor crc (ash (aref vec i) 8))))\n (loop repeat 8 do\n (setf crc (if (logbitp 15 crc)\n (logand (logxor (ash crc 1) #x1021) #xFFFF)\n (logand (ash crc 1) #xFFFF)))))\n crc))\n\n(defun u16 (hi lo) (logior (ash hi 8) lo))\n\n(defun encode-frame (&key (version 1) (type 0) (seq 0) (src 0) (dst 0)\n (payload #(0 0 0 0)) (ts-us 0))\n \"Serialise into a 17-byte (unsigned-byte 8) vector with an appended CRC.\"\n (let ((b (make-array +frame-size+ :element-type '(unsigned-byte 8)\n :initial-element 0)))\n (setf (aref b 0) +sync+\n (aref b 1) (logior (ash (logand version #x0F) 4) (logand type #x0F))\n (aref b 2) (logand (ash seq -8) #xFF) (aref b 3) (logand seq #xFF)\n (aref b 4) (logand (ash src -8) #xFF) (aref b 5) (logand src #xFF)\n (aref b 6) (logand (ash dst -8) #xFF) (aref b 7) (logand dst #xFF))\n (dotimes (i 4) (setf (aref b (+ 8 i)) (aref payload i)))\n (setf (aref b 12) (logand (ash ts-us -16) #xFF)\n (aref b 13) (logand (ash ts-us -8) #xFF)\n (aref b 14) (logand ts-us #xFF))\n (let ((crc (crc16-ccitt b 0 +crc-cover+)))\n (setf (aref b 15) (logand (ash crc -8) #xFF)\n (aref b 16) (logand crc #xFF)))\n b))\n\n(defun syndrome (w)\n \"Affine validity syndrome: W is CRC-valid iff this returns 0.\"\n (logxor (crc16-ccitt w 0 +crc-cover+) (u16 (aref w 15) (aref w 16))))\n\n(defun decode-frame (w)\n \"Return a plist of fields, or NIL if W is not a valid 17-byte frame.\"\n (when (and (= (length w) +frame-size+)\n (= (aref w 0) +sync+)\n (= (ash (aref w 1) -4) +version+)\n (zerop (syndrome w)))\n (list :version (ash (aref w 1) -4)\n :type (logand (aref w 1) #x0F)\n :seq (u16 (aref w 2) (aref w 3))\n :src (u16 (aref w 4) (aref w 5))\n :dst (u16 (aref w 6) (aref w 7))\n :payload (subseq w 8 12)\n :ts-us (logior (ash (aref w 12) 16) (ash (aref w 13) 8) (aref w 14)))))\n\n(defun %frame-core (f)\n \"The 14 reconstructable bytes of a 17-byte frame, or NIL if F is not valid.\"\n (when (and (= (length f) +frame-size+)\n (= (aref f 0) +sync+)\n (= (ash (aref f 1) -4) +version+)\n (= (crc16-ccitt f 0 +crc-cover+) (u16 (aref f 15) (aref f 16))))\n (subseq f 1 15)))\n\n(defun %rebuild-frame (core)\n \"Rebuild a full 17-byte frame from its 14-byte CORE (sync + recomputed crc).\"\n (let ((f (make-array +frame-size+ :element-type '(unsigned-byte 8) :initial-element 0)))\n (setf (aref f 0) +sync+)\n (dotimes (i +super-core-len+) (setf (aref f (+ 1 i)) (aref core i)))\n (let ((crc (crc16-ccitt f 0 +crc-cover+)))\n (setf (aref f 15) (logand (ash crc -8) #xFF)\n (aref f 16) (logand crc #xFF)))\n f))\n\n(defun pack-super (a b)\n \"Combine two valid 17-byte frames into one 32-byte SuperPack, or NIL on failure.\"\n (let ((ca (%frame-core a)) (cb (%frame-core b)))\n (when (and ca cb)\n (let ((out (make-array +super-len+ :element-type '(unsigned-byte 8) :initial-element 0)))\n (setf (aref out 0) +sync+ (aref out 1) +super-sflags+)\n (dotimes (i +super-core-len+)\n (setf (aref out (+ 2 i)) (aref ca i)\n (aref out (+ 2 +super-core-len+ i)) (aref cb i)))\n (let ((crc (crc16-ccitt out 0 30)))\n (setf (aref out 30) (logand (ash crc -8) #xFF)\n (aref out 31) (logand crc #xFF)))\n out))))\n\n(defun superpackp (buf)\n \"True iff BUF looks like a SuperPack (length + sync + version/type tag).\"\n (and (= (length buf) +super-len+)\n (= (aref buf 0) +sync+)\n (= (aref buf 1) +super-sflags+)))\n\n(defun unpack-super (buf)\n \"Split a 32-byte SuperPack into (values frame-a frame-b), or NIL on failure.\"\n (when (and (= (length buf) +super-len+)\n (= (aref buf 0) +sync+)\n (= (ash (aref buf 1) -4) +version+)\n (= (logand (aref buf 1) #x0F) +super-type+)\n (= (crc16-ccitt buf 0 30) (u16 (aref buf 30) (aref buf 31))))\n (let ((a (%rebuild-frame (subseq buf 2 16)))\n (b (%rebuild-frame (subseq buf 16 30))))\n (when (and (decode-frame a) (decode-frame b))\n (values a b)))))\n\n(defun certify ()\n \"Self-cert against the cross-language anchors; returns :CERTIFIED or signals.\"\n (let ((anchor (map '(vector (unsigned-byte 8)) #'char-code \"123456789\"))\n (zeros (make-array 15 :element-type '(unsigned-byte 8) :initial-element 0))\n (want (coerce #(#xD3 #x13 #x12 #x34 #x00 #x01 #xFF #xFF\n #xDE #xAD #xBE #xEF #xAB #x12 #xCD #x24 #xC0)\n '(vector (unsigned-byte 8)))))\n (assert (= (crc16-ccitt anchor) #x29B1) ()\n \"crc16(\\\"123456789\\\")=#x~4,'0X, want #x29B1\" (crc16-ccitt anchor))\n (assert (= (crc16-ccitt zeros) #x4EC3) ()\n \"crc16(0^15)=#x~4,'0X, want #x4EC3\" (crc16-ccitt zeros))\n ;; golden exampleFrame_full: Ctrl(3) seq #x1234 src 1 dst #xFFFF DEADBEEF ts #xAB12CD\n (let ((ex (encode-frame :version 1 :type 3 :seq #x1234 :src 1 :dst #xFFFF\n :payload #(#xDE #xAD #xBE #xEF) :ts-us #xAB12CD)))\n (assert (equalp ex want) () \"exampleFrame_full mismatch\")\n (let ((d (decode-frame ex)))\n (assert d () \"exampleFrame failed to decode\")\n (assert (= (getf d :seq) #x1234) () \"exampleFrame seq mismatch\")\n (assert (equalp (getf d :payload) #(#xDE #xAD #xBE #xEF)) () \"payload mismatch\"))\n (let ((bad (copy-seq ex)))\n (setf (aref bad 9) (logxor (aref bad 9) 1))\n (assert (null (decode-frame bad)) () \"corrupted frame was ACCEPTED\")))\n ;; SuperPack container vectors (subset embedded from superpack_vectors.json).\n (flet ((hx (s)\n (let ((v (make-array (/ (length s) 2) :element-type '(unsigned-byte 8))))\n (dotimes (i (length v) v)\n (setf (aref v i)\n (parse-integer s :start (* 2 i) :end (+ 2 (* 2 i)) :radix 16))))))\n (dolist (c '((\"d310000000000000000000000000005b80\" \"d31312340001ffffdeadbeefab12cd24c0\"\n \"d31510000000000000000000000000001312340001ffffdeadbeefab12cd2435\")\n (\"d310010203040506cafebabe010203f4af\" \"d3117fffa1a100b270696e670000ff93b3\"\n \"d31510010203040506cafebabe010203117fffa1a100b270696e670000ff2ea0\")\n (\"d31200a010002000ff00ff00ffffffb630\" \"d313ffffffffffffffffffffffffff00fc\"\n \"d3151200a010002000ff00ff00ffffff13ffffffffffffffffffffffffff02d4\")))\n (destructuring-bind (ah bh sh) c\n (let ((a (hx ah)) (b (hx bh)) (sp (hx sh)))\n (assert (equalp (pack-super a b) sp) () \"superpack pack mismatch\")\n (assert (superpackp sp) () \"superpack not recognised\")\n (multiple-value-bind (ra rb) (unpack-super sp)\n (assert (and (equalp ra a) (equalp rb b)) () \"superpack unpack mismatch\")))))\n ;; zero-core joint CRC anchor = #x5B75\n (let* ((zero (encode-frame :version 1 :type 0))\n (spz (pack-super zero zero)))\n (assert (= (u16 (aref spz 30) (aref spz 31)) #x5B75) ()\n \"superpack zero-core joint CRC anchor\")))\n :certified))\n\n;; Self-certify on load (the certify-lisp CI just loads this file).\n(eval-when (:load-toplevel :execute)\n (handler-case\n (progn (certify)\n (format t \"~&;; dcf-wire (lisp): CERTIFIED — crc16 #x29B1 / #x4EC3, exampleFrame + SuperPack OK~%\"))\n (error (e)\n (format *error-output* \"~&;; dcf-wire (lisp): FAILED — ~A~%\" e)\n #+sbcl (sb-ext:exit :code 1))))\n\n"}