diff --git a/.gitea/workflows/bench-pages.yml b/.gitea/workflows/bench-pages.yml deleted file mode 100644 index 86a31154..00000000 --- a/.gitea/workflows/bench-pages.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: public-benchmark-pages - -on: - workflow_run: - workflows: [build-test-release] - types: [completed] - workflow_dispatch: - -concurrency: - group: alkane-toolkit-public-benchmark-pages - cancel-in-progress: false - -jobs: - publish: - runs-on: alkane-verify - container: - image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5 - permissions: - contents: read - steps: - - uses: actions/checkout@v4 - - name: Install SSH client - run: bash ci/ensure-build-deps.sh ssh - - name: Render measured benchmark history - env: - GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} - run: python3 ci/bench_history.py render - - name: Publish public benchmark page - env: - GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} - BENCH_PAGES_DEPLOY_KEY: ${{ secrets.BENCH_PAGES_DEPLOY_KEY }} - run: python3 ci/publish-bench-pages.py toolkit - - name: Clean generated page - if: always() - run: python3 ci/cleanup-generated.py diff --git a/.gitea/workflows/pages.yml b/.gitea/workflows/pages.yml new file mode 100644 index 00000000..f9af984d --- /dev/null +++ b/.gitea/workflows/pages.yml @@ -0,0 +1,47 @@ +name: pages + +# The project site, https://blueflare.gitea.bluefla.re/alkane-toolkit/ : +# overview, user manual (docs/manual), code-quality dashboard (from the +# quality record main CI publishes with the badges) and benchmark history. +# Rebuilt after every main build-test-release run and published to this +# repository's gh-pages branch. +on: + workflow_run: + workflows: [build-test-release] + types: [completed] + workflow_dispatch: + +concurrency: + group: alkane-toolkit-pages + cancel-in-progress: false + +jobs: + publish: + runs-on: alkane-verify + container: + image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5 + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + - name: Install page tools + run: bash ci/ensure-build-deps.sh pages + - name: Render measured benchmark history + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 ci/bench_history.py render + - name: Fetch measured quality record + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 ci/fetch-quality.py quality.json + - name: Build site + run: | + python3 ci/build-pages.py --out site --quality quality.json \ + --bench bench-site/index.html --sha "$GITHUB_SHA" + - name: Publish site + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 ci/publish-pages.py site + - name: Clean generated site + if: always() + run: python3 ci/cleanup-generated.py diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 10df1e5c..2c06e3ff 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -271,8 +271,10 @@ jobs: set -euo pipefail rustup component add llvm-tools-preview >/dev/null 2>&1 || true [ "$(cargo llvm-cov --version)" = 'cargo-llvm-cov 0.8.7' ] - PCT=$(bash ci/coverage.sh --summary-only \ - | awk '/^TOTAL/{gsub(/%/,"",$10); print $10}') + # Keep the whole table: gen-badges turns it into the per-crate and + # per-file breakdown on the Pages quality dashboard. + bash ci/coverage.sh --summary-only | tee coverage-summary.txt + PCT=$(awk '/^TOTAL/{gsub(/%/,"",$10); print $10}' coverage-summary.txt) [ -n "$PCT" ] || { echo "coverage report produced no TOTAL line" >&2; exit 1; } echo "pct=${PCT}" >> "$GITHUB_OUTPUT" echo "line coverage (tests + self-test): ${PCT}%" @@ -300,7 +302,8 @@ jobs: python3 ci/gen-badges.py --tests "$PASS" \ --coverage "${{ steps.cov.outputs.pct }}" \ --bench-coverage "${{ steps.benchcov.outputs.pct }}" \ - --bench-delta "$BENCH_DELTA" --clippy clean + --bench-delta "$BENCH_DELTA" --clippy clean \ + --coverage-summary coverage-summary.txt - name: Publish measured badges env: diff --git a/.gitignore b/.gitignore index 6b41dc3c..5dbf7a62 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,8 @@ **/target .claude/ __pycache__/ +# Internal working notes live outside this public repository. +/AGENTS.md +/HANDOFF.md +/CLAUDE.md +code-review-report*.md diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index ed159b41..00000000 --- a/AGENTS.md +++ /dev/null @@ -1,62 +0,0 @@ -# AGENTS.md - alkane-toolkit - -Short standing orders for working in this repo. Read `HANDOFF.md` first on any -resume; it names the live threads. Parent project rules live in -`../AGENTS.md` (bench discipline, live-fleet-ops). - -## Build / run (this machine) - -- Never build or run inside the synced repo tree (noexec, slow FS). Cargo target - is `~/.cache/alkane-tk-target` (set in `~/.cargo/config.toml`, not committed); - wx builds go to `~/.cache/wxbuild` / `~/.cache/wx-3.3.3-linux`. -- `scripts/build-wx-linux.sh` (once) then `scripts/build-gui-linux.sh` (release). -- CI sets `CARGO_TARGET_DIR=target` and removes target, coverage, bench, and - release staging after each job, including failed runs. For local builds, - run `scripts/clean-old-builds.sh` at the end of each task; keep only the - current release binary and the pinned wxWidgets cache. -- The GUI is pure-Rust wxWidgets on the vendored, patched `wx-rs` - (`thirdparty/wx-rs/wx-rs-0.2.0-patched`). When you change it, record the - change with `python3 scripts/wx_rs_patches.py capture NAME "Subject"` and - commit both; CI runs `scripts/wx_rs_patches.py check`. -- OS differences in Rust go in `alkane_core::platform` (config dir, private - files, null device, console-less helper processes), not inline `cfg`s. - -## Development / review / visual-feedback loop - -Every UI change goes through this loop before it is considered done: - -1. Edit, then `scripts/ui-selftest.sh` -- builds and runs the app headless in - `ALKANE_SELFTEST` mode: it renders the bench-fleet fixtures through the real - widgets and compares the table cells + KPIs to the expected hardware output. - Non-zero exit = a regression. Also run `cargo test -p alkane-gui --offline` - for the transform-layer unit tests. -2. `scripts/ui-screenshot.sh out.png` -- captures the running UI to a PNG on a - private Xvfb display (never the real desktop). Defaults to the offline - fixtures (`ALKANE_FAKE_SCAN`) so the shot is deterministic; `--live` scans - the network. Eyeball the PNG for layout regressions. -3. Only after both pass, wire in real hardware (a live scan) per parent rules. - -Headless X gotcha: the GTK window only maps under Xvfb with `GDK_BACKEND=x11` -set; without it the app runs but never shows a window. The scripts set it. - -Windows: `scripts/build-gui-windows.sh` cross-builds the `.exe`; -`scripts/ui-selftest-windows.sh` runs the same self-test under Wine, and -`. scripts/windows-cross-env.sh` lets `cargo test --target x86_64-pc-windows-gnu` -run the unit tests under Wine. Bridge (C++) changes must work on both wxGTK -and wxMSW, where the table is wx's generic data view; see docs/windows.md. -Real-Windows checks use the Win11 VM (docs/windows.md, "Native Windows runner"). - -## Offline modes (no hardware needed) - -- `ALKANE_FAKE_SCAN=1` -- feed `crates/alkane-gui/src/fixtures.rs` (the 9 bench - boards' expected output) instead of scanning. Use for demos and screenshots. -- `ALKANE_SELFTEST=1` -- run the workflow self-test and exit (see the loop). - -Keep the fixtures in step with the bench inventory (`HANDOFF.md` section 7). - -## Conventions - -- Keep discovery, protocol parsing, artifact checks, flash safety, and GUI runtime in Rust. Use Python for CI, release, reporting, and host tests only. -- Confidence tags (CONFIRMED/DERIVED/EXTERNAL) on doc claims; cite file paths. -- Single-line imperative commit summaries. -- No emojis in any file (parent-project + global rule). diff --git a/HANDOFF.md b/HANDOFF.md deleted file mode 100644 index 5772409a..00000000 --- a/HANDOFF.md +++ /dev/null @@ -1,144 +0,0 @@ -# HANDOFF — alkane-toolkit - -**For:** resuming this work in Claude Code (or any fresh agent session). -**Read order:** this file → `docs/IMPLEMENTATION-PLAN.md` → `docs/UI-SPEC.md` → `docs/adr/000{1,2,3}*.md` → `README.md`. -Parent project: `~/Ultron/projects/miner-firmware/` (its `HANDOFF.md`, `AGENTS.md` and `MEMORY-SNAPSHOT/` hold the bench context and standing orders — read them before touching real hardware). - -## 1. What this repo is - -`alkane-toolkit` = cross-platform desktop toolkit (pure-Rust GUI on wxWidgets) -to install **stock or alkaneOS** on ASIC miner control boards, whatever they -currently run. Sibling repo `~/Ultron/projects/miner-firmware/alkane-sdk/` -owns the board doctrine (`docs/install-methods.md` = the invariants) and the -board metadata (`boards/*/board.yml`); this toolkit mechanizes those recipes. - -- Remote: `https://gitea.bluefla.re/blueflare/alkane-toolkit` (private, branch `main`, tip `b264cdd6`) -- GitHub is DEAD (account suspended): never touch github remotes; old ones are kept as `github-suspended` in sibling clones -- Gitea auth: token in `~/.config/gitea/token`, askpass helper `~/.config/gitea/askpass` (user `noah`, admin). For git: `export GIT_ASKPASS=~/.config/gitea/askpass GIT_TERMINAL_PROMPT=0` - -## 2. Current state (2026-09-15) - -**Ships today (M1 primary view):** -- Discovery via vendored **asic-rs 0.8.1** (MinerFactory::scan_stream over the configured CIDR list) -- UI-SPEC primary view: 6 KPIs (Total/Hashing/Slow/Not hashing/total hashrate/est. power), scan-ranges editor, Excel-style filter panel, columns panel, sortable + drag-reorderable table with row checkboxes, IP pinned first, default order hashrate → power → chip temp → cooling → firmware → pool worker → model/status -- Pure-Rust GUI on wxWidgets: vendored wx-rs 0.2.0 **extended by patches** (upstream stubs Linux and had no widgets) + vendored wxWidgets 3.3.3 (static monolithic GTK3) -- **Visually verified working** (off-screen Xvfb screenshots): table renders below the header full-width; all dialogs (Scan ranges / Filter / Columns) open, apply, and close without crashing; header-click sort, column hide, and row-checkbox all work. - -**Fixed 2026-09-15 (this session), with regression tests:** -- **Table rendered in the top-left corner** instead of below the header: the dvlc was created but never added to the sizer. `rebuild_table` now adds it to the root sizer (proportion 1, EXPAND) and re-runs the panel layout; `add_stretch(1)` (which ate all vertical space) removed. -- **App crashed (abort) on most buttons**: the dialog `root` sizers passed `ALIGN_CENTRE_VERTICAL` to a *vertical* sizer, tripping a wxWidgets consistency assert whose default handler pumps a nested event loop; the 1 s scan timer then re-entered the single `dispatch` while it still held the `App` `RefCell` borrow → `RefCell already borrowed` → non-unwinding panic → abort. Fixed the invalid flags, and hardened `dispatch` into two phases (build under the borrow, `show_modal` outside it) with `try_borrow_mut` so any future nested re-entry drops the event instead of aborting. -- Header-click sort mapped the clicked column through `view.order` (wrong when a column was hidden) → now maps through `display_columns()`. Drag-reorder likewise (`ViewState::apply_visible_reorder`, splices visible order back into the full order so hidden columns are never dropped). Row-selection checkbox now survives a table refresh. - -**Feature round 2026-09-15 (operator requests, verified by live bench scan + selftest):** -- Redesigned KPI header: colour-coded cards (green Hashing / amber Slow / red Not hashing / blue Hashrate), big value over small label, theme-aware. -- Light/dark mode follows the system (wxSystemSettings + `set_appearance_system`); custom KPI colours adapt. -- SI-formatted hashrate/power everywhere (KPIs + columns): prefix chosen so the mantissa is 1-999, 1 decimal below 100 (e.g. `685 TH/s`, `21.3 kW`, `95.0 TH/s`). Note: strict "<=2 digits" would render 685 TH/s as `0.7 PH/s`; the 3-sig-fig form reads better - flag if you want the strict form. -- Scan ranges accept CIDR, single IP, `A.B.C.D-E.F.G.H` full ranges, and `A.B.C.D-N` short ranges (`scan::parse_line`). -- Scan progress bar across the top of the table + status-bar text (`scan_stream_with_ip` gives per-address progress); the inline "scan done" text is gone. -- Out-of-range miners are dropped when a scan starts (rows retained by the new target set). -- Columns panel exposes **every** scannable `MinerData` metric (~30, model.rs `Column`), with All / None / Defaults. -- Excel-style filter panel built out: per-category value checklists (numeric columns excluded), per-column All/None, Apply/Reset/Cancel, "(blank)" handling. -- Sort direction shown as an ASCII marker in the header (`^`/`v`); native `SetSortOrder` was rejected because it re-sorts the store lexically and fought the numeric sort. -- Double-click a row opens `http://` in the default browser (`wxLaunchDefaultBrowser`). -- Filter panel horizontal layout can get wide with many category columns (no scrolled-window in the bridge yet); it is resizable. Live text-search within a filter column is not implemented. - -**Feature round 2 (2026-09-16, operator requests):** -- Scan-ranges button is a fixed "Scan ranges" label (no longer grows with the ranges). -- Dark-mode KPI cards fixed: colours derive from the live system theme luminance (`palette()` reads `system_color`), not `is_dark()` which mis-detected some GTK dark themes. -- Checkbox column removed; the table is multi-select (`wxDV_MULTIPLE`, ctrl/shift-click), selection tracked by IP so it survives scan refreshes. -- Rescan replaced by Play / Pause / Stop; auto-rescan interval editable in the scan-ranges dialog (`scan::load/save_auto_secs`, `~/.config/alkane-toolkit/auto-rescan-secs.txt`). Timer-driven scheduler with a countdown. -- Status bar shows the last-probed IP during a scan and a countdown to the next scan when idle (no more "scan complete" text). -- Default sort is IP-ascending with a header chevron; IP is column 0 and sortable. -- Choose-columns dialog is a `wxRearrangeCtrl` (check to show, up/down or drag to reorder); exposes every metric incl. Pool 1/2/3 URL + worker (`MinerRow.pools`). -- Column drag-reorder in the table moves the whole column with its data on drop (native GTK shows only the header ghost during the drag - not changeable without a custom-drawn table). -- Row separation: `wxDV_ROW_LINES` (thin separators). GTK3's native dataview has no zebra striping (SetAlternateRowColour is generic-only; `:nth-child` CSS is GTK4-only). A `wxbr_apply_zebra_css` hook is in place for GTK4; true zebra on GTK3 needs a custom `wxDataViewVirtualListModel` with `GetAttrByRow` - deferred. -- `build.rs` now adds `pkg-config --cflags gtk+-3.0` so the bridge can call GTK directly. - -**Deferred - item 11 (right-click multi-config menu):** intersection-of-config context menu that writes to live miners via asic-rs `HasMinerControl`/`SupportsConfigs` (fault light, power limit, tuning, restart, pause/resume, pool config). The wx bridge for it (popup menu + context-menu event) is already in place; the apply-to-live-hardware layer + confirm-before-apply is the next round. - -**Dev / review / visual-feedback loop (see AGENTS.md):** -- `scripts/ui-selftest.sh` — headless workflow self-test: `ALKANE_SELFTEST` mode renders the bench-fleet fixtures through the real widgets and compares the table cells + KPIs to the expected hardware output (13 checks; exit non-zero on any mismatch). `cargo test -p alkane-gui` runs the transform-layer unit tests (10). -- `scripts/ui-screenshot.sh [out.png] [--live]` — off-screen (private Xvfb) screenshot for visual review; defaults to the offline `ALKANE_FAKE_SCAN` fixtures. -- Offline modes: `ALKANE_FAKE_SCAN=1` feeds `crates/alkane-gui/src/fixtures.rs` (the 9 bench boards) instead of scanning; `ALKANE_SELFTEST=1` runs the self-test and exits. -- Headless X gotcha: the GTK window only maps under Xvfb with `GDK_BACKEND=x11` set (the scripts do this). - -**Not done yet (open threads, in rough priority):** -1. Windows: DONE 2026-11-02 (docs/windows.md, ADR 0004) -- cross-built with mingw-w64, tested under Wine in CI and natively on the Win11 VM runner, released with every version. macOS still needs a Mac to link. -2. ARP/ICMP pre-pass for link-up-but-silent boards (M1 scope, spec'd in plan §5, not implemented) -3. Column order/visibility *persistence* to `ui.conf` (spec'd in UI-SPEC "Implementation notes"). Visibility (Columns dialog) and drag-reorder both work in-session; only the save/restore across runs is missing. -4. Sort-direction indicator in headers; per-model "Slow" bands (currently flat 80% of expected); model-derived power estimates for units that don't report wattage -5. M2: verify-image port (magic/min-size/integrity) + artifact registry expansion (`crates/alkane-artifacts/data/manifest-seed.csv` = 14 sha256'd bench artifacts; bulk archives 3.7GB/624MB not hashed) -6. M3+: first install pathway (zynq-7010 stock↔stock, proven on the bench S17), then per plan §7. Note **no alkaneOS build exists** (SDK boards all "bake"), so installs are stock↔stock only until the SDK produces artifacts. - -## 3. How to build / run (this machine) - -```sh -cd ~/Ultron/projects/miner-firmware/alkane-toolkit -scripts/build-wx-linux.sh # once: wx 3.3.3 → ~/.cache/wx-3.3.3-linux (out-of-tree) -scripts/build-gui-linux.sh # release build (needs WX_RS_WXCONFIG, script sets it) -/usr/local/bin/alkane-toolkit # installed binary; or ~/.cache/alkane-tk-target/release/alkane-toolkit -``` - -Needs a display (user's desktop session has DISPLAY=:0). Headless smoke test: -`timeout 15 xvfb-run -a /usr/local/bin/alkane-toolkit` — rc 124 = ran until killed (good), rc 139 = crash. - -## 4. Machine quirks (these cost hours — don't re-learn them) - -- **The synced project mount is noexec** for newly-written files: never build or execute anything inside the repo tree. wx builds go to `~/.cache/wxbuild`, cargo target to `~/.cache/alkane-tk-target` (set machine-locally via `~/.cargo/config.toml`, NOT committed). -- **`cargo vendor vendor` DELETES unmanaged directories under vendor/**. Hand-made trees live in `thirdparty/` (wxwidgets, wx-rs). Only cargo-managed crate sources are in `vendor/` (341 crates; offline builds via committed `.cargo/config.toml`). -- **/tmp tmpfs is 100% full** (bench artifacts live there — do not clean). Build outputs must not go to /tmp. -- The FS is very slow for many-file operations: `git add` of thirdparty/wxwidgets (~10k files) takes ~20 min; extraction of the wx tarball will blow a 120 s timeout. Run big FS operations as background jobs and poll. -- sudo: `sudo -S -p '' < ~/.sudopass` (non-interactive). -- Rust 1.97.1, cargo, gdb, xvfb-run, mingw-w64, gtk3 dev, pcre2 dev all installed. - -## 5. Architecture map - -``` -crates/ - alkane-core/ domain types (stub — next milestone fills it) - alkane-discovery/ asic-rs dependency wired (engine lives in alkane-gui/scan.rs today) - alkane-access/ stub (SSH/foothold layer, M3+) - alkane-flash/ stub (write/verify engines, M3+) - alkane-artifacts/ manifest-seed.csv (14 artifacts w/ sha256) - alkane-cli/ stub bin - alkane-gui/ THE APP (bin "alkane-toolkit"): main.rs, model.rs, scan.rs, ui.rs -thirdparty/ - wxwidgets/wxWidgets-3.3.3/ pristine dist tarball tree (+ VERSION sha256, patches/ empty) - wx-rs/wx-rs-0.2.0-patched/ the used crate (path dep) + VERSION + patches/: - 0001 linux/GTK3 wx-config build path (build.rs; handles full-path .a in --libs!) - 0002 Rust widget bindings (src/widgets.rs: Widget API + single event dispatcher) - 0003 C++ widget bridge (cpp_src/widgets_bridge.cpp: panel/sizers/static text/ - button/textctrl/checkbox/checklistbox/dialog/dvlc/timer/destroy) - 0004 upstream fixes (Linux get_client_size branch; init render/handle_events — - upstream left them UNINITIALIZED: 5ms render timer calls garbage in release) -vendor/ cargo-managed ONLY (341 crates, offline) -scripts/ build-wx-linux.sh, build-gui-{linux,windows,macos}.sh -docs/ IMPLEMENTATION-PLAN.md, UI-SPEC.md, adr/0001-0003 -``` - -Key implementation facts (don't re-derive): -- **Event model**: ONE C callback (`wxbr_set_widget_event_fn`) → Rust `set_event_handler(Handler)`; all events funnel through `ui::dispatch` (thread_local APP). Event kinds: ButtonClicked(id), DvlcValueChanged(row,col), DvlcHeaderClick(col), DvlcReordered, TimerTick(id). -- **Table semantics**: `view.order` = creation order = display order; toggle col is creation idx 0 (bool variants only); `dvlc_col_at_pos()` maps display→creation after a drag; store rows are appended in filtered+sorted view order, so store row == `view_idx[row]`. Header click sort cycles asc→desc→off and refills. -- **Scan thread**: std thread + own tokio runtime + std mpsc; a 1 s wx Timer drains it (`App::drain_scan`). Ranges: `~/.config/alkane-toolkit/scan-ranges.txt` (default 10.255.1.0/24), parse via `scan::parse_cidr`. -- **asic-rs API**: `MinerFactory::from_subnet("a.b.c.d/p")`, `.scan_stream()` → `Stream>`; `Miner::get_data().await -> MinerData` (trait at `asic_rs::core::traits::miner::Miner`); `HashRate.clone().as_unit(HashRateUnit::TeraHash).value`; `Power::as_watts()`, `Temperature::as_celsius()`, `AngularVelocity::as_rpm()`; pools: `MinerData.pools[].pools[]` with `.user/.active`. -- **wx 3.3 API gotchas hit**: `store->GetValueByRow(v,row,col)` (not GetValue), `GetColumnPosition()` (no GetColumnAt), `--enable-dataview` doesn't exist, `--disable-stc --without-catch2 --disable-tests` needed only if using the GitHub source export (the dist tarball in thirdparty/ is complete — just chmod +x configure). - -## 6. Verification evidence - -- `cargo build --workspace --offline` clean (network-independent; all sources vendored) -- `cargo test -p alkane-gui --offline`: 10 transform-layer unit tests pass (KPIs, sort, filter, cell formatting, slow band, hidden-column mapping, drag-reorder splice, selection-survives-upsert). -- `scripts/ui-selftest.sh`: 13/13 checks pass end-to-end through the real widgets (KPI labels, row count, every cell matches the model, slow/not-hashing spot checks, IP is first text column). -- Visual review via `scripts/ui-screenshot.sh` (off-screen Xvfb): confirmed the table renders below the header, and drove every button with xdotool (open/apply/cancel each dialog, header sort, column hide, row check) with zero crashes/panics. -- Git: previous tip `b264cdd6` pushed to gitea (gitea repo `size` field updates lazily — that commit has 16k files/4.9M insertions incl. the wx tree). -- Still open: eyeball on the **real bench fleet** (`--live`). The visual + interaction checks above used the offline fixtures; a live run against the 9 boards on 10.255.1.0/24 is the remaining confidence step. - -## 7. Bench fleet context (for the scan you'll see) - -9 boards live on 10.255.1.0/24: S17 stock (.112, root+EMPTY password, legacy SSH algos), S19 xil OurOS (.166), S19j Pro bb OurOS (.152), S19k Pro cv OurOS (.167), S21 Pro aml stock (.149), WhatsMiner H3 (.126), H616 (.131), M50 CB4 (.148 — random MAC, address moves), WardenOS dev (.115). Scanning is read-only and routine; the `live-fleet-ops` rules (no auth bursts, gentle on prod 10.2.1.0/24) are standing orders in AGENTS.md. Never install/flash anything without the operator explicitly asking. - -## 8. Conventions for this repo - -- Confidence tags (CONFIRMED/DERIVED/EXTERNAL) on claims in docs; cite file paths. -- Commit style so far: single-line imperative summaries, no sign-off noise. -- Repo-level rules now live in `AGENTS.md` (dev/review/visual loop, offline modes, build discipline). Keep it short. -- When you change the vendored wx-rs: edit `thirdparty/wx-rs/wx-rs-0.2.0-patched/`, regenerate the matching `patches/NNNN-*.patch` via `diff -u` against the pristine crate (tarball URL+sha in `thirdparty/wx-rs/VERSION`), and confirm the patch set reconstructs the patched tree before committing both. diff --git a/README.md b/README.md index 7b3d7e79..6395e402 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,18 @@ # Alkane Toolkit [![CI](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/main.svg)](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions) -![tests](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/tests.svg) -![coverage](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/coverage.svg) -![bench](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/bench.svg) -![bench coverage](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/bench-coverage.svg) -![lines of code](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/loc.svg) -![code quality](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/quality.svg) -![dependencies](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/dependencies.svg) -![license](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/license.svg) +[![tests](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/tests.svg)](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/) +[![coverage](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/coverage.svg)](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/#coverage) +[![bench](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/bench.svg)](https://blueflare.gitea.bluefla.re/alkane-toolkit/bench/) +[![bench coverage](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/bench-coverage.svg)](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/) +[![lines of code](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/loc.svg)](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/#coverage) +[![code quality](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/quality.svg)](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/) +[![dependencies](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/dependencies.svg)](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/) +[![license](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/license.svg)](LICENSE) -The code quality grade reports GUI Clippy and first-party Rust formatting checks -from the last successful main build. Test coverage has a separate badge. +The badges link to the [project site](https://blueflare.gitea.bluefla.re/alkane-toolkit/): the [manual](https://blueflare.gitea.bluefla.re/alkane-toolkit/manual/), +the [code-quality dashboard](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/) (how the grade is set, coverage by +crate and file) and the [benchmark history](https://blueflare.gitea.bluefla.re/alkane-toolkit/bench/). Desktop miner discovery and monitoring. The Rust GUI uses wxWidgets through a patched [wx-rs bridge](thirdparty/wx-rs). In-app image flashing is disabled @@ -42,8 +43,7 @@ macOS is not built. aftermarket firmware to stock. Discovery is read-only. Control and restore actions change miners. Check the -selected devices before applying them. See the [implementation plan](docs/IMPLEMENTATION-PLAN.md) -and [firmware matrix](docs/aftermarket-parity-roadmap.md) for planned coverage. +selected devices before applying them. ## Development @@ -55,8 +55,8 @@ WX_RS_WXCONFIG="$HOME/.cache/wx-3.3.3-linux/bin/wx-config" \ Keep build output off the source share. `main` runs full CI and publishes qualifying releases; `next` builds `-rc` candidates. Badges measure host -code, not installation support. See the public -[benchmark history](https://blueflare.gitea.bluefla.re/alkane-benchmarks/toolkit/). +code, not installation support. See the +[benchmark history](https://blueflare.gitea.bluefla.re/alkane-toolkit/bench/). ## Firmware safety diff --git a/ci/build-pages.py b/ci/build-pages.py new file mode 100755 index 00000000..c2bc35c7 --- /dev/null +++ b/ci/build-pages.py @@ -0,0 +1,293 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Build the Alkane Toolkit Pages site (served from this repo's gh-pages). + + build-pages.py --out site [--manual docs/manual] [--quality quality.json] + [--bench bench-site/index.html] [--sha SHA] + +Pages: + / overview and downloads + /manual/ the user manual, one page per docs/manual/NN-name.md chapter + /quality/ code-quality dashboard from the measured quality.json that main + CI publishes next to the badges (ci/gen-badges.py) + /bench/ the measured benchmark history (ci/bench_history.py render) + +Every value taken from CI data is HTML-escaped; the manual is Markdown written +in this repository. +""" + +import argparse +import html +import json +import re +import shutil +from pathlib import Path + +import markdown + +REPO = "https://gitea.bluefla.re/blueflare/alkane-toolkit" +RELEASES = REPO + "/releases" +SECTIONS = (("", "Overview"), ("manual/", "Manual"), ("quality/", "Code quality"), + ("bench/", "Benchmarks")) + +CSS = """ +:root { --bg:#ffffff; --fg:#1f2328; --muted:#59636e; --line:#d1d9e0; --card:#f6f8fa; + --accent:#d9822b; --link:#0969da; --good:#1a7f37; --warn:#9a6700; --bad:#cf222e; } +@media (prefers-color-scheme: dark) { :root { --bg:#0d1117; --fg:#e6edf3; --muted:#9198a1; + --line:#30363d; --card:#151b23; --link:#4493f8; --good:#3fb950; --warn:#d29922; --bad:#f85149; } } +* { box-sizing: border-box; } +body { margin:0; background:var(--bg); color:var(--fg); + font:16px/1.55 system-ui,-apple-system,"Segoe UI",Roboto,Ubuntu,sans-serif; } +a { color:var(--link); text-decoration:none; } a:hover { text-decoration:underline; } +header { border-bottom:1px solid var(--line); } +header .bar, main { max-width:1040px; margin:0 auto; padding:0 16px; } +header .bar { display:flex; align-items:center; gap:24px; height:56px; flex-wrap:wrap; } +header .brand { font-weight:700; color:var(--fg); display:flex; gap:8px; align-items:center; } +header .brand i { width:20px; height:20px; border-radius:5px; background:var(--accent); display:inline-block; } +header nav { display:flex; gap:18px; flex-wrap:wrap; } +header nav a { color:var(--muted); } header nav a.on { color:var(--fg); font-weight:600; } +main { padding:28px 16px 64px; } +h1 { font-size:1.9rem; margin:.2em 0 .4em; } h2 { margin-top:1.8em; border-bottom:1px solid var(--line); padding-bottom:.25em; } +code { background:var(--card); border:1px solid var(--line); border-radius:5px; padding:.1em .35em; font-size:.92em; } +pre { background:var(--card); border:1px solid var(--line); border-radius:8px; padding:12px; overflow:auto; } +pre code { border:0; padding:0; } +table { border-collapse:collapse; width:100%; margin:1em 0; display:block; overflow-x:auto; } +th, td { border:1px solid var(--line); padding:6px 10px; text-align:left; vertical-align:top; } +th { background:var(--card); } +td.num, th.num { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; } +.cards { display:grid; grid-template-columns:repeat(auto-fill,minmax(180px,1fr)); gap:12px; margin:1.2em 0; } +.card { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:14px; } +.card b { display:block; font-size:1.6rem; } .card span { color:var(--muted); font-size:.9rem; } +.good { color:var(--good); } .warn { color:var(--warn); } .bad { color:var(--bad); } +.bar-cell { min-width:120px; } .meter { height:8px; background:var(--line); border-radius:4px; overflow:hidden; } +.meter i { display:block; height:100%; } +.layout { display:grid; grid-template-columns:220px 1fr; gap:32px; } +.layout aside ol { padding-left:1.2em; margin:0; } .layout aside li { margin:.3em 0; } +.layout aside a.on { font-weight:600; color:var(--fg); } +@media (max-width:760px) { .layout { grid-template-columns:1fr; } } +.buttons a { display:inline-block; margin:4px 8px 4px 0; padding:8px 14px; border-radius:8px; + border:1px solid var(--line); background:var(--card); color:var(--fg); } +.buttons a.primary { background:var(--accent); border-color:var(--accent); color:#fff; } +footer { color:var(--muted); font-size:.85rem; margin-top:48px; } +""" + + +def page(title: str, body: str, depth: int, current: str, sha: str) -> str: + up = "../" * depth + nav = "".join( + f'{label}' + for path, label in SECTIONS) + built = f"Built from {html.escape(sha[:10])}. " if sha else "" + return f""" + + +{html.escape(title)} - Alkane Toolkit + +
+
{body} +
{built}Alkane Toolkit is MIT licensed.
+""" + + +def write(out: Path, rel: str, text: str) -> None: + path = out / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +# ---- manual ----------------------------------------------------------------- + +def chapters(manual: Path) -> list[tuple[str, str, str]]: + """(slug, title, markdown) for docs/manual/NN-slug.md, in file-name order.""" + out = [] + for path in sorted(manual.glob("[0-9][0-9]-*.md")): + text = path.read_text(encoding="utf-8") + m = re.search(r"^# (.+)$", text, re.M) + title = m.group(1).strip() if m else path.stem + out.append((path.stem[3:], title, text)) + return out + + +def build_manual(out: Path, manual: Path, sha: str) -> None: + items = chapters(manual) + if not items: + raise SystemExit(f"no manual chapters in {manual}") + + def toc(current: str) -> str: + links = "".join( + f'
  • ' + f"{html.escape(title)}
  • " for slug, title, _ in items) + return f"" + + for slug, title, text in items: + # Chapters link to each other as NN-name.md in the repo; on the site + # they are name.html. + text = re.sub(r"\]\((?:\./)?[0-9][0-9]-([a-z0-9-]+)\.md(#[^)]*)?\)", r"](\1.html\2)", text) + body_html = markdown.markdown(text, extensions=["tables", "fenced_code", "toc"]) + write(out, f"manual/{slug}.html", + page(title, f'
    {toc(slug)}
    {body_html}
    ', + 1, "manual/", sha)) + first = items[0][0] + listing = "".join(f'
  • {html.escape(t)}
  • ' for s, t, _ in items) + write(out, "manual/index.html", + page("Manual", f"

    Manual

    Start with " + f'{html.escape(items[0][1])}.

      {listing}
    ', + 1, "manual/", sha)) + + +# ---- quality dashboard --------------------------------------------------------- + +def pct_class(pct: float | None) -> str: + if pct is None: + return "" + return "good" if pct >= 80 else "warn" if pct >= 40 else "bad" + + +def meter(pct: float) -> str: + colour = {"good": "var(--good)", "warn": "var(--warn)", "bad": "var(--bad)"}[pct_class(pct)] + return f'
    ' + + +def build_quality(out: Path, quality: dict | None, sha: str) -> None: + e = html.escape + if not quality: + write(out, "quality/index.html", page( + "Code quality", "

    Code quality

    No measurement has been published yet; " + "the next main build will fill this page.

    ", 1, "quality/", sha)) + return + grade = str(quality.get("grade", "pending")) + cov = quality.get("coverage_pct") + bench_cov = quality.get("bench_coverage_pct") + delta = quality.get("bench_delta_pct") + + def card(value: str, label: str, cls: str = "") -> str: + return f'
    {value}{label}
    ' + + cards = "".join([ + card(e(grade), "Quality grade", {"A": "good", "B": "good", "C": "warn"}.get(grade, "bad")), + card(e(str(quality.get("tests_passed", "-"))), "Tests passing", "good"), + card(f"{cov:.1f}%" if cov is not None else "-", "Line coverage", pct_class(cov)), + card(f"{bench_cov:.1f}%" if bench_cov is not None else "-", "Benchmark coverage", pct_class(bench_cov)), + card(e(str(quality.get("clippy") or "-")), "Clippy (warnings are errors)", + "good" if quality.get("clippy") == "clean" else "bad"), + card(e(str(quality.get("rustfmt") or "-")), "rustfmt", "good" if quality.get("rustfmt") == "clean" else ""), + card(f"{quality.get('loc', 0):,}", "Lines of Rust"), + card(e(str(quality.get("dependencies", "-"))), "Crates in Cargo.lock"), + card((f"{'+' if delta > 0 else ''}{delta:.1f}%" if delta is not None else "-"), + "Benchmarks vs previous" + (" (same inputs)" if quality.get("bench_same_inputs") else ""), + "" if delta is None else "good" if delta >= 2 else "" if delta > -2 else "warn"), + ]) + bands = ", ".join(f"{e(str(letter))} at {floor:.0f}% or more" + for floor, letter in quality.get("grade_bands", [])) + grade_rule = (f"

    The grade is F if Clippy or rustfmt fails on main. Otherwise it is the " + f"line-coverage band: {bands}, and F below that. The coverage badge uses the " + f"same bands for its colour, so the two never disagree.

    ") + + crates = quality.get("coverage_by_crate", {}) + loc = quality.get("loc_by_crate", {}) + rows = [] + for name in sorted(set(crates) | set(loc)): + c = crates.get(name) + if c and c["lines"]: + pct = 100.0 * (c["lines"] - c["missed"]) / c["lines"] + cov_cells = (f'{pct:.1f}%' + f'{meter(pct)}' + f'{c["lines"] - c["missed"]:,} / {c["lines"]:,}') + else: + cov_cells = '--' + rows.append(f"{e(name)}{cov_cells}{loc.get(name, 0):,}") + crate_table = ("" + "" + + "".join(rows) + "
    CrateLine coverageCovered linesLines of Rust
    ") + + files = sorted(quality.get("coverage_by_file", []), + key=lambda r: (r["lines"] - r["missed"]) / r["lines"] if r["lines"] else 1) + file_rows = "".join( + f"{e(r['file'])}" + f"" + f"{100.0 * (r['lines'] - r['missed']) / r['lines']:.1f}%" + f"{r['missed']:,}{r['lines']:,}" + for r in files if r["lines"]) + file_table = ("" + "" + + file_rows + "
    File (least covered first)CoverageUncovered linesLines
    ") if file_rows else "" + + measured = str(quality.get("sha", ""))[:10] + of_build = f" (this page: {e(measured)})" if measured else "" + body = f"""

    Code quality

    +

    Measured by main CI on every build{of_build}: +unit tests, line coverage (unit tests plus the headless UI self-test), Clippy with +warnings as errors, and rustfmt. Windows builds run the same tests under Wine and +on real Windows 11.

    +
    {cards}
    +

    How the grade is set

    {grade_rule} +

    Coverage by crate

    {crate_table} +

    Coverage by file

    {file_table} +

    The dependency count is every package in Cargo.lock, direct and +transitive. Lines of Rust count every .rs line under crates/, +tests included.

    """ + write(out, "quality/index.html", page("Code quality", body, 1, "quality/", sha)) + + +# ---- benchmarks + overview ------------------------------------------------------- + +def build_bench(out: Path, bench: Path | None, sha: str) -> None: + if bench is None or not bench.is_file(): + write(out, "bench/index.html", page( + "Benchmarks", "

    Benchmarks

    No benchmark history yet.

    ", 1, "bench/", sha)) + return + rendered = bench.read_text(encoding="utf-8") + # The history renderer emits a complete document; keep its body (and its + # own styles) under the site's header. + styles = "".join(re.findall(r"]*>.*?", rendered, re.S | re.I)) + m = re.search(r"]*>(.*)", rendered, re.S | re.I) + inner = m.group(1) if m else rendered + text = page("Benchmarks", inner, 1, "bench/", sha) + write(out, "bench/index.html", text.replace("", styles + "", 1)) + + +def build_index(out: Path, quality: dict | None, sha: str) -> None: + grade = html.escape(str((quality or {}).get("grade", "pending"))) + body = f"""

    Alkane Toolkit

    +

    Desktop discovery and monitoring for ASIC miners on your network: find every +miner in your IP ranges, see hashrate, power, temperatures, fans and hashboard +health at a glance, and run the controls each firmware supports.

    + +

    Platforms

    +
    • Windows 10 and 11 (x86_64): one signed, self-contained alkane-toolkit.exe.
    • +
    • Linux (x86_64, GTK 3): one binary.
    +

    Every release is built, tested and signed by CI from the public source.

    """ + write(out, "index.html", page("Overview", body, 0, "", sha)) + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--out", required=True) + ap.add_argument("--manual", default="docs/manual") + ap.add_argument("--quality", default=None) + ap.add_argument("--bench", default=None) + ap.add_argument("--sha", default="") + args = ap.parse_args() + out = Path(args.out) + if out.exists(): + shutil.rmtree(out) + out.mkdir(parents=True) + quality = None + if args.quality and Path(args.quality).is_file(): + quality = json.loads(Path(args.quality).read_text()) + if not isinstance(quality, dict) or quality.get("schema") != 1: + raise SystemExit("unsupported quality.json") + (out / "style.css").write_text(CSS.strip() + "\n", encoding="utf-8") + build_index(out, quality, args.sha) + build_manual(out, Path(args.manual), args.sha) + build_quality(out, quality, args.sha) + build_bench(out, Path(args.bench) if args.bench else None, args.sha) + print(f"built {sum(1 for _ in out.rglob('*.html'))} pages in {out}") + + +if __name__ == "__main__": + main() diff --git a/ci/check-runner-image.py b/ci/check-runner-image.py index 61730880..d8244918 100644 --- a/ci/check-runner-image.py +++ b/ci/check-runner-image.py @@ -32,12 +32,12 @@ def main() -> int: print(f"{path.name}: {name} has a different runner image", file=sys.stderr) return 1 pages = yaml.load( - (ROOT / ".gitea/workflows/bench-pages.yml").read_text(), + (ROOT / ".gitea/workflows/pages.yml").read_text(), Loader=yaml.BaseLoader, ) if (pages["on"]["workflow_run"]["workflows"] != ["build-test-release"] or pages["jobs"]["publish"].get("runs-on") != "alkane-verify"): - print("Benchmark Pages must follow main CI on the trusted verifier", file=sys.stderr) + print("Pages must follow main CI on the trusted verifier", file=sys.stderr) return 1 release = yaml.load( (ROOT / ".gitea/workflows/release.yml").read_text(), @@ -46,7 +46,7 @@ def main() -> int: if release["jobs"]["release"].get("runs-on") != "alkane-ci": print("Main release must use the dedicated Alkane build pool", file=sys.stderr) return 1 - if any("ci/publish-bench-pages.py" in step.get("run", "") + if any("ci/publish-pages.py" in step.get("run", "") for step in release["jobs"]["release"]["steps"]): print("Main release must not publish Pages from GARM", file=sys.stderr) return 1 diff --git a/ci/cleanup-generated.py b/ci/cleanup-generated.py index f0096c82..3def2858 100644 --- a/ci/cleanup-generated.py +++ b/ci/cleanup-generated.py @@ -9,9 +9,9 @@ import sys ROOT = Path(__file__).resolve().parents[1] -DIRECTORIES = ("target", "dist", "coverage", "bench-site") -FILES = ("bench-current.txt",) -BADGE_FILES = ("bench-baseline.json", "bench-context.json") +DIRECTORIES = ("target", "dist", "coverage", "bench-site", "site") +FILES = ("bench-current.txt", "coverage-summary.txt", "quality.json") +BADGE_FILES = ("bench-baseline.json", "bench-context.json", "quality.json") def cleanup() -> None: diff --git a/ci/compute-version.sh b/ci/compute-version.sh index 302a2434..76c475f5 100755 --- a/ci/compute-version.sh +++ b/ci/compute-version.sh @@ -46,7 +46,7 @@ vendor/*|thirdparty/asic-rs/*) # resources, embedded assets). ui.rs/fixtures.rs/bin # match the UI arm above first, so they still bump Z, not Y. backend=true ;; - *) : ;; # docs, HANDOFF, README, thirdparty/wxwidgets tree: no bump + *) : ;; # docs, README, thirdparty/wxwidgets tree: no bump esac done <<< "$changed" diff --git a/ci/ensure-build-deps.sh b/ci/ensure-build-deps.sh index c60f5c0f..68d9c15d 100644 --- a/ci/ensure-build-deps.sh +++ b/ci/ensure-build-deps.sh @@ -3,11 +3,12 @@ # Use the preinstalled CI image or install missing packages on older runners. set -euo pipefail -mode="${1:?usage: ensure-build-deps.sh base|ui|all|ssh|windows}" +mode="${1:?usage: ensure-build-deps.sh base|ui|all|ssh|windows|pages}" case "$mode" in base) packages=(libssl-dev pkg-config ca-certificates) ;; ui) packages=(xvfb xauth dbus-x11 fonts-dejavu-core) ;; ssh) packages=(openssh-client) ;; + pages) packages=(python3-markdown) ;; all) packages=(libssl-dev pkg-config ca-certificates openssh-client xvfb xauth dbus-x11 fonts-dejavu-core) ;; # Windows cross build (mingw-w64, posix threads) + Wine for its tests. diff --git a/ci/fetch-quality.py b/ci/fetch-quality.py new file mode 100755 index 00000000..00dfa8b4 --- /dev/null +++ b/ci/fetch-quality.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Download the measured quality record (badges/quality.json on ci-badges). + + fetch-quality.py OUT.json + +Writes nothing (and exits 0) when main CI has not published one yet, so the +Pages build shows a "not measured yet" dashboard instead of failing. +""" + +import base64 +import json +import os +from pathlib import Path +import sys +from urllib.error import HTTPError +from urllib.request import Request, urlopen + + +def main() -> None: + out = Path(sys.argv[1]) + api = os.environ["GITHUB_API_URL"].rstrip("/") + repo = os.environ["GITHUB_REPOSITORY"] + url = f"{api}/repos/{repo}/contents/badges/quality.json?ref=ci-badges" + request = Request(url, headers={"Authorization": f"token {os.environ['GITEA_TOKEN']}"}) + try: + with urlopen(request, timeout=20) as response: + content = base64.b64decode(json.load(response)["content"]) + except HTTPError as error: + if error.code == 404: + print("No quality record published yet") + return + raise + if not isinstance(json.loads(content), dict): + sys.exit("invalid quality record") + out.write_bytes(content) + print(f"Fetched quality record ({len(content)} bytes)") + + +if __name__ == "__main__": + main() diff --git a/ci/gen-badges.py b/ci/gen-badges.py index ba9f005c..35484843 100644 --- a/ci/gen-badges.py +++ b/ci/gen-badges.py @@ -135,10 +135,66 @@ def cov_color(pct: float) -> str: return "red" -def quality_grade(clippy: str | None) -> str: - if clippy is None: +# Code-quality grade (shown on the badge and explained on the Pages quality +# dashboard). Lint failures fail the grade outright; otherwise the grade is the +# measured line-coverage band, using the same bands as the coverage badge +# colour, so the two badges can never disagree. +GRADE_BANDS = ((80.0, "A"), (60.0, "B"), (40.0, "C"), (20.0, "D")) +GRADE_COLORS = {"A": "brightgreen", "B": "yellowgreen", "C": "yellow", + "D": "orange", "F": "red", "pending": "lightgrey"} + + +def quality_grade(clippy: str | None, coverage: float | None = None) -> str: + if clippy is None or (clippy == "clean" and coverage is None): return "pending" - return "A" if clippy == "clean" else "F" + if clippy != "clean": + return "F" + for floor, grade in GRADE_BANDS: + if coverage >= floor: + return grade + return "F" + + +def coverage_by_file(summary_path: str | None, root: str) -> list[dict]: + """Per-file line coverage from a `cargo llvm-cov --summary-only` table. + + Columns: Filename, Regions, Missed Regions, Cover, Functions, Missed + Functions, Executed, Lines, Missed Lines, Cover, ... + """ + if not summary_path: + return [] + rows = [] + root_abs = os.path.abspath(root).rstrip("/") + "/" + for line in Path(summary_path).read_text(errors="replace").splitlines(): + cols = line.split() + if len(cols) < 10 or cols[0] in ("Filename", "TOTAL") or not cols[0].endswith(".rs"): + continue + try: + lines, missed = int(cols[7]), int(cols[8]) + except ValueError: + continue + name = cols[0][len(root_abs):] if cols[0].startswith(root_abs) else cols[0] + rows.append({"file": name, "lines": lines, "missed": missed}) + return rows + + +def crate_of(path: str) -> str: + parts = Path(path).parts + if "crates" in parts and parts.index("crates") + 1 < len(parts): + return parts[parts.index("crates") + 1] + if "wx-rs-0.2.0-patched" in parts: + return "wx-rs (bridge)" + return "other" + + +def loc_by_crate(root: str) -> dict[str, int]: + out: dict[str, int] = {} + crates = Path(root) / "crates" + for path in sorted(crates.glob("*/**/*.rs")): + crate = path.relative_to(crates).parts[0] + with open(path, encoding="utf-8", errors="ignore") as fh: + out[crate] = out.get(crate, 0) + sum(1 for _ in fh) + return out def human(n: int) -> str: @@ -169,6 +225,9 @@ def main() -> int: # percentage string, or "NEW" when there is no baseline. ap.add_argument("--bench-delta", default=None) ap.add_argument("--clippy", choices=("clean", "failed")) + # The full `cargo llvm-cov --summary-only` table, for the per-crate and + # per-file breakdown in quality.json (the Pages quality dashboard). + ap.add_argument("--coverage-summary", default=None) args = ap.parse_args() for value in (args.coverage, args.bench_coverage): if value is not None and (not math.isfinite(value) or not 0 <= value <= 100): @@ -189,11 +248,9 @@ def main() -> int: write("loc", "lines of code", human(loc), loc_color(loc)) write("license", "license", lic, "blue") write("dependencies", "dependencies", str(deps), "blue") - grade = quality_grade(args.clippy) - write("quality", "code quality", grade, - {"A": "brightgreen", "B": "yellowgreen", "C": "yellow", - "D": "orange", "F": "red", "pending": "lightgrey"}[grade], - f"code quality: {grade} (GUI Clippy and first-party rustfmt)") + grade = quality_grade(args.clippy, args.coverage) + write("quality", "code quality", grade, GRADE_COLORS[grade], + f"code quality: {grade} (Clippy, rustfmt and line coverage)") if args.tests is not None: write("tests", "tests", f"{args.tests} passing", "brightgreen") if args.coverage is not None: @@ -228,6 +285,38 @@ def main() -> int: write("bench", "bench", "baseline set", "blue") elif args.bench is not None: write("bench", "bench", args.bench, "blue") + + # Everything above, plus the per-crate breakdowns, for the Pages quality + # dashboard (ci/build-pages.py). + files = coverage_by_file(args.coverage_summary, args.root) + crates: dict[str, dict] = {} + for row in files: + c = crates.setdefault(crate_of(row["file"]), {"lines": 0, "missed": 0}) + c["lines"] += row["lines"] + c["missed"] += row["missed"] + quality = { + "schema": 1, + "sha": os.environ.get("GITHUB_SHA", ""), + "grade": grade, + "grade_bands": [[floor, letter] for floor, letter in GRADE_BANDS], + "clippy": args.clippy, + "rustfmt": "clean" if args.clippy is not None else None, + "tests_passed": args.tests, + "coverage_pct": args.coverage, + "bench_coverage_pct": args.bench_coverage, + "bench_delta_pct": delta, + "bench_same_inputs": same_inputs, + "loc": loc, + "loc_by_crate": loc_by_crate(args.root), + "dependencies": deps, + "license": lic, + "coverage_by_crate": crates, + "coverage_by_file": files, + } + path = os.path.join(args.root, args.out, "quality.json") + with open(path, "w", encoding="utf-8") as fh: + json.dump(quality, fh, indent=1, sort_keys=True) + print(f"wrote {path}") return 0 diff --git a/ci/publish-bench-pages.py b/ci/publish-bench-pages.py deleted file mode 100644 index 5adff3bd..00000000 --- a/ci/publish-bench-pages.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env python3 -# SPDX-License-Identifier: MIT -"""Publish a measured benchmark page to the public, data-only Pages repo.""" - -import argparse -import json -import os -from pathlib import Path -import shlex -import subprocess -import tempfile -from urllib.request import Request, urlopen - -PAGES_REPO = "ssh://git@gitea.bluefla.re:2222/blueflare/alkane-benchmarks.git" -GUARD_REPO = "https://gitea.bluefla.re/blueflare/alkane-benchmarks.git" -GUARD_COMMIT = "ea160545c49bc419a245692deda8dd7db7a611eb" -PAGES_HOST = "gitea.bluefla.re" -PAGES_HOST_FINGERPRINT = "SHA256:lqB5cmC9E5HNeg/lkzdOwQ++I8A70Wx7lnNs6liN24g" -PAGES_HOST_KEY = "[gitea.bluefla.re]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIO1II6NkmRW+QAd+Wj+7qbNrA8Oo+/N/WRog4hELskn/" - - -def run(*args: str, env: dict[str, str] | None = None, - cwd: Path | None = None) -> subprocess.CompletedProcess[str]: - return subprocess.run(args, env=env, cwd=cwd, text=True, - capture_output=True, check=True) - - -def current_main_sha() -> str: - api = os.environ["GITHUB_API_URL"].rstrip("/") - repo = os.environ["GITHUB_REPOSITORY"] - token = os.environ["GITEA_TOKEN"] - request = Request(f"{api}/repos/{repo}/branches/main", - headers={"Authorization": f"token {token}"}) - with urlopen(request, timeout=20) as response: - branch = json.load(response) - return branch["commit"]["id"] - - -def publish(site: str) -> None: - if os.environ.get("GITHUB_REF") != "refs/heads/main": - raise ValueError("benchmark Pages publication requires main") - sha = os.environ["GITHUB_SHA"] - if current_main_sha() != sha: - print("Skipping benchmark page from a superseded main commit") - return - page = Path("bench-site/index.html").read_bytes() - if not page.startswith(b"") or len(page) > 1_048_576: - raise ValueError("invalid benchmark page") - with tempfile.TemporaryDirectory(prefix="alkane-pages-") as directory: - temporary = Path(directory) - guard_checkout = temporary / "guard" - run("git", "clone", "--quiet", "--single-branch", "--branch", "next", - GUARD_REPO, str(guard_checkout)) - guard_source = run("git", "show", f"{GUARD_COMMIT}:ci/validate_site.py", - cwd=guard_checkout).stdout - guard_script = temporary / "validate_site.py" - guard_script.write_text(guard_source) - run("python3", str(guard_script), "--page", site, - str(Path("bench-site/index.html").resolve())) - key = os.environ["BENCH_PAGES_DEPLOY_KEY"] - if not key.startswith("-----BEGIN OPENSSH PRIVATE KEY-----"): - raise ValueError("missing benchmark Pages deploy key") - key_path = temporary / "deploy_key" - key_path.write_text(key.rstrip("\n") + "\n") - key_path.chmod(0o600) - known_hosts = temporary / "known_hosts" - known_hosts.write_text(PAGES_HOST_KEY + "\n") - fingerprint = run("ssh-keygen", "-lf", str(known_hosts)).stdout.split()[1] - if fingerprint != PAGES_HOST_FINGERPRINT: - raise ValueError("benchmark Pages SSH host key changed") - git_env = os.environ.copy() - ssh_command = (f"ssh -i {shlex.quote(str(key_path))} -o IdentitiesOnly=yes " - f"-o UserKnownHostsFile={shlex.quote(str(known_hosts))} " - "-o StrictHostKeyChecking=yes -o ConnectTimeout=10") - git_env["GIT_SSH_COMMAND"] = ssh_command - git_env["GIT_TERMINAL_PROMPT"] = "0" - checkout = temporary / "site" - run("git", "clone", "--quiet", "--single-branch", "--branch", "gh-pages", - PAGES_REPO, str(checkout), env=git_env) - run("git", "config", "user.name", "Alkane CI", cwd=checkout) - run("git", "config", "user.email", "ci@bluefla.re", cwd=checkout) - for attempt in range(3): - if current_main_sha() != sha: - print("Skipping benchmark page from a superseded main commit") - return - run("git", "fetch", "--quiet", "origin", "gh-pages", env=git_env, - cwd=checkout) - run("git", "checkout", "-q", "-B", "bench-publish", "origin/gh-pages", - cwd=checkout) - destination = checkout / site / "index.html" - destination.parent.mkdir(exist_ok=True) - destination.write_bytes(page) - run("git", "add", f"{site}/index.html", cwd=checkout) - changed = subprocess.run(("git", "diff", "--cached", "--quiet"), - cwd=checkout, check=False) - if changed.returncode == 0: - print(f"{site} benchmark page is already current") - return - if changed.returncode != 1: - raise RuntimeError("cannot compare benchmark page") - run("git", "commit", "-q", "-m", - f"Update {site} benchmarks for {sha[:10]} [skip ci]", cwd=checkout) - pushed = subprocess.run(("git", "push", "--quiet", "origin", - "HEAD:gh-pages"), env=git_env, cwd=checkout, - text=True, capture_output=True, check=False) - if pushed.returncode == 0: - print(f"Published {site} benchmark page for {sha[:10]}") - return - if attempt == 2: - raise RuntimeError(f"benchmark Pages push failed: {pushed.stderr.strip()}") - raise RuntimeError("benchmark Pages publication did not complete") - - -def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument("site", choices=("sdk", "os", "toolkit")) - publish(parser.parse_args().site) - - -if __name__ == "__main__": - main() diff --git a/ci/publish-metrics.py b/ci/publish-metrics.py index 3a6f06f0..35384c99 100644 --- a/ci/publish-metrics.py +++ b/ci/publish-metrics.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """Publish measured toolkit badges to the private Gitea badge branch.""" +import json import os from pathlib import Path @@ -22,7 +23,14 @@ def main() -> None: raise ValueError(f"invalid {name} SVG") publish_file(api, repo, f"badges/{name}.svg", data, token, f"Update measured {name} badge") - print(f"Published {len(NAMES)} measured badge SVGs") + # The full measurement record behind the badges, read by the Pages + # quality dashboard (ci/build-pages.py). + data = (ROOT / "badges" / "quality.json").read_bytes() + if not isinstance(json.loads(data), dict): + raise ValueError("invalid quality.json") + publish_file(api, repo, "badges/quality.json", data, token, + "Update measured quality record", max_bytes=262_144) + print(f"Published {len(NAMES)} measured badge SVGs and quality.json") if __name__ == "__main__": diff --git a/ci/publish-pages.py b/ci/publish-pages.py new file mode 100755 index 00000000..71334039 --- /dev/null +++ b/ci/publish-pages.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Publish the built Pages site to this repository's gh-pages branch. + + publish-pages.py SITE_DIR + +Served at https://blueflare.gitea.bluefla.re/alkane-toolkit/ by the Pages +server, which serves the gh-pages branch of public repositories. Each publish +is one orphan commit (force-pushed), so the branch never accumulates history. +Only main may publish, and a run for a superseded main commit skips. +""" + +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +from urllib.request import Request, urlopen + +BRANCH = "gh-pages" +MAX_BYTES = 20 * 1024 * 1024 + + +def current_main_sha(api: str, repo: str, token: str) -> str: + request = Request(f"{api}/repos/{repo}/branches/main", + headers={"Authorization": f"token {token}"}) + with urlopen(request, timeout=20) as response: + return json.load(response)["commit"]["id"] + + +def git(*args: str, cwd: Path, env: dict | None = None) -> None: + subprocess.run(("git", *args), cwd=cwd, env=env, check=True) + + +def main() -> None: + if len(sys.argv) != 2: + sys.exit(__doc__) + site = Path(sys.argv[1]) + if not (site / "index.html").is_file(): + sys.exit(f"{site} has no index.html") + size = sum(p.stat().st_size for p in site.rglob("*") if p.is_file()) + if size > MAX_BYTES: + sys.exit(f"site is {size} bytes, over the {MAX_BYTES} byte limit") + for path in site.rglob("*"): + if path.is_file() and path.suffix not in {".html", ".css", ".svg", ".png", ".json"}: + sys.exit(f"unexpected file type on the site: {path}") + + api = os.environ["GITHUB_API_URL"].rstrip("/") + repo = os.environ["GITHUB_REPOSITORY"] + sha = os.environ["GITHUB_SHA"] + token = os.environ["GITEA_TOKEN"] + if os.environ.get("GITHUB_REF") != "refs/heads/main": + sys.exit("Pages publication requires main") + if current_main_sha(api, repo, token) != sha: + print("Skipping Pages for a superseded main commit") + return + + server = api.removesuffix("/api/v1") + with tempfile.TemporaryDirectory(prefix="alkane-pages-") as directory: + work = Path(directory) + shutil.copytree(site, work, dirs_exist_ok=True) + env = dict(os.environ, GIT_TERMINAL_PROMPT="0") + git("init", "-q", "-b", BRANCH, cwd=work) + git("-c", "user.name=Alkane CI", "-c", "user.email=ci@noreply.gitea.bluefla.re", + "add", "-A", cwd=work) + git("-c", "user.name=Alkane CI", "-c", "user.email=ci@noreply.gitea.bluefla.re", + "commit", "-q", "-m", f"Publish site for {sha[:10]} [skip ci]", cwd=work) + # The token is read from the environment by the credential helper at + # push time; it never appears on a command line or in the remote URL. + helper = '!f() { echo username=alkane-ci; echo "password=$GITEA_TOKEN"; }; f' + git("-c", f"credential.helper={helper}", "push", "-q", "--force", + f"{server}/{repo}.git", f"HEAD:refs/heads/{BRANCH}", cwd=work, env=env) + print(f"Published Pages for {sha[:10]} to {BRANCH}") + + +if __name__ == "__main__": + main() diff --git a/ci/test-bench-badge.py b/ci/test-bench-badge.py index 1cf6ff3d..76af8343 100644 --- a/ci/test-bench-badge.py +++ b/ci/test-bench-badge.py @@ -5,6 +5,7 @@ import importlib.util import re from pathlib import Path +import tempfile import unittest @@ -50,16 +51,35 @@ class BenchBadgeTests(unittest.TestCase): self.assertEqual(gen_badges.bench_color(30.0), "brightgreen") self.assertEqual(gen_badges.bench_color(-55.5555556), "orange") - def test_quality_grade_is_only_the_clippy_result(self): - self.assertEqual(gen_badges.quality_grade("clean"), "A") - self.assertEqual(gen_badges.quality_grade("failed"), "F") - self.assertEqual(gen_badges.quality_grade(None), "pending") - svg = gen_badges.badge_svg( - "code quality", "A", "brightgreen", - "code quality: A (GUI Clippy and first-party rustfmt)", - ) - self.assertIn('aria-label="code quality: A (GUI Clippy and first-party rustfmt)"', svg) - self.assertIn('>A', svg) + def test_quality_grade_follows_lint_and_coverage(self): + # A lint failure fails the grade; otherwise it is the coverage band, + # with the same floors as the coverage badge colour. + self.assertEqual(gen_badges.quality_grade("failed", 95.0), "F") + self.assertEqual(gen_badges.quality_grade("clean", 85.0), "A") + self.assertEqual(gen_badges.quality_grade("clean", 65.6), "B") + self.assertEqual(gen_badges.quality_grade("clean", 48.0), "C") + self.assertEqual(gen_badges.quality_grade("clean", 25.0), "D") + self.assertEqual(gen_badges.quality_grade("clean", 5.0), "F") + self.assertEqual(gen_badges.quality_grade("clean"), "pending") + self.assertEqual(gen_badges.quality_grade(None, 90.0), "pending") + for pct in (85.0, 65.6, 48.0, 25.0): + grade = gen_badges.quality_grade("clean", pct) + self.assertEqual(gen_badges.GRADE_COLORS[grade], gen_badges.cov_color(pct)) + + def test_coverage_table_is_split_by_crate(self): + with tempfile.TemporaryDirectory(prefix="alkane-cov-") as directory: + summary = Path(directory) / "summary.txt" + summary.write_text( + "Filename Regions Missed Regions Cover Functions Missed Functions " + "Executed Lines Missed Lines Cover\n" + "crates/alkane-gui/src/ui.rs 10 5 50.00% 4 2 50.00% 100 60 40.00%\n" + "crates/alkane-core/src/platform.rs 4 0 100.00% 2 0 100.00% 50 5 90.00%\n" + "TOTAL 14 5 64.29% 6 2 66.67% 150 65 56.67%\n") + rows = gen_badges.coverage_by_file(str(summary), directory) + self.assertEqual([r["file"] for r in rows], + ["crates/alkane-gui/src/ui.rs", "crates/alkane-core/src/platform.rs"]) + self.assertEqual(rows[0]["missed"], 60) + self.assertEqual(gen_badges.crate_of(rows[1]["file"]), "alkane-core") if __name__ == "__main__": diff --git a/code-review-report.md b/code-review-report.md deleted file mode 100644 index 21bb6d19..00000000 --- a/code-review-report.md +++ /dev/null @@ -1,111 +0,0 @@ -# Code review report -- Round 19 - -A multi-agent review of the Round 19 changes (columns, scan fast-path + -concurrency, per-firmware log delegation, export dialog, the wx-rs bridge -alignment/tooltip work, and the bench-delta CI badge). Four reviewers ran in -parallel across correctness, reliability/concurrency, the C++ bridge + UI, and -security/CI. Every finding was re-read against the code before it was acted on. - -## Verdict - -Ready to ship. No Critical findings. The one High (a single miner's telemetry -panic could abort the whole scan) is fixed with per-miner panic isolation. The -Mediums (right-aligned zebra fill, the scan-concurrency ceiling, and the -board-voltage/frequency sort key) are fixed. The tooltip hit-test Medium is -resolved by the Health-column uniform-slot fix. The remaining items are Lows and -documented tradeoffs. CI run 95 was green (93 unit tests + 9 microbenchmarks + -the headless self-test), and the fixes re-check clean (`cargo check --tests`, -`clippy --no-deps -D warnings`). - -## Scope - -Round 19 source only: `crates/alkane-gui/src` (model.rs, ui.rs, scan.rs, -log_scan.rs, export.rs, fixtures.rs, main.rs, presets.rs), `ci/` -(bench-badge.py, gen-badges.py), `.gitea/workflows/release.yml`, and the two -changed wx-rs bridge files (`src/widgets.rs`, `cpp_src/widgets_bridge.cpp`). -Vendored asic-rs and the wxWidgets tree were out of scope (read-only, and the -CIFS mount cannot be recursed safely). - -## Fixed - -- **[High] No panic isolation around per-miner telemetry** (scan.rs). asic-rs - backends parse miner-controlled data; a panic in one miner's `get_data` unwound - the whole scan thread, aborting every other miner and leaving the Round-19 - partial identity rows stranded. `to_row` is now wrapped in - `AssertUnwindSafe(..).catch_unwind()`, so a panicked miner is skipped (keeping - its partial identity row) and the sweep continues. (`panic = "unwind"` in the - release profile makes this effective.) -- **[Medium] Zebra stripe missing on the left of right-aligned colored columns** - (widgets_bridge.cpp, SegmentRenderer::Render). Right-aligning the colored - columns (round 19 #21) anchored the zebra fill at the content's left edge, so - the left portion of each cell kept the base colour. The fill now over-spans the - column in both directions and lets the cell-DC clip trim it. -- **[Medium] Health-column tooltip landed on the wrong icon** (widgets_bridge.cpp). - The per-icon advance used a different formula in GetSize, DrawShape, and the - tooltip hit-test, so the slot boundaries drifted. All three now use one uniform - fixed-width slot (see the Health-column change below), so the hit-test lines up. -- **[Medium] Scan-concurrency ceiling too high** (scan.rs). The user-adjustable - cap allowed 512; the code documents that 128 is fully reliable and 192 already - dropped responders (which read as phantom faults). Ceiling lowered to 256. -- **[Medium] Board voltage/frequency sort key averaged placeholder zeros** - (model.rs). Those columns store 0.0 for a board with no reading (rendered "-"), - but the sort/filter key averaged the zeros too, mis-ranking miners. A new - `avg_positive` helper skips non-positive entries (board hashrate keeps a plain - average -- a 0.0 there is a genuinely idle board). -- **[Low] Accepted/rejected share summation could overflow** on miner-controlled - counts (scan.rs, model.rs) -- now `saturating_add`. -- **[Low] Orphaned doc comment**: `efficiency_display`'s docs had attached to - `reject_ratio`; reordered. -- **[Low] Stale comment** ("3 combined columns" -> two after the Boards removal). - -## Health-column follow-up (operator-reported) - -The right-aligned Health column did not line up across rows: every miner is -padded to the same NUMBER of component-icon slots, but the individual glyphs -(bolt, brain, fan, chip, gap) have different widths, so flush-right the columns -drifted. Fixed by giving every health icon a UNIFORM fixed-width slot in both -`SegmentRenderer::GetSize` and `DrawShape` (each glyph centred in its slot), and -left-aligning the icon columns (Health/Access/Light) so the block anchors at a -consistent left edge. The tooltip hit-test uses the same uniform slot, which also -resolves the tooltip Medium above. - -## Accepted / documented tradeoffs - -- **Security (Low, release.yml):** the badge push-back passes the ephemeral, - repo-scoped Gitea run token via `git -c http.extraheader`; it is never logged, - but is briefly visible in the runner's process argv. Acceptable on the single - single-tenant capped runner. -- **`[skip release]` (Info):** Gitea recognises `[skip ci]`, not `[skip release]`, - so the badges-only commit does trigger a second workflow run -- but that run cuts - no release (compute-version.sh treats `badges/*`, including bench-baseline.json, - as no-bump), which is the intended, verified behaviour. -- **Paused-blue can mask a faulty board (#19):** a paused miner's detected boards - all render blue by design; power/control/fans keep their true colours. -- **`do_export` opens the save dialog under the App borrow:** harmless - (`try_borrow_mut` drops re-entrant timer ticks; the native save dialog emits no - wx widget events), the scan channel just buffers while it is open. - -## Verified sound (no change) - -- Fast-scan partial/full ordering: `buffer_unordered` polls inline on the - single block_on thread and the partial is sent before the future awaits - `get_data`, so a full row never precedes its own partial; the UI `upsert_into` - keys by IP, so the full row replaces the partial (preserving selection). -- WhatsMiner log fallback: `naming::brand` returns "WhatsMiner", which matches the - case-insensitive brand gate, so WhatsMiner correctly routes to the fault-code - view. -- Every new Column arm is internally consistent (is_numeric <-> sort_key <-> - num_value <-> cell blank logic); `timestamp_utc` matches UTC over 200k samples; - the export column subset keeps headers and values aligned; the bench-badge - parser handles all nine bench line formats and the weighted delta is correct; - `tail()` never panics on a non-UTF8 boundary. - -## Automated verification - -- `cargo check --release --tests -p alkane-gui` -- clean (local). -- `cargo clippy -p alkane-gui --no-deps --release --bins -- -D warnings` -- clean. -- CI run 95 (v0.65.0): 93 unit tests + 9 microbenchmarks + headless self-test all - pass; coverage 44%. -- Right-alignment verified from a headless screenshot of the built binary; the - Health-column and paused-blue changes are verified in the next release's - screenshot. diff --git a/crates/alkane-gui/src/fixtures.rs b/crates/alkane-gui/src/fixtures.rs index 81e8da8f..a01e792f 100644 --- a/crates/alkane-gui/src/fixtures.rs +++ b/crates/alkane-gui/src/fixtures.rs @@ -1,6 +1,6 @@ -//! Bench-fleet fixtures: the expected hardware output of the 9 boards on -//! 10.255.1.0/24 (see ../../../HANDOFF.md section 7 and the parent project's -//! MEMORY-SNAPSHOT). These are the reference values the workflow tests compare +//! Fixture fleet: the expected hardware output of nine representative miners +//! (one per control-board family / firmware). These are the reference values +//! the workflow tests compare //! the application's actual output against, and the rows the offline //! `ALKANE_FAKE_SCAN` demo mode renders. Only miners that respond become rows, //! so there is no synthetic "offline" fixture. diff --git a/docs/IMPLEMENTATION-PLAN.md b/docs/IMPLEMENTATION-PLAN.md deleted file mode 100644 index 7b9474eb..00000000 --- a/docs/IMPLEMENTATION-PLAN.md +++ /dev/null @@ -1,117 +0,0 @@ -# Toolkit plan - -Drafted 2026-09-14. This is an installer design reference. See the -[README](../README.md) for current delivery status. - -## Scope - -The Toolkit is planned to install stock or Alkane OS from stock, -Vnish/AnthillOS, Braiins OS+, LuxOS, ePIC UMC, BixBit, and WardenOS. -The SDK owns board data, image packers, and build outputs. The Toolkit -owns discovery, access, execution, verification, and the operator UI. -An entry in this plan is a target, not a shipping install path. - -The source rules are [SDK install methods](https://gitea.bluefla.re/blueflare/alkane-sdk/src/branch/main/docs/install-methods.md), -[firmware recipes](https://gitea.bluefla.re/blueflare/alkane-sdk/src/branch/main/install/from-firmware/README.md), -and `boards/*/board.yml`. The bench evidence cited below includes the -S17 NAND restore (2026-09-14), WhatsMiner network updates and `/data` -overlay, Amlogic stock capture, and Braiins CV bootloader analysis. - -## Install pipeline - -``` -discover -> classify -> root access -> pack -> backup -> transfer -> write - -> verify write -> select boot -> reboot -> verify live - -> verify after at least two unattended power cycles -``` - -Each `{board, source OS}` recipe supplies typed parameters to one engine -([ADR 0001](adr/0001-recipes-as-data.md)). Each stage must be resumable -or idempotent and write an audit record. The GUI and CLI use the same -engine; board facts come from the SDK. WhatsMiner package builders must -match captured vendor output byte for byte when ported from Python. - -## Safety requirements - -1. Refuse writes to bootloader and secure partitions in the engine. -2. Verify a positive marker and liveness over an independent channel, - then pass at least two unattended power cycles. -3. Treat a dropped SSH session after root-initiated reboot as possible - success; reclassify over the liveness channel. -4. Bind each image packer to its board and verify boot-switch state. -5. Require a live serial console before kernel or boot-adjacent writes. -6. Verify image digest and format before writing, and read back over an - independent channel. Protect live earners from broad auth attempts; - teardown requires explicit operator authorization in the audit log. - -These requirements encode recorded UBI volume-name and installer-exit -false positives. The SDK documents the per-board recovery path. - -## Components - -| Component | Planned responsibility | -| --- | --- | -| `alkane-core` | Board, OS, artifact, partition, stage, and safety types | -| `alkane-discovery` | Vendored asic-rs 0.8.1 scan, CIDR lists, classification, and a planned ARP/ICMP pre-pass for silent boards | -| `alkane-access` | SSH with legacy algorithms, Bitmain and WhatsMiner port 4028 clients, and serial transport where network receive is broken | -| `alkane-flash` | SSH stream transfer for minimal BusyBox, MTD/eMMC writes, board packers, readback, U-Boot environment updates, LuxOS installer, and IMAGEWTY tooling | -| `alkane-artifacts` | SHA-256 manifest and image magic, size, and integrity checks; seed manifest has 14 bench artifacts | -| `alkane-cli` | Headless bench and scripting commands for the same engine | -| `alkane-gui` | Rust wxWidgets UI through patched wx-rs ([ADR 0002](adr/0002-gui-bindings.md)); primary view in [UI spec](UI-SPEC.md) | - -Access details include the WhatsMiner `update_firmware` token and -AES-ECB/u32-LE chunk framing, old stock SSH algorithms, and serial -base64/bzip2 transfer for A113D. Flash recipes must retain the -single-block U-Boot environment readback and per-board format checks. - -## Bench pathways - -The matrix records physical install observations. It does not prove that -the Toolkit implements them. The recipe schema must represent each row. - -| Board (SoC) | Proven installs | Foothold on stock | Transfer | Hard rules | -|---|---|---|---|---| -| am335x-bb (S19j Pro) | 5/5 network-only (stock, LuxOS, ePIC, Braiins, Vnish -> OurOS), round-tripped | `miner:miner` + update-daemon loopback RCE | SSH/SFTP | autoboot abort = ESC with 1 s window (catcher first, then power); mtd0-3 never written; bootloader written last; no SD boot proven; NAND is the only net | -| zynq-7010 (S19) | stock->OurOS, Vnish->OurOS network-only | `miner:miner` + loopback RCE | SSH/SFTP | PS RSA eFuse is per-unit; read 0xF800D010 before planning; FIT unverified branch is the entry; autoboot 0 s (keys must pre-flood); stock console echoes but no getty | -| zynq-7010 (S17) | stock NAND restore verified by CRC through U-Boot (2026-09-14) | stock `root` with EMPTY password; legacy SSH algos (dh-group1-sha1, ssh-rsa, aes128-cbc) | ymodem over serial for NAND writes; SSH for userspace | board mtd char/block reads return EIO; verify only via U-Boot `nand read`+`crc32`; ymodem splits at ≤2047 blocks; `reboot -f` no-ops from RAM-boot (sysrq `b`) | -| a113d (BHB42XXX) | 5/5 | `miner:miner` + loopback RCE; `amlenv.py` edits env in-band over SSH (`/dev/nand_env`) | SSH (net), U-Boot env is the boot switch | UBI volume name is order-dependent (`nvdada_log`/`umc_os_rootfs`/`overlay`); detect live, never hardcode; per-OS DHCP lease differs (false DARK trap; a failed self-report downgrades to WARNING, SSH fingerprint decides) | -| a113d hardened (S21 Pro) | stock restore via env swap; two root paths | `miner:miner`; daemon injection char-whitelisted (dead); use `eclipse`/`updatem` forged `{type:root}` package -> sudoers -> root | SSH or serial-only (base64/bzip2, ~10 KiB/s, ~11 min install) | stock busybox has no wget/nc/tftp/curl/gzip/xz; console arg must be `ttyAML0`+`meson` earlycon or the board boots blind and the install looks failed | -| cv1835 (S19k Pro) | 3/3 buildable (LuxOS no asset, ePIC wrong silicon excluded) | `miner:miner` + `/nvdata/rroot` (non-permanent; p7 reformat destroys it; gate on `rroot -c id`) or loopback RCE | SSH pipe (`cat >`, busybox has no wget/tftp/nc) | Vnish/Braiins are RAM overlays on stock kernel; exit while overlay is live; eMMC boot0 eFuse-hook units cannot SD-recover; golden copy at raw LBA 0x300000 is the only net; serial catch needs 3 ms flood | -| allwinner H3/H6/H616 (WhatsMiner) | rooted `/data` overlay survives genuine reinstall (proven on H616); genuine network update executed on H3 + H616 | `admin:admin` uid-300 shell; root via `/data/rootshell` overlay (persists) or rooted SD image | 4028 API `update_firmware` (AES-ECB + md5crypt token, ≤1 MB chunks); IMAGEWTY SD-burn for rooted card | package format 0x9A5BA57C forgeable (MD5+CRC only); 8889 binary daemon AES key unknown; not implementable, use 4028; H616 payload key eFuse/OP-TEE-bound; H3 rootfs.fex LUKS (only /data slices editable); random MAC -> DHCP moves | - -Antminer port 4028 uses `{"command":...}`; WhatsMiner uses -`{"cmd":"get_version"}`. SSH banner and KEX help classify old stock. - -## Milestones - -| Phase | Exit condition | -| --- | --- | -| M0 | Workspace, CI, vendored asic-rs/wxWidgets/wx-rs, and Rust GUI decision recorded | -| M1 | Nine-board bench discovery view, scan ranges, filters, columns, and silent-board classification | -| M2 | Artifact registry and image verification, including bulk archives and per-model corpus | -| M3 | Zynq-7010 stock restore, then Alkane OS installation after SDK release qualification; readback, boot switch, liveness, and persistence gates | -| M4 | Guided SD recovery builders and verified image burn | -| M5 | WhatsMiner, A113D, CV1835, and AM335x install pathways | -| M6 | Install wizard, progress and cancel, audit log, and platform packaging | - -The SDK now builds rootfs artifacts for all seven boards. No production -image or Toolkit installation pathway is qualified. The first install -milestone remains blocked by release evidence and installer implementation. -Bench validation closes each milestone; do not exercise live earners -without explicit authorization. - -## Open questions - -- Which stock image version is canonical for each board? The bench corpus - has an S17 restore image; other stock packages need selection. -- Which SDK release should the installer pin after board and simulator - gates pass? -- Which of Linux, Windows, and macOS must ship in the first GUI package? - -## References - -- [SDK install rules](https://gitea.bluefla.re/blueflare/alkane-sdk/src/branch/main/docs/install-methods.md) -- [SDK firmware recipes](https://gitea.bluefla.re/blueflare/alkane-sdk/src/branch/main/install/from-firmware/README.md) -- `bench-wiki/boards/` and `MEMORY-SNAPSHOT/` in the parent workspace -- `crates/alkane-artifacts/data/manifest-seed.csv` -- `scratch/wm-install-build/` package and IMAGEWTY builders in the parent workspace diff --git a/docs/adr/0003-vendoring-policy.md b/docs/adr/0003-vendoring-policy.md index 72a9d9b6..a7f2b955 100644 --- a/docs/adr/0003-vendoring-policy.md +++ b/docs/adr/0003-vendoring-policy.md @@ -61,6 +61,6 @@ Rules: ## Consequences - The repo grows by the vendored sources (one-time; git-compressed). -- Offline/reproducible builds on any machine, including the bench Pi. +- Offline/reproducible builds on any machine. - Updating either dependency is mechanical, reviewable, and never entangles our changes with upstream files. diff --git a/docs/aftermarket-parity-roadmap.md b/docs/aftermarket-parity-roadmap.md deleted file mode 100644 index ead28ae9..00000000 --- a/docs/aftermarket-parity-roadmap.md +++ /dev/null @@ -1,468 +0,0 @@ -# Firmware parity - -This plan covers configuration and telemetry parity. It excludes firmware -installation. The original audit was read-only and made no live miner changes. - -It compares the Toolkit with Braiins Toolbox/BOS, LuxOS/luxminer, ePIC -PowerPlay/UMC, WhatsMinerTool/btminer, Vnish, and stock Antminer. Sources -include the Toolkit baseline audit, vendor API/help surfaces, and the -read-only device checks listed under [Verification](#verification). - -At the audit point, Antminer support covered 15 of 58 features fully and -15 partially (about 39% weighted parity). WhatsMiner covered 12 of 30 -fully and 5 partially (about 48%). Missing work centers on structured -tuning, cooling, fan control, auto-scaling, network settings, and CLI -coverage. The gap list below records each feature and its evidence. - -## Parity matrices - -Legend: our_support = have / partial / missing. UI = exposed in GUI right-click menu today. -CLI = exposed in committed `miner_probe` today (uncommitted local-only additions are marked -`local`). Toolkit columns: B = Braiins toolbox/BOS, L = LuxOS/luxminer, V = VNish, E = ePIC/ -PowerPlay, S = stock Antminer. A dot means that toolkit exposes the feature. - -### Antminer - -Category C = config, T = telemetry/scan. - -| # | Feature | Cat | B | L | V | E | S | our_support | asic-rs trait | UI | CLI | -|---|---------|-----|---|---|---|---|---|-------------|---------------|----|-----| -| 1 | Discovery + make/model/fw ID | T | . | . | . | . | . | have | MinerFactory + Validate + GetDeviceInfo | yes | scan | -| 2 | Device identity (mac/serial/host/ctrl-board/versions/PIC) | T | . | . | . | . | . | have | GetMAC/GetHostname/GetSerialNumber/GetControlBoardVersion/GetApiVersion/GetFirmwareVersion | yes | scan | -| 3 | Live telemetry core (hr/exp-hr/watts/eff/temps/fans/state/uptime/light) | T | . | . | . | . | . | have | GetHashrate/GetExpectedHashrate/GetWattage/GetHashboards/GetFans/GetOperatingState/GetIsMining/GetUptime/GetLightFlashing | yes | no | -| 4 | Per-hashboard telemetry (board_name/chip_type/multi-window) | T | . | . | . | . | . | partial | GetHashboards | yes | no | -| 5 | Fan RPM + commanded duty ratio | T | . | . | . | . | . | partial | GetFans | yes | no | -| 6 | Pool list + extended per-pool share stats | T | . | . | . | . | . | partial | GetPools | yes | no | -| 7 | Best share + session best share | T | . | . | . | . | . | missing | GetBestShare/GetSessionBestShare (empty impls) | no | no | -| 8 | PSU info (model/hw/fw/voltage range) | T | . | . | . | . | | missing | none (new GetPsuInfo) | no | no | -| 9 | Fluid / immersion temperature | T | . | . | . | | | partial | GetFluidTemperature (BOS empty; VNish impl) | yes | no | -| 10 | Tuning target read (configured + scaled) | T | . | . | . | . | | partial | GetTuningTarget/GetScaledTuningTarget | yes | no | -| 11 | Tuner / power / hashrate constraints read | T | . | . | | . | | partial | GetTuningCapabilities (BOS have; Lux limits missing) | yes | no | -| 12 | Cooling constraints read | T | . | . | | . | | missing | none (new GetCoolingCapabilities) | no | no | -| 13 | DPS / hashboard / scaling constraints read | T | . | . | | . | | missing | none (new) | no | no | -| 14 | Advanced keyed settings read (22 keys) | T | . | | | | | missing | none (new AdvancedSettings) | no | no | -| 15 | Network config read (ip/mask/gw/dns/proto) | T | . | . | . | . | | partial | partial (GetMAC/GetHostname drop the rest) | no | no | -| 16 | Diagnostics data-collection archive | T | . | | | . | | partial | ReadLogs (compose) | no | no | -| 17 | Firmware update check (read only) | T | . | . | . | . | | have | UpgradeFirmware::check_firmware_update | no | no | -| 18 | Structured messages / events / appeals | T | . | . | . | . | . | have | GetMessages | yes | no | -| 19 | Per-chip health detail (score/errors) | T | | . | | | | partial | DataField::Chips (reduced) | no | no | -| 20 | Per-chip frequency array | T | | . | | | | missing | none (frequencyget unused) | no | no | -| 21 | Temp-control targets read | T | . | . | . | . | | missing | none (Lux tempctrl / ePIC shutdowntemp unmapped) | no | no | -| 22 | Limits / bounds read | T | | . | | . | | missing | none (Lux limits / ePIC capabilities partial) | no | no | -| 23 | Operating-state / paused (derived) | T | . | . | . | . | | partial | GetOperatingState (Lux missing/derivable) | yes | no | -| 24 | Perpetual-tune / ATM / DPS status read | T | . | . | | . | | missing | none (ePIC perpetualtune / Lux atm unmapped) | no | no | -| 25 | Scheduler / idle-periods read | T | | | | . | | missing | none | no | no | -| 26 | Fault / locate light on-off | C | . | . | . | . | . | have | SetFaultLight | yes | local | -| 27 | Pause mining | C | . | . | . | . | . | have | Pause | yes | no | -| 28 | Resume mining | C | . | . | . | . | . | have | Resume | yes | no | -| 29 | Restart / reboot | C | . | . | . | . | . | have | Restart | yes | no | -| 30 | Configure pools (write) | C | . | . | . | . | . | have | SupportsPoolsConfig | yes | local | -| 31 | Set power limit / power target (watts) | C | . | . | . | . | . | have | SetPowerLimit (VNish masked) | yes | local | -| 32 | Set tuning percent / throttle | C | | | . | | | have | SetTuningPercent | yes | no | -| 33 | Set hashrate target + tuner-mode + reset + steps | C | . | . | . | . | | missing | SupportsTuningConfig (BOS false) | no | no | -| 34 | Named preset / profile select | C | | . | . | . | | partial | SupportsPresets + SupportsTuningConfig::Preset | no | no | -| 35 | Custom profile create / remove | C | | . | | | | missing | none (profilenew/profilerem) | no | no | -| 36 | Per-board voltage + frequency override | C | | . | . | . | | missing | SupportsTuningConfig::Manual (unwired) | no | no | -| 37 | Cooling config (mode/temps/fan-pause/min-fans/range) | C | . | . | . | . | | missing | partial (SupportsTemperatureConfig/FanConfig defaults) | no | no | -| 38 | Manual fan control | C | | . | | . | . | missing | SupportsFanConfig (antminer/epic true; unwired UI) | no | no | -| 39 | Temperature / thermal-limit config | C | . | . | . | . | | partial | SupportsTemperatureConfig (VNish only) | no | no | -| 40 | DPS / auto-scaling config | C | . | | | . | | missing | SupportsScalingConfig (epic true; BOS false) | no | no | -| 41 | ATM auto-thermal-tuning (min/max profile + windows) | C | | . | | | | missing | none (new SupportsAutoTuningConfig) | no | no | -| 42 | Perpetual-tune config (algo + target) | C | | | | . | | missing | none (new; overlaps auto-tuning trait) | no | no | -| 43 | Timezone config | C | . | | . | . | | partial | SupportsTimezoneConfig (backends done, UI/CLI missing) | no | no | -| 44 | Change password | C | . | | . | . | | partial | ChangePassword (backends done, UI/CLI missing) | no | no | -| 45 | Factory reset | C | . | | . | | | partial | FactoryReset (backends done, UI/CLI missing) | no | no | -| 46 | Network config write (dhcp/static) | C | . | . | . | . | | missing | none (new SupportsNetworkConfig) | no | no | -| 47 | Advanced keyed settings write | C | . | | | | | missing | none (new AdvancedSettings) | no | no | -| 48 | Remove tuned profiles (force retune) | C | . | | | | | missing | none | no | no | -| 49 | Stock miner mode (high/normal/low/sleep) | C | . | | | | . | missing | SupportsTuningConfig::MiningMode (stock impl, unwired) | no | no | -| 50 | Chip health check trigger | C | | . | | | | missing | none (healthchipset) | no | no | -| 51 | Reset miner (process restart, no reboot) | C | | . | | | | missing | none (reset_miner unwired) | no | no | -| 52 | Kill (hard-stop) | C | | . | | | | missing | none | no | no | -| 53 | Hostname set | C | . | . | . | . | | missing | none (mostly install-time on Lux) | no | no | -| 54 | Coin type select | C | | | | . | | missing | none (/coin) | no | no | -| 55 | Board enable / disable | C | | | | . | | missing | none (/boardenable) | no | no | -| 56 | Scheduler / idle-periods write | C | | | | . | | missing | none (/scheduler) | no | no | -| 57 | Shutdown-temp / critical-temp / overdrive / idle-on-loss | C | | | | . | | missing | none (ePIC misc setters) | no | no | -| 58 | Custom contract apply (Braiins pool) | C | . | | | | | missing | none (niche) | no | no | - -Antminer totals: have 15, partial 15, missing 28 (of 58). - -### WhatsMiner - -Toolkit column W = WhatsMinerTool / btminer API (:4028 read + :8889 or 4028-token write). -btminer notes: :4028 is anonymous read-only; privileged writes go to :8889 (AES-ECB + md5-crypt -token) or 4028 with host_sign token. Confirmed writes on stock BTMiner: update_pools, -restart_btminer, set_power_pct, reboot, poweroff, update_network, update_password, restore_factory, -restore_dhcp, update_power_mode, update_coin_type. Confirmed NOT on stock 4028: set_freq, -set_voltage, set_led, adjust_power (LED/per-board tuning live in the ~40% uncharted :8889 space). - -| # | Feature | Cat | W | our_support | asic-rs trait | UI | CLI | -|---|---------|-----|---|-------------|---------------|----|-----| -| 1 | Discovery + make/model/fw ID | T | . | have | MinerFactory + Validate | yes | scan | -| 2 | Device identity (mac/serial/model/control-board) | T | . | have | GetMAC/GetSerialNumber/GetDeviceInfo | yes | scan | -| 3 | Live telemetry core (hr/exp/watts/eff/temps/fans/uptime) | T | . | have | GetHashrate/GetWattage/GetHashboards/GetFans/GetUptime | yes | no | -| 4 | Ambient / environment temperature | T | . | have | GetFluidTemperature (ambient) | yes | no | -| 5 | PSU fan RPM | T | . | have | GetFans (PSU fan, WhatsMiner-only) | yes | no | -| 6 | Pool list + accepted/rejected | T | . | have | GetPools | yes | no | -| 7 | Best share + session best share | T | . | missing | GetBestShare/GetSessionBestShare (empty) | no | no | -| 8 | PSU info (get_psu: model/vout/true-power) | T | . | missing | none (new GetPsuInfo) | no | no | -| 9 | Error codes / health messages (get_error_code) | T | . | have | GetMessages | yes | no | -| 10 | Operating state / paused | T | . | missing | GetOperatingState (not populated for WM) | no | no | -| 11 | Power-mode read (high/normal/low) | T | . | missing | none | no | no | -| 12 | Per-board detail (freq/chips/serial/voltage) | T | . | partial | GetHashboards | yes | no | -| 13 | Fault / locate light on-off | C | . | have | SetFaultLight (supports=true) | yes | local | -| 14 | Restart / reboot | C | . | have | Restart | yes | no | -| 15 | Pause mining | C | . | have | Pause | yes | no | -| 16 | Resume mining | C | . | have | Resume | yes | no | -| 17 | Configure pools (write, 3 slots) | C | . | have | SupportsPoolsConfig | yes | local | -| 18 | Set power limit (watts) | C | . | partial | SetPowerLimit (v1/v2/v3; error-swallow bug r15 #4) | yes | local | -| 19 | Power-mode set (high/normal/low/sleep) | C | . | partial | SupportsTuningConfig (v2/v3 true; MiningMode unwired) | no | no | -| 20 | Set power percent | C | . | missing | none (set_power_pct; SetTuningPercent false for WM) | no | no | -| 21 | Poweroff device | C | . | missing | none (distinct from pause) | no | no | -| 22 | Change password (update_password) | C | . | missing | ChangePassword (WM supports=false) | no | no | -| 23 | Network config (update_network / restore_dhcp) | C | . | missing | none (new SupportsNetworkConfig) | no | no | -| 24 | Factory reset (restore_factory) | C | . | missing | FactoryReset (WM supports=false) | no | no | -| 25 | Coin type select (update_coin_type) | C | . | missing | none | no | no | -| 26 | Timezone / NTP config | C | . | missing | SupportsTimezoneConfig (WM false) | no | no | -| 27 | Fan / cooling config | C | . | missing | SupportsFanConfig (WM false) | no | no | -| 28 | Per-board freq / voltage tuning | C | . | missing | none (not on stock 4028; :8889 uncharted) | no | no | -| 29 | Structured tuning config (target) | C | . | partial | SupportsTuningConfig (v2/v3 true; unwired UI/CLI) | no | no | -| 30 | Restore miner setting (revert config) | C | . | missing | none | no | no | - -WhatsMiner totals: have 12, partial 5, missing 13 (of 30). - ---- - -## Gaps - -Each gap gives: asic-rs backend work, ui.rs ConfigAction / action wiring, miner_probe/CLI surface, -clean-integration note, hardware verification plan (IP/model + read-back + restore), and priority. -Standard UI wiring for any NEW capability (a compile break otherwise), applied throughout below: -(1) add bool to `struct MinerCaps` (model.rs); (2) add to `MinerCaps::intersect` and `any_control()`; -(3) set it in the caps literal in scan.rs `to_row` from the matching `supports_*()`; (4) add a -`ConfigAction` variant with label()/progress_label(); (5) add an apply_action arm calling the -`&dyn Miner` trait method; (6) add ID_CTX_* const + a gated `menu.menu_append` block + a handler -arm in ui.rs; (7) add a `miner_probe` subcommand. Any NEW setter trait must join the -`SupportsConfigs` supertrait bundle (traits/miner.rs) and get a `ConfigField` variant -(config/collector.rs) or it will not dispatch on `&dyn Miner`. - -HARD constraint reflected in every verification plan: config-WRITE tests run on a bench/lab unit -or a unit pulled from production during a maintenance window, NEVER on the live production units -that are read-only (BOS .83/.27, LuxOS .60/.67, ePIC .6/.10, the WhatsMiner fleet). Read paths -verify against those live units. - -### High priority - -G1. Commit a full write CLI in miner_probe (all makes). -- Backend: none (reuse existing traits). -- CLI: promote uncommitted local-only modes into committed subcommands and add config verbs: - `light `, `pause`, `resume`, `restart`, `setpools `, - `config power ` (was `setpl`), plus every new config verb below. Each does - arg-parse + capability gate + constraint clamp before the call. -- Integration: the CLI mirrors the GUI ConfigAction set one-to-one; a shared apply layer keeps - them from diverging. -- HW verify: read-only verbs vs live units (`miner_probe scan`, hashrate). LED is reversible even - on production (does not disturb hashing): set on -> read state true -> set off -> read false. - Disruptive verbs (pause/restart/power) on bench only. -- Priority: HIGH (unblocks scripted fleet ops; every UI action is CLI-invisible today). - -G2. Structured tuning: power target + hashrate target + tuner-mode + reset + relative steps. -- Backend: implement `SupportsTuningConfig` for BraiinsV2604 (set_tuning_config: HashRate -> PUT - performance/hashrate-target, Power -> reuse SetPowerLimit path; switching target type flips - tuner_mode); flip supports_tuning_config -> true. Stock Antminer v2020/v2023_07 already map - `TuningTarget::MiningMode` Low/Normal/High (unwired). WhatsMiner v2/v3 already true. -- UI: `ConfigAction::HashrateTarget(f64)` (or unified TuningTarget action) + MinerCaps.tuning_config - gate + dialog offering power|hashrate|default clamped to tuner_constraints. -- CLI: `config hashrate `, `config tuner default`, `config mode `. -- Integration: one generic tuning action routes to per-make backends; clamp via GetTuningCapabilities. -- HW verify: bench BOS S19J Pro (hashrate_target 70.75-252.57 TH/s) - record tuner_mode+target, - set, read back configuration/miner + tuner-state, restore original. NEVER on .83/.27. -- Priority: HIGH. - -G3. Named preset / profile select. -- Backend: LuxOS - impl `SupportsPresets::get_presets` from `profiles` (21 dynamic steps, list - live never hardcoded) and `SupportsTuningConfig::set_tuning_config(Preset(name)) -> rpc.profileset` - (flip privileged=true; see G16). VNish get_presets already true. ePIC - map Tune Presets from - /capabilities and `POST /tune` / `POST /perpetualtune`. -- UI: MinerCaps.tuning_config + `ConfigAction::Preset(String)` + ID_CTX_PRESET dialog populated - live from get_presets(). Note the existing GUI "Presets" button is unrelated (view layouts). -- CLI: `presets ` (list), `setpreset `. -- HW verify: LuxOS bench (.67 shows config Profile=495MHz/Step -2) - snapshot Profile, profileset - another, read back, restore. NEVER on .60/.67 production. -- Priority: HIGH. - -G4. Cooling configuration (largest missed config family). -- Backend: BOS - impl `SupportsTemperatureConfig` (hot/dangerous/target) + `SupportsFanConfig` - (Auto{target_temp,idle_speed} / Manual{fan_speed}) + a NEW cooling-mode trait/enum - CoolingMode{Auto,Manual,Immersion} + fan-pause (mode/runtime/pwm) + min-required-fans + - custom-fan-range on a CoolingConfig aggregate (endpoint from a web capture; do not execute). - LuxOS - add rpc.tempctrlset + wire tempctrl/fanctrl. ePIC - POST /fanspeed, /fans/minimum, - /shutdowntemp, /criticaltemp. -- UI: `ConfigAction::Cooling(CoolingConfig)` + gate + dialog whose ranges come from cooling - constraints (new CoolingCapabilities read, G8). -- CLI: `config cooling --mode ... --target-temp ... --hot-temp ...`. -- HW verify: bench BOS/LuxOS/ePIC - record cooling/state + config temps + fan duty, set (e.g. - target-temp to current), read back, restore. NEVER on production. -- Priority: HIGH. - -G5. Manual fan control. -- Backend: LuxOS impl `SupportsFanConfig` -> rpc.fanset(speed|-1, min_fans) (already - privileged=true); antminer/epic backends already report supports_fan_config=true (unwired). - ePIC POST /fanspeed. -- UI: MinerCaps.fan + `ConfigAction::Fan(FanConfig)` + ID_CTX_FAN dialog (Auto vs Manual %, - clamped to limits FanSpeed range). -- CLI: `fans ` (read FANCTRL) + `setfan `. -- HW verify: LuxOS bench (.60 FANCTRL FanMinSpeed 20, MinFans 1) - snapshot, fanset 80, read - ~80, restore fanset -1 (auto). Never below thermally safe speed. NEVER on production. -- Priority: HIGH. - -G6. Auto-scaling config: BOS DPS + LuxOS ATM + ePIC PerpetualTune. -- Backend: BOS impl `SupportsScalingConfig::set_scaling_config` (power_step/min_power_target/ - shutdown/duration); note ScalingConfig lacks hashrate_step/on_start_percent/mode - extend it or - carry via set_tuning_config's Option. LuxOS + ePIC need a dedicated core - `SupportsAutoTuningConfig` trait + AtmConfig/PerpetualTuneConfig struct (min/max profile, three - temp windows, startup/post-ramp timings, algorithm select) added to the SupportsConfigs bundle - with a ConfigField::Atm so the collector iterates it. ePIC: POST /perpetualtune{,/algo,/reset, - /errorthrottle} with algorithms VoltageOptimizer/BoardTune/ChipTune/PowerTune (min/max from - /capabilities). -- UI: `ConfigAction::Dps` / `ConfigAction::Atm` / `ConfigAction::PerpetualTune` + gates + dialogs - fed by the constraints reads (G8). -- CLI: `config dps on|off [...]`, `atm ` / `setatm ...`, `config perpetualtune ...`. -- HW verify: bench per make - record current config, set current-equivalent params, read back, - restore off/original. NEVER on production. -- Priority: HIGH. - -G7. Per-board voltage + frequency override. -- Backend: LuxOS add rpc.voltageset/frequencyset/frequencystop; handle - `TuningTarget::Manual{boards:(freq,voltage)}` in set_tuning_config (exact type match, no new - trait). ePIC POST /tune/clock/{all,board,chip}, /tune/voltage, /tune/config/chip. Determine - per-board vs per-chip grammar on the bench first (Lux frequencyget returns 126 per-chip freqs). -- UI: reuse tuning-config dialog with an Advanced manual per-board mode, clamped to limits. -- CLI: `setmanual `. -- HW verify: bench with CONSOLE access only (bad voltage can damage a board) - snapshot - voltageget/frequencyget, apply small delta, read back, restore via profileset(default). -- Priority: HIGH. - -G8. Constraints / limits / capabilities scan reads (plumbing for every dialog above). -- Backend: BOS parse cooling_constraints + dps_constraints + hashboards_constraints from the - already-fetched WEB_CONSTRAINTS response into new CoolingCapabilities/ScalingCapabilities/ - HashboardCapabilities. LuxOS parse `limits` (PowerTarget 1000-4000, AtmMinutes 1-1440, AtmTemp - 1-10, FanSpeed -1..100, MinFans 0-4, Frequency 100-1000 step 5-25, BypassVoltage 11.5-15.5). - ePIC parse /capabilities (Default Clock/Voltage/Hashrate, Tune Presets, PerpetualTune min/max, - Psu Info). -- UI/CLI: not necessarily a visible column; required to validate/clamp dialog inputs. `limits `, - `capabilities `. -- HW verify: read-only on live units (already captured on .83, .60, .6). No restore. -- Priority: HIGH (blocks safe write dialogs). - -G9. Best share + session best share scan. -- Backend: BOS impl GetBestShare from WEB_MINER_STATS /miner_stats/best_share (or best_share_str - for large diffs; verified 130601978 live on .83; session stays None - BOS has no session field). - LuxOS add DataField::BestShare -> summary /SUMMARY/0/Best Share and SessionBestShare -> - /SUMMARY/0/Best Session Share (verified 638881749 live on .60). WhatsMiner map btminer summary - best-share. All reuse already-fetched responses. -- UI: populates the two existing MinerRow columns that no backend fills today. -- CLI: appears in `scan` extended output. -- HW verify: read-only vs live units, assert equals the API value. No restore. -- Priority: HIGH (cheap, two dead columns). - -### Medium priority - -G10. Timezone config (BOS/VNish/ePIC). -- Backend: COMPLETE (SupportsTimezoneConfig; BOS GraphQL setTimezone, ePIC POST /timezone). No - asic-rs work. -- UI: `ConfigAction::Timezone(Tz)` + MinerCaps.timezone gate + dialog populated from - get_timezone_config's available list. -- CLI: `config timezone `. -- HW verify: bench - read current tz, set to same, read back, restore. Low risk. -- Priority: MEDIUM (pure wiring). - -G11. Change password (BOS/VNish/antminer/ePIC; WhatsMiner needs backend). -- Backend: COMPLETE for BOS/VNish/antminer/ePIC (ChangePassword; re-auths on success). WhatsMiner - gap - impl update_password over the :8889/4028-token path (supports currently false). -- UI: `ConfigAction::ChangePassword(String)` + gate + dialog; GUI must update saved credentials on - success (change_password takes &mut self and re-auths). -- CLI: `config password `. -- HW verify: bench only - change to temp password then back; verify get_data() still authenticates. - NEVER on production (a failed change locks the toolkit out). -- Priority: MEDIUM. - -G12. Factory reset (BOS/VNish/antminer; WhatsMiner needs backend). -- Backend: COMPLETE for BOS/VNish/antminer (FactoryReset; distinct from restore.rs stock-firmware - flow). WhatsMiner gap - impl restore_factory (supports currently false). -- UI: `ConfigAction::FactoryReset` + gate + STRONG double-confirm dialog. -- CLI: `config factory-reset --yes`. -- HW verify: bench only, destructive - read config before/after. NEVER on production. -- Priority: MEDIUM (low frequency, but backend already there). - -G13. Pool config completeness + LuxOS session-bug fix. -- Backend: LuxOS - flip addgroup/groupquota/removegroup/addpool/switchpool/enablepool/disablepool - to privileged=true (they currently send no session_id, so writes fail on password-set units); - add the missing rpc.removepool. Extend build_pools_dialog with incremental ops - (switch/enable/disable/quota/remove) beyond wholesale replace-all. -- UI: richer pools dialog; caps.pools already wired. -- CLI: committed `setpools` already planned in G1; add per-op verbs. -- HW verify: sacrificial bench NOT pointed at a production pool - reproduce the "Missing session_id" - error on a password-set bench unit, then confirm privileged=true fixes it; restore original pools. -- Priority: MEDIUM (correctness bug on locked units). - -G14. Enrich per-hashboard / fan / pool telemetry (fetched-but-discarded fields). -- Backend: BOS add fan target_speed_ratio (commanded duty) to FanData; add stale_shares/ - last_difficulty/generated_work/last_share_time/per-pool best_share to PoolData; add board_name/ - chip_type to BoardData. LuxOS retain per-chip Score/ReadErrors/WriteErrors/BadHashCount from - healthchipget. All from already-fetched responses. -- UI: tooltips / detail panels; additive. -- CLI: extended `scan` / `healthchip `. -- HW verify: read-only vs live units, assert new fields populate (BOS fan duty 0.63 on .83, Lux - per-chip Score 88-102 on .60). No restore. -- Priority: MEDIUM. - -G15. PSU info scan (BOS/ePIC/WhatsMiner). -- Backend: add core PsuInfo struct (model, hw/fw version, min/max voltage, serial, true-power) + - GetPsuInfo trait + MinerData field. BOS reads WEB_MINER_DETAILS /psu_info; ePIC /capabilities - Psu Info; WhatsMiner get_psu (unauth read). -- UI: MinerRow detail/tooltip. -- CLI: appears in scan detail. -- HW verify: read-only (BOS .83 psu APW121215d/e 11.96-15.2V; ePIC .6 PSU Type 117). No restore. -- Priority: MEDIUM. - -G16. Network config read + write (all makes). -- Backend: add core NetworkInfo struct + GetNetworkInfo (read) and NetworkConfig struct + - SupportsNetworkConfig (write, added to the SupportsConfigs bundle + ConfigField::Network). BOS - GET/PUT /network; LuxOS `config` read + rpc.netset; ePIC GET/POST /network + /wifi; WhatsMiner - update_network / restore_dhcp. Confirm grammar on bench first. -- UI: address/protocol MinerRow columns (read); `ConfigAction::Network(NetworkConfig)` + - ID_CTX_NETWORK dialog (write) behind explicit confirm + warning. Pre-fill from the read. -- CLI: `net ` (read), `config network dhcp|static [...] --yes`. -- HW verify: read-only for the read side vs live units. Write on a bench unit with SERIAL/CONSOLE - access ONLY (a wrong static config strands the miner; note the LuxOS fleet uses 1:1 NAT so netset - rewrites the miner's real interface). Change hostname (benign) then restore; do NOT change IP on a - remotely-managed unit. -- Priority: MEDIUM (read side); network-write is high-risk, gate hard. - -G17. Structured messages / per-chip health / temp-target / operating-state reads (LuxOS + ePIC). -- Backend: LuxOS map tempctrl targets (Target/Hot/ChipTarget/WaterInlet) + derive GetOperatingState - from config CurtailMode/IsTuning/SystemStatus + frequencyget per-chip array. ePIC map - PerpetualTune status + Scheduler read + HBStatus. -- UI: optional columns + detail panels; operating-state feeds the Paused column with real state. -- CLI: `tempctrl `, `freqs `. -- HW verify: read-only vs live (Lux .60 tempctrl Target 45/ChipTarget 83; CurtailMode/IsTuning - present). Derived paused state verified after a bench curtail sleep. No restore for reads. -- Priority: MEDIUM. - -G18. WhatsMiner power-mode set + set-power-percent + poweroff. -- Backend: wire WhatsMiner v2/v3 SupportsTuningConfig MiningMode (high/normal/low) via - update_power_mode; add set_power_pct path; add poweroff (distinct from pause). Note the r15 #4 - set_power_limit error-swallow bug should be fixed while here. -- UI: mode selector via the generic tuning action (G2); poweroff as a maintenance menu item with - strong confirm. -- CLI: `config mode `, `config power-pct `, `poweroff --yes`. -- HW verify: bench WhatsMiner (M30S-class) - read summary, set mode, read back, restore; poweroff - characterized on bench then power-cycle to recover. NEVER on the live fleet. -- Priority: MEDIUM. - -### Low priority - -G19. BOS advanced keyed settings (read + write, 22 keys with danger-gating). -- Backend: new AdvancedSettings trait (keyed map + static metadata: type/default/status/min_version/ - enum/min-max/depends-on from `advanced list`); read is safe/additive, write requires danger - confirm. Transport from a web capture; do not execute writes. -- UI: Advanced-settings editor panel validating against metadata, explicit confirm for - status=dangerous keys. -- CLI: `advanced-get [--key K|--all]`, `advanced set [--force]`, `advanced reset`. -- HW verify: read-only vs .83 (22 keys captured). Write on bench, benign key (mdns_enabled) only. -- Priority: LOW-MEDIUM (read side medium, write low). - -G20. LuxOS maintenance: reset-miner / kill / chip-health-check / custom-profile create-remove. -- Backend: add rpc.reset_miner wiring (CLI-only), rpc.healthchipset, rpc.profilenew/profilerem. - kill semantics to be characterized on bench first (recommend omit from fleet GUI). -- UI: profile create/delete under the preset submenu; reset-miner/kill CLI-only. -- CLI: `resetminer `, `healthchip [set ...]`, `profilenew/profilerem`. -- HW verify: bench only. -- Priority: LOW. - -G21. ePIC misc setters: coin type, board enable/disable, scheduler/idle-periods, shutdown/critical -temp, overdrive, idle-on-connection-lost, hostname. -- Backend: POST /coin, /boardenable + /disableboardonfailure + /enableboardsonidle, /scheduler + - /scheduler/idleperiods, /shutdowntemp + /criticaltemp, /overdrive, /idleonconnectionlost, /hostname. -- UI: grouped under an ePIC advanced/maintenance submenu (most are ePIC-specific, gate on make). -- CLI: matching `config ...`. -- HW verify: bench ePIC (.6/.10 are read-only production). -- Priority: LOW. - -G22. Diagnostics collect + firmware update-check surfacing + BOS custom-contract. -- Backend: none new (compose get_data + read_logs + config + constraints into a tarball); surface - check_firmware_update current-vs-latest. Custom-contract is niche Braiins-pool - document/defer. -- UI: "Collect diagnostics..." menu item; optional update badge. -- CLI: `collect [-o dir]`. -- HW verify: read-only compose vs .83. -- Priority: LOW. - ---- - -## Implementation order - -Round A - CLI foundation and cheap wins (unblocks everything else): -- G1 (commit write CLI), G9 (best-share/session-best-share), G8 (constraints/limits/capabilities - reads), G14 (fetched-but-discarded telemetry), G13 backend session-bug fix (LuxOS privileged=true). -Rationale: G8 is required plumbing for the write dialogs; G1/G9/G14 are low-risk and immediately -visible; the LuxOS session fix is a correctness bug. - -Round B - pure UI/CLI wiring of complete backends: -- G10 (timezone), G11 (change password, non-WM), G12 (factory reset, non-WM). -Rationale: backends already implemented; only UI ConfigAction + CLI verbs + dialogs needed. - -Round C - structured tuning (the flagship parity family): -- G2 (power/hashrate target + tuner-mode + stock mining-mode), G3 (preset/profile select), - G7 (per-board override). -Rationale: single generic tuning action + per-make backends; the biggest config-parity closer. - -Round D - cooling and auto-scaling: -- G4 (cooling config), G5 (fan control), G6 (DPS/ATM/PerpetualTune). -Rationale: depends on Round A constraints reads; largest remaining missed family. - -Round E - WhatsMiner config depth: -- G18 (power-mode/power-pct/poweroff), G11+G12 WhatsMiner backends (change_password, - restore_factory), G16 WhatsMiner network (update_network/restore_dhcp). - -Round F - network + advanced + long tail: -- G16 (network read everywhere + gated write), G15 (PSU info), G17 (Lux/ePIC extra reads), - G19 (BOS advanced), G20 (LuxOS maintenance), G21 (ePIC misc), G22 (diagnostics/update/contract). - ---- - -## Verification - -Confirmed on real hardware, read-only, this run: -- Braiins OS: 10.4.1.83 and 10.4.1.27 (Antminer S19J Pro NoPic, BOS 26.09-plus, API 1.8.0). Verified - live: version/details/network/miner_stats/hashboards/cooling-state/pools/tuner-state/constraints, - best_share 130601978, tuner_constraints (power 944-6435 W, hashrate 70.75-252.57 TH/s), cooling + - dps + hashboards constraints, PSU info, fan duty 0.63, configured-tuning-target None in default - power mode (both units), advanced 22-key read via braiins-toolbox. -- LuxOS: 10.4.1.60 (Profile default) and 10.4.1.67 (Profile 495MHz/Step -2), Antminer S19j Pro, - LUXminer 2026.9.21, API 3.7, IsPowerTargetSupported=false. Verified live: version/summary/stats/ - devs/devdetails/temps/fans/pools/events, 21 profiles, full `limits` bounds table, atm, tempctrl, - fanctrl (FANCTRL), healthchipget per-chip, frequencyget (126 freqs), voltageget, config network + - Update* + CurtailMode/IsTuning/SystemStatus, best-share 638881749; check-command matrix (Exists/ - Access) for led/profileset/atmset/fanset/tempctrlset/voltageset/frequencyset/curtail/rebootdevice/ - resetminer/kill/netset and the N/N set hostnameset/passwd/timezone/timezoneset/factoryreset. -- ePIC / PowerPlay UMC: 10.4.1.6 and 10.4.1.10 (AntMiner S19j Pro, BM1362), UMC API v1.36.0, 63 - OpenAPI paths captured. Verified live read-only: /summary, /capabilities (Tune Presets + - PerpetualTune algorithms VoltageOptimizer/BoardTune/ChipTune/PowerTune with min/max + Psu Info), - /perpetualtune status, /network, /ethernet, /temps, /timezone, /scheduler, /otelsettings, - /hashratesplit config+status. -- WhatsMiner: fleet scanned read-only across 10.7.1.0/24 and 10.8.1.0/24 via `miner_probe scan` - (M30S-class, H6OS/H616 control boards, mix of watts and supports_power_limit flags). btminer :4028 - anonymous reads (summary/get_token/get_error_code) confirmed as the read surface. - -Taken from docs / --help / source / reverse-engineering only (not executed live this run): -- Every config-WRITE path on every make (hard rule: no live mutation). Write endpoints and grammars - are described from braiins-toolbox --help, luxminer RPC docs, the ePIC OpenAPI POST definitions, - and the WhatsMiner btminer RE wiki (8889 command table + 4028 token flow). -- BOS firmware-update-check (hits the vendor release server), custom-contract, and the advanced-set - transport (needs a web capture to pin the exact GraphQL/REST call). -- WhatsMiner :8889 privileged writes (update_pools/set_power_pct/restart confirmed in prior RE - sessions; LED/per-board tuning live in the ~40% uncharted :8889 command space and are unverified). -- Stock Antminer / MicroBT miner set-mode was confirmed in the asic-rs source (mapping present) but - not probed against a live stock unit this run. diff --git a/docs/manual/01-getting-started.md b/docs/manual/01-getting-started.md new file mode 100644 index 00000000..69c51cfb --- /dev/null +++ b/docs/manual/01-getting-started.md @@ -0,0 +1,55 @@ +# Getting started + +Alkane Toolkit finds the ASIC miners on your network and shows them in one +table: model, firmware, hashrate, power, temperatures, fans and the health of +every hashboard. From the same table you can run the controls each miner's +firmware supports, such as pausing, restarting or changing pools. + +## Download + +Get the latest release from the +[downloads page](https://gitea.bluefla.re/blueflare/alkane-toolkit/releases). + +| Platform | File | Notes | +|---|---|---| +| Windows 10 and 11 (x86_64) | `alkane-toolkit-vX.Y.Z-windows-x86_64.zip` | One signed `alkane-toolkit.exe`; nothing to install | +| Linux (x86_64) | `alkane-toolkit-vX.Y.Z-linux-x86_64.tar.gz` | One binary; needs GTK 3 (`sudo apt install libgtk-3-0`) | + +### Windows + +1. Download the zip, right-click it, choose **Properties**, tick **Unblock** if + it is shown, then extract it. +2. Run `alkane-toolkit.exe`. Windows shows *BlueFlare Energy Solutions Inc.* as + the verified publisher. To check the signature yourself, right-click the exe, + choose **Properties** and open **Digital Signatures**. + +### Linux + +```sh +tar xzf alkane-toolkit-vX.Y.Z-linux-x86_64.tar.gz +./alkane-toolkit-vX.Y.Z-linux-x86_64/alkane-toolkit +``` + +## First run + +The toolkit starts a scan as soon as it opens. Set your own ranges first with +**Scan ranges** (see [Scanning](02-scanning.md)); until you do, it scans a +built-in default range. + +To look around without touching any miner, start it in demo mode. It shows a +built-in sample fleet and simulates every action: + +| Platform | Command | +|---|---| +| Windows (Command Prompt) | `set ALKANE_FAKE_SCAN=1 && alkane-toolkit.exe` | +| Linux | `ALKANE_FAKE_SCAN=1 ./alkane-toolkit` | + +## Where settings are kept + +| Platform | Folder | +|---|---| +| Windows | `%APPDATA%\alkane-toolkit` | +| Linux | `~/.config/alkane-toolkit` | + +See [Settings and credentials](06-settings.md) for the files in that folder. +Deleting the folder resets the toolkit to its defaults. diff --git a/docs/manual/02-scanning.md b/docs/manual/02-scanning.md new file mode 100644 index 00000000..2746baa6 --- /dev/null +++ b/docs/manual/02-scanning.md @@ -0,0 +1,51 @@ +# Scanning + +Discovery is read-only: a scan asks each address what it is and records what +it reports. It never changes a miner. + +## Scan ranges + +Click **Scan ranges** to edit the addresses to scan. Put one entry per line; +blank lines and lines starting with `#` are ignored. + +| Form | Example | Scans | +|---|---|---| +| Single address | `192.168.1.50` | that address | +| CIDR block | `192.168.1.0/24` | the whole block | +| Full range | `192.168.1.10-192.168.2.40` | every address between the two, inclusive | +| Short range | `192.168.1.10-90` | `.10` to `.90` within the same /24 | +| Per-octet ranges | `10.1-4.0-1.1-255` | every combination (10.1.0.1 ... 10.4.1.255) | + +Commas or spaces between several entries on one line are not accepted; use one +line each. Duplicates are removed automatically. One line, and all lines +together, may cover at most 1,000,000 addresses. + +**Apply** saves the ranges and starts a scan. A mistake keeps the dialog open +and the status bar explains it, for example `invalid range: bad octet range`. + +The same dialog has three numbers: + +| Field | Meaning | Default | +|---|---|---| +| Rescan (s) | seconds between automatic rescans; `0` turns auto-rescan off | 300 | +| Timeout (s) | how long to wait for one miner (scans, refreshes, actions and log fetches) | 10 | +| Concurrency | how many addresses are probed at once (8 to 256); higher is faster but slow miners may report fewer values | 128 | + +When the ranges change, miners outside the new ranges leave the table at the +next scan. + +## Running, pausing and stopping + +The three buttons next to **Scan ranges** control scanning: + +- **Play** (green) turns auto-rescan on and starts a scan now if none is running. +- **Pause** (amber) turns auto-rescan off and lets the current scan finish. +- **Stop** (red) turns auto-rescan off and cancels the current scan. + +While a scan runs, a progress bar spans the top of the table and the status bar +shows progress such as `1935/4590 - scanning 192.168.1.86 (92 found)`. Afterwards +it shows the count and the time to the next scan, for example +`245 miners - next scan in 4m 12s`. + +Actions that change miners wait for the scan to finish; see +[Actions](05-actions.md). diff --git a/docs/manual/03-the-table.md b/docs/manual/03-the-table.md new file mode 100644 index 00000000..feed9057 --- /dev/null +++ b/docs/manual/03-the-table.md @@ -0,0 +1,80 @@ +# The table and header + +## Summary cards + +The cards at the top count the miners **currently shown** (after any filter). +Each miner is in exactly one status: slow, paused, hashing or not hashing. + +| Card | Counts | Click | +|---|---|---| +| Total | rows in the view | - | +| Hashing (green rabbit) | mining at 80% of expected hashrate or more | show only these; click again to clear | +| Slow (amber turtle) | mining below 80% of expected hashrate | show only these | +| Not hashing (red glass) | answering but not mining | show only these | +| Paused (blue otter) | stopped on purpose (paused, stopped, suspended) | show only these | +| SHA-256 Hashrate | total hashrate, per algorithm | switch algorithm when the fleet runs more than one | +| Est. power | total reported power draw | - | + +On a narrow window the hashrate and power cards are hidden. + +## Columns + +IP is always the first column. The default view shows Model, Health, +Hashrate, Power, Chip temp, Firmware, CPU, Access and Light. More than seventy +other columns are available, grouped as Identity, Firmware and board, Health +and status, Performance, Temperature, Cooling, Hardware and Pools. + +- **Columns** opens a checklist: tick to show, drag to reorder, or sort the list + alphabetically or by category. *Hide columns with no scanned values* hides + columns that are empty for every miner (it resets when the app restarts). +- Drag a column header to move it. +- Right-click a header to sort by it, auto-size one or all columns, hide it, or + open the column chooser. + +Some values worth knowing: + +| Column | Shows | +|---|---| +| Hashrate | actual/expected, for example `95.0T/96.0T`; the actual part is red at 50% of expected or less, amber around 75%, green at 100% | +| Chip temp | hottest chip on each hashboard, for example `77 / 64 / 74`; blue when cool, red at 90 C and above | +| Firmware | the firmware family, coloured (Braiins purple, LuxOS gold, VNish green, ePIC light blue, Hiveon orange, Bixbit pink); stock firmware uses the normal text colour | +| Pool account / Worker | the pool user split at the first dot | +| Board HR / V / freq | per-hashboard hashrate, voltage and frequency | + +A blank cell means the miner did not report that value. + +## Sorting + +Click a header to sort ascending, again for descending, again to clear. + +- **Hashrate** also sorts by *relative* hashrate (actual as a share of + expected), shown as `%^` and `%v` in the header. +- **Health** sorts by overall health, then by power (`Pwr`), fans (`Fan`) and + hashboards (`Brd`). Ascending puts the most broken miners first. + +## Selecting miners + +Click a row to select it; Ctrl-click and Shift-click add to the selection, and +you can drag across rows to select a block. The selection follows miners by IP, +so it survives rescans. Double-click a row (or press Enter) to open the miner's +web page in your browser. Right-click the selection for [actions](05-actions.md). + +## Filters and presets + +**Filter** keeps only the rows that match. Pick a column, then: + +- for numbers: between, =, !=, >, >=, < or <= (blank cells never match); +- for text: *is any of* (tick values; `(blank)` matches empty cells), contains, + does not contain, begins with, ends with or equals (case does not matter). + +Filters on different columns must all match. **Reset** clears them. Clicking a +status card is a quick filter of its own. + +**Presets** saves and loads whole views: column order and visibility, sort and +filters. *Default* is built in and cannot be deleted; saving under an existing +name replaces it. + +## Zoom and theme + +The slider in the bottom-right corner zooms the table: text, icons and column +widths scale together. The window follows the system light or dark theme. diff --git a/docs/manual/04-health.md b/docs/manual/04-health.md new file mode 100644 index 00000000..ad4e9fbf --- /dev/null +++ b/docs/manual/04-health.md @@ -0,0 +1,54 @@ +# Health, access and light + +## The Health column + +Each miner gets a row of icons, always in the same order, so problems line up +across the table: + +1. **Bolt**: the power supply +2. **Brain**: the control board +3. **Fan**: one icon per fan +4. **Chip**: one icon per hashboard + +Hover over any icon to see its details: PSU voltage and current, the fan speed, +or a hashboard's actual and expected hashrate, frequency and voltage, and any +fault message with its code. + +| Colour | Meaning | +|---|---| +| Green | healthy | +| Amber | working but below par (a slow board, a fan well below the others, a PSU fault while still mining) | +| Red | detected but down (a faulted board, a stopped fan, a PSU that is not delivering) | +| Grey | expected but not detected or not reachable | +| Blue | the miner is paused, so its boards and stopped fans are idle on purpose | + +How each part is judged: + +- **Power** is green when the miner draws power, its PSU fan turns or it is + mining; a reported PSU fault makes it amber (still mining) or red. +- **Control board** is red for a control-board fault and amber for a + miner-wide warning such as a high ambient temperature. +- **Fans** are red at 0 rpm and amber below half the speed of the fastest fan. +- **Hashboards** follow the status the miner reports for each board. When the + firmware names the failing boards, only those turn red. A board the miner + cannot see is grey. + +While an action runs on a miner, its Health cell shows progress such as +`restarting...` or `refreshing...`. + +## Access + +The padlock shows whether the toolkit can change the miner: + +- **green, open**: changes are possible with the saved credentials; +- **red, closed**: view only; +- **blank**: not known yet. + +After a scan the padlock is an estimate from what the firmware offers. Use +**Check access (auth)** in the right-click menu for a real, read-only login +test. + +## Light + +A flashing green-over-red dot means the miner's locate light is on. Turn it on +or off with **Flash lights** / **Stop flashing lights**. diff --git a/docs/manual/05-actions.md b/docs/manual/05-actions.md new file mode 100644 index 00000000..474f975b --- /dev/null +++ b/docs/manual/05-actions.md @@ -0,0 +1,60 @@ +# Actions + +Right-click one or more selected miners for the actions menu. With several +miners selected, labels show the count, for example *Restart (12)*. An action +appears only when **every** selected miner's firmware supports it, so the menu +changes with the selection. + +| Action | What it does | Changes the miner | +|---|---|---| +| Open in browser | opens each miner's web page | no | +| Refresh | re-reads just these miners | no | +| Check access (auth) | tests whether the saved login is accepted | no | +| View log (API)... | shows the first selected miner's log (WhatsMiner: its active fault codes) | no | +| Restore to stock firmware... | removes aftermarket firmware; see [Restore to stock](07-restore.md) | yes, reboots | +| Flash lights / Stop flashing lights | locate light on or off | yes, harmless | +| Pause mining / Resume mining | stop or start hashing | yes | +| Set tuning %... | tuning level, 0 to 100 | yes | +| Set power target... | power target in watts; the prompt shows the current value and the allowed range | yes | +| Set hashrate target... | hashrate target in TH/s, for firmware that tunes by hashrate | yes | +| Set profile... | pick a firmware profile or preset (only profiles every selected miner has are listed) | yes | +| Restart | reboot | yes | +| Configure pools... | set up to three pools | yes | +| Set timezone... | IANA time zone, for example `America/Edmonton` | yes | +| Change password... | new web/API password | yes | +| Factory reset... | wipes pools, tuning and network settings and reboots; the miner may come back on a new DHCP address | yes, destructive | + +## Safety + +- Pause, Resume, Restart and Factory reset ask for confirmation. Value prompts + (tuning, targets, timezone, password) apply when you confirm the value. +- Actions that change miners do not start while a scan is running, including an + automatic rescan. Wait for it to finish or press **Pause**. Scans in turn wait + for running actions. +- Each changed miner is re-read automatically when the action finishes. Results + and failures appear in the bottom-right corner of the status bar and in + **Settings > Logs**. +- If **Change password** succeeds on every selected miner, the saved global + login is updated to the new password. If only some succeed, the saved login + is left alone and the log says so. + +## Configuring pools + +The pool dialog has three rows: Address, Account, Worker and Password. A row is +used only when it has an address and an account. A blank password becomes `x`. +The miner's username becomes `account.worker`. + +Each field has a **+** menu with common pool addresses and the values you saved +before (**Add new...** edits that list). Worker names can use placeholders that +are filled in per miner: + +| Placeholder | Becomes | +|---|---| +| `{ip1}` to `{ip4}` | one octet of the miner's IP | +| `{serial}`, `{mac}` | serial number; MAC without colons | +| `{hostname}` | the miner's hostname | +| `{brand}`, `{model}`, `{submodel}` | make and model | +| `{firmware}`, `{cpu}`, `{cb}` | firmware family, control-board CPU and board | +| `{nameplate-hr}` | the model's rated hashrate | + +For example, `rack3-{ip3}-{ip4}` gives `rack3-1-50` for `10.0.1.50`. diff --git a/docs/manual/06-settings.md b/docs/manual/06-settings.md new file mode 100644 index 00000000..fcd492c3 --- /dev/null +++ b/docs/manual/06-settings.md @@ -0,0 +1,69 @@ +# Settings and credentials + +**Settings** opens a menu with Credentials, Language and Logs. + +## Credentials + +Miners need a login for anything beyond basic discovery: for some details, and +for every action. The Credentials dialog has two parts: + +- **All firmwares** at the top: one username and password tried on every miner. + The saved password is never shown; leave the field blank to keep it. Blank + username and password clear it. +- **One row per firmware**, pre-filled with that firmware's factory default. + Change a row to override the login for that firmware only. + +The toolkit tries, in order, the firmware's own row, then the global login, +then the firmware's built-in default. + +| Firmware | Factory default (user / password) | +|---|---| +| AntMiner Stock | root / root | +| WhatsMiner Stock | admin / admin | +| Braiins | root / root | +| VNish | (none) / admin | +| LuxOS | root / root | +| UMC OS | (none) / letmein | +| Marathon | root / root | +| VolcMiner Stock | root / ltc@dog | +| Elphapex Stock | root / root | +| FutureBit Stock | futurebit / futurebit123 | +| SealMiner Stock | seal / seal | +| Auradine Stock | admin / admin | + +**Reset to defaults** clears every override and the global login at once. + +Logins are stored as plain text in the settings folder, readable only by your +user account (Linux file mode 0600; on Windows, your profile folder's +permissions). + +### SSH login + +Restoring Braiins to stock runs a command over SSH, using the system `ssh` +client (built into Windows 10/11). There is no dialog for this login yet: +create `ssh-credentials.txt` in the settings folder with the username on the +first line and the password on the second. + +## Language + +English, Chinese, Russian, French, Spanish and Portuguese. The toolbar, cards +and column headers switch immediately; menus and dialogs not yet translated +stay in English. + +## Logs + +An activity log of scans, actions, errors and exports, newest last, kept for +the current session (the last 2000 lines). Times are shown in UTC. + +## Files in the settings folder + +| File | Holds | +|---|---| +| `scan-ranges.txt` | scan ranges, one per line | +| `auto-rescan-secs.txt`, `scan-timeout-secs.txt`, `scan-concurrency.txt` | the three scan numbers | +| `scan-credentials.txt` | global login | +| `firmware-credentials.txt` | per-firmware logins | +| `ssh-credentials.txt` | SSH login (created by hand) | +| `presets.json` | saved views | +| `language.txt` | UI language | +| `pool-addresses.txt`, `pool-accounts.txt`, `pool-workers.txt`, `pool-passwords.txt` | saved pool values | diff --git a/docs/manual/07-restore.md b/docs/manual/07-restore.md new file mode 100644 index 00000000..30e72aa1 --- /dev/null +++ b/docs/manual/07-restore.md @@ -0,0 +1,18 @@ +# Restore to stock firmware + +**Restore to stock firmware...** removes aftermarket firmware and returns the +miner to the manufacturer's firmware it keeps on board. Nothing is uploaded. +The miner reboots, and some firmwares come back on a new address. + +It is offered when the selection includes a supported firmware, and asks for +confirmation with the list of miners first. + +| Firmware | How it is removed | Login used | +|---|---|---| +| VNish (and builds based on it) | web API: unlock, then remove firmware; reboots in seconds | the VNish row in Credentials, else `admin` | +| LuxOS | miner API: log on, then uninstall | none | +| Braiins OS | SSH: runs the firmware's own `uninstall.sh` | `ssh-credentials.txt` (see [Settings](06-settings.md)) | + +Miners are restored one at a time. A dropped connection after the command is +sent counts as success, because that is the reboot. A refused login counts as +a failure and leaves the miner unchanged. diff --git a/docs/manual/08-export.md b/docs/manual/08-export.md new file mode 100644 index 00000000..b4a6ff5c --- /dev/null +++ b/docs/manual/08-export.md @@ -0,0 +1,14 @@ +# Export + +**Export** saves the scan as a CSV file for spreadsheets or other tools. + +1. Choose the fields to include (all are ticked by default; **All** and + **None** help). +2. Pick where to save. The suggested name is `alkane-export-YYYYMMDD-HHMMSS.csv`. + +The export contains **every scanned miner**, not just the rows the current +filter shows. Per-board temperatures, fan speeds, board status and pools +become numbered columns (`board_temp_1_c`, `fan_2_rpm`, `pool_1_url`, ...). + +Values that start with `=`, `+`, `-` or `@` are prefixed with `'` so a +spreadsheet treats them as text, not formulas. diff --git a/docs/manual/09-command-line.md b/docs/manual/09-command-line.md new file mode 100644 index 00000000..f4c193fd --- /dev/null +++ b/docs/manual/09-command-line.md @@ -0,0 +1,32 @@ +# Command line and environment + +## Environment variables + +| Variable | Effect | +|---|---| +| `ALKANE_FAKE_SCAN=1` | demo mode: a built-in sample fleet, no network traffic, simulated actions | +| `ALKANE_APPEARANCE=light` or `dark` | force the light or dark theme | +| `ALKANE_SELFTEST=1` | run the built-in UI self-test on the sample fleet and exit (prints `SELFTEST PASS` or `FAIL`) | +| `ALKANE_ACCESS_PROBE=" "` | print whether the saved login can change that miner, then exit | +| `ALKANE_LOG_SCAN=" "` | fetch that miner's log through its API, print the size, then exit | + +On Windows these one-shot modes print to the Command Prompt they are started +from. + +## miner_probe + +`miner_probe` is a command-line companion for scripting and diagnosis. These +commands only read: + +| Command | Prints | +|---|---| +| `miner_probe scan [...]` | discovered miners and their telemetry, as tab-separated values | +| `miner_probe hashrate ...` | raw hashrate and algorithm | +| `miner_probe msgs ` | fault messages and per-board data | +| `miner_probe tune ` | tuning support and limits | +| `miner_probe presets ` | available firmware profiles | +| `miner_probe timezone ` | the current time zone | + +Its other commands change miners. It uses the global login from the settings +folder, or `ALKANE_PROBE_USER` and `ALKANE_PROBE_PASS`, and +`ALKANE_PROBE_CONCURRENCY` (default 128). diff --git a/docs/manual/10-troubleshooting.md b/docs/manual/10-troubleshooting.md new file mode 100644 index 00000000..52f9f490 --- /dev/null +++ b/docs/manual/10-troubleshooting.md @@ -0,0 +1,28 @@ +# Troubleshooting + +**Windows says "Windows protected your PC".** SmartScreen warns about new +downloads until a certificate has built up reputation. The publisher shown +should be *BlueFlare Energy Solutions Inc.*; click **More info**, then **Run +anyway**. If no publisher is shown, do not run the file and download it again +from the releases page. + +**A miner is missing.** Check that its address is inside the scan ranges and +that it answers on its web page from this computer. On busy or slow networks, +raise **Timeout** or lower **Concurrency** in the Scan ranges dialog. + +**An action is missing from the right-click menu.** Actions appear only when +every selected miner supports them. Select fewer miners, or only miners with +the same firmware. + +**An action does nothing and the status says a scan is in progress.** Changes +wait for scans. Press **Pause**, let the scan finish, then try again. + +**Check access says locked.** The saved login is not accepted. Set the right +password in **Settings > Credentials**, either for all firmwares or for that +firmware's row. + +**Values are blank.** The firmware did not report them, or it needs a login to +report them. Try **Check access** and the Credentials dialog. + +**The window is too small or too large.** It opens at most as large as your +screen's work area. Use the zoom slider in the status bar to scale the table. diff --git a/docs/windows.md b/docs/windows.md index 721757d4..ddc88d67 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -99,8 +99,7 @@ AZURE_SIGNING_TOKEN=$(az account get-access-token --resource https://codesigning ## Native Windows runner `windows-native.yml` runs on the self-hosted runner `win11-test-vm` -(label `alkane-windows`, host mode) inside the Windows 11 test VM -(`~/vms/win11-fresh.qcow2` on the workstation). It downloads the +(label `alkane-windows`, host mode) inside a Windows 11 test VM. It downloads the `alkane-toolkit-windows-tests` artifact of the triggering main run, runs every test executable and the UI self-test natively, and never blocks a release: while the VM is off, the job waits for the runner.