← Commit history
SKILL.mdadded+51
@@ -0,0 +1,51 @@+---+name: lan7800-programmer+description: "Read, edit, and program the EEPROM of a Microchip LAN7800 USB-3.1 to Gigabit-Ethernet controller (VID 0x0424 / PID 0x7800) on Linux — MPLAB-Connect parity. Trigger words: LAN7800, program EEPROM, change MAC address on USB ethernet adapter, edit VID/PID, dump EEPROM to bin, LED/GPIO config, verify a network adapter, MPLAB Connect on Linux, flash a Microchip USB gigabit dongle."+user-invocable: true+---++# LAN7800 EEPROM Programmer++Read the EEPROM off a Microchip **LAN7800** USB-3.1→GbE adapter, edit+MAC / VID / PID / bcdDevice / strings / serial and LED/GPIO with a byte-exact+preview, and program a physical adapter with verify-after-write. **LAN7800 only**+(VID `0x0424` / PID `0x7800`).++## Safety model (read first)++- **Reads are free.** `scan`, `read`, `read-device`, `info`, `verify`, `edit`,+  and preview never touch hardware.+- **Physical writes are gated.** Only `program` and `erase` change an adapter,+  and both refuse unless `--force-physical-write` is passed. Set that flag only+  after a deliberate, confirmed decision — the webapp never sets it and returns+  the exact command for a human to run instead.+- **Keep a backup** before any write: `lan7800prog read --iface <if> --out backup.bin`.++## CLI (single source of truth)++```bash+lan7800prog scan                                   # FREE — enumerate LAN7800s+lan7800prog read-device --out dump.bin             # FREE — read connected adapter+lan7800prog info --in dump.bin                     # parse fields, config, LED/GPIO+lan7800prog edit --in dump.bin --out out.bin \+  --mac 00:80:0F:12:34:56 --serial SN0001 --ensure-signature+lan7800prog verify --iface <if> --image out.bin    # FREE — diff device vs image+# GATED — only after a confirmed decision:+lan7800prog program --iface <if> --image out.bin --force-physical-write+```++Every command prints `OK:` / `ERROR:` + `Hint:` lines and supports `--json`.++## Webapp++```bash+lan7800-programmer         # launches the Hydrogen webapp on http://127.0.0.1:8747+```++Scan → Load a `.bin` (or read a device) → edit fields + LED/GPIO with a live+byte-exact preview → save. `Program to device` is intentionally gated and shows+the exact command to run. State lives on the server (`GET /state`, `/console`,+`/scan`) so it is AI-drivable.++See `README.md` for the full command reference and `docs/` for the EEPROM+mechanism and MPLAB-Connect parity notes.
cli/lan7800/__init__.pyadded+2
@@ -0,0 +1,2 @@+"""LAN7800 EEPROM programmer — Core v1 engine (LAN7800 only)."""+__version__ = "1.0.0"
cli/lan7800/backends/__init__.pyadded+7
@@ -0,0 +1,7 @@+from .base import EepromBackend, BackendError+from .binfile import BinFileBackend+from .ethtool import EthtoolBackend+from .usb import UsbEepromBackend, udev_rule, udev_install_commands++__all__ = ["EepromBackend", "BackendError", "BinFileBackend", "EthtoolBackend",+           "UsbEepromBackend", "udev_rule", "udev_install_commands"]
cli/lan7800/backends/base.pyadded+43
@@ -0,0 +1,43 @@+"""Pluggable EEPROM access backends.++A backend abstracts *where the bytes come from and go to*. The engine and CLI+only ever deal with whole-image reads and per-byte/whole-image writes, so a new+transport (libusb) can be added later without touching field logic.++Contract:+  - read_image() -> bytes            (FREE; never gated)+  - write_bytes(offset, values)      (GATED; physical writes require escalation+                                      handled one layer up, in the CLI)+  - reload()                         (ask the device to reload its EEPROM image)++Backends must NOT perform escalation themselves; the CLI owns the human-in-the-+loop gate so the policy lives in exactly one place.+"""+from __future__ import annotations++import abc+++class BackendError(Exception):+    pass+++class EepromBackend(abc.ABC):+    #: True if this backend talks to real hardware (writes must be escalated).+    physical: bool = False+    name: str = "base"++    @abc.abstractmethod+    def read_image(self) -> bytes:+        """Return the full EEPROM image. Free / non-destructive."""++    @abc.abstractmethod+    def write_bytes(self, offset: int, values: bytes) -> None:+        """Write `values` starting at `offset`. May be per-byte under the hood."""++    def reload(self) -> None:+        """Optional: ask the device to reload the EEPROM (replug equivalent)."""+        raise BackendError(f"{self.name} backend does not support reload")++    def close(self) -> None:+        pass
cli/lan7800/backends/binfile.pyadded+50
@@ -0,0 +1,50 @@+"""Offline .bin-file backend — the default, hardware-free path.++Everything except the final program-to-adapter step happens here: load a base+image, edit fields, preview, save. Writes to a file are still "writes" but they+are NOT physical, so they are not gated behind hardware escalation (the CLI+distinguishes physical from file writes via `backend.physical`). File overwrites+are protected by `mesh backup` in the CLI, not here.+"""+from __future__ import annotations++import os++from .base import EepromBackend, BackendError+from ..eeprom import MAX_EEPROM_SIZE, SIZES+++class BinFileBackend(EepromBackend):+    physical = False+    name = "binfile"++    def __init__(self, path: str, size: int = MAX_EEPROM_SIZE):+        self.path = path+        self.size = size++    def read_image(self) -> bytes:+        if not os.path.exists(self.path):+            raise BackendError(f"no such .bin file: {self.path}")+        with open(self.path, "rb") as fh:+            data = fh.read()+        if len(data) not in SIZES:+            # not fatal — the image model tolerates/pads — but surface it+            pass+        return data++    def write_bytes(self, offset: int, values: bytes) -> None:+        # Read-modify-write the file image.+        if os.path.exists(self.path):+            with open(self.path, "rb") as fh:+                buf = bytearray(fh.read())+        else:+            buf = bytearray(self.size)+        if len(buf) < offset + len(values):+            buf.extend(bytearray(offset + len(values) - len(buf)))+        buf[offset:offset + len(values)] = values+        with open(self.path, "wb") as fh:+            fh.write(buf)++    def write_image(self, data: bytes) -> None:+        with open(self.path, "wb") as fh:+            fh.write(data)
cli/lan7800/backends/ethtool.pyadded+93
@@ -0,0 +1,93 @@+"""ethtool backend — the RECOMMENDED physical path (in-tree lan78xx driver).++Read:  `ethtool -e <iface> raw on`            -> full image on stdout (bytes)+Write: `ethtool -E <iface> magic 0x78A5 offset <o> value <v>`  (one byte / call)++The driver issues EWEN internally on the -E path, so we never manage EWEN/EWDS+here. Per-byte writes are how the hardware works; the CLI batches a field's+bytes and calls write_bytes(), which loops one `ethtool -E` per byte.++This backend is `physical = True`; the CLI MUST escalate before any write.+Reads are free. We never call ethtool here from any read path other than+read_image(), and read_image() is non-destructive.+"""+from __future__ import annotations++import shutil+import subprocess++from .base import EepromBackend, BackendError+from ..eeprom import EEPROM_MAGIC, MAX_EEPROM_SIZE+++class EthtoolBackend(EepromBackend):+    physical = True+    name = "ethtool"++    def __init__(self, iface: str, size: int = MAX_EEPROM_SIZE, sudo: bool = True):+        self.iface = iface+        self.size = size+        self.sudo = sudo+        if shutil.which("ethtool") is None:+            raise BackendError("ethtool not found on PATH; install ethtool")++    def _cmd(self, args: list[str]) -> list[str]:+        # sudo -n (non-interactive): if passwordless ethtool is configured it+        # works; otherwise it fails FAST instead of hanging on a password prompt+        # (there is no TTY). Callers treat that failure as "ethtool unavailable".+        base = ["sudo", "-n"] if self.sudo else []+        return base + ["ethtool"] + args++    def read_image(self) -> bytes:+        # `-e <iface> raw on` streams the raw EEPROM bytes to stdout.+        proc = subprocess.run(+            self._cmd(["-e", self.iface, "raw", "on"]),+            capture_output=True)+        if proc.returncode != 0:+            raise BackendError(self._clean_err(proc.stderr, proc.returncode))+        return proc.stdout++    @staticmethod+    def _clean_err(stderr: bytes, rc) -> str:+        """Map raw ethtool/sudo stderr to a clean, non-leaky message."""+        err = stderr.decode(errors="replace").strip()+        low = err.lower()+        if "enodata" in low or "no data" in low:+            return ("EEPROM reads as blank/unsigned (byte0 != 0xA5); "+                    "no valid image present")+        if "sudo" in low or "password" in low or "terminal is required" in low:+            return ("ethtool needs elevated access to read the EEPROM; "+                    "grant passwordless sudo for ethtool or run with privilege")+        if "no such device" in low or "no device" in low:+            return "no such network device (is the lan78xx netdev bound?)"+        if "operation not permitted" in low:+            return "operation not permitted; ethtool needs elevated access"+        return f"ethtool error (rc={rc})"++    def read_range(self, offset: int, length: int) -> bytes:+        proc = subprocess.run(+            self._cmd(["-e", self.iface, "raw", "on",+                       "offset", str(offset), "length", str(length)]),+            capture_output=True)+        if proc.returncode != 0:+            raise BackendError(self._clean_err(proc.stderr, proc.returncode))+        return proc.stdout++    def write_bytes(self, offset: int, values: bytes) -> None:+        for i, v in enumerate(values):+            o = offset + i+            proc = subprocess.run(+                self._cmd(["-E", self.iface,+                           "magic", hex(EEPROM_MAGIC),+                           "offset", str(o), "value", str(v)]),+                capture_output=True)+            if proc.returncode != 0:+                raise BackendError(+                    f"write failed at offset {o}: "+                    f"{self._clean_err(proc.stderr, proc.returncode)}")++    def reload(self) -> None:+        # No safe in-band reload; require a replug / usb reset. Surface clearly.+        raise BackendError(+            "reload the EEPROM by replugging the adapter or issuing a USB reset; "+            "the driver does not expose a safe RELOAD on this path")
cli/lan7800/backends/usb.pyadded+272
@@ -0,0 +1,272 @@+"""libusb backend, driver-independent EEPROM access via USB vendor commands.++Primary path when the LAN7800 has NO lan78xx netdev (so ethtool cannot reach it).+Talks to the chip directly with libusb-1.0 via ctypes (no pyusb / pip install+needed; uses the system libusb-1.0.so.0). Implements the EEPROM read protocol+from docs/01 section B:++  read reg  : bmRequestType 0xC0, bRequest 0xA1, wIndex=reg  -> 4 bytes LE+  write reg : bmRequestType 0x40, bRequest 0xA0, wIndex=reg  <- 4 bytes LE+  read byte A: write E2P_CMD = BUSY|READ|A ; poll BUSY clear ; read E2P_DATA[7:0]+  write byte : EWEN ; write E2P_DATA ; write E2P_CMD=BUSY|WRITE|A ; poll ; EWDS++Runtime needs USB read/write access to 0424:7800 (a udev rule; see udev_rule()).+Root is NOT required at runtime once the rule is installed.+"""+from __future__ import annotations++import ctypes as C+import time++from .base import EepromBackend, BackendError+from ..eeprom import LAN7800_VID, LAN7800_PID, MAX_EEPROM_SIZE++# LAN78xx register map (docs/01)+HW_CFG = 0x010+# On the LAN7800, the EEPROM interface pins (EECLK/EEDI/EEDO) are MUXED with the+# LED0/LED1 outputs. While these LED enables are set, the EEPROM bus is NOT+# connected -- reads return 0x00 and writes silently no-op. The in-kernel lan78xx+# driver clears these before every EEPROM access and restores them after; we must+# do the same or nothing reaches the chip. (lan78xx.h: HW_CFG_LEDx_EN_)+HW_CFG_LED0_EN = 0x00100000+HW_CFG_LED1_EN = 0x00200000+E2P_CMD = 0x040+E2P_DATA = 0x044+E2P_BUSY = 0x80000000+# EPC_TIMEOUT status bit. On the LAN7800 this is bit 10 (0x00000400), NOT the+# bit-30 value some LAN78xx docs list -- confirmed on hardware (RESEARCH). When+# the EEPROM bus is unreachable (LED pin-mux still enabled, or no chip), the+# command "completes" (BUSY clears) with this bit SET and E2P_DATA reads 0x00;+# the OLD code ignored it and returned 0x00-as-blank. Each fresh E2P_CMD write+# (addr <= 0x1FF, so bits 9/10 are 0) clears any stale timeout before the op.+E2P_TIMEOUT = 0x00000400+E2P_CMD_READ = 0x0 << 28+E2P_CMD_EWEN = 0x2 << 28+E2P_CMD_WRITE = 0x3 << 28+E2P_CMD_EWDS = 0x1 << 28+E2P_ADDR_MASK = 0x1FF++# USB vendor request constants+VENDOR_READ_TYPE = 0xC0+VENDOR_WRITE_TYPE = 0x40+REQ_READ_REG = 0xA1+REQ_WRITE_REG = 0xA0++UDEV_RULE_PATH = "/etc/udev/rules.d/99-lan7800.rules"+++def udev_rule() -> str:+    # GROUP=plugdev + 0660 grants the container user (a plugdev member) rw on+    # the device node. NOTE: TAG+="uaccess"/MODE 0660 root:root does NOT work in+    # a headless container (uaccess needs a logind seat; 0660 root:root excludes+    # the user). Use 0666 instead if the running user is not in plugdev.+    return ('SUBSYSTEM=="usb", ATTR{idVendor}=="0424", ATTR{idProduct}=="7800", '+            'GROUP="plugdev", MODE="0660"')+++def udev_install_commands() -> list[str]:+    return [+        f'echo \'{udev_rule()}\' | sudo tee {UDEV_RULE_PATH}',+        "sudo udevadm control --reload-rules",+        "sudo udevadm trigger --subsystem-match=usb --attr-match=idVendor=0424",+        "# then unplug + replug the adapter so the new node gets the rule",+    ]+++class _LibUSB:+    """Thin ctypes shim over the pieces of libusb-1.0 we use."""++    def __init__(self):+        try:+            self.lib = C.CDLL("libusb-1.0.so.0")+        except OSError as e:+            raise BackendError(f"libusb-1.0 not available: {e}")+        L = self.lib+        L.libusb_init.argtypes = [C.POINTER(C.c_void_p)]+        L.libusb_open_device_with_vid_pid.restype = C.c_void_p+        L.libusb_open_device_with_vid_pid.argtypes = [C.c_void_p, C.c_uint16, C.c_uint16]+        L.libusb_close.argtypes = [C.c_void_p]+        L.libusb_exit.argtypes = [C.c_void_p]+        L.libusb_kernel_driver_active.argtypes = [C.c_void_p, C.c_int]+        L.libusb_detach_kernel_driver.argtypes = [C.c_void_p, C.c_int]+        L.libusb_attach_kernel_driver.argtypes = [C.c_void_p, C.c_int]+        L.libusb_claim_interface.argtypes = [C.c_void_p, C.c_int]+        L.libusb_release_interface.argtypes = [C.c_void_p, C.c_int]+        L.libusb_control_transfer.restype = C.c_int+        L.libusb_control_transfer.argtypes = [+            C.c_void_p, C.c_uint8, C.c_uint8, C.c_uint16, C.c_uint16,+            C.POINTER(C.c_ubyte), C.c_uint16, C.c_uint]+        self.ctx = C.c_void_p()+        if L.libusb_init(C.byref(self.ctx)) != 0:+            raise BackendError("libusb_init failed")++    def open(self, vid, pid):+        h = self.lib.libusb_open_device_with_vid_pid(self.ctx, vid, pid)+        if not h:+            raise BackendError(+                f"cannot open USB {vid:04x}:{pid:04x} (device absent, or no "+                f"permission; install the udev rule and replug)")+        return C.c_void_p(h)++    def close(self, h):+        if h:+            self.lib.libusb_close(h)++    def exit(self):+        if self.ctx:+            self.lib.libusb_exit(self.ctx)+++def can_access() -> bool:+    """True if we can OPEN 0424:7800 (USB access granted), without claiming or+    detaching the kernel driver. A gentle probe for 'is the udev rule live yet'."""+    try:+        u = _LibUSB()+    except BackendError:+        return False+    try:+        h = u.lib.libusb_open_device_with_vid_pid(u.ctx, LAN7800_VID, LAN7800_PID)+        if h:+            u.lib.libusb_close(C.c_void_p(h))+            return True+        return False+    finally:+        u.exit()+++class UsbEepromBackend(EepromBackend):+    physical = True+    name = "libusb"++    def __init__(self, size: int = MAX_EEPROM_SIZE, iface: int = 0):+        self.size = size+        self.iface = iface+        self._usb = _LibUSB()+        self._h = None+        self._detached = False++    # -- lifecycle --------------------------------------------------------+    def _ensure_open(self):+        if self._h is not None:+            return+        # Open the handle ONLY. We deliberately do NOT detach the kernel driver+        # or claim the interface: the LAN78xx register reads/writes go through+        # ep0 (the default control endpoint) via control transfers, which do NOT+        # require claiming an interface. Detach/claim would need CAP_NET_ADMIN+        # (i.e. root) and would disrupt the bound lan78xx netdev. Staying on ep0+        # keeps the read fully sudo-free and non-disruptive.+        self._h = self._usb.open(LAN7800_VID, LAN7800_PID)++    def close(self):+        if self._h is not None:+            self._usb.close(self._h)+            self._h = None+        self._usb.exit()++    # -- register access --------------------------------------------------+    def _read_reg(self, reg: int) -> int:+        buf = (C.c_ubyte * 4)()+        n = self._usb.lib.libusb_control_transfer(+            self._h, VENDOR_READ_TYPE, REQ_READ_REG, 0, reg, buf, 4, 2000)+        if n != 4:+            raise BackendError(f"read reg 0x{reg:03x} failed (libusb rc {n})")+        return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24)++    def _write_reg(self, reg: int, val: int) -> None:+        buf = (C.c_ubyte * 4)(val & 0xFF, (val >> 8) & 0xFF,+                              (val >> 16) & 0xFF, (val >> 24) & 0xFF)+        n = self._usb.lib.libusb_control_transfer(+            self._h, VENDOR_WRITE_TYPE, REQ_WRITE_REG, 0, reg, buf, 4, 2000)+        if n != 4:+            raise BackendError(f"write reg 0x{reg:03x} failed (libusb rc {n})")++    def _wait_not_busy(self, timeout_s: float = 1.0, poll_s: float = 0.0005) -> None:+        """Poll E2P_CMD until BUSY clears, bounded by wall-clock time (NOT a raw+        iteration count). A serial EEPROM cell-program cycle is ~5-10 ms; USB+        register reads are ~tens of us, so a fixed small iteration cap (the old+        100 tries) could elapse in ~5 ms and give up mid-write. Sleep between+        polls and bound by real time so one write cycle always fits, and report+        the EPC_TIMEOUT status bit truthfully when the chip itself aborts."""+        deadline = time.monotonic() + timeout_s+        while True:+            cmd = self._read_reg(E2P_CMD)+            if not (cmd & E2P_BUSY):+                if cmd & E2P_TIMEOUT:+                    raise BackendError(+                        "EEPROM unreachable (E2P_CMD EPC_TIMEOUT set): the LED "+                        "pin-mux is still enabled, or no EEPROM device is "+                        "present. The E2P operation did NOT complete -- refusing "+                        "to report a false blank/success.")+                return+            if time.monotonic() >= deadline:+                raise BackendError(+                    f"E2P_CMD BUSY never cleared within {timeout_s:.1f}s "+                    f"(EEPROM timeout; last E2P_CMD=0x{cmd:08X})")+            time.sleep(poll_s)++    # -- EEPROM pin-mux gate ----------------------------------------------+    def _begin_eeprom(self) -> int:+        """Connect the EEPROM bus by clearing the LED0/LED1 pin-mux enables in+        HW_CFG (they share pins with EECLK/EEDI/EEDO). Returns the prior HW_CFG+        so _end_eeprom can restore it. Mirrors the in-kernel lan78xx driver."""+        saved = self._read_reg(HW_CFG)+        self._write_reg(HW_CFG, saved & ~(HW_CFG_LED0_EN | HW_CFG_LED1_EN))+        return saved++    def _end_eeprom(self, saved: int) -> None:+        self._write_reg(HW_CFG, saved)++    # -- EEPROM byte ops --------------------------------------------------+    def _read_byte(self, addr: int) -> int:+        self._write_reg(E2P_CMD, E2P_BUSY | E2P_CMD_READ | (addr & E2P_ADDR_MASK))+        self._wait_not_busy()+        return self._read_reg(E2P_DATA) & 0xFF++    def _write_byte(self, addr: int, val: int) -> None:+        self._write_reg(E2P_CMD, E2P_BUSY | E2P_CMD_EWEN)      # enable writes+        self._wait_not_busy()+        self._write_reg(E2P_DATA, val & 0xFF)+        self._write_reg(E2P_CMD, E2P_BUSY | E2P_CMD_WRITE | (addr & E2P_ADDR_MASK))+        self._wait_not_busy()+        self._write_reg(E2P_CMD, E2P_BUSY | E2P_CMD_EWDS)      # disable writes+        self._wait_not_busy()++    # -- backend API ------------------------------------------------------+    def read_image(self) -> bytes:+        self._ensure_open()+        saved = self._begin_eeprom()+        try:+            return bytes(self._read_byte(a) for a in range(self.size))+        finally:+            self._end_eeprom(saved)++    def write_bytes(self, offset: int, values: bytes) -> None:+        self._ensure_open()+        saved = self._begin_eeprom()+        try:+            for i, v in enumerate(values):+                self._write_byte(offset + i, v)+        finally:+            self._end_eeprom(saved)++    def program_image(self, data: bytes) -> None:+        """Program a whole EEPROM image sudo-free via ep0 control transfers.++        EWEN once, write every byte EXCEPT byte0, then write byte0 (the 0xA5+        signature) LAST so a partially-written image is never treated as valid+        (anti-brick), then EWDS. No interface claim / kernel-driver detach.+        """+        self._ensure_open()+        saved = self._begin_eeprom()+        try:+            self._write_reg(E2P_CMD, E2P_BUSY | E2P_CMD_EWEN)+            self._wait_not_busy()+            order = list(range(1, len(data))) + [0]   # byte0 (signature) last+            for a in order:+                self._write_reg(E2P_DATA, data[a])+                self._write_reg(E2P_CMD, E2P_BUSY | E2P_CMD_WRITE | (a & E2P_ADDR_MASK))+                self._wait_not_busy()+            self._write_reg(E2P_CMD, E2P_BUSY | E2P_CMD_EWDS)+            self._wait_not_busy()+        finally:+            self._end_eeprom(saved)
cli/lan7800/bulk.pyadded+180
@@ -0,0 +1,180 @@+"""Bulk program mode: program many LAN7800 adapters in one run with an+auto-incrementing identity (MAC + serial), a RESUMABLE manifest, and+verify-after-write.++The sequence math and manifest here are hardware-free and unit-tested. The+per-unit burn reuses the exact LED-mux-gated UsbEepromBackend.program_image ++read-back verify that `program` uses.++SAFETY: a real identity write requires --force-physical-write AND (per the mesh)+a session-scoped allow for the run. The default and the dev/test path is+--dry-run: compute + log the whole sequence and write DRYRUN manifest rows, with+NO device access and NO writes.+"""+from __future__ import annotations++import csv+import json+import os+from datetime import datetime, timezone++from .eeprom import Eeprom, EepromError, parse_mac+++# ---- MAC / serial sequence math (pure, no hardware) -----------------------+def mac_to_int(octets) -> int:+    v = 0+    for b in octets:+        v = (v << 8) | b+    return v+++def int_to_mac(v: int) -> list:+    if not 0 <= v <= 0xFFFFFFFFFFFF:+        raise EepromError(f"MAC integer out of 48-bit range: 0x{v:012X}")+    return [(v >> (8 * (5 - i))) & 0xFF for i in range(6)]+++def mac_str(octets) -> str:+    return ":".join(f"{b:02X}" for b in octets)+++def serial_for(octets, scheme: str = "mac-hex") -> str:+    """Default scheme: iSerial = the MAC as uppercase hex with no separators,+    so the serial tracks the MAC 1:1 (matches the factory 00800F780000)."""+    if scheme == "mac-hex":+        return "".join(f"{b:02X}" for b in octets)+    raise EepromError(f"unknown serial scheme {scheme!r} (known: mac-hex)")+++def apply_local_admin(octets) -> list:+    """Force the locally-administered bit (0x02) and clear the multicast bit+    (0x01) of the first octet -- the '02:'-style prefix option."""+    o = list(octets)+    o[0] = (o[0] | 0x02) & ~0x01+    return o+++def sequence(base_mac: str, count: int, step: int = 1,+             local_admin: bool = False, scheme: str = "mac-hex") -> list:+    """Compute the full [{index, mac, serial}] plan. Refuses a multicast base,+    a run that overflows 48 bits, or one that crosses out of the base OUI+    (top 24 bits) -- i.e. NIC space exhausted."""+    if count < 1:+        raise EepromError("count must be >= 1")+    if step == 0:+        raise EepromError("step must be non-zero")+    base = parse_mac(base_mac)+    if local_admin:+        base = apply_local_admin(base)+    if base[0] & 0x01:+        raise EepromError(f"base MAC {mac_str(base)} is MULTICAST (low bit of "+                          "first octet set); a NIC MAC must be unicast")+    base_int = mac_to_int(base)+    base_oui = base_int >> 24+    out = []+    seen = set()+    for i in range(count):+        v = base_int + i * step+        octets = int_to_mac(v)               # raises on 48-bit overflow+        if (v >> 24) != base_oui:+            raise EepromError(+                f"unit {i}: MAC {mac_str(octets)} crosses out of the base OUI "+                f"{base_oui:06X} (NIC space exhausted) -- reduce count/step or "+                "pick a base with more headroom")+        m = mac_str(octets)+        if m in seen:+            raise EepromError(f"internal: duplicate MAC {m} in sequence")+        seen.add(m)+        out.append({"index": i, "mac": m, "serial": serial_for(octets, scheme)})+    return out+++# ---- per-unit image build -------------------------------------------------+def build_image(template: Eeprom, mac: str, serial: str,+                set_serial: bool = True) -> bytes:+    """Clone the template and stamp this unit's identity. Signature is ensured;+    program_image writes byte0 (0xA5) LAST for anti-brick ordering."""+    e = Eeprom.from_bytes(template.to_bytes())+    e.set_signature()+    e.set_mac(mac)+    if set_serial:+        try:+            e.set_string_inplace("serial", serial)+        except EepromError as ex:+            raise EepromError(+                f"cannot stamp serial {serial!r}: {ex}. Provide a --template "+                "whose 'serial' string slot fits the 12-char MAC-hex serial.")+    return e.to_bytes()+++# ---- resumable manifest (CSV + JSON) --------------------------------------+MANIFEST_FIELDS = ["index", "timestamp", "usb_path", "old_mac", "old_serial",+                   "new_mac", "new_serial", "verify"]+_DONE_STATES = ("PASS", "DRYRUN")+++class Manifest:+    """Append-only run record, mirrored to <path>.csv and <path>.json. Resumable:+    next_index() skips completed rows and burned_macs() blocks MAC reuse."""++    def __init__(self, csv_path: str):+        root = os.path.splitext(csv_path)[0]+        self.csv_path = root + ".csv" if not csv_path.endswith(".csv") else csv_path+        self.json_path = root + ".json"+        self.rows = []+        self._load()++    def _load(self):+        if os.path.exists(self.csv_path):+            with open(self.csv_path, newline="") as f:+                self.rows = [dict(r) for r in csv.DictReader(f)]++    def burned_macs(self) -> set:+        return {(r.get("new_mac") or "").upper()+                for r in self.rows+                if str(r.get("verify", "")).upper() in _DONE_STATES+                and r.get("new_mac")}++    def has_mac(self, mac: str) -> bool:+        return mac.upper() in self.burned_macs()++    def next_index(self) -> int:+        done = [int(r["index"]) for r in self.rows+                if str(r.get("verify", "")).upper() in _DONE_STATES]+        return (max(done) + 1) if done else 0++    def last_burned_mac(self):+        """MAC of the most recent REAL (PASS) burn, for the not-swapped guard.+        DRYRUN rows are ignored (a preview never programmed a physical unit)."""+        for r in reversed(self.rows):+            if str(r.get("verify", "")).upper() == "PASS" and r.get("new_mac"):+                return r["new_mac"]+        return None++    def append(self, *, index, usb_path, old_mac, old_serial,+               new_mac, new_serial, verify):+        if verify.upper() in _DONE_STATES and self.has_mac(new_mac):+            raise EepromError(+                f"REFUSING to reuse MAC {new_mac}: already burned in this run "+                f"(manifest {self.csv_path}). Each MAC must be unique.")+        self.rows.append({+            "index": index,+            "timestamp": datetime.now(timezone.utc).isoformat(),+            "usb_path": usb_path or "",+            "old_mac": old_mac or "",+            "old_serial": old_serial or "",+            "new_mac": new_mac or "",+            "new_serial": new_serial or "",+            "verify": verify,+        })+        self._flush()++    def _flush(self):+        with open(self.csv_path, "w", newline="") as f:+            w = csv.DictWriter(f, fieldnames=MANIFEST_FIELDS)+            w.writeheader()+            for r in self.rows:+                w.writerow({k: r.get(k, "") for k in MANIFEST_FIELDS})+        with open(self.json_path, "w") as f:+            json.dump(self.rows, f, indent=2)
cli/lan7800/cli.pyadded+721
@@ -0,0 +1,721 @@+"""lan7800prog — LAN7800 EEPROM programmer CLI (Core v1, LAN7800 ONLY).++Design contract (Adom AI-oriented CLI):+  * Every command prints a human line: `OK: ...`, or `ERROR: ...` + `Hint: ...`.+  * `--json` additionally emits one machine-readable object on stdout.+  * Reads are FREE. The ONLY commands that touch a physical adapter are+    `program` and `erase`; both refuse unless `--force-physical-write` is+    given. That flag is the safety catch — the operator/agent must have a+    cleared `mesh escalate` PROCEED before setting it. The webapp never sets it+    without an escalation.++Field edits produce a .bin image (file->file). Hardware programming is a+separate, explicit, gated step (load base -> edit -> preview .bin -> program).+"""+from __future__ import annotations++import argparse+import json+import sys++from .eeprom import (Eeprom, EepromError, parse_u16, LAN7800_VID, LAN7800_PID,+                     SIG_VALUE, SIZES, MAX_EEPROM_SIZE)+from .backends import (BinFileBackend, EthtoolBackend, UsbEepromBackend,+                       BackendError, udev_rule, udev_install_commands)+from .scan import scan_devices, diagnose_netdev+from . import regs+++# ---- output helpers -------------------------------------------------------+def _emit(args, ok, payload=None, human=None, hint=None):+    if getattr(args, "json", False):+        obj = {"ok": ok}+        if payload:+            obj.update(payload)+        if not ok and human:+            obj["error"] = human+        if hint:+            obj["hint"] = hint+        print(json.dumps(obj))+    else:+        if ok:+            if human:+                print(f"OK: {human}")+        else:+            print(f"ERROR: {human}", file=sys.stderr)+            if hint:+                print(f"Hint: {hint}", file=sys.stderr)+    return 0 if ok else 1+++def _fail(args, human, hint=None):+    return _emit(args, False, human=human, hint=hint)+++# ---- image sourcing -------------------------------------------------------+def _load_image_from_in(args) -> Eeprom:+    if not getattr(args, "in_file", None):+        raise EepromError("this command needs --in <base.bin>")+    data = BinFileBackend(args.in_file).read_image()+    return Eeprom.from_bytes(data)+++def _read_device_image(iface: str, sudo: bool) -> Eeprom:+    data = EthtoolBackend(iface, sudo=sudo).read_image()+    return Eeprom.from_bytes(data)+++def _describe(eep: Eeprom) -> dict:+    descs = []+    lan7800_seen = False+    for d in eep.descriptors():+        if d.present and d.vid == LAN7800_VID and d.pid == LAN7800_PID:+            lan7800_seen = True+        descs.append({+            "kind": d.kind, "present": d.present, "looks_valid": d.looks_valid,+            "ptr_word": d.ptr_word, "byte_offset": d.byte_offset,+            "vid": (f"0x{d.vid:04X}" if d.vid is not None else None),+            "pid": (f"0x{d.pid:04X}" if d.pid is not None else None),+            "bcd_device": (f"0x{d.bcd_device:04X}" if d.bcd_device is not None else None),+        })+    strings = [{"name": s.name, "present": s.present, "value": s.value,+                "byte_offset": s.byte_offset} for s in eep.strings()]+    return {+        "size": eep.size,+        "signature": f"0x{eep.signature:02X}",+        "signature_ok": eep.has_signature,+        "mac": eep.mac,+        "descriptors": descs,+        "strings": strings,+        "config_flags": [f"0x{v:08X}" for v in eep.config_flags()],+        "lan7800_identity": lan7800_seen,+        "regs": regs.describe_regs(eep),+    }+++# ---- commands -------------------------------------------------------------+def cmd_scan(args):+    """Enumerate attached LAN7800 adapters (FREE)."""+    devices = scan_devices(probe_eeprom=not args.no_probe)+    if not getattr(args, "json", False):+        if not devices:+            print("OK: no LAN7800 (0x0424/0x7800) adapters found")+            return 0+        print(f"OK: {len(devices)} LAN7800 adapter(s):")+        for d in devices:+            iface = d["iface"] or "(no netdev bound)"+            print(f"  usb {d['usb_path']} (bus {d['busnum']}/dev {d['devnum']})  "+                  f"{iface}  driver={d['driver'] or '-'}")+            print(f"    MAC={d['mac'] or '?'}  EEPROM={d['eeprom']}  "+                  f"product={d['product'] or '?'}")+        return 0+    return _emit(args, True, {"count": len(devices), "devices": devices})+++def cmd_read_device(args):+    """Read the CURRENTLY-CONNECTED LAN7800, auto-picking the backend.++    netdev present -> ethtool; else -> libusb (driver-independent). FREE read.+    """+    devices = scan_devices(probe_eeprom=False)+    if not devices:+        return _fail(args, "no LAN7800 (0x0424/0x7800) adapter connected",+                     hint="plug in the adapter, or run `scan`")+    dev = devices[0]+    data = None+    backend_used = None+    errors = []+    # libusb is PRIMARY: no sudo, permissioned via the plugdev udev rule, and it+    # works even when this flapping adapter has no stable lan78xx netdev. ethtool+    # is only a fallback, tried when libusb is unavailable AND a netdev exists;+    # its "needs sudo" failure is NOT surfaced as the headline error when libusb+    # is the real path.+    try:+        backend_used = "libusb"+        be = UsbEepromBackend(size=args.size)+        try:+            data = be.read_image()+        finally:+            be.close()+    except BackendError as e:+        errors.append(f"libusb: {e}")+        data = None+    if data is None and dev.get("iface"):+        try:+            backend_used = f"ethtool:{dev['iface']}"+            data = EthtoolBackend(dev["iface"], sudo=args.sudo).read_image()+        except BackendError as e:+            errors.append(f"ethtool: {e}")+            data = None+    if data is None:+        payload = {"device": dev, "errors": errors,+                   "udev_rule": udev_rule(),+                   "udev_install_commands": udev_install_commands(),+                   "netdev_diagnosis": diagnose_netdev(dev["usb_path"])}+        return _emit(args, False, payload,+                     human="could not read the connected device (libusb primary)",+                     hint="libusb needs the plugdev udev rule "+                          "(udev_install_commands) then a replug; no sudo/root "+                          "required. ethtool is only a fallback and needs a "+                          "netdev + passwordless sudo.")+    eep = Eeprom.from_bytes(data)+    view = _describe(eep)+    view["backend"] = backend_used+    view["device"] = dev+    view["raw_head_hex"] = data[:64].hex()+    if not dev.get("iface"):+        view["netdev_diagnosis"] = diagnose_netdev(dev["usb_path"])+    if args.out:+        BinFileBackend(args.out).write_image(data)+        view["out"] = args.out+    if not getattr(args, "json", False):+        print(f"OK: read {len(data)}B from {dev['usb_path']} via {backend_used}"+              f"  sig={view['signature']} "+              f"({'valid' if view['signature_ok'] else 'blank/invalid'})")+        print(f"  MAC: {view['mac']}")+        return 0+    return _emit(args, True, view)+++def cmd_udev_rule(args):+    return _emit(args, True,+                 {"path": "/etc/udev/rules.d/99-lan7800.rules",+                  "rule": udev_rule(),+                  "install_commands": udev_install_commands()},+                 human="udev rule for libusb access to 0x0424/0x7800 (run the "+                       "install_commands as the human, then replug)")+++def cmd_new(args):+    size = args.size+    if size not in SIZES:+        return _fail(args, f"size must be one of {SIZES}")+    if args.blank:+        eep = Eeprom.blank(size)+        if args.sign:+            eep.set_signature()+        kind = "blank" + (" signed" if args.sign else "")+    else:+        eep = Eeprom.default_template(size)   # signed default LAN7800 template+        kind = "default LAN7800 template"+    BinFileBackend(args.out).write_image(eep.to_bytes())+    return _emit(args, True, {"out": args.out, "size": size, "kind": kind,+                              "preview": _describe(eep)},+                 human=f"wrote {kind} {size}-byte image to {args.out}")+++def cmd_info(args):+    try:+        if args.iface:+            eep = _read_device_image(args.iface, args.sudo)+            source = f"iface:{args.iface}"+        else:+            eep = _load_image_from_in(args)+            source = f"file:{args.in_file}"+    except (EepromError, BackendError) as e:+        return _fail(args, str(e), hint="give --in <base.bin> or --iface <name>")+    view = _describe(eep)+    view["source"] = source+    if not getattr(args, "json", False):+        sig_note = ("valid" if view["signature_ok"]+                    else "INVALID — device falls back to OTP/defaults")+        print(f"OK: {source}  size={view['size']}  sig={view['signature']} "+              f"({sig_note})")+        print(f"  MAC: {view['mac']}")+        for d in view["descriptors"]:+            if d["present"]:+                print(f"  {d['kind'].upper()} desc @0x{d['byte_offset']:X}: "+                      f"VID={d['vid']} PID={d['pid']} bcdDevice={d['bcd_device']}"+                      f"{'' if d['looks_valid'] else '  (!! not a std device desc)'}")+            else:+                print(f"  {d['kind'].upper()} desc: absent")+        for s in view["strings"]:+            if s["present"]:+                print(f"  str[{s['name']}]: {s['value']!r}")+        if not view["lan7800_identity"]:+            print("  note: no descriptor advertises VID/PID 0x0424/0x7800 — "+                  "confirm this is a LAN7800 image (this tool is LAN7800-only)")+        return 0+    return _emit(args, True, view)+++def _apply_edits(eep: Eeprom, args) -> list[str]:+    changes = []+    if args.mac is not None:+        eep.set_mac(args.mac)+        changes.append(f"mac={eep.mac}")+    if args.vid is not None:+        v = parse_u16(args.vid)+        touched = eep.set_vid(v)+        changes.append(f"vid=0x{v:04X}({'+'.join(touched)})")+    if args.pid is not None:+        p = parse_u16(args.pid)+        touched = eep.set_pid(p)+        changes.append(f"pid=0x{p:04X}({'+'.join(touched)})")+    if args.bcd is not None:+        b = parse_u16(args.bcd)+        touched = eep.set_bcd_device(b)+        changes.append(f"bcdDevice=0x{b:04X}({'+'.join(touched)})")+    if args.serial is not None:+        eep.set_string_inplace("serial", args.serial)+        changes.append(f"serial={args.serial!r}")+    for pair in (args.set_string or []):+        if "=" not in pair:+            raise EepromError(f"--set-string needs name=value, got {pair!r}")+        name, value = pair.split("=", 1)+        eep.set_string_inplace(name.strip(), value)+        changes.append(f"str[{name.strip()}]={value!r}")+    for spec in (args.set_led or []):        # index=mode+        idx, _, mode = spec.partition("=")+        regs.set_led_mode(eep, int(idx), int(mode, 0))+        changes.append(f"led{int(idx)}.mode={int(mode, 0)}")+    for spec in (args.led_enable or []):      # index=1|0+        idx, _, on = spec.partition("=")+        regs.set_led_enable(eep, int(idx), on.strip() in ("1", "on", "true"))+        changes.append(f"led{int(idx)}.enable={on.strip()}")+    if args.led_blink is not None:+        regs.set_led_blink(eep, int(args.led_blink))+        changes.append(f"led.blink={args.led_blink}")+    for spec in (args.set_gpio or []):        # index=dir,drive,out+        idx, _, rest = spec.partition("=")+        parts = [p.strip() for p in rest.split(",")]+        kw = {}+        if len(parts) > 0 and parts[0]:+            kw["direction"] = parts[0]+        if len(parts) > 1 and parts[1]:+            kw["drive"] = parts[1]+        if len(parts) > 2 and parts[2] != "":+            kw["output_value"] = int(parts[2])+        regs.set_gpio(eep, int(idx), **kw)+        changes.append(f"gpio{int(idx)}={rest}")+    for spec in (args.gpio_wake or []):       # index=en,pol+        idx, _, rest = spec.partition("=")+        en, _, pol = rest.partition(",")+        regs.set_gpio(eep, int(idx),+                      wake_enabled=en.strip() in ("1", "on", "true"),+                      wake_active_high=(pol.strip() in ("1", "on", "true")) if pol else None)+        changes.append(f"gpio{int(idx)}.wake={rest}")+    for spec in (args.set_configflag or []):  # index=hexval  e.g. 0=0x00000001+        idx, _, val = spec.partition("=")+        eep.set_config_flag(int(idx), int(val, 0))+        changes.append(f"configflag{int(idx)}={int(val, 0):#010x}")+    for spec in (args.set_raw or []):         # offset=hexbytes  e.g. 0x48=0103+        off, _, hexb = spec.partition("=")+        regs.set_region(eep, int(off, 0), bytes.fromhex(hexb.strip()))+        changes.append(f"raw[{off}]={hexb.strip()}")+    if args.ensure_signature:+        eep.set_signature()+        changes.append("signature=0xA5")+    return changes+++def cmd_edit(args):+    try:+        eep = _load_image_from_in(args) if args.in_file else Eeprom.blank(args.size)+        changes = _apply_edits(eep, args)+    except EepromError as e:+        return _fail(args, str(e),+                     hint="VID/PID/strings need a base --in image that already "+                          "has descriptor blocks; MAC/signature work on blanks too")+    if not changes:+        return _fail(args, "no edits requested",+                     hint="pass --mac/--vid/--pid/--bcd/--serial/--set-string/"+                          "--ensure-signature")+    out = args.out or args.in_file+    if not out:+        return _fail(args, "nowhere to write", hint="give --out <file.bin>")+    BinFileBackend(out).write_image(eep.to_bytes())+    payload = {"out": out, "changes": changes, "preview": _describe(eep)}+    return _emit(args, True, payload,+                 human=f"applied [{', '.join(changes)}] -> {out}")+++def cmd_read(args):+    """Read a device EEPROM to a .bin (FREE)."""+    try:+        data = EthtoolBackend(args.iface, sudo=args.sudo).read_image()+    except BackendError as e:+        return _fail(args, str(e))+    BinFileBackend(args.out).write_image(data)+    eep = Eeprom.from_bytes(data)+    return _emit(args, True, {"out": args.out, "bytes": len(data),+                              "preview": _describe(eep)},+                 human=f"read {len(data)} bytes from {args.iface} -> {args.out}")+++def _read_connected_image(args) -> bytes:+    """Read the connected device: libusb by default, ethtool if --iface given."""+    if getattr(args, "iface", None):+        return EthtoolBackend(args.iface, sudo=args.sudo).read_image()+    be = UsbEepromBackend()+    try:+        return be.read_image()+    finally:+        be.close()+++def cmd_verify(args):+    """Read device and compare against an expected image (FREE)."""+    try:+        expected = BinFileBackend(args.image).read_image()+        actual = _read_connected_image(args)+    except BackendError as e:+        return _fail(args, str(e))+    n = min(len(expected), len(actual))+    diffs = [{"offset": i, "expected": expected[i], "actual": actual[i]}+             for i in range(n) if expected[i] != actual[i]]+    if len(expected) != len(actual):+        diffs.append({"offset": None, "note":+                      f"length differs expected={len(expected)} actual={len(actual)}"})+    ok = not diffs+    return _emit(args, ok, {"match": ok, "diff_count": len(diffs),+                            "diffs": diffs[:32]},+                 human=("device matches image" if ok+                        else f"{len(diffs)} byte(s) differ"),+                 hint=None if ok else "re-program or investigate the mismatched offsets")+++# ---- GATED hardware writers ----------------------------------------------+def _refuse_physical(args, action):+    tgt = getattr(args, "iface", None) or "the connected 0424:7800 (libusb)"+    return _emit(+        args, False,+        {"gated": True, "action": action},+        human=f"REFUSED: {action} writes to {tgt}",+        hint="physical writes are gated. The operator/agent must clear a "+             "mesh escalate PROCEED, then re-run with --force-physical-write.")+++def cmd_program(args):+    if not args.force_physical_write:+        return _refuse_physical(args, "program")+    used = f"ethtool:{args.iface}" if args.iface else "libusb"+    try:+        image = BinFileBackend(args.image).read_image()+        eep = Eeprom.from_bytes(image)+        if not eep.has_signature and not args.allow_unsigned:+            return _fail(args, "image byte0 != 0xA5 (unsigned)",+                         hint="run `edit --ensure-signature` first, or pass "+                              "--allow-unsigned to write it as-is")+        if args.iface:+            EthtoolBackend(args.iface, sudo=args.sudo).write_bytes(0, image)+        else:+            be = UsbEepromBackend(size=len(image))   # sudo-free, signature last+            try:+                be.program_image(image)+            finally:+                be.close()+    except (BackendError, EepromError) as e:+        return _fail(args, str(e))+    result = {"backend": used, "bytes": len(image), "verified": None}+    if not args.no_verify:+        try:+            actual = _read_connected_image(args)+        except BackendError as e:+            return _fail(args, f"programmed but could not read back to verify: {e}")+        n = min(len(image), len(actual))+        diffs = [i for i in range(n) if image[i] != actual[i]]+        result["verified"] = (not diffs and len(image) == len(actual))+        result["diff_count"] = len(diffs)+        if not result["verified"]:+            return _emit(args, False, result,+                         human=f"programmed but VERIFY FAILED ({len(diffs)} bytes)",+                         hint="do not trust this image; re-read and re-program")+    return _emit(args, True, result,+                 human=f"programmed {len(image)} bytes via {used}"+                       + ("" if args.no_verify else " (verified)")+                       + "; replug/USB-reset to reload")+++def cmd_erase(args):+    if not args.force_physical_write:+        return _refuse_physical(args, "erase")+    used = f"ethtool:{args.iface}" if args.iface else "libusb"+    payload = bytes([0x00]) if args.mode == "signature" else bytes([0xFF] * args.size)+    off = 0+    try:+        if args.iface:+            EthtoolBackend(args.iface, sudo=args.sudo).write_bytes(off, payload)+        else:+            be = UsbEepromBackend(size=args.size)+            try:+                be.write_bytes(off, payload)+            finally:+                be.close()+    except BackendError as e:+        return _fail(args, str(e))+    touched = ("byte0 signature cleared (recoverable fallback)"+               if args.mode == "signature"+               else f"wrote 0xFF across {args.size} bytes")+    return _emit(args, True, {"backend": used, "mode": args.mode},+                 human=f"erase ({args.mode}) via {used}: {touched}; replug to reload")+++def _bulk_old_identity(args, dev):+    """Best-effort read of a connected unit's CURRENT MAC/serial for the record."""+    try:+        cur = Eeprom.from_bytes(_read_connected_image(args))+        if cur.has_signature:+            sv = cur.string("serial")+            return cur.mac, (sv.value if sv.present else "")+    except (BackendError, EepromError):+        pass+    return (dev.get("mac") if dev else None), ""+++def cmd_bulk(args):+    """Bulk-program many adapters with an auto-incrementing MAC/serial and a+    resumable manifest. Dry-run is the default; real writes are gated."""+    from . import bulk+    try:+        seq = bulk.sequence(args.base, args.count, step=args.step,+                            local_admin=args.local_admin, scheme=args.scheme)+        manifest = bulk.Manifest(args.manifest)+    except EepromError as e:+        return _fail(args, str(e))+    start = manifest.next_index()+    remaining = [u for u in seq if u["index"] >= start+                 and not manifest.has_mac(u["mac"])]++    # DRY-RUN is the default AND the forced behaviour whenever a real write is+    # not explicitly authorised -- so `bulk` never touches hardware by accident.+    if args.dry_run or not args.force_physical_write:+        for u in remaining:+            manifest.append(index=u["index"], usb_path="", old_mac="",+                            old_serial="", new_mac=u["mac"],+                            new_serial=u["serial"], verify="DRYRUN")+        preview = "\n".join(+            f"  [{u['index']:>3}]  MAC {u['mac']}   serial {u['serial']}"+            for u in remaining) or "  (nothing to do; manifest already complete)"+        return _emit(args, True,+                     {"mode": "dry-run", "count": args.count, "step": args.step,+                      "start_index": start, "planned": remaining,+                      "manifest": manifest.csv_path},+                     human=(f"DRY-RUN preview: {len(remaining)} unit(s) "+                            f"(resume from index {start}); no device touched.\n"+                            f"{preview}\nManifest -> {manifest.csv_path}"),+                     hint="real burn: escalate a mesh session-scoped allow, then "+                          "re-run with --force-physical-write")++    # REAL burn (gated). One unit per invocation by default (replug + re-run);+    # --loop prompts between units in a single run for bench use.+    try:+        tmpl = (Eeprom.from_bytes(BinFileBackend(args.template).read_image())+                if args.template else Eeprom.default_template())+    except (BackendError, EepromError) as e:+        return _fail(args, f"template load failed: {e}")++    to_do = remaining if args.loop else remaining[:1]+    burned = []+    for u in to_do:+        if args.loop:+            try:+                input(f"\n>> Insert unit for index {u['index']} "+                      f"(MAC {u['mac']}); press Enter (Ctrl-C to stop)... ")+            except (EOFError, KeyboardInterrupt):+                break+        devs = scan_devices(probe_eeprom=False)+        if not devs:+            return _fail(args, f"no LAN7800 attached for index {u['index']}")+        dev = devs[0]+        old_mac, old_serial = _bulk_old_identity(args, dev)+        # NOT-SWAPPED GUARD: if the connected unit's EEPROM already carries the+        # identity we just wrote to the previous unit, barrett almost certainly+        # did not swap adapters. Refuse to re-burn the same physical unit.+        last = manifest.last_burned_mac()+        if last and old_mac and old_mac.upper() == last.upper():+            return _emit(args, False,+                         {"same_unit": True, "current_mac": old_mac,+                          "next_index": u["index"], "manifest": manifest.csv_path},+                         human=(f"This looks like the unit you just programmed "+                                f"(MAC {old_mac}). Unplug it and insert the next "+                                f"blank adapter, then retry."),+                         hint="not-swapped guard: refusing to re-burn the same unit")+        try:+            img = bulk.build_image(tmpl, u["mac"], u["serial"])+            be = UsbEepromBackend(size=len(img))+            try:+                be.program_image(img)           # LED-mux-gated, signature LAST+            finally:+                be.close()+            actual = _read_connected_image(args)+            ok = bytes(actual) == bytes(img)+        except (BackendError, EepromError) as e:+            manifest.append(index=u["index"], usb_path=dev.get("usb_path"),+                            old_mac=old_mac, old_serial=old_serial,+                            new_mac=u["mac"], new_serial=u["serial"], verify="FAIL")+            return _fail(args, f"index {u['index']} program failed: {e}")+        manifest.append(index=u["index"], usb_path=dev.get("usb_path"),+                        old_mac=old_mac, old_serial=old_serial,+                        new_mac=u["mac"], new_serial=u["serial"],+                        verify="PASS" if ok else "FAIL")+        burned.append({"index": u["index"], "mac": u["mac"],+                       "serial": u["serial"], "verified": ok})+        if not ok:+            return _emit(args, False,+                         {"burned": burned, "manifest": manifest.csv_path},+                         human=f"index {u['index']} VERIFY FAILED after write")+    return _emit(args, True,+                 {"mode": "burn", "burned": burned, "manifest": manifest.csv_path},+                 human=(f"burned {len(burned)} unit(s); manifest {manifest.csv_path}"+                        + ("" if args.loop else "; replug next unit + re-run")))+++# ---- argument parser ------------------------------------------------------+def build_parser():+    p = argparse.ArgumentParser(+        prog="lan7800prog",+        description="LAN7800 EEPROM programmer (Core v1, LAN7800 only)")+    p.add_argument("--json", action="store_true", help="emit machine-readable JSON")+    sub = p.add_subparsers(dest="cmd", required=True)++    def add_target(sp, iface=True, infile=True):+        if infile:+            sp.add_argument("--in", dest="in_file", help="base .bin image")+        if iface:+            sp.add_argument("--iface", help="network interface of the LAN7800")+            sp.add_argument("--no-sudo", dest="sudo", action="store_false",+                            default=True, help="do not prefix ethtool with sudo")++    sp = sub.add_parser("scan", help="enumerate attached LAN7800 adapters (FREE)")+    sp.add_argument("--no-probe", action="store_true",+                    help="skip the ethtool EEPROM signature probe")+    sp.set_defaults(func=cmd_scan)++    sp = sub.add_parser("read-device",+                        help="read the connected LAN7800 (auto: netdev->ethtool "+                             "else libusb) (FREE)")+    sp.add_argument("--out", help="also write the image to this .bin")+    sp.add_argument("--size", type=int, default=MAX_EEPROM_SIZE, choices=SIZES)+    sp.add_argument("--no-sudo", dest="sudo", action="store_false", default=True)+    sp.set_defaults(func=cmd_read_device)++    sp = sub.add_parser("udev-rule",+                        help="print the udev rule needed for libusb device access")+    sp.set_defaults(func=cmd_udev_rule)++    sp = sub.add_parser("new",+                        help="create a default LAN7800 template .bin "+                             "(or --blank for an empty image)")+    sp.add_argument("--out", required=True)+    sp.add_argument("--size", type=int, default=MAX_EEPROM_SIZE, choices=SIZES)+    sp.add_argument("--blank", action="store_true",+                    help="all-zero image instead of the default template")+    sp.add_argument("--sign", action="store_true",+                    help="with --blank: lay down the 0xA5 signature")+    sp.set_defaults(func=cmd_new)++    sp = sub.add_parser("info", help="parse & print an image or a live device")+    add_target(sp)+    sp.set_defaults(func=cmd_info)++    sp = sub.add_parser("edit", help="edit fields, write a new .bin (no hardware)")+    sp.add_argument("--in", dest="in_file", help="base .bin (required for VID/PID/strings)")+    sp.add_argument("--out", help="output .bin (defaults to --in)")+    sp.add_argument("--size", type=int, default=MAX_EEPROM_SIZE, choices=SIZES)+    sp.add_argument("--mac")+    sp.add_argument("--vid")+    sp.add_argument("--pid")+    sp.add_argument("--bcd", help="bcdDevice / DID")+    sp.add_argument("--serial")+    sp.add_argument("--set-string", action="append",+                    help="name=value (manufacturer/product/serial/configuration/interface)")+    sp.add_argument("--set-led", action="append", metavar="I=MODE",+                    help="LED index=mode(0..15), e.g. 0=10")+    sp.add_argument("--led-enable", action="append", metavar="I=1|0")+    sp.add_argument("--led-blink", help="blink rate code 0=2.5Hz 1=5Hz 2=10Hz 3=20Hz")+    sp.add_argument("--set-gpio", action="append", metavar="I=dir,drive,out",+                    help="e.g. 0=out,push-pull,1")+    sp.add_argument("--gpio-wake", action="append", metavar="I=en,pol",+                    help="e.g. 0=1,1")+    sp.add_argument("--set-configflag", action="append", metavar="I=HEX",+                    help="Config Flags 0..3, e.g. 0=0x00000001")+    sp.add_argument("--set-raw", action="append", metavar="OFF=HEX",+                    help="raw bytes, e.g. 0x48=0103 (authoritative fallback)")+    sp.add_argument("--ensure-signature", action="store_true")+    sp.set_defaults(func=cmd_edit)++    sp = sub.add_parser("read", help="read device EEPROM -> .bin (FREE)")+    sp.add_argument("--iface", required=True)+    sp.add_argument("--out", required=True)+    sp.add_argument("--no-sudo", dest="sudo", action="store_false", default=True)+    sp.set_defaults(func=cmd_read)++    sp = sub.add_parser("verify",+                        help="compare connected device against a .bin (FREE; "+                             "libusb by default, --iface for ethtool)")+    sp.add_argument("--iface", help="use ethtool via this iface (default: libusb)")+    sp.add_argument("--image", required=True)+    sp.add_argument("--no-sudo", dest="sudo", action="store_false", default=True)+    sp.set_defaults(func=cmd_verify)++    sp = sub.add_parser("program",+                        help="GATED: write a .bin to the connected device + verify "+                             "(libusb by default, --iface for ethtool)")+    sp.add_argument("--iface", help="use ethtool via this iface (default: libusb)")+    sp.add_argument("--image", required=True)+    sp.add_argument("--force-physical-write", action="store_true",+                    help="required; set only after a cleared mesh escalation")+    sp.add_argument("--allow-unsigned", action="store_true")+    sp.add_argument("--no-verify", action="store_true")+    sp.add_argument("--no-sudo", dest="sudo", action="store_false", default=True)+    sp.set_defaults(func=cmd_program)++    sp = sub.add_parser("erase", help="GATED: clear signature or full 0xFF erase")+    sp.add_argument("--iface", help="use ethtool via this iface (default: libusb)")+    sp.add_argument("--mode", choices=["signature", "full"], default="signature")+    sp.add_argument("--size", type=int, default=MAX_EEPROM_SIZE, choices=SIZES)+    sp.add_argument("--force-physical-write", action="store_true")+    sp.add_argument("--no-sudo", dest="sudo", action="store_false", default=True)+    sp.set_defaults(func=cmd_erase)++    sp = sub.add_parser(+        "bulk",+        help="program many adapters with an auto-incrementing identity "+             "(dry-run by default; real writes gated)")+    sp.add_argument("--base", required=True,+                    help="base MAC, e.g. 00:80:0F:78:00:00 (OUI not hardcoded)")+    sp.add_argument("--count", type=int, required=True, help="number of units")+    sp.add_argument("--step", type=int, default=1, help="MAC increment (default 1)")+    sp.add_argument("--manifest", required=True,+                    help="manifest path (.csv; a .json is written alongside)")+    sp.add_argument("--scheme", default="mac-hex",+                    help="serial scheme (default mac-hex: iSerial = MAC hex)")+    sp.add_argument("--local-admin", dest="local_admin", action="store_true",+                    help="force the locally-administered 02: bit on the base MAC")+    sp.add_argument("--template",+                    help="base .bin (needs a serial slot); default: built-in template")+    sp.add_argument("--dry-run", dest="dry_run", action="store_true",+                    help="compute+log the sequence, write DRYRUN rows; no device")+    sp.add_argument("--loop", action="store_true",+                    help="interactive: prompt to insert each unit within one run")+    sp.add_argument("--force-physical-write", dest="force_physical_write",+                    action="store_true",+                    help="authorize REAL writes (needs a mesh session-scoped allow)")+    sp.add_argument("--iface", help="use ethtool via this iface instead of libusb")+    sp.add_argument("--no-sudo", dest="sudo", action="store_false", default=True)+    sp.set_defaults(func=cmd_bulk)++    return p+++def main(argv=None):+    parser = build_parser()+    args = parser.parse_args(argv)+    try:+        return args.func(args)+    except (EepromError, BackendError) as e:+        return _fail(args, str(e))+    except (ValueError, KeyError) as e:+        # user-input parse errors (int(), bytes.fromhex, dict lookups) — never+        # leak a Python traceback / server paths to the caller or the webapp.+        return _fail(args, f"invalid input: {e}",+                     hint="check numeric/hex arguments and field names")+    except BrokenPipeError:+        return 0+    except Exception as e:  # last-resort: clean message, no traceback+        return _fail(args, f"unexpected error: {type(e).__name__}: {e}")+++if __name__ == "__main__":+    sys.exit(main())
cli/lan7800/eeprom.pyadded+332
@@ -0,0 +1,332 @@+"""LAN7800 EEPROM image model.++Pure, hardware-free representation of a LAN7800 EEPROM image (a raw .bin of+256 or 512 bytes) plus typed accessors for the fields the Core v1 tool edits:+signature, MAC, VID/PID/bcdDevice (across the SS/HS/FS descriptor blocks),+string descriptors, and serial.++Layout facts come from docs/01-eeprom-mechanism.md (datasheet DS00001992G+Table 10-2 + lan78xx.c). Anything the doc flagged "VERIFY against a real dump"+is centralized here as a named constant with a comment so it can be corrected+in one place once a physical adapter is available.+"""+from __future__ import annotations++from dataclasses import dataclass, field+from typing import Optional++# ---- constants (authoritative: lan78xx.c + datasheet Table 10-2) ----------+EEPROM_MAGIC = 0x78A5          # ethtool -E magic for LAN78xx+SIG_OFFSET = 0x00+SIG_VALUE = 0xA5              # byte0; device ignores EEPROM if != 0xA5+MAC_OFFSET = 0x01+MAC_LEN = 6+MICROCHIP_OUI = (0x00, 0x80, 0x0F)+MAX_EEPROM_SIZE = 512+SIZES = (256, 512)++# String descriptor pointer table: 5 entries at 0x25..0x2E, each (len, word_off).+STR_TABLE_OFFSET = 0x25+STR_NAMES = ("manufacturer", "product", "serial", "configuration", "interface")++# Config Flags 0..3: four 32-bit LE words at 0x13/0x17/0x1B/0x1F (docs/01).+CONFIG_FLAGS_OFFSET = 0x13+CONFIG_FLAGS_COUNT = 4++# Device-descriptor block pointers (word units). VID/PID/bcdDevice live inside.+# LAN7800 exposes SuperSpeed + HighSpeed + FullSpeed descriptor blocks.+DESC_PTRS = {"ss": 0x31, "hs": 0x35, "fs": 0x39}+# offsets within a standard USB device descriptor:+DD_VID = 8      # idVendor  (LE u16)+DD_PID = 10     # idProduct (LE u16)+DD_BCDDEV = 12  # bcdDevice (LE u16)+DD_LEN = 18     # bLength of a device descriptor (0x12)++# LAN7800 identity guard — this tool is LAN7800 ONLY.+LAN7800_VID = 0x0424+LAN7800_PID = 0x7800++# MAC octet order in EEPROM. RESOLVED against real hardware (2026-07-30): the+# lan78xx driver reads EEPROM offset 0x01 as addr[0], i.e. NATURAL order, so+# MAC AA:BB:CC:DD:EE:FF is stored AA BB CC DD EE FF (0x01=AA ... 0x06=FF).+# The datasheet doc's "little-endian FF EE DD CC BB AA" note was WRONG: entering+# the device's known MAC 00:80:0F:78:00:00 under LE produced the byte-reverse+# 00:00:78:0F:80:00 on the wire. Natural order is confirmed correct.+MAC_LITTLE_ENDIAN = False+++class EepromError(Exception):+    pass+++@dataclass+class DescriptorView:+    kind: str            # ss / hs / fs+    ptr_word: int        # raw pointer value (word units)+    byte_offset: int     # resolved byte offset of the descriptor block+    present: bool+    looks_valid: bool    # bLength==0x12 and bDescriptorType==0x01+    vid: Optional[int] = None+    pid: Optional[int] = None+    bcd_device: Optional[int] = None+++@dataclass+class StringView:+    name: str+    length_field: int+    word_offset: int+    byte_offset: int+    present: bool+    value: Optional[str] = None+++@dataclass+class Eeprom:+    data: bytearray++    # ---- construction ------------------------------------------------------+    @classmethod+    def from_bytes(cls, raw: bytes) -> "Eeprom":+        if len(raw) not in SIZES:+            # tolerate any length up to 512 by padding to the nearest known size+            if len(raw) == 0 or len(raw) > MAX_EEPROM_SIZE:+                raise EepromError(+                    f"unexpected EEPROM length {len(raw)}; expected one of {SIZES}")+            size = 256 if len(raw) <= 256 else 512+            buf = bytearray(raw) + bytearray(size - len(raw))+            return cls(buf)+        return cls(bytearray(raw))++    @classmethod+    def blank(cls, size: int = MAX_EEPROM_SIZE) -> "Eeprom":+        if size not in SIZES:+            raise EepromError(f"size must be one of {SIZES}")+        return cls(bytearray(size))++    @classmethod+    def default_template(cls, size: int = MAX_EEPROM_SIZE) -> "Eeprom":+        """A sensible DEFAULT LAN7800 image: 0xA5 signature, a Microchip-OUI MAC+        placeholder (00:80:0F:00:00:00), and SS/HS/FS USB device-descriptor+        blocks carrying VID 0x0424 / PID 0x7800 / bcdDevice 0x0300. Strings are+        left blank. This is the single source of truth for the webapp's default+        pre-populated fields. Descriptor blocks sit at 0x60/0x80/0xA0, clear of+        the fixed LED/GPIO register offsets."""+        import struct+        e = cls.blank(size)+        e.set_signature()+        e.set_mac("00:80:0F:00:00:00")+        dd = struct.pack("<BBHBBBBHHHBBBB", 0x12, 0x01, 0x0300, 0xFF, 0x00, 0x00,+                         64, LAN7800_VID, LAN7800_PID, 0x0300, 0, 0, 0, 1)+        block = 0x60+        for kind in ("ss", "hs", "fs"):+            e.data[block:block + len(dd)] = dd+            e._put_u16le(DESC_PTRS[kind], block // 2)   # pointer in word units+            block += 24+        return e++    def to_bytes(self) -> bytes:+        return bytes(self.data)++    @property+    def size(self) -> int:+        return len(self.data)++    # ---- low-level helpers -------------------------------------------------+    def _u16le(self, off: int) -> int:+        if off + 1 >= self.size:+            raise EepromError(f"read u16 out of range at 0x{off:02X}")+        return self.data[off] | (self.data[off + 1] << 8)++    def _put_u16le(self, off: int, val: int) -> None:+        if off + 1 >= self.size:+            raise EepromError(f"write u16 out of range at 0x{off:02X}")+        self.data[off] = val & 0xFF+        self.data[off + 1] = (val >> 8) & 0xFF++    def _u32le(self, off: int) -> int:+        return (self.data[off] | (self.data[off + 1] << 8)+                | (self.data[off + 2] << 16) | (self.data[off + 3] << 24))++    def _put_u32le(self, off: int, val: int) -> None:+        for i in range(4):+            self.data[off + i] = (val >> (8 * i)) & 0xFF++    # ---- config flags ------------------------------------------------------+    def config_flags(self) -> list[int]:+        return [self._u32le(CONFIG_FLAGS_OFFSET + 4 * i)+                for i in range(CONFIG_FLAGS_COUNT)]++    def set_config_flag(self, i: int, val: int) -> None:+        if not 0 <= i < CONFIG_FLAGS_COUNT:+            raise EepromError(f"config flag index must be 0..{CONFIG_FLAGS_COUNT-1}")+        if not 0 <= val <= 0xFFFFFFFF:+            raise EepromError("config flag must be a 32-bit value")+        self._put_u32le(CONFIG_FLAGS_OFFSET + 4 * i, val)++    # ---- signature ---------------------------------------------------------+    @property+    def signature(self) -> int:+        return self.data[SIG_OFFSET]++    @property+    def has_signature(self) -> bool:+        return self.signature == SIG_VALUE++    def set_signature(self) -> None:+        self.data[SIG_OFFSET] = SIG_VALUE++    # ---- MAC ---------------------------------------------------------------+    @property+    def mac(self) -> str:+        octets = self.data[MAC_OFFSET:MAC_OFFSET + MAC_LEN]+        if MAC_LITTLE_ENDIAN:+            octets = octets[::-1]+        return ":".join(f"{b:02X}" for b in octets)++    def set_mac(self, mac: str) -> None:+        octets = parse_mac(mac)+        stored = octets[::-1] if MAC_LITTLE_ENDIAN else octets+        self.data[MAC_OFFSET:MAC_OFFSET + MAC_LEN] = bytes(stored)++    # ---- descriptor blocks (VID/PID/bcdDevice) -----------------------------+    def descriptor(self, kind: str) -> DescriptorView:+        if kind not in DESC_PTRS:+            raise EepromError(f"unknown descriptor kind {kind!r}")+        ptr_off = DESC_PTRS[kind]+        ptr_word = self._u16le(ptr_off)+        byte_off = ptr_word * 2+        present = ptr_word != 0 and byte_off + DD_LEN <= self.size+        view = DescriptorView(kind=kind, ptr_word=ptr_word, byte_offset=byte_off,+                              present=present, looks_valid=False)+        if present:+            b_len = self.data[byte_off]+            b_type = self.data[byte_off + 1]+            view.looks_valid = (b_len == DD_LEN and b_type == 0x01)+            view.vid = self._u16le(byte_off + DD_VID)+            view.pid = self._u16le(byte_off + DD_PID)+            view.bcd_device = self._u16le(byte_off + DD_BCDDEV)+        return view++    def descriptors(self) -> list[DescriptorView]:+        return [self.descriptor(k) for k in DESC_PTRS]++    def _set_desc_field(self, field_off: int, val: int) -> list[str]:+        """Write a u16 field into every present descriptor block. Returns the+        list of blocks touched (kinds)."""+        touched = []+        for d in self.descriptors():+            if d.present:+                self._put_u16le(d.byte_offset + field_off, val)+                touched.append(d.kind)+        if not touched:+            raise EepromError(+                "no USB device-descriptor block present to write into; "+                "load a base image that already has descriptor pointers")+        return touched++    def set_vid(self, vid: int) -> list[str]:+        _check_u16(vid, "VID")+        return self._set_desc_field(DD_VID, vid)++    def set_pid(self, pid: int) -> list[str]:+        _check_u16(pid, "PID")+        return self._set_desc_field(DD_PID, pid)++    def set_bcd_device(self, bcd: int) -> list[str]:+        _check_u16(bcd, "bcdDevice")+        return self._set_desc_field(DD_BCDDEV, bcd)++    # ---- string descriptors ------------------------------------------------+    def string(self, name: str) -> StringView:+        if name not in STR_NAMES:+            raise EepromError(f"unknown string {name!r}; one of {STR_NAMES}")+        idx = STR_NAMES.index(name)+        entry = STR_TABLE_OFFSET + idx * 2+        length_field = self.data[entry]+        word_off = self.data[entry + 1]+        byte_off = word_off * 2+        present = length_field != 0 and word_off != 0 and byte_off < self.size+        sv = StringView(name=name, length_field=length_field, word_offset=word_off,+                        byte_offset=byte_off, present=present)+        if present:+            sv.value = self._read_usb_string(byte_off)+        return sv++    def strings(self) -> list[StringView]:+        return [self.string(n) for n in STR_NAMES]++    def _read_usb_string(self, off: int) -> Optional[str]:+        # USB string descriptor: bLength, bDescriptorType(0x03), UTF-16LE payload+        if off + 1 >= self.size:+            return None+        b_len = self.data[off]+        b_type = self.data[off + 1]+        if b_type != 0x03 or b_len < 2 or off + b_len > self.size:+            return None+        payload = self.data[off + 2:off + b_len]+        try:+            return payload.decode("utf-16-le", errors="replace")+        except Exception:+            return None++    def set_string_inplace(self, name: str, value: str) -> None:+        """Overwrite an existing string descriptor IN PLACE.++        v1 constraint: the new UTF-16LE payload must fit within the existing+        descriptor's byte length (we do not relocate/repack the string heap in+        v1 — that is an ADVANCED item). Shorter strings are zero-padded and+        bLength is updated. Raises if it would not fit or the string is absent.+        """+        sv = self.string(name)+        if not sv.present:+            raise EepromError(+                f"string {name!r} is absent in this image; v1 can edit existing "+                f"strings in place but not allocate new ones (ADVANCED)")+        encoded = value.encode("utf-16-le")+        capacity = self.data[sv.byte_offset]  # existing bLength (incl. 2-byte header)+        new_len = 2 + len(encoded)+        if new_len > capacity:+            raise EepromError(+                f"string {name!r}: new value needs {new_len} bytes but the "+                f"existing slot holds {capacity}; in-place edit only in v1")+        off = sv.byte_offset+        self.data[off] = new_len+        self.data[off + 1] = 0x03+        self.data[off + 2:off + 2 + len(encoded)] = encoded+        # zero any leftover tail within the old slot+        for i in range(off + new_len, off + capacity):+            self.data[i] = 0x00+++# ---- module helpers -------------------------------------------------------+def parse_mac(mac: str) -> list[int]:+    parts = mac.replace("-", ":").split(":")+    if len(parts) != 6:+        raise EepromError(f"invalid MAC {mac!r}: need 6 octets")+    try:+        octets = [int(p, 16) for p in parts]+    except ValueError:+        raise EepromError(f"invalid MAC {mac!r}: non-hex octet")+    if any(o < 0 or o > 0xFF for o in octets):+        raise EepromError(f"invalid MAC {mac!r}: octet out of range")+    return octets+++def parse_u16(text) -> int:+    if isinstance(text, int):+        val = text+    else:+        t = str(text).strip().lower()+        try:+            val = int(t, 16) if t.startswith("0x") else int(t, 0)+        except ValueError:+            raise EepromError(+                f"invalid 16-bit value {text!r}: expected decimal or 0x-hex")+    _check_u16(val, "value")+    return val+++def _check_u16(val: int, label: str) -> None:+    if not isinstance(val, int) or val < 0 or val > 0xFFFF:+        raise EepromError(f"{label} must be a 16-bit value (0..0xFFFF), got {val!r}")
cli/lan7800/regs.pyadded+214
@@ -0,0 +1,214 @@+"""LED + GPIO EEPROM field accessors (advanced tier, moved into v1).++⚠ BIT-LAYOUT VERIFY: docs/01 give the byte OFFSETS for these regions but not the+datasheet's bit-level packing. The offset placement below is authoritative (from+docs/01 + the task brief); the *bit assignments within each byte* are a+best-effort mapping of the standard LAN7800 LED_CFG / GPIO_CFG registers and are+flagged VERIFY — confirm against datasheet DS00001992G §15 (LED_CFG, GPIO_*) or a+real dump before trusting for production. A raw get/set_region() escape hatch is+provided so an operator can always write exact bytes regardless of this mapping.++Regions (docs/01 + task brief):+  LED:  0x0B-0x0D (config 0/1/2)  + 0x58-0x59 (behavior/blink)+  GPIO: 0x07 wake-enable, 0x0E wake-polarity, 0x48-0x4F per-pin config+"""+from __future__ import annotations++from .eeprom import Eeprom, EepromError, DD_LEN++# ---- LED --------------------------------------------------------------------+LED_MODES = [+    "Link/Act", "Link1000/Act", "Link100/Act", "Link10/Act",+    "Link100+1000/Act", "Link10+1000/Act", "Link10+100/Act", "reserved",+    "Duplex/Collision", "Collision", "Activity", "reserved",+    "AutoNeg Fault", "Serial Mode", "Force Off", "Force On",+]+LED_COUNT = 4+LED_MODE_BASE = 0x0B          # LED i mode nibble: byte 0x0B+(i//2), nibble (i%2)*4  [VERIFY]+LED_ENABLE_OFFSET = 0x0D      # bit i = LED i enabled                                [VERIFY]+LED_BEHAVIOR_OFFSET = 0x58    # u16 LE; blink rate in bits[1:0]                       [VERIFY]+LED_BLINK_RATES = {0: "2.5Hz", 1: "5Hz", 2: "10Hz", 3: "20Hz"}++# ---- GPIO -------------------------------------------------------------------+GPIO_COUNT = 8+GPIO_WAKE_EN_OFFSET = 0x07    # bit i = GPIO i wake enable                            [VERIFY]+GPIO_WAKE_POL_OFFSET = 0x0E   # bit i = GPIO i wake polarity (1=active high)          [VERIFY]+GPIO_CFG_BASE = 0x48          # one byte per pin, 0x48..0x4F                          [VERIFY]+# per-pin config byte bits [VERIFY]:+GPIO_DIR_BIT = 0x01           # 1 = output, 0 = input+GPIO_OPEN_DRAIN_BIT = 0x02    # 1 = open-drain+GPIO_PUSH_PULL_BIT = 0x04     # 1 = push-pull+GPIO_OUT_VALUE_BIT = 0x08     # output level when dir=output+++def _check_index(i, count, what):+    if not isinstance(i, int) or i < 0 or i >= count:+        raise EepromError(f"{what} index must be 0..{count - 1}, got {i}")+++# Fixed LED/GPIO register byte ranges (inclusive). These are absolute EEPROM+# offsets; USB descriptor blocks are pointer-placed and *should* live elsewhere.+# If a descriptor block lands on one of these, a named LED/GPIO write would+# corrupt the descriptor (and vice-versa) — so we detect and block it.+FIXED_RANGES = [+    ("GPIO wake-enable", GPIO_WAKE_EN_OFFSET, GPIO_WAKE_EN_OFFSET),+    ("LED config", LED_MODE_BASE, LED_ENABLE_OFFSET),+    ("GPIO wake-polarity", GPIO_WAKE_POL_OFFSET, GPIO_WAKE_POL_OFFSET),+    ("GPIO config", GPIO_CFG_BASE, GPIO_CFG_BASE + GPIO_COUNT - 1),+    ("LED behavior", LED_BEHAVIOR_OFFSET, LED_BEHAVIOR_OFFSET + 1),+]+++def _descriptor_at(eep: Eeprom, offset: int):+    """Return the descriptor kind whose block covers `offset`, else None."""+    for d in eep.descriptors():+        if d.present and d.byte_offset <= offset < d.byte_offset + DD_LEN:+            return d.kind+    return None+++def _guard(eep: Eeprom, offset: int, field: str):+    kind = _descriptor_at(eep, offset)+    if kind:+        raise EepromError(+            f"{field} at 0x{offset:02X} lies inside the {kind.upper()} USB "+            f"descriptor block; a named write here would corrupt the "+            f"descriptor. This image has an overlapping layout. Use --set-raw "+            f"only if you truly intend to write that byte.")+++def region_overlaps(eep: Eeprom) -> list[dict]:+    """List every collision between a fixed LED/GPIO range and a descriptor."""+    out = []+    for name, lo, hi in FIXED_RANGES:+        for off in range(lo, hi + 1):+            kind = _descriptor_at(eep, off)+            if kind:+                out.append({"register": name, "offset": off, "descriptor": kind})+    return out+++# ===== raw region escape hatch (authoritative) ==============================+def get_region(eep: Eeprom, offset: int, length: int) -> bytes:+    if offset < 0 or offset + length > eep.size:+        raise EepromError(f"region 0x{offset:02X}+{length} out of range")+    return bytes(eep.data[offset:offset + length])+++def set_region(eep: Eeprom, offset: int, values: bytes) -> None:+    if offset < 0 or offset + len(values) > eep.size:+        raise EepromError(f"region 0x{offset:02X}+{len(values)} out of range")+    eep.data[offset:offset + len(values)] = values+++# ===== LED ===================================================================+def get_led(eep: Eeprom, i: int) -> dict:+    _check_index(i, LED_COUNT, "LED")+    byte = eep.data[LED_MODE_BASE + (i // 2)]+    mode = (byte >> ((i % 2) * 4)) & 0x0F+    enabled = bool(eep.data[LED_ENABLE_OFFSET] & (1 << i))+    return {"index": i, "mode": mode, "mode_name": LED_MODES[mode],+            "enabled": enabled}+++def set_led_mode(eep: Eeprom, i: int, mode: int) -> None:+    _check_index(i, LED_COUNT, "LED")+    if not 0 <= mode <= 15:+        raise EepromError("LED mode must be 0..15")+    off = LED_MODE_BASE + (i // 2)+    _guard(eep, off, f"LED{i} mode")+    shift = (i % 2) * 4+    eep.data[off] = (eep.data[off] & ~(0x0F << shift)) | (mode << shift)+++def set_led_enable(eep: Eeprom, i: int, on: bool) -> None:+    _check_index(i, LED_COUNT, "LED")+    _guard(eep, LED_ENABLE_OFFSET, f"LED{i} enable")+    bit = 1 << i+    if on:+        eep.data[LED_ENABLE_OFFSET] |= bit+    else:+        eep.data[LED_ENABLE_OFFSET] &= ~bit+++def get_led_blink(eep: Eeprom) -> dict:+    val = eep.data[LED_BEHAVIOR_OFFSET] | (eep.data[LED_BEHAVIOR_OFFSET + 1] << 8)+    rate = val & 0x03+    return {"raw": val, "blink_rate": LED_BLINK_RATES.get(rate, "?"), "code": rate}+++def set_led_blink(eep: Eeprom, rate_code: int) -> None:+    if rate_code not in LED_BLINK_RATES:+        raise EepromError(f"blink rate code must be one of {list(LED_BLINK_RATES)}")+    _guard(eep, LED_BEHAVIOR_OFFSET, "LED blink")+    val = eep.data[LED_BEHAVIOR_OFFSET] | (eep.data[LED_BEHAVIOR_OFFSET + 1] << 8)+    val = (val & ~0x03) | rate_code+    eep.data[LED_BEHAVIOR_OFFSET] = val & 0xFF+    eep.data[LED_BEHAVIOR_OFFSET + 1] = (val >> 8) & 0xFF+++# ===== GPIO ==================================================================+def get_gpio(eep: Eeprom, i: int) -> dict:+    _check_index(i, GPIO_COUNT, "GPIO")+    cfg = eep.data[GPIO_CFG_BASE + i]+    return {+        "index": i,+        "direction": "out" if cfg & GPIO_DIR_BIT else "in",+        "drive": ("open-drain" if cfg & GPIO_OPEN_DRAIN_BIT+                  else "push-pull" if cfg & GPIO_PUSH_PULL_BIT else "default"),+        "output_value": 1 if cfg & GPIO_OUT_VALUE_BIT else 0,+        "wake_enabled": bool(eep.data[GPIO_WAKE_EN_OFFSET] & (1 << i)),+        "wake_active_high": bool(eep.data[GPIO_WAKE_POL_OFFSET] & (1 << i)),+    }+++def set_gpio(eep: Eeprom, i: int, direction=None, drive=None, output_value=None,+             wake_enabled=None, wake_active_high=None) -> None:+    _check_index(i, GPIO_COUNT, "GPIO")+    off = GPIO_CFG_BASE + i+    if any(v is not None for v in (direction, drive, output_value)):+        _guard(eep, off, f"GPIO{i} config")+    if wake_enabled is not None:+        _guard(eep, GPIO_WAKE_EN_OFFSET, f"GPIO{i} wake-enable")+    if wake_active_high is not None:+        _guard(eep, GPIO_WAKE_POL_OFFSET, f"GPIO{i} wake-polarity")+    cfg = eep.data[off]+    if direction is not None:+        if direction not in ("in", "out"):+            raise EepromError("direction must be 'in' or 'out'")+        cfg = (cfg | GPIO_DIR_BIT) if direction == "out" else (cfg & ~GPIO_DIR_BIT)+    if drive is not None:+        cfg &= ~(GPIO_OPEN_DRAIN_BIT | GPIO_PUSH_PULL_BIT)+        if drive == "open-drain":+            cfg |= GPIO_OPEN_DRAIN_BIT+        elif drive == "push-pull":+            cfg |= GPIO_PUSH_PULL_BIT+        elif drive != "default":+            raise EepromError("drive must be open-drain/push-pull/default")+    if output_value is not None:+        cfg = (cfg | GPIO_OUT_VALUE_BIT) if int(output_value) else (cfg & ~GPIO_OUT_VALUE_BIT)+    eep.data[off] = cfg & 0xFF+    if wake_enabled is not None:+        bit = 1 << i+        eep.data[GPIO_WAKE_EN_OFFSET] = (eep.data[GPIO_WAKE_EN_OFFSET] | bit) \+            if wake_enabled else (eep.data[GPIO_WAKE_EN_OFFSET] & ~bit)+    if wake_active_high is not None:+        bit = 1 << i+        eep.data[GPIO_WAKE_POL_OFFSET] = (eep.data[GPIO_WAKE_POL_OFFSET] | bit) \+            if wake_active_high else (eep.data[GPIO_WAKE_POL_OFFSET] & ~bit)+++def describe_regs(eep: Eeprom) -> dict:+    overlaps = region_overlaps(eep)+    return {+        "leds": [get_led(eep, i) for i in range(LED_COUNT)],+        "led_blink": get_led_blink(eep),+        "gpios": [get_gpio(eep, i) for i in range(GPIO_COUNT)],+        "overlaps": overlaps,+        "overlap_warning": (+            "LED/GPIO register offsets overlap a USB descriptor block in this "+            "image; named LED/GPIO edits are blocked on the colliding bytes to "+            "avoid corrupting the descriptor." if overlaps else None),+        "verify_note": "LED/GPIO bit layout is best-effort; confirm vs datasheet "+                       "sec 15 or a real dump. Offsets are authoritative.",+    }
cli/lan7800/scan.pyadded+125
@@ -0,0 +1,125 @@+"""Enumerate attached LAN7800 adapters (USB VID 0x0424 / PID 0x7800).++Pure /sys walking for the device inventory (free, no privilege). For each USB+match we resolve the bound netdev (if any), its driver and current MAC, and+best-effort probe whether the EEPROM carries a valid 0xA5 signature via a+NON-interactive `ethtool -e` (sudo -n) so it can never hang waiting for a+password — if privilege is missing the eeprom state is reported "unknown".+"""+from __future__ import annotations++import glob+import os+import shutil+import subprocess++from .eeprom import LAN7800_VID, LAN7800_PID, SIG_VALUE++USB_DEVICES = "/sys/bus/usb/devices"+++def _read(path: str) -> str:+    try:+        with open(path) as fh:+            return fh.read().strip()+    except OSError:+        return ""+++def _hex_id(path: str) -> int:+    v = _read(path)+    try:+        return int(v, 16)+    except ValueError:+        return -1+++def _find_iface(usb_dev_dir: str) -> str | None:+    # netdev lives under an interface child: <dev>:<cfg>.<intf>/net/<iface>+    for net in glob.glob(os.path.join(usb_dev_dir, "*:*", "net", "*")):+        return os.path.basename(net)+    return None+++def _iface_driver(iface: str) -> str:+    link = f"/sys/class/net/{iface}/device/driver"+    if os.path.islink(link):+        return os.path.basename(os.path.realpath(link))+    return ""+++def _probe_eeprom_signed(iface: str) -> str:+    """Return 'signed' | 'blank' | 'unknown'. Never blocks (sudo -n)."""+    if shutil.which("ethtool") is None:+        return "unknown"+    for cmd in (["sudo", "-n", "ethtool", "-e", iface, "raw", "on",+                 "offset", "0", "length", "1"],+                ["ethtool", "-e", iface, "raw", "on",+                 "offset", "0", "length", "1"]):+        try:+            p = subprocess.run(cmd, capture_output=True, timeout=5)+        except (subprocess.TimeoutExpired, OSError):+            continue+        if p.returncode == 0 and p.stdout:+            return "signed" if p.stdout[0] == SIG_VALUE else "blank"+        err = p.stderr.decode(errors="replace")+        if "ENODATA" in err or "No data" in err:+            return "blank"+        # password / permission / no-device -> try next form, else unknown+    return "unknown"+++def diagnose_netdev(usb_path: str) -> dict:+    """Explain why a bound LAN7800 may have no netdev (best effort, no privilege)."""+    dev_dir = os.path.join(USB_DEVICES, usb_path)+    intf_drivers = {}+    for intf in glob.glob(os.path.join(dev_dir, f"{usb_path}:*")):+        drv = os.path.realpath(os.path.join(intf, "driver")) if \+            os.path.islink(os.path.join(intf, "driver")) else ""+        intf_drivers[os.path.basename(intf)] = os.path.basename(drv) if drv else None+    module_loaded = os.path.isdir("/sys/module/lan78xx")+    has_netdev = bool(_find_iface(dev_dir))+    notes = []+    if module_loaded and any(d == "lan78xx" for d in intf_drivers.values()) \+            and not has_netdev:+        notes.append("interface is bound to lan78xx but no netdev was created; "+                     "the device is likely re-enumerating/resetting (a changing "+                     "USB devnum across probes points to link/power flapping), or "+                     "PHY init failed")+    if not module_loaded:+        notes.append("lan78xx module is not loaded")+    notes.append("full cause needs `dmesg | grep lan78xx` (requires privilege)")+    return {"interface_drivers": intf_drivers, "module_loaded": module_loaded,+            "has_netdev": has_netdev, "notes": notes}+++def scan_devices(probe_eeprom: bool = True) -> list[dict]:+    found = []+    for idv in glob.glob(os.path.join(USB_DEVICES, "*", "idVendor")):+        dev_dir = os.path.dirname(idv)+        if _hex_id(idv) != LAN7800_VID:+            continue+        if _hex_id(os.path.join(dev_dir, "idProduct")) != LAN7800_PID:+            continue+        name = os.path.basename(dev_dir)          # e.g. "2-1"+        iface = _find_iface(dev_dir)+        mac = _read(f"/sys/class/net/{iface}/address") if iface else ""+        driver = _iface_driver(iface) if iface else ""+        entry = {+            "usb_path": name,+            "busnum": _read(os.path.join(dev_dir, "busnum")),+            "devnum": _read(os.path.join(dev_dir, "devnum")),+            "port_path": _read(os.path.join(dev_dir, "devpath")),+            "product": _read(os.path.join(dev_dir, "product")),+            "usb_serial": _read(os.path.join(dev_dir, "serial")),+            "iface": iface,+            "driver": driver,+            "mac": mac.upper() if mac else None,+            "bound": bool(iface),+            "eeprom": "unbound",+        }+        if iface and probe_eeprom:+            entry["eeprom"] = _probe_eeprom_signed(iface)+        found.append(entry)+    found.sort(key=lambda e: e["usb_path"])+    return found
cli/lan7800progadded+13
@@ -0,0 +1,13 @@+#!/usr/bin/env python3+"""Entry point for the LAN7800 EEPROM programmer CLI.++Runnable directly (`./lan7800prog ...`) or via `python3 -m lan7800.cli`.+"""+import os+import sys++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from lan7800.cli import main  # noqa: E402++if __name__ == "__main__":+    sys.exit(main())
cli/tests/__init__.pyadded

  
cli/tests/make_fixture.pyadded+73
@@ -0,0 +1,73 @@+"""Build a synthetic-but-realistic LAN7800 EEPROM .bin fixture.++No hardware needed. Lays down: 0xA5 signature, a MAC, a string heap with a+manufacturer/product/serial USB string descriptor, and SS/HS/FS USB device+descriptor blocks carrying VID/PID/bcdDevice — matching the layout the parser+in eeprom.py expects, so round-trip tests have something valid to chew on.+"""+import struct+import sys+import os++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+from lan7800.eeprom import (SIG_OFFSET, SIG_VALUE, MAC_OFFSET, STR_TABLE_OFFSET,+                            STR_NAMES, DESC_PTRS, MAC_LITTLE_ENDIAN)+++def usb_string(s: str) -> bytes:+    payload = s.encode("utf-16-le")+    return bytes([len(payload) + 2, 0x03]) + payload+++def device_descriptor(vid: int, pid: int, bcd: int) -> bytes:+    # 18-byte standard USB device descriptor; only VID/PID/bcdDevice matter here.+    return struct.pack("<BBHBBBBHHHBBBB",+                       0x12, 0x01, 0x0300, 0xFF, 0x00, 0x00, 64,+                       vid, pid, bcd, 1, 2, 3, 1)+++def build(mac="00:80:0F:11:22:33", vid=0x0424, pid=0x7800, bcd=0x0300,+          size=512) -> bytes:+    buf = bytearray(size)+    buf[SIG_OFFSET] = SIG_VALUE+    octets = [int(x, 16) for x in mac.split(":")]+    stored = octets[::-1] if MAC_LITTLE_ENDIAN else octets+    buf[MAC_OFFSET:MAC_OFFSET + 6] = bytes(stored)++    # --- string heap (word-aligned) ---+    # Placed high (0xC0+) so it clears both the fixed LED/GPIO register offsets+    # (0x07/0x0B-0x0D/0x0E/0x48-0x4F/0x58-0x59) and the descriptor blocks below.+    heap = 0xC0+    strings = {"manufacturer": "Microchip", "product": "LAN7800 USB 3.1 GbE",+               "serial": "SN0000000001"}+    for i, name in enumerate(STR_NAMES):+        entry = STR_TABLE_OFFSET + i * 2+        if name in strings:+            desc = usb_string(strings[name])+            buf[heap:heap + len(desc)] = desc+            buf[entry] = len(desc)          # length field (bytes)+            buf[entry + 1] = heap // 2       # word offset+            heap += (len(desc) + 1) & ~1     # keep word alignment+        else:+            buf[entry] = 0+            buf[entry + 1] = 0++    # --- descriptor blocks for SS/HS/FS ---+    # Placed at 0x60/0x80/0xA0 (24-byte slots) so no 18-byte block overlaps the+    # fixed GPIO config region (0x48-0x4F) or LED behavior (0x58-0x59). This+    # matches how a real EEPROM's pointer table keeps descriptors clear of the+    # low config/register bytes.+    dd = device_descriptor(vid, pid, bcd)+    block = 0x60+    for kind, ptr_off in DESC_PTRS.items():+        buf[block:block + len(dd)] = dd+        buf[ptr_off] = (block // 2) & 0xFF+        buf[ptr_off + 1] = ((block // 2) >> 8) & 0xFF+        block += 24+    return bytes(buf)+++if __name__ == "__main__":+    out = sys.argv[1] if len(sys.argv) > 1 else "fixture.bin"+    open(out, "wb").write(build())+    print(f"wrote {out}")
cli/tests/test_bulk.pyadded+128
@@ -0,0 +1,128 @@+"""Offline tests for bulk program mode: sequence math, image stamping, and the+resumable manifest. No hardware."""+import os+import sys+import tempfile++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+from lan7800.eeprom import Eeprom, EepromError  # noqa+from lan7800 import bulk  # noqa+from tests.make_fixture import build  # noqa+++def test_sequence_basic():+    seq = bulk.sequence("00:80:0F:78:00:00", count=3)+    assert [u["mac"] for u in seq] == [+        "00:80:0F:78:00:00", "00:80:0F:78:00:01", "00:80:0F:78:00:02"]+    assert [u["index"] for u in seq] == [0, 1, 2]+++def test_sequence_step_and_serial():+    seq = bulk.sequence("00:80:0F:78:00:00", count=3, step=16)+    assert [u["mac"] for u in seq] == [+        "00:80:0F:78:00:00", "00:80:0F:78:00:10", "00:80:0F:78:00:20"]+    # serial tracks MAC 1:1 as uppercase hex, no separators+    assert seq[2]["serial"] == "00800F780020"+++def test_sequence_carry_across_octet():+    seq = bulk.sequence("00:80:0F:78:00:FF", count=2)+    assert seq[1]["mac"] == "00:80:0F:78:01:00"+++def test_local_admin_sets_bit():+    seq = bulk.sequence("00:11:22:33:44:55", count=1, local_admin=True)+    # 0x00 -> 0x02 (locally administered, unicast)+    assert seq[0]["mac"] == "02:11:22:33:44:55"+++def test_multicast_base_refused():+    try:+        bulk.sequence("01:00:5E:00:00:01", count=1)  # low bit set = multicast+    except EepromError:+        return+    raise AssertionError("expected multicast base to be refused")+++def test_oui_overflow_refused():+    # only 2 NIC values left in this OUI, ask for 4 -> must refuse+    try:+        bulk.sequence("00:80:0F:FF:FF:FE", count=4)+    except EepromError:+        return+    raise AssertionError("expected OUI-crossing overflow to be refused")+++def test_build_image_stamps_mac_and_serial():+    tmpl = Eeprom.from_bytes(build())          # fixture has a 12-char serial slot+    data = bulk.build_image(tmpl, "00:80:0F:78:00:2A", "00800F78002A")+    e = Eeprom.from_bytes(data)+    assert e.has_signature+    assert e.mac == "00:80:0F:78:00:2A"+    assert e.string("serial").value == "00800F78002A"+++def test_manifest_resume_and_dedupe():+    with tempfile.TemporaryDirectory() as d:+        path = os.path.join(d, "run.csv")+        m = bulk.Manifest(path)+        assert m.next_index() == 0+        m.append(index=0, usb_path="1-1", old_mac="FF:FF:FF:FF:FF:FF",+                 old_serial="", new_mac="00:80:0F:78:00:00",+                 new_serial="00800F780000", verify="PASS")+        m.append(index=1, usb_path="1-1", old_mac="FF:FF:FF:FF:FF:FF",+                 old_serial="", new_mac="00:80:0F:78:00:01",+                 new_serial="00800F780001", verify="PASS")+        # reopen -> resumes at next index, remembers burned MACs+        m2 = bulk.Manifest(path)+        assert m2.next_index() == 2+        assert m2.has_mac("00:80:0F:78:00:00")+        assert os.path.exists(os.path.join(d, "run.json"))+        # refuse to reuse a burned MAC+        try:+            m2.append(index=2, usb_path="1-1", old_mac="x", old_serial="",+                      new_mac="00:80:0F:78:00:00", new_serial="00800F780000",+                      verify="PASS")+        except EepromError:+            return+        raise AssertionError("expected duplicate-MAC append to be refused")+++def test_last_burned_mac_for_swap_guard():+    with tempfile.TemporaryDirectory() as d:+        path = os.path.join(d, "run.csv")+        m = bulk.Manifest(path)+        assert m.last_burned_mac() is None+        m.append(index=0, usb_path="1-1", old_mac="FF:FF:FF:FF:FF:FF",+                 old_serial="", new_mac="00:80:0F:78:00:00",+                 new_serial="00800F780000", verify="PASS")+        m.append(index=1, usb_path="1-1", old_mac="FF:FF:FF:FF:FF:FF",+                 old_serial="", new_mac="00:80:0F:78:00:01",+                 new_serial="00800F780001", verify="PASS")+        # a DRYRUN row must NOT count as the last burned unit+        m.append(index=2, usb_path="", old_mac="", old_serial="",+                 new_mac="00:80:0F:78:00:99", new_serial="00800F780099",+                 verify="DRYRUN")+        assert m.last_burned_mac() == "00:80:0F:78:00:01"+++def test_manifest_dryrun_counts_as_done():+    with tempfile.TemporaryDirectory() as d:+        path = os.path.join(d, "run.csv")+        m = bulk.Manifest(path)+        m.append(index=0, usb_path="", old_mac="", old_serial="",+                 new_mac="00:80:0F:78:00:00", new_serial="00800F780000",+                 verify="DRYRUN")+        assert bulk.Manifest(path).next_index() == 1+++def _run():+    fns = [v for k, v in sorted(globals().items()) if k.startswith("test_")]+    for fn in fns:+        fn()+        print(f"  ok  {fn.__name__}")+    print(f"\n{len(fns)}/{len(fns)} passed")+++if __name__ == "__main__":+    _run()
cli/tests/test_eeprom.pyadded+191
@@ -0,0 +1,191 @@+"""Offline round-trip tests for the LAN7800 image model. No hardware.++Run: python3 -m pytest cli/tests   (or)   python3 cli/tests/test_eeprom.py+"""+import os+import sys++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+from lan7800.eeprom import Eeprom, EepromError, LAN7800_VID, LAN7800_PID  # noqa+from tests.make_fixture import build  # noqa+++def _fx():+    return Eeprom.from_bytes(build())+++def test_signature_and_size():+    e = _fx()+    assert e.size == 512+    assert e.has_signature and e.signature == 0xA5+++def test_mac_exact_bytes_natural_order():+    # RESOLVED assumption: EEPROM offset 0x01 = addr[0] (natural order).+    # Entering 00:80:0F:78:00:00 must store bytes 00 80 0F 78 00 00 at 0x01,+    # so the lan78xx driver reads the intended MAC back (not the byte-reverse).+    from lan7800.eeprom import MAC_OFFSET+    e = Eeprom.blank(512)+    e.set_mac("00:80:0F:78:00:00")+    assert bytes(e.data[MAC_OFFSET:MAC_OFFSET + 6]) == \+        bytes([0x00, 0x80, 0x0F, 0x78, 0x00, 0x00])+    assert e.mac == "00:80:0F:78:00:00"+    # and the reverse would have been the bug we fixed+    assert e.mac != "00:00:78:0F:80:00"+++def test_mac_roundtrip():+    e = _fx()+    assert e.mac == "00:80:0F:11:22:33"+    e.set_mac("AA:BB:CC:DD:EE:FF")+    assert e.mac == "AA:BB:CC:DD:EE:FF"+    # re-parse persisted bytes to prove octet order survives a save/load+    e2 = Eeprom.from_bytes(e.to_bytes())+    assert e2.mac == "AA:BB:CC:DD:EE:FF"+++def test_vid_pid_across_all_blocks():+    e = _fx()+    for d in e.descriptors():+        assert d.present and d.looks_valid+        assert d.vid == LAN7800_VID and d.pid == LAN7800_PID+    touched = e.set_vid(0x1234)+    assert set(touched) == {"ss", "hs", "fs"}+    e.set_pid(0xABCD)+    e2 = Eeprom.from_bytes(e.to_bytes())+    for d in e2.descriptors():+        assert d.vid == 0x1234 and d.pid == 0xABCD+++def test_bcd_device():+    e = _fx()+    e.set_bcd_device(0x0410)+    e2 = Eeprom.from_bytes(e.to_bytes())+    assert all(d.bcd_device == 0x0410 for d in e2.descriptors() if d.present)+++def test_strings_read():+    e = _fx()+    s = {x.name: x.value for x in e.strings() if x.present}+    assert s["manufacturer"] == "Microchip"+    assert s["product"] == "LAN7800 USB 3.1 GbE"+    assert s["serial"] == "SN0000000001"+++def test_serial_inplace_shorter_ok():+    e = _fx()+    e.set_string_inplace("serial", "SN42")  # shorter -> fits+    e2 = Eeprom.from_bytes(e.to_bytes())+    assert e2.string("serial").value == "SN42"+++def test_serial_inplace_too_long_refused():+    e = _fx()+    try:+        e.set_string_inplace("serial", "X" * 40)  # far larger than slot+    except EepromError:+        return+    raise AssertionError("expected EepromError for oversized in-place string")+++def test_set_string_absent_refused():+    e = _fx()+    try:+        e.set_string_inplace("interface", "eth")  # absent in fixture+    except EepromError:+        return+    raise AssertionError("expected EepromError setting an absent string")+++def test_signature_setter():+    e = Eeprom.blank(512)+    assert not e.has_signature+    e.set_signature()+    assert e.has_signature+++def test_bad_mac_rejected():+    e = _fx()+    for bad in ("00:11:22:33:44", "zz:11:22:33:44:55", "1:2:3:4:5:6:7"):+        try:+            e.set_mac(bad)+        except EepromError:+            continue+        raise AssertionError(f"expected rejection of {bad!r}")+++def test_led_roundtrip():+    from lan7800 import regs+    e = _fx()+    regs.set_led_mode(e, 0, 10); regs.set_led_enable(e, 0, True)+    regs.set_led_mode(e, 3, 15); regs.set_led_blink(e, 3)+    e2 = Eeprom.from_bytes(e.to_bytes())+    assert regs.get_led(e2, 0)["mode"] == 10 and regs.get_led(e2, 0)["enabled"]+    assert regs.get_led(e2, 3)["mode_name"] == "Force On"+    assert regs.get_led_blink(e2)["blink_rate"] == "20Hz"+++def test_gpio_roundtrip():+    from lan7800 import regs+    e = _fx()+    regs.set_gpio(e, 5, direction="out", drive="open-drain", output_value=1,+                  wake_enabled=True, wake_active_high=False)+    e2 = Eeprom.from_bytes(e.to_bytes())+    g = regs.get_gpio(e2, 5)+    assert g["direction"] == "out" and g["drive"] == "open-drain"+    assert g["output_value"] == 1 and g["wake_enabled"] and not g["wake_active_high"]+++def test_regs_bounds():+    from lan7800 import regs+    e = _fx()+    for bad in (-1, 4, 99):+        try:+            regs.set_led_mode(e, bad, 0)+        except EepromError:+            continue+        raise AssertionError("expected LED index rejection")+++def test_default_template():+    e = Eeprom.default_template()+    assert e.has_signature+    assert e.mac == "00:80:0F:00:00:00"+    ds = [d for d in e.descriptors() if d.present]+    assert len(ds) == 3+    assert all(d.vid == LAN7800_VID and d.pid == LAN7800_PID for d in ds)+    from lan7800 import regs+    assert regs.region_overlaps(e) == []   # descriptors clear of LED/GPIO offsets+++def test_overlap_guard():+    from lan7800 import regs+    from lan7800.eeprom import DESC_PTRS+    e = _fx()+    # Point the SS descriptor at 0x48 (word 0x24) so its 18-byte block covers+    # the fixed GPIO config region, and make it look like a real descriptor.+    e.data[DESC_PTRS["ss"]] = 0x24+    e.data[DESC_PTRS["ss"] + 1] = 0x00+    e.data[0x48] = 0x12+    e.data[0x49] = 0x01+    overlaps = regs.region_overlaps(e)+    assert overlaps, "region_overlaps should detect the collision"+    try:+        regs.set_gpio(e, 5, output_value=1)+    except EepromError:+        return+    raise AssertionError("guard should block a GPIO write into a descriptor block")+++def _run():+    fns = [v for k, v in sorted(globals().items()) if k.startswith("test_")]+    passed = 0+    for fn in fns:+        fn()+        passed += 1+        print(f"  ok  {fn.__name__}")+    print(f"\n{passed}/{len(fns)} passed")+++if __name__ == "__main__":+    _run()
docs/01-eeprom-mechanism.mdadded+61
@@ -0,0 +1,61 @@+# LAN7800 EEPROM programming on Linux — mechanism reference++Source: CONDUCTOR research scout, verified against Linux kernel source, LAN7800+datasheet DS00001992G, and u-boot. LAN7800 only (USB VID 0x0424 / PID 0x7800).++## Two backends++### A. Kernel driver + ethtool  (RECOMMENDED primary)+`drivers/net/usb/lan78xx.c` implements ethtool EEPROM ops.+- Constants: `LAN78XX_EEPROM_MAGIC 0x78A5`, `OTP_MAGIC 0x78F3`, `MAX_EEPROM_SIZE 512`,+  `EEPROM_INDICATOR 0xA5`, `EEPROM_MAC_OFFSET 0x01`, OTP indicators `0xF3`/`0xF7`.+- Read: `ethtool -e <iface> [raw on] [offset N length M]`. Reading a blank/unsigned+  EEPROM returns `-ENODATA` (offset 0 != 0xA5) — not zeros.+- Write: `ethtool -E <iface> magic 0x78A5 offset <o> value <v>` — one byte per call.+  The driver issues EWEN internally; you do NOT manage EWEN/EWDS on this path.+- Quirks: 512-byte max; 9-bit address (0–511); no signature check on write (you own+  writing 0xA5); reset/replug to reload the image (avoid raw RELOAD).++### B. libusb vendor commands  (only if driver-independence / blank-chip needed)+Unbind the kernel driver first. Two vendor control transfers:+- Read reg:  bmRequestType `0xC0`, bRequest `0xA1`, wValue 0, wIndex=reg offset, 4-byte LE.+- Write reg: bmRequestType `0x40`, bRequest `0xA0`, wValue 0, wIndex=reg offset, 4-byte LE.+Registers: `HW_CFG 0x010`, `E2P_CMD 0x040`, `E2P_DATA 0x044`.+E2P_CMD bits: `BUSY 0x80000000`, cmd field bits 30:28 — READ 0x0, EWDS 0x1<<28,+EWEN 0x2<<28, WRITE 0x3<<28, WRAL 0x4<<28, ERASE 0x5<<28, ERAL 0x6<<28, RELOAD 0x7<<28;+`TIMEOUT 0x400`, `DL 0x200`, `ADDR_MASK 0x1FF`.+- Read byte A: write E2P_CMD = BUSY|READ|A; poll BUSY clear; read E2P_DATA[7:0].+- Write byte D@A: EWEN once (BUSY|EWEN, poll); write E2P_DATA=D; write E2P_CMD=BUSY|WRITE|A+  (poll); repeat; EWDS when done. **You must issue EWEN yourself on this path.**++## EEPROM binary layout (datasheet Table 10-2, byte offsets)+- 0x00: `0xA5` signature (device ignores EEPROM if != 0xA5 → falls back to OTP/defaults)+- 0x01–0x06: MAC, **LE octet order** — MAC AA:BB:CC:DD:EE:FF → bytes FF EE DD CC BB AA+  (VERIFY direction against a real dump + datasheet §15.1.54 before trusting.)+- 0x07: GPIO wakeup enables; 0x09–0x0A GPIO PME flags; 0x0B–0x0D LED config 0/1/2+- 0x0E: GPIO wakeup polarity; 0x10–0x12 interrupt-EP polling (FS/HS/SS)+- 0x13–0x22: Config Flags 0–3 (4 bytes each, LE)+- 0x23–0x24: Language ID; 0x25–0x2E string desc len+word-offset pairs (Mfr, Product,+  Serial, Config, Interface). VID/PID live INSIDE the SS/HS/FS device-descriptor blocks+  (pointed to by 0x31/0x35/0x39), idVendor at desc bytes 8–9, idProduct 10–11, LE.+- Pointer fields are in 16-bit WORD units; length 0 = field absent → hardware default.++## Boot precedence+valid EEPROM → configured OTP → CSR defaults. USB reset reloads MAC only; full load on POR/RESET/SRST.++## Safe procedure (ethtool path)+1. Back up full EEPROM first: `sudo ethtool -e <iface> raw on > eeprom-backup.bin`+2. Confirm byte 0 == A5; MAC at 0x01–0x06.+3. Edit only the 6 MAC bytes on a COPY.+4. Write per-byte with magic 0x78A5.+5. Replug / usb reset to reload.+6. Verify: re-read, diff against intended image; `ip link` shows new MAC.++Anti-brick: never touch 0x00 unless deliberately writing 0xA5; stay 0–511; change the+minimum bytes; keep the backup; a cleared/!=A5 signature is recoverable (falls back).++## References+- linux drivers/net/usb/lan78xx.c + lan78xx.h (authoritative register map)+- LAN7800 Data Sheet DS00001992G §10.0–10.4, Table 10-2, §15.1.54+- u-boot drivers/usb/eth/lan78xx.c ; microchip-ung/lan78xx_linux+- Template libusb scaffolding (different chip, reuse structure only): karosium/asix_eepromtool, jglim/ASIXFlash
docs/02-mplab-connect-parity.mdadded+46
@@ -0,0 +1,46 @@+# MPLAB Connect parity — feature checklist for the LAN7800 Linux app++Source: CONDUCTOR research scout. Match the MPLAB Connect Configurator GUI feature set.+Docs to mirror: DS50002634D (GUI), DS50002552A Ch.11 (CLI/INI field schema), DS50002629 (CLI).++## Transport (settles the access-method question)+LAN78xx is driven through Microchip's **kernel network driver (NDIS miniport on Windows)**,+NOT WinUSB/libusb — WinUSB is their USB-hub path only. The Linux analog is the in-tree+`lan78xx` driver via **ethtool -e/-E**, which is exactly what Microchip's own support+article "LAN78xx EEPROM/OTP Programming on Linux" recommends. → ethtool is the right primary.++## CORE (v1 table-stakes parity)+- EEPROM **read → .bin dump**, **write image + verify**, **erase / restore defaults**+  (EEPROM only, not OTP). Support both 256- and 512-byte parts.+- **Config file = raw binary .bin** — byte-for-byte EEPROM image, NOT json. (JSON/.cfg is+  hub-line only; do not implement it for LAN78xx.) Load base → edit → **Preview** the exact+  .bin without touching hardware → Save.+- **MAC (single)**: colon hex; Microchip OUI 00:80:0F.+- **USB descriptor overrides**: VID, PID, bcdDevice/DID (on LAN7800 set BOTH USB2 and USB3+  VID/PID), string descriptors (Manufacturer, Product, Configuration, Interface — each+  enable/disable; empty string disables), serial number.+- **Signature contract (must be byte-exact)**: EEPROM byte0 = `0xA5`; OTP `0xF3`→payload@0x01,+  `0xF7`→payload@0x100; **`0xFF` on OTP sig = permanently dead** (guard hard in UI). Tools lay+  down the signature automatically when compiling settings→image.+- **Verify-after-write is mandatory** — read back and compare on every write cycle.+- Model **EEPROM-over-OTP boot precedence** in the UI (warn: if it boots from EEPROM, OTP+  writes appear to "do nothing").++## ADVANCED (later)+- OTP program (write-once, "fixed location"), MAC ranges / mass production (Start/Max/Increment+  for MAC + serial), multi-adapter targeting.+- Config flags / raw register overrides (ConfigFlags0/3/4/5), LED (4 LEDs × 16 modes + behavior),+  GPIO, PME/wake-up-frame filters, power (Self/Bus, SSMaxPower/HSMaxPower), remote wakeup.+- Live register R/W (control/status + PHY), production test harness (ping/loopback/speed).+- Optional human-readable source format (INI/TOML) that compiles to the .bin (that's what+  MPLAB's INI layer is). Not required for v1.++## LED modes (16), for later parity+0 Link/Act,1 Link1000/Act,2 Link100/Act,3 Link10/Act,4 Link100+1000/Act,5 Link10+1000/Act,+6 Link10+100/Act,7 rsvd,8 Duplex/Collision,9 Collision,10 Activity,11 rsvd,12 AutoNeg Fault,+13 Serial Mode,14 Force Off,15 Force On. + behavior reg (blink 2.5/5/10/20Hz, 5kHz pulse).++## Reading order (sources)+1. DS50002552A Ch.11 (definitive INI/BIN field schema) 2. DS50002634D (GUI) 3. DS50002629 (CLI)+4. EVB-LAN7800 UG DS50002482A (boot precedence) 5. support.microchip.com "LAN78xx EEPROM/OTP+Programming on Linux". Local PDFs saved this session under scratchpad (lan7800_sw_guide.pdf, mplab_gui.pdf).
docs/hero.pngadded
⋯ 1 unchanged line ⋯
install.shadded+47
@@ -0,0 +1,47 @@+#!/bin/sh+# lan7800-programmer install — put the CLI + webapp launcher on PATH.+# The CLI (cli/lan7800prog) needs its cli/lan7800/ package dir alongside it and+# the webapp finds the CLI relatively, so we install wrappers that point back+# into this module dir rather than copying files out of it.+set -e+SRC="$(cd "$(dirname "$0")" && pwd)"++pick_bindir() {+  if [ -w /usr/local/bin ]; then+    echo /usr/local/bin+  else+    mkdir -p "$HOME/.local/bin"+    echo "$HOME/.local/bin"+  fi+}+BIN="$(pick_bindir)"++# lan7800prog — the CLI+cat > "$BIN/lan7800prog" <<EOF+#!/bin/sh+exec python3 "$SRC/cli/lan7800prog" "\$@"+EOF+chmod +x "$BIN/lan7800prog"+echo "installed lan7800prog -> $BIN/lan7800prog"++# lan7800-programmer — the Hydrogen webapp (default port 8747, override with PORT)+cat > "$BIN/lan7800-programmer" <<EOF+#!/bin/sh+exec python3 "$SRC/webapp/server.py" "\$@"+EOF+chmod +x "$BIN/lan7800-programmer"+echo "installed lan7800-programmer -> $BIN/lan7800-programmer"++case ":$PATH:" in+  *":$BIN:"*) : ;;+  *) echo "note: add $BIN to your PATH" ;;+esac++# place the user skill where Claude Code discovers it+if [ -f "$SRC/SKILL.md" ]; then+  mkdir -p "$HOME/.claude/skills/lan7800-programmer"+  cp "$SRC/SKILL.md" "$HOME/.claude/skills/lan7800-programmer/SKILL.md"+  echo "installed skill -> $HOME/.claude/skills/lan7800-programmer/SKILL.md"+fi++echo "run: lan7800prog scan   (or)   lan7800-programmer   for the webapp"
package.jsonadded+72
@@ -0,0 +1,72 @@+{+  "slug": "lan7800-programmer",+  "title": "LAN7800 EEPROM Programmer",+  "type": "app",+  "version": "1.0.0",+  "bundled": true,+  "files": [+    "cli/**",+    "webapp/**",+    "docs/**",+    "templates/**",+    "install.sh",+    "uninstall.sh",+    "package.json",+    "README.md",+    "SKILL.md"+  ],+  "description": "MPLAB-Connect-parity EEPROM tool for the Microchip LAN7800 USB-3.1 to Gigabit-Ethernet controller (VID 0x0424 / PID 0x7800). Read an adapter's EEPROM to a .bin, edit MAC / VID / PID / bcdDevice / strings / serial and LED/GPIO with a byte-exact preview, and program hardware with verify-after-write. Reads are free; physical writes are gated behind --force-physical-write. Ships an AI-oriented CLI (single source of truth) plus a Hydrogen webapp that shells out to it.",+  "tags": [+    "cli",+    "eeprom",+    "lan7800",+    "microchip",+    "usb-ethernet",+    "hardware",+    "mac-address",+    "programmer"+  ],+  "dependencies": {},+  "discovery_triggers": [+    "program a LAN7800 EEPROM",+    "change the MAC address on a USB ethernet adapter",+    "LAN7800",+    "read an EEPROM from a USB3 ethernet dongle",+    "edit VID PID on a network adapter",+    "MPLAB connect on linux",+    "flash a Microchip LAN7800",+    "set the MAC on my usb gigabit adapter",+    "dump EEPROM to a bin file"+  ],+  "discovery_pitch": "When you need to read, edit, or program the EEPROM (MAC / VID / PID / strings / LED / GPIO) of a Microchip LAN7800 USB-3.1 to Gigabit-Ethernet adapter on Linux, reach for the LAN7800 EEPROM Programmer.",+  "sample_prompts": [+    {+      "label": "Change a MAC",+      "prompt": "I need to change the MAC address on my LAN7800 USB ethernet adapter"+    },+    {+      "label": "Read EEPROM",+      "prompt": "dump the EEPROM off my USB3-to-gigabit dongle to a file so I can inspect it"+    },+    {+      "label": "Open the app",+      "prompt": "open the LAN7800 programmer so I can edit an adapter's EEPROM in the browser"+    }+  ],+  "metadata": {+    "activate": {+      "kind": "skill",+      "skill": "lan7800-programmer",+      "requires": [],+      "verbPrefixes": []+    }+  },+  "scripts": {+    "install": "./install.sh",+    "uninstall": "./uninstall.sh"+  },+  "hero": {+    "type": "image",+    "path": "docs/hero.png"+  }+}
templates/lan7800-factory-template.binadded
⋯ 1 unchanged line ⋯
uninstall.shadded+12
@@ -0,0 +1,12 @@+#!/bin/sh+# lan7800-programmer uninstall — remove the wrappers and the user skill.+set -e+for BIN in /usr/local/bin "$HOME/.local/bin"; do+  for f in lan7800prog lan7800-programmer; do+    if [ -f "$BIN/$f" ]; then+      rm -f "$BIN/$f" && echo "removed $BIN/$f"+    fi+  done+done+rm -rf "$HOME/.claude/skills/lan7800-programmer"+echo "uninstalled lan7800-programmer"
webapp/screenshots/blank-banner.pngadded
⋯ 1 unchanged line ⋯
webapp/screenshots/desktop-0-defaults.pngadded
⋯ 1 unchanged line ⋯
webapp/screenshots/desktop-1-loaded.pngadded
⋯ 1 unchanged line ⋯
webapp/screenshots/desktop-3-scan.pngadded
⋯ 1 unchanged line ⋯
webapp/screenshots/desktop-4-errortoast.pngadded
⋯ 1 unchanged line ⋯
webapp/screenshots/desktop-5-overlap-banner.pngadded
⋯ 1 unchanged line ⋯
webapp/screenshots/desktop.pngadded
⋯ 1 unchanged line ⋯
webapp/screenshots/fixed-mac.pngadded
⋯ 1 unchanged line ⋯
webapp/screenshots/loadflow.pngadded
⋯ 1 unchanged line ⋯
webapp/screenshots/phone-1-loaded.pngadded
⋯ 1 unchanged line ⋯
webapp/screenshots/phone-3-scan.pngadded
⋯ 1 unchanged line ⋯
webapp/screenshots/phone-4-errortoast.pngadded
⋯ 1 unchanged line ⋯
webapp/screenshots/phone-5-overlap-banner.pngadded
⋯ 1 unchanged line ⋯
webapp/screenshots/phone.pngadded
⋯ 1 unchanged line ⋯
webapp/server.pyadded+971
@@ -0,0 +1,971 @@+#!/usr/bin/env python3+"""LAN7800 EEPROM Programmer, Hydrogen webapp (shells out to the CLI).++The web layer holds ZERO EEPROM logic: every operation runs `lan7800prog+--json ...` against a per-session working .bin, so the CLI stays the single+source of truth. Reads/edits/preview/save are free. Physical PROGRAM is+deliberately NOT wired to hardware here: the UI shows the exact gated command+and the escalation requirement instead of ever setting --force-physical-write.++AI-drivable per adom-ui-design: state lives on the server (GET /state), there is+a GET /console log, and every action returns structured JSON.+"""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+import time+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from urllib.parse import urlparse++HERE = os.path.dirname(os.path.abspath(__file__))+CLI = os.path.join(HERE, "..", "cli", "lan7800prog")+WORK_DIR = tempfile.mkdtemp(prefix="lan7800-webapp-")+WORK_BIN = os.path.join(WORK_DIR, "session.bin")+# Default template for BULK mode when the operator leaves the Template field+# blank. The bulk serial is stamped by an in-place string edit, so the template+# must carry a serial string slot; the built-in default template has blank+# strings and would fail at unit 0. This factory-derived image has ADOM/LAN7800+# strings + a 12-char serial slot that fits the mac-hex serial.+DEFAULT_BULK_TEMPLATE = os.path.join(HERE, "..", "templates",+                                     "lan7800-factory-template.bin")+# Default manifest so the operator can leave the field blank (no long path to+# paste). The CLI Manifest class does NOT create parent dirs, so we ensure the+# manifests/ dir exists here.+DEFAULT_BULK_MANIFEST = os.path.normpath(+    os.path.join(HERE, "..", "manifests", "bulk-run.csv"))+try:+    os.makedirs(os.path.dirname(DEFAULT_BULK_MANIFEST), exist_ok=True)+except OSError:+    pass+CONSOLE: list[str] = []+_BAD_JSON = object()  # sentinel: body present but not valid JSON+SOURCE = {"kind": "defaults", "name": None}  # defaults | image | device+++def log(msg: str) -> None:+    line = f"{time.strftime('%H:%M:%S')} {msg}"+    CONSOLE.append(line)+    del CONSOLE[:-200]+    print(line, file=sys.stderr)+++def run_cli(*args) -> dict:+    """Run the CLI with --json and return its parsed object."""+    cmd = [sys.executable, CLI, "--json", *args]+    log("cli " + " ".join(args))+    proc = subprocess.run(cmd, capture_output=True, text=True)+    out = proc.stdout.strip()+    try:+        obj = json.loads(out) if out else {"ok": proc.returncode == 0}+    except json.JSONDecodeError:+        obj = {"ok": False, "error": "internal CLI error"}+    if not obj.get("ok") and proc.stderr.strip() and "error" not in obj:+        obj["error"] = proc.stderr.strip()+    return obj+++class Handler(BaseHTTPRequestHandler):+    def _send(self, code, body, ctype="application/json"):+        if isinstance(body, (dict, list)):+            body = json.dumps(body).encode()+        elif isinstance(body, str):+            body = body.encode()+        self.send_response(code)+        self.send_header("Content-Type", ctype)+        self.send_header("Content-Length", str(len(body)))+        self.end_headers()+        self.wfile.write(body)++    def _body_json(self):+        n = int(self.headers.get("Content-Length", 0) or 0)+        if not n:+            return {}+        raw = self.rfile.read(n)+        try:+            return json.loads(raw or b"{}")+        except json.JSONDecodeError:+            return _BAD_JSON++    def log_message(self, *a):+        pass++    # -- routes -----------------------------------------------------------+    def do_GET(self):+        path = urlparse(self.path).path+        if path in ("/", "/index.html"):+            return self._send(200, INDEX_HTML, "text/html; charset=utf-8")+        if path == "/state":+            return self._send(200, self._state())+        if path == "/console":+            return self._send(200, {"ok": True, "lines": CONSOLE[-100:]})+        if path == "/scan":+            return self._send(200, run_cli("scan"))+        if path == "/bulk-defaults":+            return self._send(200, {"ok": True,+                "manifest": DEFAULT_BULK_MANIFEST,+                "template": os.path.normpath(DEFAULT_BULK_TEMPLATE)})+        if path == "/bin":+            if not os.path.exists(WORK_BIN):+                return self._send(404, {"ok": False, "error": "no session image"})+            with open(WORK_BIN, "rb") as fh:+                return self._send(200, fh.read(), "application/octet-stream")+        return self._send(404, {"ok": False, "error": "not found"})++    def do_POST(self):+        path = urlparse(self.path).path+        if path == "/upload":+            return self._upload()+        body = self._body_json()+        if body is _BAD_JSON:+            return self._send(400, {"ok": False, "error": "malformed JSON body"})+        if path == "/new":+            r = run_cli("new", "--out", WORK_BIN)+            SOURCE["kind"], SOURCE["name"] = "defaults", None+            return self._send(200, {**r, "state": self._state_obj()})+        if path == "/load":+            src = body.get("path", "")+            if not src or not os.path.exists(src):+                return self._send(400, {"ok": False,+                                        "error": f"no such file: {src}"})+            shutil.copyfile(src, WORK_BIN)+            SOURCE["kind"], SOURCE["name"] = "image", os.path.basename(src)+            log(f"loaded base {src}")+            return self._send(200, {"ok": True, "state": self._state_obj()})+        if path == "/read-connected":+            r = run_cli("read-device", "--out", WORK_BIN)+            if r.get("ok"):+                SOURCE["kind"], SOURCE["name"] = "device", \+                    (r.get("device", {}) or {}).get("usb_path")+            return self._send(200 if r.get("ok") else 502,+                              {**r, "state": self._state_obj()})+        if path == "/read-device":+            iface = body.get("iface", "").strip()+            if not iface:+                return self._send(400, {"ok": False, "error": "iface required"})+            r = run_cli("read", "--iface", iface, "--out", WORK_BIN)+            if r.get("ok"):+                SOURCE["kind"], SOURCE["name"] = "device", iface+            return self._send(200 if r.get("ok") else 502,+                              {**r, "state": self._state_obj()})+        if path == "/edit":+            r = self._edit(body)+            return self._send(200 if r.get("ok") else 400, r)+        if path == "/save":+            dst = body.get("path", "")+            if not dst:+                return self._send(400, {"ok": False, "error": "path required"})+            if not os.path.exists(WORK_BIN):+                return self._send(400, {"ok": False, "error": "no session image"})+            os.makedirs(os.path.dirname(os.path.abspath(dst)), exist_ok=True)+            shutil.copyfile(WORK_BIN, dst)+            log(f"saved to {dst}")+            return self._send(200, {"ok": True, "path": dst})+        if path == "/verify":+            iface = body.get("iface", "").strip()+            if not iface:+                return self._send(400, {"ok": False, "error": "iface required"})+            r = run_cli("verify", "--iface", iface, "--image", WORK_BIN)+            return self._send(200 if r.get("ok") else 502, r)+        if path == "/program":+            return self._send(200, self._program_request())+        if path == "/program-poll":+            return self._send(200, self._program_poll(body.get("escalation_id", "")))+        if path == "/bulk-preview":+            return self._send(200, self._bulk_preview(body))+        if path == "/bulk-program":+            return self._send(200, self._bulk_program_request(body))+        if path == "/bulk-program-poll":+            return self._send(200, self._bulk_program_poll(body.get("escalation_id", "")))+        if path == "/bulk-burn-one":+            return self._send(200, self._bulk_burn_one(body))+        return self._send(404, {"ok": False, "error": "not found"})++    # -- helpers ----------------------------------------------------------+    def _upload(self):+        n = int(self.headers.get("Content-Length", 0) or 0)+        if not n:+            return self._send(400, {"ok": False, "error": "empty upload"})+        if n > 512:+            return self._send(413, {"ok": False,+                              "error": f"file too large ({n}B); EEPROM is 512B max"})+        data = self.rfile.read(n)+        with open(WORK_BIN, "wb") as fh:+            fh.write(data)+        fname = self.headers.get("X-Filename", "upload.bin")+        SOURCE["kind"], SOURCE["name"] = "image", fname+        log(f"uploaded {fname} ({len(data)}B) via file picker")+        resp = {"ok": True, "bytes": len(data), "state": self._state_obj()}+        if not data or data[0] != 0xA5:+            resp["hint"] = ("loaded, but this is not a signed LAN7800 EEPROM "+                            "(byte0 is not 0xA5); the device would ignore it")+        return self._send(200, resp)++    def _edit(self, body) -> dict:+        args = ["edit", "--in", WORK_BIN, "--out", WORK_BIN]+        for key, flag in (("mac", "--mac"), ("vid", "--vid"), ("pid", "--pid"),+                          ("bcd", "--bcd"), ("serial", "--serial")):+            val = body.get(key)+            if val not in (None, ""):+                args += [flag, str(val)]+        for name, val in (body.get("strings") or {}).items():+            if val not in (None, ""):+                args += ["--set-string", f"{name}={val}"]+        for key, flag in (("set_led", "--set-led"), ("led_enable", "--led-enable"),+                          ("set_gpio", "--set-gpio"), ("gpio_wake", "--gpio-wake"),+                          ("set_configflag", "--set-configflag"),+                          ("set_raw", "--set-raw")):+            for spec in (body.get(key) or []):+                if spec:+                    args += [flag, str(spec)]+        if body.get("led_blink") not in (None, ""):+            args += ["--led-blink", str(body["led_blink"])]+        if body.get("ensure_signature"):+            args += ["--ensure-signature"]+        if len(args) <= 4:+            return {"ok": False, "error": "no fields to edit"}+        r = run_cli(*args)+        r["state"] = self._state_obj()+        return r++    # -- gated program flow (webapp escalates; writes only after PROCEED) ----+    def _program_request(self) -> dict:+        if not os.path.exists(WORK_BIN):+            return {"ok": False, "error": "no image to program"}+        info = run_cli("info", "--in", WORK_BIN)+        # Never assemble/escalate an unsigned or empty image.+        if not info.get("signature_ok"):+            return {"ok": False, "error": "refusing to program an UNSIGNED image "+                    "(byte0 != 0xA5). Click 'Load defaults to program this chip', "+                    "set a MAC/VID/PID, then Apply before programming."}+        if info.get("mac") in (None, "00:00:00:00:00:00"):+            return {"ok": False, "error": "refusing to program an all-zero MAC. "+                    "Set a real MAC (Microchip OUI 00:80:0F:xx:xx:xx) and Apply first."}+        d0 = next((x for x in info.get("descriptors", []) if x.get("present")), {})+        summ = (f"MAC {info.get('mac')} VID {d0.get('vid')} PID {d0.get('pid')} "+                f"sig {info.get('signature')}")+        # diff vs the connected device (free libusb read)+        v = run_cli("verify", "--image", WORK_BIN)+        diff = v.get("diff_count", "?")+        q = (f"Human clicked Program on the connected 0424:7800 (libusb, sudo-free). "+             f"Image: {summ}. Bytes differing vs current device: {diff}. "+             f"Approve this ONE physical EEPROM write (signature written last, "+             f"verify-after-write)?")+        proc = subprocess.run(+            ["mesh", "escalate", "--agent", "LAN7800",+             "--action", "program-device", "--question", q,+             "--risk", "medium", "--default", "hold"],+            capture_output=True, text=True)+        try:+            r = json.loads(proc.stdout.strip() or "{}")+        except json.JSONDecodeError:+            return {"ok": False, "error": "could not raise escalation",+                    "detail": proc.stderr.strip()[:200]}+        eid = r.get("escalation_id")+        log(f"program escalated: {eid}")+        return {"ok": True, "pending": True, "escalation_id": eid,+                "summary": summ, "diff_count": diff,+                "message": "Escalated to CONDUCTOR for approval; waiting for PROCEED."}++    def _poll_decision(self, eid: str):+        """Scan CONDUCTOR's thread for a decision on THIS escalation_id.+        Returns 'allow' | 'deny' | None (still pending). Shared by the single+        program flow and the bulk burn so both match identically."""+        thread = os.path.expanduser("~/.agent-mesh/CONDUCTOR_LAN7800.jsonl")+        decision = None+        try:+            with open(thread) as fh:+                for line in fh:+                    try:+                        m = json.loads(line)+                    except json.JSONDecodeError:+                        continue+                    if m.get("kind") != "decision":+                        continue+                    # Match the STRUCTURED escalation_id field. The prior code+                    # checked `eid in msg` -- but a decision carries the id in the+                    # `escalation_id` field, NOT the human-facing `msg` text, so+                    # it never matched and the UI polled forever. Fall back to a+                    # substring check for older/hand-written decisions.+                    ref = m.get("escalation_id", "")+                    msg = m.get("msg", "")+                    if ref == eid or (eid and eid in msg):+                        verdict = (m.get("verdict") or msg).upper()+                        if "PROCEED" in verdict or "ALLOW" in verdict:+                            decision = "allow"+                        elif "STOP" in verdict or "DENY" in verdict:+                            decision = "deny"+        except OSError:+            pass+        return decision++    def _program_poll(self, eid: str) -> dict:+        if not eid:+            return {"ok": False, "error": "escalation_id required"}+        decision = self._poll_decision(eid)+        if decision is None:+            return {"ok": True, "pending": True,+                    "message": "Still waiting for CONDUCTOR approval."}+        if decision == "deny":+            log(f"program {eid}: DENIED")+            return {"ok": False, "denied": True,+                    "message": "CONDUCTOR denied the program request."}+        # APPROVED -> run the real gated libusb write + verify+        log(f"program {eid}: PROCEED -> writing via libusb")+        r = run_cli("program", "--image", WORK_BIN, "--force-physical-write")+        if r.get("ok"):+            SOURCE["kind"], SOURCE["name"] = "device", "programmed"+            return {"ok": True, "programmed": True, "result": r,+                    "state": self._state_obj(),+                    "message": f"Programmed via {r.get('backend')} "+                               f"({'verified' if r.get('verified') else 'no-verify'})."}+        return {"ok": False, "result": r,+                "message": r.get("error") or "program failed", "state": self._state_obj()}++    # -- bulk program mode (reuses the CLI `bulk` subcommand; no dup logic) ---+    def _bulk_cli_args(self, body):+        """Validate the bulk inputs and build the shared CLI arg list. Returns a+        dict on error (so callers can `if isinstance(args, dict): return args`)."""+        base = (body.get("base") or "").strip()+        if not base:+            return {"ok": False, "error": "base MAC is required"}+        try:+            count = int(body.get("count"))+        except (TypeError, ValueError):+            return {"ok": False, "error": "count must be an integer"}+        if count < 1:+            return {"ok": False, "error": "count must be >= 1"}+        args = ["--base", base, "--count", str(count)]+        step = body.get("step")+        if step not in (None, ""):+            try:+                args += ["--step", str(int(step))]+            except (TypeError, ValueError):+                return {"ok": False, "error": "step must be an integer"}+        if body.get("scheme"):+            args += ["--scheme", str(body["scheme"])]+        if body.get("local_admin"):+            args += ["--local-admin"]+        tmpl = (body.get("template") or "").strip()+        if not tmpl and os.path.exists(DEFAULT_BULK_TEMPLATE):+            tmpl = DEFAULT_BULK_TEMPLATE   # blank -> factory template (has a serial slot)+        if tmpl:+            args += ["--template", tmpl]+        return args++    def _effective_template(self, body) -> str:+        tmpl = (body.get("template") or "").strip()+        if not tmpl and os.path.exists(DEFAULT_BULK_TEMPLATE):+            return os.path.normpath(DEFAULT_BULK_TEMPLATE)+        return tmpl or "(built-in default template)"++    def _bulk_preview(self, body) -> dict:+        """DRY-RUN preview: full per-unit MAC/serial table, no device, no writes.+        Uses a THROWAWAY temp manifest so a preview never pollutes a real-burn+        manifest."""+        import tempfile+        args = self._bulk_cli_args(body)+        if isinstance(args, dict):+            return args+        fd, tmp = tempfile.mkstemp(suffix=".csv", prefix="bulk-preview-")+        os.close(fd)+        try:+            r = run_cli("bulk", *args, "--dry-run", "--manifest", tmp)+        finally:+            for p in (tmp, os.path.splitext(tmp)[0] + ".json"):+                try:+                    os.remove(p)+                except OSError:+                    pass+        if isinstance(r, dict):+            r["template_used"] = self._effective_template(body)+        return r++    def _bulk_program_request(self, body) -> dict:+        """Escalate ONCE for a session-scoped allow before any unit is written."""+        args = self._bulk_cli_args(body)+        if isinstance(args, dict):+            return args+        scheme = body.get("scheme") or "mac-hex"+        la = ", locally-administered 02:" if body.get("local_admin") else ""+        q = (f"BULK burn: program {body.get('count')} LAN7800 unit(s) from base "+             f"MAC {body.get('base')} (serial={scheme}{la}). SESSION-scoped allow "+             f"for this run: per-unit insert -> write (signature last) -> verify "+             f"-> manifest row. Approve the run?")+        proc = subprocess.run(+            ["mesh", "escalate", "--agent", "LAN7800", "--action",+             "program-device", "--question", q, "--risk", "medium",+             "--default", "hold"], capture_output=True, text=True)+        try:+            r = json.loads(proc.stdout.strip() or "{}")+        except json.JSONDecodeError:+            return {"ok": False, "error": "could not raise escalation",+                    "detail": proc.stderr.strip()[:200]}+        eid = r.get("escalation_id")+        log(f"bulk escalated: {eid}")+        return {"ok": True, "pending": True, "escalation_id": eid,+                "message": "Bulk burn escalated to CONDUCTOR; waiting for a "+                           "session-scoped PROCEED."}++    def _bulk_program_poll(self, eid: str) -> dict:+        if not eid:+            return {"ok": False, "error": "escalation_id required"}+        d = self._poll_decision(eid)+        if d is None:+            return {"ok": True, "pending": True,+                    "message": "Waiting for CONDUCTOR session-scoped approval."}+        if d == "deny":+            return {"ok": False, "denied": True,+                    "message": "CONDUCTOR denied the bulk burn."}+        return {"ok": True, "allow": True, "message": "Approved; burn may proceed."}++    def _bulk_burn_one(self, body) -> dict:+        """Program the NEXT un-burned unit on the connected device (one per call;+        the operator inserts each unit between calls). Requires a persistent+        --manifest so the run is resumable and MAC reuse is refused."""+        manifest = (body.get("manifest") or "").strip() or DEFAULT_BULK_MANIFEST+        # The CLI Manifest class does not create parent dirs; ensure it exists.+        try:+            os.makedirs(os.path.dirname(os.path.abspath(manifest)), exist_ok=True)+        except OSError as e:+            return {"ok": False, "error": f"cannot create manifest dir: {e}"}+        args = self._bulk_cli_args(body)+        if isinstance(args, dict):+            return args+        r = run_cli("bulk", *args, "--manifest", manifest, "--force-physical-write")+        if isinstance(r, dict):+            r["template_used"] = self._effective_template(body)+            r["manifest_used"] = os.path.normpath(manifest)+        return r++    def _state_obj(self) -> dict:+        if not os.path.exists(WORK_BIN):+            return {"loaded": False, "source_kind": "defaults"}+        info = run_cli("info", "--in", WORK_BIN)+        info["loaded"] = True+        info["source_kind"] = SOURCE["kind"]+        info["source_name"] = SOURCE["name"]+        return info++    def _state(self) -> dict:+        return {"ok": True, "state": self._state_obj()}+++INDEX_HTML = r"""<!doctype html>+<html lang="en"><head>+<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">+<title>USB3.0 to Ethernet Molecule Programmer</title>+<style>+  :root{--bg:#0e1116;--panel:#161b22;--edge:#1c2128;--fg:#e6edf3;--mut:#8b949e;+        --acc:#00b8b1;--acc-d:#00938d;--ok:#3fb950;--warn:#d29922;--bad:#f85149}+  *{box-sizing:border-box} body{margin:0;background:var(--bg);color:var(--fg);+    font:14px/1.5 system-ui,Segoe UI,Roboto,sans-serif}+  header{height:44px;display:flex;align-items:center;gap:10px;padding:0 16px;+    background:var(--panel);border-bottom:1px solid var(--edge);position:sticky;top:0;z-index:5}+  header .dot{width:10px;height:10px;border-radius:50%;background:var(--acc)}+  header h1{font-size:15px;margin:0;font-weight:600}+  header .sig{margin-left:auto;font-size:12px;color:var(--mut)}+  main{max-width:960px;margin:0 auto;padding:16px;display:grid;gap:16px;+    grid-template-columns:1fr 1fr}+  .panel{background:var(--panel);border:1px solid var(--edge);border-radius:10px;padding:14px}+  .panel.full{grid-column:1/-1}+  h2{font-size:13px;text-transform:uppercase;letter-spacing:.04em;color:var(--mut);margin:0 0 10px}+  h2 .warn{color:var(--warn);text-transform:none;letter-spacing:0}+  label{display:block;font-size:12px;color:var(--mut);margin:8px 0 3px}+  input,select{width:100%;background:#0d1117;border:1px solid var(--edge);color:var(--fg);+    border-radius:6px;padding:7px 9px;font:13px monospace}+  .row{display:flex;gap:8px} .row>*{flex:1}+  button{background:var(--acc);color:#08110f;border:0;border-radius:6px;padding:8px 12px;+    font-weight:600;cursor:pointer} button:hover{background:var(--acc-d)}+  button.ghost{background:#21262d;color:var(--fg)} button.ghost:hover{background:#2b323c}+  button:disabled{opacity:.45;cursor:not-allowed}+  button.danger{background:var(--bad);color:#fff}+  .kv{display:flex;justify-content:space-between;gap:12px;border-bottom:1px solid var(--edge);padding:4px 0}+  .kv b{font-weight:600;font-family:monospace}+  .pill{font-size:11px;padding:2px 7px;border-radius:20px;background:#2b323c}+  .pill.ok{background:rgba(63,185,80,.15);color:var(--ok)}+  .pill.bad{background:rgba(248,81,73,.15);color:var(--bad)}+  .note{font-size:12px;color:var(--warn);margin-top:8px}+  .mut{color:var(--mut)}+  #toast{position:fixed;left:50%;transform:translateX(-50%);bottom:16px;+    display:flex;flex-direction:column;align-items:center;gap:8px;z-index:20}+  .t{background:#21262d;border:1px solid var(--edge);border-left:3px solid var(--acc);+    padding:10px 14px;border-radius:6px;max-width:360px;font-size:13px;animation:in .2s}+  .t.ok{border-left-color:var(--ok)}+  .t.bad{border-left-color:var(--bad);background:rgba(248,81,73,.14);+    border-color:rgba(248,81,73,.5);color:#ffd7d3}+  .t.bad::before{content:"Error: ";font-weight:700;color:var(--bad)}+  @keyframes in{from{opacity:0;transform:translateY(6px)}}+  @media(pointer:coarse){input[type=checkbox]{min-width:22px;min-height:22px}+    .panel label{padding:5px 0;min-height:30px}}+  @media(max-width:720px){main{grid-template-columns:1fr} #ledgpio{grid-template-columns:1fr !important}}+  @media(max-width:430px){header{height:auto;min-height:44px;padding:6px 12px}+    header h1{font-size:13px;line-height:1.15}}+</style></head><body>+<header><span class="dot"></span><h1>USB3.0 to Ethernet Molecule Programmer</h1>+  <span class="pill" id="srcind" style="margin-left:auto"+    title="What the form is currently showing">Defaults</span>+  <span class="sig" id="sig" style="margin-left:12px">no image</span></header>+<main>+  <div id="blankBanner" class="panel full" role="alert"+    style="display:none;border-color:var(--bad);background:rgba(248,81,73,.09)"></div>+  <div id="overlapBanner" class="panel full" role="alert"+    style="display:none;border-color:var(--warn);background:rgba(210,153,34,.09)"></div>+  <section class="panel">+    <h2>Source</h2>+    <button class="ghost" style="width:100%" onclick="scan()"+      title="Enumerate attached LAN7800 adapters (USB 0424:7800). Reads only.">Scan for devices</button>+    <div id="scanList"></div>+    <label for="loadFile">Base image (.bin)</label>+    <div class="row"><input id="loadFile" type="file" accept=".bin,application/octet-stream"+        aria-label="Choose a .bin EEPROM image from disk"+        title="Pick a .bin file (max 512 bytes); it uploads and previews without touching hardware"+        onchange="uploadFile()" style="padding:5px">+      <input id="loadPath" placeholder="or type a server path" style="flex:1.2"+        aria-label="Server-side path to a .bin image"+        title="Absolute path to a .bin already on the server">+      <button class="ghost" style="flex:0 0 auto" onclick="loadBase()"+        title="Load the .bin at the typed server path">Load path</button></div>+    <button style="width:100%;margin-top:8px" onclick="readConnected()"+      title="Read the EEPROM from the currently connected LAN7800 (auto: netdev via ethtool, else libusb). Free, no write.">Read connected device</button>+    <label for="iface">Or read a specific interface (free)</label>+    <div class="row"><input id="iface" placeholder="e.g. enx00800f780000"+        aria-label="Network interface of the LAN7800"+        title="The lan78xx-bound network interface to read the EEPROM from">+      <button class="ghost" style="flex:0 0 auto" onclick="readDev()"+        title="Read the device EEPROM via this interface (free, no write)">Read</button></div>+    <div class="row" style="margin-top:10px">+      <button class="ghost" onclick="newImg()"+        title="Create a fresh 512-byte image with the 0xA5 signature set">New blank (signed)</button>+      <a href="/bin" download="lan7800.bin" style="flex:1"><button class="ghost" style="width:100%"+        title="Download the current session image as a .bin">Download .bin</button></a>+    </div>+  </section>++  <section class="panel">+    <h2>Edit fields</h2>+    <label for="mac">MAC (Microchip OUI 00:80:0F)</label>+    <input id="mac" placeholder="00:80:0F:xx:xx:xx" aria-label="MAC address"+      title="Six hex octets, colon or hyphen separated">+    <div class="row">+      <div><label for="vid">VID</label><input id="vid" placeholder="0x0424"+        aria-label="USB Vendor ID" title="USB Vendor ID, decimal or 0x-hex (LAN7800 is 0x0424)"></div>+      <div><label for="pid">PID</label><input id="pid" placeholder="0x7800"+        aria-label="USB Product ID" title="USB Product ID, decimal or 0x-hex (LAN7800 is 0x7800)"></div>+      <div><label for="bcd">bcdDevice</label><input id="bcd" placeholder="0x0300"+        aria-label="bcdDevice (device release number)" title="bcdDevice / DID, 16-bit"></div></div>+    <label for="serial">Serial (in-place, fits existing slot)</label>+    <input id="serial" placeholder="SN..." aria-label="Serial number string"+      title="Overwrites the existing serial string in place; must fit the current slot">+    <label for="product">Product string (in-place)</label>+    <input id="product" placeholder="LAN7800 ..." aria-label="Product descriptor string"+      title="Overwrites the existing product string in place">+    <label for="manufacturer">Manufacturer string (in-place)</label>+    <input id="manufacturer" aria-label="Manufacturer descriptor string"+      title="Overwrites the existing manufacturer string in place">+    <div class="row">+      <div><label for="configuration">Configuration string</label>+        <input id="configuration" aria-label="Configuration descriptor string" title="In-place"></div>+      <div><label for="interface">Interface string</label>+        <input id="interface" aria-label="Interface descriptor string" title="In-place"></div></div>+    <label>Config Flags 0..3 (32-bit hex, from the loaded image)</label>+    <div class="row">+      <input id="cf0" aria-label="Config Flag 0" title="Config Flags word 0 (0x13)" placeholder="0x00000000">+      <input id="cf1" aria-label="Config Flag 1" title="Config Flags word 1 (0x17)" placeholder="0x00000000">+      <input id="cf2" aria-label="Config Flag 2" title="Config Flags word 2 (0x1B)" placeholder="0x00000000">+      <input id="cf3" aria-label="Config Flag 3" title="Config Flags word 3 (0x1F)" placeholder="0x00000000"></div>+    <div class="row" style="margin-top:12px">+      <button onclick="applyEdit()" title="Apply these fields and refresh the preview">Apply and preview</button>+      <button class="ghost" onclick="refresh()" title="Reload state from the server">Reload state</button></div>+    <div class="note">VID/PID/strings need a base image with descriptor blocks. Signature auto-set on apply.</div>+  </section>++  <section class="panel full">+    <h2>LED / GPIO <span class="warn">(bit layout: verify vs datasheet sec 15)</span></h2>+    <div id="ledgpio" style="display:grid;grid-template-columns:1fr 1fr;gap:16px">+      <div><b style="font-size:12px">LEDs</b><div id="ledRows"></div>+        <label for="blink">Blink rate</label>+        <select id="blink" aria-label="LED blink rate" title="Global LED blink rate">+          <option value="">(unchanged)</option><option value="0">2.5Hz</option>+          <option value="1">5Hz</option><option value="2">10Hz</option><option value="3">20Hz</option></select></div>+      <div><b style="font-size:12px">GPIO</b>+        <label for="gpioPin">Pin</label>+        <select id="gpioPin" aria-label="GPIO pin index" title="Which GPIO pin to edit (0..7)"></select>+        <label for="gpioDir">Direction</label>+        <select id="gpioDir" aria-label="GPIO direction" title="Input or output">+          <option value="">(unchanged)</option><option>in</option><option>out</option></select>+        <label for="gpioDrive">Drive</label>+        <select id="gpioDrive" aria-label="GPIO drive type" title="Output driver type">+          <option value="">(unchanged)</option><option>push-pull</option><option>open-drain</option><option>default</option></select>+        <label><input type="checkbox" id="gpioOut" style="width:auto" aria-label="GPIO output high"+          title="Output level when direction is output"> output high</label>+        <label><input type="checkbox" id="gpioWake" style="width:auto" aria-label="GPIO wake enable"+          title="Enable wake-on-GPIO for this pin"> wake enable</label>+        <label><input type="checkbox" id="gpioPol" style="width:auto" aria-label="GPIO wake active-high"+          title="Wake polarity: checked means active-high"> wake active-high</label>+      </div>+    </div>+    <button style="margin-top:12px" onclick="applyLedGpio()"+      title="Apply LED and GPIO settings and refresh the preview">Apply LED/GPIO and preview</button>+    <div class="note">Offsets are authoritative (LED 0x0B to 0x0D and 0x58 to 0x59; GPIO 0x07, 0x0E,+      0x48 to 0x4F); per-bit encoding is best-effort until confirmed against a real dump. A write that+      would land inside a USB descriptor block is blocked to avoid corruption.</div>+  </section>++  <section class="panel full">+    <h2>Live preview (exact .bin, no hardware)</h2>+    <div id="preview"><span class="mut">Load or read an image to begin.</span></div>+    <div class="row" style="margin-top:12px;max-width:520px">+      <input id="savePath" placeholder="/path/to/output.bin" aria-label="Path to save the .bin to"+        title="Server-side path to write the current image">+      <button style="flex:0 0 auto" onclick="save()" title="Save the current image to the path">Save .bin</button></div>+  </section>++  <section class="panel full">+    <h2>Hardware</h2>+    <div class="row" style="max-width:520px">+      <input id="vIface" placeholder="interface for verify (free)" aria-label="Interface for verify"+        title="Interface to compare the device EEPROM against the current image">+      <button class="ghost" style="flex:0 0 auto" onclick="verify()"+        title="Read the device and compare it to the current image (free)">Verify device vs image</button></div>+    <button class="danger" style="margin-top:12px" onclick="program()"+      title="Programming is gated; this returns the exact command to run under escalation">Program to device...</button>+    <div class="note">Warning: programming writes to a physical adapter and is gated.+      This UI never writes hardware directly; it returns the exact command, which an+      operator runs only after a mesh escalate PROCEED.</div>+  </section>++  <section class="panel full">+    <h2>Bulk Program mode</h2>+    <div class="note">Program many adapters with an auto-incrementing identity.+      <b>Preview</b> is safe (no device). <b>Program All</b> is gated: it escalates+      ONCE to CONDUCTOR, then walks units (insert &rarr; write &rarr; verify &rarr;+      manifest).</div>+    <div class="row" style="flex-wrap:wrap;gap:8px;max-width:860px;margin-top:8px">+      <input id="bkBase" placeholder="base MAC e.g. 00:80:0F:78:00:00" aria-label="Base MAC"+        title="Starting MAC; the OUI is not hardcoded" style="flex:1 1 220px">+      <input id="bkCount" type="number" min="1" value="10" aria-label="Count"+        title="How many units to program" style="flex:0 0 90px">+      <input id="bkStep" type="number" value="1" aria-label="Step"+        title="MAC increment per unit (default 1)" style="flex:0 0 84px">+      <select id="bkScheme" aria-label="Serial scheme" title="Serial numbering scheme"+        style="flex:0 0 150px"><option value="mac-hex">serial = MAC hex</option></select>+      <label style="flex:0 0 auto;display:flex;align-items:center;gap:6px;margin:0"+        title="Force the locally-administered 02: bit instead of using the base OUI">+        <input type="checkbox" id="bkLocal" style="width:auto"> local-admin (02:)</label>+      <input id="bkTemplate" placeholder="template .bin (blank = factory ADOM/LAN7800)" aria-label="Template"+        title="Base image whose serial slot fits the 12-char MAC-hex serial; blank uses the built-in factory template" style="flex:1 1 200px">+      <input id="bkManifest" placeholder="blank = default manifests/bulk-run.csv" aria-label="Manifest"+        title="Resumable run record; a .json is written alongside. Leave blank to use the default." style="flex:1 1 200px">+    </div>+    <div class="row" style="margin-top:10px;gap:8px">+      <button class="ghost" style="flex:0 0 auto" onclick="bulkPreview()"+        title="Compute + show the full N-unit sequence; no device touched">Preview (dry-run)</button>+      <button id="bkGo" class="danger" style="flex:0 0 auto" onclick="bulkProgramAll()"+        title="Gated: escalate once, program the connected unit as unit 0, then one unit per Next click">Program All (one-at-a-time)&hellip;</button>+      <button id="bkNext" style="flex:0 0 auto;display:none" onclick="bulkNextUnit()"+        title="Detect the newly-inserted blank adapter and program it as the next unit">Next unit &rarr;</button>+    </div>+    <div id="bulkResult" style="margin-top:12px;overflow-x:auto"></div>+    <div id="bulkProgress" class="mut" style="margin-top:8px"></div>+  </section>+</main>+<div id="toast" aria-live="polite"></div>+<script>+const $=id=>document.getElementById(id);+function toast(msg,kind){const d=document.createElement('div');d.className='t '+(kind||'');+  d.textContent=msg;$('toast').appendChild(d);setTimeout(()=>d.remove(),4600);}+async function api(path,body){const r=await fetch(path,{method:body?'POST':'GET',+  headers:{'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined});+  return {status:r.status,data:await r.json().catch(()=>({}))};}+function render(state){+  const ob=$('overlapBanner');+  if(ob){const ov=state&&state.regs&&state.regs.overlaps;+    if(ov&&ov.length){ob.style.display='block';+      ob.innerHTML='<b style="color:var(--warn)">Overlap warning:</b> '+state.regs.overlap_warning+        +' To change those bytes anyway, Save and use --set-raw in the CLI.';+    }else{ob.style.display='none';ob.innerHTML='';}}+  if(!state||!state.loaded){$('preview').innerHTML='<span class="mut">No image.</span>';+    $('sig').textContent='no image';return;}+  // state indicator: Defaults / Loaded image <name> / Live device read+  const blank = state.loaded && state.signature_ok===false;+  const si=$('srcind');+  if(si){const k=state.source_kind;+    si.textContent = k==='image' ? ('Loaded image '+(state.source_name||'')+(blank?' (blank)':''))+      : k==='device' ? ('Live device read'+(blank?' (blank)':''))+      : 'Defaults';+    si.className='pill '+(blank?'bad':k==='device'?'ok':k==='image'?'':'');}+  const bb=$('blankBanner');+  if(bb){if(blank){bb.style.display='block';+    bb.innerHTML='<b style="color:var(--bad)">EEPROM is BLANK (unprogrammed).</b> '+      +'byte0 is not 0xA5, so the device ignores the EEPROM and runs on OTP / default '+      +'(e.g. MAC 00:80:0F:78:00:00). '+      +'<button onclick="loadDefaultsToProgram()" style="margin-left:8px">Load defaults to program this chip</button>';+    }else{bb.style.display='none';bb.innerHTML='';}}+  const ok=state.signature_ok;+  $('sig').innerHTML='sig '+state.signature+' <span class="pill '+(ok?'ok':'bad')+'">'+    +(ok?'valid':'INVALID')+'</span> '+state.size+'B';+  let h='<div class="kv"><span>MAC</span><b>'+state.mac+'</b></div>';+  (state.descriptors||[]).forEach(d=>{if(d.present)+    h+='<div class="kv"><span>'+d.kind.toUpperCase()+' VID/PID/bcd</span><b>'+      +d.vid+' / '+d.pid+' / '+d.bcd_device+'</b></div>';});+  (state.strings||[]).forEach(s=>{if(s.present)+    h+='<div class="kv"><span>str['+s.name+']</span><b>'+s.value+'</b></div>';});+  if(state.lan7800_identity===false)+    h+='<div class="note">No block advertises 0x0424/0x7800; confirm this is a LAN7800 image.</div>';+  $('preview').innerHTML=h;}+const LED_MODES=["Link/Act","Link1000/Act","Link100/Act","Link10/Act","Link100+1000/Act",+  "Link10+1000/Act","Link10+100/Act","reserved","Duplex/Collision","Collision","Activity",+  "reserved","AutoNeg Fault","Serial Mode","Force Off","Force On"];+let LAST_STATE=null;+const setv=(id,v)=>{const el=$(id);if(el&&document.activeElement!==el)el.value=(v==null?'':v);};+function buildLedGpio(state){+  const lr=$('ledRows');+  if(!lr.dataset.built){+    let h='';for(let i=0;i<4;i++){+      const opts=LED_MODES.map((m,ix)=>'<option value="'+ix+'">'+ix+' '+m+'</option>').join('');+      h+='<div class="row" style="align-items:center;margin:3px 0"><label for="ledMode'+i+'" style="margin:0;flex:0 0 44px">LED'+i+'</label>'+        +'<input type="checkbox" id="ledEn'+i+'" style="width:auto;flex:0 0 auto" aria-label="LED'+i+' enable" title="Enable LED'+i+'">'+        +'<select id="ledMode'+i+'" aria-label="LED'+i+' mode" title="LED'+i+' function (one of 16 modes)">'+opts+'</select></div>';}+    lr.innerHTML=h;lr.dataset.built='1';+    $('gpioPin').innerHTML=[0,1,2,3,4,5,6,7].map(i=>'<option>'+i+'</option>').join('');+    $('gpioPin').addEventListener('change',()=>populateGpio(LAST_STATE));}+}+function populateGpio(state){+  const g=state&&state.regs&&state.regs.gpios;if(!g)return;+  const p=parseInt($('gpioPin').value||'0',10);const pin=g[p];if(!pin)return;+  const s=(id,v)=>{const el=$(id);if(el&&document.activeElement!==el)el.value=v;};+  s('gpioDir',pin.direction);s('gpioDrive',pin.drive==='default'?'':pin.drive);+  if(document.activeElement!==$('gpioOut'))$('gpioOut').checked=!!pin.output_value;+  if(document.activeElement!==$('gpioWake'))$('gpioWake').checked=!!pin.wake_enabled;+  if(document.activeElement!==$('gpioPol'))$('gpioPol').checked=!!pin.wake_active_high;+}+// Populate EVERY editable field from the loaded/read image (hard requirement).+function populateFields(state){+  if(!state||!state.loaded)return;+  setv('mac',state.mac);+  const d0=(state.descriptors||[]).find(d=>d.present)||{};+  setv('vid',d0.vid);setv('pid',d0.pid);setv('bcd',d0.bcd_device);+  const gs=n=>{const s=(state.strings||[]).find(x=>x.name===n);return s&&s.present?s.value:'';};+  ['manufacturer','product','serial','configuration','interface'].forEach(n=>setv(n,gs(n)));+  (state.config_flags||[]).forEach((v,i)=>setv('cf'+i,v));+  buildLedGpio(state);+  (state.regs&&state.regs.leds||[]).forEach((l,i)=>{+    if(document.activeElement!==$('ledEn'+i))$('ledEn'+i).checked=l.enabled;+    setv('ledMode'+i,l.mode);});+  if(state.regs&&state.regs.led_blink)setv('blink',String(state.regs.led_blink.code));+  populateGpio(state);+  LAST_STATE=state;+}+async function scan(){toast('Scanning USB');const {data}=await api('/scan');+  const el=$('scanList');+  if(!data.ok||!data.devices||!data.devices.length){+    el.innerHTML='<div class="note">No LAN7800 (0x0424/0x7800) adapters found.</div>';return;}+  let h='';data.devices.forEach(d=>{+    const badge=d.eeprom==='signed'?'<span class="pill ok">signed</span>':+      d.eeprom==='blank'?'<span class="pill bad">blank</span>':+      '<span class="pill">'+d.eeprom+'</span>';+    const pick=d.iface?'<button class="ghost" style="flex:0 0 auto" onclick="pick(\''+d.iface+'\')" title="Target this adapter">Use</button>':+      '<span class="mut" style="font-size:12px">no netdev bound</span>';+    h+='<div class="kv"><span>usb '+d.usb_path+', '+(d.iface||'(none)')+', MAC '+      +(d.mac||d.usb_serial||'?')+' '+badge+'</span>'+pick+'</div>';});+  el.innerHTML=h;toast(data.devices.length+' adapter(s)','ok');}+function pick(iface){$('iface').value=iface;$('vIface').value=iface;toast('Selected '+iface,'ok');}+async function uploadFile(){const f=$('loadFile').files[0];if(!f)return;+  const buf=await f.arrayBuffer();+  const r=await fetch('/upload',{method:'POST',headers:{'Content-Type':'application/octet-stream',+    'X-Filename':f.name},body:buf});+  const data=await r.json().catch(()=>({}));+  if(data.ok){toast('Loaded '+f.name+' ('+f.size+'B)'+(data.hint?': '+data.hint:''),data.hint?'':'ok');}+  else{toast(data.error||'upload failed','bad');}+  render(data.state);populateFields(data.state);}+async function loadBase(){const {data}=await api('/load',{path:$('loadPath').value});+  data.ok?toast('Base loaded','ok'):toast(data.error,'bad');render(data.state);populateFields(data.state);}+async function readDev(){toast('Reading device');const {data}=await api('/read-device',{iface:$('iface').value});+  data.ok?toast('Read OK','ok'):toast(data.error||'read failed','bad');render(data.state);populateFields(data.state);}+async function readConnected(){toast('Reading connected device');const {data}=await api('/read-connected',{});+  if(data.ok){toast('Read connected device via '+(data.backend||'device'),'ok');}+  else{const errs=(data.errors||[]).join(' | ')||data.error||'read failed';+    toast(errs,'bad');+    if(data.udev_install_commands){toast('Needs a one-time udev rule; see console for the exact commands','bad');+      data.udev_install_commands.forEach(c=>console.log('udev:',c));}}+  render(data.state);populateFields(data.state);}+async function newImg(){const {data}=await api('/new',{});toast('Default template loaded','ok');render(data.state);populateFields(data.state);}+async function loadDefaultsToProgram(){const {data}=await api('/new',{});+  toast('Loaded signed defaults - edit the fields, then Program to write this blank chip','ok');+  render(data.state);populateFields(data.state);}+async function applyEdit(){+  const strings={};['manufacturer','product','serial','configuration','interface']+    .forEach(n=>{const v=$(n).value;if(v!=='')strings[n]=v;});+  const b={mac:$('mac').value,vid:$('vid').value,pid:$('pid').value,+    bcd:$('bcd').value,ensure_signature:true,strings,set_configflag:[]};+  for(let i=0;i<4;i++){const v=$('cf'+i).value;if(v!=='')b.set_configflag.push(i+'='+v);}+  const {data}=await api('/edit',b);+  data.ok?toast('Applied: '+(data.changes||[]).join(', '),'ok'):toast(data.error,'bad');+  render(data.state);LAST_STATE=data.state;}+async function applyLedGpio(){+  const b={set_led:[],led_enable:[],set_gpio:[],gpio_wake:[],ensure_signature:true};+  for(let i=0;i<4;i++){b.set_led.push(i+'='+$('ledMode'+i).value);+    b.led_enable.push(i+'='+($('ledEn'+i).checked?1:0));}+  if($('blink').value!=='')b.led_blink=$('blink').value;+  const p=$('gpioPin').value,dir=$('gpioDir').value,drv=$('gpioDrive').value;+  b.set_gpio.push(p+'='+dir+','+drv+','+($('gpioOut').checked?1:0));+  b.gpio_wake.push(p+'='+($('gpioWake').checked?1:0)+','+($('gpioPol').checked?1:0));+  const {data}=await api('/edit',b);+  data.ok?toast('LED/GPIO applied','ok'):toast(data.error,'bad');render(data.state);LAST_STATE=data.state;}+async function save(){const {data}=await api('/save',{path:$('savePath').value});+  data.ok?toast('Saved '+data.path,'ok'):toast(data.error,'bad');}+async function verify(){toast('Verifying');const {data}=await api('/verify',{iface:$('vIface').value});+  data.ok?toast('Device matches image','ok'):toast((data.error||'mismatch'),'bad');}+async function program(){+  const {data}=await api('/program',{});+  if(!data.ok){toast(data.error||'could not raise escalation','bad');return;}+  toast('Program escalated to CONDUCTOR ('+data.diff_count+' bytes differ vs device). Waiting for PROCEED...','');+  const eid=data.escalation_id; let n=0;+  const iv=setInterval(async()=>{+    n++;const {data:p}=await api('/program-poll',{escalation_id:eid});+    if(p.pending){if(n>150){clearInterval(iv);toast('Approval timed out; click Program to retry','bad');}return;}+    clearInterval(iv);+    if(p.programmed){toast(p.message,'ok');render(p.state);populateFields(p.state);}+    else if(p.denied){toast(p.message,'bad');}+    else{toast(p.message||'program failed','bad');if(p.state)render(p.state);}+  },2000);+}+// populate=true only on load events + first paint; the 5s interval refreshes the+// preview/indicator WITHOUT clobbering fields the user is mid-editing.+async function refresh(populate){const {data}=await api('/state');+  render(data.state);LAST_STATE=data.state;if(populate)populateFields(data.state);}+// ---- Bulk Program mode ----+function bulkBody(){+  const base=$('bkBase').value.trim();+  if(!base){toast('Base MAC required','bad');return null;}+  const count=parseInt($('bkCount').value||'0',10);+  if(!(count>=1)){toast('Count must be >= 1','bad');return null;}+  return {base,count,step:parseInt($('bkStep').value||'1',10),+    scheme:$('bkScheme').value,local_admin:$('bkLocal').checked,+    template:$('bkTemplate').value.trim(),manifest:$('bkManifest').value.trim()};+}+function renderBulkTable(planned){+  if(!planned||!planned.length){$('bulkResult').innerHTML='<span class="mut">Nothing to preview (manifest may already be complete).</span>';return;}+  let h='<table style="border-collapse:collapse;min-width:420px"><thead><tr>'+    +'<th style="text-align:left;padding:3px 10px;border-bottom:1px solid #333">#</th>'+    +'<th style="text-align:left;padding:3px 10px;border-bottom:1px solid #333">MAC</th>'+    +'<th style="text-align:left;padding:3px 10px;border-bottom:1px solid #333">serial</th></tr></thead><tbody>';+  planned.forEach(u=>{h+='<tr><td style="padding:3px 10px">'+u.index+'</td>'+    +'<td style="padding:3px 10px"><b>'+u.mac+'</b></td>'+    +'<td style="padding:3px 10px">'+u.serial+'</td></tr>';});+  $('bulkResult').innerHTML=h+'</tbody></table>';+}+async function bulkPreview(){+  const b=bulkBody(); if(!b)return;+  toast('Computing preview (no device)...','');+  const {data}=await api('/bulk-preview',b);+  if(!data.ok){toast(data.error||'preview failed','bad');$('bulkResult').innerHTML='';return;}+  renderBulkTable(data.planned);+  if(data.template_used)$('bulkProgress').textContent='Template: '+data.template_used;+  toast('Preview: '+data.planned.length+' unit(s); no device touched','ok');+}+// One-at-a-time state machine: Program All burns unit 0 (the connected unit),+// then each Next-unit click detects the freshly-inserted adapter, guards against+// re-burning the same one, programs it, verifies, and prompts for the swap.+let BULK=null;+async function bulkProgramAll(){+  const b=bulkBody(); if(!b)return;+  // Manifest may be blank -> the server uses the default manifests/bulk-run.csv.+  const {data:pv}=await api('/bulk-preview',b);+  if(!pv.ok){toast(pv.error||'preview failed','bad');return;}+  renderBulkTable(pv.planned);+  const total=pv.planned.length;+  if(!total){toast('Nothing to burn (manifest already complete)','');return;}+  if(!confirm('Program '+total+' unit(s) for REAL, ONE AT A TIME?\n'+    +'Unit 0 is the adapter plugged in NOW. After each unit you unplug it, insert the next blank one, and click "Next unit".'))return;+  const {data:esc}=await api('/bulk-program',b);+  if(!esc.ok){toast(esc.error||'escalation failed','bad');return;}+  toast('Escalated; waiting for CONDUCTOR session-scoped PROCEED...','');+  $('bulkProgress').textContent='Waiting for CONDUCTOR approval...';+  const eid=esc.escalation_id; let n=0;+  const approved=await new Promise(res=>{const iv=setInterval(async()=>{n++;+    const {data:p}=await api('/bulk-program-poll',{escalation_id:eid});+    if(p.pending){if(n>150){clearInterval(iv);res(false);}return;}+    clearInterval(iv);res(!!p.allow);},2000);});+  if(!approved){toast('Not approved / timed out','bad');$('bulkProgress').textContent='';return;}+  toast('Approved. Programming unit 0 (the connected adapter)...','ok');+  BULK={b,total,done:0,planned:pv.planned};+  $('bkGo').disabled=true;+  await bulkBurnStep();+}+async function bulkBurnStep(){+  if(!BULK)return;+  $('bkNext').style.display='none';+  const {data:r}=await api('/bulk-burn-one',BULK.b);+  if(r.same_unit){                     // not-swapped guard fired -> let barrett swap+    toast('Looks like the same unit - please swap it','bad');+    $('bulkProgress').innerHTML='<b style="color:var(--warn)">Swap needed:</b> '+      +(r.error||'insert the next blank adapter')+' Then click <b>Next unit</b>.';+    $('bkNext').style.display='inline-block';return;+  }+  const bu=(r.burned&&r.burned[0])||{};+  if(!r.ok||bu.verified===false){+    toast('Unit FAILED: '+(r.error||r.message||'verify failed'),'bad');+    $('bulkProgress').innerHTML='<b style="color:var(--bad)">Stopped:</b> unit failed ('+      +(r.error||'verify failed')+'). Fix, then click <b>Next unit</b> to retry.';+    $('bkNext').style.display='inline-block';return;+  }+  BULK.done++;+  if(r.manifest_used)BULK.manifestUsed=r.manifest_used;+  const done=BULK.done,total=BULK.total;+  toast('Unit '+done+'/'+total+' done: '+bu.mac+' verified','ok');+  if(done>=total){+    $('bulkProgress').innerHTML='<b style="color:var(--ok)">All '+total+' units done.</b> Manifest: '+(BULK.manifestUsed||BULK.b.manifest||'(default)');+    $('bkNext').style.display='none';$('bkGo').disabled=false;BULK=null;return;+  }+  const next=BULK.planned[done];+  $('bulkProgress').innerHTML='<b style="color:var(--ok)">Unit '+done+'/'+total+' done &#10003;</b> (MAC '+bu.mac+'). '+    +'Unplug it, insert the next BLANK adapter, then click <b>Next unit</b>'+    +(next?(' (next: '+next.mac+')'):'')+'.';+  $('bkNext').style.display='inline-block';+}+async function bulkNextUnit(){+  if(!BULK)return;+  $('bkNext').disabled=true;+  $('bulkProgress').textContent='Detecting the connected adapter...';+  try{await bulkBurnStep();}finally{$('bkNext').disabled=false;}+}+// Pre-fill the manifest so barrett never has to type/paste a long path.+async function loadBulkDefaults(){+  try{const {data}=await api('/bulk-defaults');+    if(data&&data.ok){+      if($('bkManifest')&&!$('bkManifest').value)$('bkManifest').value=data.manifest;+      if(data.template&&$('bkTemplate'))$('bkTemplate').placeholder='blank = '+data.template.split('/').pop();+    }}catch(e){}+}+// Pause the 5s refresh while a bulk field is focused, so a re-render never lands+// under the cursor while the operator is typing/pasting.+function bulkFieldFocused(){const a=document.activeElement;+  return !!(a&&['bkBase','bkCount','bkStep','bkScheme','bkTemplate','bkManifest'].includes(a.id));}+loadBulkDefaults();+refresh(true);setInterval(()=>{if(!bulkFieldFocused())refresh(false);},5000);+</script></body></html>"""+++def main():+    port = int(os.environ.get("PORT", "8747"))+    # Pre-populate the session with the CLI's default LAN7800 template so the+    # UI shows sensible defaults on first load (source_kind == "defaults").+    run_cli("new", "--out", WORK_BIN)+    SOURCE["kind"], SOURCE["name"] = "defaults", None+    srv = ThreadingHTTPServer(("127.0.0.1", port), Handler)+    log(f"LAN7800 webapp on http://127.0.0.1:{port} (work dir {WORK_DIR})")+    print(f"LAN7800 EEPROM Programmer webapp: http://127.0.0.1:{port}")+    try:+        srv.serve_forever()+    except KeyboardInterrupt:+        pass+++if __name__ == "__main__":+    main()