Skip to content
Back to skills

Firmware

ASecurity

Use when working on the silken_net STM32 firmware — Soldier (sense→Lorenz→encrypt→TX, STOP2 loop) and Queen (LoRa RX→CIFO dedup→CoAP flush, OTA) in firmware/{soldier,queen}/main.c, the mruby bio_contract.rb, and the header-only One-Home libs in firmware/common/ (silken_sha256, lorenz_seed, lora_ccm, silken_crc, queen_attest). Knows the non-obvious gotchas — ECB-restore after CBC, Load_AES_Key before MX_CRYP_Init, RTC DR0..DR19 budget (DR13/DR14 and the CCM build's DR16 reserved for the FW.54 ...

  • 23 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added September 20, 2026
businessrustgorubynodeexpressrailsgitapibackendsecurity

Works with

  • cursor
  • api

Security analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned November 26, 2026

npx -y skills add Alexey-Lukin/silken_net --skill firmware --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Firmware?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Firmware
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/alexey-lukin-firmware/badge)](https://www.skillsdirectory.com/skills/alexey-lukin-firmware)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: firmware
description: "Use when working on the silken_net STM32 firmware — Soldier (sense→Lorenz→encrypt→TX, STOP2 loop) and Queen (LoRa RX→CIFO dedup→CoAP flush, OTA) in firmware/{soldier,queen}/main.c, the mruby bio_contract.rb, and the header-only One-Home libs in firmware/common/ (silken_sha256, lorenz_seed, lora_ccm, silken_crc, queen_attest). Knows the non-obvious gotchas — ECB-restore after CBC, Load_AES_Key before MX_CRYP_Init, RTC DR0..DR19 budget (DR13/DR14 and the CCM build's DR16 reserved for the FW.54 live set, only DR17/DR18 of the CCM build unowned, DR7 = the Standby wake marker), post-FW.29 StatusByte bit-layout, Lorenz continuation vs cold-start, HAL_GetTick frozen in STOP2 (wall-seconds instead — HAL-free arithmetic in wall_time.h, the RTC read in soldier/main.c), vcap = VDDA-mV not EDLC-Vcap, gated CCM vs live ECB — and the host-test parity discipline (make -C firmware/test). The gotcha bodies live in gotchas.md, one generated index line each in the body — open it before touching a peripheral init, the RTC map, the crypto path, the wire format or a gated block. Routes to CLAUDE.md §5 + the 03_01..03_06 canon, does not restate. Examples: \"add a sensor field\", \"change Lorenz params\", \"modify AES / CRYP init\", \"touch RTC-persisted state\", \"why do LoRa decrypts fail after a flush\", \"edit the seed / cold-start crypto\", \"add FEC / change the LoRa code rate\", \"skip redundant or low-value frames on the device\"."
---

# Firmware (Soldier + Queen)

Navigation aid + non-obvious gotchas. The **SSOT is the docs + code below** — this skill
points, it does not restate (so it can't drift). Verify a fact at its home before trusting a summary.

## SSOT Documents — Read These First

| Document | What it covers |
|----------|---------------|
| `CLAUDE.md §1` + `§5` | High-level architecture, AES/key table (post-FW.2 (в)), Lorenz/StatusByte summary — for the exact packet/Status-byte bit-layout trust the canon docs below; OTA wire → gotcha 11 / `03_02 §5` |
| `docs/03_01_Firmware_Lifecycle_and_DMA.md` | Soldier/Queen lifecycle, STOP2 phases, ISR map, **RTC Backup Register Map §2 (canonical DR0..DR19 + magic markers)**, binary packet format §8, mesh-relay + rendezvous ladder §1.9 (CCM-era star-only; single-Queen scale ceiling §1.9.1) |
| `docs/03_02_Queen_Gateway_Firmware.md` | Queen: LoRa RX → CIFO dedup → CoAP flush, OTA broadcast, AES mode transitions |
| `docs/03_03_TinyML_Acoustic_Inference.md` | **Parked since HW.30 (2026-09-29):** the model, the INT8 forward-pass (NOT CMSIS-NN) and the log-mel contract are an asset with NO Soldier call-site; the design history it still carries (the DSP-path decision matrix §3.2) is marked as such by its header; the Soldier fauna session, the decision logic and the DR13/DR14 thresholds have left the canon for git, and §10 keeps only the fauna source and what a revival on a site carrier would need (§10.5) |
| `docs/03_04_mruby_Lorenz_Attractor.md` | **CCM-era contract without Lorenz — §8** (what the device computes ⊥ what the server does; FW.66 (Б)); ECB-era: Lorenz constants (§1.2; Z-thresholds §4.1), Float-not-BigDecimal parity, RTC continuation vs cold-start (§2.1), Status-byte packing (§4.4) |
| `docs/03_05_Hardware_Symmetric_Crypto_and_Security.md` | AES modes, key rotation (FW.17), SE05x secure element (baseline SE051C2; SEC.6 + SEC.14 provisioning-only — KEYL stays in Protected Flash; ATECC608B = banner-legacy pattern), IV, QATT wire (§2.2), PQC roadmap |
| `docs/03_06_Factory_Flashing_and_Key_Provisioning.md` | Factory home: HKDF per-device derivation, K_seed, OTA seal (Ed25519, FW.23 §4), flashing pipeline + ops-security (SEC.3 §5) |
| `docs/00_07_Action_Plan_Tracker.md` | FW.*/SEC.* task status, open items (canonical home of blockers) |

## Gotchas Not Obvious From Docs

**Bodies live in [`gotchas.md`](gotchas.md) — open it before you touch a peripheral init, the RTC map, the crypto path, the wire format, a gated block or the lint lane.** One generated line per gotcha below: the line is the CARRIER, meant to stop you mid-action; the mechanism and the bounds are in the companion. Numbering is append-only (`1b` · `1c` are items of their own) — cite `firmware #N`.

<!-- FIRMWARE-GOTCHAS-INDEX:AUTO — generated from gotchas.md by `ruby scripts/guard_craft_index.rb --write`; edit rules THERE, never here -->

1. Shared peripheral, per-operation reconfig: restore the baseline — and make sure a baseline EXISTS
1b. Queen re-resolves the CoAP server IP after N≥3 consecutive flush-fails, so an A-record flip is picked up without an IWDG reboot
1c. Retransmit is UPLINK-only — the downlink poll has none, so a lost 2.05 is recovered only by the `cmd=` echo cursor, never by a CoAP retry (FW.63)
2. RTC registers are nearly all spoken-for — but allocated ≠ optimally packed
3. `Load_AES_Key()` must run BEFORE `MX_CRYP_Init()` — reversed, CRYP silently uses a zeroed key
4. Cold-TX deferral: at low temperature the Soldier skips TX entirely, so never assume every wake cycle emits a packet
5. StatusByte layout is post-FW.29 — `[PanicFlag:1 | Status:2 | GrowthPoints:5]`, and status 3 means vm_error, never tamper
6. Lorenz state on boot is a warm continuation from DR16–18 only when DR19 holds the magic AND all three values are finite, otherwise a cold start derived from `K_seed`
7. CCM is gated, ECB is live — WL CCM API is TWO-PHASE, and the CCM era is TWO-KEY
8. `HAL_GetTick()` is frozen in STOP2 — a tick delta measures active time only, never wall time, so use wall-seconds
9. `vcap_voltage` is honest mV of VDDA, NOT the EDLC Vcap — the rail says nothing about stored energy, so all three thresholds on it are degenerate
10. `BIO_STATUS_VM_ERROR = 0x60`, not 0xFF — it must survive the panic-bit mask (`& ~PANIC_FLAG_BIT`) as status 3 with zero growth points
11. OTA wire has two layers with different headers — LoRa Queen→Soldier and CoAP Rails→Queen — and a length is never guessed from padding
12. cppcheck version-skew: a green local lint proves NOTHING about CI
13. Enabling compile-coverage of a gated block = wire ALL its board-freeze deps FIRST; only the ARM `hal_check_ccm` lane compiles the gated branch — and, for the Soldier, `soldier_lora_e5_gated` links it — so build both locally (`firmware/.toolchain/`, gotcha 7.4) before pushing, or each miss is a separate red CI push
14. The audio window is gone with the piezo (HW.30, 2026-09-29) — but its HAL fact outlives it: `HAL_ADC_Start_DMA` dereferences `hadc->DMA_Handle` before any check, so an unlinked DMA is a NULL write → HardFault, not `HAL_ERROR`
15. A `--assert` model is trusted TWICE — as a gate and as a READING — and the two fail in opposite directions; the day you drive it past its design point, both failures surface at once
16. Two chips, one family: the node board carries STM32WLE5CC (UFQFPN48), the bench carries STM32WLE5JC (UFBGA73 inside LoRa-E5) — the build targets `STM32WLE5xx`, so the compiler cannot tell them apart, and the PINS can
17. A mutation probe on the host lane can run the PREVIOUS binary, because make judges MTIME and not CONTENT — so force the target with `make -C firmware/test -B <target>`
18. The Flash-KV base is ONE gate expression over THREE sites — declaration, mount, compact — so a new journal consumer joins the expression, never a site
19. A host test that exercises a HAND-COPIED `main.c` function proves the copy, not the firmware — so when you touch a `main.c` function that `firmware/test/` mirrors, move its logic into a pure header both include, instead of editing both copies
20. `Radio.Send` is asynchronous — the frame is still in the air for its whole time-on-air, and ANY next radio command (Send · Rx · SetTxConfig · Sleep) aborts it; so every frame goes through `Lora_Phy_Send`, and its return value is a WAIT, not a status
21. `radio_conf.h` does not exist yet, and the ST template it will be born from sets `RF_WAKEUP_TIME` to 1 ms — shorter than our TCXO's start, so a copied template leaves the radio without a clock on every wake
22. Standby — the ratified sleep target, gated `FW54_STANDBY_ENABLED` — wakes through a RESET: `main()` starts over and ALL SRAM is gone, so a `static` added to `firmware/soldier/main.c` silently restarts from its initializer on every wake after the flip
23. A power mode or HAL call taken from an app note, a forum or another STM32 family may not exist on WL — and a grep of the vendored tree can still hit its name
24. On the cycle the radio sleeps in ONE place — the first statement of Phase 5 (`phase5_kenosis:`; the PVD callback is the only other site) — and every path into low power must pass it; a `goto` past it or a TX after it leaves the radio in STDBY_RC, 0.7 mA against 140 nA of sleep, and `Set_Sleep` is accepted only from Standby, so a live receiver ignores it
25. A byte of the CCM plaintext has MORE THAN ONE WRITER — the panic path packs its own literals into the same 14 bytes the telemetry path fills, so re-homing a byte is an audit of every call site of `Soldier_Build_CCM_LoRa_Packet` and of every backend reader of that byte, not an edit of one `Pack_*` helper
26. Sleeping from INSIDE an interrupt with WFI wakes only on an interrupt that can PREEMPT it — at the highest priority nothing can, so the board sleeps until reset
27. The PVD rescuer writes DR1 = 0 — ALWAYS, not only mid-commit
28. FEC on LoRa is the code rate, not a new layer: CR 4/5 and 4/6 only DETECT inside a packet, 4/7 and 4/8 correct one bit, and one constant switches them — `LORA_PHY_CR` in `firmware/common/lora_phy.h`
29. A TX gate that judges the FRAME — dedup of «similar» frames, novelty, importance, utility — is refuted, not pending: it adds no gate over cadence and `m(Δt)`, and it silences the very beat the server reads growth from
30. A stale error flag in `FLASH->SR` fails the NEXT Flash operation in WL-HAL without executing it — so Flash glue clears `FLASH_FLAG_SR_ERRORS` after unlock, before every program or erase
31. A dw that a reset or a power loss tore mid-program can read on WL with an ECC double error — `FLASH_ECCR.ECCD` and an NMI — and the vendor `Default_Handler` spins, so the readers of runtime-written pages go through `Silken_Flash_Read_Dw` (`firmware/common/flash_eccd.h`), which returns 0 for it — all but the mruby VM's raw read of the contract body

<!-- /FIRMWARE-GOTCHAS-INDEX -->

## Source Files

| File | Role |
|------|------|
| `firmware/soldier/main.c` | Sensor node: sense → Lorenz → encrypt → TX (multi-phase STOP2 loop) |
| `firmware/queen/main.c` | Gateway: RX → decrypt → CIFO cache → batch flush via CoAP (CCM-ера gated: blind courier — air-кадр (30B wire-rev2.2) НЕ розшифровується, запис air+1 via `rx_route.h`) |
| `firmware/queen/*.h` | Queen-only pure headers (host-tested): `at_engine`/`coap_pdu`/`sim7070_coap` (FW.3/FW.56 модем-труба + `Sim7070_Read_Csq` + `Sim7070_Ensure_Lte_Only` — HW.31 ворота «лише LTE» перед першою RF-командою flush'у; init-команди поза ними flush НЕ повторює), `sim7070_udp` (FW.60 сира CA*-розмова poll-тракту: `Sim7070_Udp_Fetch`, CARECV-заголовок посимвольно; механіка poll'а = `Queen_Poll_Downlink` main.c — канон `03_02 §4а`), `uart_rx_ring`, `ota_window` (FW.52б), `ota_sha_guard` (FW.52 SHA-256 cross-check на Magic Re-Request по закритому OTA-вікну — Queen's ВЛАСНА сторінка 125 [номер збігається з Soldier-івською 125 (KPUB/KEYB, `03_01 §2.3`) — інший чіп, не колізія, але завжди читай «сторінка 125» з іменем чіпа поруч], magic-last; свідомо сиблінг `firmware/common/flash_ota.h`, не reuse), `rx_route` (FW.2 роутер 16/air + запис air+1), `cifo_cache` (FW.3/E.8 edge-кеш: слот `EdgeCache`, priority-aware витіснення й облік `cache_count` — `main.c` лишає собі масив і ARCH.35-хук спілу, тест кличе справжній код; gotcha 19), `soldier_cmd_queue` (FW.20-Q2 · FW.17: адресна черга готових CCM-кадрів — лише структура, постріл за почутим DID, порядок за DLFC), `sim7070_init` (HW.41 init-послідовність модема таблицею + `Sim7070_Init_Run` — її кличуть і `main.c`, і тест, гоча #19; `QUEEN_APN` живе тут), `tx_duty` (FW.61 лімітер робочого циклу TX: ≤ 36 с у будь-яку годину, резерв маяка; кожен P2P-кадр — `Tx_Duty_Allows` ДО `Lora_Phy_Send`, `Tx_Duty_Charge` після; епізод LoRaWAN-детуру — стелею свого ефіру `Helium_Mac_Episode_Air_Max_Ms`, бо смуга в них одна (ARCH.34); канон `03_02 §5`), `ota_rerequest_table` (FW.68 борг перепитувань `0x55`: зойк лише ЗАПИСУЄТЬСЯ, а віддається рефлекс-пострілом по блоку на наступні кадри того ж DID — вухо Солдата бере один пакет, а після зойку він спить; дедупу свідомо немає — канон `03_02 §5.1.3`), `coap_iv` (SEC.12), `pull_mac` (SEC.38 MAC запиту `m=` · FW.60 тег poll-ВІДПОВІДІ, звіряється до розшифрування, і nonce `n=` у кожному запиті — golden-вектори спільні з `Downlink::PullMac`; KEYC із нулів запиту не складає), `cmd_token` (FW.60/FW.63 — locator of the idempotency token = the LAST field of the CMD envelope; host-pinned in `test_queen_logic.c`; gotcha 1c), `helium_sos` (ARCH.34: 12B SOS-wire byte-parity з `HeliumSosWorker` + тригер + бюджет сліпоти; MAC-шов `Helium_Mac_SendSos` = adapter у `firmware/queen/lorawan_glue/helium_mac.c`; ⚠️ поріг тиші SOS = 2× каденс флашу — заголовок несе лише `#ifndef`-дефолт для host-тестів, справжній каденс підставляє `main.c` з `FLUSH_INTERVAL_MS`+jitter і `_Static_assert`ить нерівність: фіксоване 30 хв було МЕНШЕ за 60-хв каденс і кричало на здоровій Королеві при N ≈ 45–160 (⚖️ 2026-09-10) — той самий клас, що #13(a): pure-заголовок, який дзеркалить константу main.c, мусить мати `#ifndef` і static-assert, не число) |
| `firmware/bio_contracts/` | mruby contracts (run on MCU), one per wire era with its OWN entry point: `bio_contract.rb` — ECB, Lorenz, `calculate_state` (9 args); `ccm_contract.rb` — CCM, no Lorenz, `ccm_state(pt)` = 14 B plaintext → status byte (ABI frozen at the FW.2 flip, ⚖️ FW.66 S4 — `03_04 §6`); `metabolic_core.rb` — the ONE device home of the GP formula, compiled first into BOTH (`tools/firmware/gen_bytecode.sh` → `firmware/common/{lorenz,ccm}_bytecode.h`) |
| `firmware/common/*.h` | Shared One-Home libs — header-only except `flash_kv` · `flash_ota` · `flash_ring` · `logmel` (`.h` + `.c`; ⚠️ «common» тут — місце, не споживач: `flash_ring` — ARCH.35 кільце телеметрії КОРОЛЕВИ на SPI NOR W25Q32JV, на Солдаті й bench-carrier mini SPI NOR немає, тож носієм запису Солдата він не є; носій логера П3 — `logger_journal.h`, `00_07` FW.70) — compiled into BOTH firmware + host tests (kill the mirror-drift pattern): `silken_sha256.h` (SHA-256/HMAC, FIPS/RFC KAT), `lorenz_seed.h` (FW.30 cold-start deriv), `silken_crc.h` (CRC16-CCITT, OTA), `lora_ccm.h` (CCM packet), `downlink_ccm.h` + `downlink_ccm_open.h` (FW.17 адресна команда Rails → Солдат під сесійним ключем цілі: довжина за опкодом, нонс із байтом напрямку, реконструкція DLFC; відкриття — HAL-половина, як `ccm_selftest.h`), **`lora_phy.h`** (FW.61 базлайн модуляції raw-LoRa P2P — pure, БЕЗ `Radio`, тож його включає й `cad_sniff.h` у host-тестах; дім номіналів `03_05 §2.1`, модель airtime `tools/firmware/lora_airtime.rb`; потужність TX — стала РОЛІ `_SOLDIER` 14 ⊥ `_QUEEN` 10 під `_Static_assert` стелі ЕВП, ⚖️ 2026-09-24 — гоча #1(c)) + **`lora_phy_apply.h`** (той самий профіль → драйвер: `Lora_Phy_Apply_Tx/Rx`, єдиний шов, ЄДИНИЙ файл у `common/`, що тягне вендорський `radio.h`; ⛔ не зливати з pure-половиною), `tx_defer.h` (FW.10 Cold-TX: `Should_Defer_TX` — freeze-contract на `<` −15°C/4000mV, host-gated One-Home; раніше тест-локальний дубль = false-green; ⚠️ [ARCH.99] Vcap-половина у полі НЕ розрізняє — див. гочу 9), `adc_convert.h` (FW.50 VREFINT-cal ADC→mV; wired: `vcap_voltage = Adc_Vdda_Mv(...)` — VDDA-mV, not EDLC-Vcap; `Adc_Temp_C` — °C from the MEASURED VDDA, reference via `Adc_Temp_Ref_Mv`, gotcha 9), `queen_attest.h` (L1 QATT **v2** signed-batch envelope + 8B health-блок пульсу — ARCH.54; wire home `03_05 §2.2`; residue 1, ct=0 heartbeat легальний), `flash_eccd.h` (FW.70 · ARCH.28 HAL-половина: `NMI_Handler` на ECC double error внутрішньої Flash + `Silken_Flash_Read_Dw`, що віддає порваний dw як 0 — через нього читають Flash-KV, журнал логера, перевірку RITE контракту й OTA-SHA Королеви, а обробник повертається лише під час цього читання; визначає вектор, тож включають лише обидва `main.c`, host-тести — ні — гоча #31), `flash_kv.h`+`fc_hiwater.h`+`ota_antirollback.h` (journal Flash-KV база + FC/OTA-version high-water — SEC.20 anti-rollback ключ 0x15, строго `>`; база винесена з-під фіч-фліп-гейтів: один вираз `FLASH_KV_BASE_ENABLED` (`firmware/soldier/main.c`) на три сайти — декл · mount · **compact**, `SEC20_OTA_ANTIROLLBACK_ENABLED 1` у ньому під `#error`-піном (Put32 НЕ auto-компактить — гоча #18)), `fw_report.h` (SEC.20 wire-звіт contract-стану `[semantic:1|reverted:1|hiwater&0x3FFF]` — байти 12..13 legacy / CCM байт 11 (wire-rev2.2); ⚠️ `FIRMWARE_VERSION_ID` = compile-const C-образу, на дроті її БІЛЬШЕ НЕМА — bytecode-OTA її не міняє), `stack_canary.h` (SEC.21 guard-сів, I-CG: ніколи не нуль; власні `__stack_chk_fail` у обох main.c — Soldier слід DR0[10], Queen reset-only), `mpu_regions.h` (SEC.21 MPU-draft: 3 регіони + SRD-трюк, RW рівно стор. 122-127; гейт `SEC21_MPU_ENABLED` компілиться в hal_check_ccm, trap = bench), `device_event.h` (SEC.21 uplink 0x57 — 2 шари: Шар1 Soldier→Queen ECB-кадр (canary-trip DR0[10]); Шар2 Queen→Rails підписаний L1-конверт `[ver\|ts\|count\|records\|sig]` тег `SLKN-QEVT1` — Королева витягує cleartext і підписує EDSK, Rails verify gateway-origin, LoRa-ключа НЕ торкається; дім `03_05 §2.2а`), `ota_rerequest_wire.h` (FW.27-B · FW.68 зойк `0x55`: розкладка, сентинел печатки `0xFFFF`, будівники й рішення про тишу — спільний Солдату, Королеві й host-тестам), `standby_wake.h` (FW.54 цільовий сон Standby: рішення «пробудження ⊥ холодний старт» за C1SBF AND власний маркер пробудження (DR7, пише перший крок входу — FW.66 (Б) · S5) + порядок входу через ops-шов; гейт `FW54_STANDBY_ENABLED` компілиться в hal_check_ccm — гоча #22), `ema_filter.h` (FW.21 EMA пульсу delta_t/vcap, α 2/10 у цілих ×100/×10: стан `SilkenEma`, `EMA_Feed` пропускає сентинел, пакування DR12 — `main.c` тримає лише `soldier_ema` і HAL-читання/запис; delta_t-половина = вхід балів CCM, тож теплу гілку дзеркалить сервер — `Telemetry::EmaRecurrence`, SEC.42 (б); його спек читає α звідси й golden-таблиці з `test_soldier_logic.c`, тож однобічна зміна червонить іншу сюїту), `reset_cause.h` (FW.59 декодер `RCC_CSR` → 3-бітний код, спільний Королеві й Солдату, + `Silken_Reset_Cause_Resolve` — яку причину несе кадр Солдата: на ребуті декодер, на пробудженні зі Standby — стан із DR0), `soldier_dr0.h` (розкладка DR0 Солдата й ЄДИНИЙ пакувальник для всіх його писачів; канон — `03_01 §2`), `logger_journal.h` (FW.70 сторінковий журнал логера П3 у внутрішній Flash mini: пара вимірів у dw, явний слот, якорі часу, кільце, декодер у CSV — формат і межі в шапці; шов `LogJOps`; якір BOOT заряджають на старті, а лягає він перед першим записом старту) + `logger_console.h` (FW.70 консоль логера: рядок UART → `T` · `D` · `S` · `Q`, запис часу судить перечитування; шов `LogCOps`; руки — `Logger_Boot` у `main.c` під `FW70_LOGGER_ENABLED`, де `set_time = NULL`: календар Солдата — база `delta_t`, писати його повз `Silken_Beacon_Commit` не можна — SEC.42, `tools/firmware/check_sec42_calendar.py`), `bme280.h` (HW.32: компенсація Bosch, VPD FAO-56, forced-mode через шов `Bme280_Ops` і `Bme280_Sense` — ОДИН замір із ключем живлення для кадру CCM і бенч-POST; руки — `main.c` під одним виразом `BME280_GLUE_ENABLED`, шина й пін ключа — glue плати; гоча #4 ⊕ — сенсор не будять для кадру, що не полетить), `*_selftest.h` + `*_kat_vectors.h` (bench POST) |
| `firmware/hal_glue/` | `{soldier,queen}_hal_check.c` — OBJECT-обгортки `main.c` з порожніми MX-заглушками (ARM compile-lane, лише компіляція); `boards/lora_e5/` — образ Солдата для bench-carrier LoRa-E5 mini (`soldier_lora_e5`, FW.46): справжні MX/MSP-тіла, лінкер-карта під сторінкою 104 (104–121 — журнал логера FW.70, `ASSERT` лінкера проти `_Static_assert` у `main.c`), консоль логера на USART2 (`FW70_LOGGER_ENABLED`, обидва образи mini), заглушка радіо, бенч-POST-и `CCM_SELFTEST` і `BME280_SELFTEST` (HW.32: I2C2 + ключ `PB10`; читає `firmware/scripts/bench/02_selftest_attest.py [--bme]`) — ЛІНКУЮТЬ лише він і його близнюк `soldier_lora_e5_gated` (той самий образ із гейтованим набором `hal_check_ccm`, один список `SILKEN_GATED_DEFS`), тож посилання без дефініції бачать лише вони; локальний лінк на darwin — порожні архіви `libssp` (гоча #7 (4)); межі зрізу — шапка `soldier_lora_e5.c` і `03_01 §12.4` |
| `firmware/test/` | x86 host-based tests — `make -C firmware/test` (host gate; not gcov-instrumented — per-line coverage gaps → best-TU трюк `[[reference_firmware_coverage_gcov_gotcha]]`). **`make -C firmware/test asan`** = ASan+UBSan dynamic memory-safety lane (TEST.5, CI-gating in `firmware_test` — keep it green; canon `04_06 §B.1.1`). New crypto in `common/` ⇒ add a parity test vs OpenSSL, don't re-copy logic into the test file. |
| `firmware/extern/subghz-phy` | Vendored `stm32-mw-subghz-phy` @v1.5.0 (FW.46 Шлях A): `radio_driver/radio.h` = THE Semtech API both main.c compile against (owned stub deleted; both register a **static** `RadioEvents_t` — driver keeps the pointer). `radio.c` NOT compiled until `radio_conf.h` exists (.ioc board-freeze); ⚠️ its `lorawan/` dir is the **LBM radio layer** (SWL2001 support: smtc_ral/ralf, radio_planner, SPI chip drivers) — NOT a MAC stack; the ARCH.34 LoRaMac-node = separate submodule `firmware/extern/stm32-mw-lorawan` @v2.6.2; its `Conf/*_template.h` are CubeMX-fill templates → owned copies live in **`queen/lorawan_glue/`** (EU868-only profile, soft_timer/systime pure-cores, `helium_mac.c` adapter — episode = fresh OTAA join, DevNonce = the ONLY cross-join persist via MIB_NVM_CTXS→flash_kv 0x30). Host-smoke of the REAL MAC on a stub radio: `make -C firmware/test helium_mac_smoke` — full OTAA join+uplink cycle vs an in-test mock-LNS (crypto-valid JoinAccept on the zero-key se-identity; server-side MIC + FRM parity with LNS-derived session keys; deadline = the real 20s blind budget at SF12-TOA) + a crypto-valid 23B JoinRequest + DevNonce monotonicity/KV-reboot. The mock needs `-DAES_DEC_PREKEYED` (smoke-target-only — the server ENCRYPTS JoinAccept with AES-decrypt; mirrored in `firmware/.clangd`). ⚠️ `Helium_Mac_Bind_Nvm` keeps the pointer forever — bind only a static/file-scope FlashKv (ASan stack-use-after-scope class). ⚠️ The recipe links **`-lm`**: `RegionCommon.c` calls `floor()`, and the **coverage lane's `-O0`** (`make coverage`) does NOT inline it as a builtin the way `-O1` (asan) / `-O2` (normal) do → a green local `helium_mac_smoke` + `asan` still red-CIs on coverage without it (the class: a vendored-math TU needs explicit `-lm`; `make coverage` is the only lane that catches it). ARM targets: `lorawan_mac_check` (glue+MAC) builds in the CI HAL compile-lane beside `hal_check hal_check_ccm` since 2026-09-27 (until then NO step built it, and by hand it failed on `stm32wlxx_hal_conf.h` — the target lacked `hal_glue` in its include paths; FW.65); `hal_check_ccm` (CI, and locally — gotcha 7.4) compiles the gated Queen KV-mount block (ARCH34_HELIUM_ENABLED=1). The submodule is OUR FORK `Alexey-Lukin/stm32-mw-lorawan` @v2.6.2-silken.1 — v2.6.2 + one fix: `RegionCommonComputeSymbolTimeLoRa` SF11/SF12 signed-overflow (upstream Semtech master has the same hole; UBSan found it, upstream-PR = `00_07` ARCH.34 👤). Bumping the submodule → re-check that fix survives. Include-path lives in CMake hal-lane + `firmware/.clangd` (change one → sync the other) |

| `tools/firmware/*.rb` | Pure-Ruby моделі енергії й ефіру (no Rails, no bundle), кожна з власним `--assert` і CI-кроком у `docs.yml`: `lora_airtime` (ToA за Semtech; ⊕ читальний `sf-sweep[=<байт>]` — ціна SF без зміни профілю) · `tx_cadence_budget` (`--levers` на чинних входах друкує запас стоку VSTOR і важелі (г)/(д) розвилки ARCH.8; (а)–(в) — лише під override, що кладе CCM за підлогу) · `boot_brownout_cycle` (зимове вікно `VBAT_OK`, HW.44; ⊕ вікно VOC проти того ж буфера й стеля LPTIM-пробудження, HW.19; ⊕ прочитання ESR іоністора під кадром — warn-only, `esr_ohm`, `02_03 §12.1`) · `bq25570_dividers` · `uncertainty_budget` · `scc_rate`. ⛔ Спільна арифметика сон-стіку/годинних перерахунків живе в `tools/firmware/lib/energy_chain.rb` — прилади свідомо НЕ злиті (різні питання, різні стелі), інтерфейс іменований, щоб зимовий ККД boost'а не підмінявся річним |

> Line counts drift every commit — don't hardcode them (see `[[feedback_no_volatile_counts]]`); `wc -l` if you need a number.

## Common Tasks

- **Add sensor field**: Soldier Phase 1 ADC → pack in `lora_payload[]` → Queen `Process_And_Cache_Data` → `Flush_Cache_To_Rails` → Rails `TelemetryUnpackerService` unpack string → host tests. Check the budgets first: a wire byte → a row in the `03_05 §2.1` wire-budget ledger before it is promised (headroom after rev2.1 = 0); RTC-persisted state → gotcha 2.
- **Change Lorenz params / `bio_contract.rb`**: ⚠️ under ⚖️ branch (Б) (`00_07` FW.66, 2026-10-05) Lorenz leaves the device with its implementation — this recipe holds until then, and after it the device half is gone (`03_04 §7.3`). Edit `bio_contract.rb` AND `app/services/silken_net/attractor.rb` → run parity tests (must stay bitwise-identical, Float IEEE-754 both sides). **Three hidden gates a subset-run misses** (the first two tripped in E.63 + E.64): (1) regenerate BOTH mirrors (`tools/firmware/gen_bytecode.sh` → `lorenz_bytecode.h` · `ccm_bytecode.h`; the GP formula lives once in `metabolic_core.rb` and feeds both) — the **FW.46 sha256 stamp-gate goes red if either is stale**, and the CCM contract must stay under the OTA ceilings (FW.67 pin in `deployment_dispatcher_service_spec`); (2) a signature change → grep **`spec/` too** (not just app/lib — once missed 6 integration-spec callers) + run the **FULL `bin/rspec`**, never a subset, before pushing a contract/DCI change; (3) the SHA-pins `lorenz_core` / `metabolic_gp_core` in `lib/canonical_block_pins.yml` — `bin/rails docs:check_refs` stays red until the mirrors listed there are reconciled and `rake docs:repin` is run.
- **Change seed/cold-start crypto**: edit `firmware/common/lorenz_seed.h` / `silken_sha256.h` ONCE (shared) → `make -C firmware/test seed_derivation` re-proves parity vs OpenSSL + backend `SeedDerivation`. Never fork the math into the test file.
- **Modify AES**: touch `MX_CRYP_Init()` in BOTH files, update `Load_AES_Key()`/`Load_Broadcast_Key()`, `Restore_ECB_Mode()`, host tests — and preserve the two-key scoping contract (gotcha 7.3; guarded by `test_ccm.c::test_two_key_scoping_contract` + KEYB-load tests in `test_soldier_logic.c`). On a bench, silicon is attested by the `CCM_SELFTEST` build + `firmware/scripts/bench/02_selftest_attest.py` (RUNBOOK §2.1–2.2) — it catches the `CRYP_DATATYPE_32B` word-swap class invisible to host mocks; `make -C firmware/test selftest sym_selftest` only proves the self-test logic + KAT vectors on the OpenSSL mock. New factory key slot? Mirror it in `FactoryFlashing::CommandBuilder` + `03_06 §2` (page 124 = per-device identity, page 125 = cluster membership KPUB/KEYB) — and mind that every factory run ERASES each page a slot touches: a slot on a runtime-written page (Soldier 122–123 KV / 126 contract, Queen 125 OTA-SHA / 127 UID) would wipe it (factory-flashing gotcha #11).
- **Touch RTC-persisted state**: update the `03_01 §2` canonical table FIRST (SSOT), add `isfinite()`/magic/range restore guards, then ≥3 host tests (cold-boot / warm-roundtrip / corruption-fallback).

Files in this skill

  • SKILL.md16.5 KB
  • gotchas.md21.7 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in business →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.