Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions NOTICE.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,15 @@ All seven resolved runtime packages, including transitive packages, appear in
`about credits` / `about licenses`. Self-contained runtime notices are additionally
included by CI under `third-party/dotnet`. No affiliate relationship is implied;
manufacturer links are ordinary URLs.

## Storage and firmware protocols (2026-11-30)

`Firmware.cs`, `UsbStorage.cs` and `Read2Me.cs` adapt the package validation,
SPS1/SPI1 USB messages and READ2ME v1 protocol described by upstream
`src/sidepulse/firmware.py`, `usb_control.py`, `storage.py`, and
`_vendor/read2me.py` at `4ebe1a3849c8098b87e7ef9436d9d2f875df8e46`.
Copyright (c) 2026 Peter Kuhar, MIT; the license is retained in
`third-party/inteliwear-sidepulse/LICENSE`. Windows aligned uncached I/O and
SPN command integration are implemented here. Firmware images are downloaded
from the official upstream repository or supplied by the user; none are embedded.
libusb is an optional externally installed Linux/macOS component, not bundled.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,19 @@ host first and confirm `installed` before restarting it. See
publish a release. A matching version tag or manual Prepare release run on `main`
builds and verifies six archives, then creates an unpublished release draft.
Publishing the reviewed draft is a separate explicit release action.

### Device storage and firmware

```text
spn storage status --json
spn storage off --device SPD-000006
spn firmware version --json
spn firmware upgrade --device E:\ --dry-run
spn firmware upgrade --device E:\
```

Firmware packages are verified against checksums and the device model/version.
Windows read-only Pro updates use `--read-only`; raw Dot USB control currently
supports Linux/macOS with system libusb. A safe Windows USB backend remains open. Storage on/off saves the preference; safely eject and
reconnect to apply it. See [device protocols](docs/wiki/Devices-and-Protocols.md)
for prerequisites, transfer semantics and hardware acceptance limits.
25 changes: 25 additions & 0 deletions docs/reviews/upstream-2026-11-30.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Upstream review — 2026-11-30

Reviewed target: `inteliwear/sidepulse@4ebe1a3849c8098b87e7ef9436d9d2f875df8e46`.
The watch issue #72 reports 103 commits since the previous baseline. This is a
partial port, so `upstream.json` retains its previous baseline until the remaining
items have been assessed and dispositioned.

| Change | SPN disposition |
|---|---|
| SPS1 persisted storage status/on/off; SPI1 Dot USB discovery | #77 adds explicit serial/USB selection and acknowledged preference saves. Linux/macOS use libusb. Safe Windows raw control is blocked pending #82; mounted-volume ejection remains #79. |
| Verified customer OTA ZIPs, batch upgrade, model/version guards | #77 adds online/local packages, bounded downloads, complete checksums, multi-device preflight and no downgrade. |
| Read-only Pro transfer | #77 implements Windows aligned uncached READ2ME v1; native symbol probe fails closed. Other read-only platforms and physical acceptance remain #78. |
| Storage-disabled Dot firmware | #77 temporarily enables a uniquely identified Dot drive, restores its saved preference before image bytes and matches serial/version after reconnect. |
| Direct SPC2 live LEDs and unmounted devices in normal delivery | Deferred: #11 / #3. Firmware/storage USB access does not imply that `state`/`write` can use raw USB. |
| OSC 7501 program status, PTY forwarding and terminal/session presentation | #80; requires schema fixtures and a compatibility design with SPN host lifecycle. |
| New Antigravity/Herdr/T3 Code hooks; Cursor/Grok/Junie improvements; terminal opening | #80 plus existing #41–44. No copied adapter is presented as tested. |
| OpenCode event ordering/hot reload, Codex trust entries/memory jobs/plan waits, Claude compaction/browser waits | #80 / #40 / #30; audit against SPN adapters before changing session state rules. |
| Android pairing and remote transports | Existing #46 / #45; retain current iPhone boundaries. |
| Dark hours, battery, platform helpers and Neon animations | #80, #50, #47; review UX, grammar vectors and attribution before porting. |
| Platform installers, VM tests and daemon refactoring | Reference material for #18, #25 and #40; SPN keeps its own install/host contracts. |

Firmware protocol code is adapted with the retained upstream MIT notice. Images
are neither embedded nor redistributed by this change. Package hashes establish
integrity against the selected upstream source, not an independent signature.
No firmware was sent to physical hardware during development.
73 changes: 73 additions & 0 deletions docs/wiki/Devices-and-Protocols.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,76 @@ A later migration or relay feature must preserve source machine identity.

Protocol fixtures should be derived from the pinned upstream source revision and
redacted captures, with attribution recorded alongside them.

## Firmware updates

```text
spn firmware version --json
spn firmware upgrade --device E:\ --dry-run
spn firmware upgrade --device E:\
spn firmware upgrade --device E:\ --release-version 1.1.17
spn firmware upgrade --device E:\ --file sidepulse-dot-1.1.17-ota.zip
spn firmware upgrade --device E:\ --read-only
spn firmware upgrade --all --dry-run
```

`--release-version` selects firmware; SPN reserves `--version` for its own version.
The default source is the official `inteliwear/sidepulse` firmware directory.
Downloads and expanded packages are limited to 4 MiB. SPN checks the published
ZIP SHA-256, every embedded file checksum, archive layout, package/model/version,
connected device identity and downgrade protection before writing. SHA-256 detects
corruption; these packages do not provide an independent publisher signature.
Local ZIPs are checked against their internal checksums and model/version header.

Dry-run validates without creating device files or changing storage preferences.
Unknown or repeated maintenance options fail before hardware access. Multiple
devices require explicit selection or `--all`; all packages are verified first.
Stop the SPN host and other LED writers before upgrading. SPN serializes its own
file writes and holds the device lock for ten seconds after sending firmware.
A transferred image is **not** confirmed installation: keep connected, then
reconnect and run `firmware version` to verify the installed version. Failed or
ambiguous transfers are never automatically replayed.

Writable mounted Dot and Pro updates use a flushed `FIRMWARE.BIN` file on all
platforms, including Windows. A read-only **Pro** can use `--read-only` on Windows:
SPN reads aligned 512-byte sectors of `setup.html` with `FILE_FLAG_NO_BUFFERING`,
probes exact symbol delivery, and validates chunk/completion acknowledgements and
CRC. It refuses other sector sizes and cached/aggregated reads before uploading.
This Windows hardware path still needs physical-device acceptance; unit and CI
checks do not prove that a particular Windows storage stack supports it. The
read-only channel is currently Windows-only. Dot firmware requires writable storage.

## Dot USB storage

```text
spn storage status --json
spn storage off --device SPD-000006
spn storage on --device SPD-000006
spn storage on --device SPD-000006 --reconnect
```

Requires Dot firmware supporting SPI1/SPS1. Select by production serial or
`usb:BUS:ADDRESS`. Pro does not support this setting. `Saved` is the persisted
preference; `Active` is the current USB configuration. `on/off` saves the setting
and verifies acknowledgement. Safely eject any mounted Dot drive, then unplug and
reconnect to apply it. `--reconnect` can enable storage when it is already inactive;
it refuses to detach active storage. Unlike upstream macOS/Linux, SPN does not yet
automatically eject a mounted drive. No filesystem is forcibly unmounted.

USB control currently supports Linux/macOS with externally installed libusb 1.0.
Linux needs permission for VID `1a86`, PID `fe10`; macOS can use Homebrew libusb.
Windows Dot storage control is rejected **before** loading a native backend:
libusb's UsbDk backend captures the entire device on open and detaches it from
Windows PnP/storage drivers, even for a status query. SPN must not do that to a
mounted drive. Keep the normal mass-storage driver; do not replace it with
WinUSB/Zadig. A safe Windows control backend remains open in #82. Mounted Windows firmware
updates and the Windows read-only Pro channel do not require libusb/UsbDk.
SPN never installs drivers, claims interfaces, detaches kernel drivers, or resets
arbitrary USB devices.

`firmware version` also discovers storage-disabled Dots when USB access is available.
A USB-selected Dot upgrade requires a unique production serial. SPN temporarily
enables storage, verifies the reconnected serial/version, restores the saved
storage-off preference **before** sending image bytes, and matches the mounted drive.
If storage preparation fails, no firmware bytes are sent. Read the error and check
`storage status` before retrying. Hardware acceptance for these paths remains open.
40 changes: 40 additions & 0 deletions scripts/cli_smoke.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Exercise published CLI, local hooks and a simulated device without hardware."""
import json
import hashlib
import zipfile
import os
from pathlib import Path
import subprocess
Expand All @@ -8,6 +10,43 @@
import time


def firmware_checks(exe, environment):
with tempfile.TemporaryDirectory(prefix='SidePulse firmware ü ') as directory:
root = Path(directory)
device = root / 'device'
device.mkdir()
(device / 'STATUS.TXT').write_text('app_version 1.1.16\nserial SPD-000123\n', encoding='utf-8')
payload = bytes(range(256)) * 3
files = {'FIRMWARE.BIN': payload,
'README.txt': b'SidePulse Dot firmware update - version 1.1.17\n',
'RELEASE_NOTES.txt': b'Smoke fixture\n'}
files['SHA256SUMS.txt'] = '\n'.join(hashlib.sha256(data).hexdigest() + ' ' + name for name, data in files.items()).encode()
package = root / 'sidepulse-dot-1.1.17-ota.zip'
with zipfile.ZipFile(package, 'w') as archive:
for name, data in files.items():
archive.writestr(name, data)
env = dict(environment, SIDEPULSE_NET_HOME=str(root / 'config'))
def invoke(*args, success=True):
response = subprocess.run([exe, *args, '--json'], env=env, capture_output=True, text=True, timeout=25)
assert (response.returncode == 0) == success, (args, response.stdout, response.stderr)
return json.loads(response.stdout if success else response.stderr)
version = invoke('firmware', 'version', '--device', str(device))
assert version[0]['Serial'] == 'SPD-000123'
result = invoke('firmware', 'upgrade', '--device', str(device), '--file', str(package), '--dry-run')
assert result[0]['State'] == 'verified' and result[0]['DryRun']
assert not (device / 'FIRMWARE.BIN').exists() and not (root / 'config').exists()
for option in ('--dryrun', '--dry-run=false', '--file='):
invoke('firmware', 'upgrade', '--device', str(device), option, success=False)
assert not (device / 'FIRMWARE.BIN').exists()
invoke('storage', 'status', '--unknown', success=False)
result = invoke('firmware', 'upgrade', '--device', str(device), '--file', str(package))
assert result[0]['State'] == 'transferred-reconnect-to-confirm'
assert (device / 'FIRMWARE.BIN').read_bytes() == payload
(device / 'STATUS.TXT').write_text('app_version 1.1.18\nserial SPD-000123\n', encoding='utf-8')
invoke('firmware', 'upgrade', '--device', str(device), '--file', str(package), success=False)
assert (device / 'FIRMWARE.BIN').read_bytes() == payload


def main():
exe = str(Path(sys.argv[1]).resolve())

Expand All @@ -18,6 +57,7 @@ def run(*args, input=None):
assert result.returncode == 0, (args, result.stdout, result.stderr)
return result

firmware_checks(exe, child_env)
version = run('--version').stdout
assert version and version == run('-v').stdout
assert run('--version', '--quiet').stdout == ''
Expand Down
25 changes: 17 additions & 8 deletions scripts/install_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,20 @@
import time


def remove_tree(path, timeout=10):
# Windows can retain an executable image lock briefly after its process exits.
# Retry only sharing/lock violations, and preserve permanent failures.
deadline = time.monotonic() + timeout
while True:
try:
shutil.rmtree(path)
return
except OSError as error:
if getattr(error, 'winerror', None) not in (32, 33) or time.monotonic() >= deadline:
raise
time.sleep(0.1)


def main(executable):
source = Path(executable).resolve()
if os.name == 'nt' and os.environ.get('SIDEPULSE_INSTALL_SYSTEM_TESTS') != '1':
Expand Down Expand Up @@ -76,7 +90,7 @@ def run(exe, *args, success=True, extra_env=None):
assert Path(registration['Backup']).read_bytes() == original_profile
assert profile.read_text().count('# >>> SidePulse.NET PATH >>>') == 1
profile.write_bytes(profile.read_bytes() + b'# Added after installation\n')
shutil.rmtree(download)
remove_tree(download)
unrelated = root / 'unrelated working directory'
unrelated.mkdir()
fresh_env = dict(env)
Expand Down Expand Up @@ -117,13 +131,8 @@ def run(exe, *args, success=True, extra_env=None):
assert Path(registration['Backup']).exists()
else:
assert user_path() == original_path, 'User PATH or its registry type was not restored exactly'
# Give the detached Windows helper time to close its executable before cleanup.
for attempt in range(100):
try:
shutil.rmtree(job)
break
except PermissionError:
time.sleep(0.1)
# Result publication can precede the detached helper releasing its image.
remove_tree(job)
print('Single-file offline resources, install/PATH preview, conflicts, idempotence, stable hooks and owned uninstall passed.')


Expand Down
9 changes: 9 additions & 0 deletions scripts/json_compatibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@

def normalize(value, executable):
if isinstance(value, dict):
# This reviewed notice is appended with the new protocol implementation.
# Preserve exact comparison of all pre-existing notice text and fields.
if set(value) == {'name', 'text'} and value['name'].endswith('NOTICE.md') and value['text']:
marker = '\n## Storage and firmware protocols (2026-11-30)\n'
notice = (Path(__file__).resolve().parents[1] / 'NOTICE.md').read_text(encoding='utf-8')
if marker in notice:
appendix = marker + notice.split(marker, 1)[1]
if value['text'].endswith(appendix):
value = dict(value, text=value['text'][:-len(appendix)])
# Explicit reviewed dependency upgrades change inventory values, not its schema.
# Keep all other fields and all unlisted version changes under exact comparison.
transitions = {('QRCoder', '1.8.1'): '1.9.0',
Expand Down
30 changes: 30 additions & 0 deletions scripts/tests/test_install_smoke.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from pathlib import Path
import sys
import unittest
from unittest.mock import patch

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from install_smoke import remove_tree


class InstallSmokeTests(unittest.TestCase):
def error(self, code):
error = PermissionError('fixture Windows error')
error.winerror = code
return error

def test_exited_process_image_lock_can_clear_before_cleanup(self):
with patch('install_smoke.shutil.rmtree', side_effect=[self.error(32), None]) as remove, patch('install_smoke.time.sleep'):
remove_tree('fixture')
self.assertEqual(2, remove.call_count)

def test_access_denied_is_not_hidden_as_a_transient_lock(self):
with patch('install_smoke.shutil.rmtree', side_effect=self.error(5)) as remove:
with self.assertRaises(PermissionError):
remove_tree('fixture')
self.assertEqual(1, remove.call_count)

def test_persistent_sharing_violation_still_fails_acceptance(self):
with patch('install_smoke.shutil.rmtree', side_effect=self.error(32)):
with self.assertRaises(PermissionError):
remove_tree('fixture', timeout=0)
11 changes: 10 additions & 1 deletion src/SidePulse.Cli/CliApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ static string[] Normalize(string[] command)
return command;
}
args = Normalize(args);
try { MaintenanceArguments.Validate(args); }
catch (Exception ex) { return TerminalMode.Error(ex); }
using var logOutput = HostLogs.Redirect(args);
var app = new CommandApp();
app.Configure(config =>
Expand Down Expand Up @@ -80,6 +82,13 @@ static string[] Normalize(string[] command)
links.AddCommand<RemovePhoneCommand>("remove").WithDescription("Remove a local phone link.");
});
config.AddCommand<DoctorCommand>("doctor").WithDescription("Check local setup without sending to devices or the network.");
config.AddCommand<StorageCommand>("storage").WithDescription("Show or save Dot USB storage on/off settings.");
config.AddBranch("firmware", firmware =>
{
firmware.SetDescription("Inspect and update device firmware using verified official OTA packages.");
firmware.AddCommand<FirmwareVersionCommand>("version");
firmware.AddCommand<FirmwareUpgradeCommand>("upgrade");
});
config.AddCommand<DevicesCommand>("devices").WithDescription("List mounted SidePulse devices.");
config.AddCommand<StateCommand>("state").WithDescription("Display an agent state on USB or iPhone.");
config.AddCommand<WriteCommand>("write").WithDescription("Send a raw LED program with firmware envelope checks.");
Expand Down Expand Up @@ -110,7 +119,7 @@ static string[] Normalize(string[] command)
return TerminalMode.Error(exception);
});
});
try { return session ? new ShellSession((command, token) => app.Run(Normalize(command), token)).Run(args) : app.Run(args); }
try { return session ? new ShellSession((command, token) => { var normalized = Normalize(command); MaintenanceArguments.Validate(normalized); return app.Run(normalized, token); }).Run(args) : app.Run(args); }
catch (Exception ex) { return TerminalMode.Error(ex); }
}
}
Loading
Loading