diff --git a/.agents/skills/verify-gbat/SKILL.md b/.agents/skills/verify-gbat/SKILL.md new file mode 100644 index 0000000..92fe03e --- /dev/null +++ b/.agents/skills/verify-gbat/SKILL.md @@ -0,0 +1,179 @@ +--- +name: verify-gbat +description: Verify gbat's real macOS/Linux battery CLI and macOS Raycast script with isolated PTY runs, version checks, hardware-aware feature journeys, and retained command evidence. Use after changing CLI output, HID behavior, or Raycast integration. +--- + +# Verify gbat + +Read [the feature map](features/README.md), then the relevant journey. The primary +surface is a one-shot Rust CLI; the secondary surface is the macOS Raycast Script +Command `Logitech Mouse Battery`. No service, port, login, database, migrations, +or seed data is involved. An empty working directory is sufficient for version +checks; successful battery reads require a real awake Logitech mouse. + +## Launch + +Run from this checkout using Rust/rustup (the version is pinned in +`rust-toolchain.toml`) and `uv`. The helper uses Python 3.12, provisioned by `uv` +if necessary; Python is a verification dependency, not an app dependency. +On Linux the native hidraw backend needs a C compiler/linker, not `libudev-dev` +or `libusb`. Build as your regular user. + +Keep these variables in one shell across launch, doctor, drive, and cleanup: + +```sh +REPO="$(git rev-parse --show-toplevel)" +cd "$REPO" +CARGO_TARGET_DIR="$REPO/target" cargo build --release --locked +BINARY="$REPO/target/release/gbat" +HARNESS="$REPO/.agents/skills/verify-gbat/scripts/capture.py" +mkdir -p "$REPO/target/verification-evidence" +EVIDENCE="$(mktemp -d "$REPO/target/verification-evidence/run.XXXXXX")" +SCRATCH="$(mktemp -d "${TMPDIR:-/tmp}/gbat-verify.XXXXXX")" +printf 'Evidence: %s\nScratch: %s\n' "$EVIDENCE" "$SCRATCH" +trap 'rmdir -- "$SCRATCH"' EXIT +``` + +The build must succeed before driving. A successful doctor below establishes +CLI readiness and the manifest version. It does not establish hardware +readiness. There is no persistent app process: start each action with the helper +in its own PTY, which exits and is reaped before the next action. Teardown is +the Cleanup section; run it after failures too. + +Hardware queries cannot be isolated by working directory: interfaces are shared, +requests use one software ID, and input reports are flushed. Never run two +battery queries concurrently against the same receiver, including Raycast +refreshes or another agent's run. If another driver is active, defer the query; +do not kill or commandeer it. Version-only runs can coexist. There is no device +selector: multiple Logitech devices can make the reading belong to another +device. Establish the intended device/connection before claiming GPW2 proof. + +## Doctor + +This is the read-only instance check. It invokes the exact local binary without +opening HID, requires the version in `Cargo.toml`, and records its SHA-256: + +```sh +uv run --no-project --python 3.12 "$HARNESS" \ + --evidence "$EVIDENCE/doctor" --cwd "$SCRATCH" --binary "$BINARY" \ + --feature version-local --expect version -- "$BINARY" --version +``` + +Require helper exit `0`, `result.json` `passed: true`, exact version stdout, +and empty stderr. The helper records a binary hash on every action: compare it +with the doctor hash to detect a build replaced during verification. Version +alone cannot establish freshness, so always build this checkout first. If +anything looks off, repeat this check in a new evidence directory, retaining +the failed attempt. On Linux this command needs no `sudo`. + +## Drive + +The executable [PTY helper](scripts/capture.py) accepts exact commands after +`--`; it never runs them through a shell. Every invocation requires a new +evidence subdirectory and an existing, disposable scratch directory. Stdout and +stdin use a private controlling PTY; stderr is redirected to its own proof file +so channel assertions remain possible. It supplies no interactive input. The +default deadline is 30 seconds, not the internal six-second discovery budget; +use `--timeout 60` only for a justified slow host. + +For a real battery read on macOS: + +```sh +uv run --no-project --python 3.12 "$HARNESS" \ + --evidence "$EVIDENCE/battery-terminal" --cwd "$SCRATCH" --binary "$BINARY" \ + --feature battery-terminal --expect battery -- "$BINARY" +``` + +For the corresponding Linux action, use `-- sudo -n "$BINARY"` instead. +Build first as a regular user. If `sudo -n` needs authentication, use the +environment's secret-delivery mechanism; do not put passwords into commands, +artifacts, or this skill. A sudo error is a failed prerequisite, not a gbat +failure-path pass. Do not change udev rules or device permissions for a run. + +Follow the map for charging, offline/recovery, and Raycast actions. A missing +mouse or required charging state is a failed journey with its unmet precondition, +not a successful substitute. Only the first CLI argument exactly equal to +`--version` avoids HID. There is no `--help`, dry-run, or device-list mode; +unknown arguments execute a battery query. The Raycast script does not forward +arguments, so `mouse-battery.sh --version` also queries hardware. + +## Evidence + +Keep proof in `$REPO/target/verification-evidence/run.XXXXXX`, outside scratch. +`target/` is already ignored by Git. Copy evidence elsewhere before `cargo clean` +or deleting the checkout. Each action contains: + +- `action.json`: feature/entry-point ID, exact argv, working directory, UTC time, + platform, binary path/hash, manifest version, expected behavior, scratch before. +- `terminal.bin` and `events.jsonl`: raw stdout PTY bytes and timed output chunks. +- `stdout.txt` and `stderr.txt`: stdout with terminal CRLF normalized to LF and + separately captured stderr. +- `result.json`: actual app exit code, timeout/interruption/capture error, + assertion result, scratch after, + and whether scratch files stayed unchanged. Helper exit `0` means all its + checks passed; app exit code is recorded separately. + +Record connection mode, intended device identity, wake/charging conditions, +manual actions, and feature outcomes in `$EVIDENCE/notes.md`. Capture the action +and resulting state through the real user entry point. For hardware queries, +compare charging suffix with independently observed cable/charging conditions; +do not require an exact historical battery percentage. A command that merely +prints a plausible battery line cannot prove device identity or charging state. + +Observe relevant side effects alongside output: the helper compares scratch +file contents; it does not audit the whole filesystem or network. gbat has no +documented state files, network calls, or browser launches, but battery queries +send real HID++ writes before reading replies. Do not call them pure device +reads. `--version` returns before HID initialization. No mock battery provider, +replacement executable, or internal test setter proves real hardware behavior. +Existing protocol tests are useful supplementary checks, not CLI/hardware proof. + +For Raycast UI proof, retain the actual invocation and visible compact result +using available native-app capture tooling; terminal execution of its script is +a separate path. Do not reuse the historical README GIF/WebP as fresh evidence. +Do not run `docs/record-demo.sh` for routine verification: it replaces +`assets/demo.gif`. + +## Cleanup + +The helper waits for its child and closes its PTY. On timeout, SIGINT, or SIGTERM +it kills only the process group it created and reaps the child. Never kill by +process name. No server remains to stop. Close only UI windows opened by the +run and restore any device state changed specifically for a journey. + +After every attempt, including a failed one, remove only that run's scratch: + +```sh +rmdir -- "$SCRATCH" +trap - EXIT +test ! -e "$SCRATCH" +test -s "$EVIDENCE/doctor/action.json" +test -s "$EVIDENCE/doctor/result.json" +test -s "$EVIDENCE/doctor/stdout.txt" +printf 'Retained proof: %s\n' "$EVIDENCE" +``` + +Also confirm the driven feature's `action.json`, `result.json`, stdout/stderr, +and terminal evidence survive. Never remove `$EVIDENCE` in cleanup. For a failed +build before scratch exists, no instance was launched and there is nothing to +terminate. Scratch should be empty: if `rmdir` fails, inspect it and remove only +the run-created files before retrying; do not recursively delete an uninspected +path. Do not erase failed evidence when retrying. SIGKILL or machine termination +cannot be handled; such runs may retain partial evidence and need inspection. + +## Helpers + +All invocations above run `scripts/capture.py` through `uv`; it is also directly +executable. Inspect its options without touching HID with: + +```sh +uv run --no-project --python 3.12 "$HARNESS" --help +``` + +`--expect version` requires the current manifest version; `battery` requires one +valid `Battery: N%` line with an optional charging suffix; `error` requires app +exit `1`, empty stdout, and a known gbat error prefix; `missing-binary` requires +the Raycast wrapper's exact missing-executable message. Every expectation also +requires no timeout and unchanged scratch file contents. `error` recognizes a +family of failures: read stderr to assert the specific scenario in the map. +The helper cannot certify hardware setup or native Raycast UI behavior. diff --git a/.agents/skills/verify-gbat/features/README.md b/.agents/skills/verify-gbat/features/README.md new file mode 100644 index 0000000..fc74360 --- /dev/null +++ b/.agents/skills/verify-gbat/features/README.md @@ -0,0 +1,42 @@ +# gbat verification map + +This is the maintained map of gbat's user-facing behavior. Read the matching +feature file before driving it. Every listed entry point needs its own outcome; +a terminal script run does not cover the native Raycast entry point. + +## Baseline preconditions + +- Follow Launch and Doctor in [the skill](../SKILL.md) from a fresh scratch dir. +- Use the absolute release binary built from this checkout with `--locked`. +- Keep `$REPO`, `$BINARY`, `$HARNESS`, `$EVIDENCE`, and `$SCRATCH` in the shell. +- Use macOS or Linux. Raycast and its zsh script are macOS-only product paths. +- For battery journeys, connect a real awake GPW2 via LIGHTSPEED or USB, identify + the device, and ensure no competing query is using its shared HID interface. +- No fixture can seed hardware state. Missing connection, charging state, + permission, or Raycast installation fails the dependent journey; record the + reason and retain the attempt rather than substituting canned output. + +## Driving conventions + +- Use `capture.py` with a unique evidence subdirectory per action, serially. +- Commands in features assume the Launch variables. On Linux only, replace + battery `-- "$BINARY"` with `-- sudo -n "$BINARY"` after arranging access. +- Match one stdout battery line and exit status, never README percentages. +- Restore physical states changed during testing; preserve evidence in `target/`. + +## Proof and coverage + +Each action needs argv, stdout, stderr, exit code, binary identity, and its +result. For battery/charging record the real device preconditions and observed +physical actions too. Native UI proof needs the actual UI invocation/result. +The initial generated-skill smoke run may prove only one feature; name every +unexercised journey as unverified. Successful unit tests do not fill those gaps. + +## Features + +- [Version identity](version.md): local CLI and installed CLI version reporting. +- [Battery and charging](battery.md): receiver, direct USB, charging suffix. +- [Failure and recovery](failure-recovery.md): offline, absent device, + permissions, recovery through the same CLI path. +- [Raycast integration](raycast.md): explicit binary, automatic discovery, + missing executable, native Script Command. diff --git a/.agents/skills/verify-gbat/features/battery.md b/.agents/skills/verify-gbat/features/battery.md new file mode 100644 index 0000000..faf9e2c --- /dev/null +++ b/.agents/skills/verify-gbat/features/battery.md @@ -0,0 +1,55 @@ +# Battery and charging + +Users run gbat once to see the connected mouse's current battery percentage and +whether it is actively charging, through a LIGHTSPEED receiver or direct USB. + +## Sub-features + +- `battery-receiver` reads an awake mouse through LIGHTSPEED. +- `battery-usb` reads a mouse connected directly through USB. +- `battery-charging` shows `(charging)` during active charging. +- `battery-idle` omits the suffix when not actively charging. + +## How to get to it (user POV) + +- Connect the LIGHTSPEED receiver, wake the mouse, and run `gbat` in Terminal. +- Connect the mouse by USB and run the same command. +- On Linux, run `sudo /absolute/path/to/gbat` for either connection. + +## Driving it with capture.py + +Preconditions: + +- Doctor passes; a real intended GPW2 is connected and awake, with no competing + HID driver/query. Record connection and other connected Logitech devices. +- Establish active charging and non-charging separately to cover both suffix + states. Physical access is required; absence of either state fails that case. +- On Linux, the command has permission to open hidraw for reading and writing. + +- **Receiver entry.** With the receiver connected and the mouse unplugged from + USB, record that setup in `notes.md`. Run + `uv run --no-project --python 3.12 "$HARNESS" --evidence "$EVIDENCE/battery-receiver" --cwd "$SCRATCH" --binary "$BINARY" --feature battery-receiver --expect battery -- "$BINARY"`. + Expect one `Battery: N%` line, `N` within `0..100`, empty stderr, app exit `0`, + no charging suffix, and unchanged scratch. +- **Direct USB entry.** With the mouse connected by USB, ensure the receiver + cannot provide an ambiguous second path; change connections only when the + current verification scope permits it. Run the same command with evidence + `"$EVIDENCE/battery-usb"` and feature `battery-usb`. Require valid battery + output and record the independently observed charging state. +- **Charging state.** During active charging, repeat in a new directory + `"$EVIDENCE/battery-charging"` with feature `battery-charging`. Require the + exact ` (charging)` suffix in stdout, not merely a successful `battery` + assertion. After charging stops or USB is unplugged, repeat as `battery-idle` + and require the suffix to be absent. Record the actions and both results. +- **Proof.** Retain the command/output/status artifacts for each reached entry, + connection and charging observations in `notes.md`, and unchanged scratch. + Restore connections changed solely for testing, then run Cleanup. + +## Gotchas + +- A receiver-only pass does not prove direct USB, and vice versa. +- The CLI cannot select a device; another Logitech device may answer first. +- An idle/offline mouse is an unmet success precondition, not valid battery proof. +- At `100%` a mouse may stop charging despite being plugged in. That setup + cannot prove `battery-charging`; record the missing active-charging state. +- Values can change between reads; the historical README percentages are not fixtures. diff --git a/.agents/skills/verify-gbat/features/failure-recovery.md b/.agents/skills/verify-gbat/features/failure-recovery.md new file mode 100644 index 0000000..488392c --- /dev/null +++ b/.agents/skills/verify-gbat/features/failure-recovery.md @@ -0,0 +1,56 @@ +# Failure and recovery + +When no battery status can be read, gbat reports an actionable error instead of +inventing a percentage. Users can restore connection or wake the mouse and retry. + +## Sub-features + +- `failure-absent` reports no responsive interface. +- `failure-offline` reports the receiver has no connected mouse. +- `failure-permission` explains a real Linux HID access denial. +- `failure-recovery` reads a real battery after the failed condition is resolved. + +## How to get to it (user POV) + +- Run `gbat` without a responsive Logitech device, or with the mouse switched off. +- On Linux, run without `sudo` when the device actually requires elevated access. +- Restore connection, turn on or move the mouse, then run the query again. + +## Driving it with capture.py + +Preconditions: + +- Doctor passes. Establish the specific physical/error condition independently. +- Do not disconnect the user's active input devices or change their permissions + just to manufacture an error without scope to do so. If the required state + is unavailable, report that journey failed its precondition. + +- **Absent device.** In an established no-responsive-device state, run + `uv run --no-project --python 3.12 "$HARNESS" --evidence "$EVIDENCE/failure-absent" --cwd "$SCRATCH" --binary "$BINARY" --feature failure-absent --expect error -- "$BINARY"`. + Require app exit `1`, empty stdout, and stderr beginning + `No responsive Logitech HID++ interface found.`. `--expect error` also accepts + other gbat errors, so inspect this exact prefix to prove this scenario. +- **Offline receiver.** With the receiver attached and its mouse switched off, + run the same recipe with `failure-offline` as directory/feature. Require stderr + beginning `The receiver reports no connected mouse.` and app exit `1`. +- **Linux permissions.** On a Linux host where unprivileged device access is + denied, run the binary without sudo in directory/feature `failure-permission`. + Require `Permission denied (os error 13)` and the Linux sudo guidance in the + gbat error, empty stdout and app exit `1`. Do not use a sudo authentication + error as evidence of this feature, or revoke working permissions to force it. +- **Recover through the same entry.** Restore the attempted connection/wake state + or use Linux `sudo -n`. Run + `uv run --no-project --python 3.12 "$HARNESS" --evidence "$EVIDENCE/failure-recovery" --cwd "$SCRATCH" --binary "$BINARY" --feature failure-recovery --expect battery -- "$BINARY"` + (Linux: `-- sudo -n "$BINARY"`). Require valid battery stdout, empty stderr + and exit `0`. Record the recovery action between the failed/successful runs. +- **Proof.** Keep both failed and recovered artifacts, physical conditions and + recovery action. An error-only run does not prove recovery. Run Cleanup. + +## Gotchas + +- No hardware can yield an absent-device error, but cannot prove offline, + permissions, battery success, or recovery without the corresponding setup. +- A receiver may answer differently depending on pairing/wake state. Do not + relabel a different error to make the offline expectation pass. +- Initialization/HID errors are possible; retain them and diagnose the actual + failure. Never accept exit `1` alone as the intended failure scenario. diff --git a/.agents/skills/verify-gbat/features/raycast.md b/.agents/skills/verify-gbat/features/raycast.md new file mode 100644 index 0000000..7730ac9 --- /dev/null +++ b/.agents/skills/verify-gbat/features/raycast.md @@ -0,0 +1,62 @@ +# Raycast integration + +On macOS, users run `Logitech Mouse Battery` in Raycast to see the real CLI's +battery line. Its script can also be run directly in Terminal. + +## Sub-features + +- `raycast-explicit` uses the executable selected by `GBAT_BINARY`. +- `raycast-discovery` finds gbat through the documented automatic search order. +- `raycast-missing` reports an explicitly configured non-executable path. +- `raycast-ui` shows the real Script Command's result in Raycast. + +## How to get to it (user POV) + +- Run `GBAT_BINARY=/absolute/path/to/gbat ./raycast/mouse-battery.sh` in Terminal. +- Run the script without the override to use its binary discovery. +- Add the script directory to Raycast Settings, search `Logitech Mouse Battery`, + and execute it. Homebrew installs the CLI only; script registration is separate. + +## Driving it with capture.py + +Preconditions: + +- macOS with zsh; Doctor passes. Hardware-success cases also need an awake mouse. +- The native UI case requires Raycast installed and the script directory already + registered, or authorization to register it. Record this prerequisite. +- Check `test -x "$REPO/raycast/mouse-battery.sh"` for the executable script. + +- **Explicit terminal entry.** Run + `uv run --no-project --python 3.12 "$HARNESS" --evidence "$EVIDENCE/raycast-explicit" --cwd "$SCRATCH" --binary "$BINARY" --feature raycast-explicit --expect battery -- env GBAT_BINARY="$BINARY" "$REPO/raycast/mouse-battery.sh"`. + Require valid battery stdout, empty stderr and app exit `0`. +- **Automatic discovery entry.** Run + `uv run --no-project --python 3.12 "$HARNESS" --evidence "$EVIDENCE/raycast-discovery" --cwd "$SCRATCH" --binary "$BINARY" --feature raycast-discovery --expect battery -- env -u GBAT_BINARY PATH="$REPO/target/release:$PATH" "$REPO/raycast/mouse-battery.sh"`. + This proves the PATH entry with this checkout's build. Search order after PATH + is `/opt/homebrew/bin/gbat`, `/usr/local/bin/gbat`, `$HOME/.local/bin/gbat`, then + the repository's `target/release/gbat`. When modifying fallback discovery, + exercise each affected location on an appropriately configured host; do not + overwrite installed binaries or claim all fallbacks from the PATH case. +- **Missing configured executable.** Confirm `test ! -e "$SCRATCH/no-gbat"`. + Run + `uv run --no-project --python 3.12 "$HARNESS" --evidence "$EVIDENCE/raycast-missing" --cwd "$SCRATCH" --binary "$BINARY" --feature raycast-missing --expect missing-binary -- env GBAT_BINARY="$SCRATCH/no-gbat" "$REPO/raycast/mouse-battery.sh"`. + Require app exit `1`, empty stdout and exact stderr + `gbat binary not found. Build it with: cargo build --release` plus a newline. + A bad explicit override must not fall back to an installed binary. This case + requires no hardware and invokes the real script without a fake executable. +- **Native UI entry.** Using available native-app control, open Raycast, search + the exact command `Logitech Mouse Battery`, and execute it. Capture the action + and visible compact battery result in `$EVIDENCE/raycast-ui/`, with connection + conditions and the configured executable identity in `notes.md`. Terminal + `GBAT_BINARY` does not propagate into an already running Raycast. If the UI + cannot be driven or its configured binary cannot be identified, record the + unmet precondition; a terminal script pass does not prove this entry. +- **Proof.** Retain each terminal action/result and native UI evidence separately. + Close only windows opened for verification, restore any authorized registration + or script configuration changes, and run Cleanup. + +## Gotchas + +- The script ignores its arguments, including `--version`; it queries hardware. +- Invalid `GBAT_BINARY` takes precedence even when a working gbat is on PATH. +- Linux CLI support does not imply Raycast support; Linux cannot prove this map. +- The original Raycast WebP is historical evidence, not proof of the current build. diff --git a/.agents/skills/verify-gbat/features/version.md b/.agents/skills/verify-gbat/features/version.md new file mode 100644 index 0000000..383a56e --- /dev/null +++ b/.agents/skills/verify-gbat/features/version.md @@ -0,0 +1,44 @@ +# Version identity + +Users can identify the local or installed gbat version without connecting a +mouse, granting HID access, or elevating privileges. + +## Sub-features + +- `version-local` reports the release build version from this checkout. +- `version-installed` reports the executable selected by the user's `PATH`. + +## How to get to it (user POV) + +- Build from source and run `./target/release/gbat --version`. +- After installing gbat, run `gbat --version` in Terminal or a Linux shell. + +## Driving it with capture.py + +Preconditions: + +- Launch has built the release binary and created the shell variables. +- For the installed entry point, a real gbat installation is on `PATH` and its + expected release version is known. Do not change the installation for a smoke test. + +- **Doctor/local entry.** Run the Doctor command in the skill. Expect exactly + `gbat ` plus `Cargo.toml`'s version and a newline, empty stderr, app exit `0`, + helper exit `0`, and unchanged empty scratch. Its `doctor/` artifacts prove + `version-local`; no second identical invocation is needed. +- **Installed entry.** Resolve `INSTALLED="$(command -v gbat)"`, require an + absolute executable path, then run + `uv run --no-project --python 3.12 "$HARNESS" --evidence "$EVIDENCE/version-installed" --cwd "$SCRATCH" --binary "$INSTALLED" --feature version-installed --expect version -- "$INSTALLED" --version`. + For an installation of this checkout's version, require the same stdout and + status as local. If the installed release differs, this expectation fails: + record its observed version and coverage mismatch rather than claiming the + checkout was verified through that installed binary. +- **Proof.** Inspect `action.json` for the absolute binary/hash and `result.json` + for `passed: true`. Run Cleanup and confirm both files and `stdout.txt` remain. + +## Gotchas + +- Only `--version` as the first argument avoids hardware. `--help` is not help. +- A matching version is not proof that two binaries contain the same code; use + recorded SHA-256 and build this checkout immediately before verification. +- If no installed executable exists, `version-installed` fails its precondition; + the local entry remains independently verifiable. diff --git a/.agents/skills/verify-gbat/scripts/capture.py b/.agents/skills/verify-gbat/scripts/capture.py new file mode 100755 index 0000000..c50042d --- /dev/null +++ b/.agents/skills/verify-gbat/scripts/capture.py @@ -0,0 +1,244 @@ +#!/usr/bin/env -S uv run --no-project --python 3.12 +"""Capture a short-lived real command in a private PTY and retain its proof.""" + +from __future__ import annotations + +import argparse +import errno +import hashlib +import json +import os +import platform +import pty +import re +import select +import signal +import sys +import time +import tomllib +from datetime import UTC, datetime +from pathlib import Path +from types import FrameType + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def snapshot(directory: Path) -> dict[str, str]: + return { + str(path.relative_to(directory)): ( + f"symlink:{os.readlink(path)}" if path.is_symlink() else digest(path) + ) + for path in sorted(directory.rglob("*")) + if path.is_symlink() or path.is_file() + } + + +def write_json(path: Path, data: object) -> None: + path.write_text(json.dumps(data, indent=2) + "\n") + + +def interrupt_handler(signum: int, frame: FrameType | None) -> None: + raise KeyboardInterrupt + + +def capture( + command: list[str], cwd: Path, evidence: Path, timeout: float +) -> tuple[int, bool, bool]: + started = time.monotonic() + status: int | None = None + timed_out = False + interrupted = False + eof = False + with (evidence / "stderr.txt").open("xb") as errors: + sys.stdout.flush() + sys.stderr.flush() + pid, master = pty.fork() + if pid == 0: + try: + os.chdir(cwd) + os.dup2(errors.fileno(), 2) + os.execvpe(command[0], command, os.environ) + except OSError as error: + os.write(2, f"Could not execute command: {error}\n".encode()) + os._exit(127) + try: + with ( + (evidence / "terminal.bin").open("xb") as terminal, + (evidence / "events.jsonl").open("x") as events, + ): + while not (eof and status is not None): + if time.monotonic() - started >= timeout: + timed_out = True + break + if not eof and select.select([master], [], [], 0.1)[0]: + try: + chunk = os.read(master, 65536) + except OSError as error: + if error.errno != errno.EIO: + raise + chunk = b"" + if chunk: + terminal.write(chunk) + terminal.flush() + events.write( + json.dumps( + { + "elapsed_seconds": time.monotonic() - started, + "stream": "stdout-pty", + "text": chunk.decode(errors="replace"), + } + ) + + "\n" + ) + events.flush() + else: + eof = True + elif eof: + time.sleep(0.01) + if status is None: + waited, child_status = os.waitpid(pid, os.WNOHANG) + if waited: + status = child_status + except KeyboardInterrupt: + interrupted = True + finally: + try: + # Closing the master first can invalidate killpg on macOS. + if status is None or timed_out or interrupted: + try: + os.killpg(pid, signal.SIGKILL) + except ProcessLookupError: + pass + if status is None: + _, status = os.waitpid(pid, 0) + finally: + os.close(master) + return os.waitstatus_to_exitcode(status), timed_out, interrupted + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--evidence", type=Path, required=True) + parser.add_argument("--cwd", type=Path, required=True) + parser.add_argument("--binary", type=Path, required=True) + parser.add_argument("--feature", required=True) + parser.add_argument( + "--expect", + choices=["version", "battery", "error", "missing-binary"], + required=True, + ) + parser.add_argument("--timeout", type=float, default=30) + parser.add_argument("command", nargs=argparse.REMAINDER) + args = parser.parse_args() + command: list[str] = args.command + if command[:1] == ["--"]: + command = command[1:] + if not command or args.timeout <= 0: + parser.error("Provide a command after -- and a positive timeout") + cwd = args.cwd.resolve(strict=True) + binary = args.binary.resolve(strict=True) + evidence = args.evidence.resolve() + if evidence == cwd or cwd in evidence.parents: + parser.error("Evidence must be outside the scratch working directory") + repo = Path(__file__).resolve().parents[4] + version = tomllib.loads((repo / "Cargo.toml").read_text())["package"]["version"] + evidence.mkdir(parents=True, exist_ok=False) + before = snapshot(cwd) + write_json( + evidence / "action.json", + { + "feature": args.feature, + "command": command, + "cwd": str(cwd), + "started_utc": datetime.now(UTC).isoformat(), + "platform": platform.platform(), + "binary": str(binary), + "binary_sha256": digest(binary), + "manifest_version": version, + "expectation": args.expect, + "timeout_seconds": args.timeout, + "stderr_capture": "redirected to stderr.txt; stdout and stdin use a private PTY", + "scratch_before": before, + }, + ) + capture_error: str | None = None + previous_handler = signal.signal(signal.SIGTERM, interrupt_handler) + try: + exit_code, timed_out, interrupted = capture( + command, cwd, evidence, args.timeout + ) + except (OSError, ValueError) as error: + exit_code, timed_out, interrupted = -1, False, False + capture_error = f"{type(error).__name__}: {error}" + finally: + signal.signal(signal.SIGTERM, previous_handler) + for name in ("terminal.bin", "events.jsonl", "stderr.txt"): + (evidence / name).touch(exist_ok=True) + stdout = (evidence / "terminal.bin").read_bytes().replace(b"\r\n", b"\n") + stderr = (evidence / "stderr.txt").read_bytes() + (evidence / "stdout.txt").write_bytes(stdout) + if args.expect == "version": + matched = ( + exit_code == 0 and stdout == f"gbat {version}\n".encode() and not stderr + ) + elif args.expect == "battery": + matched = ( + exit_code == 0 + and re.fullmatch( + rb"Battery: (?:100|[1-9]?[0-9])%(?: \(charging\))?\n", stdout + ) + is not None + and not stderr + ) + elif args.expect == "missing-binary": + matched = ( + exit_code == 1 + and not stdout + and stderr + == (b"gbat binary not found. Build it with: cargo build --release\n") + ) + else: + matched = ( + exit_code == 1 + and not stdout + and stderr.startswith( + ( + b"No responsive Logitech HID++ interface found.", + b"The receiver reports no connected mouse.", + b"Could not read battery level", + b"Could not initialize HID access:", + ) + ) + ) + after = snapshot(cwd) + passed = bool( + matched + and not timed_out + and not interrupted + and not capture_error + and before == after + ) + result = { + "feature": args.feature, + "exit_code": exit_code, + "timed_out": timed_out, + "interrupted": interrupted, + "capture_error": capture_error, + "expectation_matched": bool(matched), + "scratch_unchanged": before == after, + "scratch_after": after, + "passed": passed, + } + write_json(evidence / "result.json", result) + sys.stdout.buffer.write(stdout) + sys.stdout.buffer.flush() + sys.stderr.buffer.write(stderr) + sys.stderr.buffer.flush() + print(json.dumps({"evidence": str(evidence), **result})) + return 0 if passed else 1 + + +if __name__ == "__main__": + raise SystemExit(main())