Skip to content

wled_apjoin: put WLED devices in AP mode onto the network - #32

Merged
aphelps-claude-bot merged 21 commits into
mainfrom
wled-ap-autojoin
Aug 22, 2026
Merged

aphelps-claude-bot merged 21 commits into
mainfrom
wled-ap-autojoin

Conversation

@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator

Finds WLED devices sitting in AP-fallback mode, joins each, pushes your network's credentials, and restores this machine's network on every path. Implements the approved plan; all four decisions are recorded there.

$ scripts/wled_apjoin.py --ssid MyNet --password ... --dry-run
Scanning the current LAN first (devices already here are left alone)…
  1 WLED device(s) already on this LAN

2 candidate AP(s):
  Trancender            rssi=-63  ch=11  open 2.4GHz AP — may be a renamed device
  Basement speaker.o,   rssi=-61  ch=6   open 2.4GHz AP — may be a renamed device

Discovery unions three sources

Each misses what the others catch:

Source Catches Why the others miss it
targeted probe for WLED-AP the default case a broadcast sweep was observed missing an AP that was plainly there — this is the only reliable route
sweep hits matching WLED-* WLED_AP_SSID_UNIQUE builds the WLED-<mac-suffix> SSID can't be probed for in advance
open 2.4 GHz APs renamed devices they're indistinguishable from strangers by name alone

Open APs are restricted to 2.4 GHz. An ESP32 has no 5 GHz radio, so a 5 GHz open network cannot be a WLED device — that one check excludes most public hotspots for free (xfinitywifi is on channel 44 here).

Credentials never go through /settings/wifi

That handler reads every field unconditionally and ESPAsyncWebServer returns "" for a missing one, so a credentials-only POST would also empty apSSID (destroying AP-fallback recovery, since WLED_SET_AP_SSID() runs at wled.cpp:475 before config load at :484), force apBehavior=0, clamp TX power, and disable ESP-NOW while clearing linked_remotes. POST /json/cfg preserves absent keys by construction (cfg.cpp:41, CJSON(a,b) a = b | a).

The push is gated on identity: brand == "WLED" and an Espressif OUI on info.mac. Open-AP probing means associating to networks that aren't ours, and the thing being transmitted is your network's plaintext PSK across a link whose passphrase is published in WLED's own source — or absent entirely.

Already-joined devices

Skipped only if on the current LAN; a device on a different network is re-pointed onto this one. That makes the pre-run LAN scan a correctness input, not just verification — an incomplete scan means working devices get needlessly rewritten.

Safety

A hop takes this machine off its own network, so:

  • restore runs in a finally that ignores further signals, so a second Ctrl-C can't abandon it half-done
  • the rejoin is verified and retried once — not assumed from a zero exit status
  • a detached watchdog (start_new_session=True) force-restores even if this process is SIGKILLed; a plain background child dies with a terminal SIGINT
  • every AP is forgotten after use — macOS stores the passphrase and adds the SSID to the preferred list, which the OS then auto-joins later. WLED-AP was already in this machine's preferred list from earlier manual hops.

Tests

21 host tests against a fake platform, wired in as make test-apjoin. The three safety properties are mutation-verified — removing the identity gate, the forget() cleanup, or the 5 GHz exclusion each turns tests red.

⚠️ Not yet run live. WLED-AP isn't currently broadcasting, so there's nothing to provision; the device needs to be back in AP mode. Adam and I will test together. Everything here is dry-run and host-test only.

🤖 Generated with Claude Code

Scans for candidate APs, joins each, identifies it, pushes credentials if it
needs them, and restores this machine's network on every path.

Discovery unions three sources because each misses what the others catch: a
targeted probe for WLED-AP (a broadcast sweep was observed missing an AP that
was plainly there), sweep hits matching WLED-* (catches WLED_AP_SSID_UNIQUE
builds whose SSID suffix cannot be known in advance), and open 2.4GHz APs, which
is the only way to find RENAMED devices — they are indistinguishable from
strangers by name.

Open APs are restricted to 2.4GHz. An ESP32 has no 5GHz radio, so a 5GHz open
network cannot be a WLED device, and that single check keeps the tool away from
most public hotspots — xfinitywifi is on channel 44 here.

Credentials go via POST /json/cfg, never the /settings/wifi form: that handler
reads every field unconditionally and missing ones arrive as "", so a
credentials-only POST also empties apSSID (destroying AP-fallback recovery),
forces apBehavior=0, clamps TX power and disables ESP-NOW while clearing
linked_remotes.

The push is gated on identity — brand == WLED AND an Espressif OUI on info.mac —
because the target network's plaintext PSK crosses a link whose passphrase is
published in WLED's own source, or absent entirely. Open-AP probing means
associating to networks that are not ours; nothing is ever sent to one.

Devices already on the CURRENT LAN are skipped; a device on a different network
is re-pointed onto this one. That makes the pre-run LAN scan a correctness input,
not just verification.

Safety, since a hop takes this machine off its own network: restore runs in a
finally that ignores further signals so a second Ctrl-C cannot abandon it
half-done, it verifies the rejoin and retries once, and a detached watchdog
(start_new_session, so it survives SIGINT to the process group and SIGKILL of
this process) force-restores regardless. Every AP is forgotten after use —
macOS stores the passphrase and adds the SSID to the preferred list, which the
OS then auto-joins later.

Scanning uses a small Swift CoreWLAN helper: airport is gone on macOS 26 and
system_profiler redacts SSIDs. It reports withheld-SSID explicitly rather than
returning an empty list, which would be indistinguishable from "no devices".

21 host tests against a fake platform, wired in as make test-apjoin. The three
safety properties are mutation-verified: removing the identity gate, the forget()
cleanup, or the 5GHz exclusion each turns tests red.

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the working tree on wled-ap-autojoin (0c0f066). Empirical checks run: make test-apjoin (21 pass), swift scripts/wled_scan_ap.swift (read-only, 22 SSIDs), --dry-run end-to-end, and two mutation probes against assertions I doubted. No radio state was changed.

The pure-logic layer is in good shape and the identity gate is genuinely tight. The problems are all in the part the plan itself flagged as the dangerous part: the restore path and the watchdog. Two of the four defects the plan listed against wled-ap-hop.sh are still present here, and the watchdog has a new one of its own.

Structural findings (the line-anchored ones are inline):

  • A single pass keyed by SSID cannot handle two WLED-AP devices. seen = {n["ssid"]: n for n in nets} dedupes by name and main() walks candidates exactly once — there is no "loop until no candidate APs remain" (plan, Subtasks). Two stock devices both broadcasting WLED-AP collapse to one entry and only one is ever configured, which is the "Testing Required" scenario the plan calls out explicitly. Knock-on: decide_action's give-up branch is unreachable in production — attempts is per-run and each candidate is visited at most once, so attempts.get(mac,0) >= max_attempts can only be true in the unit test. Either add the outer loop or drop --max-attempts rather than shipping a cap that never engages.

  • Band classification is not sound, and the Swift helper's error payload is discarded. Three separate things: (a) "band": ch <= 14 ? 2 : 5 misreads 6 GHz — CoreWLAN numbers 6 GHz channels 1–233, so an open 6 GHz AP on channel 5 is reported as 2.4 GHz and becomes a candidate; wlanChannel?.channelBand is the correct source. (b) wlanChannel nil yields ch = -1 → also classified 2.4 GHz. (c) is_candidate tests net.get("band") == 5 rather than == 2, so a scan dict with the key absent falls through to "candidate" — I confirmed is_candidate({"ssid":"X","open":True}, DEFAULT_PATTERNS, True) returns (True, 'open 2.4GHz AP …'). Fail closed instead. Separately, emit() exits 1 for ok:false but MacPlatform.scan() checks out.returncode != 0 first, so the {"ok":false,"error":…} JSON on stdout is never parsed and "no Wi-Fi interface" surfaces as scan failed: no output.

  • No Location Services preflight — the plan required one ("Preflight the authorisation and fail loudly rather than returning an empty list"). ssids_withheld only fires when nets.count > 0 && out.isEmpty; if the unauthorised path returns an empty array rather than SSID-less entries, the tool prints "No candidate APs found." and exits 0 — exactly the silent wrong answer the plan set out to prevent. CLLocationManager.authorizationStatus would make this deterministic rather than inferred.

  • Two smaller plan deviations. --password is required=True with no env-var or file alternative, so the target PSK lands in ps and shell history on every run (the plan asked for all three mechanisms, calling a flag "the worst place for a secret"). And --yes's help says "do not confirm each device" while the implementation asks one bulk [y/N] for the whole list — with open-AP probing on by default, that single prompt is all that stands between a run and associating to every open 2.4 GHz AP in range.

  • Suggested test: the restore path has no coverage at all. FakePlatform implements only join/forget; watchdog, wait_online, is_connected and the entire finally block in main() are untested — and that is precisely the code the plan says makes this tool survivable. The plan's Test Plan asked for "a fake platform that simulates a join failing, hanging, and succeeding — assert the host network is restored in all three"; none of that exists. Add a fake covering the full platform surface and assert, for join-succeeds / join-fails / join-hangs (TimeoutExpired) / body-raises / KeyboardInterrupt: the home join is attempted, the watchdog is not terminated when the restore could not be confirmed, and the exit status is non-zero.

  • Suggested test: pin the report-row contract that verification depends on. want = {r[2].split(" ")[0] for r in pushed} re-parses the MAC out of the human-readable f"{mac} — rebooting" detail string. Nothing stops that string being reformatted, and doing so would silently turn every device into never-appeared. Better: carry the MAC as its own tuple field and delete the re-parse; failing that, assert the format.

  • Suggested post-merge check: run make test on merged main and confirm == wled_apjoin host tests == actually appears in the output — see the Makefile comment; today it does not, because test-apjoin is not a prerequisite of test:.

Comment thread scripts/wled_apjoin.py Resolved
Comment thread scripts/wled_apjoin.py Resolved
Comment thread scripts/wled_apjoin.py Resolved
Comment thread scripts/wled_apjoin.py Resolved
Comment thread scripts/wled_apjoin.py Resolved
Comment thread Makefile Resolved
…CI never ran

Six defects, two of which could strand the machine off its network.

The watchdog built a /bin/sh -c string with subprocess.list2cmdline — the WINDOWS
quoting rule. An SSID or password containing a space, quote, backtick or $ was
corrupted or executed: `pa$$word` became the shell's PID, `a;id` ran id, and a
single quote killed the watchdog at launch with unexpected-EOF while the handle
still looked alive — i.e. the recovery path was silently absent exactly when
someone's password contained an apostrophe. It also put the network PSK in a
ps-visible argv for the whole timeout. Replaced with a detached python child that
execs an argv list and takes the password on stdin.

dog.terminate() ran before checking whether the restore had worked, so in the one
scenario the watchdog exists for, the code disarmed it and then printed "the
watchdog may still recover it" — false, and it had just removed the only
remaining recovery path. Now only disarmed once we are demonstrably back.

is_connected() accepted any IPv4 address, but a WLED SoftAP hands out 4.3.2.x —
so "still on the device's AP" read as "back on home Wi-Fi", the watchdog was
disarmed and the run exited 0 on a stranded host. Excludes the SoftAP subnet and
link-local now. This was defect #1 from the plan's own critique of
wled-ap-hop.sh, faithfully reproduced.

The host's own networks were candidates. A real run would join the home network,
find no WLED device, and then FORGET it — removing it from the preferred list on
the way past. Verified: naming the target network as --ssid now drops it.

forget() was skipped when the join failed, though a failed join can still have
added the SSID to the preferred list. The guarding test never asserted
plat.forgotten, so it passed against code doing the opposite of its name — the
third such test in this repo, so the pattern is mine.

The band check tested `!= 5`, which fails OPEN for an unknown band; now requires
2.4 positively. The Swift helper also inferred band from channel number, which
misreads 6GHz (channels 1-233) — it now uses CoreWLAN's own channelBand.

Finally: test-apjoin was never wired into `test:`. My earlier edit searched for a
string containing test-sync, which only exists on another branch, so .replace()
silently matched nothing and I reported "make test green" for a suite that never
ran. The edit now asserts before substituting.
@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Review — cross-session, read-only

Reviewed at 5a53e74. I ran the test suite and mutation-tested it, checked the make/CI wiring by breaking it, typechecked the Swift helper, and read the WLED-side handlers at the current submodule pin. I did not join any AP or change this machine's network.

Bottom line: the shape is right and the safety reasoning is genuine — restore-in-finally with signals ignored, a verified rather than assumed rejoin, the detached watchdog, forgetting the AP, the identity gate, and choosing /json/cfg over /settings/wifi are all correct instincts. The test file is real, not decorative — I broke seven separate guards and the suite went red on every one. The problems are concentrated in the one area with no test coverage at all: the platform layer and main(). Six findings below are verified, one is a "this will bite on hardware" prediction.


1. The home PSK reaches an error message and the printed report — verified

subprocess.TimeoutExpired.__str__ embeds the full argv. MacPlatform.join catches subprocess.SubprocessError (of which TimeoutExpired is a subclass) and returns str(e). Demonstrated:

>>> plat.join("HomeNet", "hunter2-my-real-wifi-password", 30)   # networksetup hangs
(False, "Command '['networksetup', '-setairportnetwork', 'en0', 'HomeNet',
         'hunter2-my-real-wifi-password']' timed out after 30 seconds")

That string goes two places, both user-visible:

  • provision_one → report.append((ssid, "join-failed", err)) → printed in the results table
  • main's finally → print(f"WARNING: could not confirm rejoin to {home_ssid} ({err …})")

--connect-timeout defaults to 30s and networksetup can absolutely sit that long on a marginal AP, so this is not exotic. Fix: never put str(e) from a subprocess exception into a user-facing string — f"timed out after {timeout}s" / type(e).__name__ carries the same information.

2. argv exposure on the two paths that carry the real PSK — verified by reading

The watchdog goes to real lengths here (stdin, no shell, argv list) and its docstring explicitly names ps-visible argv as a defect it fixed. But:

  • MacPlatform.join passes the passphrase as networksetup argv, so the home PSK is in ps for the duration of the restore join — up to --connect-timeout, twice with the retry. The watchdog's own child does the same at the moment it fires; the stdin trick only covers the sleep window (which the docstring is honest about).
  • More easily fixed: the tool's own --password / --home-password sit on wled_apjoin.py's argv for the entire run and land in shell history. The module docstring's usage examples show --password secret literally.

networksetup has no stdin form so (a) is hard to avoid; worth a comment saying so, since the watchdog docstring currently implies argv exposure was eliminated. (b) is easy — a prompt, WLED_PSK env, or --password-stdin as the documented default.

3. plat.join() sits outside the try, so the forget() guarantee has a hole — verified

wled_apjoin.py:315-316:

ok, err = plat.join(ssid, None if net.get("open") else args.ap_password, args.connect_timeout)
try:
    ...
finally:
    plat.forget(ssid)

The comment two lines down reasons carefully about forgetting after a failed join — but an interrupt or exception during the join skips forget() entirely, and the join is the one call that takes tens of seconds, i.e. the likeliest moment for a Ctrl-C. macOS will have already stored the passphrase and added the SSID to the preferred list by then. Demonstrated with a fake platform that raises KeyboardInterrupt from join: forgotten == [].

test_forgets_even_when_join_fails can't see this because FakePlatform.join returns normally rather than raising. Moving the join inside the try fixes it.

4. "not" in msg.lower() misses the most likely failure string — verified against the binary

$ strings /usr/sbin/networksetup | grep -iE 'join|could not find'
Failed to join network %s.
Could not find network %s.
You cannot join a network when Wi-Fi power is off.

Could not find network X. and You cannot join… both contain "not". Failed to join network X. does not — no "not" substring anywhere in it. That is the string you get on a wrong passphrase or a failed association, i.e. the common failure, and the code reports it as success. The run then GETs 4.3.2.1/json/info while still on the home network, gets nothing, and records not-wled — silently masking a bad --ap-password as "that AP wasn't a WLED device". Match the known strings explicitly, or confirm with networksetup -getairportnetwork after the call.

5. The watchdog is a one-shot absolute deadline, and firing it destroys the safety net — verified by reading

It's armed once before the loop with --safety-timeout (180s default) and sleeps that long from arming, not from the last hop. A two-candidate run plausibly exceeds it: per device up to 30s join + 5s GET + 10s POST + /reset, then the restore itself is up to 2×(30+45)s. When it fires mid-run it does two bad things:

  1. yanks the machine onto the home network while provision_one is mid-hop, so the remaining HTTP fails and subsequent joins fight it;
  2. exits — so from that point there is no watchdog at all, and dog.terminate() at the end is a silent no-op on a dead child. The "even if SIGKILLed" guarantee expires without any signal that it has.

Re-arming per candidate (kill + respawn), or turning the child into a loop that re-checks a heartbeat file the parent touches, would make the claim hold for the whole run.

6. /json/cfg does not preserve everything the PR body says — verified in WLED at this pin

The body's central argument is "POST /json/cfg preserves absent keys by construction (CJSON(a,b) a = b | a)". That's true for scalars reached through CJSON, but three things in the path this POST touches are assigned unconditionally:

  • cfg.cpp:64-66 — linked_remotes.clear(); runs before nw["linked_remote"] is even read, and unconditionally. Our body omits linked_remote, so /json/cfg clears linked_remotes too — the exact harm the PR body cites as a reason to avoid /settings/wifi. (enableESPNow is CJSON-preserved, so it's strictly better than the form, but the claim as stated is wrong.) In this repo, with the esp-now-router work, that's a live concern.
  • cfg.cpp:107-109 — multiWiFi[n].staticIP/GW/SN are assigned from locals that default to 0.0.0.0 / 0.0.0.0 / 255.255.255.0, not CJSON-merged. Pushing {ssid, psk} wipes a static IP configured on entry 0.
  • Under WLED_ENABLE_WPA_ENTERPRISE, enterpriseAnonIdentity / enterpriseIdentity are unconditionally strlcpy'd from "" → cleared.

Suggest GET /json/cfg, merge, POST back the whole nw object — or at minimum document the three fields it clobbers so the comparison table is accurate.

Things I checked on the WLED side that are correct, for the record: pin is the right auth key (wled_server.cpp:426, 401 at :441), /reset exists as a GET (:396), nw.ins[].ssid/psk is the right shape, and the immediate /reset is safe — wled.cpp:232 writes the config before the reboot check at :255, and deserializeConfig returns doc["sv"] | true so configNeedsWrite is set. No race there.

7. No settle time between association and the HTTP GET — prediction, not verified

provision_one fires get_json(DEVICE_IP, "/json/info", timeout=5) the instant networksetup returns, once, with no retry. On real hardware, DHCP from the SoftAP plus WLED's server coming ready after a client associates will sometimes exceed that — and the failure mode is a real device reported not-wled, forgotten, and skipped. There's a wait_online poll on the restore side but nothing analogous here. Poll /json/info for ~15-20s instead. This is the one I'd most expect to show up in the first live run.


Guards and tests — checked by breaking them, not by inference

make genuinely runs the new file. test: … test-apjoin; make test-apjoin runs 23 tests; CI runs make test STRICT=1 (.github/workflows/ci.yml:91). I renamed tests/test_wled_apjoin.py away and confirmed both halves of the guard: lenient → -- skipped: no tests/test_wled_apjoin.py --, exit 0; STRICT=1 → ERROR: … (STRICT=1 …), exit 1. Correctly wired.

Mutation-verified. All three properties the PR claims, plus four more. Each mutation applied to a scratch copy, suite rerun:

mutation result
drop the is_espressif gate in identify 2 failures
drop plat.forget(ssid) from the finally 4 failures
drop the band != 2 check 2 failures
drop the own-network exclude check 1 failure
drop the brand != "WLED" check 1 failure
drop the max-attempts cap 1 failure
drop the already-on-LAN skip 3 failures

Two tested branches are unreachable from main():

  • provision_one's if args.dry_run (line 332) can never execute — main returns at line 407, before the loop. So test_dry_run_pushes_nothing covers dead code and the real --dry-run path has no test. (The real path is fine — I read it: it returns before any join and before the watchdog is armed, so --dry-run is genuinely side-effect-free w.r.t. network config. It does still run an active LAN sweep and a Wi-Fi scan, which is worth one line in --help.)
  • decide_action's give-up branch is likewise dead: main makes a single pass over candidates with attempts starting empty, so --max-attempts is effectively a no-op flag today.

The entire platform layer and main() are untested. Every provision_one test runs against FakePlatform; MacPlatform.join/is_connected/forget/watchdog, the restore finally, the signal-ignoring, the watchdog arm/disarm, and the verification loop have zero coverage. Findings 1, 3, 4 and 5 all live there — none are visible to the suite. Given "restores on every path" is the headline claim, one test driving main() against a fake platform (assert restore ran after an exception; after KeyboardInterrupt; when a device never answers; assert the watchdog is not disarmed when back is false) would be worth more than several of the remaining pure-logic tests. (Also: 23 tests, not 21.)

Restoration, path by path

path restored?
clean success yes — verified rejoin, retried once, watchdog disarmed only on confirmed success
exception mid-loop yes (the finally runs) — but the exception then propagates and the report is never printed
Ctrl-C during a hop, inside the try yes
Ctrl-C during plat.join itself restore yes; forget() no — finding 3
Ctrl-C during the restore yes — SIGINT/SIGTERM SIG_IGN'd first. Good.
device never responds yes — join → None → not-wled → forget → restore
half-succeeded push (POST ok, /reset lost) machine restored; device reported pushed then never-appeared, exit 1. Correct.
SIGTERM mid-loop no in-process restore — Python does not run finally on a default-handled SIGTERM. Watchdog only, up to --safety-timeout later.
SIGHUP (terminal closed) same as SIGTERM.
SIGKILL watchdog only — and see finding 5 for the window where the watchdog has already fired and exited

So "every path" is close to true. The exceptions are the SIGTERM/SIGHUP window (arguably by design — that's what the watchdog is for, but it isn't what "every path" says), the forget hole, and finding 5 quietly removing the last net. Installing SIG_IGN-adjacent handlers for SIGTERM/SIGHUP at the top of the provisioning block that raise instead of terminating would close the first one cheaply.

wled_scan_ap.swift

Running it interpreted with no build artifact is the right call — nothing to keep in sync, and swiftc -typecheck is clean here. Neither failure mode is silent: a missing swift raises OSError → scan failed: … → main prints and returns 2; a compile error gives non-zero exit with stderr. The withheld-SSID detection is good — that's the one failure that would otherwise look identical to "no devices found".

One real diagnostics bug: emit() writes its error JSON to stdout and exits 1. MacPlatform.scan tests out.returncode != 0 before parsing JSON and reports out.stderr.strip() or 'no output' — stderr is empty in that case, so every structured Swift error (no Wi-Fi interface, any scanForNetworks throw) collapses to scan failed: no output. The carefully-written message is discarded exactly when it's needed. Parse stdout first and prefer d["error"].

Minor: Swift always uses CWWiFiClient.shared().interface() and ignores --iface, which the Python side threads through to networksetup. Harmless on a single-radio Mac; it diverges the moment the porting note's "second radio" idea is tried.

Smaller notes

  • Open-AP probing is on by default. The tool will associate to any open 2.4 GHz AP in range. The brand == "WLED" + Espressif-OUI gate is a good anti-accident guard but not an anti-adversary one — anything can serve {"brand":"WLED","mac":"244cab…"} at 4.3.2.1, and what follows is the user's plaintext PSK. Consider making --probe-open opt-in, or at minimum confirming the open-AP candidates individually (they're the only ones where "this might not be mine" is true).
  • --yes help says "do not confirm each device", but the confirmation is a single batch prompt. For a safety prompt that distinction matters.
  • lan_device_macs() returning {} — e.g. local_subnets() finds nothing — silently means "no device is on this LAN", so everything gets re-pointed. That's the failure the code's own comment warns about; a hard warning (or abort) when the pre-scan finds zero subnets would match the stated intent.
  • main() indexes n["ssid"], n['rssi'], n['channel'] unguarded. Fine given the Swift helper always emits them, but the rest of that boundary is defensive.
  • import urllib.error is unused; the watchdog child is never wait()ed (zombie until exit). Both cosmetic.

Nothing here is a reason to throw the design out — #1, #3, #4 and #6 are small, local fixes, and #5 is the one worth reworking before a live run.

@aphelps aphelps left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs a good readme for what to do and how to run the commands

Review feedback on #32: the tool shipped with no user-facing docs.

scripts/README.md covers what wled_apjoin does and how to run it: the
prerequisites that are easy to get wrong (macOS-only, a 2.4GHz target
network, the Location Services grant without which scanning always looks
empty), the dry-run-first workflow, a full flag table, what each RESULT
column value means, and how to recover by hand if a run leaves the machine
off its network. Known limitations are stated rather than left to be
discovered: two devices sharing an SSID are adopted one run at a time, and
this is deliberately not something an ESP32 should run.

Also states plainly that --password lands in `ps` and shell history, since
that is still true and a reader should know before typing it.

Two small doc fixes alongside it: `make test-apjoin` was missing from the
Makefile's own usage header, and --yes's help said "do not confirm each
device" while the implementation asks one prompt for the whole list.

No behaviour change; 23 host tests still pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Added scripts/README.md (3b0b4f8).

It covers the run itself — dry-run first, then the real thing, with a full flag table — but the parts I expect to actually save time are the ones that are easy to get wrong and give no useful error:

  • Location Services. Without the grant, macOS withholds SSIDs and scanning looks like "no devices in range". The README says to verify with the read-only swift scripts/wled_scan_ap.swift before anything else, and how to tell that failure apart from a genuinely empty area.
  • A 5 GHz target network produces devices that accept the credentials and never connect — never-appeared in the output table, which now has a row explaining exactly that.
  • It disconnects the machine it runs on, so not over SSH/VPN. Stated up front rather than as a footnote.
  • Recovery by hand, in case the watchdog is not what you want to wait on: the two networksetup lines that put you back and drop a leftover WLED-AP from the preferred list.

Every RESULT value in the output table has a row saying what it means and, where there is one, the usual cause.

Known limitations are written down rather than left to be discovered — notably that two devices both broadcasting WLED-AP are deduplicated to one and adopted a run at a time, and that this is deliberately not something to port to an ESP32 (single radio, it would drag its own SoftAP onto the device's channel and drop the backbone every hop).

I also left the --password caveat in plainly: it is still argv-only, so it is visible in ps and lands in history. That is a real gap rather than a documented feature — say the word and I will add --password-env / --password-file in a follow-up.

Two small fixes came along with it: make test-apjoin was missing from the Makefile's own usage header, and --yes claimed "do not confirm each device" while the implementation asks a single prompt for the whole list. No behaviour change; 23 host tests still pass.

Adopting two real devices onto a real network broke this in four distinct
ways, none of which the host tests could have caught. Each fix ships with a
regression test, and each of those tests was mutation-checked by reverting
the fix and confirming it fails.

1. The Espressif OUI table was a guess, not the assignment. It held 34
   prefixes collected from devices we happened to have seen. Both live
   devices are 2c:bc:bb, which was not among them, so a genuine WLED device
   was refused with "MAC is not Espressif" — the identity gate failing
   closed on real hardware, which is the same as not working. Replaced with
   all 331 prefixes IEEE has assigned to Espressif.

2. HTTP was attempted before DHCP. networksetup returns once the
   association is up, not once there is a lease, so the probe of 4.3.2.1
   fired with no route and the device was reported `not-wled  no /json/info
   response`. The same two devices gave opposite answers on consecutive
   runs, purely on timing. Now waits for an address first, and a missing
   lease is reported as join-failed rather than as a verdict on the device.

3. A single pass cannot adopt a flapping AP. A device in AP-fallback drops
   its SoftAP every time it retries its own connection, so the AP seen
   during the scan is routinely gone a second later — "Could not find
   network". Added --adopt-deadline: keep re-scanning and retrying, with
   device verdicts final and radio failures retryable, so a device is never
   re-pushed and never abandoned for being mid-retry. The deadline also
   covers the opening scan, since finding nothing at t=0 is the normal
   starting state. --safety-timeout is raised to match, out loud, so the
   watchdog cannot fire mid-adoption.

4. The device was rebooted before its config was saved. POST /json/cfg
   applies values and defers the flash write to a later main-loop pass, so
   an immediate /reset can discard the credentials. Of the two devices in
   the first successful run, one came back up still broadcasting its AP.
   Now reads the config back before rebooting, and checks `pskl` as well as
   the SSID — WLED returns the passphrase length, never the passphrase, and
   an SSID that saved without its PSK yields a device that looks configured
   and can never authenticate. Absent pskl means "cannot disprove".

Result: WLED-TOUCH-BOX (2cbcbbd98960) adopted onto the target network and
confirmed at 192.168.1.39. WLED-TOUCH-MATRIX still declines to associate
after a confirmed push; that looks device-side and is still being chased.

30 host tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Live-tested against two real devices on Adam's network. It found four defects that the host tests could not have — fixed in 78e6ed9, each with a regression test that was mutation-checked by reverting the fix and confirming the test fails.

Result: WLED-TOUCH-BOX (2cbcbbd98960) adopted onto the target network and confirmed at 192.168.1.39.

1. The OUI table was a guess, not the assignment. 34 prefixes collected from devices we happened to have seen. Both live devices are 2c:bc:bb, not among them — so the identity gate refused a genuine WLED device with "MAC is not Espressif". An allowlist that fails closed is the right shape only if it is actually complete; an incomplete one just means the tool does not work and blames the device. Now all 331 prefixes IEEE has assigned to Espressif.

2. HTTP fired before DHCP. networksetup returns on association, not on lease, so the probe of 4.3.2.1 went out with no route and the device came back not-wled no /json/info response — a real device misreported as a stranger. The same two devices gave opposite answers on consecutive runs, purely on timing. Now waits for an address, and a missing lease reports as join-failed rather than as a verdict on the device.

3. A single pass cannot adopt a flapping AP. This is the one your review and mine both flagged as missing, and the live run is what made it concrete: a device in AP-fallback drops its SoftAP every time it retries its own connection, so the AP present during the scan is routinely gone a second later. Added --adopt-deadline, which keeps re-scanning; device verdicts are final, radio failures are retryable, so nothing is re-pushed and nothing is abandoned for being mid-retry. The deadline covers the opening scan too, because finding nothing at t=0 is the normal starting state.

4. The device was rebooted before its config was saved. POST /json/cfg applies the values and defers the flash write to a later main-loop pass, so an immediate /reset can discard them — one of the two devices came back up still broadcasting its AP after a reported success. Now reads the config back before rebooting, and checks pskl as well as the SSID: WLED returns the passphrase length, never the passphrase, and an SSID that saved without its PSK produces a device that looks configured and can never authenticate. Absent pskl means "cannot disprove", so older builds are not failed.

Still open, and it looks device-side rather than tool-side: WLED-TOUCH-MATRIX (2cbcbbdaca60) takes the push — SSID and passphrase length confirmed read back before the reboot — and then never associates, falling back to its AP each cycle. Worth noting the adopted device reports ap.behav: 0; if the matrix is on behav: 2 its single radio is pinned to the SoftAP channel (1) while the target network's 2.4GHz BSS is on channel 9, which would prevent association. That needs a serial console to confirm, and it is a separate question from whether this tool works.

30 host tests pass.

aphelps-claude-bot and others added 4 commits August 4, 2026 00:11
Two more findings from chasing WLED-TOUCH-MATRIX, which accepted a
confirmed credential push and then still refused to associate.

--inspect joins a device, reports its identity and wifi/AP config, and
pushes nothing. --dry-run answers "which APs would I touch?" without using
the radio; this answers "why won't that device join?", which can only be
learned from the device. A test asserts it never POSTs, never hits /reset,
and still forgets the AP — it exists to be pointed at hardware someone is
already unsure about, so read-only has to be a property, not an intention.

It paid for itself immediately: the matrix is configured for SSID
'STARLINK' with pskl=0 — a network with no stored passphrase, which it can
never authenticate against, so it falls back to its AP forever. Its
ap.behav is 0, the same as the device that adopted cleanly, which rules out
the SoftAP-channel-pinning theory I had been working from.

The second finding is a hole in yesterday's DHCP fix. wait_for_address
accepted ANY address, but networksetup can report success while leaving the
host exactly where it was — so the check passed instantly on the home
address, the run probed 4.3.2.1 from the wrong subnet, and the device was
reported `not-wled  no /json/info response`. That is the same lie the DHCP
wait was added to remove, one layer up: a radio failure wearing a verdict
about the device. wait_for_address now takes different_from and the address
must actually change; failing that is reported as join-failed with the
address we never left.

Visible immediately in the next live run: six retries against the matrix,
every one correctly attributed to the radio rather than to the device.

32 host tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Five new options since the README was written, and two of them are the
difference between the tool working and not:

- A section on flapping APs and --adopt-deadline, because "join-failed
  Could not find network" against an AP you can plainly see is the single
  most confusing thing this tool does, and the fix is one flag.
- A section on --inspect for diagnosing a device that takes the credentials
  and still never joins, with the real output from WLED-TOUCH-MATRIX and
  what it means: nw.ssid='STARLINK' nw.pskl=0 is a device configured for a
  network it has no passphrase for. Explains that pskl is a length and that
  0 against a non-empty SSID is the signature of credentials that did not
  save.

Also expanded the RESULT table: join-failed now covers three distinct
failures and the detail string says which, and push-failed can now mean
"the config never read back", in which case the device is deliberately not
rebooted.

Known limitations revised — the same-SSID case is now usually resolved
across passes rather than needing a rerun, and repeated association failure
against a short-lived AP is written down as a real outcome with what to do
about it.

A check that every --flag the parser defines appears in the README passes:
20 flags, none undocumented.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Repeat sweeps come back in well under a second, which means CoreWLAN is
serving a cache rather than sampling the radio. A candidate can therefore
be an artifact of an AP that has already cycled off, and the join fails
with "Could not find network" against an AP the scan just reported. One
attempt per sighting loses that race over and over — six consecutive
failures against WLED-TOUCH-MATRIX, an AP that was genuinely up much of
that time.

Retrying via the outer re-scan loop does not fix it: re-scanning costs
seconds and re-reads the same cache. --join-retries (default 4, 4s apart)
retries the association directly, which is both faster and actually
samples the radio. A successful join breaks out immediately; the failure
detail now says how many attempts were made.

This is what finally got the matrix adopted: joined, pushed, and the
config confirmed read back.

34 host tests pass, including one asserting the retries actually happen
(mutation-checked by pinning the loop to a single iteration) and one
asserting a successful join does not keep retrying.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…saved"

Continued diagnosis of WLED-TOUCH-MATRIX, which takes a confirmed push and
still will not join.

--inspect now reports every nw.ins entry with its static-IP fields, plus
filesystem usage, free heap and uptime. Reading only ins[0]'s ssid/pskl hid
three different things that look identical from outside: a second
configured network taking priority, a leftover static address (the device
associates fine and is then unreachable on the wrong subnet), and whether
the device is actually rebooting when told to.

Two hypotheses died on the evidence, which is worth recording so they are
not re-litigated: the matrix is addr=dhcp, not a stale static IP; and
fs=24/983kB, so its filesystem is nowhere near full.

The finding that matters: the config read-back proves less than it looks.
GET /json/cfg serves the IN-MEMORY config, so it returns whatever was just
pushed regardless of whether cfg.json was written, and WLED defers that
write to a later main-loop pass. Confirming on the first poll and resetting
immediately can therefore beat the write — the device accepts the push,
reads it back, and reverts to its old network on the next real power cycle,
which is exactly what was observed twice. --write-settle (default 6s) waits
after the confirmation before rebooting. The previous "read it back before
rebooting" fix was necessary but not sufficient; this is the other half.

35 host tests pass, including one asserting the settle happens between the
confirmation and the reset rather than anywhere else.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
aphelps pushed a commit that referenced this pull request Aug 8, 2026
Both from Adam's review of 2026-08-07.

The import first, since it is the shorter answer: there was no reason for
`import ipaddress` to sit inside main(). It is stdlib, there is no circular
import to break and no optional dependency to guard — it was a slip, not a
decision. It is the only mid-file import in the module; the other ten were
already at the top. Moved.

scripts/README.md documents what wled_sync does and how to run it, leading
with dry-run. The parts that earn their space are the behaviours that
surprise people rather than the flag list:

- a palette can silently override --color, because most palettes supply
  their own colours and the effect ignores the segment colour; the tool
  warns, and the README says which palettes are colour-driven
- --speed/--intensity are deliberately unset by default, since they are
  usually tuned per installation and overwriting them fleet-wide destroys
  that
- out-of-range speed/intensity is rejected up front because WLED does not
  clamp — above 255 becomes 0, freezing every device at once
- effect and palette are matched by NAME because the numbers differ between
  firmware builds

A check confirms every flag the parser defines appears in the README: 15
flags, none undocumented.

Note this file will conflict with the one PR #32 adds, which documents
wled_apjoin in the same shape. Written to match its structure so resolving
is mechanical — two sections in one index.

The separate task for a comprehensive top-level README is filed; there is
no README.md at the repo root at all today.

33 host tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved, but held: this PR is blocked on human testing, not on code.

## Testing Required in the plan has four items. One is now satisfied by the live run; three are not, so the merge is gated until you /ack-tested.

  • A real device in AP mode joined end-to-end, confirmed by wleds. Done 2026-08-04 — WLED-TOUCH-BOX (2cbcbbd98960) adopted onto Acropolis and confirmed at 192.168.1.39. That run is what surfaced the six defects fixed on this branch.
  • Two devices in one run, both on the default WLED-AP SSID. Not covered. The live run did carry two devices, but they had distinct names (WLED-TOUCH-MATRIX, WLED-TOUCH-BOX), so the actual risk this item names — same-SSID dedup collapsing two devices into one — was never exercised. Two stock, unrenamed devices are needed.
  • Host network restored after a deliberately interrupted run (Ctrl-C mid-join). Not tested. The restore path is the part that can strand the machine, and it is covered by host tests with a fake platform but never by a real interrupt.
  • A run from the Raspberry Pi. Not tested; the first real exercise of the platform seam.

Worth being explicit that the one ticked item is the weakest of the four for confidence: it is the happy path, and the other three are the ones that would stand the machine up badly if wrong.

Nothing further from me here — the code side is done, CI is green, and all review threads are resolved.

aphelps pushed a commit that referenced this pull request Aug 9, 2026
The self-review found six issues; four were real and are fixed here. The
embarrassing ones are in the checker I added to prevent exactly this.

**Commands in the README did not run when pasted.** `make test-bridge# HMTL
wire format (run twice: ...)` — `#` glued to the target is not a bash
comment, so pasting it gave `No rule to make target 'test-libs#'` and a
bash syntax error on the parentheses. Both reproduced. In a document whose
whole purpose is being followable by someone who cannot ask a question,
that is the worst defect in the PR. The columns are now aligned so every
`#` is a real comment, and two checks guard it: `bash -n` per line, plus an
assertion that `#` is preceded by whitespace — because `bash -n` only
catches syntax errors, and `make test-libs# note` parses fine while
invoking a target that does not exist.

**Two assertions could never fail.**
- The submodule check used a substring test, and `aphelps/WLED` is a
  substring of the clone URL `aphelps/WLED_dev.git`, so it passed with the
  entire WLED row deleted. Strengthened to require the path and its
  upstream URL on the same line — which also fixes a second weakness found
  while mutation-testing: `| \`WLED/\`` appears in the Repo layout table
  too, so "does this path appear anywhere" was still satisfiable.
- The env and .gitmodules sections announced they were checking the README
  while testing hardcoded literals. They now parse the README's own tables,
  so a typo or a rename fails.

**`make test` broke unhelpfully on an uninitialised clone** — `test-readme`
was the only suite with no `require_submodule` guard, so it died on a
FileNotFoundError traceback instead of the deliberate "run ./setup.sh"
message. Guarded, and the script now resolves paths from its own location
rather than the cwd.

Also added the drift-prone numbers the docstring claimed to protect but did
not check: WLED version, env count, default_envs count, default device IP.
Writing that check found my own error — the first regex ran past the blank
line terminating `default_envs` and reported 36 where the answer is 23. The
README was right; the check was wrong.

Every check is now mutation-tested: 10 deliberate defects introduced, 10
caught. One apparent miss was a mis-specified mutation that changed a link
label while leaving the URL correct — passing was the right answer, and
mutating the URL itself is caught.

Not fixed, deliberately: the fleet-scripts pointer. `scripts/` is untracked
on main until #31/#32 land, so linking it would fail the link checker. A
follow-up adds it.

make test green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
aphelps pushed a commit that referenced this pull request Aug 18, 2026
Both from Adam's review of 2026-08-07.

The import first, since it is the shorter answer: there was no reason for
`import ipaddress` to sit inside main(). It is stdlib, there is no circular
import to break and no optional dependency to guard — it was a slip, not a
decision. It is the only mid-file import in the module; the other ten were
already at the top. Moved.

scripts/README.md documents what wled_sync does and how to run it, leading
with dry-run. The parts that earn their space are the behaviours that
surprise people rather than the flag list:

- a palette can silently override --color, because most palettes supply
  their own colours and the effect ignores the segment colour; the tool
  warns, and the README says which palettes are colour-driven
- --speed/--intensity are deliberately unset by default, since they are
  usually tuned per installation and overwriting them fleet-wide destroys
  that
- out-of-range speed/intensity is rejected up front because WLED does not
  clamp — above 255 becomes 0, freezing every device at once
- effect and palette are matched by NAME because the numbers differ between
  firmware builds

A check confirms every flag the parser defines appears in the README: 15
flags, none undocumented.

Note this file will conflict with the one PR #32 adds, which documents
wled_apjoin in the same shape. Written to match its structure so resolving
is mechanical — two sections in one index.

The separate task for a comprehensive top-level README is filed; there is
no README.md at the repo root at all today.

33 host tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 0c0f066..f3e546a. Empirical checks: make test-apjoin equivalent run from the branch tip (35 tests, all pass) and a CoreWLAN SDK header check for the band enum. No radio state was changed.

These commits address most of the last review, and the live-test-driven additions (read-back before reboot, write-settle, --inspect, the DHCP/changed-address gates) are the right kind of paranoia — each one pinned by a test that names the observed failure. Status of prior findings, then what's new.

Addressed:

  • Outer loop exists now: --adopt-deadline + the TERMINAL/done verdict split is a sound device-vs-radio distinction. (The same-SSID pair still collapses — inline at wled_apjoin.py:684.)
  • Band check fails closed: is_candidate requires band == 2 positively, tested for None/-1/5/6; Swift now reads channelBand for 2.4/5 GHz. (6 GHz still leaks through the Swift default: — inline, one-line fix.)
  • --yes help text now matches the single bulk prompt, and the README says so plainly.
  • Makefile: test-apjoin is now a prerequisite of test: — the prior post-merge concern is fixed at the source.
  • Watchdog: disarm now happens only on a confirmed rejoin (armed-on-failure is the correct hard case), and the list2cmdline-into-sh -c quoting hole is gone — argv exec plus password over stdin also keeps the PSK out of ps.
  • is_connected excludes 4.3.2.x/169.254.x; forget-on-failed-join is now actually asserted by the test that previously passed against opposite behaviour.
  • OUI table is the full 331-prefix IEEE assignment with a count+format regression test, fixing an observed live refusal of a real device.

Still open from last time:

  • No Location Services preflight. README:38-42 now claims the tool "stops with an explicit error", but that only holds when the unauthorised scan returns SSID-less rows (ssids_withheld); an unauthorised empty array still ends in "No candidate APs found." exit 0. CLLocationManager.authorizationStatus remains the deterministic check the plan asked for.
  • --password is still required=True with no env-var or file alternative. The README warning is honest, but the plan asked for the mechanisms, not documentation of their absence.
  • emit()'s {"ok":false,"error":…} payload is still discarded: MacPlatform.scan() tests returncode != 0 before parsing stdout, so "no Wi-Fi interface" still surfaces as scan failed: no output.
  • Suggested test: the restore path remains uncovered. FakePlatform still has no is_connected/wait_online/watchdog, and main()'s finally — the code the tool's safety claim rests on, including the new leave-the-watchdog-armed branch — has no test for join-fails / join-hangs / body-raises / KeyboardInterrupt.
  • Suggested test: verification still re-parses the MAC out of the human-readable detail string (r[2].split(" ")[0], lines 732 and 739); a reformat of f"{mac} — rebooting" silently turns every pushed device into never-appeared. Carry the MAC as its own tuple field, or pin the format with an assertion.

New issues from these commits: four inline (wled_scan_ap.swift:45, wled_apjoin.py:684, :668, :641).

Trivial: provision_one's would-push branch (line 503) is now unreachable in production — main() returns inside its own --dry-run block (651) before any join happens — so the README output-table row for would-push describes a line the tool never prints.

Suggested post-merge check: make test on merged main shows == wled_apjoin host tests == in the log — the prerequisite now exists in the Makefile; confirm it survives the merge.

Comment thread scripts/wled_scan_ap.swift Resolved
Comment thread scripts/wled_apjoin.py Resolved
Comment thread scripts/wled_apjoin.py Resolved
Comment thread scripts/wled_apjoin.py Resolved
…t-scan-failure exit, 6GHz band label

Co-Authored-By: Claude Fable 5 <[email protected]>

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of f3e546a..777900d. Empirical check: full host suite run from the branch tip — 40 tests, all pass (35 prior + the 5 new decision/budget tests). No radio state was changed.

Addressed (all four prior inline findings):

  • Same-SSID collapse: pushed is no longer TERMINAL and finality moved to the MAC via last_push/PUSH_GRACE_S — the right design. But two mechanics defects keep the second device from actually getting its turn (inline at wled_apjoin.py:186 and :190).
  • Per-hop watchdog: re-armed per candidate with a budget computed from the actual hop knobs; the raise-the-run-wide-timeout contradiction is gone.
  • Persistent scan failure: three consecutive failures exit 2 in both the discovery wait and the adopt loop, and a trailing scan error no longer decays into "No candidate APs found." exit 0.
  • Swift band: 6 GHz labeled 6, so is_candidate's band == 2 now excludes it.
  • Bonus fix: the empty-rounds break honors last_push, so a run whose only work was pushes no longer waits out the full deadline.

Still open from earlier reviews:

  • Location Services preflight: the scan_errs exit covers persistent errors, but an unauthorised scan returning an empty array still succeeds into "No candidate APs found." exit 0. CLLocationManager.authorizationStatus remains the deterministic check the plan asked for.
  • --password still required=True with no env-var/file alternative (the plan asked for the mechanisms, not documentation of their absence).
  • emit()'s {"ok":false,"error":…} payload still discarded (wled_apjoin.py:223) — "no Wi-Fi interface" still surfaces as scan failed: no output.
  • Suggested test: the restore path remains uncovered — FakePlatform still has no is_connected/wait_online/watchdog, and main()'s finally (the safety claim, including leave-the-watchdog-armed) has no test for join-fails / join-hangs / body-raises / KeyboardInterrupt.
  • Suggested test: verification still re-parses the MAC from the human-readable detail string (r[2].split(" ")[0], now lines 783/790); carry the MAC as its own tuple field or pin the format.

New issues from this commit: two inline, both on the grace mechanism (wled_apjoin.py:186, :190). Suggested test: drive main()'s adopt loop with a FakePlatform hosting two devices behind one WLED-AP — it would have caught both.

Trivial: provision_one's would-push branch remains unreachable (main() returns in its own --dry-run block first); and the new "note: watchdog per-hop budget…" prints on every default run (computed 426s > default --safety-timeout 180s), reading like a user error when the user set nothing.

Suggested post-merge check: unchanged — make test on merged main shows == wled_apjoin host tests == in the CI log.

Comment thread scripts/wled_apjoin.py Resolved
Comment thread scripts/wled_apjoin.py Resolved

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 777900d..9420d68. Empirical check: full host suite run at the branch tip — 44 tests, all pass (40 prior + the new grace-ordering and ensure_off_device_ap tests). No radio state was changed.

Addressed (both prior inline findings):

  • Grace is now checked before give-up, so the final allowed push no longer terminally retires the shared SSID mid-reboot; covered by test_grace_shields_the_final_push_from_give_up.
  • ensure_off_device_ap detaches from the device AP after every hop, fixing both halves of the second finding: the grace window no longer spends itself holding the AP client count above zero, and the next hop's before_addr is no longer a stale 4.3.2.x lease. Detach failure surfaces as radio_stuck → early stop + exit 1 rather than silence, and the function is unit-tested.

New issue from this commit: one inline, at wled_apjoin.py:169 — the detach gate covers only WLED's 4.3.2.x, and ESP-based stranger open APs (192.168.4.x) reproduce the exact 'never left' false join-failure this function was added to kill.

Still open from earlier reviews:

  • Location Services preflight: an unauthorised scan returning an empty networks array still exits 0 with 'No candidate APs found.' — ssids_withheld only trips when networks came back with nil names; CLLocationManager.authorizationStatus remains the deterministic check the plan asked for.
  • --password still required=True (line 588) with no env-var/file alternative.
  • The Swift helper's {"ok":false,"error":…} stdout payload is still discarded on non-zero exit (line 245) — 'no Wi-Fi interface' still surfaces as scan failed: no output.
  • Suggested test: restore path — FakePlatform still lacks is_connected/wait_online/watchdog, and main()'s finally (including leave-the-watchdog-armed) has no test for join-fails / join-hangs / body-raises / KeyboardInterrupt.
  • Suggested test: verification still re-parses the MAC from the human-readable detail string (r[2].split(" ")[0], now lines 812/819); carry the MAC as its own tuple field or pin the format.
  • Suggested test: two devices behind one WLED-AP driving main()'s adopt loop end-to-end — doubly valuable now, since it is also what would probe the residual below.

TOP-LEVEL residual on same-SSID finality (pre-existing, but sharpened by this commit's own rationale): finality is per-MAC only on the push path; skip, give-up and not-wled still retire the SSID via done. An adopted device with ap.behav=2 (the live Trancender case) keeps broadcasting after joining, so the next probe of WLED-AP reaches it, earns skip, and retires the shared name while device B still waits; give-up on a mis-credentialed device does the same. The pending 'two devices in AP mode in one run' live test will hit this whenever either device is behav=2 or has wrong credentials — worth deciding which verdicts are about the AP versus about one MAC behind it before that test.

Trivial, unchanged: provision_one's would-push branch is unreachable, and the 'note: watchdog per-hop budget…' still prints on every default run (426s > default 180s).

Suggested post-merge check: unchanged — make test on merged main shows == wled_apjoin host tests == in the CI log.

Comment thread scripts/wled_apjoin.py Resolved

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 9420d68..94adf84. Empirical check: full host suite run at the branch tip — 47 tests, all pass (44 prior + the three new detach-gate tests). No radio state was changed.

Addressed (the one new inline from last pass):

  • The detach gate is no longer WLED-specific: ESP-IDF's default 192.168.4.x is covered, and the commit goes further — with the pre-loop home address captured, any unrecognised lease (a stranger AP handing out 10.x) forces the rejoin, strictly stronger than the subnet list asked for. All three paths (stranger ESP AP, home-address reference, no lease at all) are unit-tested.

New issue from this commit: one inline (minor), at wled_apjoin.py:734 — home_addr is captured once and never refreshed, so a mid-run DHCP lease change turns every later hop's detach into a redundant join + wait_online.

Still open from earlier reviews:

  • Location Services preflight: an unauthorised scan returning an empty networks array still exits 0 with 'No candidate APs found.' — ssids_withheld only trips on nil names; CLLocationManager.authorizationStatus remains the deterministic check the plan asked for.
  • --password still required=True (now line 593) with no env-var/file alternative.
  • The Swift helper's {"ok":false,"error":…} stdout payload is still discarded on non-zero exit (line 250) — 'no Wi-Fi interface' still surfaces as scan failed: no output.
  • Suggested test: restore path — FakePlatform (tests line 266) still lacks is_connected/wait_online/watchdog, and main()'s finally (including leave-the-watchdog-armed) has no test for join-fails / join-hangs / body-raises / KeyboardInterrupt.
  • Suggested test: verification still re-parses the MAC from the human-readable detail string (r[2].split(" ")[0], now lines 820/827); carry the MAC as its own tuple field or pin the format.
  • Suggested test: two devices behind one WLED-AP driving main()'s adopt loop end-to-end — still the test that would probe the residual below.

TOP-LEVEL residual on same-SSID finality: unchanged by this commit (skip/give-up/not-wled still retire the SSID via done), but it is now recorded in the plan's Open Questions for Adam to decide alongside the two-device live test — tracked rather than silently open, which is the right resting state pending that decision.

Trivial, unchanged: provision_one's would-push branch (line 552) is unreachable (--dry-run exits at line 714, before the adopt loop), and the 'note: watchdog per-hop budget…' still prints on every default run.

Suggested post-merge check: unchanged — make test on merged main shows == wled_apjoin host tests == in the CI log.

Comment thread scripts/wled_apjoin.py Resolved

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 94adf84..0430d17 (one commit, +5 lines in scripts/wled_apjoin.py, no test changes). Empirical check: full host suite run at the branch tip — 47 tests, all pass. No radio state was changed.

Addressed (the one new inline from last pass):

  • home_addr staleness: the reference is now refreshed after every successful detach, so a mid-run DHCP lease change no longer costs a redundant join + wait_online on every later hop. The if home_addr: gate is also right — no-reference mode never acquires an address it cannot verify is home.

New issue from this commit: one inline at wled_apjoin.py:767 — the refresh can latch a stranger ESP AP's lease as the home reference (details + suggestion inline).

Still open from earlier reviews (untouched by this commit):

  • Location Services preflight: an unauthorised scan returning an empty networks array still exits 0 with 'No candidate APs found.' — CLLocationManager.authorizationStatus remains the deterministic check the plan asked for.
  • --password still required=True (line 593) with no env-var/file alternative.
  • The Swift helper's {"ok":false,"error":…} stdout payload is still discarded on non-zero exit (line 250) — 'no Wi-Fi interface' still surfaces as scan failed: no output.
  • Suggested test: restore path — FakePlatform still lacks is_connected/wait_online/watchdog, and main()'s finally has no test for join-fails / join-hangs / body-raises / KeyboardInterrupt. The new refresh also lives in main()'s loop, so it inherits this gap — a fake-platform drive of the adopt loop is exactly what would have caught the latching case flagged inline.
  • Suggested test: verification still re-parses the MAC from the human-readable detail string (r[2].split(" ")[0], now lines 825/832); carry the MAC as its own tuple field or pin the format.
  • Suggested test: two devices behind one WLED-AP driving main()'s adopt loop end-to-end.

TOP-LEVEL residual on same-SSID finality: unchanged by this commit; correctly parked in the plan's Open Questions for Adam to decide alongside the two-device live test.

Trivial, unchanged: provision_one's would-push branch is unreachable (--dry-run exits before the adopt loop), and the 'note: watchdog per-hop budget…' still prints on every default run.

Suggested post-merge check: unchanged — make test on merged main shows == wled_apjoin host tests == in the CI log.

Comment thread scripts/wled_apjoin.py Resolved
…the home refresh never latches a device lease

Co-Authored-By: Claude Fable 5 <[email protected]>

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 0430d17..0a59683 (one commit: is_connected learns ESP-IDF's SoftAP subnet, the home-address refresh gains a latch guard, +3 tests). Empirical check: full host suite run at the branch tip — 50 tests, all pass. No radio state was changed.

Addressed (the one new inline from last pass):

  • Stranger-ESP-AP lease latching at the home-address refresh: fixed on both ends — is_connected now rejects 192.168.4.x alongside 4.3.2.x, and the refresh only records an address outside both device-AP subnets. TestIsConnected pins exactly the latching subnet cases, including the 192.168.4.x one.

New issues from this commit: two inlines —

  • wled_apjoin.py:734 — the widened is_connected exclusion makes a home LAN that leases from 192.168.4.0/24 unusable, and the failure surfaces mid-run as a misleading radio error (suggestion inline: refuse loudly at startup).
  • wled_apjoin.py:770 — the refresh guard admits a link-local read, the one address class is_connected rejects that this guard does not (one-line suggestion).

Trivial: the device-AP prefix pair now appears in three places (lines 174, 340, 770) — a single DEVICE_AP_SUBNETS tuple would keep them from drifting when the next SoftAP subnet shows up.

Still open from earlier reviews (untouched by this commit):

  • Location Services preflight: an unauthorised scan still exits 0 with 'No candidate APs found.'
  • --password still required=True (line 593) with no env-var/file alternative.
  • The Swift helper's {"ok":false,...} stdout payload is still discarded on non-zero exit (line 250).
  • Suggested test: restore path — FakePlatform still lacks is_connected/wait_online/watchdog, and main()'s adopt loop + finally remain untested; note the two fixes in this very commit both live in or feed that loop, so this is now the third consecutive commit whose changed behaviour no test can drive end-to-end.
  • Suggested test: verification still re-parses the MAC from the detail string (r[2].split(" ")[0], now lines 829/836).
  • Suggested test: two devices behind one WLED-AP driving main() end-to-end.

TOP-LEVEL residual on same-SSID finality: unchanged; still correctly parked in the plan's Open Questions for Adam alongside the two-device live test.

Trivial, unchanged: provision_one's would-push branch is unreachable, and the watchdog per-hop budget note still prints on every default run.

Suggested post-merge check: unchanged — make test on merged main shows == wled_apjoin host tests == in the CI log.

Comment thread scripts/wled_apjoin.py Resolved
Comment thread scripts/wled_apjoin.py Resolved

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 0a59683..32edb35 (one commit, wled_apjoin.py only: refuse at startup a home LAN that leases from a device-AP subnet; the home-address refresh also rejects link-local; no test changes). Empirical check: full host suite run at the branch tip — 50 tests, all pass. No radio state was changed.

Addressed (both inlines from last pass):

  • wled_apjoin.py:734 — a home LAN leasing from a device-AP subnet is now refused loudly at startup (lines 738–743), watchdog torn down before exit, instead of surfacing mid-run as a radio-shaped failure.
  • wled_apjoin.py:770 — the refresh guard now excludes 169.254. (line 779), so a link-local read can no longer be latched as the home reference.

New from this commit: one inline (trivial, suggestion attached) — the startup capture at line 737 is now the only unguarded current_address() read feeding home_addr.

Trivial, grown: the (AP_SUBNET, ESP_AP_SUBNET) pair now appears in four places (lines 174, 340, 738, 779) — the DEVICE_AP_SUBNETS tuple suggested last pass would collapse all four.

Still open from earlier reviews (untouched by this commit):

  • Location Services preflight: an unauthorised scan still exits 0 with 'No candidate APs found.'
  • --password still required=True (line 593) with no env-var/file alternative.
  • The Swift helper's {"ok":false,...} stdout payload is still discarded on non-zero exit (line 249).
  • Suggested test: restore path — FakePlatform still lacks is_connected/wait_online/watchdog, and main()'s adopt loop + finally remain untested. This is now the fourth consecutive commit whose changed behaviour lives in main() where no test can drive it — and the new startup refusal is itself a cheaply testable pure branch (fake current_address returning 4.3.2.2 → expect exit 1).
  • Suggested test: verification still re-parses the MAC from the detail string (r[2].split(" ")[0], now lines 838/845).
  • Suggested test: two devices behind one WLED-AP driving main() end-to-end.

TOP-LEVEL residual on same-SSID finality: unchanged; still correctly parked in the plan's Open Questions for Adam alongside the two-device live test.

Trivial, unchanged: provision_one's would-push branch is unreachable, and the watchdog per-hop budget note still prints on every default run.

Suggested post-merge check: unchanged — make test on merged main shows == wled_apjoin host tests == in the CI log.

Comment thread scripts/wled_apjoin.py Resolved
…e; name the subnet tuple once

Co-Authored-By: Claude Fable 5 <[email protected]>

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 32edb35..2d33df0 (one commit, wled_apjoin.py only: the subnet pair named once as DEVICE_AP_SUBNETS/NOT_HOME, and the startup home_addr capture now rejects link-local; no test changes). Empirical check: full host suite at the branch tip — 50 tests, all pass. No radio state was changed.

Addressed (both items from last pass):

  • wled_apjoin.py:737 — the startup capture is no longer unguarded: a 169.254.x launch address is blanked (lines 740–741) instead of being latched as the home reference.
  • Trivial-grown tuple duplication — collapsed: DEVICE_AP_SUBNETS (line 159) and NOT_HOME (line 160) now name the pair once across all four former sites.

New from this commit: one inline (suggestion attached) — ensure_off_device_ap's no-reference fallback (line 176) still tests DEVICE_AP_SUBNETS, not the new NOT_HOME, and the blanked-home_addr startup path makes that gap newly reachable: a link-local read between hops now passes as "detached and home".

Still open from earlier reviews (untouched by this commit):

  • Location Services preflight: an unauthorised scan still exits 0 with 'No candidate APs found.'
  • --password still required=True (line 595) with no env-var/file alternative.
  • The Swift helper's {"ok":false,...} stdout payload is still discarded on non-zero exit (line 251).
  • Suggested test: restore path — FakePlatform still lacks is_connected/wait_online/watchdog, and main()'s adopt loop + finally remain untested. Fifth consecutive commit whose changed behaviour lives in main(); the startup refusal and the new link-local blank are both cheaply testable pure branches (fake current_address returning 4.3.2.2 → exit 1; returning 169.254.5.5 → home_addr empty).
  • Suggested test: verification still re-parses the MAC from the detail string (r[2].split(" ")[0], now lines 842/849).
  • Suggested test: two devices behind one WLED-AP driving main() end-to-end.

TOP-LEVEL residual on same-SSID finality: unchanged; still correctly parked in the plan's Open Questions for Adam alongside the two-device live test.

Trivial, unchanged: provision_one's would-push branch is unreachable, and the watchdog per-hop budget note still prints on every default run.

Suggested post-merge check: unchanged — make test on merged main shows == wled_apjoin host tests == in the CI log.

Comment thread scripts/wled_apjoin.py Resolved
…anked home reference can recover

Co-Authored-By: Claude Fable 5 <[email protected]>

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 2d33df0..4bd7d20 (one commit, wled_apjoin.py only: the no-reference fallback now tests NOT_HOME, and the home-reference refresh is unconditional so a launch-blanked reference can recover; no test changes). Empirical check: full host suite at the branch tip — 50 tests, all pass. No radio state was changed.

Addressed (the one inline from last pass):

  • wled_apjoin.py:176 — the fallback now tests NOT_HOME: a link-local read between hops forces the rejoin instead of passing as "detached and home".

New from this commit: two inline — one PLAUSIBLE latch edge on the now-unconditional refresh (line 784), and a Suggested test: for the newly reachable line-176 branch.

Still open from earlier reviews (untouched by this commit):

  • Location Services preflight: an unauthorised scan still exits 0 with 'No candidate APs found.'
  • --password still required=True (line 595) with no env-var/file alternative.
  • The Swift helper's {"ok":false,...} stdout payload is still discarded on non-zero exit.
  • Suggested test: restore path — FakePlatform still lacks is_connected/wait_online/watchdog, and main()'s adopt loop + finally remain untested. Sixth consecutive commit whose changed behaviour lives at least partly in main() (the unconditional-latch recovery path is only exercisable there).
  • Suggested test: verification still re-parses the MAC from the detail string (r[2].split(" ")[0], now lines 843/850).
  • Suggested test: two devices behind one WLED-AP driving main() end-to-end.

TOP-LEVEL residual on same-SSID finality: unchanged; still correctly parked in the plan's Open Questions for Adam alongside the two-device live test.

Trivial, unchanged: provision_one's would-push branch is unreachable, and the watchdog per-hop budget note still prints on every default run.

Suggested post-merge check: unchanged — make test on merged main shows == wled_apjoin host tests == in the CI log.

Comment thread scripts/wled_apjoin.py Resolved
Comment thread scripts/wled_apjoin.py Resolved
…hind a confirmed rejoin

Co-Authored-By: Claude Fable 5 <[email protected]>

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 4bd7d20..198c184 (one commit, wled_apjoin.py + tests: the home-reference latch moved into ensure_off_device_ap, which now returns (ok, home_addr) and latches only from a lease observed behind a wait_online-confirmed rejoin; three new tests). Empirical check: full host suite at the branch tip — 53 tests, all pass. No radio state was changed.

Addressed (both inlines from last pass):

  • The PLAUSIBLE latch edge on the unconditional refresh (old line 784) — the passive fast-paths can no longer latch a stranger routable lease (test_never_latches_a_stranger_routable_lease_as_home proves it), and the caller cannot latch an unverified address at all now.
  • Suggested test: for the line-176 link-local branch — test_link_local_with_no_reference_forces_the_rejoin added.

New from this commit: one inline PLAUSIBLE residual of the same edge, now confined to the rejoin path — join()'s result is discarded at line 185, so a rejoin that fails to associate while the host holds a stranger routable lease still "confirms" and latches it (suggestion attached), plus a Suggested test: companion.

Still open from earlier reviews (untouched by this commit):

  • Location Services preflight: unauthorised-scan failure is surfaced only at scan time via ssids_withheld (and only when the sweep returns nil-SSID rows), not preflighted.
  • --password still required=True (now line 607) with no env-var/file alternative.
  • The Swift helper's {"ok":false,...} stdout payload is still discarded on non-zero exit.
  • Suggested test: restore path — FakePlatform still lacks is_connected/wait_online/watchdog, and main()'s adopt loop + finally remain untested. Credit where due: this is the first commit in the series whose behaviour change moved INTO a host-tested function rather than main() — only the mechanical tuple unpacking lives there now.
  • Suggested test: verification still re-parses the MAC from the detail string (r[2].split(" ")[0], now lines 846/853).
  • Suggested test: two devices behind one WLED-AP driving main() end-to-end.

TOP-LEVEL residual on same-SSID finality: unchanged; still correctly parked in the plan's Open Questions for Adam alongside the two-device live test.

Trivial, unchanged: provision_one's would-push branch is unreachable, and the watchdog per-hop budget note still prints on every default run.

Suggested post-merge check: unchanged — make test on merged main shows == wled_apjoin host tests == in the CI log.

Comment thread scripts/wled_apjoin.py Resolved
Comment thread tests/test_wled_apjoin.py Resolved
…or latches the reference

Co-Authored-By: Claude Fable 5 <[email protected]>

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 198c184..e25615d (one commit, wled_apjoin.py + tests). Empirical check: full host suite at the tip — 54 tests, all pass (53 prior + the 1 new). No radio state was changed.

Addressed (the only inline from last pass):

  • The rejoin-path latch residual is closed exactly as suggested: ensure_off_device_ap now unpacks join()'s result and returns (False, home_addr) on a failed association, so a stranger routable lease can no longer "confirm" via wait_online and latch as home. The suggested companion test (test_a_failed_rejoin_on_a_stranger_lease_neither_confirms_nor_latches) was added and asserts both the verdict and that the reference stays untouched.

New from this commit: none. Verified the (ok, err) tuple contract the new unpack depends on — real MacPlatform.join returns it on every path (line 282), and both test fakes were updated consistently.

Still open from earlier reviews (untouched by this commit; line refs shifted +4 in main()):

  • Location Services preflight: unauthorised-scan failure still surfaces only at scan time via the withheld-SSIDs message, not preflighted.
  • --password still required=True with no env-var/file alternative (plan's Credentials section).
  • The Swift helper's {"ok":false,...} stdout payload is still discarded on non-zero exit.
  • Suggested test: restore path — FakePlatform still lacks is_connected/wait_online/watchdog; main()'s adopt loop + finally remain untested (the finally block's retry at line 832 also still discards join()'s result, same shape as the bug this commit fixed — cheap to cover together).
  • Suggested test: verification still re-parses the MAC from the detail string (r[2].split(" ")[0], now lines 850/858).
  • Suggested test: two devices behind one WLED-AP driving main() end-to-end.

TOP-LEVEL residual on same-SSID finality: unchanged; correctly parked in the plan's Open Questions for Adam alongside the two-device live test.

Trivial, unchanged: provision_one's would-push branch is unreachable, and the watchdog per-hop budget note still prints on every default run.

Suggested post-merge check: unchanged — make test on merged main shows == wled_apjoin host tests == in the CI log.

The only conflict was the Makefile's .PHONY line and test's prerequisites, where
this branch added test-apjoin and main added test-hmtl. Neither side removes the
other's target, so the resolution is the union of the two.

Both targets exist after the merge (test-hmtl:152, test-apjoin:192), `make -n test`
reaches each of them, and the branch's own suite is 54/54.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01F4oTr1YW3z7ozksMUT1z5j
@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Rebased onto main and resolved the Makefile conflict as the union of both sides — this branch's
target plus main's test-hmtl. Verified both exist after the merge and that make -n reaches each.

Heads-up for whoever merges this and #32: both branches were merged against a main carrying
test-hmtl only, and each adds its own target to the same .PHONY / test: lines. Whichever
lands first will make the other conflict again
, on the same line, with the same union resolution.
It is a two-line hand-merge, not a problem — just expect it rather than treating it as new drift.

Filed as a P4: that list is a single line every new test target has to edit, so any two such branches
conflict by construction. Accumulating into a variable (TEST_TARGETS += … beside each target's own
definition) would make it mergeable and put the registration next to the thing it registers.

aphelps-claude-bot added a commit that referenced this pull request Aug 20, 2026
* add a top-level README, verified against the source files

There was no README.md at the repo root, so a newcomer landed on CLAUDE.md
(written for agents) or skills/README.md (skills only). Neither answers
"what is this and where do I start".

Adam's three decisions shaped it, and the first two changed the task:

- **Audience is him plus collaborators who may be remote and setting up
  while he is unavailable.** So it has to stand alone: a "when it goes
  wrong" section, and the traps documented rather than just the happy path.
- **"Quick deploy on clone should be the standard."** Clone -> setup ->
  build -> flash -> verify is the spine, not an appendix. Flashing and
  confirming /json/info matches what you built are part of the main path.
- **Reference only files in this repo.** That rule and the gitlink problem
  agree: submodule docs (BACKBONE_ROUTER.md, SENSOR_SYNC.md, the
  rs485_bridge readme) are named as plain-text paths, never linked — they
  are not this repo's files and they 404 on github.com because GitHub
  renders a submodule as a commit pointer.

It deliberately does not send the reader to CLAUDE.md for any setup step.
CLAUDE.md is written for agents, and it carries at least three claims that
are no longer true — the default build env, the number of make targets, and
the WLED version (it says 0.15.3; package.json says 16.0.1). Propagating
those to the people least able to spot them would be the worst outcome.

That is also why tools/check_readme.py exists, wired in as `make
test-readme` and part of `make test`. It verifies the README against
platformio.ini, the Makefile and .gitmodules rather than trusting anyone's
memory: links resolve to tracked files, no link points into a submodule,
every make target and [env:] named exists in the file it is attributed to,
the submodule table matches .gitmodules, and setup.sh/upload_wled.py really
support the flags shown. My own first draft inherited two of CLAUDE.md's
stale claims, which is the failure this guards against.

Scoped to what is on main today: scripts/ and tests/ arrive with #31/#32,
so nothing references them yet and `make test` is described as four suites.
A follow-up adds the scripts section once those land.

make test green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* address self-review: a checker whose checks could not fail

The self-review found six issues; four were real and are fixed here. The
embarrassing ones are in the checker I added to prevent exactly this.

**Commands in the README did not run when pasted.** `make test-bridge# HMTL
wire format (run twice: ...)` — `#` glued to the target is not a bash
comment, so pasting it gave `No rule to make target 'test-libs#'` and a
bash syntax error on the parentheses. Both reproduced. In a document whose
whole purpose is being followable by someone who cannot ask a question,
that is the worst defect in the PR. The columns are now aligned so every
`#` is a real comment, and two checks guard it: `bash -n` per line, plus an
assertion that `#` is preceded by whitespace — because `bash -n` only
catches syntax errors, and `make test-libs# note` parses fine while
invoking a target that does not exist.

**Two assertions could never fail.**
- The submodule check used a substring test, and `aphelps/WLED` is a
  substring of the clone URL `aphelps/WLED_dev.git`, so it passed with the
  entire WLED row deleted. Strengthened to require the path and its
  upstream URL on the same line — which also fixes a second weakness found
  while mutation-testing: `| \`WLED/\`` appears in the Repo layout table
  too, so "does this path appear anywhere" was still satisfiable.
- The env and .gitmodules sections announced they were checking the README
  while testing hardcoded literals. They now parse the README's own tables,
  so a typo or a rename fails.

**`make test` broke unhelpfully on an uninitialised clone** — `test-readme`
was the only suite with no `require_submodule` guard, so it died on a
FileNotFoundError traceback instead of the deliberate "run ./setup.sh"
message. Guarded, and the script now resolves paths from its own location
rather than the cwd.

Also added the drift-prone numbers the docstring claimed to protect but did
not check: WLED version, env count, default_envs count, default device IP.
Writing that check found my own error — the first regex ran past the blank
line terminating `default_envs` and reported 36 where the answer is 23. The
README was right; the check was wrong.

Every check is now mutation-tested: 10 deliberate defects introduced, 10
caught. One apparent miss was a mis-specified mutation that changed a link
label while leaving the URL correct — passing was the right answer, and
mutating the URL itself is caught.

Not fixed, deliberately: the fleet-scripts pointer. `scripts/` is untracked
on main until #31/#32 land, so linking it would fail the link checker. A
follow-up adds it.

make test green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* address review: block-level bash -n, narrowed glued-# check, scoped and guarded ini lookups

Co-Authored-By: Claude Fable 5 <[email protected]>

* address review: glued-# check also covers tabled env names

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: aphelps-claude-bot <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
The re-conflict predicted when #34 merged first. Three hunks this round, not one:
the help comment, the .PHONY/test lists, and — new — the target recipes
themselves, since test-apjoin and test-readme now sit at the same place in the
file. All three resolve as the union; neither side replaces the other.

Verified rather than assumed: both recipes dry-run, `make -n test` reaches them,
and the branch suite is 54/54.

This is the third time this line has conflicted in one session (test-hmtl,
test-readme, test-apjoin). Filed as a P4 in WLED_dev's todo: accumulating into a
TEST_TARGETS variable beside each target's own definition would make it mergeable
instead of a serialisation point every branch has to queue through.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01F4oTr1YW3z7ozksMUT1z5j
aphelps-claude-bot added a commit that referenced this pull request Aug 22, 2026
* add wled_sync: drive every WLED device on the LAN to one look

Scans the local subnet and applies the same effect, colour and palette to every
device it finds, turning them on in the process.

Resolution is BY NAME, per device. Effect and palette numbers are
firmware-specific — 220 effects on 16.0.1 against 187 on 0.14.4 — so the same
index is a different effect on different hardware, which would silently produce a
mismatched fleet that looks like a wiring or timing fault. Names are stable:
diffing mode-data strings between v0.14.4 and 16.0.1 shows zero renames across
the 178 shared effects, only Police and Meteor Smooth removed. A device missing
the requested name is skipped and said so, never given a near-miss substitute.

Four things in the request body are there for non-obvious reasons:

  udpn.nn  suppresses WLED's own UDP sync. Without it, deserializeState ->
           stateUpdated -> notify() (led.cpp:95) re-broadcasts the RAW effect and
           palette bytes (udp.cpp:51,69) to every device with sync receive on --
           which Trancender has -- undoing the per-device name resolution through
           a side channel and racing our own POSTs.
  tb       one timebase shared across the whole run, so devices agree on
           strip.now and animate in step rather than drifting apart.
  v        makes WLED return the full state instead of {"success":true}, folding
           verification into the same round trip with no window for a playlist or
           another operator to slip in. Needed because a 200 does not mean
           applied: pal is silently ignored for non-RGB segments (json.cpp:298).
  on       a reachable device is powered, so light it. No brightness is imposed --
           toggleOnOff restores the device's own briLast (led.cpp:44-47), so
           per-device levels survive.

Palette IDs are not one contiguous list: fixed palettes are their position in
/json/pal, usermod palettes are 255-j and are named only in info.umpalnames, and
custom are 200-k with no names at all. Position is the ID for the fixed block
only. /json/pal also decorates five entries with a leading '*', so "Random Cycle"
must match "* Random Cycle".

--color warns when the chosen palette will make it invisible: under palette 0 or
any gradient palette most effects take colour from the palette and ignore col
entirely, and a flag that silently does nothing reads as a bug.

21 host tests, wired into the top-level Makefile as test-sync so CI's
`make test STRICT=1` actually runs them. The cross-version case stands up two
stub HTTP servers rather than needing two firmware versions on the bench -- only
one device is currently reachable. Highest-value assertion is that every
generated body carries udpn.nn: that regression would be silent and fleet-wide.

Verified live in --dry-run against the one reachable device: resolved Hiphotic to
fx=180 and Random Cycle to pal=1, independently matching what it already runs,
and left its state byte-identical.

* fix an intermittent bug that silently disabled phase alignment

WLED parses `tb` into `long tr` (json.cpp:398) and ignores it unless `tr >= 0`
(json.cpp:417-418). `long` is 32-bit signed on ESP32, but the tool was sending
`int(time.time()*1000) & 0xFFFFFFFF` — 3124561992 today, well above INT32_MAX.
That value does not survive the parse, so `strip.timebase` was never assigned and
devices kept their own phase while the tool reported success. Exactly the silent
no-op this tool is built to avoid.

The failure is intermittent, which is worse than a constant one: bit 31 of
epoch-milliseconds flips about every 24.8 days, so alignment would have worked
for ~25 days, quietly stopped for ~25 days, then resumed — reading as
"sometimes the lights drift" rather than as a bug.

Masks to 31 bits instead. The absolute value is arbitrary: `strip.timebase =
tb - millis()` means only agreement between devices matters, not the epoch.

The existing test missed this by asserting on a small literal (1234567) rather
than what the tool actually generates. Added two regressions: one constructing
the overflow half explicitly (0x1C0000000, so it does not depend on when the
suite runs — my first attempt used a "realistic" epoch that happened to land in
the safe half and passed against the broken code), and one asserting the anchor
is shared across devices, since alignment depends on every device getting the
same value.

* address self-review: the colour warning was inverted, and sx/ix defeated the sync

colour_is_moot had the two palettes that matter exactly backwards, so the tool
warned precisely when it should have stayed quiet and stayed quiet precisely when
it should have warned. Both were verified in WLED's source rather than inferred
from the names, which mislead in both directions:

  "Default" (0)        color_from_palette short-circuits to getCurrentColor()
                       (FX_fcn.cpp:1168-1170), so --color is at its MOST effective
                       here — the tool called it moot.
  "* Random Cycle" (1) wears the same '*' as the colour palettes but uses
                       _randomPalette and never reads colors[] (FX_fcn.cpp:248-249),
                       so --color does nothing — the tool called it effective.

Palettes 2-5 build their CRGBPalette16 from colors[0..2] and are genuinely
colour-driven. The set now cites the switch it came from.

Effect changes now send fxdef. setMode only reloads speed/intensity under
loadDefaults (FX_fcn.cpp:600-611), so without it every device kept its own sx/ix
and ran the same effect at a different rate — the exact divergence the shared
timebase exists to prevent, arriving through another door.

One device's exception no longer discards the whole report. f.result() re-raised
inside the as_completed loop and the traceback escaped before the table printed;
urlopen does not wrap http.client exceptions, so this was reachable rather than
theoretical.

verify_applied stops crying wolf in two knowable cases, both distinguishable from
fields WLED already returns. A seg body with no id only touches SELECTED segments
(json.cpp:470-474), so when none are selected nothing was written — previously
reported as a phantom "wrong effect" via an `or segs` fallback. And non-RGB
segments have pal skipped and col forced to white, which would have pinned the
exit code to 1 forever; lc (json.cpp:597) identifies them.

Exit code now reflects whether devices actually got the look: skipped and
unreachable count as failure. A run where every device was skipped was exiting 0.

27 tests, including the RGBW four-channel and unselected-segment cases that the
reviewer asked about specifically — neither false-fails.

* clear the remaining self-review items

The dry-run test could not fail. Its stub had no do_POST, so a write got a 501,
which post_json swallows into a quiet "failed" row — the test would have passed
even if --dry-run had written. The stub now accepts POSTs and records them, and
the test asserts nothing was recorded. Mutation-checked by disabling the dry-run
branch: the test fails, as it should have all along.

--timeout and --workers governed only the apply phase while discovery was pinned
to hardcoded 1.0s/64. Split into explicit --discovery-timeout/--discovery-workers
so the fast-sweep defaults stay visible rather than hidden, and gave every flag
help text.

Dropped CUSTOM_PALETTE_ID_BASE. It was never used, and the reason is worth
stating rather than leaving an unused constant to puzzle over: WLED exposes no
names for custom palettes, so they cannot be selected by name at all.

* revert fxdef — it would have wrecked 2D geometry — and use explicit sx/ix

The previous commit sent seg.fxdef to equalise speed across devices. That was
overreach and would have damaged the one device we actually have.

setMode(fx, true) resets far more than sx/ix. It resets map1D2D UNGUARDED for any
effect that does not declare m12=, and WLED's own call site carries the warning:
"may change map1D2D causing geometry change" (json.cpp:291). On a matrix that
destroys the expansion mode, and re-running does not undo it — Trancender is a
54x24 matrix, so the fix targeted exactly the hardware it would have broken. It
also applies the effect's default palette (FX_fcn.cpp:616-617), silently
overriding colour whenever --palette was not given: --effect "Noise 1" --color
red would have applied gradient palette 20 and made the red invisible, with no
warning, verification passing, and the row reporting success.

It would not even have fixed the problem it was for: both call sites gate on
fx != mode, so a device already running the target effect keeps its drifted
speed. Broken on the second run, destructive on the first.

Replaced with explicit --speed/--intensity, which are narrower and idempotent.
They are NOT sent by default: speed is often deliberately tuned per installation,
so normalising it silently is its own kind of wrong. Documented that a shared
effect can still run at different rates without them.

Also: the verify_applied and colour_is_moot docstrings still described pre-fix
behaviour and contradicted the code beneath them; softened the "Default is where
--color is MOST effective" claim, since it holds only for call sites passing
mcol < NUM_COLORS and a minority pass 255; and corrected --host's help, which
claimed to skip discovery when the host is still probed.

Added the exit-code tests that were missing — the only change in the last batch
that was not mutation-proof. Verified the new rule differs from the old on all
four cases that matter (skipped, unreachable, mixed, empty), so the tests would
genuinely fail against the previous behaviour.

* make the exit-rule test real, and reject out-of-range speed

TestExitRule was vacuous — it hand-copied the rule into the test file instead of
calling it, so mutating main() to `return 0` left all 31 tests green. The rule is
now exit_code() at module level and the test calls it; mutation-checked, two
tests go red. This is the third test in this PR that could not fail, so the
pattern is mine, not bad luck: a test written from the same understanding as the
code inherits its blind spots unless it is forced through the shipped path.

--speed/--intensity are now range-checked. WLED does not clamp: getVal passes no
bounds (json.cpp:294) and ArduinoJson's convertNumber returns 0 when the value
will not fit a uint8_t, so `--speed 999` would have set sx=0 on every device — a
visible freeze on most effects — while verify_applied never checks sx/ix, every
row read "applied" and the exit code stayed 0. Silent, fleet-wide, and only
catchable by looking at the lights.

They can also now be used alone; requiring --effect/--palette/--color to
accompany them was arbitrary, since a speed-only run is valid on every device.
And --dry-run prints sx/ix, without which the safety valve was blind to the one
knob nothing downstream verifies.

verify_applied's docstring claimed both the non-RGB and no-selected-segment cases
were exempt from reporting. Only the first is; the second is reported, with the
real reason instead of a misleading "wrong effect". The test asserted the
opposite of the paragraph above it.

* cover the apply path, and stop getattr masking a real asymmetry

Nothing ran sync_one with dry_run=False, so the line forwarding args.speed into
build_body had zero coverage and the stubs' speed/intensity attributes were
decorative — removing them left the suite green. There is now an apply-path test
asserting what actually goes on the wire (sx, ix, tb, udpn.nn), and both
mutations bite: dropping the forwarding fails it, and so does removing the stub
attributes.

Replaced getattr(args, "speed", None) with plain attribute access in the dry-run
detail. The defensive form hid exactly the mismatch the stub attributes existed
to catch — dry-run tolerated a missing attribute while the apply path raised
AttributeError on it.

The verify_applied docstring said non-RGB segments are "EXEMPT", but fx is still
checked on them and the suite asserts that. Only pal and col are exempt.

Sharpened the range-check message: WLED's two out-of-range behaviours differ. A
value above 255 becomes 0 via convertNumber, freezing the fleet; a negative one
is ignored outright (util.cpp:73). Rejecting both is right, but the message
claimed zeroing for both.

Module usage block now shows --speed/--intensity.

* move wled_sync into scripts/ as requested in review

Puts it alongside wled-ap-hop.sh rather than at the repo root. REPO_ROOT now
walks one level up so the scanner path and the seam stay repo-relative, and the
test loads it from its new location. Tests stay in tests/, which is where the
Makefile target expects them.

Note scripts/ was previously untracked — this commit starts tracking it, but
only this file. promote-base-to-main.sh and wled-ap-hop.sh remain untracked and
are not mine to add.

* docs: scripts/README.md for wled_sync; hoist a stray import

Both from Adam's review of 2026-08-07.

The import first, since it is the shorter answer: there was no reason for
`import ipaddress` to sit inside main(). It is stdlib, there is no circular
import to break and no optional dependency to guard — it was a slip, not a
decision. It is the only mid-file import in the module; the other ten were
already at the top. Moved.

scripts/README.md documents what wled_sync does and how to run it, leading
with dry-run. The parts that earn their space are the behaviours that
surprise people rather than the flag list:

- a palette can silently override --color, because most palettes supply
  their own colours and the effect ignores the segment colour; the tool
  warns, and the README says which palettes are colour-driven
- --speed/--intensity are deliberately unset by default, since they are
  usually tuned per installation and overwriting them fleet-wide destroys
  that
- out-of-range speed/intensity is rejected up front because WLED does not
  clamp — above 255 becomes 0, freezing every device at once
- effect and palette are matched by NAME because the numbers differ between
  firmware builds

A check confirms every flag the parser defines appears in the README: 15
flags, none undocumented.

Note this file will conflict with the one PR #32 adds, which documents
wled_apjoin in the same shape. Written to match its structure so resolving
is mechanical — two sections in one index.

The separate task for a comprehensive top-level README is filed; there is
no README.md at the repo root at all today.

33 host tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* address re-review: describe the actual test suite, note argparse's exit 2

Co-Authored-By: Claude Fable 5 <[email protected]>

* Say plainly that the stub tables are synthetic

Same correction as the README one, in the file it describes. "Real name tables,
trimmed" sends anyone chasing a discrepancy off to look for a capture that does
not exist; they are real names at the indices under test with repeated padding
between, which establishes the cross-version index property exactly as well.

Lengths stated so the next reader does not have to count: EFF_16 is 220, EFF_014
is 186.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01F4oTr1YW3z7ozksMUT1z5j

* Cover the usermod-palette and verify-after-apply wiring

Two more of the re-review's confirmed-uncovered paths, each verified by re-running
the mutation that exposed it.

usermod palette end-to-end: resolve_palette's 255-j arithmetic was well unit-tested,
but nothing drove it through sync_one, so replacing dev.get("umpalnames") with None
left every test green. The new test stands up a stub advertising umpalnames and
asserts the wire body carries pal=255-j rather than a list index. Mutation
re-applied: now fails.

verify-after-apply wiring: verify_applied was covered directly, but the code that
CONSUMES its verdict was not — `problems = []` left the suite green. Now fails.

Worth recording precisely, because my first version of that test described a
mechanism it does not use: sync_one checks the POST *response* (wled_sync.py:361),
not a later GET of /json/state. I had added a /json/state fixture and written a
docstring claiming the stub "answers with a state that does not hold what was asked
for". The fixture was never read — the stub answers every POST with `{}`, and that
is what fails verification. The test was passing for a reason its own comment got
wrong, so the fixture is gone and the docstring now says what actually drives it.

39 tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01F4oTr1YW3z7ozksMUT1z5j

* Cover --no-phase and the colour-moot warning

The last two confirmed-uncovered paths from the re-review. Both mutations
re-applied and both now fail, where the old suite gave 0 failures for each:

  timebase = make_timebase()          (drop the --no-phase conditional)  -> fails
  if False:                           (suppress the colour-moot warning) -> fails

--no-phase is asserted on the WIRE body, not the local variable: what matters is
that no tb reaches the device. It also asserts the other direction — that tb IS
sent without the flag — because a test checking only for absence would pass
against a build that never sends a timebase at all.

The colour-moot test likewise asserts a colour-DRIVEN palette does NOT warn.
A warning that fires on everything is one people learn to ignore, so the
suppression half is the half worth pinning.

41 tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01F4oTr1YW3z7ozksMUT1z5j

---------

Co-authored-by: aphelps-claude-bot <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
wled_sync landed on main (#31) while this branch was open, and both added
scripts/README.md and a test target. Resolved by keeping both rather than
picking a side:

- Makefile: `test` runs test-sync AND test-apjoin, both target bodies kept.
  This is the merge hot spot the Makefile task already describes.
- scripts/README.md: one intro covering both tools and the scan skill they
  bracket, each tool's section intact, and a Tests section split per tool so
  neither set of caveats is lost.
@aphelps-claude-bot
aphelps-claude-bot merged commit b833adc into main Aug 22, 2026
1 check passed
@aphelps-claude-bot
aphelps-claude-bot deleted the wled-ap-autojoin branch August 22, 2026 08:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants