diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index c365cd1..e9c3609 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -5,4 +5,8 @@ updates:
schedule:
interval: weekly
open-pull-requests-limit: 5
-# Add NuGet updates when the first project and package manifests exist.
+ - package-ecosystem: nuget
+ directory: /
+ schedule:
+ interval: weekly
+ open-pull-requests-limit: 5
diff --git a/.github/workflows/dotnet-ci.yml b/.github/workflows/dotnet-ci.yml
index ff7ee3e..acdd635 100644
--- a/.github/workflows/dotnet-ci.yml
+++ b/.github/workflows/dotnet-ci.yml
@@ -1,8 +1,10 @@
name: .NET CI
on:
push:
+ branches: [main]
pull_request:
workflow_dispatch:
+ workflow_call:
permissions:
contents: read
concurrency:
@@ -42,6 +44,9 @@ jobs:
matrix:
os: [windows-latest, ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
+ timeout-minutes: 20
+ env:
+ SIDEPULSE_NATIVE_VAULT_TESTS: '1'
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
@@ -49,11 +54,31 @@ jobs:
- uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6
with:
dotnet-version: 10.0.x
+ - name: Prepare isolated native credential vault
+ if: runner.os != 'Windows'
+ shell: bash
+ run: |
+ if [ "$RUNNER_OS" = 'Linux' ]; then
+ sudo apt-get update -qq -o Acquire::Retries=1 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30
+ sudo apt-get install -y --no-install-recommends libsecret-tools gnome-keyring dbus-x11
+ bus_address=$(dbus-daemon --session --fork --print-address=1)
+ export DBUS_SESSION_BUS_ADDRESS="$bus_address"
+ echo "DBUS_SESSION_BUS_ADDRESS=$bus_address" >> "$GITHUB_ENV"
+ printf '%s' 'sidepulse-ci-only' | gnome-keyring-daemon --unlock --components=secrets
+ else
+ security default-keychain -d user > "$RUNNER_TEMP/sidepulse-previous-keychain"
+ security list-keychains -d user > "$RUNNER_TEMP/sidepulse-previous-search-list"
+ security create-keychain -p 'sidepulse-ci-only' "$RUNNER_TEMP/sidepulse-ci.keychain-db"
+ security default-keychain -d user -s "$RUNNER_TEMP/sidepulse-ci.keychain-db"
+ security list-keychains -d user -s "$RUNNER_TEMP/sidepulse-ci.keychain-db"
+ security unlock-keychain -p 'sidepulse-ci-only' "$RUNNER_TEMP/sidepulse-ci.keychain-db"
+ security set-keychain-settings -lut 21600 "$RUNNER_TEMP/sidepulse-ci.keychain-db"
+ fi
- name: Restore
env:
SOLUTION: ${{ needs.detect.outputs.solution }}
shell: pwsh
- run: dotnet restore $env:SOLUTION
+ run: dotnet restore $env:SOLUTION --locked-mode
- name: Build
env:
SOLUTION: ${{ needs.detect.outputs.solution }}
@@ -64,3 +89,75 @@ jobs:
SOLUTION: ${{ needs.detect.outputs.solution }}
shell: pwsh
run: dotnet test $env:SOLUTION --configuration Release --no-build
+ - name: Exercise CLI and local host with simulated hardware
+ shell: pwsh
+ run: |
+ $binary = if ($IsWindows) { 'sidepulse-net.exe' } else { 'sidepulse-net' }
+ python scripts/cli_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary"
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ python scripts/terminal_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary"
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ python scripts/animation_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary"
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ python scripts/agent_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary"
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ - name: Publish and exercise self-contained previews
+ shell: pwsh
+ run: |
+ $prefix = if ($IsWindows) { 'win' } elseif ($IsMacOS) { 'osx' } else { 'linux' }
+ $native = "$prefix-$([System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture.ToString().ToLowerInvariant())"
+ foreach ($architecture in @('x64', 'arm64')) {
+ $rid = "$prefix-$architecture"
+ $destination = "artifacts/$rid"
+ dotnet publish src/SidePulse.Cli -c Release -r $rid --self-contained true -o $destination
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ Copy-Item LICENSE,NOTICE.md $destination
+ Copy-Item -Recurse third-party $destination
+ New-Item -ItemType Directory -Force "$destination/third-party/dotnet" | Out-Null
+ Copy-Item "$env:DOTNET_ROOT/LICENSE.txt","$env:DOTNET_ROOT/ThirdPartyNotices.txt" "$destination/third-party/dotnet"
+ Copy-Item docs/wiki/Getting-Started.md $destination
+ $version = ([xml](Get-Content src/SidePulse.Cli/SidePulse.Cli.csproj -Raw)).Project.PropertyGroup.Version
+ python scripts/package_manifest.py $destination $rid $version
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ if ($rid -eq $native) {
+ $binary = if ($IsWindows) { 'sidepulse-net.exe' } else { 'sidepulse-net' }
+ python scripts/cli_smoke.py "$destination/$binary"
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ python scripts/animation_smoke.py "$destination/$binary"
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ python scripts/update_smoke.py "$destination/$binary"
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ python scripts/agent_smoke.py "$destination/$binary"
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ }
+ if ($IsWindows) {
+ Compress-Archive -Path "$destination/*" -DestinationPath "artifacts/sidepulse-net-$rid.zip"
+ } else {
+ tar -czf "artifacts/sidepulse-net-$rid.tar.gz" -C $destination .
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ }
+ }
+ - name: Upload platform previews
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: sidepulse-net-${{ runner.os }}-preview
+ path: |
+ artifacts/*.zip
+ artifacts/*.tar.gz
+ retention-days: 14
+ - name: Remove temporary macOS keychain
+ if: always() && runner.os == 'macOS'
+ shell: bash
+ run: |
+ if [ -f "$RUNNER_TEMP/sidepulse-previous-keychain" ]; then
+ previous=$(cat "$RUNNER_TEMP/sidepulse-previous-keychain" | tr -d '"' | xargs)
+ security default-keychain -d user -s "$previous"
+ fi
+ if [ -f "$RUNNER_TEMP/sidepulse-previous-search-list" ]; then
+ keychains=()
+ while IFS= read -r keychain; do keychains+=("$keychain"); done < <(python3 -c 'import shlex,sys; print("\n".join(shlex.split(sys.stdin.read())))' < "$RUNNER_TEMP/sidepulse-previous-search-list")
+ security list-keychains -d user -s "${keychains[@]}"
+ fi
+ if [ -f "$RUNNER_TEMP/sidepulse-ci.keychain-db" ]; then
+ security delete-keychain "$RUNNER_TEMP/sidepulse-ci.keychain-db"
+ fi
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..df77ac0
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,60 @@
+name: Release
+on:
+ push:
+ tags: ['v*']
+ workflow_dispatch:
+permissions:
+ contents: read
+concurrency:
+ group: release-${{ github.ref }}
+ cancel-in-progress: false
+jobs:
+ validate:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ - name: Require a version tag matching the application
+ env:
+ RELEASE_REF: ${{ github.ref }}
+ run: |
+ python3 - <<'PY'
+ import os, re, xml.etree.ElementTree as ET
+ version = ET.parse('src/SidePulse.Cli/SidePulse.Cli.csproj').findtext('./PropertyGroup/Version')
+ if os.environ['RELEASE_REF'] != 'refs/tags/v' + version or not re.fullmatch(r'\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?', version):
+ raise SystemExit('Select/push a vVERSION tag matching the project version; build metadata is not used for release tags.')
+ PY
+ build:
+ needs: validate
+ uses: ./.github/workflows/dotnet-ci.yml
+ publish:
+ needs: build
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ actions: read
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ - name: Collect tested packages and write checksums
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ RELEASE_RUN: ${{ github.run_id }}
+ run: |
+ gh run download "$RELEASE_RUN" --pattern 'sidepulse-net-*-preview' --dir release-input
+ mkdir release-files
+ find release-input -type f \( -name '*.zip' -o -name '*.tar.gz' \) -exec cp -n {} release-files/ \;
+ python3 scripts/release_checksums.py release-files
+ - name: Upload all assets before making the release visible
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ RELEASE_TAG: ${{ github.ref_name }}
+ run: |
+ flags=()
+ if [[ "$RELEASE_TAG" == *-* ]]; then flags+=(--prerelease); fi
+ gh release create "$RELEASE_TAG" --verify-tag --draft --title "SidePulse.NET ${RELEASE_TAG#v}" --generate-notes "${flags[@]}" release-files/*
+ gh release edit "$RELEASE_TAG" --draft=false "${flags[@]}"
diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml
new file mode 100644
index 0000000..8fd3e37
--- /dev/null
+++ b/.github/workflows/security.yml
@@ -0,0 +1,77 @@
+name: Security
+on:
+ push:
+ branches: [main]
+ pull_request:
+ schedule:
+ - cron: '43 6 * * 2'
+ workflow_dispatch:
+permissions:
+ contents: read
+concurrency:
+ group: security-${{ github.ref }}
+ cancel-in-progress: true
+jobs:
+ codeql:
+ name: CodeQL (${{ matrix.language }})
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ permissions:
+ contents: read
+ security-events: write
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - language: csharp
+ build-mode: manual
+ - language: python
+ build-mode: none
+ - language: actions
+ build-mode: none
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6
+ if: matrix.language == 'csharp'
+ with:
+ dotnet-version: 10.0.x
+ - uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4
+ with:
+ languages: ${{ matrix.language }}
+ build-mode: ${{ matrix.build-mode }}
+ - name: Build C# for analysis
+ if: matrix.language == 'csharp'
+ run: |
+ dotnet restore --locked-mode
+ dotnet build --configuration Release --no-restore --no-incremental
+ - uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4
+ with:
+ category: '/language:${{ matrix.language }}'
+ output: codeql-results
+ - name: Summarize scan findings
+ if: always()
+ run: |
+ python3 - <<'PYCODE'
+ import json
+ from pathlib import Path
+ for report in sorted(Path('codeql-results').glob('*.sarif')):
+ for run in json.loads(report.read_text()).get('runs', []):
+ for result in run.get('results', []):
+ locations = [item.get('physicalLocation', {}) for item in result.get('locations', [])]
+ print(json.dumps({'rule': result.get('ruleId'), 'message': result.get('message'), 'locations': locations}))
+ PYCODE
+ dependencies:
+ name: Dependency review
+ if: github.event_name == 'pull_request'
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ - uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
+ with:
+ fail-on-severity: high
+ comment-summary-in-pr: never
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0f384c6..e78bfb9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,8 +1,8 @@
# Contributing
-SidePulse.NET is currently in concept review. Discuss significant design choices
-before implementation. Keep the application free of C# scaffolding until the
-concept and first milestone are approved.
+SidePulse.NET has an initial implementation preview. Discuss significant design
+changes before expanding the architecture. Keep implemented and verified behavior
+clearly distinguished from the complete planned product.
## Changes and reviews
@@ -12,11 +12,11 @@ Update wiki sources in `docs/wiki` in the same pull request as behavior changes.
The main repository is the documentation source of truth; direct wiki edits need
to be brought back into it before the next automated publication.
-## When implementation starts
+## Implementation
Use .NET 10 LTS and Spectre.Console for presentation. Keep state reduction,
-protocol logic and device transports independent of the terminal UI. Introduce
-central package management and lock files with the first solution. Add meaningful
+protocol logic and device transports independent of the terminal UI. Keep
+package versions in `Directory.Packages.props` and commit updated lock files. Add meaningful
unit, transport-contract, hook-failure and hardware smoke tests as those areas arrive.
Rendered, interactive output is for people. Hook and JSON output must have no
diff --git a/Directory.Build.props b/Directory.Build.props
new file mode 100644
index 0000000..ce1e686
--- /dev/null
+++ b/Directory.Build.props
@@ -0,0 +1,10 @@
+
+
+ net10.0
+ enable
+ enable
+ true
+ true
+ true
+
+
diff --git a/Directory.Packages.props b/Directory.Packages.props
new file mode 100644
index 0000000..e5670d1
--- /dev/null
+++ b/Directory.Packages.props
@@ -0,0 +1,12 @@
+
+ true
+
+
+
+
+
+
+
+
+
+
diff --git a/NOTICE.md b/NOTICE.md
index 9c639fc..f52d1dd 100644
--- a/NOTICE.md
+++ b/NOTICE.md
@@ -19,3 +19,59 @@ Peter Kuhar or InteliWEAR. No original branding artwork is included.
Spectre.Console and Spectre.Console.Cli are planned dependencies. Their licenses
must be recorded with other distributed third-party components when dependencies
are introduced. No Spectre package is included in this planning commit.
+
+## First implementation preview
+
+`src/SidePulse.Core/LedProgram.cs` adapts status animation profiles from the Python
+Windows companion and the upstream LEDS.LED protocol. `DeviceTransport.cs` follows
+the upstream virtual-file write contract and `PhoneBridge.cs` follows the APNS
+bridge payload/channel contract. Reference: upstream revision above, files
+`LEDS_FORMAT.md`, `src/sidepulse/device_writer.py` and `src/sidepulse/links.py`.
+The retained upstream MIT notice applies to these adapted portions.
+
+Spectre.Console, Spectre.Console.Cli and Spectre.Console.Ansi 0.57.2 are MIT
+licensed dependencies, copyright Patrik Svensson, Phil Scott, Nils Andresen, Cédric Luthi and contributors.
+Their repository license is retained in `third-party/spectre.console/LICENSE.md` and included in CI distribution artifacts.
+Test packages are development dependencies and are not part of the application.
+
+## Phone linking and credential storage
+
+`Pairing.cs` and `PhoneLink.cs` adapt the QR URI, SSE registration and APNS token
+normalization contracts from upstream `src/sidepulse/links.py` at the reference
+revision above. `LinkStore.cs` and CLI link management are new .NET implementations.
+The upstream MIT notice is retained with these adapted protocol portions.
+
+QRCoder 1.8.1 is MIT licensed, copyright Raffael Herrmann and Shane Krueger.
+Its original license is retained in `third-party/qrcoder/LICENSE.txt`.
+System.Security.Cryptography.ProtectedData 10.0.13 and the Microsoft libraries
+resolved with QRCoder are MIT licensed .NET components. Windows preview artifacts
+include the .NET license and third-party notices in `third-party/dotnet`.
+
+## Platform adapters
+
+`PlatformSecrets.cs` and `MacKeychainVault.cs` are new implementations using native
+OS credential APIs/helpers and .NET AES-GCM. No third-party source was copied for
+these adapters. The credential APIs do not require a cloud account or token.
+
+## Agent adapters and host lifecycle
+
+`AgentEvents.cs`, `HookConfiguration.cs`, `HookInstallation.cs` and the associated
+CLI host/agent commands are new .NET implementations based on the public provider
+protocols linked in `docs/wiki/Agent-Integrations.md`. No provider application
+source or transcript data is copied. The adapter tests use synthetic payloads.
+
+## Animation studio and credits
+
+`src/SidePulse.Core/Animations/*.LED` contains unchanged upstream animation assets
+from `src/sidepulse/resources/animations/` at the reference revision above.
+Copyright (c) 2026 Peter Kuhar, MIT. The retained upstream license accompanies
+these assets. `Animation.cs` is a new managed interpreter based on that revision's
+`LEDS_FORMAT.md`; it is an approximation and does not embed the firmware/WASM.
+
+The offline dependency registry in `src/SidePulse.Cli/Dependencies.json` is derived
+from committed NuGet locks and package metadata. License texts and notices for
+Microsoft package dependencies are retained under `third-party/dotnet-packages`.
+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.
diff --git a/README.md b/README.md
index b017837..b825170 100644
--- a/README.md
+++ b/README.md
@@ -2,24 +2,32 @@
An unofficial .NET companion for SidePulse, with a Spectre.Console terminal interface.
-**Status: concept and project preparation. No C# application, downloads or feature-complete port exist yet.**
+**Status: first C# implementation preview. Feature parity and hardware validation are still in progress.**
-SidePulse.NET will bring the SidePulse workflow to a native Windows application:
+Start with [Getting started](docs/wiki/Getting-Started.md) for build, USB, phone delivery and Copilot CLI instructions.
+
+SidePulse.NET brings the SidePulse workflow to Windows, macOS and Linux:
pair a phone or connect a USB device, enable an agent integration, and see when
an agent is working, waiting for input or finished.
-## Planned experience
+## Preview functionality
+
+- Cursor menus, script-command review/copy/export, plain/quiet/JSON output.
+- Copilot CLI, Codex, Claude Code and Kiro CLI V3 hooks with shared status aggregation.
+- Writable USB/SD LED output, iPhone linking and native protected credentials.
+- Dot/Pro animation simulation, custom editor, upstream patterns and state profiles.
+- Host lifecycle, bounded logs, diagnostics and phone aliases.
+- Six self-contained platform/architecture packages and verified-update commands.
-- A live terminal dashboard for devices, agent sessions and recent events.
-- Fast, silent commands for hooks and scripts, alongside interactive setup.
-- Native Copilot CLI hooks, followed by the other upstream integrations.
-- USB LED programs, iPhone linking and bridge delivery, animation previews and profiles.
-- Reliable session aggregation, device aliases, diagnostics and explicit configuration migration.
-- A self-contained Windows distribution without a Python dependency.
+The baseline is **C# / .NET 10 LTS**, **Spectre.Console** and
+**Spectre.Console.Cli**. Windows, macOS and Linux are supported by the preview;
+see the [platform matrix](docs/wiki/Platforms.md) for native credential requirements
+and architecture-specific validation. No release has been published yet.
-The proposed baseline is **C# / .NET 10 LTS**, **Spectre.Console** and
-**Spectre.Console.Cli**. Windows is the first delivery target. Platform-specific
-features and later Linux/macOS support are tracked individually.
+Hardware/firmware, real provider sessions and the public release/update flow still
+need acceptance evidence. A live dashboard, device aliases, explicit Python
+migration, remote relay and read-only transports remain planned. See the
+[architecture and QA review](docs/reviews/pr-12.md) and [open issues](https://github.com/Anheledir/SidePulse.NET/issues).
## Documentation
@@ -33,10 +41,11 @@ The editable source of truth lives in [docs/wiki](docs/wiki/Home.md).
- [Copilot integration](docs/wiki/Copilot-CLI.md)
- [Roadmap and acceptance criteria](docs/wiki/Roadmap.md)
- [Repository and automation setup](docs/wiki/Project-Setup.md)
+- [Security policy](SECURITY.md) and [observed/desired repository settings](docs/repository-settings.md)
## Original project and attribution
-This project is inspired by and plans to port functionality from
+This project ports selected functionality from
[**inteliwear/sidepulse**](https://github.com/inteliwear/sidepulse), created by
**Peter Kuhar / InteliWEAR**, and the [SidePulse hardware](https://sidepulse.io/).
It is independently maintained and is not an official InteliWEAR product.
@@ -45,23 +54,99 @@ The reference baseline is upstream commit
[`ffb1d3c2f3eed3b7e80e32d7876a7e1d67bd5dfb`](https://github.com/inteliwear/sidepulse/commit/ffb1d3c2f3eed3b7e80e32d7876a7e1d67bd5dfb),
checked on 2026-10-23. Upstream is MIT licensed. See [NOTICE.md](NOTICE.md) and
the retained [upstream license](third-party/inteliwear-sidepulse/LICENSE).
-No upstream application code or animation assets have been copied into this initial setup.
+Status LED profiles and protocol behavior are adapted from this baseline; see the provenance notice.
## Development
-Application implementation has not started. Review the concept and compatibility
-inventory before creating the solution. Future commands shown in the wiki are
-proposals, not currently executable instructions.
+```shell
+dotnet build -c Release
+dotnet test -c Release
+dotnet run --project src/SidePulse.Cli -- dashboard
+```
+
+
+The solution contains a portable core, a Spectre.Console CLI and behavioral tests.
+Command groups include `devices`, `state`, `write`, `dashboard`, `host`, `agents`,
+`link`, `animations`, `profiles`, `about`, `docs` and `update`. Use `--help` for
+subcommands and `--dry-run` where supported before changing files or sending a program.
+The command name `sidepulse-net` coexists with the existing Python port.
-The initial repository contains documentation checks, conditional .NET CI,
-optional wiki publication, Dependabot configuration, issue templates and a
-backlog of [11 planning issues](https://github.com/Anheledir/SidePulse.NET/issues).
-It does not claim a passing application build or test suite.
+QR pairing and protected token storage use DPAPI on Windows, Keychain on macOS
+and Secret Service on Linux. Login-startup registration, firmware-verified simulator parity,
+remaining upstream integrations and signed installers remain planned. The wiki's
+concept pages describe the intended complete product; the getting-started page
+records what is implemented now.
-Run the current checks with Python 3:
+CI builds and tests Windows, Linux and macOS; CI publishes self-contained x64 and ARM64
+preview archives for all three platforms. Wiki publishing uses the built-in Actions token. A weekly
+upstream check opens or updates a review issue when the original repository
+changes. See [automation setup](docs/wiki/Project-Setup.md).
+
+Documentation checks:
```shell
python scripts/check_docs.py
+python -m unittest discover -s scripts/tests -v
```
Contributions: [CONTRIBUTING.md](CONTRIBUTING.md). License: [MIT](LICENSE).
+
+## Agent setup and background use
+
+```shell
+sidepulse-net agents install codex --dry-run
+sidepulse-net agents install codex
+sidepulse-net agents install claude
+sidepulse-net agents install kiro
+sidepulse-net agents install copilot
+sidepulse-net host start --phone default
+sidepulse-net host status
+sidepulse-net host stop
+```
+
+See [agent integrations](docs/wiki/Agent-Integrations.md) for provider capabilities,
+configuration backups and trust requirements, and [host management](docs/wiki/Host-Management.md)
+for logs and foreground use. Additional providers remain planned.
+
+## Animation studio and scripting
+
+```shell
+sidepulse-net animations preview cyan-roll --both
+sidepulse-net animations edit --file custom.LED --model dot
+sidepulse-net animations validate custom.LED --quiet
+sidepulse-net animations import personal --file custom.LED --model dot
+sidepulse-net animations apply personal --model dot --phone default --brightness 40
+sidepulse-net profiles set personal --state Working --pattern cyan-roll --brightness 40
+sidepulse-net host start --phone default --profile personal --model dot
+sidepulse-net about credits
+sidepulse-net about licenses --full
+```
+
+Run with no arguments in a terminal for arrow-key menus and guided setup. Review
+shows the single-line command for copying into scripts. Redirected input/output,
+`--no-interactive`, `--quiet` and `--json` never open menus. Errors use stderr and
+nonzero exit codes. Preview is entirely Spectre.Console and supports pause,
+frame stepping and restart; terminal colors/timing approximate the firmware.
+
+See [animations](docs/wiki/Animations.md) and
+[scripting and menus](docs/wiki/Scripting-and-Menus.md). `docs --offline` reads
+bundled documentation; `about` provides manufacturer/upstream/project links and
+licensed dependency credits. Browser opening requires `--open`.
+
+## Verified updates
+
+```shell
+sidepulse-net update check
+sidepulse-net update install --prerelease --dry-run
+sidepulse-net host stop
+sidepulse-net update install --prerelease
+sidepulse-net update status
+```
+
+The updater selects a published GitHub release for the current OS/architecture,
+verifies SHA-256, stages the complete distribution and replaces it after the CLI
+exits. A backup and startup probe support rollback. Use self-contained packages
+with an installation manifest; older previews need one manual upgrade. Stop the
+host first and confirm `installed` before restarting it. See
+[updating and recovery](docs/wiki/Updating.md). Adding the release workflow does not
+publish a release; a matching version tag explicitly triggers publishing.
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..b0ae8fb
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,48 @@
+# Security policy
+
+SidePulse.NET is an unofficial, independently maintained MIT project. The current
+implementation is an unreleased alpha in PR #12. No stable release or response-time
+SLA is offered. Security fixes target the latest preview branch and subsequently
+the latest published preview; older previews are not maintained independently.
+
+## Report a vulnerability
+
+Use [GitHub private vulnerability reporting](https://github.com/Anheledir/SidePulse.NET/security/advisories/new)
+(enabled and verified 2026-10-24). If that page is unavailable, open an issue requesting a private
+reporting channel without publishing exploit details, phone tokens, credentials,
+logs containing secrets, or personal data. A maintainer will arrange a private
+channel. Effective settings and subsequent changes are tracked in the repository settings
+record.
+
+Please include the commit/version, OS and architecture, affected command, impact,
+and a minimal reproduction with redacted sample data. Coordinate publication with
+the maintainer. Report upstream firmware, iOS application and bridge-service
+vulnerabilities to their maintainers through their published reporting channels.
+
+## Trust boundaries
+
+- Hooks execute locally with the agent's existing user permissions. Setup never
+ approves tools, changes agent trust, or reads conversation transcripts.
+- Local IPC is restricted to the current OS user. It is not a boundary against
+ malicious software already running as that user. All CLI and host instances
+ should use the same version; rolling mixed-version IPC is not supported.
+- Phone credentials use DPAPI, Keychain or Secret Service. There is no plaintext
+ fallback. Bridge acceptance does not prove that an iPhone displayed a pattern.
+- Self-update accepts packages from this project's GitHub releases and verifies
+ SHA-256 before extraction and each manifest-owned file before replacement.
+ Checksums from the same publisher detect corruption, not a compromised publisher.
+ Packages are not independently code-signed. Keep the previous installation backup
+ until startup and hardware behavior have been checked.
+- Use a dedicated application directory. Stop the host and other application
+ instances, run updates from outside that directory, and avoid editing its files
+ while an update is pending. User-added files are copied during preparation;
+ later changes remain in the retained backup and require manual reconciliation.
+
+## Maintainer controls
+
+Actions use pinned revisions and read-only permissions by default, with scoped
+write permissions for publication and scanning. Weekly Dependabot proposals,
+CodeQL and PR dependency review are configured in source. Their effective status,
+repository-level controls and any access limitations are documented in
+[the settings record](docs/repository-settings.md). Security findings require
+triage; a green build is not proof of firmware compatibility or absence of flaws.
diff --git a/SidePulse.NET.slnx b/SidePulse.NET.slnx
new file mode 100644
index 0000000..3b127e1
--- /dev/null
+++ b/SidePulse.NET.slnx
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
diff --git a/docs/backlog.json b/docs/backlog.json
index 4326474..a4ed7a4 100644
--- a/docs/backlog.json
+++ b/docs/backlog.json
@@ -1,79 +1,79 @@
[
{
- "title": "M0: Review product concept and compatibility boundaries",
+ "title": "Investigate firmware, raw USB and platform-specific helpers",
"labels": [
"documentation"
],
- "body": "Approve terminal workflow, .NET 10 baseline, initial sidepulse-net command, aggregation priorities and explicit platform exclusions. Record decisions before C# scaffolding.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started."
+ "body": "Priority: P3 feasibility research; intentionally outside the preview implementation.\n\n- [ ] Inventory firmware recovery and read-only control protocols against pinned upstream, with licensing and device/firmware matrix.\n- [ ] Assess SPC2/READ2ME and raw USB access separately on Windows/macOS/Linux, including drivers, privilege requirements and exclusive-device access.\n- [ ] Define recovery and interruption tests before firmware writes; require explicit device confirmation and a recoverable test unit.\n- [ ] Assess macOS guards/power helpers and optional MLX classifier as separate platform-specific features, not cross-platform requirements.\n- [ ] Record go/no-go decisions, excluded behavior and safe fallback to mounted-file output.\n\nAcceptance: publish research and transport boundaries before implementing privileged/raw access. Do not bundle drivers, flash firmware or claim parity as part of this review. Dependencies: physical inventory/results from #2/#3.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met."
},
{
- "title": "M1: Port LED language and upstream validation vectors",
+ "title": "M3: Validate cross-platform releases and verified self-update",
"labels": [
"enhancement"
],
- "body": "Verify escapes, 512-byte and 20-line limits, LED counts, brightness, invalid input and attributed fixtures against the pinned upstream revision.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started."
+ "body": "Priority: P1 release gate. Status: cross-platform packaging/updater implemented in PR #12; no release published.\n\n- [x] Self-contained Windows/Linux/macOS x64 + ARM64 archives; manifests, bundled licenses, SHA256SUMS publication workflow.\n- [x] Explicit update check/install/status, semantic channel selection, checksums/digests, bounded extraction and file verification.\n- [x] Native Windows x64/Linux x64/macOS ARM64 helper replacement, startup-failure rollback and receipts in CI. Other architectures are cross-built only.\n- [x] Review fixes cover pre-existing download preservation, body timeout and directory-entry limits.\n- [ ] Exercise matching-tag release workflow and inspect all six assets/checksums before announcing a downloadable release. Creating a release is not authorized by this issue review.\n- [ ] Test public install orchestration end to end against a controlled published preview: lookup/download/prepare/helper launch/caller exit/replacement/status. Existing smoke prepares the helper plan directly.\n- [ ] Validate manual install/remove/PATH instructions on clean supported systems; execute remaining architecture packages on native hardware.\n- [ ] Record signing and package-manager decisions; packages are currently unsigned, no installer/package manager exists.\n- [ ] Before adding cleanup or stronger preservation claims, detect user-added file edits between Prepare and Apply; current snapshot is preparation-time and later edits survive only in retained backup.\n\nAcceptance: scheduling is not completion; keep backups and stop host before update. Checksums detect corruption, not compromise of the release publisher. Upgrade from source/old unmanifested builds requires manual install.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met."
},
{
- "title": "M1: Implement writable USB device transport on Windows",
+ "title": "M2: Port remaining upstream integrations and remote relay",
"labels": [
"enhancement"
],
- "body": "Discover volumes, select destinations and write/flush programs. Verify a real Dot and removal, read-only and ambiguous-device cases.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started."
+ "body": "Priority: P2 provider expansion and remote design.\n\n- [x] Codex current local lifecycle hooks, Claude Code and Kiro CLI V3 adapters/config generators added in PR #12, alongside Copilot (#6).\n- [x] Provider capability inventory states unsupported subagent/payload cases; root sessions are namespaced.\n- [ ] Record actual installed provider versions and captured redacted event fixtures for Codex, Claude and Kiro; run real waiting/error/completion acceptance separately for each.\n- [ ] Cursor adapter and documented event contract.\n- [ ] Grok adapter and documented event contract.\n- [ ] Junie adapter and documented event contract.\n- [ ] Assess Gemini support before advertising it.\n- [ ] Design authenticated relay and Android support with separate threat model, secrets storage and delivery semantics.\n\nAcceptance: no implied provider parity from generated JSON alone; no paid API dependency or automatic trust changes. Split a provider into its own issue when implementation begins.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met."
},
{
- "title": "M1: Implement phone pairing and bridge delivery",
+ "title": "M1: Add diagnostics, aliases and explicit migration",
"labels": [
"enhancement"
],
- "body": "Pair original iOS app, protect credentials, support target selection and separate silent LED updates from visible notifications. Test offline delivery and show only supported acknowledgement levels.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started."
+ "body": "Priority: P2 follow-up, partial implementation.\n\n- [x] Doctor diagnostics, explicit device selection, phone aliases/defaults and host logs.\n- [x] Existing Python configuration is not silently modified or imported.\n- [ ] Add device aliases with ambiguity checks and previewable target resolution.\n- [ ] Implement explicit Python migration/import preview, exact backups, user-selected destinations and rollback evidence.\n- [ ] Test missing drives, inaccessible vaults, invalid hooks and failed bridge delivery with actionable diagnostics.\n\nAcceptance: a dry-run must not create provider/configuration/backup/lock files. Preserve old Python configuration and credentials; never print tokens. Depends on transport and phone behavior in #3/#4.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met."
},
{
- "title": "M1: Implement shared host and session state reduction",
+ "title": "M1: Design and implement the Spectre terminal experience",
"labels": [
"enhancement"
],
- "body": "Version current-user IPC, aggregate concurrent sessions, ignore late events, persist minimal restart metadata and serialize outputs. Hooks must not wait on network I/O.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started."
+ "body": "Priority: P2 UX and accessibility. Status: interactive CLI and animation studio implemented in PR #12.\n\n- [x] Root/group cursor menus, guided pattern editor, Dot/Pro Spectre previews, review/copy/export of full single-line commands.\n- [x] --quiet, --json, --no-interactive, redirected IO and NO_COLOR behavior; shell quoting tests; Unix PTY menu/editor/playback smoke.\n- [x] About/docs/credits and offline dependency license texts, explicit website opening without unapproved affiliate IDs.\n- [ ] Implement or explicitly defer the originally proposed continuously refreshed host dashboard (current host renders state snapshots).\n- [ ] Manual Windows Terminal keyboard/clipboard and narrow-screen/no-color accessibility checks; PTY smoke is Unix-only.\n- [ ] Audit JSON schemas across command states, including update status with/without receipts, and document stable script fields.\n\nAcceptance: scripts never enter menus or wait for input; stdout remains usable for machine output and errors go to stderr.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met."
},
{
"title": "M1: Implement Copilot CLI hook integration",
"labels": [
"enhancement"
],
- "body": "Install/repair/remove dedicated hooks, handle real waiting notifications and turn ends, avoid permission decisions, preserve unrelated hooks and verify a real Windows CLI session.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started."
+ "body": "Priority: P1 real-provider acceptance. Status: integration implemented in PR #12.\n\n- [x] Provider-specific Copilot lifecycle/notification parser and silent Bash/PowerShell wrappers.\n- [x] Dedicated hook ownership, byte-exact backups, dry-run setup/removal and changed-file refusal.\n- [x] QA regression: changed executable reinstall now refuses instead of silently retaining old hooks; uninstall preview creates no lock file.\n- [ ] Verify real Windows Copilot CLI session with recorded version: Working, permission waiting, completion, error and multiple concurrent sessions.\n- [ ] Verify trust prompts, restart requirements and setup/remove alongside unrelated real hooks.\n- [ ] Define repair workflow. Current safe path is explicit uninstall/reinstall; no automatic repair command exists.\n\nAcceptance: do not auto-approve tool use or modify trust/permission settings. Current tests use fixtures/generated wrappers, not a live Copilot session.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met."
},
{
- "title": "M1: Design and implement the Spectre terminal experience",
+ "title": "M1: Implement shared host and session state reduction",
"labels": [
"enhancement"
],
- "body": "Prototype live dashboard/menu interaction, compact layout, session/device views, terminal capabilities, keyboard flow and plain/JSON/noninteractive modes.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started."
+ "body": "Priority: P1 lifecycle/compatibility specification. Status: shared host implemented in PR #12.\n\n- [x] Current-user IPC, single-host lease, bounded requests, ACKed control RPC, independent bounded output queue.\n- [x] Provider-namespaced sessions; out-of-order timestamp rejection; Waiting > Working > Error > Done > Idle > Unknown; error survives Stop.\n- [x] Detached start/status/stop/logs and Unix crash recovery exercised in native CI.\n- [ ] Decide and implement explicit IPC protocol version negotiation before supporting mixed CLI/host versions. Currently require same version and stop host for upgrade.\n- [ ] Resolve restart semantics: implementation intentionally starts Unknown and does not persist sessions; original minimal-restart-metadata requirement is deferred, not complete.\n- [ ] Specify retention/recovery for 1,024 live/error sessions and long-lived abandoned sessions; provide an explicit reset/removal policy without inventing agent completion.\n- [ ] Define direct-command arbitration: state/write/animation apply currently bypass host serialization and can replace its output; either document manual override semantics or route them through the host.\n\nAcceptance: hooks remain silent and bounded, never wait for network or change permission decisions. Keep restart/version/retention decisions testable.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met."
},
{
- "title": "M1: Add diagnostics, aliases and explicit migration",
+ "title": "M1: Implement phone pairing and bridge delivery",
"labels": [
"enhancement"
],
- "body": "Explain broken integrations/paths and transport failures; add device aliases and import preview/backup without modifying the existing Python port silently.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started."
+ "body": "Priority: P1 iPhone acceptance. Status: pairing and delivery implemented in PR #12.\n\n- [x] QR/SSE pairing, bounded input, token normalization and link aliases/defaults.\n- [x] DPAPI/Keychain/Secret Service protection with fail-closed recovery; native vault CI.\n- [x] Silent bridge delivery and explicit target selection; redacted errors.\n- [ ] Scan the QR with the original TestFlight app and verify token persistence/restart on each desktop OS.\n- [ ] Test offline bridge, network interruption, HTTP errors and phone reconnection; document retry policy (no durable offline queue today).\n- [ ] Demonstrate silent LED update versus any visible notification behavior supported by the app; visible notifications are not implemented as a separate command.\n\nAcceptance: record bridge HTTP acceptance separately from observed phone display. No transport acknowledgement overclaim.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met."
},
{
- "title": "M2: Port remaining upstream integrations and remote relay",
+ "title": "M1: Validate cross-platform writable USB/SD device transport",
"labels": [
"enhancement"
],
- "body": "Track Codex, Claude, Cursor, Grok and Junie separately, plus relay and Android. Record payload compatibility and hardware verification per inventory row.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started."
+ "body": "Priority: P1 physical acceptance. Status: cross-platform mounted-file implementation in PR #12.\n\n- [x] Discover mounted LEDS.LED files; explicit selection; ambiguous-device refusal.\n- [x] Write/length/flush to the existing virtual file without rename; simulated file tests.\n- [ ] Record physical Dot and Pro acceptance on Windows, macOS and Linux with device/firmware/OS versions.\n- [ ] Exercise removal during write, read-only media, multiple devices and recovery on real mounts.\n- [ ] Verify Linux mount discovery on actual USB and SD mount layouts; document when --device is required.\n\nAcceptance: report file-write success only, never firmware/display acknowledgement. Read-only USB/SPC2/READ2ME work belongs in #11.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met."
},
{
- "title": "M3: Build verified self-contained Windows releases",
+ "title": "M1: Port LED language and upstream validation vectors",
"labels": [
"enhancement"
],
- "body": "Introduce release workflow after real projects/tests exist; produce x64/arm64 artifacts and checksums, verify install/uninstall and document signing/package-manager decisions.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started."
+ "body": "Priority: P1 before firmware-parity claims. Status: partial implementation in PR #12.\n\n- [x] Envelope validation: escapes, NUL rejection, 512 UTF-8 bytes, 20 physical lines.\n- [x] Managed Dot/Pro parser/player: indexed colors, timing, easing, brightness, roll and repeat; bounded simulation.\n- [x] Attributed upstream pattern assets pinned by NOTICE.md; automated parsing/frame tests.\n- [ ] Build an independently derived, attributed upstream/firmware golden vector corpus for timing, repeat boundaries, invalid syntax and model indexing.\n- [ ] Compare real Dot and Pro output against these vectors and record firmware versions/results.\n\nAcceptance: distinguish envelope validation, managed simulation and firmware acceptance. Terminal color/timing is approximate until comparison. No claim of full grammar or firmware parity.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met."
},
{
- "title": "Investigate firmware, raw USB and platform-specific helpers",
+ "title": "M0: Review product concept and compatibility boundaries",
"labels": [
"documentation"
],
- "body": "Decide feasibility and safety tests for firmware recovery, read-only USB control, Windows drivers, macOS guards/power helpers and the optional MLX classifier. Do not imply parity before verification.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started."
+ "body": "Priority: complete concept decision.\n\n- [x] Maintainer approved recognizable/simple Spectre terminal design, MIT license and implementation.\n- [x] .NET 10, independent sidepulse-net executable and coexistence with the Python port.\n- [x] Cross-platform scope, provider-namespaced sessions and explicit unsupported transport boundaries.\n- [x] Decisions recorded in docs/decisions/0001 through 0003; implementation proceeds in PR #12.\n\nThe discussion subsequently expanded the Windows-first concept to Windows, macOS and Linux. This closes concept approval only; implementation, physical compatibility and release gates remain in #2–#11.\n\nReview: 2026-10-23. See PR #12 and docs/decisions."
}
]
diff --git a/docs/decisions/0001-project-boundary.md b/docs/decisions/0001-project-boundary.md
index 43f55ee..d4765ee 100644
--- a/docs/decisions/0001-project-boundary.md
+++ b/docs/decisions/0001-project-boundary.md
@@ -1,14 +1,13 @@
# ADR 0001: Independent .NET companion
-Status: proposed, 2026-10-23.
+Status: accepted by the maintainer in the project discussion, 2026-10-23.
-Build SidePulse.NET as an independently maintained, Windows-first .NET 10 LTS
+Build SidePulse.NET as an independently maintained, cross-platform .NET 10 LTS
application using Spectre.Console and Spectre.Console.Cli. Preserve compatible
wire behavior where feasible, while tracking platform-specific limitations.
-The initial repository contains planning and automation only. Do not add C#
-application scaffolding until concept review is complete. The working Python port
-and its hook add-on remain separate reference implementations.
+The concept review is complete and implementation is in PR #12. The working
+Python port and its hook add-on remain separate reference implementations.
This permits an idiomatic C# architecture without claiming drop-in compatibility
for all macOS-specific helpers. Upstream attribution and license retention are
diff --git a/docs/decisions/0002-runtime-and-coexistence.md b/docs/decisions/0002-runtime-and-coexistence.md
index bc5c22b..182a4c2 100644
--- a/docs/decisions/0002-runtime-and-coexistence.md
+++ b/docs/decisions/0002-runtime-and-coexistence.md
@@ -1,13 +1,16 @@
# ADR 0002: Shared state owner and explicit migration
-Status: proposed, 2026-10-23.
+Status: accepted by the maintainer in the project discussion, 2026-10-23.
A local background host will own event reduction, per-session state and device
outputs. Hook adapters will enqueue small events over authenticated local IPC.
The Spectre dashboard and noninteractive commands will use the same state owner.
-Windows named pipes scoped to the current user are the preferred initial IPC
-transport. Transport details, restart recovery and latency budgets need a prototype.
+Current-user .NET named pipes are implemented on all three desktop platforms.
+Hooks have a 600ms budget; host control has a two-second deadline. Native CI
+exercises host lifecycle and Unix endpoint crash recovery. Protocol negotiation,
+session restart persistence and retention policy remain open decisions in #5;
+restart currently begins Unknown and CLI/host versions must match.
Use `sidepulse-net` as the initial command to coexist with the existing Python
`sidepulse`. Offer a `sidepulse` alias only by explicit choice. Store new settings
diff --git a/docs/decisions/0003-platform-support.md b/docs/decisions/0003-platform-support.md
new file mode 100644
index 0000000..3366633
--- /dev/null
+++ b/docs/decisions/0003-platform-support.md
@@ -0,0 +1,17 @@
+# ADR 0003: Windows, macOS and Linux preview support
+
+Status: accepted, 2026-10-23, following the explicit request for multiple platforms.
+
+The application targets Windows, macOS and Linux with shared portable logic.
+Runtime-specific credential adapters use DPAPI, native Keychain SecItem APIs and
+Secret Service respectively. Unix link documents use authenticated AES-256-GCM
+with per-configuration-path keys in the native vault. No plaintext fallback is
+provided. Windows retains its existing path and format.
+
+Copilot hook files include PowerShell and Bash commands. Current-user .NET named
+pipes provide local IPC on all three platforms. Platform CI must exercise native
+credentials, hook forwarding and simulated device writes, and package x64/ARM64
+archives with execution checks for each runner's native architecture.
+
+This supersedes the initial Windows-only delivery priority. It does not promise
+parity for upstream OS-specific helpers, raw USB, firmware, installers or services.
diff --git a/docs/repository-settings.json b/docs/repository-settings.json
new file mode 100644
index 0000000..ab06230
--- /dev/null
+++ b/docs/repository-settings.json
@@ -0,0 +1,276 @@
+{
+ "repository": "Anheledir/SidePulse.NET",
+ "reviewedOn": "2026-10-24",
+ "implementationPullRequest": 12,
+ "observed": {
+ "visibility": "public",
+ "defaultBranch": "main",
+ "description": "Unofficial cross-platform SidePulse companion in C# and Spectre.Console: agent status hooks, LED patterns, iPhone pairing and verified updates.",
+ "homepage": "https://github.com/Anheledir/SidePulse.NET/wiki",
+ "topics": [
+ "sidepulse",
+ "dotnet",
+ "csharp",
+ "spectre-console",
+ "cli",
+ "cross-platform",
+ "github-copilot",
+ "codex",
+ "claude-code",
+ "kiro",
+ "led"
+ ],
+ "hasIssues": true,
+ "hasWiki": true,
+ "hasProjects": true,
+ "deleteBranchOnMerge": true,
+ "allowMergeCommit": false,
+ "allowSquashMerge": true,
+ "allowRebaseMerge": true,
+ "allowAutoMerge": false,
+ "privateVulnerabilityReporting": true,
+ "dependencyGraph": true,
+ "dependabotAlerts": true,
+ "dependabotSecurityUpdates": true,
+ "groupedSecurityUpdates": true,
+ "malwareAlerts": true,
+ "secretScanning": true,
+ "secretScanningPushProtection": true,
+ "codeQLSetup": "advanced",
+ "codeScanningSecurityFailureThreshold": "high or higher",
+ "codeScanningStandardFailureThreshold": "errors",
+ "releaseImmutability": true,
+ "wikiCollaboratorsOnly": true,
+ "webCommitSignoff": true,
+ "actionsDefaultTokenPermissions": "read",
+ "actionsCanCreateAndApprovePullRequests": false,
+ "actionsAllowedSources": "Owner and GitHub-created actions only; Marketplace creators not broadly allowed; no extra allowlist.",
+ "actionsRequireFullCommitSHA": true,
+ "forkWorkflowApproval": "all external contributors",
+ "retentionDays": 90,
+ "cacheRetentionDays": 7,
+ "cacheSizeGB": 10
+ },
+ "desired": {
+ "description": "Unofficial cross-platform SidePulse companion in C# and Spectre.Console: agent status hooks, LED patterns, iPhone pairing and verified updates.",
+ "homepage": "https://github.com/Anheledir/SidePulse.NET/wiki",
+ "topics": [
+ "sidepulse",
+ "dotnet",
+ "csharp",
+ "spectre-console",
+ "cli",
+ "cross-platform",
+ "github-copilot",
+ "codex",
+ "claude-code",
+ "kiro",
+ "led"
+ ],
+ "hasProjects": true,
+ "privateVulnerabilityReporting": true,
+ "dependabotAlerts": true,
+ "dependabotSecurityUpdates": true,
+ "secretScanning": true,
+ "secretScanningPushProtection": true,
+ "actionsDefaultTokenPermissions": "read",
+ "actionsCanApprovePullRequests": false,
+ "mainRules": {
+ "requirePullRequest": true,
+ "requiredApprovals": 0,
+ "requireConversationResolution": true,
+ "requireUpToDateBranch": true,
+ "blockForcePushes": true,
+ "blockDeletion": true,
+ "requiredChecksPolicy": "Require Quality, all three native build jobs, CodeQL and dependency review after successful check names are observed.",
+ "requiredCheckNames": [
+ "documentation",
+ "build (windows-latest)",
+ "build (ubuntu-latest)",
+ "build (macos-latest)",
+ "CodeQL (csharp)",
+ "CodeQL (python)",
+ "CodeQL (actions)",
+ "Dependency review",
+ "CodeQL"
+ ]
+ }
+ },
+ "verificationLimits": {
+ "repositoryAdministration": "The connector lacks admin mutations. Requested settings were applied in the signed-in browser, with fresh GitHub verification for ruleset creation.",
+ "branchProtection": "Classic branch-protection GET still excluded by integration; active ruleset verified in UI and GET /rulesets/25761788.",
+ "securityAndAnalysis": "Effective settings verified in browser rather than inferred from the limited repository response.",
+ "unperformed": "No merge, release, tag, real hardware or real provider acceptance performed."
+ },
+ "verifiedPullRequestChecks": {
+ "commit": "f1ada51a836a91e2420e507ac589e195b9990ab5",
+ "nativeCI": "https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767890",
+ "nativeTestsPerOS": 104,
+ "quality": "passed",
+ "dependencyReview": "passed",
+ "codeQL": "C#, Python and Actions analyses passed; combined CodeQL check reports no new alerts after canonical containment hardening. No suppression or dismissal.",
+ "observedCheckNames": [
+ "documentation",
+ "build (windows-latest)",
+ "build (ubuntu-latest)",
+ "build (macos-latest)",
+ "CodeQL (csharp)",
+ "CodeQL (python)",
+ "CodeQL (actions)",
+ "Dependency review",
+ "CodeQL"
+ ],
+ "securityRun": "https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767819"
+ },
+ "initialObserved": {
+ "visibility": "public",
+ "defaultBranch": "main",
+ "description": "Unofficial .NET companion for SidePulse with a Spectre.Console terminal UI. Concept stage.",
+ "homepage": null,
+ "topics": [],
+ "hasIssues": true,
+ "hasWiki": true,
+ "hasProjects": false,
+ "deleteBranchOnMerge": true,
+ "allowMergeCommit": false,
+ "allowSquashMerge": true,
+ "allowRebaseMerge": true,
+ "allowAutoMerge": false
+ },
+ "initialObservedOn": "2026-10-23",
+ "appliedRemoteChanges": [
+ {
+ "setting": "Repository description, homepage and topics",
+ "result": "Saved and verified with UI plus repository API"
+ },
+ {
+ "setting": "Projects feature",
+ "result": "Enabled"
+ },
+ {
+ "setting": "Dependency malware alerts",
+ "result": "Enabled and saved"
+ },
+ {
+ "setting": "Actions source policy",
+ "result": "Restricted to owner and GitHub-created actions; full commit SHA required"
+ },
+ {
+ "setting": "Fork workflow approval",
+ "result": "Required for all external contributors"
+ },
+ {
+ "setting": "Main delivery checks ruleset",
+ "result": "Created active, ID 25761788, default branch main, no bypass actors, zero approvals, PR/conversation/current-check requirements, deletion and force-push blocked"
+ }
+ ],
+ "verifiedExistingControls": [
+ "Private vulnerability reporting",
+ "Dependency graph",
+ "Dependabot alerts and security updates",
+ "Grouped security updates",
+ "Secret scanning and push protection",
+ "Immutable releases",
+ "Collaborator-only wiki editing",
+ "Read-only Actions token default",
+ "Actions PR creation/approval disabled"
+ ],
+ "mainRuleset": {
+ "id": 25761788,
+ "name": "Main delivery checks",
+ "url": "https://github.com/Anheledir/SidePulse.NET/settings/rules/25761788",
+ "enforcement": "active",
+ "include": [
+ "~DEFAULT_BRANCH"
+ ],
+ "bypassActors": [],
+ "requiredApprovals": 0,
+ "requirePullRequest": true,
+ "requireConversationResolution": true,
+ "requireUpToDateBranch": true,
+ "blockDeletion": true,
+ "blockForcePushes": true,
+ "requiredChecks": [
+ {
+ "context": "documentation",
+ "integrationId": 15368
+ },
+ {
+ "context": "build (windows-latest)",
+ "integrationId": 15368
+ },
+ {
+ "context": "build (ubuntu-latest)",
+ "integrationId": 15368
+ },
+ {
+ "context": "build (macos-latest)",
+ "integrationId": 15368
+ },
+ {
+ "context": "CodeQL (csharp)",
+ "integrationId": 15368
+ },
+ {
+ "context": "CodeQL (python)",
+ "integrationId": 15368
+ },
+ {
+ "context": "CodeQL (actions)",
+ "integrationId": 15368
+ },
+ {
+ "context": "Dependency review",
+ "integrationId": 15368
+ },
+ {
+ "context": "CodeQL",
+ "integrationId": 57789
+ }
+ ],
+ "existingDisabledRuleset": {
+ "id": 25757011,
+ "name": "Main",
+ "disposition": "Preserved disabled without changes"
+ }
+ },
+ "project": {
+ "number": 5,
+ "name": "SidePulse.NET delivery",
+ "url": "https://github.com/users/Anheledir/projects/5/views/1",
+ "visibility": "private",
+ "linkedRepository": "Anheledir/SidePulse.NET",
+ "description": "Cross-platform SidePulse.NET delivery, compatibility evidence and release gates.",
+ "view": "Delivery",
+ "columns": [
+ "Todo",
+ "In Progress",
+ "Validation",
+ "Done"
+ ],
+ "items": {
+ "Todo": [
+ 11
+ ],
+ "In Progress": [
+ 5,
+ 7,
+ 8,
+ 9
+ ],
+ "Validation": [
+ 2,
+ 3,
+ 4,
+ 6,
+ 10,
+ 12
+ ],
+ "Done": [
+ 1
+ ]
+ },
+ "autoImport": "Open issues and pull requests from this repository",
+ "readme": "Scope, status meanings, validation evidence and attribution documented."
+ }
+}
diff --git a/docs/repository-settings.md b/docs/repository-settings.md
new file mode 100644
index 0000000..080e7e1
--- /dev/null
+++ b/docs/repository-settings.md
@@ -0,0 +1,111 @@
+# Repository configuration record
+
+Verified 2026-10-24. [Machine-readable settings and change log](repository-settings.json).
+The implementation is in PR #12 and has not been merged or released.
+
+The GitHub connector excludes administration mutations. The requested admin work
+was completed through the signed-in browser; ruleset creation required fresh
+GitHub verification. Saved values were checked in the UI, metadata through the
+repository API, and the active ruleset through the ruleset API. No PAT was created.
+
+## Changes applied
+
+| Setting | Effective value |
+|---|---|
+| Description | Unofficial cross-platform SidePulse companion in C# and Spectre.Console: agent status hooks, LED patterns, iPhone pairing and verified updates. |
+| Homepage | Project wiki |
+| Topics | sidepulse, dotnet, csharp, spectre-console, cli, cross-platform, github-copilot, codex, claude-code, kiro, led |
+| Projects | Enabled; delivery board created and linked |
+| Dependency malware alerts | Enabled |
+| Actions sources | Owner and GitHub-created actions only; no broad Marketplace allowance |
+| Actions revision policy | Full commit SHA required |
+| External fork workflows | Approval required for all external contributors |
+| Main protection | Active ruleset 25761788, described below |
+
+## Verified existing controls
+
+Private vulnerability reporting, dependency graph, Dependabot alerts/security
+updates and grouped security updates were already on. Secret scanning and push
+protection were already on. Releases were already immutable. Wiki editing was
+already restricted to collaborators. Actions default token access was already
+read-only, and Actions creation/approval of pull requests was disabled.
+
+CodeQL uses advanced setup. Its combined check fails for high-or-higher security
+alerts and standard errors. Optional AI Scan and credit-consuming agentic autofix
+remain off; existing Copilot Autofix is on. Automatic dependency submission is off.
+
+The repository remains public, `main` remains default, squash/rebase merges are
+allowed, merge commits and auto-merge are off, and merged branches are deleted.
+Existing web-commit signoff remains on. General log/artifact retention is 90 days;
+preview packages request 14 days in the workflow. Cache retention/size remain
+7 days/10 GB. No account, ownership or collaborator permissions were changed.
+
+## Main delivery checks
+
+[Active ruleset](https://github.com/Anheledir/SidePulse.NET/settings/rules/25761788)
+targets the default branch, currently `main`, with an empty bypass list:
+
+- Require a pull request, resolved conversations and an up-to-date tested branch.
+- Block branch deletion and force pushes.
+- Require `documentation`, `build (windows-latest)`, `build (ubuntu-latest)`,
+ `build (macos-latest)`, `CodeQL (csharp)`, `CodeQL (python)`, `CodeQL (actions)`,
+ `Dependency review`, and the combined `CodeQL` alert check.
+- Bind the combined alert check to GitHub Advanced Security (integration 57789)
+ and the eight workflow checks to GitHub Actions (integration 15368).
+- Require zero approvals for this solo-maintainer project. GitHub prevents
+ self-approval; the PR/check/conversation requirements still apply.
+
+The existing **Main** ruleset 25757011 was disabled. It remains untouched and
+disabled. Its signed-commit/code-quality/Copilot requirements were not silently
+activated. The new rule requires the observed combined CodeQL check rather than
+requiring scanning results on both the implementation and the unscanned default
+branch, which would block the first implementation merge.
+
+Future branch-policy changes should preserve the distinction between scan-job
+completion and a clean alert result. Required check names were observed in
+successful runs, not invented. Repository merge settings still exclude merge
+commits even though the ruleset's allowed-method intersection includes them.
+
+## Delivery project
+
+[SidePulse.NET delivery](https://github.com/users/Anheledir/projects/5/views/1)
+is a private owner project linked to this public repository. It has a Delivery
+board, short description and README explaining scope, status meanings, validation
+requirements and attribution. It imports open issues and PRs from this repository.
+
+| Column | Items at verification |
+|---|---|
+| Todo | #11 |
+| In Progress | #5, #7, #8, #9 |
+| Validation | #2, #3, #4, #6, #10, PR #12 |
+| Done | #1, concept approval only |
+
+All eleven issues and PR #12 are represented. Incomplete implementation and
+physical/provider/release acceptance remain visible instead of marking them done.
+The board remains private; repository visibility was not changed.
+
+## Source configuration and evidence
+
+Weekly Dependabot updates for NuGet and Actions already exist. PR #12 adds
+SECURITY.md, C#/Python/Actions CodeQL on PRs/main/weekly schedule, and PR dependency
+review rejecting new high/critical advisories. Third-party Actions are pinned;
+workflow permissions are read-only by default with scoped publication/scanning
+exceptions. Wiki/upstream publishing runs only from the default branch.
+
+Reviewed code `f1ada51` passed **104 tests per OS** in
+[native CI](https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767890),
+including updater replacement and rollback. Quality and dependency review passed.
+[Security analysis](https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767819)
+passed all three languages; the combined CodeQL check reports no new alerts after
+canonical containment hardening. No rule was suppressed or alert dismissed.
+
+The audit/settings commits change documentation only. Check the PR head's required
+checks before merging. Source documentation/wiki/security-policy changes become
+default-branch documentation only after merge. Runtime/hardware/provider release
+gates remain in the issues and [QA review](reviews/pr-12.md).
+
+## References
+
+- [GitHub security settings](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/managing-security-and-analysis-settings-for-your-repository)
+- [CodeQL manual builds](https://docs.github.com/en/code-security/how-tos/find-and-fix-code-vulnerabilities/manage-your-configuration/codeql-for-compiled-languages)
+- [Dependency review action](https://github.com/actions/dependency-review-action)
diff --git a/docs/reviews/pr-12.md b/docs/reviews/pr-12.md
new file mode 100644
index 0000000..54e1bf9
--- /dev/null
+++ b/docs/reviews/pr-12.md
@@ -0,0 +1,112 @@
+# PR #12 architecture and QA review
+
+Review dates: 2026-10-23 through 2026-10-24. Baseline: `444767f66cc6ca73f999339ba671923a10d61ffe`.
+Scope: application architecture, credential and IPC boundaries, hook ownership,
+terminal/script behavior, animation model, updater transactions, tests, workflows,
+all eleven open issues, repository metadata and available security settings.
+This is a maintainer-assisted review, not independent approval or a penetration test.
+
+## Assessment
+
+The Core/CLI split is appropriate: the transport, reducer, parser and update
+transaction can be tested without Spectre or hardware. Native secret adapters
+fail closed, hooks remain isolated from network delivery, shared config writes
+preserve exact backups, and update replacement verifies both packages and files.
+There is useful behavior coverage beyond happy paths, including crash recovery,
+modified configuration, corrupt packages and actual startup-probe rollback.
+
+PR #12 is an alpha implementation with substantial follow-up scope. Do not merge
+it under a firmware-parity or production-ready claim. The review found no
+confirmed critical vulnerability, but that is not evidence of absence. New
+security checks and the review fixes must pass before merge. Hardware/provider
+acceptance and the public update/release path remain explicit release gates.
+
+## Confirmed findings and disposition
+
+| ID | Priority | Trigger and impact | Disposition / evidence |
+|---|---|---|---|
+| R1 | P1 data preservation | `GitHubReleases.Download`: an existing package filename makes CreateNew fail, then unconditional cleanup deletes that pre-existing file. | Fixed: cleanup only after this invocation successfully creates the file. Regression reproduced original deletion and now checks original bytes survive. |
+| R2 | P2 availability | `Latest` uses ResponseHeadersRead, so HttpClient's timeout ends at headers; a stalled body can hang standalone update check. | Fixed: linked deadline covers metadata bodies and pagination. Regression stalls a stream after headers and uses the client's timeout without caller cancellation. |
+| R3 | P2 resource bounds | `UpdatePackage.Extract`: file limits exclude directory-only archive entries, permitting arbitrarily long directory-entry processing within archive size bounds. | Fixed: count all ZIP/tar entries and check cancellation per entry; regression covers 10,001 directories and staging cleanup. Central-directory parsing still precedes the ZIP loop; compressed archive byte limits also apply. |
+| R4 | P2 dry-run contract | `HookInstallation.Uninstall(..., true)` creates a lock sidecar before returning preview. | Fixed: preview reads only. Regression deletes the previous lock and verifies no new lock/config changes. Real removal reloads ownership after taking the lock. |
+| R5 | P2 correctness | Reinstall with a new executable returns installed while silently keeping old hooks. | Fixed: reconstruct the requested install from the verified original backup, compare hashes and require explicit uninstall/reinstall when it differs. Dedicated/shared provider regressions preserve existing bytes. |
+| R6 | P2 compatibility | IPC has no protocol handshake, starts Unknown after restart, and retains up to 1,024 active/error sessions without stale-session reset. | Tracked in #5. Same-version CLI/host is required. Decide version/restart/retention semantics before claiming mixed-version support. |
+| R7 | P2 preservation window | User-added files are copied at update preparation; edits before replacement are not recopied. | Tracked in #10 and documented in SECURITY.md. Later edits remain in retained backup; do not claim concurrent-edit preservation. |
+| R8 | P1 release evidence | Updater smoke prepares a helper plan directly. It does not exercise the complete public install command against published assets. Tag publication has not run and there is no published release. | Open release gate in #10; controlled published-preview test required before announcing self-update ready for general use. No release/tag created in this review. |
+| R9 | P1 compatibility evidence | Simulated LED output and generated agent wrappers are not real firmware, iOS or provider acceptance. | Open criteria in #2/#3/#4/#6/#9 with versioned evidence required. |
+| R11 | High scanner finding / P1 triage | Initial C# CodeQL reported `cs/zipslip` at ZIP extraction. Existing portable-name validation rejected traversal in tests, so an escape was not reproduced. | Added final canonical full-path containment with a directory-separator boundary, retaining the portable-name checks. Extended tar/ZIP traversal and directory-count tests. No rule suppression or alert dismissal. The final combined CodeQL check passed with no new alerts. |
+| R12 | P2 architecture | Target architecture claimed every writer used the host, but direct state/write/animation commands send independently. | Corrected architecture documentation; #5 now tracks arbitration/manual-override policy. Stop the host for manual device checks. |
+| R10 | P2 governance | Metadata said concept stage, homepage/topics were empty, Projects was disabled, and the existing Main ruleset was disabled. Connector admin scope was insufficient. | Resolved via permitted browser fallback: metadata, malware alerts, Actions restrictions, linked delivery board and active main ruleset applied. Existing security controls verified; full settings recorded in repository-settings.json/md. |
+
+P1 means fix before merge when it is a reproducible defect (R1), or satisfy before
+making the corresponding release/compatibility claim (R8/R9). P2 items are
+correctness, resilience or explicit follow-up decisions. No self-approval is given.
+
+## Architecture and test observations
+
+- State aggregation is deterministic and provider-namespaced. Error retention and
+ late-event handling have tests; receipt timestamps and bounded retention still
+ need a documented operating policy (#5). A static dashboard is not a live one (#7).
+- Native protection uses DPAPI or AES-GCM with native-vault keys. Link listing
+ does not print tokens. Same-user IPC does not defend against compromised local
+ user processes. No paid provider API or conversation transcript access is needed.
+- LED envelope validation is intentionally separate from parser simulation and
+ physical firmware acknowledgement. Upstream assets are attributed to a pinned
+ revision. A golden conformance corpus is still missing (#2).
+- Hook tests verify merging/ownership/backup behavior and generated wrappers.
+ Provider versions, event payload drift and real trust prompts need manual checks.
+- Shell command export has quoting tests; Unix PTY smoke covers menus/editor.
+ Windows keyboard/clipboard and narrow-terminal usability remain manual checks.
+ JSON conventions vary across commands/states; audit before promising a stable
+ external schema (#7). Runtime errors belong on stderr.
+- Updates reject unsupported runtimes, missing checksums, corruption, traversal,
+ links and manifest mismatches. Installation replacement is two renames, not a
+ crash-proof filesystem transaction. Backups/manual recovery remain necessary.
+ Hashes from the same publisher are not independent signature verification.
+- Release uses tested native CI and draft-first assets/checksums. Only the publish
+ job has contents write. Wiki/upstream workflows execute from the default branch.
+ No pull_request_target execution or permanent token was introduced.
+
+## Validation record
+
+- New regression tests first reproduced R1/R3/R4 on the baseline; R2 was confirmed
+ by reviewing ResponseHeadersRead lifetime and a stalled-body regression; R5 has
+ shared/dedicated-provider regressions.
+- Local Release suite: **96 passed**, 0 failed, 0 skipped. Native vault checks are
+ opt-in and were not enabled locally. Local host listeners are blocked by this
+ environment; native host checks require CI.
+- `dotnet list package --vulnerable --include-transitive --no-restore --format json`
+ reported no vulnerable packages in all three projects at review time. This is
+ an advisory snapshot, not a permanent assurance or a license audit.
+- Baseline [native CI](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280)
+ passed 90 tests per OS, native vaults, simulated transports, host/provider
+ wrappers and self-contained helper replacement/rollback. Those results precede
+ these fixes. Native executed architectures: Windows x64, Linux x64, macOS ARM64;
+ the other three packages were cross-built, not executed.
+- Review-fix [native CI](https://github.com/Anheledir/SidePulse.NET/actions/runs/40039097045)
+ passed **96 tests on each OS**, including native updater replacement/rollback.
+ Quality and dependency review passed. Initial CodeQL scans executed successfully,
+ but the combined CodeQL check failed with one high-severity `cs/zipslip` alert;
+ a successful analysis job alone is not a clean security result.
+- Canonical containment hardening and additional archive cases are a subsequent
+ change. The local Release suite now passes **104 tests**, including both archive
+ formats and sibling-directory traversal cases. Its native tests/security results
+ passed in [native CI](https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767890):
+ **104 tests on each OS**, with updater replacement/rollback. The
+ [security rerun](https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767819)
+ passed C#/Python/Actions analysis and dependency review; the combined CodeQL
+ check reports no new alerts. No scanner finding was suppressed or dismissed.
+ These results apply to `f1ada51`; the following audit-record commit changes
+ documentation only. Always check the PR head's required checks before merging.
+
+## Issue disposition
+
+#1 is completed because the maintainer already approved the concept and later
+explicitly requested implementation/cross-platform support. ADRs now reflect
+that decision. #2 through #11 stay open with implemented items, test evidence,
+remaining acceptance criteria and priority. #3/#10 titles now reflect all three
+platforms. `docs/backlog.json` mirrors the reviewed issue descriptions; it is a
+snapshot, not an automatic issue-state synchronizer.
+
+See [repository settings](../repository-settings.md) for effective configuration,
+applied controls, verification limits and the linked delivery project.
diff --git a/docs/wiki/Agent-Integrations.md b/docs/wiki/Agent-Integrations.md
new file mode 100644
index 0000000..b5abc7e
--- /dev/null
+++ b/docs/wiki/Agent-Integrations.md
@@ -0,0 +1,104 @@
+# Agent integrations
+
+The preview supports Copilot CLI, current local Codex lifecycle hooks, Claude Code
+and Kiro CLI V3 standalone hooks. They feed one current-user host and share the
+same status reducer. Provider IDs namespace sessions, so equal session IDs from
+different tools cannot collide. `agents list --json` reports supported events
+and limitations. Unknown providers/events are not guessed from terminal text.
+
+## Setup, inspection and removal
+
+```shell
+sidepulse-net agents list
+sidepulse-net agents install copilot --dry-run
+sidepulse-net agents install copilot
+sidepulse-net agents install codex
+sidepulse-net agents install claude
+sidepulse-net agents install kiro
+sidepulse-net agents status claude --json
+sidepulse-net agents uninstall claude --dry-run
+sidepulse-net agents uninstall claude
+```
+
+Run the published executable, or supply its absolute path with `--exe`.
+Install defaults to the provider's user configuration. Use `--config ` for
+an explicitly chosen project-scoped or isolated provider file. This is a file
+path, not a directory. Do not register the same integration at user and project
+scope unless duplicate events are intended.
+
+| Provider | Default file | Integration boundary |
+|---|---|---|
+| Copilot CLI | `$COPILOT_HOME/hooks/sidepulse-net.json` or `~/.copilot/hooks/sidepulse-net.json` | Dedicated version-1 hook file; Bash and PowerShell wrappers |
+| Codex | `$CODEX_HOME/hooks.json` or `~/.codex/hooks.json` | Merge lifecycle groups into the hooks object |
+| Claude Code | `~/.claude/settings.json` | Merge lifecycle groups while preserving unrelated settings |
+| Kiro CLI V3 | `~/.kiro/hooks/sidepulse-net.json` | Dedicated version-v1 standalone hook document |
+
+Installation is explicit. Dry runs show only the new managed fragment and target,
+never the rest of an existing settings file. Shared settings are backed up byte
+for byte before being updated. Backups have a `.bak` suffix so agents do not load
+them as hook files. SidePulse.NET stores a separate installation manifest with
+before/after hashes. Repeated installation is idempotent; uninstall then install
+to change the executable path or generated hook definitions.
+
+Uninstall restores the exact original file, or removes a dedicated file created
+by SidePulse.NET. It refuses to overwrite files edited after installation or to
+restore a missing/modified backup. Review and merge those cases manually. A
+pending installation interrupted before its target write can be removed safely.
+Backups remain available after removal. Do not delete them before uninstalling.
+Malformed JSON, unsupported hook shapes and unowned dedicated files are refused.
+The installer preserves permission settings and never approves tools, bypasses
+trust, or edits agent instructions. Restart the agent after installing/removing.
+Codex requires reviewing the new definitions in `/hooks` before they execute.
+
+## State mapping
+
+Prompt submission and tool activity indicate working; explicit root turn-stop
+signals indicate done. Codex approval requests and supported Claude/Copilot input
+notifications indicate waiting. Claude tool/turn failures and Copilot error
+signals indicate error. Codex interrupt and session-end events indicate idle.
+Kiro exposes working, idle and completed-turn signals in this adapter; no general
+permission-wait or error event is inferred. Tool failure does not automatically
+mean the entire task failed, and done does not establish correctness.
+
+Subagent and background completion events never finish root sessions. Child-agent
+payloads with an explicit `agent_id` are ignored by the root adapter. A session
+start caused by compaction does not clear active root work. Waiting wins over
+working, then unhandled errors, completed turns and idle. A stop after an error
+preserves that error until activity resumes or the session ends.
+
+Copilot uses its documented event timestamp. Other adapters use ingestion time
+because their common payloads do not guarantee timestamps. Concurrent hooks may
+arrive out of order. There is no transcript parsing, prompt classification or
+account/API access. Missing session identities are ignored rather than combining
+unrelated activity under a placeholder. The IPC message contains only provider,
+session identity, state and timestamp; prompt and tool contents are discarded.
+
+Generated wrappers are silent and return zero on runtime failures. Hook commands
+have bounded input and connection budgets. Windows command-only provider formats
+use a PowerShell 7 encoded command to avoid parent-shell quoting ambiguities;
+Copilot includes its native PowerShell field. Unix uses quoted shell commands.
+These are passive status hooks: their output never contains policy decisions.
+
+## Validation and limits
+
+Tests cover representative documented payloads, each provider's configuration
+shape, mixed-provider sessions, configuration preservation and generated command
+execution through Bash or PowerShell. CI uses synthetic events and no paid agent
+accounts. Actual agent installations still need manual checks, especially hooks
+that other plugins can delay or continue. A Stop hook can run before another hook
+requests continuation; subsequent activity returns the signal to working.
+
+Kiro CLI 2.x agent profiles, legacy Codex notification-only releases, remote/cloud
+agent orchestration and other providers (Cursor, Gemini CLI, Grok, Junie, etc.)
+remain separate adapters to implement and verify. The adapter registry and common
+installer are intended to make those additions straightforward.
+
+## Protocol references
+
+Checked 2026-10-23:
+
+- [Copilot hook reference](https://docs.github.com/en/copilot/reference/hooks-reference)
+- [Codex lifecycle hooks](https://developers.openai.com/codex/hooks)
+- [Claude Code hooks](https://code.claude.com/docs/en/hooks)
+- [Kiro standalone schema](https://kiro.dev/docs/hooks/)
+- [Kiro triggers and session identity](https://kiro.dev/docs/hooks/types/)
diff --git a/docs/wiki/Animations.md b/docs/wiki/Animations.md
new file mode 100644
index 0000000..b60a2f0
--- /dev/null
+++ b/docs/wiki/Animations.md
@@ -0,0 +1,66 @@
+# Animations and custom patterns
+
+SidePulse Dot (USB-C) has two LEDs; SidePulse Pro (SD slot) has eight. Both use
+upstream `LEDS.LED` syntax. Named patterns select a model-specific variant. Preview
+defaults to Dot; apply detects a known mounted model or requires `--model`. Phone
+output requires an explicit model. File transport still requires writable storage;
+this feature does not add direct USB or SD read transports.
+
+```sh
+sidepulse-net animations list
+sidepulse-net animations preview cyan-roll --model dot
+sidepulse-net animations preview --file custom.LED --model pro
+sidepulse-net animations preview --file custom.LED --both
+sidepulse-net animations validate custom.LED --quiet
+sidepulse-net animations edit --file custom.LED --model dot
+sidepulse-net animations import personal --file custom.LED --model dot
+sidepulse-net animations export personal --model dot --output exported.LED
+sidepulse-net animations apply personal --model dot --phone default --brightness 40
+```
+
+The editor supports guided color, per-LED color/hold, off, roll, brightness,
+duration, easing, delay, raw line editing and repeat settings. Preview with Space
+(pause), Right (advance 100ms), R (restart) and Escape (back). Save before leaving;
+unsaved changes can be discarded explicitly. Existing files are replaced only if
+they have not changed since opening. Import/export refuse replacement unless
+`--force` is supplied. Built-ins cannot be overwritten; choose a custom name.
+Custom files are stored separately for Dot and Pro. Import both variants under the
+same name when their layouts differ. Names use lowercase letters, digits, `_`, `-`.
+
+The managed interpreter validates colors, indexes, duration/delay (up to 65535ms),
+brightness 0..255, easing names, roll, finite/infinite repeats and the firmware's
+512 UTF-8 byte / 20 physical line envelope. Indexed assignments preserve other
+LEDs. A single color fills the strip; a color list clears trailing LEDs. Valid
+out-of-range LEDs are ignored. Comments begin with `;`, `//` or `# `.
+
+Preview is entirely Spectre.Console text and colored blocks. It starts from black;
+hardware may retain previous colors. Terminal colors, refresh rate, easing curves
+and rounding are approximations and have not been validated against firmware.
+Preview does not establish device receipt. `--both` compares the model-specific variants of named patterns, or plays the
+same custom file on both layouts.
+Brightness percent scales program brightness; an additional directive consumes
+one physical line, so a program at the envelope limit may need shortening.
+
+Non-interactive preview emits one frame and exits immediately. `--at 500` selects
+its time in milliseconds; `--json` emits model, timestamp and RGB values. Interactive
+preview runs for 10 seconds by default; `--seconds` permits up to 600 seconds.
+
+## Agent state profiles
+
+```sh
+sidepulse-net profiles set personal --state Working --pattern cyan-roll --brightness 40
+sidepulse-net profiles set personal --state Waiting --pattern amber-pulse
+sidepulse-net profiles show personal --json
+sidepulse-net host start --phone default --profile personal --model dot
+```
+
+Unassigned states retain the original status patterns. Profile brightness applies
+to all states. Profiles are loaded at host startup; restart the host after edits.
+Every referenced pattern must have a variant for the selected model. Existing
+running hosts retain their startup configuration; stop first to apply changes.
+
+## Upstream credit
+
+Bundled patterns are copied from `inteliwear/sidepulse` at the revision in
+`upstream.json`, under its MIT license. See [[Upstream-and-Licensing]]. The managed
+interpreter is a new implementation from the public format specification.
diff --git a/docs/wiki/Architecture.md b/docs/wiki/Architecture.md
index b21607b..17b1e95 100644
--- a/docs/wiki/Architecture.md
+++ b/docs/wiki/Architecture.md
@@ -1,6 +1,8 @@
# Architecture
-Status: proposed; no application components have been implemented.
+Status: implemented preview boundaries plus explicit future decisions. The solution
+contains Core and CLI projects, with foreground/detached host commands and
+current-user IPC. See [[Getting-Started]] and the PR #12 review for limitations.
## Boundaries
@@ -13,9 +15,13 @@ Status: proposed; no application components have been implemented.
| CLI | Spectre.Console.Cli commands and Spectre.Console presentation |
| Tests | Reducer, protocol, adapter contracts, rendered output and hardware smoke checks |
-The UI never owns device transport state. All writers submit intents to one host,
-so a background service, dashboard and hook cannot independently overwrite LEDs.
-A foreground-only mode should be possible for diagnosis and restricted machines.
+Hook-driven output is serialized by the host. Direct `state`, `write` and animation
+apply commands send independently and can overwrite a running host's pattern.
+They are explicit one-shot operations, not clients of a global output arbiter.
+Stop the host before manual device checks. Coordinating direct writers with a
+running host remains a decision in #5; do not claim exclusive device ownership.
+The Application/Transports rows describe logical responsibilities, not additional
+projects; migration, relay and persistence in this table are future work.
## Events and aggregation
@@ -24,21 +30,23 @@ last observation. Use explicit lifecycle events and ignore out-of-order events.
A finished subagent does not finish its parent session. Cancellation, agent errors,
recoverable tool errors and loss of observation remain distinguishable.
-Proposed aggregation: waiting for user input takes priority, followed by active
+Implemented aggregation: waiting for user input takes priority, followed by active
work; show unhandled errors when nothing is actively working; completion only
when no tracked session remains active. Idle and unknown are separate states.
-The exact policy is a design decision to validate with realistic event traces.
+Tests cover the reducer; validate the policy further with real provider traces.
## Local event path
Hook adapters enqueue minimal metadata and return quickly. The host handles
-network I/O, deduplication, bounded retries and transport diagnostics asynchronously.
+network I/O asynchronously through a bounded latest-state queue. Repeated events
+can retry delivery; there is no durable retry queue or separate event deduplication.
On Windows use current-user-restricted named pipes; do not open a network listener
just to receive local hook events. Document protocol versioning and startup races.
## Failure and restart behavior
-Persist enough metadata for restart recovery without storing prompts or tool
-arguments. After restart, stale work becomes unknown until refreshed by evidence.
-Do not infer successful completion from an expired heartbeat. Use bounded queues
-and expose dropped events or undelivered outputs in diagnostics.
+Restart currently begins Unknown with an empty session table; no session metadata
+is persisted. Do not infer successful completion from an expired heartbeat.
+Protocol negotiation, restart metadata and session retention are tracked in #5.
+The output queue is bounded and can drop older states while keeping the latest.
+Undelivered output is logged, but there is no per-session delivery history.
diff --git a/docs/wiki/Compatibility.md b/docs/wiki/Compatibility.md
index a9dc3c6..c506f60 100644
--- a/docs/wiki/Compatibility.md
+++ b/docs/wiki/Compatibility.md
@@ -2,18 +2,24 @@
Reference: inteliwear/sidepulse at
[ffb1d3c2f3eed3b7e80e32d7876a7e1d67bd5dfb](https://github.com/inteliwear/sidepulse/commit/ffb1d3c2f3eed3b7e80e32d7876a7e1d67bd5dfb),
-checked 2026-10-23. Every .NET row below is **planned**, not implemented.
+checked 2026-10-23. The inventory below records the full planned scope. The preview already implements
+firmware size limits, writable USB files, iPhone pairing/silent delivery, status
+profiles, Copilot hooks, in-memory session aggregation and native credential
+storage. Full LED grammar, visible notifications, broadcast and remaining
+integrations remain planned. See [[Getting-Started]] and [[Platforms]] for
+implemented commands and test boundaries.
| Area | .NET plan | Verification required |
|---|---|---|
| LED text language and limits | M1 | Port upstream vectors, escapes, 512-byte/20-line boundaries |
-| Writable USB volumes and discovery | M1 Windows | Dot hardware, volume labels, locked/removed media |
+| Writable USB volumes and discovery | Preview, all three OSes | Dot hardware, volume labels, locked/removed media |
| iPhone QR/token pairing and linked targets | M1 | Original app, production/development tokens, persistence |
| LED bridge delivery and visible notifications | M1 | Silent versus visible delivery, timeouts and failure semantics |
| Destination selection, stdin and broadcast | M1 | Compatible ambiguity checks and explicit broadcast |
| Built-in animations and LED counts | M1 | Source attribution, Dot/Pro geometry and brightness |
-| Copilot CLI hooks | M1 extension | Event payload fixtures and real Windows CLI |
-| Codex, Claude, Cursor, Grok, Junie | M2 parity | Separate hook schemas, installation and permissions per provider |
+| Copilot CLI hooks | Preview, Bash and PowerShell | Event fixtures and real CLI on each OS |
+| Codex, Claude Code, Kiro CLI V3 | Preview | Native schema fixtures and simulated wrapper execution; real agent checks pending |
+| Cursor, Grok, Junie and other providers | M2 parity | Separate hooks and manual verification |
| Session collection, history and aggregation | M1/M2 | Concurrent sessions, stale events and restart |
| Optional transcript recovery | M2 investigation | Privacy, format drift and opt-in behavior |
| Background host and service management | M1 Windows | Named-pipe access, foreground mode and login startup |
diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md
index 1d2a93b..9d80c42 100644
--- a/docs/wiki/Configuration.md
+++ b/docs/wiki/Configuration.md
@@ -1,3 +1,7 @@
+> Implementation update: Links use native credentials: Windows DPAPI, macOS Keychain or Linux Secret Service.
+> Alias/default management and the `SIDEPULSE_NET_HOME` override are implemented.
+> See [[Getting-Started]] for working commands. The remainder describes the target configuration design.
+
# Configuration and coexistence
Status: proposed.
diff --git a/docs/wiki/Devices-and-Protocols.md b/docs/wiki/Devices-and-Protocols.md
index 23dc9e8..53b96ae 100644
--- a/docs/wiki/Devices-and-Protocols.md
+++ b/docs/wiki/Devices-and-Protocols.md
@@ -1,3 +1,7 @@
+> Implementation update: QR/SSE pairing for the default iPhone bridge and encrypted
+> native link storage are implemented on Windows, macOS and Linux. Android and custom bridge origins remain planned.
+> Hardware and TestFlight app verification are still pending. See [[Getting-Started]].
+
# Devices and protocols
## Local hardware
diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md
new file mode 100644
index 0000000..9d13fcd
--- /dev/null
+++ b/docs/wiki/Getting-Started.md
@@ -0,0 +1,189 @@
+> Shared background host commands and managed setup for Codex, Claude Code, Kiro
+> and Copilot are now implemented. See [[Host-Management]] and [[Agent-Integrations]].
+> The manual Copilot hook generation below remains available for existing users.
+
+# Getting started with the implementation preview
+
+The first implementation is an alpha preview. USB discovery/writes, status profiles,
+raw programs, silent iPhone bridge delivery with an existing APNS token, session
+aggregation, QR pairing, native protected phone links, diagnostics and a foreground
+Copilot CLI host are implemented. Background-service installation, full LED grammar validation,
+animation rendering, migration and remaining agent integrations remain planned.
+
+## Build and run
+
+Install the .NET 10 SDK, then:
+
+```shell
+dotnet build -c Release
+dotnet test -c Release
+dotnet run --project src/SidePulse.Cli -- dashboard
+dotnet run --project src/SidePulse.Cli -- state working --dry-run --json
+```
+
+Publish a Windows application without a Python or .NET runtime requirement:
+
+```shell
+dotnet publish src/SidePulse.Cli -c Release -r win-x64 --self-contained true -o artifacts/win-x64
+```
+
+Run `artifacts/win-x64/sidepulse-net.exe`. For macOS or Linux, replace `win-x64`
+with the desired runtime identifier and run `./sidepulse-net`. CI publishes
+archives for `win-x64`, `win-arm64`, `osx-x64`, `osx-arm64`, `linux-x64` and
+`linux-arm64`. Windows archives use ZIP; Unix archives use tar.gz to retain
+executable permissions. Extract the inner archive after downloading the Actions
+artifact. See [[Platforms]] for prerequisites and validation limits.
+These are unsigned preview builds, not installers or stable releases.
+
+## USB device
+
+```powershell
+sidepulse-net devices --json
+sidepulse-net state working --device E:\
+sidepulse-net write 'off\n#ff9900 1.6s pulse\nrepeat' --escapes --device E:\
+```
+
+An explicit directory must contain `LEDS.LED`; the tool will not create device files
+on unrelated volumes. With no target, exactly one discovered device is selected.
+Only one writer should control a device. Physical device behavior still needs
+Windows hardware verification. Validation checks the 512-byte/20-line envelope;
+the firmware remains responsible for LED syntax validation.
+
+## Pair an iPhone
+
+```powershell
+sidepulse-net link pair iphone
+sidepulse-net link list
+sidepulse-net state done --phone iphone
+sidepulse-net host --phone default
+```
+
+Scan the terminal QR using the SidePulse app's pairing flow. The pairing URI is
+also shown for terminals without ANSI support or enough width. Pairing expires
+after five minutes, supports Ctrl+C cancellation and ignores unrelated or invalid
+registration events. `--timeout 60` shortens the wait; `--no-qr` shows only the URI.
+Treat the live pairing URI as temporary pairing access; keep it out of shared logs.
+Actual QR scanning with the TestFlight app still requires device verification.
+
+The entire link document, including names and tokens, is protected by the native
+credential system. Windows keeps the existing DPAPI format at
+`%LOCALAPPDATA%\SidePulse.NET\links.dpapi`. macOS and Linux encrypt a
+`links.encrypted` file using AES-256-GCM, with a random key held in Keychain or
+Secret Service respectively. The platform's local-application-data directory is
+used unless `SIDEPULSE_NET_HOME` selects another absolute directory.
+
+There is no plaintext fallback. The store uses exclusive locking and atomic
+encrypted replacement, with owner-only permissions for new Unix files. Missing
+keys and unreadable stores are preserved, not reset. Vault keys are scoped to the
+absolute store path; moving a Unix store requires pairing again or restoring its
+original location. Copying the encrypted file alone is not a credential migration.
+The app does not read or modify the Python port's configuration.
+
+macOS needs an unlocked Keychain and access for the executable. Linux needs
+`secret-tool`, an unlocked Secret Service keyring and a working D-Bus session.
+On Debian/Ubuntu, install `libsecret-tools`; desktop sessions commonly provide the
+keyring service. Headless Linux needs its own unlocked Secret Service session, or
+can use environment-token delivery without saved links. See [[Platforms]].
+
+The first linked phone becomes the default. Selection is explicit via `--phone`;
+commands without a phone option continue to discover USB devices.
+
+```powershell
+sidepulse-net link rename iphone personal
+sidepulse-net link default personal
+sidepulse-net link list --json
+sidepulse-net link remove personal
+sidepulse-net doctor --json
+```
+
+Aliases are case-insensitive and use 1–40 letters, digits, underscores or hyphens.
+`default` is reserved. Existing aliases and duplicate tokens are rejected.
+Removing a default link clears the default; it never silently selects another phone.
+Removing a link only removes the local credential, and does not revoke the token
+at the phone or bridge. Listing links and diagnostics never display tokens.
+`doctor` checks local runtime, mounted devices, DPAPI/storage and hook-directory
+presence; it sends no device writes or network requests.
+
+## Existing tokens and other platforms
+
+If you already have an iPhone token, set `SIDEPULSE_TOKEN` in the current process
+environment. Keep the value out of command history, source control and screenshots.
+Save it securely using the native credential vault, or use it directly without persistence:
+
+```powershell
+sidepulse-net link import iphone --token-env SIDEPULSE_TOKEN
+sidepulse-net state working --token-env SIDEPULSE_TOKEN
+sidepulse-net host --token-env SIDEPULSE_TOKEN
+```
+
+Saved links and pairing are available on Windows, macOS and Linux when the native
+credential backend is available. Environment-token delivery needs no persistent
+credential backend. `--device`, `--phone` and
+`--token-env` are mutually exclusive. A dry run previews the program without
+reading credentials or validating that a saved phone exists.
+
+The bridge uses HTTPS and silent APNS payloads with unique event IDs. An HTTP
+success is bridge acceptance, not proof of delivery to the hardware. Android and
+custom bridge servers are not implemented yet. Pairing and delivery follow the
+upstream protocol at the revision in `upstream.json`.
+
+## Copilot CLI
+
+Start the host in a terminal, choosing either USB or the phone environment token:
+
+```powershell
+sidepulse-net host --device E:\
+```
+
+Create the hook directory if needed, then generate a new, separate hook file:
+
+```powershell
+New-Item -ItemType Directory -Force "$env:USERPROFILE\.copilot\hooks" | Out-Null
+sidepulse-net hook-config --exe C:\Tools\SidePulse.NET\sidepulse-net.exe --output "$env:USERPROFILE\.copilot\hooks\sidepulse-net.json"
+```
+
+On macOS/Linux, use:
+
+```bash
+mkdir -p ~/.copilot/hooks
+sidepulse-net hook-config --exe /absolute/path/to/sidepulse-net --output ~/.copilot/hooks/sidepulse-net.json
+sidepulse-net host --phone default
+```
+
+Generated files include both Bash and PowerShell wrappers. Bash inherits JSON
+stdin and always returns zero, including when the executable is unavailable.
+If `COPILOT_HOME` is set, use its `hooks` directory instead. Existing files are never
+overwritten. Restart Copilot CLI after installation. PowerShell 7 is required for
+Copilot's Windows shell hooks. Remove this file and restart Copilot to uninstall.
+Avoid running the Python and C# hook integrations for the same output simultaneously.
+
+Hooks forward stdin to a current-user-only named pipe. They have a short connection
+budget, emit no output and always return zero for runtime input/connection failures.
+The generated PowerShell wrapper also returns zero if the executable is unavailable.
+No prompt, tool arguments or transcript content is forwarded to the host, persisted
+or sent to the bridge. The host accepts bounded messages and sessions; network
+output runs separately through a latest-state queue. Rapid intermediate states may
+be coalesced. If the host is absent or overloaded, hook events may be dropped.
+Start the host before Copilot. Restarted hosts start unknown and do not replay old
+sessions. Crashed/missing sessions are not inferred complete; restart the host to
+clear stale state. Stopping the host leaves the last LED program on the device.
+
+Waiting takes precedence over working, then errors, completed turns and idle.
+Completion is inferred only from `agentStop` with `stopReason=end_turn`, never a
+subagent/background completion or timeout. The host UI appends session tables on
+events; `--plain` provides simple lines and `--json` provides structured snapshots.
+The standalone `dashboard` is a static overview in this preview.
+
+The event mapping follows the [GitHub Copilot hook reference](https://docs.github.com/en/copilot/reference/hooks-reference).
+Actual Copilot/Windows and phone/hardware validation remain separate from unit
+and simulated transport tests. Keep the working Python installation available
+until this preview is validated on your setup.
+
+## Animation studio
+
+See [[Animations]] for Dot/Pro previews, custom editing and agent profiles, and
+[[Scripting-and-Menus]] for interactive command building and quiet/JSON output.
+
+## Updates
+
+See [[Updating]] for GitHub release checks, verified self-update and recovery.
diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md
index b9c73f5..7cd9fa6 100644
--- a/docs/wiki/Home.md
+++ b/docs/wiki/Home.md
@@ -1,9 +1,12 @@
+> Implementation preview: [[Getting-Started]] lists working commands and current limitations. Other pages describe the complete planned product.
+
# SidePulse.NET
**An unofficial .NET companion for SidePulse.**
-This wiki describes the proposed product. Application implementation has not
-started, and no SidePulse.NET binaries are available yet.
+The first implementation preview is available in the source repository and CI
+artifacts. Start with [[Getting-Started]] for working commands and limitations.
+The concept pages describe the intended complete product.
Start with [[Product-Concept]], [[Terminal-Experience]] and [[Roadmap]].
Technical detail lives in [[Architecture]], [[Compatibility]], [[Devices-and-Protocols]],
diff --git a/docs/wiki/Host-Management.md b/docs/wiki/Host-Management.md
new file mode 100644
index 0000000..241775b
--- /dev/null
+++ b/docs/wiki/Host-Management.md
@@ -0,0 +1,66 @@
+# Host management
+
+One shared host collects supported agent events and owns the selected output.
+Start it before starting your agents. It uses current-user IPC, not a network
+listener. The phone token remains in the native credential store or process
+environment; it is never added to command arguments or logs.
+
+```shell
+sidepulse-net host start --phone default
+sidepulse-net host status
+sidepulse-net host status --json
+sidepulse-net host logs --tail 30
+sidepulse-net host stop
+```
+
+Choose a target with `--phone`, `--device` or `--token-env`. `--dry-run` runs the
+host without delivery. `host start` launches a detached process and waits for an
+IPC readiness response. The executable directory is its working directory;
+explicit USB paths are made absolute before starting. Use `--exe` when invoking
+through `dotnet` rather than a published apphost. Starting again reports the
+existing host and does not silently switch its target.
+
+`host status` returns running state, PID, aggregate state and provider-specific
+session snapshots. `host stop` requests shutdown over the same current-user IPC;
+it never blindly kills a PID from a stale file. The host leaves the last LED
+program in place. Stopping does not mark unfinished work complete. Sessions are
+in memory only and begin unknown after restart.
+
+For a foreground session:
+
+```shell
+sidepulse-net host run --phone default
+```
+
+The earlier `sidepulse-net host --phone default` shorthand remains supported.
+Ctrl+C stops the foreground host. Upgrade by stopping the old host before
+replacing binaries; older preview hosts do not implement the control protocol.
+A process started from a terminal is detached on Unix. Windows launches it without
+a console window. Background logs live under `host/host.log` in the SidePulse.NET
+configuration directory, with rotation around 1 MiB and one previous file. Logs
+contain state/count diagnostics, not prompts, tool arguments or credentials.
+`host logs` reads the current log; `.previous` remains available for inspection.
+
+Login startup registration and system service installation are not implemented
+in this preview. `host start` starts a user process for the current login session.
+Linux desktop/Keychain availability can change after logout or keyring locking;
+check `doctor` and the host log if phone output becomes unavailable.
+
+Tests exercise detached start, idempotent start, status snapshots, mixed-provider
+hook delivery and graceful stop. Foreground tests also reject competing hosts
+and verify restart after forced termination. These are simulated device tests,
+not evidence of actual LED or phone receipt.
+
+## Clearing abandoned sessions
+
+`sidepulse-net host reset` clears all tracked sessions and queues the Unknown
+pattern. Use `--json` for a machine-readable snapshot. This explicitly discards
+history; it does not mark tasks successful or stop agent processes. The next agent
+event establishes fresh state. A stopped host returns exit code 1.
+
+IPC messages and host snapshots now carry `ProtocolVersion: 1`. Unknown explicit
+versions are rejected; legacy messages without the field are treated as v1.
+This does not establish compatibility between arbitrary application versions:
+stop the host before upgrades and run matching CLI/host binaries. Restart remains
+Unknown with no restored session history; reset provides explicit recovery from
+abandoned sessions without a timeout inventing successful completion.
diff --git a/docs/wiki/Platforms.md b/docs/wiki/Platforms.md
new file mode 100644
index 0000000..f6e481b
--- /dev/null
+++ b/docs/wiki/Platforms.md
@@ -0,0 +1,52 @@
+# Platform support
+
+The preview supports Windows, macOS and Linux. The core, terminal UI, QR/SSE
+pairing, phone delivery, local host, hook generation and mounted USB file transport
+share one codebase. Native credentials are selected at runtime.
+
+| Platform | Saved phone protection | Requirements | Archives |
+|---|---|---|---|
+| Windows | Current-user DPAPI; existing store format retained | Windows desktop user profile | x64, ARM64 ZIP |
+| macOS | Native SecItem Keychain API holds an AES-256-GCM key | Unlocked Keychain and access for the executable | x64, ARM64 tar.gz |
+| Linux | Secret Service holds an AES-256-GCM key | `secret-tool`, unlocked keyring, D-Bus session; glibc distribution | x64, ARM64 tar.gz |
+
+Linux uses the fixed `/usr/bin/secret-tool` or `/bin/secret-tool` helper without a
+shell. Encryption keys pass through stdin/stdout, never command arguments. The
+helper has a bounded timeout. macOS calls Security/CoreFoundation directly and
+fails with a useful error if Keychain access cannot proceed without a prompt.
+Unlock the login Keychain and grant application access before starting the host.
+There is no plaintext key file or fallback to unprotected persistence.
+
+A key is stored per absolute configuration path. Removing a phone removes the
+local link, not the native encryption key or the remote registration. A missing
+vault key does not cause replacement of an existing encrypted store. New Unix
+store and lock files have owner-only permissions. Existing Windows DPAPI stores
+continue to use `links.dpapi`; Unix stores use `links.encrypted`.
+
+The CLI's `doctor` command reports backend availability and checks an existing
+store. It does not create an encryption key or prove that an absent store can be
+created in a locked vault. `--token-env` remains available on headless machines
+without a credential service. No root/admin access is required by the application;
+the user must have write permission for the mounted device and config directory.
+
+## Tests and distribution
+
+CI runs builds, behavioral tests and simulated USB/host/CLI checks on Windows,
+Linux and macOS. Linux CI provisions an isolated D-Bus/keyring session; macOS CI
+creates and deletes a temporary Keychain. Native encryption and phone management
+are exercised on all three. Bash hook commands are executed on Unix runners. Host tests reject competing
+instances and verify restart after forced termination. Unix IPC uses a short
+per-user private directory, an exclusive host lease and current-user-only sockets.
+
+Each platform produces x64 and ARM64 archives. CI executes the archive matching
+its runner architecture; the other architecture is cross-published. This does
+not establish hardware verification for every architecture. Alpine/musl,
+32-bit systems, macOS notarization, signed Windows installers and OS service
+installation are not included in this preview.
+
+USB discovery uses mounted drives and the existing `LEDS.LED` file. Explicit
+`--device` paths work when autodiscovery cannot find a mount. On macOS use a
+mounted path such as `/Volumes/SidePulseDot`; on Linux use its actual mount path,
+for example `/media/$USER/SidePulseDot`. Do not run two writers for one device.
+Actual hardware, TestFlight scans and real Copilot installations still require
+manual verification on each target OS.
diff --git a/docs/wiki/Product-Concept.md b/docs/wiki/Product-Concept.md
index 1086c46..d71b7fc 100644
--- a/docs/wiki/Product-Concept.md
+++ b/docs/wiki/Product-Concept.md
@@ -15,7 +15,7 @@ A background host coordinates sessions and outputs.
## First milestone
-Windows-native, self-contained distribution; direct writable USB devices; iPhone
+Self-contained Windows, macOS and Linux distributions; direct writable USB devices; iPhone
pairing and bridge delivery; core LED language; manual state commands; Copilot CLI
integration; a device/session dashboard; and diagnostics.
diff --git a/docs/wiki/Project-Setup.md b/docs/wiki/Project-Setup.md
index 0172333..0293e33 100644
--- a/docs/wiki/Project-Setup.md
+++ b/docs/wiki/Project-Setup.md
@@ -11,6 +11,7 @@ The repository and wiki are public and use the MIT license.
| .NET CI | Restore, build and test a root solution on Windows, Linux and macOS |
| Wiki sync | Publish reviewed docs/wiki pages on the default branch |
| Upstream watch | Check upstream every Monday at 07:17 UTC and on manual dispatch |
+| Security | CodeQL for C#, Python and Actions; PR dependency review blocks new high/critical advisories |
| Dependabot | Propose weekly dependency updates |
Actions are pinned to upstream commit SHAs. Permissions are read-only by default.
@@ -38,3 +39,22 @@ The workflow uses the built-in Actions token with `issues: write`. No extra toke
external service or personal reminder is required. GitHub schedules may be delayed;
use **Actions → Upstream watch → Run workflow** for an immediate check. Public
repositories with no activity may have scheduled workflows disabled by GitHub.
+
+## Security and repository administration
+
+[SECURITY.md](https://github.com/Anheledir/SidePulse.NET/blob/main/SECURITY.md)
+explains private reporting and trust boundaries. The
+[configuration record](https://github.com/Anheledir/SidePulse.NET/blob/main/docs/repository-settings.md)
+separates observed settings, source configuration and desired admin changes.
+Adding a workflow does not prove that repository-level security controls are on.
+
+## Delivery tracking and protection
+
+The [delivery board](https://github.com/users/Anheledir/projects/5/views/1) is a
+private owner project linked to the repository. Todo, In Progress, Validation and
+Done separate unfinished code from outstanding compatibility evidence. All issues
+and PR #12 are represented. The active Main delivery checks ruleset requires PRs,
+resolved conversations, current native/security checks and blocks force-push and
+deletion. The combined CodeQL alert check is required in addition to scan jobs.
+The configuration record includes exact applied settings and observed existing
+controls, verified 2026-10-24.
diff --git a/docs/wiki/Roadmap.md b/docs/wiki/Roadmap.md
index 8831de2..df35e26 100644
--- a/docs/wiki/Roadmap.md
+++ b/docs/wiki/Roadmap.md
@@ -1,7 +1,11 @@
# Roadmap
-All application work is planned. Only the initial documentation and automation
-scaffolding are prepared.
+The implementation preview now includes USB file output, protected phone links,
+four agent integrations, a background host, Dot/Pro patterns, a managed animation
+interpreter, Spectre previews and custom editing, profiles, menus and script output.
+See [[Getting-Started]], [[Animations]] and [[Scripting-and-Menus]]. Native CI checks
+are distinct from actual hardware/provider verification, which remains pending.
+The milestone descriptions below retain broader acceptance targets.
## M0: Concept and project foundation
diff --git a/docs/wiki/Scripting-and-Menus.md b/docs/wiki/Scripting-and-Menus.md
new file mode 100644
index 0000000..05c647a
--- /dev/null
+++ b/docs/wiki/Scripting-and-Menus.md
@@ -0,0 +1,57 @@
+# Scripting and interactive menus
+
+In a terminal, `sidepulse-net` opens an arrow-key menu. Bare groups `animations`,
+`profiles`, `agents`, `host`, `link`, and `about` open their respective menus.
+Up/Down select, Enter continues, Escape goes back. Fully specified commands always
+execute directly. The legacy `host --phone default` shorthand remains supported.
+
+Guided actions display a single-line script command before running. Review offers
+Run, Copy command, Choose shell and Back. PowerShell and Bash quoting preserve
+literal values; CMD export rejects values it cannot safely represent. Clipboard
+support uses the OS clipboard or installed `wl-copy` / `xclip`; otherwise copy the
+printed line. Secrets are represented by phone aliases or environment variable
+names, never token values. Editor commands reference the selected file; save it
+before using a preview command elsewhere.
+
+Menus require both stdin and stdout to be terminals. Redirecting either stream,
+passing `--no-interactive`, `--quiet`, or `--json` prevents menus. Bare groups then
+show command help. No arguments show help. Missing required arguments fail without
+prompting. Editors require a terminal. QR pairing remains an explicit pairing
+operation with its existing timeout; it is not a script configuration wizard.
+
+Global flags may precede or follow subcommands:
+
+- `--quiet`: suppress stdout, preserve stderr and exit status.
+- `--json`: structured output on commands advertising JSON. Takes precedence over
+ quiet. Runtime errors are JSON on stderr, never mixed with stdout data.
+- `--no-interactive`: disable cursor menus and interactive playback.
+- `--no-color`: disable ANSI colors. `NO_COLOR` and redirected stdout also disable
+ color. A non-interactive preview prints a single RGB frame instead of animating.
+
+Exit 0 indicates successful command execution, 1 indicates an error. Delivery
+success means the OS or bridge accepted the write, not hardware acknowledgement.
+Raw `write` retains envelope-only validation for forward compatibility; use
+`animations validate` for grammar validation. Global flags are reserved before
+`--`; literal values containing a flag should be passed after `--` where supported.
+
+```sh
+sidepulse-net animations validate --file build.LED --quiet
+sidepulse-net animations preview --file build.LED --model dot --at 500 --json
+sidepulse-net state Working --phone default --quiet
+sidepulse-net devices --json
+sidepulse-net about credits --json
+sidepulse-net about licenses --full
+sidepulse-net about github
+sidepulse-net about github --open
+sidepulse-net docs --offline
+```
+
+`about` includes manufacturer, project and upstream links, credits, dependency
+versions, license identifiers, and offline license texts. Browser launch is opt-in
+through `--open`. Offline animation/scripting documentation ships with previews.
+The public wiki receives these pages after the implementation branch is merged.
+
+The manufacturer's affiliate program currently requires individual approval. The
+application uses ordinary manufacturer URLs; no referral identifier is fabricated.
+An approved affiliate link would require clear disclosure next to it. See the
+[official program](https://sidepulse.io/affiliates.html).
diff --git a/docs/wiki/Updating.md b/docs/wiki/Updating.md
new file mode 100644
index 0000000..8857c8f
--- /dev/null
+++ b/docs/wiki/Updating.md
@@ -0,0 +1,77 @@
+# Checking and installing updates
+
+```sh
+sidepulse-net update
+sidepulse-net update check --json
+sidepulse-net update check --prerelease
+sidepulse-net update install --prerelease --dry-run
+sidepulse-net host stop
+sidepulse-net update install --prerelease
+sidepulse-net update status --json
+sidepulse-net host start --phone default
+```
+
+A bare `update` checks only in scripts; in a terminal it offers a cursor menu.
+Checks use GitHub public releases without an account/token. Stable releases are
+the default. `--prerelease` includes published prereleases and selects the highest
+semantic version. Drafts, tags without releases and Actions artifacts are excluded.
+A prerelease lookup is bounded to 1,000 releases; rate limits fail with a concise
+error. Equal/older versions never downgrade an installation. Missing release assets
+or checksums prevent installation. No published release is a normal check result.
+
+Installation is explicit. The updater chooses the current process architecture
+(x64/ARM64), downloads the matching ZIP/tar.gz and `SHA256SUMS`, verifies SHA-256
+before extraction and additionally checks GitHub asset digests when supplied.
+It verifies a version/runtime/file-hash manifest and rejects archive traversal,
+links, duplicate files, special entries and excessive sizes. Checksums establish
+integrity against the published release metadata; they are not independent code
+signatures or protection against a compromised publisher account.
+
+## Replacement and recovery
+
+Self-update requires a self-contained distribution containing `sidepulse-install.json`.
+Source builds, framework-dependent binaries, older previews without that manifest,
+modified application files and symlinked installations require manual installation.
+The first updater-capable preview is 0.1.0-alpha.6. Older versions must be upgraded
+manually once. The install directory and its parent must be writable; the updater
+never elevates privileges. Package-manager installations should use that manager.
+
+Run the command from outside the installation directory. Stop the agent host and
+other processes using the installation first. The updater
+does not kill processes or change startup registration. Downloading/staging leaves
+the current installation intact. A helper copied outside the installation waits
+for the calling process to exit, replaces the whole application directory, and
+runs the new executable's version check. A failed replacement/probe attempts to
+restore the original directory. A per-installation lock prevents concurrent swaps.
+
+`update install` returning success means **scheduled**, not already installed.
+Run `update status` after it exits; wait for `installed` before restarting the host
+with its previous target/profile options. Failure/recovery states return exit 1.
+The JSON receipt includes target, backup, workspace and state. If interrupted,
+status may remain scheduled/applying. Inspect those paths before manual recovery;
+never delete the only intact backup. Updating is not a crash-atomic transaction
+across the two directory renames. A power failure between them may require restoring
+the backup directory manually before the CLI can run again.
+
+Unknown user-added files are copied into the new directory unless they collide
+with a new application-owned file. Existing directory access permissions and access
+permissions on user-added files are preserved. Avoid editing the installation
+during updating.
+Phone links, profiles and hooks normally live outside it and are not changed.
+The complete old installation and temporary download/helper workspace are retained
+for recovery. Once installation is confirmed and no helper is running, these
+paths may be removed manually to reclaim space. Failed updates preserve evidence.
+
+## Publishing
+
+The Release workflow runs on `vVERSION` tags or manual dispatch on such a tag.
+The tag must match the project version. It reuses all three native CI jobs and
+self-contained smoke checks, collects all six archives, writes `SHA256SUMS`, uploads
+a draft release and only then publishes it. Hyphenated versions are prereleases.
+No release or tag is created simply by adding this workflow to a branch. Existing
+release tags are not overwritten. Review the release notes/assets after publishing.
+
+`update status --json` always exposes the same lower-camel-case fields: `state`,
+`version`, `target`, `backup`, `workspace`, `error`, and `receipt`. Missing values
+are null; no receipt gives state `none`. Scripts should inspect `state` rather
+than infer completion from an install command returning successfully.
diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md
index 0b57584..73f1d81 100644
--- a/docs/wiki/_Sidebar.md
+++ b/docs/wiki/_Sidebar.md
@@ -11,3 +11,15 @@
- [[Roadmap]]
- [[Project-Setup]]
- [[Upstream-and-Licensing]]
+
+- [[Getting started|Getting-Started]]
+
+- [[Platforms]]
+
+- [[Agent integrations|Agent-Integrations]]
+- [[Host management|Host-Management]]
+
+- [[Animations]]
+- [[Scripting and menus|Scripting-and-Menus]]
+
+- [[Updating]]
diff --git a/global.json b/global.json
new file mode 100644
index 0000000..ebd0c5d
--- /dev/null
+++ b/global.json
@@ -0,0 +1,3 @@
+{
+ "sdk": { "version": "10.0.100", "rollForward": "latestFeature" }
+}
diff --git a/scripts/agent_smoke.py b/scripts/agent_smoke.py
new file mode 100644
index 0000000..e9a825d
--- /dev/null
+++ b/scripts/agent_smoke.py
@@ -0,0 +1,122 @@
+"""Exercise native generated wrappers, owned hook setup and detached host control, without agent accounts."""
+import json
+import os
+from pathlib import Path
+import shlex
+import subprocess
+import sys
+import tempfile
+import time
+
+
+def main():
+ exe = str(Path(sys.argv[1]).resolve())
+ with tempfile.TemporaryDirectory(prefix="SidePulse agents ü ") as directory:
+ root = Path(directory)
+ env = os.environ.copy()
+ env['SIDEPULSE_NET_HOME'] = str(root / 'state')
+
+ def run(*args, timeout=15):
+ result = subprocess.run([exe, *args], text=True, capture_output=True, timeout=timeout, env=env)
+ assert result.returncode == 0, (args, result.stdout, result.stderr)
+ return result.stdout
+
+ def status():
+ return json.loads(run('host', 'status', '--json'))
+
+ target = root / 'LEDS.LED'
+ target.write_text('off')
+ configs = {}
+ originals = {}
+ for provider in ('copilot', 'codex', 'claude', 'kiro'):
+ path = root / (provider + '.json')
+ original = '{"unrelated":"private-config-key","hooks":{}}\n' if provider in ('codex', 'claude') else None
+ if original:
+ path.write_text(original)
+ originals[provider] = original
+ preview = run('agents', 'install', provider, '--exe', exe, '--config', str(path), '--dry-run', '--json')
+ assert 'private-config-key' not in preview
+ assert (path.read_text() if path.exists() else None) == original
+ run('agents', 'install', provider, '--exe', exe, '--config', str(path))
+ assert json.loads(run('agents', 'status', provider, '--config', str(path), '--json'))['State'] == 'installed'
+ configs[provider] = (path, json.loads(path.read_text()))
+
+ pattern = root / 'working.LED'
+ pattern.write_text('off\n#123456\n')
+ run('animations', 'import', 'smoke-working', '--file', str(pattern), '--model', 'dot', '--quiet')
+ run('profiles', 'set', 'smoke', '--state', 'Working', '--pattern', 'smoke-working', '--brightness', '40', '--quiet')
+ print("Agent setup/preview checks passed; starting detached host.", flush=True)
+ started = False
+ try:
+ first = json.loads(run('host', 'start', '--exe', exe, '--device', directory, '--profile', 'smoke', '--model', 'dot', '--json', timeout=25))
+ started = True
+ print('Detached host ready.', flush=True)
+ assert first['Running']
+ assert status()['Running']
+ second = json.loads(run('host', 'start', '--exe', exe, '--device', directory, '--json'))
+ assert second['ProcessId'] == first['ProcessId']
+
+ def send(provider, event):
+ configuration = configs[provider][1]
+ if provider == 'copilot':
+ entry = configuration['hooks'][event][0]
+ command = entry['powershell'] if os.name == 'nt' else entry['bash']
+ elif provider == 'kiro':
+ command = next(h['action']['command'] for h in configuration['hooks'] if h['trigger'] == event)
+ else:
+ command = configuration['hooks'][event][0]['hooks'][0]['command']
+ payload = {'session_id': 'same-id', 'prompt': 'DO-NOT-LOG-THIS', 'stopReason': 'end_turn'}
+ if provider == 'copilot':
+ payload.update(sessionId='same-id', timestamp=time.time_ns() // 1000000)
+ if os.name == 'nt':
+ arguments = ['pwsh', '-NoLogo', '-NoProfile', '-NonInteractive', '-Command', command] if provider == 'copilot' else shlex.split(command)
+ else:
+ arguments = ['bash', '-c', command]
+ result = subprocess.run(arguments, input=json.dumps(payload), text=True, capture_output=True, timeout=10, env=env)
+ assert result.returncode == 0 and not result.stdout and not result.stderr, (provider, result.stdout, result.stderr)
+
+ for provider in configs:
+ print('Exercising ' + provider + ' wrapper.', flush=True)
+ send(provider, 'userPromptSubmitted' if provider == 'copilot' else 'UserPromptSubmit')
+ for _ in range(30):
+ snapshot = status()
+ if len(snapshot['Sessions']) == 4:
+ break
+ time.sleep(0.1)
+ assert len(snapshot['Sessions']) == 4, snapshot
+ assert {s['Provider'] for s in snapshot['Sessions']} == {'Copilot', 'Codex', 'Claude', 'Kiro'}
+ for _ in range(30):
+ if target.read_text().strip() == 'brightness 102\noff\n#123456':
+ break
+ time.sleep(0.1)
+ assert target.read_text().strip() == 'brightness 102\noff\n#123456'
+ send('claude', 'Stop')
+ assert status()['State'] == 'Working'
+ for provider in ('copilot', 'codex', 'kiro'):
+ send(provider, 'agentStop' if provider == 'copilot' else 'Stop')
+ for _ in range(30):
+ if status()['State'] == 'Done':
+ break
+ time.sleep(0.1)
+ assert status()['State'] == 'Done'
+ assert 'DO-NOT-LOG-THIS' not in run('host', 'logs', '--tail', '10')
+ cleared = json.loads(run('host', 'reset', '--json'))
+ assert cleared['ProtocolVersion'] == 1 and cleared['State'] == 'Unknown' and not cleared['Sessions'], cleared
+ assert not status()['Sessions']
+ run('host', 'stop', '--json')
+ started = False
+ assert not status()['Running']
+ print('Host stopped gracefully.', flush=True)
+ logs = run('host', 'logs', '--tail', '10')
+ assert 'DO-NOT-LOG-THIS' not in logs
+ finally:
+ if started:
+ run('host', 'stop', '--json')
+ for provider, (path, _) in configs.items():
+ run('agents', 'uninstall', provider, '--config', str(path))
+ assert (path.read_text() if path.exists() else None) == originals[provider]
+ print('Agent wrappers, mixed-session isolation, hook setup/backups and detached host lifecycle passed.')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/animation_smoke.py b/scripts/animation_smoke.py
new file mode 100644
index 0000000..073fe8f
--- /dev/null
+++ b/scripts/animation_smoke.py
@@ -0,0 +1,67 @@
+"""Exercise animation, script output and offline credits against built/published CLI."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+
+
+def main(executable):
+ executable = str(Path(executable).resolve())
+ with tempfile.TemporaryDirectory(prefix='sidepulse animations ü ') as temporary:
+ root = Path(temporary)
+ env = dict(os.environ, SIDEPULSE_NET_HOME=str(root / 'config'), NO_COLOR='1', FORCE_COLOR='1', GITHUB_ACTIONS='true')
+
+ def run(*args, code=0):
+ result = subprocess.run([executable, *args], env=env, capture_output=True, text=True, timeout=10)
+ assert result.returncode == code, (args, result.returncode, result.stdout, result.stderr)
+ assert '\x1b' not in result.stdout + result.stderr, args
+ if code == 0:
+ assert not result.stderr, (args, result.stderr)
+ return result
+
+ patterns = json.loads(run('--json', 'animations', 'list').stdout)
+ assert patterns == json.loads(run('animations', 'list', '--json').stdout)
+ assert any(p['Name'] == 'cyan-roll' and p['Models'] == ['Dot', 'Pro'] for p in patterns)
+ frames = json.loads(run('animations', 'preview', 'cyan-roll', '--both', '--at', '500', '--json').stdout)
+ assert [len(f['colors']) for f in frames] == [2, 8]
+ assert len(run('animations', 'preview', 'cyan-roll', '--seconds', '600').stdout.splitlines()) == 1
+ source = root / "Ned's custom.LED"
+ source.write_text('off\n0:#ff0000 1s pulse; 1:#00ff00 1s\nrepeat\n', encoding='utf-8')
+ assert run('animations', 'validate', str(source), '--quiet').stdout == ''
+ error = run('animations', 'validate', '--file', str(root / 'missing.LED'), '--json', code=1)
+ assert not error.stdout and 'error' in json.loads(error.stderr)
+ run('animations', 'import', 'personal', '--file', str(source), '--model', 'dot', '--quiet')
+ run('animations', 'import', 'personal', '--file', str(source), '--model', 'dot', code=1)
+ exported = root / 'exported.LED'
+ run('animations', 'export', 'personal', '--output', str(exported), '--quiet')
+ assert exported.read_text(encoding='utf-8') == source.read_text(encoding='utf-8')
+ run('animations', 'export', 'personal', '--output', str(exported), code=1)
+ device = root / 'LEDS.LED'
+ device.write_text('old data', encoding='utf-8')
+ assert not run('animations', 'apply', 'personal', '--model', 'dot', '--device', str(device), '--brightness', '40', '--quiet').stdout
+ assert device.read_text(encoding='utf-8').startswith('brightness 102\n')
+ run('animations', 'apply', 'personal', '--model', 'pro', '--device', str(device), code=1)
+ run('profiles', 'set', 'mine', '--state', 'Working', '--pattern', 'personal', '--brightness', '40', '--quiet')
+ profile = json.loads(run('profiles', 'show', 'mine', '--json').stdout)
+ assert profile['Brightness'] == 40 and profile['States']['Working'] == 'personal'
+ assert not run('state', 'Done', '--dry-run', '--quiet').stdout
+ assert json.loads(run('state', 'Done', '--dry-run', '--quiet', '--json').stdout)['dryRun']
+ run('animations', 'edit', '--file', str(source), code=1)
+ run('state', code=1)
+ assert 'COMMANDS' in run('about').stdout
+ assert 'COMMANDS' in run('host').stdout
+ assert 'USAGE' in run().stdout
+ assert json.loads(run('about', 'info', '--json').stdout)['unofficial']
+ assert run('about', 'website').stdout.strip() == 'https://sidepulse.io/'
+ credits = json.loads(run('about', 'credits', '--json').stdout)
+ assert len(credits['dependencies']) == 7
+ licenses = json.loads(run('about', 'licenses', '--full', '--json').stdout)
+ assert len(licenses['notices']) >= 10 and all(n['text'] for n in licenses['notices'])
+ assert len(json.loads(run('docs', '--offline', '--json').stdout)) >= 2
+ print('Animation studio, script output and offline credits smoke passed.')
+
+
+if __name__ == '__main__':
+ main(sys.argv[1])
diff --git a/scripts/check_docs.py b/scripts/check_docs.py
index feba854..b1d357c 100644
--- a/scripts/check_docs.py
+++ b/scripts/check_docs.py
@@ -17,7 +17,7 @@ def check(root):
count += 1
text = path.read_text(encoding='utf-8')
name = str(path.relative_to(root))
- if not text.endswith('\n'):
+ if not text.endswith('\n') and path.name != 'packages.lock.json':
errors.append(f'{name}: missing final newline')
for number, line in enumerate(text.splitlines(), 1):
if line.rstrip() != line:
diff --git a/scripts/cli_smoke.py b/scripts/cli_smoke.py
new file mode 100644
index 0000000..276f4e4
--- /dev/null
+++ b/scripts/cli_smoke.py
@@ -0,0 +1,107 @@
+"""Exercise published CLI, local hooks and a simulated device without hardware."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import time
+
+
+def main():
+ exe = str(Path(sys.argv[1]).resolve())
+
+ child_env = os.environ.copy()
+
+ def run(*args, input=None):
+ result = subprocess.run([exe, *args], input=input, text=True, capture_output=True, timeout=10, env=child_env)
+ assert result.returncode == 0, (args, result.stdout, result.stderr)
+ return result
+
+ preview = json.loads(run('state', 'working', '--dry-run', '--json').stdout)
+ assert preview['program'] == 'off\n#00e5ff 1.6s pulse\nrepeat'
+ malformed = run('hook', 'preToolUse', input='invalid')
+ assert not malformed.stdout and not malformed.stderr
+ disconnected = run('hook', 'agentStop', input=json.dumps({'sessionId': 'a', 'timestamp': 1, 'stopReason': 'end_turn'}))
+ assert not disconnected.stdout and not disconnected.stderr
+ with tempfile.TemporaryDirectory(prefix='SidePulse test ü ') as directory:
+ child_env['SIDEPULSE_NET_HOME'] = str(Path(directory) / 'config')
+ checks = json.loads(run('doctor', '--json').stdout)
+ assert all(check['Status'] != 'error' for check in checks)
+ if os.name == 'nt' or os.environ.get('SIDEPULSE_NATIVE_VAULT_TESTS') == '1':
+ token = 'a' * 64 + '_TestKey'
+ child_env['SIDEPULSE_TEST_TOKEN'] = token
+ run('link', 'import', 'iphone', '--token-env', 'SIDEPULSE_TEST_TOKEN')
+ phones = run('link', 'list', '--json').stdout
+ assert token not in phones
+ assert json.loads(phones)[0]['IsDefault']
+ blob = (Path(child_env['SIDEPULSE_NET_HOME']) / ('links.dpapi' if os.name == 'nt' else 'links.encrypted')).read_bytes()
+ assert token.encode() not in blob
+ run('link', 'rename', 'iphone', 'personal')
+ run('link', 'default', 'personal')
+ run('state', 'done', '--phone', 'default', '--dry-run')
+ run('link', 'remove', 'personal')
+ assert json.loads(run('link', 'list', '--json').stdout) == []
+ target = Path(directory) / 'LEDS.LED'
+ target.write_text('off')
+ run('state', 'waiting', '--device', directory)
+ assert '#ff9900' in target.read_text()
+ config = Path(directory) / 'hooks.json'
+ run('hook-config', '--exe', exe, '--output', str(config))
+ hooks = json.loads(config.read_text())['hooks']
+ assert 'permissionRequest' not in hooks and 'subagentStop' not in hooks
+ assert 'exit 0' in hooks['preToolUse'][0]['powershell']
+ assert 'exit 0' in hooks['preToolUse'][0]['bash']
+ refused = subprocess.run([exe, 'hook-config', '--exe', exe, '--output', str(config)], capture_output=True)
+ assert refused.returncode != 0
+ with open(Path(directory) / 'host.log', 'w') as log:
+ host = subprocess.Popen([exe, 'host', '--device', directory, '--plain'], stdout=log, stderr=log)
+ try:
+ # Repeated idempotent input accommodates host startup without a timing-only assertion.
+ for attempt in range(30):
+ assert host.poll() is None, 'Host exited: ' + (Path(directory) / 'host.log').read_text()
+ payload = json.dumps({'sessionId': 'smoke', 'timestamp': attempt + 1})
+ if os.name == 'nt':
+ result = run('hook', 'userPromptSubmitted', input=payload)
+ else:
+ result = subprocess.run(['bash', '-c', hooks['userPromptSubmitted'][0]['bash']],
+ input=payload, text=True, capture_output=True, timeout=10, env=child_env)
+ assert result.returncode == 0
+ assert not result.stdout and not result.stderr
+ if '#00e5ff' in target.read_text():
+ break
+ time.sleep(0.1)
+ else:
+ raise AssertionError('Host did not deliver the working state')
+ competing = subprocess.run([exe, 'host', '--device', directory, '--plain'],
+ text=True, capture_output=True, timeout=10, env=child_env)
+ assert competing.returncode != 0, 'A second host must not take ownership'
+ run('hook', 'agentStop', input=json.dumps({'sessionId': 'smoke', 'timestamp': 100, 'stopReason': 'end_turn'}))
+ for _ in range(30):
+ if '#00ff66' in target.read_text():
+ break
+ time.sleep(0.1)
+ else:
+ raise AssertionError('Host did not deliver the completed state')
+ finally:
+ host.terminate()
+ host.wait(timeout=10)
+ # A forcibly terminated host must be restartable without manual socket cleanup.
+ restarted = subprocess.Popen([exe, 'host', '--device', directory, '--plain'], stdout=log, stderr=log)
+ try:
+ for attempt in range(30):
+ assert restarted.poll() is None, 'Restarted host exited: ' + (Path(directory) / 'host.log').read_text()
+ run('hook', 'userPromptSubmitted', input=json.dumps({'sessionId': 'restart', 'timestamp': 200 + attempt}))
+ if '#00e5ff' in target.read_text():
+ break
+ time.sleep(0.1)
+ else:
+ raise AssertionError('Restarted host did not accept hook input')
+ finally:
+ restarted.terminate()
+ restarted.wait(timeout=10)
+ print('CLI, hook isolation, configuration and host/device smoke checks passed.')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/package_manifest.py b/scripts/package_manifest.py
new file mode 100644
index 0000000..fbac505
--- /dev/null
+++ b/scripts/package_manifest.py
@@ -0,0 +1,27 @@
+"""Describe the owned files of a self-contained distribution, with SHA-256 and modes."""
+import hashlib
+import json
+from pathlib import Path
+import re
+import sys
+
+
+def write(directory, runtime, version):
+ root = Path(directory)
+ if not re.fullmatch(r'(win|osx|linux)-(x64|arm64)', runtime):
+ raise ValueError('Unsupported runtime')
+ manifest = root / 'sidepulse-install.json'
+ files = []
+ for path in sorted(root.rglob('*')):
+ if path.is_symlink():
+ raise ValueError('Distribution contains a symlink')
+ if path == manifest or path.is_dir():
+ continue
+ files.append({'Path': path.relative_to(root).as_posix(),
+ 'Sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
+ 'Mode': path.stat().st_mode & 0o777})
+ manifest.write_text(json.dumps({'Format': 1, 'Version': version, 'Runtime': runtime, 'Files': files}, indent=2) + '\n', encoding='utf-8')
+
+
+if __name__ == '__main__':
+ write(*sys.argv[1:])
diff --git a/scripts/release_checksums.py b/scripts/release_checksums.py
new file mode 100644
index 0000000..b5dd053
--- /dev/null
+++ b/scripts/release_checksums.py
@@ -0,0 +1,19 @@
+"""Write the release checksum list after collecting all six platform archives."""
+import hashlib
+from pathlib import Path
+import sys
+
+
+def write(directory):
+ root = Path(directory)
+ expected = {f'sidepulse-net-{platform}-{arch}' + ('.zip' if platform == 'win' else '.tar.gz')
+ for platform in ('win', 'linux', 'osx') for arch in ('x64', 'arm64')}
+ archives = {p.name: p for p in root.iterdir() if p.is_file() and (p.name.endswith('.zip') or p.name.endswith('.tar.gz'))}
+ if set(archives) != expected:
+ raise ValueError('Release must contain exactly the six expected runtime archives')
+ lines = [hashlib.sha256(archives[name].read_bytes()).hexdigest() + ' ' + name for name in sorted(archives)]
+ (root / 'SHA256SUMS').write_text('\n'.join(lines) + '\n', encoding='utf-8')
+
+
+if __name__ == '__main__':
+ write(sys.argv[1])
diff --git a/scripts/terminal_smoke.py b/scripts/terminal_smoke.py
new file mode 100644
index 0000000..316d825
--- /dev/null
+++ b/scripts/terminal_smoke.py
@@ -0,0 +1,108 @@
+"""Exercise real cursor menus and editor/preview controls on Unix pseudo terminals."""
+import os
+from pathlib import Path
+import select
+import struct
+import subprocess
+import sys
+import tempfile
+import time
+
+
+def main(executable):
+ if os.name == 'nt':
+ print('PTY smoke uses Unix APIs; Windows runs the redirected CLI smoke.')
+ return
+ import fcntl
+ import pty
+ import termios
+ executable = str(Path(executable).resolve())
+ with tempfile.TemporaryDirectory(prefix='sidepulse terminal ') as temporary:
+ root = Path(temporary)
+ env = dict(os.environ, TERM='xterm-256color', COLORTERM='truecolor', SIDEPULSE_NET_HOME=str(root / 'config'))
+ env.pop('NO_COLOR', None)
+
+ class Terminal:
+ def __init__(self, args):
+ self.master, slave = pty.openpty()
+ fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 40, 120, 0, 0))
+ self.process = subprocess.Popen([executable, *args], stdin=slave, stdout=slave, stderr=slave, env=env)
+ os.close(slave)
+ self.output = b''
+
+ def until(self, text):
+ needle = text.encode('utf-8')
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline:
+ if select.select([self.master], [], [], 0.1)[0]:
+ try:
+ data = os.read(self.master, 65536)
+ except OSError:
+ break
+ self.output += data
+ if needle in self.output:
+ self.output = b''
+ return
+ if self.process.poll() is not None:
+ break
+ raise AssertionError((text, self.process.poll(), self.output[-3000:].decode('utf-8', errors='replace')))
+
+ def send(self, keys):
+ os.write(self.master, keys)
+
+ def finish(self):
+ try:
+ # Keep consuming terminal output while the app clears/redraws on exit.
+ # macOS PTYs have small buffers; waiting without reading can block it.
+ deadline = time.monotonic() + 10
+ while self.process.poll() is None and time.monotonic() < deadline:
+ if select.select([self.master], [], [], 0.1)[0]:
+ try:
+ self.output += os.read(self.master, 65536)
+ except OSError:
+ break
+ assert self.process.wait(timeout=1) == 0, self.output[-3000:]
+ finally:
+ if self.process.poll() is None:
+ self.process.kill()
+ os.close(self.master)
+
+ menu = Terminal([])
+ try:
+ menu.until('About')
+ menu.send(b'\x1b[A\r') # wrap from Animations to About
+ menu.until('Manufacturer website')
+ menu.send(b'\x1b[B' * 4 + b'\r')
+ menu.until('Peter Kuhar')
+ menu.finish()
+ finally:
+ if menu.process.poll() is None:
+ menu.process.kill()
+
+ file = root / 'custom.LED'
+ editor = Terminal(['animations', 'edit', '--file', str(file), '--model', 'dot'])
+ try:
+ editor.until('Save to library')
+ editor.send(b'\r') # preview
+ editor.until('Playing')
+ editor.send(b' ')
+ editor.until('Paused')
+ editor.send(b'\x1b[C') # frame step
+ time.sleep(0.15)
+ editor.send(b'r')
+ time.sleep(0.15)
+ editor.send(b'\x1b') # back to editor
+ editor.until('Save to library')
+ editor.send(b'\x1b[B' * 5 + b'\r') # save
+ editor.until('Pattern saved:')
+ assert file.exists() and '#00e5ff' in file.read_text(encoding='utf-8')
+ editor.send(b'\x1b')
+ editor.finish()
+ finally:
+ if editor.process.poll() is None:
+ editor.process.kill()
+ print('Cursor menus, Spectre preview controls and editor save passed.')
+
+
+if __name__ == '__main__':
+ main(sys.argv[1])
diff --git a/scripts/update_smoke.py b/scripts/update_smoke.py
new file mode 100644
index 0000000..af867c1
--- /dev/null
+++ b/scripts/update_smoke.py
@@ -0,0 +1,56 @@
+"""Run the actual updater helper against isolated self-contained installs."""
+import hashlib
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+
+
+def main(executable):
+ executable = Path(executable).resolve()
+ source = executable.parent
+ shipped = json.loads((source / 'sidepulse-install.json').read_text(encoding='utf-8'))
+ with tempfile.TemporaryDirectory(prefix='SidePulse updater ü ') as temporary:
+ root = Path(temporary).resolve()
+ env = dict(os.environ, SIDEPULSE_NET_HOME=str(root / 'state'))
+ for fail in (False, True):
+ home = root / ('rollback' if fail else 'success')
+ target = home / 'installation'
+ job = home / '.sidepulse-update-smoke'
+ stage = job / 'stage'
+ backup = home / 'installation.backup-smoke'
+ helper = job / 'helper'
+ # A deliberately incorrect expected version exercises real startup rollback.
+ for destination in (target, stage, helper):
+ shutil.copytree(source, destination)
+ expected = '99.0.0' if fail else shipped['Version']
+ if fail:
+ (stage / 'sidepulse-install.json').write_text(json.dumps(dict(shipped, Version=expected)), encoding='utf-8')
+ initial = subprocess.run([str(target / executable.name), 'update', 'status', '--json'], env=env, capture_output=True, text=True, timeout=15)
+ assert initial.returncode == 0, (initial.stdout, initial.stderr)
+ receipt = Path(json.loads(initial.stdout)['receipt'])
+ plan = dict(Target=str(target), Stage=str(stage), Backup=str(backup), Job=str(job), Receipt=str(receipt),
+ ExpectedManifestHash=hashlib.sha256((target / 'sidepulse-install.json').read_bytes()).hexdigest().upper(),
+ Version=expected, Runtime=shipped['Runtime'], ParentId=2147483647, ParentStartTicks=0)
+ plan_path = job / 'plan.json'
+ plan_path.write_text(json.dumps(plan), encoding='utf-8')
+ result = subprocess.run([str(helper / executable.name), 'internal-update', '--plan', str(plan_path)],
+ env=env, capture_output=True, text=True, timeout=75, cwd=job)
+ assert result.returncode == (1 if fail else 0), (result.returncode, result.stdout, result.stderr, receipt.read_text(encoding='utf-8') if receipt.exists() else 'no receipt')
+ state = json.loads(receipt.read_text(encoding='utf-8'))
+ assert state['State'] == ('failed' if fail else 'installed'), state
+ current = json.loads((target / 'sidepulse-install.json').read_text(encoding='utf-8'))
+ assert current['Version'] == shipped['Version']
+ version = subprocess.run([str(target / executable.name), '--version'], env=env, capture_output=True, text=True, timeout=15)
+ assert version.returncode == 0 and version.stdout.strip() == shipped['Version']
+ status = subprocess.run([str(target / executable.name), 'update', 'status', '--json'], env=env, capture_output=True, text=True, timeout=15)
+ assert status.returncode == (1 if fail else 0) and json.loads(status.stdout)['state'] == state['State']
+ assert (job / 'failed-package').exists() if fail else backup.exists()
+ print('Native updater ' + ('startup failure rollback' if fail else 'replacement and backup') + ' passed.', flush=True)
+
+
+if __name__ == '__main__':
+ main(sys.argv[1])
diff --git a/src/SidePulse.Cli/About.cs b/src/SidePulse.Cli/About.cs
new file mode 100644
index 0000000..ecb8af6
--- /dev/null
+++ b/src/SidePulse.Cli/About.cs
@@ -0,0 +1,118 @@
+using System.Diagnostics;
+using System.Reflection;
+using System.Text.Json;
+using Spectre.Console;
+using Spectre.Console.Cli;
+
+namespace SidePulse.Cli;
+
+public sealed record DependencyCredit(string Name, string Version, string License, string Authors, string Website);
+public class AboutSettings : CommandSettings
+{
+ [CommandOption("--json")] public bool Json { get; init; }
+ [CommandOption("--open")] public bool Open { get; init; }
+ [CommandOption("--offline")] public bool Offline { get; init; }
+ [CommandOption("--full")] public bool Full { get; init; }
+}
+public static class ProjectInfo
+{
+ public const string Website = "https://sidepulse.io/";
+ public const string Github = "https://github.com/Anheledir/SidePulse.NET";
+ public const string Upstream = "https://github.com/inteliwear/sidepulse";
+ public const string Wiki = Github + "/wiki";
+ private static Assembly Assembly => typeof(ProjectInfo).Assembly;
+ public static string Version => Assembly.GetCustomAttribute()?.InformationalVersion.Split('+')[0] ?? "unknown";
+ public static IReadOnlyList Dependencies
+ {
+ get
+ {
+ using var stream = Assembly.GetManifestResourceStream("SidePulse.Cli.Dependencies.json") ?? throw new IOException("Dependency credits are missing.");
+ return JsonSerializer.Deserialize(stream, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
+ }
+ }
+ public static IReadOnlyList LicenseResources => Assembly.GetManifestResourceNames().Where(n => n.Contains(".Licenses.", StringComparison.Ordinal)).Order(StringComparer.Ordinal).ToArray();
+ public static string LicenseText(string name)
+ {
+ using var reader = new StreamReader(Assembly.GetManifestResourceStream(name)!); return reader.ReadToEnd();
+ }
+ public static int Link(string url, AboutSettings settings)
+ {
+ if (settings.Open)
+ {
+ // URLs are fixed application constants; no shell command construction.
+ try { Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); }
+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException) { throw new IOException("Could not open the browser. Open this URL manually: " + url); }
+ }
+ if (settings.Json) Output.Print(new { url, opened = settings.Open }); else Console.WriteLine(url);
+ return 0;
+ }
+}
+public sealed class AboutCommand : Command
+{
+ public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken)
+ {
+ if (settings.Json) Output.Print(new { name = "SidePulse.NET", version = ProjectInfo.Version, license = "MIT", unofficial = true, website = ProjectInfo.Website, github = ProjectInfo.Github, upstream = ProjectInfo.Upstream });
+ else Console.WriteLine($"SidePulse.NET {ProjectInfo.Version}\nUnofficial .NET companion · MIT\nOriginal SidePulse by Peter Kuhar / InteliWEAR\n{ProjectInfo.Github}");
+ return 0;
+ }
+}
+public sealed class WebsiteCommand : Command
+{
+ public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken) => ProjectInfo.Link(ProjectInfo.Website, settings);
+}
+public sealed class GithubCommand : Command
+{
+ public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken) => ProjectInfo.Link(ProjectInfo.Github, settings);
+}
+public sealed class UpstreamCommand : Command
+{
+ public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken) => ProjectInfo.Link(ProjectInfo.Upstream, settings);
+}
+public sealed class DocsCommand : Command
+{
+ public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken)
+ {
+ if (!settings.Offline) return ProjectInfo.Link(ProjectInfo.Wiki, settings);
+ var directory = Path.Combine(AppContext.BaseDirectory, "docs");
+ var files = Directory.Exists(directory) ? Directory.GetFiles(directory, "*.md").Order(StringComparer.Ordinal).ToArray() : [];
+ if (files.Length == 0) throw new IOException("Offline documentation is missing from this installation.");
+ if (settings.Json) Output.Print(files); else foreach (var file in files) { Console.WriteLine(Path.GetFileName(file)); Console.WriteLine(File.ReadAllText(file)); }
+ return 0;
+ }
+}
+public sealed class CreditsCommand : Command
+{
+ public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken)
+ {
+ if (settings.Json) Output.Print(new { project = "Gordon Breuer / Anheledir", upstream = "Peter Kuhar / InteliWEAR", dependencies = ProjectInfo.Dependencies });
+ else
+ {
+ Console.WriteLine("SidePulse.NET: Gordon Breuer / Anheledir\nSidePulse hardware, protocol and original animations: Peter Kuhar / InteliWEAR\n" + ProjectInfo.Upstream);
+ foreach (var dependency in ProjectInfo.Dependencies) Console.WriteLine($"{dependency.Name} {dependency.Version} · {dependency.Authors} · {dependency.License}\n {dependency.Website}");
+ Console.WriteLine("Thank you to the maintainers and contributors. Use about licenses --full for bundled license texts.");
+ }
+ return 0;
+ }
+}
+public sealed class LicensesCommand : Command
+{
+ public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken)
+ {
+ var resources = ProjectInfo.LicenseResources;
+ var runtimeDirectory = Path.Combine(AppContext.BaseDirectory, "third-party", "dotnet");
+ var runtime = Directory.Exists(runtimeDirectory) ? Directory.GetFiles(runtimeDirectory).Order(StringComparer.Ordinal).ToArray() : [];
+ if (settings.Json) Output.Print(new { project = "MIT", dependencies = ProjectInfo.Dependencies, notices = resources.Select(r => new { name = r, text = settings.Full ? ProjectInfo.LicenseText(r) : null }), runtimeNotices = runtime.Select(r => new { name = Path.GetFileName(r), text = settings.Full ? File.ReadAllText(r) : null }) });
+ else
+ {
+ Console.WriteLine("SidePulse.NET · MIT");
+ foreach (var dependency in ProjectInfo.Dependencies) Console.WriteLine($"{dependency.Name} {dependency.Version} · {dependency.License}");
+ if (settings.Full)
+ {
+ foreach (var resource in resources) { Console.WriteLine("\n" + resource); Console.WriteLine(ProjectInfo.LicenseText(resource)); }
+ foreach (var path in runtime) { Console.WriteLine("\n" + Path.GetFileName(path)); Console.WriteLine(File.ReadAllText(path)); }
+ }
+ else Console.WriteLine("Use --full for offline license texts and notices, including the runtime when bundled.");
+ }
+ return 0;
+ }
+}
diff --git a/src/SidePulse.Cli/Agents.cs b/src/SidePulse.Cli/Agents.cs
new file mode 100644
index 0000000..7c24192
--- /dev/null
+++ b/src/SidePulse.Cli/Agents.cs
@@ -0,0 +1,87 @@
+using System.ComponentModel;
+using SidePulse.Core;
+using Spectre.Console;
+using Spectre.Console.Cli;
+
+namespace SidePulse.Cli;
+
+public sealed class AgentsListCommand : Command
+{
+ public override int Execute(CommandContext context, HostActionSettings settings, CancellationToken cancellationToken)
+ {
+ if (settings.Json) Output.Print(AgentEvents.Capabilities);
+ else
+ {
+ var table = new Table().Border(TableBorder.Rounded).AddColumn("Agent").AddColumn("Target").AddColumn("Notes");
+ foreach (var agent in AgentEvents.Capabilities) table.AddRow(agent.Provider.ToString(), agent.Target, Markup.Escape(agent.Limitations));
+ AnsiConsole.Write(table);
+ }
+ return 0;
+ }
+}
+public sealed class AgentSettings : CommandSettings
+{
+ [CommandArgument(0, "")]
+ public AgentProvider Agent { get; init; }
+ [CommandOption("--exe ")]
+ public string Executable { get; init; } = Environment.ProcessPath ?? "sidepulse-net";
+ [CommandOption("--config ")]
+ [Description("Explicit provider configuration file; useful for project-scoped or isolated setup.")]
+ public string? Config { get; init; }
+ [CommandOption("--dry-run")]
+ public bool DryRun { get; init; }
+ [CommandOption("--json")]
+ public bool Json { get; init; }
+ public override ValidationResult Validate() => Enum.IsDefined(Agent) ? ValidationResult.Success() : ValidationResult.Error("Unknown agent.");
+ public string Target
+ {
+ get
+ {
+ if (Config is not null) return Path.GetFullPath(Config);
+ var user = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
+ string Home(string variable, string fallback) => Environment.GetEnvironmentVariable(variable) is { Length: > 0 } home ? home : Path.Combine(user, fallback);
+ return Agent switch
+ {
+ AgentProvider.Copilot => Path.Combine(Home("COPILOT_HOME", ".copilot"), "hooks", "sidepulse-net.json"),
+ AgentProvider.Codex => Path.Combine(Home("CODEX_HOME", ".codex"), "hooks.json"),
+ AgentProvider.Claude => Path.Combine(user, ".claude", "settings.json"),
+ _ => Path.Combine(user, ".kiro", "hooks", "sidepulse-net.json")
+ };
+ }
+ }
+ public HookInstallation Installation => new(Path.Combine(Path.GetDirectoryName(LinkStore.DefaultPath)!, "integrations"));
+}
+public sealed class AgentInstallCommand : Command
+{
+ public override int Execute(CommandContext context, AgentSettings settings, CancellationToken cancellationToken)
+ {
+ var generated = HookConfiguration.Generate(settings.Agent, HookConfiguration.Executable(settings.Executable), OperatingSystem.IsWindows());
+ var status = settings.Installation.Install(settings.Target, settings.Agent, generated, settings.DryRun);
+ if (settings.Json) Output.Print(new { status, managedHooks = settings.DryRun ? generated : null });
+ else
+ {
+ AnsiConsole.WriteLine($"{status.State}: {status.Target}");
+ if (settings.DryRun) AnsiConsole.Write(new Text(generated.ToJsonString(Output.Json)));
+ else AnsiConsole.WriteLine("Restart the agent and review its hook trust prompts. Codex requires /hooks review; no trust or permissions were changed.");
+ }
+ return 0;
+ }
+}
+public sealed class AgentStatusCommand : Command
+{
+ public override int Execute(CommandContext context, AgentSettings settings, CancellationToken cancellationToken)
+ {
+ var status = settings.Installation.Status(settings.Target);
+ if (settings.Json) Output.Print(status); else AnsiConsole.WriteLine($"{status.State}: {status.Target}");
+ return 0;
+ }
+}
+public sealed class AgentUninstallCommand : Command
+{
+ public override int Execute(CommandContext context, AgentSettings settings, CancellationToken cancellationToken)
+ {
+ var status = settings.Installation.Uninstall(settings.Target, settings.DryRun);
+ if (settings.Json) Output.Print(status); else AnsiConsole.WriteLine($"{status.State}: {status.Target}");
+ return 0;
+ }
+}
diff --git a/src/SidePulse.Cli/Animations.cs b/src/SidePulse.Cli/Animations.cs
new file mode 100644
index 0000000..0307072
--- /dev/null
+++ b/src/SidePulse.Cli/Animations.cs
@@ -0,0 +1,234 @@
+using System.Diagnostics;
+using SidePulse.Core;
+using Spectre.Console;
+using Spectre.Console.Cli;
+using Spectre.Console.Rendering;
+
+namespace SidePulse.Cli;
+
+public class PatternSettings : CommandSettings
+{
+ [CommandArgument(0, "[NAME]")] public string? Name { get; init; }
+ [CommandOption("--file ")] public string? File { get; init; }
+ [CommandOption("--model ")] public DeviceModel Model { get; init; } = DeviceModel.Dot;
+ [CommandOption("--brightness ")] public int? Brightness { get; init; }
+ [CommandOption("--json")] public bool Json { get; init; }
+ public override ValidationResult Validate()
+ {
+ if (!Enum.IsDefined(Model)) return ValidationResult.Error("Choose dot or pro.");
+ if (Brightness is < 0 or > 100) return ValidationResult.Error("Brightness must be 0..100.");
+ return (Name is null) == (File is null) ? ValidationResult.Error("Supply a pattern name or --file, but not both.") : ValidationResult.Success();
+ }
+ public LedProgram Read() => AnimationLibrary.WithBrightness(File is { } file ? new LedProgram(System.IO.File.ReadAllText(file)) : AnimationLibrary.Default.Get(Name!, Model), Brightness);
+}
+public sealed class PatternListCommand : Command
+{
+ public override int Execute(CommandContext context, DevicesSettings settings, CancellationToken cancellationToken)
+ {
+ var items = AnimationLibrary.Default.List();
+ if (settings.Json) Output.Print(items);
+ else if (!TerminalMode.Interactive) foreach (var item in items) Console.WriteLine($"{item.Name}\t{item.Source}\t{string.Join(',', item.Models)}");
+ else
+ {
+ var table = new Table().Border(TableBorder.Rounded).AddColumn("Pattern").AddColumn("Source").AddColumn("Models");
+ foreach (var item in items) table.AddRow(item.Name, item.Source, string.Join(", ", item.Models));
+ AnsiConsole.Write(table);
+ }
+ return 0;
+ }
+}
+public sealed class PatternValidateCommand : Command
+{
+ public override int Execute(CommandContext context, PatternSettings settings, CancellationToken cancellationToken)
+ {
+ // Positional paths are accepted by validate for convenient scripting.
+ var program = settings.File is null && settings.Name is { } name && System.IO.File.Exists(name)
+ ? AnimationLibrary.WithBrightness(new(System.IO.File.ReadAllText(name)), settings.Brightness) : settings.Read();
+ var animation = Animation.Parse(program, settings.Model);
+ if (settings.Json) Output.Print(new { valid = true, model = settings.Model, bytes = program.ByteCount, lines = program.LineCount, instructions = animation.Instructions.Count });
+ else Console.WriteLine($"Valid ({program.ByteCount} bytes, {program.LineCount} lines, {settings.Model}).");
+ return 0;
+ }
+}
+public sealed class PreviewSettings : PatternSettings
+{
+ [CommandOption("--seconds ")] public double Seconds { get; init; } = 10;
+ [CommandOption("--at ")] public int At { get; init; }
+ [CommandOption("--both")] public bool Both { get; init; }
+ public override ValidationResult Validate()
+ {
+ var result = base.Validate();
+ if (!result.Successful) return result;
+ return !double.IsFinite(Seconds) || Seconds is < 0 or > 600 || At is < 0 or > 600000 ? ValidationResult.Error("Seconds must be 0..600; --at must be 0..600000ms.") : ValidationResult.Success();
+ }
+}
+public static class PatternPreview
+{
+ public static async Task Show(LedProgram program, DeviceModel model, double seconds, int at, bool both, string command, CancellationToken cancellationToken, Func? source = null)
+ {
+ var models = both ? Enum.GetValues() : [model];
+ var players = models.Select(m => new AnimationPlayer(Animation.Parse(source?.Invoke(m) ?? program, m))).ToArray();
+ foreach (var player in players) player.Advance(at);
+ if (!TerminalMode.Interactive || seconds == 0)
+ {
+ foreach (var pair in models.Zip(players)) Console.WriteLine($"{pair.First}: {string.Join(' ', pair.Second.Frame)}");
+ return;
+ }
+ var paused = false;
+ var clock = Stopwatch.StartNew();
+ var previous = clock.Elapsed.TotalMilliseconds;
+ double played = 0;
+ IRenderable Draw()
+ {
+ var rows = new List();
+ foreach (var pair in models.Zip(players))
+ {
+ rows.Add(new Text($"{pair.First} · {(int)pair.First} LEDs"));
+ var strip = new Table().NoBorder().HideHeaders();
+ for (var i = 0; i < (int)pair.First; i++) strip.AddColumn(new TableColumn("").Padding(1, 0));
+ strip.AddRow(pair.Second.Frame.Select(c => (IRenderable)(TerminalMode.ColorEnabled ? new Text(" ", new Style(background: new Color(c.R, c.G, c.B))) : new Text(c.ToString()))).ToArray());
+ rows.Add(strip);
+ }
+ rows.Add(new Text($"{(paused ? "Paused" : "Playing")} · Space pause · Right step 100ms · R restart · Esc back"));
+ rows.Add(new Panel(new Text(command)).Header("Script command").Border(BoxBorder.Rounded));
+ return new Panel(new Rows(rows)).Header("LED preview").Border(BoxBorder.Rounded);
+ }
+ await AnsiConsole.Live(Draw()).AutoClear(true).StartAsync(async live =>
+ {
+ while (played < seconds * 1000 && !cancellationToken.IsCancellationRequested)
+ {
+ var now = clock.Elapsed.TotalMilliseconds;
+ var delta = now - previous; previous = now;
+ if (Console.KeyAvailable)
+ {
+ var key = Console.ReadKey(true).Key;
+ if (key is ConsoleKey.Escape or ConsoleKey.Q) break;
+ if (key == ConsoleKey.Spacebar) paused = !paused;
+ if (key == ConsoleKey.RightArrow) { paused = true; foreach (var player in players) player.Advance(100); played += 100; }
+ if (key == ConsoleKey.R) { players = models.Select(m => new AnimationPlayer(Animation.Parse(source?.Invoke(m) ?? program, m))).ToArray(); played = 0; }
+ }
+ if (!paused) { foreach (var player in players) player.Advance(delta); played += delta; }
+ live.UpdateTarget(Draw()); live.Refresh();
+ await Task.Delay(50, cancellationToken);
+ }
+ });
+ }
+}
+public sealed class PatternPreviewCommand : AsyncCommand
+{
+ public override async Task ExecuteAsync(CommandContext context, PreviewSettings settings, CancellationToken cancellationToken)
+ {
+ var program = settings.Read();
+ if (settings.Json)
+ {
+ var models = settings.Both ? Enum.GetValues() : [settings.Model];
+ Output.Print(models.Select(m => { var selected = settings.File is null ? AnimationLibrary.WithBrightness(AnimationLibrary.Default.Get(settings.Name!, m), settings.Brightness) : program; var player = new AnimationPlayer(Animation.Parse(selected, m)); player.Advance(settings.At); return new { model = m, at = settings.At, colors = player.Frame.Select(c => c.ToString()).ToArray() }; }).ToArray());
+ }
+ else
+ {
+ var args = new List { "animations", "preview" };
+ if (settings.File is { } file) args.AddRange(["--file", Path.GetFullPath(file)]); else args.Add(settings.Name!);
+ args.AddRange(["--model", settings.Model.ToString().ToLowerInvariant(), "--seconds", settings.Seconds.ToString(System.Globalization.CultureInfo.InvariantCulture), "--at", settings.At.ToString()]);
+ if (settings.Brightness is { } brightness) args.AddRange(["--brightness", brightness.ToString()]);
+ if (settings.Both) args.Add("--both");
+ await PatternPreview.Show(program, settings.Model, settings.Seconds, settings.At, settings.Both, TerminalMode.Command(args), cancellationToken, settings.File is null ? m => AnimationLibrary.WithBrightness(AnimationLibrary.Default.Get(settings.Name!, m), settings.Brightness) : null);
+ }
+ return 0;
+ }
+}
+public sealed class PatternApplySettings : TargetSettings
+{
+ [CommandArgument(0, "[NAME]")] public string? Name { get; init; }
+ [CommandOption("--file ")] public string? File { get; init; }
+ [CommandOption("--model ")] public DeviceModel? Model { get; init; }
+ [CommandOption("--brightness ")] public int? Brightness { get; init; }
+ public override ValidationResult Validate()
+ {
+ var result = base.Validate(); if (!result.Successful) return result;
+ if (Model is { } model && !Enum.IsDefined(model)) return ValidationResult.Error("Choose dot or pro.");
+ if (Brightness is < 0 or > 100) return ValidationResult.Error("Brightness must be 0..100.");
+ return (Name is null) == (File is null) ? ValidationResult.Error("Supply a pattern name or --file.") : ValidationResult.Success();
+ }
+}
+public sealed class PatternApplyCommand : AsyncCommand
+{
+ public override async Task ExecuteAsync(CommandContext context, PatternApplySettings settings, CancellationToken cancellationToken)
+ {
+ var model = settings.Model ?? AnimationLibrary.DetectModel(settings.Device);
+ var raw = settings.File is { } file ? new LedProgram(await System.IO.File.ReadAllTextAsync(file, cancellationToken)) : AnimationLibrary.Default.Get(settings.Name!, model);
+ var program = AnimationLibrary.WithBrightness(raw, settings.Brightness);
+ Animation.Parse(program, model);
+ await Delivery.Send(settings, program, cancellationToken); Delivery.Receipt(settings, program);
+ return 0;
+ }
+}
+public sealed class PatternImportSettings : CommandSettings
+{
+ [CommandArgument(0, "")] public string Name { get; init; } = "";
+ [CommandOption("--file ")] public string File { get; init; } = "";
+ [CommandOption("--model ")] public DeviceModel Model { get; init; } = DeviceModel.Dot;
+ [CommandOption("--force")] public bool Force { get; init; }
+ [CommandOption("--json")] public bool Json { get; init; }
+ public override ValidationResult Validate() => string.IsNullOrWhiteSpace(File) || !Enum.IsDefined(Model) ? ValidationResult.Error("Supply --file and a valid --model.") : ValidationResult.Success();
+}
+public sealed class PatternImportCommand : Command
+{
+ public override int Execute(CommandContext context, PatternImportSettings settings, CancellationToken cancellationToken)
+ {
+ var path = AnimationLibrary.Default.Save(settings.Name, settings.Model, new(System.IO.File.ReadAllText(settings.File)), settings.Force);
+ if (settings.Json) Output.Print(new { saved = path }); else Console.WriteLine(path);
+ return 0;
+ }
+}
+public sealed class PatternExportSettings : PatternSettings
+{
+ [CommandOption("--output ")] public string? Destination { get; init; }
+ [CommandOption("--force")] public bool Force { get; init; }
+}
+public sealed class PatternExportCommand : Command
+{
+ public override int Execute(CommandContext context, PatternExportSettings settings, CancellationToken cancellationToken)
+ {
+ var program = settings.Read(); Animation.Parse(program, settings.Model);
+ if (settings.Destination is { } path) AnimationLibrary.WriteFile(path, program.Text + "\n", settings.Force);
+ if (settings.Json) Output.Print(new { program = program.Text, output = settings.Destination });
+ else if (settings.Destination is null) Console.WriteLine(program.Text);
+ else Console.WriteLine(Path.GetFullPath(settings.Destination));
+ return 0;
+ }
+}
+public sealed class ProfileSettings : CommandSettings
+{
+ [CommandArgument(0, "")] public string Name { get; init; } = "";
+ [CommandOption("--state ")] public AgentState? State { get; init; }
+ [CommandOption("--pattern ")] public string? Pattern { get; init; }
+ [CommandOption("--brightness ")] public int? Brightness { get; init; }
+ [CommandOption("--json")] public bool Json { get; init; }
+ public override ValidationResult Validate() => (State is { } state && !Enum.IsDefined(state)) || Brightness is < 0 or > 100 ? ValidationResult.Error("Choose a valid state and brightness 0..100.") : ValidationResult.Success();
+}
+public sealed class ProfileSetCommand : Command
+{
+ public override int Execute(CommandContext context, ProfileSettings settings, CancellationToken cancellationToken)
+ {
+ if (settings.Pattern is null || settings.State is null) throw new ArgumentException("Supply --state and --pattern.");
+ if (!AnimationLibrary.Default.List().Any(p => p.Name == settings.Pattern)) throw new ArgumentException("Pattern was not found. Import it first.");
+ AnimationProfile profile;
+ try { profile = AnimationLibrary.Default.LoadProfile(settings.Name); }
+ catch (FileNotFoundException) { profile = new([]); }
+ profile.States[settings.State.Value] = settings.Pattern;
+ profile = profile with { Brightness = settings.Brightness ?? profile.Brightness };
+ var path = AnimationLibrary.Default.SaveProfile(settings.Name, profile, true);
+ if (settings.Json) Output.Print(new { path, profile }); else Console.WriteLine(path);
+ return 0;
+ }
+}
+public sealed class ProfileShowCommand : Command
+{
+ public override int Execute(CommandContext context, ProfileSettings settings, CancellationToken cancellationToken)
+ {
+ var profile = AnimationLibrary.Default.LoadProfile(settings.Name);
+ if (settings.Json) Output.Print(profile);
+ else { Console.WriteLine($"Brightness: {profile.Brightness}%"); foreach (var pair in profile.States) Console.WriteLine($"{pair.Key}: {pair.Value}"); }
+ return 0;
+ }
+}
diff --git a/src/SidePulse.Cli/Commands.cs b/src/SidePulse.Cli/Commands.cs
new file mode 100644
index 0000000..368783d
--- /dev/null
+++ b/src/SidePulse.Cli/Commands.cs
@@ -0,0 +1,161 @@
+using System.ComponentModel;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using SidePulse.Core;
+using Spectre.Console;
+using Spectre.Console.Cli;
+
+namespace SidePulse.Cli;
+
+public static class Output
+{
+ public static readonly JsonSerializerOptions Json = new() { WriteIndented = true, Converters = { new JsonStringEnumConverter() } };
+ public static void Print(object value) => Console.WriteLine(JsonSerializer.Serialize(value, Json));
+ public static string Color(AgentState state) => state switch
+ {
+ AgentState.Working => "cyan", AgentState.Waiting => "orange1", AgentState.Done => "green",
+ AgentState.Error => "red", _ => "grey"
+ };
+}
+
+public class DevicesSettings : CommandSettings
+{
+ [CommandOption("--json")]
+ [Description("Emit structured output for scripts.")]
+ public bool Json { get; init; }
+}
+
+public sealed class DevicesCommand : Command
+{
+ public override int Execute(CommandContext context, DevicesSettings settings, CancellationToken cancellationToken)
+ {
+ var devices = DeviceTransport.Discover();
+ if (settings.Json) Output.Print(devices);
+ else
+ {
+ var table = new Table().Border(TableBorder.Rounded).AddColumn("Device").AddColumn("LEDS.LED");
+ foreach (var device in devices) table.AddRow(Markup.Escape(device.Label), Markup.Escape(device.Path));
+ AnsiConsole.Write(table);
+ if (devices.Count == 0) AnsiConsole.WriteLine("No mounted devices found. An iPhone-connected device uses the phone bridge.");
+ }
+ return 0;
+ }
+}
+
+public class TargetSettings : CommandSettings
+{
+ [CommandOption("--device ")]
+ [Description("Mounted directory or existing LEDS.LED path. Auto-selects a single discovered device.")]
+ public string? Device { get; init; }
+ [CommandOption("--token-env ")]
+ [Description("Environment variable holding an iPhone push token. Selects phone delivery.")]
+ public string? TokenEnvironment { get; init; }
+ [CommandOption("--phone ")]
+ [Description("Use a saved phone alias, or 'default', from native protected storage.")]
+ public string? Phone { get; init; }
+ [CommandOption("--dry-run")]
+ [Description("Preview the program without writing or sending anything.")]
+ public bool DryRun { get; init; }
+ [CommandOption("--json")]
+ public bool Json { get; init; }
+
+ public override ValidationResult Validate() => new[] { Device, TokenEnvironment, Phone }.Count(v => v is not null) > 1
+ ? ValidationResult.Error("Choose one of --device, --token-env or --phone.") : ValidationResult.Success();
+}
+
+public static class Delivery
+{
+ public static async Task Send(TargetSettings settings, LedProgram program, CancellationToken cancellationToken)
+ {
+ if (settings.DryRun) return;
+ if (settings.Phone is { } alias)
+ {
+ var phone = PhoneStores.Open().Get(alias);
+ using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
+ await new PhoneBridge(client).SendAsync(phone.Token, program, cancellationToken);
+ }
+ else if (settings.TokenEnvironment is { } variable)
+ {
+ var token = Environment.GetEnvironmentVariable(variable);
+ if (string.IsNullOrWhiteSpace(token)) throw new ArgumentException("The selected token environment variable is empty.");
+ using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
+ await new PhoneBridge(client).SendAsync(token, program, cancellationToken);
+ }
+ else DeviceTransport.Write(DeviceTransport.Resolve(settings.Device), program);
+ }
+ public static void Receipt(TargetSettings settings, LedProgram program)
+ {
+ if (settings.Json) Output.Print(new { dryRun = settings.DryRun, bytes = program.ByteCount, lines = program.LineCount, program = program.Text });
+ else if (settings.DryRun) AnsiConsole.Write(new Panel(new Text(program.Text)).Header("LED preview").Border(BoxBorder.Rounded));
+ else AnsiConsole.MarkupLine("[green]Sent.[/]");
+ }
+}
+
+public sealed class StateSettings : TargetSettings
+{
+ [CommandArgument(0, "")]
+ public AgentState State { get; init; }
+ public override ValidationResult Validate()
+ {
+ var target = base.Validate();
+ if (!target.Successful) return target;
+ return Enum.IsDefined(State) ? ValidationResult.Success() : ValidationResult.Error("Unknown agent state.");
+ }
+}
+public sealed class StateCommand : AsyncCommand
+{
+ public override async Task ExecuteAsync(CommandContext context, StateSettings settings, CancellationToken cancellationToken)
+ {
+ var program = LedProgram.ForState(settings.State);
+ await Delivery.Send(settings, program, cancellationToken);
+ Delivery.Receipt(settings, program);
+ return 0;
+ }
+}
+public sealed class WriteSettings : TargetSettings
+{
+ [CommandArgument(0, "[PROGRAM]")]
+ public string? Program { get; init; }
+ [CommandOption("--file ")]
+ public string? File { get; init; }
+ [CommandOption("--escapes")]
+ [Description("Decode literal backslash-n, backslash-r, backslash-t and backslash-backslash.")]
+ public bool Escapes { get; init; }
+ public override ValidationResult Validate()
+ {
+ var target = base.Validate();
+ if (!target.Successful) return target;
+ return (Program is null) == (File is null) ? ValidationResult.Error("Supply one program argument or --file.") : ValidationResult.Success();
+ }
+}
+public sealed class WriteCommand : AsyncCommand
+{
+ public override async Task ExecuteAsync(CommandContext context, WriteSettings settings, CancellationToken cancellationToken)
+ {
+ var text = settings.File is { } file ? await System.IO.File.ReadAllTextAsync(file, cancellationToken) : settings.Program!;
+ var program = new LedProgram(settings.Escapes ? LedProgram.DecodeEscapes(text) : text);
+ await Delivery.Send(settings, program, cancellationToken);
+ Delivery.Receipt(settings, program);
+ return 0;
+ }
+}
+public sealed class DashboardCommand : Command
+{
+ public override int Execute(CommandContext context, DevicesSettings settings, CancellationToken cancellationToken)
+ {
+ if (settings.Json) { Output.Print(new { devices = DeviceTransport.Discover(), profiles = Enum.GetNames() }); return 0; }
+ AnsiConsole.Write(new Rule("[cyan]SidePulse[/][white].NET[/]").LeftJustified());
+ AnsiConsole.MarkupLine("[grey]Small signals. Clear status.[/]\n");
+ new DevicesCommand().Execute(context, settings, cancellationToken);
+ var profiles = new Table().Border(TableBorder.Rounded).AddColumn("Status").AddColumn("Signal");
+ foreach (var state in Enum.GetValues())
+ profiles.AddRow($"[{Output.Color(state)}]{state}[/]", state switch
+ {
+ AgentState.Working => "Cyan pulse", AgentState.Waiting => "Amber pulse",
+ AgentState.Done => "Green", AgentState.Error => "Red pulse", _ => "Off"
+ });
+ AnsiConsole.Write(profiles);
+ AnsiConsole.MarkupLine("[grey]Use host for live Copilot sessions. Done means the turn ended.[/]");
+ return 0;
+ }
+}
diff --git a/src/SidePulse.Cli/Dependencies.json b/src/SidePulse.Cli/Dependencies.json
new file mode 100644
index 0000000..44fa2e6
--- /dev/null
+++ b/src/SidePulse.Cli/Dependencies.json
@@ -0,0 +1,51 @@
+[
+ {
+ "name": "QRCoder",
+ "version": "1.8.1",
+ "license": "MIT",
+ "authors": "Raffael Herrmann, Shane Krueger",
+ "website": ""
+ },
+ {
+ "name": "Spectre.Console",
+ "version": "0.57.2",
+ "license": "MIT",
+ "authors": "Patrik Svensson, Phil Scott, Nils Andresen, C\u00e9dric Luthi",
+ "website": "https://github.com/spectreconsole/spectre.console"
+ },
+ {
+ "name": "Spectre.Console.Cli",
+ "version": "0.57.2",
+ "license": "MIT",
+ "authors": "Patrik Svensson, Phil Scott, Nils Andresen, C\u00e9dric Luthi, Frank Ray",
+ "website": "https://github.com/spectreconsole/spectre.console.cli"
+ },
+ {
+ "name": "Microsoft.Win32.SystemEvents",
+ "version": "6.0.0",
+ "license": "MIT",
+ "authors": "Microsoft",
+ "website": "https://dot.net/"
+ },
+ {
+ "name": "Spectre.Console.Ansi",
+ "version": "0.57.2",
+ "license": "MIT",
+ "authors": "Patrik Svensson, Phil Scott, Nils Andresen, C\u00e9dric Luthi",
+ "website": "https://github.com/spectreconsole/spectre.console"
+ },
+ {
+ "name": "System.Drawing.Common",
+ "version": "6.0.0",
+ "license": "MIT",
+ "authors": "Microsoft",
+ "website": "https://dot.net/"
+ },
+ {
+ "name": "System.Security.Cryptography.ProtectedData",
+ "version": "10.0.13",
+ "license": "MIT",
+ "authors": "Microsoft",
+ "website": "https://dot.net/"
+ }
+]
diff --git a/src/SidePulse.Cli/Doctor.cs b/src/SidePulse.Cli/Doctor.cs
new file mode 100644
index 0000000..924888e
--- /dev/null
+++ b/src/SidePulse.Cli/Doctor.cs
@@ -0,0 +1,64 @@
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using SidePulse.Core;
+using Spectre.Console;
+using Spectre.Console.Cli;
+
+namespace SidePulse.Cli;
+
+public sealed record DiagnosticCheck(string Name, string Status, string Detail);
+public sealed class DoctorSettings : CommandSettings
+{
+ [CommandOption("--json")]
+ [Description("Emit diagnostics without ANSI output or credential values.")]
+ public bool Json { get; init; }
+}
+public sealed class DoctorCommand : Command
+{
+ public override int Execute(CommandContext context, DoctorSettings settings, CancellationToken cancellationToken)
+ {
+ var checks = new List
+ {
+ new("Runtime", "ok", RuntimeInformation.FrameworkDescription),
+ new("Platform", "ok", RuntimeInformation.OSDescription)
+ };
+ var devices = DeviceTransport.Discover();
+ checks.Add(new("USB discovery", devices.Count == 0 ? "info" : "ok", $"{devices.Count} mounted device(s). No write was attempted."));
+ try
+ {
+ var protector = PlatformSecrets.Create(LinkStore.DefaultPath);
+ checks.Add(new("Credential protection", "ok", PlatformSecrets.Description + ". An unlocked native vault is required for saved links."));
+ if (File.Exists(LinkStore.DefaultPath))
+ {
+ var links = PhoneStores.Open().List();
+ checks.Add(new("Phone store", "ok", $"{links.Count} protected phone link(s). Tokens are never shown."));
+ }
+ else checks.Add(new("Phone store", "info", "No saved phone store. Use link pair to get started."));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.Cryptography.CryptographicException or PlatformNotSupportedException)
+ {
+ checks.Add(new("Credential protection", File.Exists(LinkStore.DefaultPath) ? "error" : "info",
+ "Native credentials are unavailable or unreadable. Unlock Keychain on macOS; on Linux install secret-tool and unlock a Secret Service keyring. Existing data was preserved. Environment-token delivery remains available."));
+ }
+ var copilotHome = Environment.GetEnvironmentVariable("COPILOT_HOME");
+ var hooks = string.IsNullOrWhiteSpace(copilotHome)
+ ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".copilot", "hooks")
+ : Path.Combine(copilotHome, "hooks");
+ checks.Add(new("Copilot hooks", Directory.Exists(hooks) ? "ok" : "info",
+ Directory.Exists(hooks) ? "Hook directory exists. Use hook-config to generate a separate opt-in file."
+ : "Hook directory does not exist. See Getting started for installation."));
+ if (settings.Json) Output.Print(checks);
+ else
+ {
+ AnsiConsole.Write(new Rule("[cyan]SidePulse.NET diagnostics[/]").LeftJustified());
+ var table = new Table().Border(TableBorder.Rounded).AddColumn("Check").AddColumn("Status").AddColumn("Detail");
+ foreach (var check in checks)
+ {
+ var color = check.Status == "error" ? "red" : check.Status == "ok" ? "green" : "grey";
+ table.AddRow(Markup.Escape(check.Name), $"[{color}]{check.Status}[/]", Markup.Escape(check.Detail));
+ }
+ AnsiConsole.Write(table);
+ }
+ return checks.Any(c => c.Status == "error") ? 1 : 0;
+ }
+}
diff --git a/src/SidePulse.Cli/Hooks.cs b/src/SidePulse.Cli/Hooks.cs
new file mode 100644
index 0000000..14fc6d8
--- /dev/null
+++ b/src/SidePulse.Cli/Hooks.cs
@@ -0,0 +1,253 @@
+using System.ComponentModel;
+using System.IO.Pipes;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Channels;
+using SidePulse.Core;
+using Spectre.Console;
+using Spectre.Console.Cli;
+
+namespace SidePulse.Cli;
+
+public static class LocalPipe
+{
+ // Per-user namespace plus OS-enforced current-user access on server and client.
+ private static string UserKey => Convert.ToHexString(SHA256.HashData(
+ Encoding.UTF8.GetBytes(Environment.UserDomainName + "\\" + Environment.UserName)))[..20];
+ // Use a short private path to stay below Unix-domain socket limits on macOS.
+ private static string UnixDirectory => Path.Combine("/tmp", "sidepulse-net-" + UserKey);
+ public static string Name => OperatingSystem.IsWindows() ? "sidepulse-net-" + UserKey : Path.Combine(UnixDirectory, "events");
+ public static IDisposable AcquireHostLease()
+ {
+ if (OperatingSystem.IsWindows()) return new Lease(null, null);
+ Directory.CreateDirectory(UnixDirectory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+ if ((File.GetAttributes(UnixDirectory) & FileAttributes.ReparsePoint) != 0
+ || (File.GetUnixFileMode(UnixDirectory) & (UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute
+ | UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute)) != 0)
+ throw new IOException("The local IPC directory must be a private, non-symlink directory for the current user.");
+ FileStream gate;
+ try
+ {
+ gate = new FileStream(Path.Combine(UnixDirectory, "host.lock"), new FileStreamOptions
+ {
+ Mode = FileMode.OpenOrCreate, Access = FileAccess.ReadWrite, Share = FileShare.None,
+ UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite
+ });
+ }
+ catch (IOException) { throw new IOException("A SidePulse.NET host is already running for this user."); }
+ try
+ {
+ // A held lease proves no other cooperating host can own this endpoint.
+ // Remove the socket left by a killed host; never unlink an active host's socket.
+ File.Delete(Name);
+ return new Lease(gate, Name);
+ }
+ catch { gate.Dispose(); throw; }
+ }
+ private sealed class Lease(FileStream? gate, string? path) : IDisposable
+ {
+ public void Dispose()
+ {
+ try { if (path is not null) File.Delete(path); }
+ finally { gate?.Dispose(); }
+ }
+ }
+ public const int MaximumMessageBytes = 16384;
+}
+
+public sealed class HookSettings : CommandSettings
+{
+ [CommandArgument(0, "")]
+ public string Event { get; init; } = "";
+ [CommandOption("--source ")]
+ public AgentProvider Source { get; init; } = AgentProvider.Copilot;
+}
+public sealed class HookCommand : AsyncCommand
+{
+ public override async Task ExecuteAsync(CommandContext context, HookSettings settings, CancellationToken cancellationToken)
+ {
+ // Every path is silent and returns zero. Hooks must never change Copilot permission decisions.
+ try
+ {
+ using var timeout = new CancellationTokenSource(TimeSpan.FromMilliseconds(600));
+ var buffer = new char[LocalPipe.MaximumMessageBytes + 1];
+ var length = 0;
+ while (length < buffer.Length)
+ {
+ var read = await Console.In.ReadAsync(buffer.AsMemory(length), timeout.Token);
+ if (read == 0) break;
+ length += read;
+ }
+ if (length > LocalPipe.MaximumMessageBytes) return 0;
+ var item = AgentEvents.Parse(settings.Source, settings.Event, new string(buffer, 0, length));
+ if (item is null) return 0;
+ var bytes = JsonSerializer.SerializeToUtf8Bytes(item);
+ if (bytes.Length > LocalPipe.MaximumMessageBytes) return 0;
+ using var pipe = new NamedPipeClientStream(".", LocalPipe.Name, PipeDirection.Out,
+ PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
+ await pipe.ConnectAsync(timeout.Token);
+ await pipe.WriteAsync(bytes.Concat(new byte[] { 10 }).ToArray(), timeout.Token);
+ await pipe.FlushAsync(timeout.Token);
+ }
+ catch (Exception) { /* A missing host or invalid hook input must not break Copilot. */ }
+ return 0;
+ }
+}
+public sealed class HostSettings : TargetSettings
+{
+ [CommandOption("--profile ")]
+ public string? Profile { get; init; }
+ [CommandOption("--model ")]
+ public DeviceModel? Model { get; init; }
+ [CommandOption("--log-file ")]
+ public string? LogFile { get; init; }
+ [CommandOption("--background")]
+ public bool Background { get; init; }
+ [CommandOption("--plain")]
+ [Description("Write plain state changes instead of terminal panels.")]
+ public bool Plain { get; init; }
+ public override ValidationResult Validate()
+ {
+ var result = base.Validate();
+ return !result.Successful ? result : Model is { } model && !Enum.IsDefined(model) ? ValidationResult.Error("Choose dot or pro.") : ValidationResult.Success();
+ }
+}
+public sealed class HostCommand : AsyncCommand
+{
+ public override async Task ExecuteAsync(CommandContext context, HostSettings settings, CancellationToken cancellationToken)
+ {
+ var patterns = AnimationLibrary.ResolveProfile(settings.Profile, settings.Model, settings.Device);
+ if (settings.Background) HostLogs.Detach();
+ using var shutdown = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ ConsoleCancelEventHandler cancel = (_, args) => { args.Cancel = true; shutdown.Cancel(); };
+ Console.CancelKeyPress += cancel;
+ var sessions = new Sessions();
+ AgentState? queued = null;
+ var outputs = Channel.CreateBounded(new BoundedChannelOptions(1)
+ {
+ SingleReader = true, SingleWriter = true, FullMode = BoundedChannelFullMode.DropOldest
+ });
+ var delivery = Task.Run(async () =>
+ {
+ try
+ {
+ await foreach (var program in outputs.Reader.ReadAllAsync(shutdown.Token))
+ {
+ try { await Delivery.Send(settings, program, shutdown.Token); }
+ catch (Exception ex) when (ex is IOException or ArgumentException or OperationCanceledException)
+ {
+ Console.Error.WriteLine("Output unavailable; check the device, token environment variable or network.");
+ }
+ }
+ }
+ catch (OperationCanceledException) when (shutdown.IsCancellationRequested) { }
+ }, CancellationToken.None);
+ if (!settings.Json) AnsiConsole.WriteLine("SidePulse.NET host | Ctrl+C to stop | session state starts unknown");
+ try
+ {
+ // FirstPipeInstance prevents competing hosts from accepting alternate events.
+ using var lease = LocalPipe.AcquireHostLease();
+ using var pipe = new NamedPipeServerStream(LocalPipe.Name, PipeDirection.InOut, 1,
+ PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly | PipeOptions.FirstPipeInstance);
+ while (!shutdown.IsCancellationRequested)
+ {
+ await pipe.WaitForConnectionAsync(shutdown.Token);
+ try
+ {
+ using var deadline = CancellationTokenSource.CreateLinkedTokenSource(shutdown.Token);
+ deadline.CancelAfter(TimeSpan.FromSeconds(1));
+ using var message = new MemoryStream();
+ var buffer = new byte[1];
+ while (message.Length <= LocalPipe.MaximumMessageBytes)
+ {
+ var count = await pipe.ReadAsync(buffer, deadline.Token);
+ if (count == 0 || buffer[0] == 10) break;
+ message.Write(buffer, 0, count);
+ }
+ if (message.Length > LocalPipe.MaximumMessageBytes) continue;
+ using var request = JsonDocument.Parse(message.ToArray());
+ if (request.RootElement.TryGetProperty("ProtocolVersion", out var protocol) && (!protocol.TryGetInt32(out var version) || version != 1)) continue;
+ if (request.RootElement.TryGetProperty("Command", out var command))
+ {
+ var action = command.GetString();
+ if (action is "status" or "stop" or "reset")
+ {
+ if (action == "reset")
+ {
+ sessions.Clear();
+ queued = AgentState.Unknown;
+ outputs.Writer.TryWrite(patterns[AgentState.Unknown]);
+ }
+ var response = JsonSerializer.SerializeToUtf8Bytes(new HostSnapshot(true, Environment.ProcessId, sessions.State, sessions.Snapshot));
+ await pipe.WriteAsync(response.Concat(new byte[] { 10 }).ToArray(), deadline.Token);
+ await pipe.FlushAsync(deadline.Token);
+ // Windows disconnect discards unread reply bytes. Wait for a bounded receipt
+ // acknowledgement before disconnecting; no unbounded pipe drain is needed.
+ await pipe.ReadExactlyAsync(new byte[1], deadline.Token);
+ if (action == "stop") shutdown.Cancel();
+ }
+ continue;
+ }
+ var item = JsonSerializer.Deserialize(message.ToArray());
+ if (item is null || !Enum.IsDefined(item.State) || !sessions.Apply(item)) continue;
+ var state = sessions.State;
+ if (settings.Json) Output.Print(new { state, sessions = sessions.Snapshot });
+ else if (settings.Plain || Console.IsOutputRedirected) Console.WriteLine($"{DateTimeOffset.Now:HH:mm:ss} {state} ({sessions.Snapshot.Count} sessions)");
+ else
+ {
+ var table = new Table().Border(TableBorder.Rounded).AddColumn("Agent").AddColumn("Session").AddColumn("Status");
+ foreach (var session in sessions.Snapshot)
+ table.AddRow(session.Provider.ToString(), Markup.Escape(session.Id), $"[{Output.Color(session.State)}]{session.State}[/]");
+ AnsiConsole.Write(table);
+ }
+ // Delivery runs separately so bridge latency cannot block pipe acceptance.
+ // The bounded queue keeps the latest state during slow network delivery.
+ // Re-enqueue repeated states to recover after a failed delivery.
+ if (state != queued || !settings.DryRun)
+ {
+ outputs.Writer.TryWrite(patterns[state]);
+ queued = state;
+ }
+ }
+ catch (Exception ex) when (ex is JsonException or InvalidOperationException or IOException or OperationCanceledException) { }
+ finally { pipe.Disconnect(); }
+ }
+ }
+ catch (OperationCanceledException) when (shutdown.IsCancellationRequested) { }
+ finally
+ {
+ shutdown.Cancel();
+ outputs.Writer.TryComplete();
+ await delivery;
+ Console.CancelKeyPress -= cancel;
+ }
+ return 0;
+ }
+}
+public sealed class HookConfigSettings : CommandSettings
+{
+ [CommandOption("--exe ")]
+ [Description("Absolute path to a published sidepulse-net executable.")]
+ public string Executable { get; init; } = Environment.ProcessPath ?? "sidepulse-net";
+ [CommandOption("--output ")]
+ [Description("Create a NEW hook file. Existing files are never overwritten. Otherwise prints JSON.")]
+ public string? OutputPath { get; init; }
+}
+public sealed class HookConfigCommand : Command
+{
+ public override int Execute(CommandContext context, HookConfigSettings settings, CancellationToken cancellationToken)
+ {
+ var exe = HookConfiguration.Executable(settings.Executable);
+ var json = HookConfiguration.Generate(AgentProvider.Copilot, exe, OperatingSystem.IsWindows()).ToJsonString(Output.Json) + Environment.NewLine;
+ if (settings.OutputPath is { } path)
+ {
+ using var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
+ using var writer = new StreamWriter(file, new UTF8Encoding(false));
+ writer.Write(json);
+ AnsiConsole.WriteLine("Created hook configuration. Restart Copilot CLI after installing it in your hooks directory.");
+ }
+ else Console.Write(json);
+ return 0;
+ }
+}
diff --git a/src/SidePulse.Cli/HostLogs.cs b/src/SidePulse.Cli/HostLogs.cs
new file mode 100644
index 0000000..ab9ba0d
--- /dev/null
+++ b/src/SidePulse.Cli/HostLogs.cs
@@ -0,0 +1,78 @@
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Text;
+using SidePulse.Core;
+using Spectre.Console;
+using Spectre.Console.Cli;
+
+namespace SidePulse.Cli;
+
+public static class HostLogs
+{
+ public static string PathName => Path.Combine(Path.GetDirectoryName(LinkStore.DefaultPath)!, "host", "host.log");
+ public static IDisposable? Redirect(string[] args)
+ {
+ if (args.Length < 2 || args[0] != "host" || args[1] != "run") return null;
+ var position = Array.IndexOf(args, "--log-file");
+ if (position < 0 || position + 1 >= args.Length) return null;
+ var writer = new RollingWriter(Path.GetFullPath(args[position + 1]));
+ var originalOut = Console.Out;
+ var originalError = Console.Error;
+ var sync = TextWriter.Synchronized(writer);
+ Console.SetOut(sync);
+ Console.SetError(sync);
+ return new Restore(originalOut, originalError, sync);
+ }
+ private sealed class Restore(TextWriter output, TextWriter error, TextWriter writer) : IDisposable
+ {
+ public void Dispose() { Console.SetOut(output); Console.SetError(error); writer.Dispose(); }
+ }
+ private sealed class RollingWriter(string path) : TextWriter
+ {
+ private StreamWriter? writer;
+ public override Encoding Encoding => Encoding.UTF8;
+ private StreamWriter Open()
+ {
+ if (writer is not null && writer.BaseStream.Length < 1048576) return writer;
+ writer?.Dispose();
+ if (File.Exists(path) && new FileInfo(path).Length >= 1048576) File.Move(path, path + ".previous", true);
+ var options = new FileStreamOptions { Mode = FileMode.Append, Access = FileAccess.Write, Share = FileShare.ReadWrite | FileShare.Delete };
+ if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
+ writer = new StreamWriter(new FileStream(path, options), new UTF8Encoding(false)) { AutoFlush = true };
+ return writer;
+ }
+ public override void Write(char value) => Open().Write(value);
+ public override void Write(string? value) => Open().Write(value);
+ public override void Flush() => writer?.Flush();
+ protected override void Dispose(bool disposing) { if (disposing) writer?.Dispose(); base.Dispose(disposing); }
+ }
+ public static void Detach()
+ {
+ if (!OperatingSystem.IsWindows() && setsid() < 0) throw new IOException("Could not detach the host from its terminal session.");
+ }
+ [DllImport("libc", SetLastError = true)] private static extern int setsid();
+}
+public sealed class HostLogsSettings : CommandSettings
+{
+ [CommandOption("--tail ")]
+ [DefaultValue(50)]
+ public int Tail { get; init; } = 50;
+ public override ValidationResult Validate() => Tail is >= 1 and <= 500 ? ValidationResult.Success() : ValidationResult.Error("Tail must be between 1 and 500.");
+}
+public sealed class HostLogsCommand : Command
+{
+ public override int Execute(CommandContext context, HostLogsSettings settings, CancellationToken cancellationToken)
+ {
+ if (!File.Exists(HostLogs.PathName)) { AnsiConsole.WriteLine("No background host log exists yet."); return 0; }
+ using var file = new FileStream(HostLogs.PathName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
+ using var reader = new StreamReader(file);
+ var lines = new Queue();
+ while (reader.ReadLine() is { } line)
+ {
+ lines.Enqueue(line);
+ if (lines.Count > settings.Tail) lines.Dequeue();
+ }
+ foreach (var line in lines) Console.WriteLine(line);
+ return 0;
+ }
+}
diff --git a/src/SidePulse.Cli/HostManagement.cs b/src/SidePulse.Cli/HostManagement.cs
new file mode 100644
index 0000000..b22a4f2
--- /dev/null
+++ b/src/SidePulse.Cli/HostManagement.cs
@@ -0,0 +1,126 @@
+using System.ComponentModel;
+using System.Diagnostics;
+using System.IO.Pipes;
+using System.Text;
+using System.Text.Json;
+using SidePulse.Core;
+using Spectre.Console;
+using Spectre.Console.Cli;
+
+namespace SidePulse.Cli;
+
+public sealed record HostSnapshot(bool Running, int? ProcessId, AgentState State, IReadOnlyList Sessions, int ProtocolVersion = 1);
+public static class HostControl
+{
+ public static async Task Request(string command, CancellationToken cancellationToken)
+ {
+ using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ deadline.CancelAfter(TimeSpan.FromSeconds(2));
+ using var pipe = new NamedPipeClientStream(".", LocalPipe.Name, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
+ try { await pipe.ConnectAsync(deadline.Token); }
+ catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { return new(false, null, AgentState.Unknown, []); }
+ await pipe.WriteAsync(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { Command = command, ProtocolVersion = 1 }) + "\n"), deadline.Token);
+ await pipe.FlushAsync(deadline.Token);
+ using var reader = new StreamReader(pipe, Encoding.UTF8);
+ var response = await reader.ReadLineAsync(deadline.Token) ?? throw new IOException("The host closed without a response.");
+ await pipe.WriteAsync(new byte[] { 10 }, deadline.Token);
+ await pipe.FlushAsync(deadline.Token);
+ var snapshot = JsonSerializer.Deserialize(response, Output.Json) ?? throw new IOException("Invalid host response.");
+ if (snapshot.ProtocolVersion != 1) throw new IOException("Host protocol mismatch. Stop the old host and use matching CLI/host versions.");
+ return snapshot;
+ }
+}
+public sealed class HostActionSettings : CommandSettings
+{
+ [CommandOption("--json")]
+ public bool Json { get; init; }
+}
+public sealed class HostStatusCommand : AsyncCommand
+{
+ public override async Task ExecuteAsync(CommandContext context, HostActionSettings settings, CancellationToken cancellationToken)
+ {
+ var state = await HostControl.Request("status", cancellationToken);
+ if (settings.Json) Output.Print(state);
+ else AnsiConsole.WriteLine(state.Running ? $"Host running (PID {state.ProcessId}), {state.State}, {state.Sessions.Count} sessions." : "Host is not running.");
+ return 0;
+ }
+}
+public sealed class HostStopCommand : AsyncCommand
+{
+ public override async Task ExecuteAsync(CommandContext context, HostActionSettings settings, CancellationToken cancellationToken)
+ {
+ var state = await HostControl.Request("stop", cancellationToken);
+ if (state.Running)
+ {
+ for (var attempt = 0; attempt < 25; attempt++)
+ {
+ await Task.Delay(100, cancellationToken);
+ if (!(await HostControl.Request("status", cancellationToken)).Running) break;
+ if (attempt == 24) throw new IOException("The host acknowledged stop but has not exited. No process was forcibly killed.");
+ }
+ }
+ if (settings.Json) Output.Print(new { stopped = state.Running });
+ else AnsiConsole.WriteLine(state.Running ? "Host stopped." : "Host was not running.");
+ return 0;
+ }
+}
+public sealed class HostStartSettings : TargetSettings
+{
+ [CommandOption("--profile ")] public string? Profile { get; init; }
+ [CommandOption("--model ")] public DeviceModel? Model { get; init; }
+ [CommandOption("--exe ")]
+ public string Executable { get; init; } = Environment.ProcessPath ?? "sidepulse-net";
+ public override ValidationResult Validate()
+ {
+ var result = base.Validate();
+ return !result.Successful ? result : Model is { } model && !Enum.IsDefined(model) ? ValidationResult.Error("Choose dot or pro.") : ValidationResult.Success();
+ }
+}
+public sealed class HostStartCommand : AsyncCommand
+{
+ public override async Task ExecuteAsync(CommandContext context, HostStartSettings settings, CancellationToken cancellationToken)
+ {
+ var existing = await HostControl.Request("status", cancellationToken);
+ if (existing.Running) { if (settings.Json) Output.Print(existing); else AnsiConsole.WriteLine("Host is already running. Stop it before changing its target."); return 0; }
+ _ = AnimationLibrary.ResolveProfile(settings.Profile, settings.Model, settings.Device);
+ var exe = HookConfiguration.Executable(settings.Executable);
+ var directory = Path.Combine(Path.GetDirectoryName(LinkStore.DefaultPath)!, "host");
+ if (OperatingSystem.IsWindows()) Directory.CreateDirectory(directory);
+ else Directory.CreateDirectory(directory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+ var log = Path.Combine(directory, "host.log");
+ var info = new ProcessStartInfo(exe) { UseShellExecute = OperatingSystem.IsWindows(), WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true,
+ RedirectStandardInput = !OperatingSystem.IsWindows(), RedirectStandardOutput = !OperatingSystem.IsWindows(),
+ RedirectStandardError = !OperatingSystem.IsWindows(), WorkingDirectory = Path.GetDirectoryName(exe)! };
+ foreach (var value in new[] { "host", "run", "--plain", "--background", "--log-file", log }) info.ArgumentList.Add(value);
+ if (settings.Device is { } device) { info.ArgumentList.Add("--device"); info.ArgumentList.Add(Path.GetFullPath(device)); }
+ if (settings.Phone is { } phone) { info.ArgumentList.Add("--phone"); info.ArgumentList.Add(phone); }
+ if (settings.TokenEnvironment is { } variable) { info.ArgumentList.Add("--token-env"); info.ArgumentList.Add(variable); }
+ if (settings.Profile is { } profile) { info.ArgumentList.Add("--profile"); info.ArgumentList.Add(profile); }
+ if (settings.Model is { } model) { info.ArgumentList.Add("--model"); info.ArgumentList.Add(model.ToString()); }
+ if (settings.DryRun) info.ArgumentList.Add("--dry-run");
+ using var process = Process.Start(info) ?? throw new IOException("Could not start the host.");
+ if (!OperatingSystem.IsWindows()) process.StandardInput.Close();
+ for (var attempt = 0; attempt < 5; attempt++)
+ {
+ if (process.HasExited) throw new IOException("Host exited during startup. Check host.log in the configuration directory.");
+ var started = await HostControl.Request("status", cancellationToken);
+ if (started.Running)
+ {
+ if (settings.Json) Output.Print(started); else AnsiConsole.WriteLine($"Host started (PID {started.ProcessId}). Log: {log}");
+ return 0;
+ }
+ }
+ throw new IOException("Host readiness could not be confirmed. Use host status before retrying.");
+ }
+}
+
+public sealed class HostResetCommand : AsyncCommand
+{
+ public override async Task ExecuteAsync(CommandContext context, HostActionSettings settings, CancellationToken cancellationToken)
+ {
+ var result = await HostControl.Request("reset", cancellationToken);
+ if (settings.Json) Output.Print(result);
+ else Console.WriteLine(result.Running ? "Session history cleared; status is Unknown until the next agent event." : "Host is not running.");
+ return result.Running ? 0 : 1;
+ }
+}
diff --git a/src/SidePulse.Cli/Interactive.cs b/src/SidePulse.Cli/Interactive.cs
new file mode 100644
index 0000000..ea6e74d
--- /dev/null
+++ b/src/SidePulse.Cli/Interactive.cs
@@ -0,0 +1,165 @@
+using SidePulse.Core;
+using Spectre.Console;
+using Spectre.Console.Rendering;
+
+namespace SidePulse.Cli;
+
+public sealed record MenuItem(string Label, string[]? Arguments = null);
+public static class Interactive
+{
+ public static string[]? Resolve(string[] args)
+ {
+ if (!TerminalMode.Interactive)
+ {
+ if (args.Length == 0) return ["--help"];
+ if (args.Length == 1 && args[0] is "about" or "animations" or "agents" or "link" or "host" or "profiles") return [args[0], "--help"];
+ return args;
+ }
+ if (args.Length > 1 || args.Length == 1 && args[0] is not ("about" or "animations" or "agents" or "link" or "host" or "profiles" or "update")) return args;
+ var group = args.FirstOrDefault();
+ while (true)
+ {
+ if (group is null)
+ {
+ var selected = Choose("SidePulse.NET", [new("Animations"), new("Devices", ["devices"]), new("Display state"), new("Agent hooks"), new("Background host"), new("Phone links"), new("Profiles"), new("Diagnostics", ["doctor"]), new("Updates"), new("About")]);
+ if (selected is null) return null;
+ if (selected.Arguments is { } direct) return direct;
+ group = selected.Label switch { "Animations" => "animations", "Agent hooks" => "agents", "Background host" => "host", "Phone links" => "link", "Profiles" => "profiles", "About" => "about", "Updates" => "update", _ => "state" };
+ }
+ var command = Build(group);
+ if (command is not null) return command;
+ group = null;
+ }
+ }
+ public static MenuItem? Choose(string title, IReadOnlyList