# Remote WebFS content updates — design and implementation plan

Status: MVP-first plan, reviewed against source and build evidence on 2026-09-12. This is a small home device. Use the attached hardware directly, keep a
private USB backup, and get one basic remote content update working first. Broader
qualification and convenience features must not block that experiment.

The priority checklist below controls implementation order. Detailed sections later
in this document describe the fuller design; optional details are not MVP gates.
Keep the existing single-bank layout, OS/firmware preservation and remote-recovery
requirements. No new double-image design is needed.

## Remote WebFS update quickstart

Yes. The blog content can be replaced remotely over the trusted LAN after the
update-capable firmware has been installed once by USB. Remote updates never rewrite
the ESP application firmware, bootloader, partition table, Wi-Fi credentials or host
OS. TCP port 8081 is a binary maintenance connection; do not forward it through the
router or Caddy.

Prepare a deterministic image from a safe tar.gz, then check its size and contents:

```sh
python3.12 scripts/webfs-prepare.py blog.tar.gz -o artifacts/blog.wfs
```

Check the device before uploading:

```sh
python3.12 scripts/webfs-upload.py status --device 192.168.3.225
```

Upload the complete image. The client validates it with `mkwebfs --check`, sends
sector 0 last, waits for read-back and full WebFS validation, and prints the committed
generation, digest and duration:

```sh
python3.12 scripts/webfs-upload.py upload artifacts/blog.wfs \
  --device 192.168.3.225 --mkwebfs "$PWD/artifacts/mkwebfs"
```

If the connection drops, run `retry` with the same image; it performs a complete
transfer with a new transaction/generation. To restore a retained previous image,
run `restore` with that `.wfs` file. Query STATUS afterward and fetch the site to
verify the change:

```sh
python3.12 scripts/webfs-upload.py retry artifacts/blog.wfs --device 192.168.3.225
python3.12 scripts/webfs-upload.py restore artifacts/previous.wfs --device 192.168.3.225
curl --noproxy '*' --compressed http://192.168.3.225/
```

The first upload after firmware-only USB migration uses `RECOVER_BEGIN` automatically
because the device has no committed update journal. A normal serving device uses
`BEGIN`. A missing or interrupted transaction leaves the device in recovery; it does
not expose a partial image. The current workflow uses full-image retries; HASH_RANGE,
automatic reconnect and Caddy snapshot switching are deferred.

### If `/` returns 404 after a successful upload

The packer preserves paths exactly. The root URL `/` maps to `index.html` at the
image root. If the image contains `blog/index.html`, request `/blog/` or
`/blog/index.html`; `/` will correctly return 404. Inspect an image before upload:

```sh
strings blog.wfs | rg 'index\.html'
curl --noproxy '*' --compressed http://192.168.3.225/blog/
python3.12 scripts/webfs-upload.py status --device 192.168.3.225
```

For the site to appear at `/`, pack the directory whose contents include
`index.html` directly (or remove the extra top-level archive directory before
running `webfs-prepare.py`). A successful upload STATUS only confirms commit and
validation; always fetch the expected URL afterward.

## Progress — verified device backup

The first hardware preparation item passed on 2026-09-11. esptool identified
ESP32-C3 QFN32 revision 0.4, 4 MiB XMC flash, MAC `90:70:69:ad:77:f4` on
`/dev/cuaU1`. A full 4,194,304-byte read-back backup passed `verify-flash` against
all flash bytes. It is retained privately with mode 600 at
`/home/wongk/esp32c3-webfs/artifacts/pre-update-mvp-20260911.bin` and is excluded
from Fossil because it contains Wi-Fi credentials.

Backup SHA-256:
`c8ea8c9a5a8b875dcfa1da66aab8df573b57784ec07d70982839631b36f46caf`.
After reset, all 92 blog assets matched the source image, write methods returned
405, removed endpoints returned 404, and HEAD returned 200 without a body.
Evidence: `docs/update-evidence/backup-20260911/` in the source repository.
Recovery listener firmware is now flashed and verified; the content-writing protocol
was absent from that verified device firmware. A new upload implementation now
builds (see the 2026-09-12 progress below) but has not been installed on the device.
The exploratory simulator's basic host test passes; it does not prove updater correctness.

## Progress — recovery networking and listener

The recovery-networking item passed on real hardware on 2026-09-11. Firmware
`update-recovery-v1` starts Wi-Fi, DHCP, diagnostics and a bounded port-8081
listener before mounting WebFS. With a valid image, the normal eight HTTP workers
also start. With the first 4 KiB of the WebFS partition erased, HTTP port 80 refused
connections and port 8081 still returned `WFSU\\x01 RECOVERY`; this proves recovery
networking does not depend on a mountable blog. The exact 2,228,224-byte content
partition was restored from the private verified backup and esptool read-back
verification passed. All 92 blog assets then matched again.

This listener is deliberately a fixed recovery probe, not the upload protocol. The
new source adds bounded STATUS/BEGIN/PUT_SECTOR/VERIFY_COMMIT framing and flash
ownership, but the corresponding device and network-exposure checks remain open. Evidence: `docs/update-evidence/recovery-listener-20260911/`.

## Progress — build and host-test verification (2026-09-12)

- [x] Repair exploratory update-crate compilation and remove unused imports.
  Updated `crates/webfs-update/src/update_engine.rs`, `journal.rs` and
  `protocol.rs`: use the imported journal types, borrow the existing journal,
  and finalize a cloned SHA-256 hasher with an explicit digest type.
- [x] Fix the basic flash-simulator host test stack overflow.
  `crates/webfs-update/src/lib.rs` runs the inline 2.2 MiB simulator on a
  dedicated 32 MiB test-thread stack to accommodate debug-build moves.
- [x] Add build-command failure reporting and compact Cargo output.
  `scripts/build-freebsd.sh` reports the failed command, working directory and
  exit status, and uses RTK for Cargo tests/builds. Packer and benchmark binaries
  run directly after building; benchmark stdout remains unfiltered CSV.
  Failure reporting was observed for `rtk cargo test --workspace --locked`
  with exit status 101, including a simulator crash omitted from RTK’s summary.
- [x] Run the complete FreeBSD jail build successfully after these fixes.
  Command: `doas bastille cmd esp32c3 sh /project/scripts/build-freebsd.sh`.
  Result: 26 host tests passed (12 suites), packer and benchmark completed,
  and firmware ELF plus merged image were generated. Five existing firmware
  dead-code warnings remain. `sh -n scripts/build-freebsd.sh` also passed.

This verification built artifacts only; no device was flashed. LAN upload,
journal durability, interruption recovery and hardware qualification checklist
items below remain open. The basic simulator test verifies construction and
capacity only, not the complete update mechanism.

## Progress — LAN updater implementation (2026-09-12)

The next implementation is built but **not yet flashed or hardware-qualified**.
Evidence: [host verification](docs/update-evidence/lan-implementation-20260912/host-verification.md).
Wire format and commands: [LAN protocol v1](docs/webfs-update-wire.md).

- [x] Implement bounded command framing and CRC validation in `firmware/src/wire.rs`
  and connect STATUS, BEGIN/RECOVER_BEGIN, PUT_SECTOR and VERIFY_COMMIT in `update.rs`.
  One maintenance socket uses one 4 KiB staging buffer and bounded receive/write deadlines.
- [x] Implement canonical journal records in `journal.rs` and append/read-back ordering
  in `fs.rs`. A separate validity page binds the body SHA-256; the latest record's
  physical sector is preserved while replacing its peer. Host tests cover record
  corruption and torn prefixes; physical rollover/interruption tests remain open.
- [x] Add content-only sector bounds, page read-back, exact image SHA-256 and full
  format validation. Boot now requires valid COMMITTED metadata and a matching image;
  missing/UPDATING metadata stays in recovery. This path still needs device testing.
- [x] Implement HTTP read leases in `app.rs`/`connection.rs`, a 35-second drain ceiling,
  and publication of new mounted metadata after COMMITTED. Runtime behavior is unverified.
- [x] Reserve the two metadata sectors in the packer CLI and USB provisioning bounds:
  payload maximum `0x21e000` (2,220,032 bytes). Add a CLI regression test and document
  the first RECOVER_BEGIN upload required after USB provisioning.
- [x] Add a firmware-only USB migration mode to `scripts/flash-freebsd.sh` that
  preserves content/metadata, refuses busy serial ports and verifies the private
  4 MiB backup before writing. Four command-order/failure tests pass using fake
  device tools; real USB migration remains part of the unchecked hardware item.
- [x] Add safe tar.gz preparation in `scripts/webfs-prepare.py`: reject traversal,
  symlink/hardlink and special members, enforce 64 MiB/100,000-file limits, pack
  and revalidate the image in a private staging directory. Ten Python tests pass,
  including changed-tar-mtime deterministic output and hostile archive members.
  Usage: `python3.12 scripts/webfs-prepare.py site.tar.gz -o site.wfs`.
- [x] Verify the updated build: 30 Rust tests passed; complete jail firmware/packer/
  benchmark build succeeded without firmware warnings. Eight Python tests now pass (four client and four USB-script tests).
  Exact commands, artifact identity and test limitations are in the evidence above.

The private backup hash was rechecked and matches the recorded value. The device upload evidence is recorded below. Router forwarding/DMZ isolation still
requires a router-side check; the host firewall cannot prove it. Power-loss and
mid-transfer recovery remain untested.

## Progress — real-device LAN update (2026-09-12)

The update-capable firmware was installed correctly at the app image offset after
backing up and verifying the full 4 MiB flash. The firmware artifact SHA-256 was
`b649fa2625707150cc666776581987996e8352dc12eabeca49704ffc0db20eda`; the backup
SHA-256 is `06412205116a5f1468b1578406ddbbdc5e593e67b350fed37da503179c3d2731`.
The board remained the expected ESP32-C3 QFN32 revision 0.4, MAC
`90:70:69:ad:77:f4`, on `/dev/cuaU1`.

- STATUS after firmware-only migration returned `state=recovery`, no journal, and
  zero content fields.
- `RECOVER_BEGIN` uploaded a changed 808-byte image in one sector. STATUS returned
  `generation=1`, `sequence=2`, `length=808`, and SHA-256
  `9fcb592d7bf31d366f030c7e982d58f953dabba09839fc62b9df1089e1cc0e4e`.
  HTTP served `Hello from LAN WebFS Update`.
- A second upload restored the prior 623,656-byte image in 153 sectors, with header
  sector zero sent last. It completed in 9.737 seconds and committed
  `generation=2`, `sequence=4`, SHA-256
  `97749f365ac3e2e9d22a20f74903183ed968fbc5223a43f17a1d570222a0ce0b`.
- `scripts/verify-readonly.py artifacts/blog.wfs --host 192.168.3.225` confirmed
  all 92 assets byte-for-byte, rejected POST/PUT/DELETE/PATCH with 405, found removed
  endpoints 404, and confirmed HEAD 200 with no body.
- Four malformed maintenance connections (bad magic, oversized header, bad request
  order and unknown opcode) were closed with zero response bytes. STATUS afterward
  still reported the committed image.

This proves the normal upload, recovery initialization, journal commit, remount and
malformed-frame behavior on hardware. It does not prove router Internet isolation,
mid-transfer reset/power-loss recovery, or measured flash-stall limits.

## Priority checklist — start here

### Existing work — reuse only what helps the device

- [x] Existing blog packer, read-only server and FreeBSD build/USB workflow are available
  in `/home/wongk/esp32c3-webfs`.
- [x] Exploratory update source exists in `crates/webfs-update/`. It is not an MVP
  dependency and must not delay direct device work. Reuse a piece only after it is
  understandable, tested on the ESP32-C3 and committed with that test evidence.

The previous checklist reported early journal/engine work. It is preserved in
[the original checklist](docs/webfs-update-original-checklist.md), but it is not proof
that a simulator, protocol suite or host-only engine is complete. The direct ESP
implementation is now authoritative. `webfs-work/crates/webfs-update` uses two
storage slots and is reference material only; do not copy that layout.

### 1. First working LAN upload — immediate milestone

Goal: send an existing `.wfs` from the host to the real ESP, validate it, and serve
the changed blog. Do this before archive automation, delta upload or Caddy automation.

- [x] Keep a private known-good firmware/content backup and identify the USB device.
  Build and flash directly after content-only bounds checks are implemented.
- [x] Start Wi-Fi and management even if WebFS is absent or corrupt. Keep Wi-Fi
  credentials and recovery code in firmware, outside the writable content.
- [x] Implement one maintenance connection on LAN port 8081 without authentication
  for the MVP, with bounded framing and one 4 KiB staging buffer. Minimum commands:
  STATUS, BEGIN/RECOVER_BEGIN, PUT_SECTOR and VERIFY_COMMIT. Record the wire format
  alongside the implementation. Device STATUS, recovery, upload and malformed-frame
  tests passed on hardware. Confirm the port is not exposed to the Internet via the
  router before production use; that router-side check remains open.
- [x] Integrate the smallest working journal/flash engine: durable UPDATING before
  payload erase, checked content-only sector writes, read-back verification, full
  image validation and durable COMMITTED before serving. Reuse the two metadata
  sectors; do not require a general-purpose filesystem or new format.
- [x] Stop/drain public content reads while writing and remount cleanly afterward.
  Device uploads drained and remounted successfully; serial logs report per-sector
  write/verify timing. A broader flash-stall campaign remains open.
- [x] Add a simple host command accepting a validated `.wfs` and device address. Upload
  the full image sequentially, write its header sector last, verify and report status.
  Manual rerunning the whole transfer is sufficient initially; HASH_RANGE is later.
  Implemented in `scripts/webfs-upload.py` with upload/status/retry/restore commands;
  four host tests pass, including fragmented replies and header-last ordering. The
  existing 623,656-byte blog validates; the real-device upload is the next item.
- [x] Flash update-capable firmware once, upload a visibly changed blog over Wi-Fi,
  fetch its files and compare bytes/hashes. Recorded above: changed image then
  153-sector restore, 9.737 seconds, all 92 assets exact.
- [x] Confirm blog upload never calls esptool or rewrites firmware/partition table,
  and reject malformed commands, oversized images and out-of-range sector writes.
  The LAN client contains no esptool path; device malformed-frame cases closed safely
  and host/Rust bounds tests pass. Router isolation remains a separate open check.

**Milestone 1 done:** a real content-only LAN update works. It is a development
checkpoint, not a claim that interruption recovery has already been tested.
Manual Caddy snapshot selection is sufficient if preserving public availability;
for a direct-LAN experiment a temporary serving outage is expected.

### 2. Minimum dependable home updater — MVP acceptance

Goal: archive in, updated blog out, with remote retry after interruption. These
requirements remain essential even for this home device.

- [x] Wrap the existing packer: accept tar.gz, extract only regular files/directories
  under a private staging root, reject escaping paths/links and enforce size limits,
  then validate/build `.wfs`. `scripts/webfs-prepare.py` implements this with
  traversal/link/type/size checks; host tests cover hostile members and changed
  tar mtimes producing identical packed bytes. Keep the input and prior image on
  the host; no release-database framework.
- [ ] On partial upload, invalid header or missing journal, boot into LAN
  network recovery. Retrying the **whole image** is acceptable; no USB repair needed.
- [ ] Test on this hardware: kill the uploader halfway and retry; reset during an
  upload and retry; physically cut power during writing, restore power and retry.
  Observe Wi-Fi/DHCP and STATUS, then verify the completed blog. Record physical
  power-cut testing separately from reset testing; no 20-cut campaign required here.
- [x] Test corrupt/missing metadata with a disposable image and recover remotely.
  Firmware-only migration left no journal; Wi-Fi and recovery STATUS remained
  available and RECOVER_BEGIN initialized the first committed image remotely. A
  deliberately corrupt (rather than missing) journal remains untested.
- [x] Upload a second real blog and restore the previous host image as a new update.
  Compare all served files, and confirm the firmware identity is unchanged. The
  changed image and prior 92-asset image were uploaded as generations 1 and 2; the
  device MAC/partition identity remained unchanged.
- [ ] Confirm router forwarding/DMZ rules do not expose TCP 8081 to the Internet.
  This requires the router configuration; no host-side command can establish it.
- [x] Provide short commands for prepare, upload, status, retry and restore, plus the
  one-time USB migration. Commands are documented in `docs/webfs-update-wire.md` and
  implemented by `scripts/webfs-prepare.py`, `scripts/webfs-upload.py` and
  `scripts/flash-freebsd.sh --firmware-only`; the source is committed without secrets.

**MVP done:** tar.gz can update the blog over the LAN; interrupted content writes
leave a remotely recoverable ESP; no OS/firmware rewrite or second content bank.
Keep management LAN-only. Manual Caddy fallback remains enough for this milestone;
do not claim continuous public availability unless that fallback was actually set.

### 3. Make occasional updates convenient

- [ ] Add a simple Caddy snapshot/proxy switch using the retained public tree. Check
  fallback before upload, verify the ESP before switching back, and leave fallback
  active on failure. Preserve unrelated sites. Automate the manual procedure first.
- [ ] Add STATUS-driven reconnect and automatic retry. Persist only the target identity
  and minimal host state needed to continue after the tool exits.
- [ ] Add HASH_RANGE and skip matching sectors; demonstrate zero writes for identical
  content and fewer transfers after an interrupted update. Full transfer stays valid.
- [ ] Add a small per-device lock and current/previous release retention. Do not build
  a multi-user service, dashboard or scheduler for 0–3 updates per week.
- [ ] Test Caddy-facing requests during an update and verify the management port is
  not Internet-reachable. Check Caddy's upstream connection count against ESP limits.

### 4. Confidence and optimization — after the updater is useful

- [ ] Use real-device failures as regression cases. A simulator may be added later for
  focused journal or framing bugs, but it is not required work for this homelab device.
- [ ] Expand hardware cuts across commit/recovery/rollover, including a cut during
  recovery itself. The former 20-cut campaign is optional follow-up, not an MVP gate.
- [ ] Add near-capacity, all-pages-changed and malformed-archive edge cases; improve
  error messages and recovery based on the results.
- [ ] Measure RAM/stack margin, flash wear, update duration and browser latency. Fix
  observed resource problems; the previous 20% headroom and 120% p95 targets belong
  to later qualification, not the first hardware upload.
- [ ] Run the 24-minute mixed soak when basic update/recovery works. It is optional
  confidence testing for this MVP; it does not become a prerequisite retroactively.
- [ ] Add fully crash-safe Caddy orchestration, durable release management and asset
  compatibility routing only if the simple host workflow proves insufficient.

### Working rules for the implementing agent

Use the attached ESP32-C3 as the test target. Do not spend time repairing, expanding
or requiring a simulator before a real LAN update works. Keep one flash owner,
bounds checking and recovery boot behavior from the beginning.
USB is allowed for development firmware and rescue; it does not count as successful
remote recovery of an interrupted blog update.

After each completed checklist item, record files changed, the exact command tested
and its result here, check the item off, and commit the tested source to Fossil
without secrets. Avoid implementing later layers merely because the detailed design
mentions them. Recovery startup and the fixed maintenance probe are verified. The
new framing, writer and reader-drain implementation passes the host build. The next
task is router-isolation confirmation, firmware installation and a full-image LAN
upload with device evidence, followed by interruption/recovery checks.

## Detailed design reference — apply according to milestone

The sections below retain the chosen storage and recovery design. Delta transfer,
rich CLI subcommands, comprehensive archive checks, durable orchestration and broad
qualification are layered according to the checklist above. A small upload script
is a valid first CLI. Manual full retry is a valid first recovery workflow.

## Decision

Use **host-staged, resumable, single-bank content replacement**. A FreeBSD host
accepts a `tar.gz`, safely expands it, builds a deterministic WebFS image, switches
Caddy to a retained static snapshot, and updates the ESP over a LAN-only maintenance connection. After read-back validation, Caddy switches back
to the ESP. The ESP application firmware is never remotely rewritten.

This deliberately puts archive handling, compression, durable backups and public
availability on the host. The ESP does bounded sector writes and integrity checks.
There is one blog image on the ESP, plus 8 KiB of recovery metadata. There is no
second firmware image, second full blog bank, general writable filesystem, on-device
tar/gzip extraction, or background garbage collector.

**Availability contract:** the public blog remains available through Caddy while
the ESP is in maintenance or recovering. Direct ESP HTTP service is temporarily
unavailable during writes; it returns bounded 503 responses when able. We do not
promise uninterrupted service directly from the ESP while erasing its executing
flash. Caddy serves the old snapshot until the new ESP image is fully validated.

This is an explicit architectural tradeoff. Arbitrary replacement of a nearly full
single bank cannot preserve all old and new bytes simultaneously. Without spare
storage, rollback must come from somewhere else. Here that durable source is the
host. If uninterrupted ESP-origin service itself becomes mandatory, revisit the
storage budget or add hardware; do not silently introduce a second image bank.

## Required invariants — OS preservation and remote recovery

Clarification (2026-09-11): **a routine blog update must not rewrite either the
FreeBSD host OS or the ESP application firmware/runtime**. The host changes only
staged content, update state and the scoped Caddy route configuration. It does not
reinstall or upgrade the OS, packages, jail or toolchain. The ESP changes only the
WebFS payload and its two metadata sectors. Firmware, bootloader, partition table,
Wi-Fi credentials remain intact. No update authentication key is required for the MVP.

Installing update-capable firmware once by USB is a separate migration. After that,
`apply`, `resume` and `restore` must never invoke esptool, write a merged firmware
image, erase the chip or change firmware versions. A future firmware upgrade is an
explicit, separate operation, never an automatic dependency of a blog package.

**Power-loss acceptance criterion:** after power returns, an ESP interrupted at any
content-update step must boot its unchanged firmware, reconnect to configured
Wi-Fi, obtain DHCP configuration, and accept remote retry or resume.
It must do this without a valid WebFS header, mountable filesystem, complete target
image, valid journal record, USB connection, BOOT-button press or serial reader.
This is a functioning *recovery appliance*; it need not serve the old blog from its
partially overwritten content bank. Caddy continues to serve the retained snapshot.

This guarantee assumes power is restored, the Wi-Fi network and management host
are reachable, and the flash hardware remains operational. Lost network access or
physical flash failure is distinct from an interrupted WebFS transaction. Ordinary
update power loss must not be classified as a reason to require USB rescue.

### Recovery is part of the permanent firmware

The Wi-Fi configuration, management protocol, journal scanner, image validator
and flash writer live in the application partition. None is loaded from WebFS.
Recovery does not need a second firmware slot: it is a small startup state of the
same application used for normal serving.

Start Wi-Fi and management independently of mounting or validating content. A bad
header, digest, record or bounded-read error enters recovery, rather than panicking,
reboot-looping, waiting forever for content, or disabling networking. Perform any
long image validation incrementally so the management task remains responsive.
STATUS reports `validating`, `serving`, `updating` or `recovery`, with a bounded error
code, transaction identity if trustworthy, and progress. It does not expose secrets.

If journal metadata is missing or entirely invalid, STATUS reports unknown content
and generation. A LAN `RECOVER_BEGIN` command may establish a fresh UPDATING record
and target identity without mounting or trusting previous content. It requires an
explicit host recovery action and verifies a durable new record before payload
writes. The host chooses a generation from its retained history; the device must
not claim it recovered a lost monotonic counter. Generation and transaction checks
prevent accidental stale commands; the MVP does not provide cryptographic replay
protection. Never infer that old content is safe to serve.

For a valid UPDATING journal, ordinary resume compares sectors against the retained
target. For unknown metadata, the host can upload any authorized complete retained
release, comparing sectors only as an optimization. Both paths finish with full
image validation and a durable COMMITTED record. Losing metadata therefore loses
progress information, not the ability to repair content remotely.

## Hardware and existing-code constraints

| Fact verified from this project | Design implication |
|---|---|
| ESP32-C3, 4 MiB flash; no external RAM used | Stream small blocks; never buffer an archive/image in RAM |
| One application at `0x10000`, size `0x1d0000` | Remote content protocol cannot address firmware, bootloader, NVS or PHY data |
| WebFS region `0x1e0000..0x400000`, size `0x220000` | Reserve recovery metadata within this region; no partition-table expansion |
| Eight TCP workers, 2 KiB RX + 4 KiB TX each; 96 KiB heap | Account for an additional maintenance socket and buffers before deployment |
| Current WebFS v2 is a packed immutable index/names/data image | Keep v2 initially; add a transaction envelope outside it |
| New firmware writer bounds payload writes to `0x21e000`, verifies pages and journals commits | Verify physical writes, rollover and reader draining on the ESP before claiming runtime correctness |
| Recovery Wi-Fi and the fixed port-8081 probe survived an invalid image on 2026-09-11 | Preserve this boot order when adding the upload protocol; missing-journal recovery is still unverified |
| Previously verified device blog: 623,656 bytes, 92 files (not the factory build artifact) | Full transfer is small; correctness is more valuable than a complex delta filesystem |
| Updates only 0–3/week | Avoid continuous polling writes and frequent metadata checkpoints |

The CPU executes from the same SPI flash being programmed. Flash operations can
restrict cache access and interrupt execution. ESP-IDF documents these constraints
and optional auto-suspend, but this project uses **esp-storage 0.9.0 and esp-hal**;
an IDF configuration option does not establish safety for this Rust driver.
Inspect the actual driver, ROM calls, critical sections and linked RAM functions,
then measure erase/program behavior on this board before designing timeouts around
it. Use sector-sized operations, never a whole-bank erase in one blocking call.
[Espressif flash concurrency documentation](https://docs.espressif.com/projects/esp-idf/en/v5.1.5/esp32c3/api-reference/peripherals/spi_flash/spi_flash_concurrency.html).

### Source map to revisit during implementation

- `firmware/src/main.rs`: startup, DHCP, task/resource allocation.
- `firmware/src/connection.rs`: socket ownership, admission, deadlines and draining.
- `firmware/src/fs.rs`: bounds-checked read adapter; keep ordinary HTTP read-only.
- `firmware/src/diag.rs`: bounded progress/error reporting.
- `firmware/partitions.csv`: physical boundary authority.
- `crates/webfs-format/src/lib.rs`: v2 validation, lookup, checksums and lengths.
- `crates/mkwebfs`: deterministic host packing and validation.
- `scripts/flash-freebsd.sh`: USB migration, backup and recovery.

## Host workflow and archive conversion

Proposed CLI (does not exist yet):

```sh
webfs-update prepare blog.tar.gz --device keybox-blog --output /var/db/webfs/releases
webfs-update plan --device keybox-blog --release <release-sha256>
webfs-update apply --device keybox-blog --release <release-sha256>
webfs-update status --device keybox-blog
webfs-update resume --device keybox-blog
webfs-update restore --device keybox-blog --release <previous-release-sha256>
```

Run it locally on the management host, or remotely through its existing SSH access.
Do not add a public upload service in the first version. Caddy is the public blog
front end, not the package uploader. Secrets belong in a mode-600 host config and
an ignored, embedded ESP configuration; never command-line arguments or logs.

The fuller prepare workflow below has no device side effects. For milestone 2,
start with safe extraction, packing/validation and retained image files; rich
manifests, link checking and durable release publication can follow:


1. Create a private staging directory. Limit compressed input (initially 32 MiB),
   total expanded bytes (64 MiB), regular files (2,048) and normalized path length
   (255 UTF-8 bytes); independently enforce actual WebFS image capacity. Make
   limits explicit CLI/config values with hard ceilings, not unbounded overrides.
2. Stream-parse the tar. Accept regular files and directories only; reject symlinks,
   hardlinks, devices, FIFOs, sparse files, absolute paths, `..`, backslashes,
   control characters, duplicate normalized names and file/directory collisions.
   Validate effective PAX/GNU names too. Never call unrestricted `extractall`.
   Do not follow existing filesystem links. Select a top-level archive directory
   only through an explicit `--strip-prefix`; never guess it away.
3. Keep only the static public tree. Require `index.html`. Do not execute archive
   content. Report local broken asset links; do not fetch external URLs. Treat HTML
   and JavaScript as publisher-authorized public content, not executable host code.
4. Pack with stable path ordering, fixed alignment, pinned compression settings,
   gzip timestamp zero and no original filename. Ignore source mtime, ownership,
   archive order and permission changes when determining content identity.
5. Validate the image independently; emit SHA-256, logical length, format version,
   per-sector SHA-256 values, per-file stored/decoded hashes and a release manifest.
   Keep both the image and an expanded public tree for Caddy fallback.
6. Durably save the release, manifest and checksums using file fsync, directory
   fsync and atomic rename. Retain current and previous releases plus an unfinished
   transaction. Refuse apply until the current fallback snapshot is verified.

### Rebuilt pages, compression and delta transfer

Do not use filesystem timestamps to infer changed pages. Repacking identical
bytes must produce the same image even when the generator rewrites every file.
If template dates or navigation actually change every page, those pages really
are different and must be updated.

Compare SHA-256 of **4 KiB target sectors**, not file modification times. In milestone 3, equal
sectors are skipped, including after interrupted transfers. The MVP may resend all
sectors and restart the same target safely. A packed v2 index or
length change can shift many later sectors: this optimization is not a promise of
small deltas. Worst case is a complete image transfer and rewrite. Budget and test
that case; for the present roughly 609 KiB blog it is acceptable.

Do not start with binary patches, content-addressed objects or a log-structured
copy-on-write format. Those add dependency ordering, fragmentation and garbage
collection recovery. A future stable-extent format can improve erase counts if
measurements justify it; it must not be a prerequisite for reliable updates.

## ESP flash layout and transaction metadata

Keep the external `webfs` partition unchanged. Subdivide its contents:

| Relative offset | Absolute offset | Size | Purpose |
|---|---|---|---|
| `0x000000` | `0x1e0000` | `0x21e000` (2,220,032 bytes; 542 sectors) | Single WebFS v2 image area |
| `0x21e000` | `0x3fe000` | `0x1000` | Metadata journal A |
| `0x21f000` | `0x3ff000` | `0x1000` | Metadata journal B |

Added permanent flash overhead is 8 KiB, about 0.37% of the former blog region.
No scratch image is needed: the host retains every desired sector and retries a
torn write. A target sector may be destroyed only after durable UPDATING metadata
exists. A torn sector is never exposed as an active blog.

Keep WebFS v2 payload semantics and checksums, but enforce the reduced capacity in
all packers, validators and USB scripts. SHA-256 of the complete logical image is
the transaction identity; existing CRCs detect format corruption but are not
authentication. Pad the final transfer sector with `0xff`; its sector hash covers
all 4,096 bytes, while the image hash covers the exact declared logical length.
Old bytes beyond the logical image are unreachable and need not be erased. Validate
all index/data ranges against logical length, not just partition capacity.

### Journal rules — implement the minimum, extend fault tests later

Use fixed 1,024-byte append-only records: three 256-byte pages of canonical record
body (unused bytes fixed), followed by one separately programmed validity page.
There are four slots per sector. Confirm these alignment assumptions against the
actual flash driver. Never assume a page program or a 32-bit marker is atomic.

Record body: magic, schema, device identifier, monotonic 64-bit record number,
transaction ID, state (UPDATING or COMMITTED), current/base generation, target
generation, target length, target SHA-256, format version, body CRC and SHA-256.
Validity page: fixed marker plus a digest binding it to the complete body. Write
and read-back verify the body before programming validity; then verify both.
Reject torn, unknown-version or noncanonical records. Sequence wrap is an error.

At least one latest valid record must survive journal rollover. Copy it with a
higher record number into an erased peer sector, verify, and only then erase the
old sector. Never erase the only valid record. Validate this ordering on the real
device with the focused interruption checks in milestone 2. A simulator is an
optional later regression aid. Journal slots are consumed for BEGIN, COMMIT and
rollover, **not for every payload sector**.

Boot selects the highest valid record. UPDATING means recovery-only serving even
if an old header happens to parse. COMMITTED requires complete image SHA-256 and
format validation before serving. Failure enters recovery; never fall back to a
historical COMMITTED record whose payload may already have been overwritten.
No valid journal also means remote recovery through RECOVER_BEGIN;
it must not disable networking or require USB. USB remains a last-resort option for
firmware/credential damage or failed hardware outside the content-update boundary.

## Firmware state machine and flash ownership

```mermaid
stateDiagram-v2
    [*] --> Validate
    Validate --> Serving: committed image validates
    Validate --> Recovery: updating / invalid / missing metadata
    Serving --> Draining: LAN BEGIN; Caddy fallback ready
    Draining --> Updating: workers drained; UPDATING record durable
    Updating --> Verifying: all desired sectors match
    Verifying --> Serving: full hash and format pass; COMMITTED durable
    Verifying --> Recovery: validation failure
    Updating --> Recovery: disconnect / restart / timeout
    Recovery --> Updating: LAN resume or replacement transaction
```

- Wi-Fi and a bounded maintenance listener start even when blog mounting fails.
  Wi-Fi secrets stay in firmware; content writes cannot touch them.
- One task owns flash operations. Its capability allows payload-sector writes and
  validated journal operations only. Network requests never carry arbitrary flash
  addresses. Arithmetic is checked before conversion and before every operation.
- Before BEGIN is made durable, stop accepting new normal blog work, wait for
  existing responses to finish under a 35-second drain ceiling, and cancel/close
  any remaining tasks through their existing bounded cleanup. Prove no retained
  `Volume`, flash borrow or response metadata can outlive entry to update mode.
- The writer never erases concurrently with a public flash read. During maintenance,
  port 80 can return a fixed RAM-backed 503, or be temporarily unreachable during
  a flash stall. Public requests are already handled by Caddy's snapshot.
- Only one maintenance command and one 4 KiB payload buffer can be active. Validate
  framing, transaction, sector bounds and block integrity before erasing its destination. Erase one sector,
  program in driver-supported page units, verify full sector, then acknowledge.
- Write sector zero (the v2 header) last as defense in depth. The journal, not the
  header, determines whether an image may be served.
- Full verification streams image SHA-256 and runs all v2 structural checks. Persist
  COMMITTED before remounting. Replace in-memory volume/metadata only after workers
  are quiescent. No automatic restart is required to publish content.
- Disconnects leave recovery state and never resume serving a partial image. The
  host may resume the same transaction or start an replacement with
  a higher generation; remote restore uploads an old release as a new generation.
  There is no local rollback button or automatic timeout rollback.

## Management transport — unauthenticated LAN MVP

User decision: the MVP works without application authentication or authorization.
Use a separate binary TCP listener on port 8081, reachable on the trusted LAN and
not exposed to the Internet. Caddy never proxies this port. No PSK provisioning,
MAC, challenge exchange, certificates or key-file argument is required for the MVP.
Any client able to reach this port can replace blog content; LAN isolation is the
access boundary for this version. Content hashes detect corruption, not identity.

Keep the wire protocol small and versioned:

- Fixed header with magic, version, opcode, transaction ID and bounded payload
  length; define integer widths and byte order alongside the implementation.
  Reject unsupported versions, malformed lengths and out-of-state commands.
- STATUS; BEGIN(base/new generation, target length and SHA-256); PUT_SECTOR(index,
  4,096 bytes); VERIFY_COMMIT; RECOVER_BEGIN for unknown metadata. HASH_RANGE is a
  later optimization. Version 1 has no MAC field or authentication handshake.
- One active client, one 4 KiB staging buffer and sequential commands. Validate the
  entire frame and target bounds before flash mutation; verify programmed bytes
  before acknowledging. Read-back and final SHA-256/format validation remain required.
- Repeated BEGIN for the same target is idempotent. On a lost reply, query STATUS
  and retry the complete image if necessary. Transaction/generation checks catch
  stale retries but do not authenticate clients or prevent deliberate replay.
- Start with a 5-second frame reception and 10-second idle timeout, and a 15-second
  host command timeout; adjust from measured hardware behavior. Verification may
  report progress through STATUS. A dropped connection leaves a retryable durable
  transaction, never a partially served image.
- Budget bounded socket buffers, staging and hash state. Check these fit before
  flashing and inspect runtime memory during the first real upload.

Before using the MVP, check router/firewall rules have no Internet path to 8081,
including IPv6 if later enabled. Restrict it to the management host where convenient;
a trusted-LAN restriction is sufficient for this homelab MVP. If using an HTTP
management route later, block it on the public Caddy listener and keep it LAN-only.

### Optional later authentication

If the trust boundary changes, add a versioned authenticated protocol using a
per-device PSK and HMAC-SHA-256, fresh session challenges and replay checks. Require
that mode explicitly rather than silently downgrading to unauthenticated operation.
This is future work, not a checklist prerequisite for basic updates or recovery.

## Caddy and public availability

Normal mode proxies the blog to ESP TCP 80. Maintenance mode serves a **verified,
immutable host copy of the currently published release** using Caddy `file_server`.
There is no dependence on a warm HTTP cache: all assets are present on disk before
maintenance starts. Never use an opportunistic upstream-error retry as the only
fallback; it may occur after response bytes have already been sent.

Caddy supports static file roots and precompressed sidecars; construct the fallback
from validated release contents and verify decoded bodies, MIME types, missing paths
and HEAD behavior. Do not enable directory browsing. Reject unsupported methods;
map directory indexes consistently with WebFS. Use an explicit route for the blog,
not a global rewrite affecting other sites.
[Caddy file server documentation](https://caddyserver.com/docs/caddyfile/directives/file_server).

Host orchestration, with one durable per-device lock:

1. Save transaction intent and both release identities durably. Confirm previous
   snapshot is complete and public-domain probes work.
2. Validate a Caddy configuration selecting that immutable snapshot, then gracefully
   reload. Persist the same choice for Caddy/host restart. Probe actual public routes
   and verify fallback identity with a local control probe/log before sending BEGIN.
3. Drain old proxied requests before allowing ESP erasure. The ESP drain barrier is
   authoritative; a successful Caddy reload alone does not mean old requests ended.
4. Upload/resume, commit and verify the ESP directly from the host: active digest,
   every asset, absent paths, HEAD and conditional requests. Keep Caddy in snapshot
   mode through all failures. Retain old content throughout this process.
5. Reload Caddy back to proxying only after verification; test actual public pages.
   If this fails, restore the old snapshot route. Persist the new published release
   only after public checks pass. Host crashes at any step reconcile from durable
   intent, actual Caddy config and ESP status, never an assumed state.

Use a single validated reload per transition and serialize configuration changes
with the operator's existing Caddy workflow. Do not overwrite unrelated sites.
Caddy's configuration API guarantees apply per request, not to this entire
multi-system transaction. [Caddy API documentation](https://caddyserver.com/docs/api).

Caddy reloads do not create an atomic snapshot across a visitor's multiple requests.
Use content-hashed asset URLs where possible and test old HTML loading its assets
after cutover. If the generator uses mutable asset paths, retain old-only assets
in the host compatibility route for the cache lifetime; document the limits of
same-path changed assets. No claim of whole-browser-session atomicity is made.

Network policy: Internet traffic reaches Caddy only; no router forward to ESP ports
80 or 8081. Permit TCP 80 to the ESP from Caddy and required LAN diagnostics, and
8081 from the trusted LAN (preferably only the management host). The ESP's per-IP quota sees the Caddy address,
so configure/test its upstream connection reuse and parallelism against the four
connections-per-IP cap. Do not trust X-Forwarded-For to bypass ESP admission.

If management is later exposed through Caddy, deny it on the public listener and
use a distinct LAN listener with explicit source ranges; authentication is optional
for the MVP. Test
spoofed forwarded headers. Caddy client-IP matching depends on trusted-proxy
configuration. [Caddy request matchers](https://caddyserver.com/docs/caddyfile/matchers).

## Failure and recovery contract

| Failure | Device behavior | Public behavior / operator recovery |
|---|---|---|
| Unsafe archive / oversize image / malformed command | No flash mutation | Previous blog remains served |
| Power loss before durable BEGIN | Previously committed image remains intact | Reconcile and retry |
| Power loss during any payload erase/program | Boot recovery networking; never mount partial blog | Caddy serves snapshot; resume sector comparison |
| Disconnect or lost ACK | Durable target unchanged; sector may already be complete | Idempotent query/retry |
| Full-image hash or structural failure | Stay in recovery; no COMMIT | Repair/resume or upload previous host image |
| Torn journal append / rollover | Select highest valid record, or enter network recovery if none is valid | Resume or LAN RECOVER_BEGIN; no USB required |
| Power loss after durable COMMIT | Verify and serve committed target after boot | Host discovers commit; verifies and switches Caddy |
| Host/tool crash | Device remains serving or recoverable according to journal | Persisted snapshot route remains; restart tool and reconcile |
| Target release deleted from host | No autonomous rollback possible mid-update | Restore retained backup or USB image; prevent retention deletion while active |
| Wi-Fi unavailable | Retry connection; retain journal | Caddy continues serving snapshot |
| Bad new blog content despite valid hashes | New image is technically valid | Restore previous host release as a new generation |

A host/Caddy outage is outside the availability guarantee: it is already the public
entry point. Use normal host backup/service management. Never acknowledge a release
as durable if it exists only in a temporary upload directory.

## Deferred features

No firmware OTA, public archive ingestion service, scheduler, dynamic content,
web UI, certificate management on the ESP, generic flash read/write API or automatic
rollback to nonexistent local old content. Stable extents, content-addressed chunk
storage and additional compression are future measured optimizations, not hidden
requirements for this first dependable update path.
