fader_master/task.md

685 lines
56 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Implementation tasks
This is the build plan for `architecture.md`. Checked boxes record verified acceptance criteria. Follow `AGENTS.md`: one local commit per passing behavior/test increment, with the implementation and test together. A milestone below normally needs several commits; do not make one giant milestone commit or separate failing-test commits. Record focused test commands/results in commit bodies.
## Planning delivered
Current user-facing baseline: live MIDI/Pulse server and TUI, all-in-one or
split processes, managed profile switching, guided fader editing, configurable
separators including unnamed spacers, themes, and pickup presentation.
Historical milestone notes below describe incremental delivery; unchecked
boxes still require their remaining acceptance evidence.
- [x] Inspect the workspace and define the project-steward role in `AGENTS.md`.
- [x] Specify state ownership, adapter boundaries, matching/groups, MIDI identity/feedback, and TOML lifecycle in `architecture.md`.
- [x] Research libraries using linked primary documentation and identify bounded technical spikes.
- [x] Define implementation order, acceptance tests, and requirement coverage below.
Planning validation: parse the architecture's TOML example, verify local Markdown links and cross-references, check all 15 requirements are mapped below, and run `git diff --check`. No runtime behavior is changed by these documents.
Baseline test attempt on 2026-10-05: `cargo test --workspace --all-targets --offline` could not run because `compact_str v0.8.2` was not cached. This is an environment/dependency limitation, not a passing suite or evidence of a code failure. Cargo generated an ignored lockfile during resolution. Foundation work must establish a complete baseline with dependencies available.
## M0 — Reproducible Rust foundation
Dependencies: planning.
- [x] **M0.1 Toolchain and build:** select/test an MSRV and pinned toolchain, centralize workspace metadata/dependencies, track Cargo.lock for the executable, document native build prerequisites. Acceptance: a fresh supported Linux checkout builds and tests reproducibly with `--locked`; the chosen MSRV builds the chosen dependency set.
- [ ] **M0.2 CI gates:** align Jenkins with AGENTS.md, including doctests, Clippy `-D warnings`, release build and later backend feature matrix. Acceptance: representative formatting/lint/test failures fail the pipeline; default and full-feature builds pass with provisioned dependencies.
Repository configuration now runs locked default, no-default-features, and all-features checks/tests plus warning-strict documentation, Clippy, and release gates. Keep this open until a real Jenkins run on the provisioned worker passes.
While the only worker is FreeBSD, the `ENABLE_NATIVE_BACKENDS=false` default
runs explicit portable-package gates and honestly marks coverage unavailable.
Enabling that build parameter restores the full existing Linux/native matrix;
M0.2 remains open until that mode passes on a provisioned Linux worker.
- [x] **M0.2a Coverage badges:** measure locked all-target line coverage with a pinned tool, enforce the documented 20% scaffold floor, and generate/archive the version, test, and coverage badges on every build. Publish atomically only from `main`, with fresh-build markers preventing stale test or coverage values. Acceptance: renderer, coverage lifecycle, finalization, and publication fixture tests pass; the real local measurement is above the floor. Jenkins publication and public retrieval remain deployment checks.
- [x] **M0.3 Domain boundary:** add `fader-core` and `fader-config`, wire current crates inward, remove placeholder arithmetic tests as real contracts replace them. Acceptance: core tests run without a terminal, sound daemon, native device connection, or Tokio runtime; dependency graph has no cycles.
## M1 — Domain state and virtual objects
Dependencies: M0.
- [x] **M1.1 Typed values:** stable IDs, finite gain, channel vectors, mute/availability/mixed states, revisions and backend epochs. Tests: invalid ranges/NaN/infinity rejected; gain/silence/channel-balance properties hold; IDs cannot be interchanged accidentally.
- [x] **M1.2 Application selectors:** normalized metadata, exact/regex matching, OR selectors, multiple live streams and offline objects. Tests: anchored/unanchored/case-sensitive cases, missing fields, malformed regex, stream creation/removal and backend ID reuse.
- [x] **M1.3 Fader resolution:** surface binding -> fader -> application/group -> deduplicated live streams. Tests: identical CCs on different surfaces stay separate, multiple faders can share an object, and overlap never writes the same stream twice per operation.
- [x] **M1.4 Group gain:** active absolute/sync planning plus a prepared
relative-group domain state with per-member independent/external maxima,
channel balance, reversible zero, normalized position, lifecycle removal,
aggregate max/mixed state, and clipping. Tests: heterogeneous members,
externally changed member anchors, zero-to-maximum recovery, empty group,
late joiner behavior, and partial failure. Runtime profile validation keeps
`relative` reserved and accepts only `absolute` groups.
- [x] **M1.5 Mute:** explicit set/toggle independent of volume. Tests: mixed-group toggle mutes all, fully muted toggle unmutes all, two rapid toggles cancel logically, zero gain does not imply mute, and unmute does not alter gain.
M1 verification on 2026-10-05: 30 unit/integration/property tests and one
compile-fail doctest pass. Locked workspace formatting, all-target/all-feature
checks/tests, doctests, strict Clippy, release/default/no-default-feature builds,
no-default-feature tests, warning-strict rustdoc, and CI script fixtures pass on
Linux with Rust 1.88.0. Line coverage is 83.2487309645% against the unchanged 20%
floor. Group partial-failure tests operate on observed domain snapshots; native
dispatch and asynchronous operation correlation remain M3 work. M0.2 still
requires a real Jenkins run. Per user direction, stop here before starting M2.
## M2 — TOML schemas and safe persistence
Dependencies: M1 types; runtime activation follows in M10.
- [x] **M2.1 Schema and validation:** profile, application/group/fader/binding/device, and state schemas; check all references and capabilities. Tests: architecture example parses semantically, round trip preserves meaning, invalid IDs/duplicate bindings/unknown fields/schema versions fail with useful paths, all supported MIDI ranges are checked.
The strict version-1 profile, reusable device-capability, and persisted-state
documents now validate before construction. The architecture TOML block and
checked-in example are test-locked to one another; five integration tests
cover semantic round trips, reference/capability failures, unknown fields,
versions, duplicates, and MIDI channel/data endpoints.
- [x] **M2.2 Atomic files:** XDG paths, same-directory temp/rename/fsync, restrictive ownership, comment-preserving edits and migration backups. Tests: disk/permission/write failures keep the old document readable; malformed/missing state is recoverable; unsafe profile paths and incompatible migrations are rejected.
XDG roots now resolve with specification fallbacks and no shared runtime
fallback. Private layout creation, effective-owner/symlink checks, mode-0600
streaming atomic writes, directory sync, recoverable state loading,
comment-preserving validated edits, and backed-up forward migration are
covered by seven persistence integration tests. Optional default-empty profile
arrays may remain omitted: editor additions materialize them lazily and empty
removals are no-ops, while malformed present sections still fail startup
validation.
- [x] **M2.3 Checkpoints:** per-profile observed state and separate validated desired object volume/mute, surface assignments, UI preferences, debounce and shutdown flush. Tests with a fake clock: sustained movement causes bounded writes and final state persists; crash/restart treats cached observations as stale, never restores runtime IDs or pending requests; an offline command survives restart as saved intent but only explicit restore applies it when the application launches (adopt emits no write).
A runtime-independent monotonic coordinator now keeps only the newest complete
snapshot, flushes after 500 ms quiet or two seconds continuously dirty, retries
failed writes without discarding pending state, and flushes on shutdown. Five
fake-clock tests cover timing, final persistence, typed checkpoint mutations,
stale restart observations, absent ephemeral state, and bounded explicit
restore behavior.
M2 verification on 2026-10-14: 17 configuration integration tests pass alongside
the existing 30 core tests and compile-fail doctest. Locked formatting,
all-target/all-feature checks and tests, doctests, strict Clippy, release build,
and no-default-feature checks/tests pass on Rust 1.88.0. M0.2 still requires a
real Jenkins run.
## M3 — Server and fake-adapter vertical slice
Dependencies: M1, M2. No real USB/audio device required.
- [x] **M3.1 Reducer/effects:** one owner, command origins/revisions, desired/pending/observed state. Tests: accepted intent is recorded before adapter dispatch; success requires readback/observation; failure leaves actual state truthful; external changes update views without an outgoing audio command.
- [x] **M3.2 Worker contract:** capabilities, snapshot barriers, readback, per-property ordered writes, operation results and fake backend. Tests: changes during snapshot are reconciled, old epoch/incarnation events are ignored, stream removal during write is handled, and newer pending intent survives an older completion.
- [x] **M3.3 Load and ordering:** bounded channels, latest-volume coalescing, preserved mute ordering, overflow fault reporting. Tests: burst ends at latest value, toggles are not silently lost or guessed, memory stays bounded, and final readback resolves ambiguous acknowledgments.
- [x] **M3.4 Lifecycle:** startup adopt, optional explicit restore, unavailable status, reconnect/backoff and orderly shutdown. Tests: startup emits no writes by default; reconnect resnapshots; restore conflict order is deterministic; disconnect expires in-flight state; cancellation joins workers and flushes state.
Exit: simulated MIDI input changes a virtual object through a fake adapter; observation generates a confirmed snapshot and feedback effect.
M3 verification on 2026-10-14: the pure reducer records desired and pending
state before dispatch and publishes only adapter observations as confirmation.
The fake adapter implements capability reporting, snapshot barriers, readback,
failure/removal behavior, and stale epoch/incarnation rejection. Its bounded
dispatch lane coalesces only volume motion and reports mute-edge overflow.
The in-process lifecycle slice covers adopt/restore policy, bounded retry,
disconnect invalidation, final draining/checkpointing, and simulated MIDI
volume intent converging through fake write acceptance and readback.
## M4 — PulseAudio adapter and real audio slice
Dependencies: M3.
- [ ] **M4.1 Bounded API spike:** verify libpulse-binding event loop, sink-input enumeration/properties, native volume conversion, change subscriptions and readback on PulseAudio and pipewire-pulse. Record native prerequisites and visibility limitations. Acceptance: isolated test streams are discovered and volume/mute changes are observed in both directions; no shell parsing in the production path.
The pinned binding now compiles against libpulse 17 on Rust 1.88, with
feature-gated no-backend builds. A no-autospawn client implements sink-input
enumeration, normalized metadata copies, linear multichannel conversion,
volume/mute writes, and mandatory readback. Manual verification on 2026-10-14
passed discovery, balanced volume/mute control, subscriptions, external mixer
changes, and stream churn against PipeWire 1.6.9 through `pipewire-pulse` on
Arch Linux. Keep this item open until the isolated fixture also verifies a
standalone PulseAudio server.
- [x] **M4.2 Implement worker:** own native handles on their loop thread; copy callback data; reconcile enumeration races. Contract tests: add/remove/change, operation error, unavailable daemon, reconnect, balanced stereo and multichannel conversion, external mixer edit.
The bounded Pulse worker creates and retains all native objects on its owner
thread, subscribes before snapshotting, replays queued notifications before
the snapshot barrier, and copies metadata and observations across the event
lane. Per-epoch incarnation tracking rejects stale commands and distinguishes
reused sink-input indexes. Contract tests cover connection failure, reconnect
epochs, add/change/remove and external edits, stereo/multichannel writes,
rejected operations, stale handles, and explicit overflow-driven resync.
- [x] **M4.3 Adapter policy:** configured/CLI override, auto probe order/capabilities, diagnostics and feature errors. Tests: manual failure never falls back; auto chooses one authority, skips incapable candidates and never substitutes ALSA Master for applications; disconnect follows retry policy.
Validated profile choices and ordered preferences now translate into a typed
runtime policy, with a non-persistent session/CLI override taking precedence.
Probes retain server identity, capability, availability, and unbuilt-feature
diagnostics. Auto mode stops at its first capable authority; manual mode
never falls back; application profiles reject hardware-only candidates.
Disconnect backoff remains pinned to the selected authority until a reload.
- [x] **M4.4 Real-daemon fixture:** isolated playback streams and external control client. Acceptance: server command and external change both converge to the observed value/mute; stream churn and daemon restart recover. Document commands and opt-in fixture requirements; do not label mocks as hardware verification.
An opt-in fixture now creates a uniquely named silent `paplay` stream and
verifies real worker volume/mute writes, independent-client edits, readback,
removal, and replacement without targeting other desktop streams. That phase
passed against PipeWire 1.6.9 through `pipewire-pulse` on 2026-10-14. A
separately acknowledged test restarts the known PipeWire user services and
requires disconnect, bounded retry, a new epoch, and a complete resnapshot.
That disruptive phase passed on 2026-10-15: it observed epoch 20 disconnect,
epoch 21 reconnect, and a complete fresh snapshot. The same stream fixture can
target an isolated standalone PulseAudio server through `PULSE_SERVER`.
- [ ] **M4.5 Default output master:** expose the Pulse server's current default
output as a stable logical target; subscribe to sink/default changes and keep
application streams distinct. Tests: balanced output volume and mute use
confirmed readback, external changes re-arm pickup, a default-sink switch
invalidates the old handle, and application commands cannot reach an output.
The Pulse worker, profile schema, live mixer, IPC, and TUI now carry a
dedicated `output/default` object. The Arch profile assigns the APC master
strip CC 56 / Note 98 to it and moves Media to CC 50 / Note 66. Keep this
item open until the physical output checklist passes on PipeWire/Pulse.
M4.2 verification on 2026-10-14: the scripted worker contract suite passes
without an audio daemon, and a read-only owner-thread smoke run against PipeWire
1.6.9 through `pipewire-pulse` produced a framed snapshot of live application
streams. Locked workspace formatting, all-target/all-feature checks and tests,
doctests, strict Clippy, release build, and no-default-feature checks/tests pass
on Rust 1.88.0. M4.1 still awaits the standalone PulseAudio fixture, and M0.2
still requires a real Jenkins run.
M4.3 verification on 2026-10-14: deterministic policy tests cover manual and
automatic selection, session override precedence, incapable/unavailable
candidates, ALSA application rejection, compiled-feature errors, single
authority, and bounded same-backend reconnect. A read-only auto probe selected
the Pulse adapter and reported `PulseAudio (on PipeWire 1.6.9)` version 15.0.0;
an explicit native PipeWire request failed visibly without fallback.
## M5 — MIDI transport, device identity, and first controller
Dependencies: M3; M4 for full end-to-end acceptance.
- [x] **M5.1 Decode/bind:** midir connections; absolute 7-bit CC, note/CC press/release; validate channels/data. Tests: malformed/truncated messages, note-on zero, ignored clock traffic, unknown controls, duplicate press policy and surface-specific routing.
The feature-gated `midir` 0.11.1 transport enumerates opaque port IDs and
names, owns each input connection, and copies decoded events into a bounded
nonblocking callback lane with explicit overflow state. The pure decoder and
surface-scoped router cover every channel and 7-bit endpoint, press/release
normalization, press-only toggles, unrelated traffic, and malformed input.
An opt-in monitor lists real ports and watches one selected input without
changing audio or saved configuration.
- [ ] **M5.2 Identity spike:** inspect port identifiers and ALSA/udev USB mapping; establish serial/path/manual fallback policy. Acceptance: record metadata actually exposed by tested controllers, distinguish two identical models where possible, and demonstrate explicit ambiguity resolution where not possible.
The Linux probe now maps midir's ALSA `client:port` through the sequencer
client card number to udev, copying VID/PID, serial, and physical path. Pure
policy tests prove serial and path matching survive port reorder and that two
identical serial-less candidates stay ambiguous until manually selected.
An Akai APC MINI (USB 09e8:0028, firmware-reported serial `Ver00.10`) was
observed on 2026-10-15. Its serial and ALSA backend ID `36:0` remained stable
across USB sockets while its udev path changed, validating serial-first
matching on real hardware. Keep this item open until the two-identical-device
ambiguity cases in the checklist can be exercised.
- [ ] **M5.3 Multi-surface lifecycle:** persist user IDs and independent input/output assignment; hotplug scanning/notification, retries and absent placeholders. Tests: unplug/replug/reboot-style port reorder preserve assignments; ambiguous serial-less matches stay unassigned; one failed device does not stop another.
The server now scans on a bounded interval, matches validated VID/PID and
serial/path hints, owns independent bounded input connections, and publishes
connected/missing/ambiguous/error placeholders through IPC and `status`.
Deterministic tests cover reorder, unplug/replug, ambiguity, duplicate claims,
retry after one connection failure, and isolation between surfaces. A live
smoke run connected the APC MINI as `36:0`; keep this item open for physical
unplug/replug acceptance and durable editor-managed assignment persistence.
- [ ] **M5.4 Pickup:** crossing/tolerance, current physical position, reset on external change/rebind/reconnect/profile switch. Tests: old physical position cannot jump audio at startup; crossing activates; another surface re-arms pickup; above-range target can be picked up at the endpoint.
The pure pickup state machine and routed live server cover startup inhibition,
tolerance and crossing activation, external-change/reconnect resets,
competing surfaces, and above-range endpoint pickup. The Arch profile routes
APC MINI CC 48/49/50/56 and notes 64/65/66/98 to Music, Browser, Media, and
the default output master. Input targeting an offline/read-only object is a
nonfatal no-op, leaving other targets and the server available. Keep this item
open for remaining physical multi-surface acceptance. Pickup snapshots and
profile-switch rearming are now implemented and covered by automated tests.
- [ ] **M5.5 Physical smoke test:** one controller -> server -> application audio; then two controllers with overlapping MIDI message numbers. Acceptance: correct applications respond, bindings persist, and USB loss leaves server running. Record controller/firmware and environment.
M5.1 verification on 2026-10-14: nine decoder/router/transport tests pass with
the native transport enabled, seven hardware-free tests pass without default
features, and the locked dependency set builds and tests on Rust 1.88.0. The
host ALSA sequencer probe initialized and enumerated port `14:0`; controller
traffic remains an opt-in checklist item. Locked workspace formatting,
all-target/all-feature checks and tests, doctests, strict Clippy, release build,
and no-default-feature checks/tests pass.
## M6 — Confirmed MIDI feedback
Dependencies: M4, M5.
- [x] **M6.0 Confirmed mute lights:** default same-note or configured note/CC feedback follows confirmed
uniform mute state, treats mixed as off, does not guess for offline targets,
deduplicates successful writes, and resynchronizes after independent output
reconnect. Output failures remain surface-local and do not disable MIDI
input or audio operation. Hardware-free planner tests cover on/off,
deduplication, unavailable state, surface scoping, and reconnect refresh;
physical LED verification remains part of M6.1.
- [ ] **M6.1 Output profiles:** mute LED/value/motor capabilities, output pairing, mixed-state policy. Tests: confirmed/internal and external changes reach all bound surfaces; outputless surfaces receive no unsupported message; pending/failed writes never produce false success feedback.
All note mute bindings now default to same-channel/same-note on=127/off=0
with an output port, including the first learned binding in an empty profile.
Device-specific protocols live in explicit feedback configuration rather than
USB-identity branches or note whitelists.
Tests cover save/reload, on/off, reconnect/deduplication, explicit overrides,
all channels/notes, and exclusion of outputless surfaces and volume controls.
Other device profiles and physical hardware verification remain outstanding.
- [ ] **M6.2 Feedback lifecycle:** attach snapshot, rate limits, deduplication, separate audio/output errors, documented device-specific echo suppression. Tests: feedback echoed as input cannot oscillate volume/mute; rapid updates converge; suppression does not swallow a genuine tested input sequence.
- [ ] **M6.3 Extended controllers:** 14-bit CC/pitch bend, explicit relative encoder modes, motor output and touch handling for declared profiles. Tests: endpoints/byte-pair ordering, relative increments, no motor push while touched, and non-motorized profile never receives motor commands. Hardware-verify every shipped specialized profile.
## M7 — Local server interface and CLI
Dependencies: M3, M2; may proceed after the fake-adapter slice.
- [x] **M7.1 CLI:** serve/tui/validate/devices/status/profile switch arguments and override precedence. Tests: help/errors, invalid config has no side effects, explicit override wins for the session without silently modifying disk.
Typed subcommands now validate profiles before probing audio or creating the
runtime socket. `serve`, `tui`, `validate`, `devices`, and `status` are active;
Transactional profile switching is now implemented by M10.1, including the
Config-tab profile picker.
A session audio override is applied only to runtime selection.
- [x] **M7.2 IPC:** owned Unix socket, one-instance lock, version negotiation, length-bounded TOML frames, request IDs and revisioned state. Tests: wrong peer permissions, oversized/truncated/incompatible messages, second server, stale socket recovery and slow/disconnected client.
The first local slice uses an owned mode-0600 socket, bounded request timeouts,
versioned/request-correlated 64-KiB TOML frames, revisioned snapshots,
one-instance detection, safe stale-socket replacement, same-UID Linux peer
authentication, and a 20-ms server-side frame deadline so stalled clients
cannot monopolize the state owner.
- [x] **M7.3 Client resync:** full snapshot on attach/lag and revision checks for edits. Tests: TUI exit never stops the server; reconnect shows current observations; concurrent clients cannot overwrite each other's edits unnoticed.
Each request receives a complete current snapshot; stale edit revisions
trigger bounded background resnapshot/retry attempts, covering consecutive
server revisions without allowing an unbounded retry loop. The TUI's IPC
client recognizes revision conflicts independent of their transport error
kind and renders any surfaced conflict as a warning rather than a fatal error.
worker exits independently of the server, starts with a disconnected placeholder when the
socket is absent, retains the last confirmed view during failures, and retries
until a server appears again. Competing edits from one attached revision prove
that only the first is accepted and that a lagging client obtains the newer
complete snapshot before retrying.
- [x] **M7.4 Buffered interaction:** isolate blocking IPC and native audio
round trips from input/rendering; coalesce unsent volume motion, preserve mute
edges, update the local view immediately, and converge on confirmed state.
Tests: a blocked client call does not block snapshot/redraw access, a volume
burst sends its first in-flight and final buffered values only, stale edits
resnapshot and retry, rapid mute presses remain ordered, and server dispatch
uses bounded backpressure rather than failing on a merely busy worker.
A TUI client thread owns IPC, publishes optimistic shared snapshots, polls at
20 ms while pending and 250 ms while idle, and retains a bounded 128-edge mute
FIFO. Quit restores the terminal before teardown; cooperative workers join in
a short grace period, while a worker stuck in a server request is detached so
it cannot block exit. The live server uses the tested 256-command coalescing
queue ahead of a one-slot Pulse command lane, an independent 256-event
snapshot lane, and a batch event drain. Matching Pulse subscription echoes
retain the originating operation so confirmed writes do not repeatedly re-arm
pickup during continuous physical fader motion; genuinely different external
observations still re-arm it. Profiles may tune the shared server/native
polling interval from 1 through 100 ms (`10` by default) without changing
bounded latest-value coalescing.
- [x] **M7.5 Combined and dedicated launchers:** provide
`fader_master_server`, `fader_master_client`, and an all-in-one `fader_master`
default mode. Combined mode reuses a responding per-user server, starts one
only when absent, resolves startup races through the owned socket, and stops
and joins only the server it created. Existing `serve` and `tui` subcommands
remain compatible. Tests: CLI parsing and binary help cover all three entry
points; the launch decision never invokes server startup after a successful
probe.
## M8 — Live TUI
Dependencies: M7, M4 for real use.
- [x] **M8.1 Mixer:** replace blocking prototype with event-driven client views and volume/mute actions. Test-backend assertions: groups/applications, mixed/offline/pending/error indicators, pickup state, resize and keyboard navigation reflect snapshots accurately.
The live slice now lists stable configured applications and groups, preserves
offline and mixed gain/mute states, deduplicates overlapping group streams,
and fans sync-group writes out with absolute policy. It refreshes without
blocking rendering or server operation, updates accepted input locally, and
shows pending, read-only, and error indicators.
Pickup state now follows configured surface/fader bindings through IPC and is
rendered as unavailable, waiting, tracking, or mixed. Profile-aware hands-on
checks including terminal resize passed on 2026-10-15. A later UI refinement
should add a denser row mode and/or horizontal fader layout for smaller
terminals.
- [x] **M8.2 Devices/status:** show adapter selection/probe errors, device mappings, ambiguity and persistence problems. Tests: disconnected/unsupported states have useful actions; manual backend selection validates rather than silently applying incompatible mappings.
The live TUI now preserves server-published MIDI placeholders and shows
connected backend IDs, connection progress, missing-device guidance,
ambiguity selection guidance, and transport errors in its compact status
line. Editor save/conflict failures now remain visible while the prior live
state and unsaved draft are retained.
- [x] **M8.3 Terminal lifecycle:** restoration on normal/error exit, nonblocking refresh, logging away from display. Tests: injected IO/client failure releases terminal guard; polling/refresh does not block server operation.
Blocking IPC runs on a joined worker and a delayed request cannot block redraw
access. The restoration guard is independently injected and proven to run
when client initialization returns an error; client/transport diagnostics are
rendered inside the TUI rather than printed into the active terminal.
- [ ] **M8.4 Relative-group activation (reserved):** wire the prepared
per-member maximum state into origin-aware runtime observations, lifecycle,
snapshots, pickup, and editor help before allowing `volume_mode = "relative"`
in profiles. Tests: group confirmations never rebase maxima; application MIDI,
TUI, and external edits rebase only the affected member; zero is reversible;
joins adopt live maxima and removals discard anchors. Do not enable this mode
in shipped profiles without a separate product decision.
- [x] **M8.5 Built-in themes (stretch):** centralize semantic TUI colors and
provide Default, Dracula, Nord, Gruvbox Dark, Catppuccin Mocha, and Solarized
Dark palettes. Profiles persist the selected palette; `tui --theme` is an
optional session override and `t` edits the profile draft. Tests: known CLI
names parse, unknown names fail, cycling wraps deterministically, and the
selected palette/name reach rendered cells.
First live TUI slice verification on 2026-10-15: a real server selected Pulse
against PipeWire, reached `ready`, and published the active Qobuz playback stream
through the private socket. A PTY-rendered client displayed its confirmed 9%
gain and restored the terminal on quit without stopping the server. Locked
workspace formatting, all-target/all-feature checks and tests, doctests, strict
Clippy, release build, no-default-feature checks/tests, and the complete Rust
1.88 all-feature test suite pass. M7.2, M7.3, and M8.1 remain open for the
explicit acceptance gaps noted above and in the hands-on checklist.
Hands-on acceptance on 2026-10-15 confirmed one-instance enforcement, live
multi-stream display, keyboard selection, confirmed volume/mute actions,
external-change refresh, stream churn, independent TUI exit/reconnect, and
terminal restoration against PipeWire 1.6.9. Terminal resize remains to be
checked alongside the next profile-aware TUI slice.
Profile-aware TUI verification on 2026-10-15: hardware-free tests cover stable
application/group rows, offline values, mixed gain/mute aggregation, group
write fan-out, pending state, stale-client resync, and small-terminal rendering.
A read-only live smoke run against PipeWire 1.6.9 matched the reported Qobuz
stream into `Music` and `Media group` while retaining `Browser` offline. All
workspace formatting, all-target/all-feature checks and tests, doctests, strict
Clippy, release build, default and no-default-feature tests, and isolated Pulse,
no-audio, midir, and no-MIDI feature checks pass on Rust 1.88.0.
The subsequent hands-on run passed application-isolated writes, two-member
absolute group writes, mixed gain/mute aggregation, offline/rejoin behavior,
resize, and reconnect. Waterfox initially remained offline because its reported
`Waterfox`/`waterfox-bin` metadata was absent from the example selector; the
regression-tested profile fix then matched it into the two-stream media group.
## M9 — TUI configuration editor
Dependencies: M8, M2, M1.
- [x] **M9.1 Editor drafts:** separate tab to create/edit/delete applications, groups and faders; target/member selection, matcher preview, validation errors and referenced-delete handling. Tests: invalid regex/dangling member rejected; Cancel has no side effects; creating a group/fader produces the expected semantic TOML.
Transactional, comment-preserving draft primitives now create applications,
absolute groups and faders, and roll back invalid regexes or referenced
deletes. A separate Config tab now shows the server-owned applications, group
membership, logical fader targets, pickup policy, and MIDI assignments. The
keyboard editor accepts explicit target/member IDs, previews live matcher
results, and provides the full create/update/delete surface with inline
validation errors and cancellation.
The server now owns the validated draft and its independent revision; stale
or invalid edit requests are rejected without advancing or altering it, and
accepted edits are exposed as an unsaved draft in the Config tab.
The Config tab also reports the server-resolved path of the loaded profile so
configuration failures can be traced to the file that needs inspection.
- [x] **M9.2 Surface bindings / MIDI learn:** select surface, listen for one supported control, preview conflicts and save binding. Tests: learning suppresses the normal action, other surfaces are not captured accidentally, cancellation restores routing, duplicate binding is rejected.
The Config tab starts surface/fader/action-scoped learning with `L` and
cancels with `C`. Captured CC/note identity is added to the validated server
draft; conflicts are shown without changing the draft revision.
- [x] **M9.3 Save/conflict:** server-owned revisioned edits with one Save action
that persists and activates the validated draft. Tests: stale edits conflict,
external file edits are not overwritten, comments survive save, and write
failure leaves the previous disk and live configuration usable.
Save commits the latest server-owned validated draft when the requesting view
is behind; it does not reject already accepted shared edits as stale.
Fixed MIDI volume/mute failures after Save: public revision validation now
belongs to external client requests, not server-owned MIDI actions. A
regression exercises both controls and correlated readbacks after repeated
routing reconfiguration; stale external clients remain rejected.
- [x] **M9.4 Mixer-first layout:** persist ordered logical-fader and separator
entries, synthesize declaration-order entries for old profiles, and retain
hidden faders in place. The main mixer can reorder either entry type, add/edit/
remove separators, hide visible faders, and restore hidden faders without
changing targets or bindings. Stable-ID moves rebase onto the latest draft
when another edit advances it. Tests: invalid/duplicate/dangling layout entries
fail; reorder and hide/show round trip through comment-preserving drafts; a
hidden application remains routable through a visible group.
Profiles now validate and publish ordered fader/separator entries, with
declaration-order synthesis for existing files. The mixer renders that
layout and provides direct move, separator add/rename/remove, hide, and
hidden-fader restore actions through revisioned comment-preserving drafts.
Separator add and rename collect their label in a centered modal rather than
reusing the mixer status line.
Hidden restoration now lives in the Config settings page rather than a
second mixer mode. Config also persists a Vertical or Horizontal mixer
orientation. Horizontal mode renders side-by-side console-style fader strips;
vertical mode keeps the stacked card layout. Separators are inline labeled
divider columns in Horizontal mode so entries stay on one row, and span the
display width in Vertical mode. Arrow-key selection and reordering follow the
layout axis, while the perpendicular arrows adjust volume.
Config also persists pickup-status presentation as Detailed, Compact,
Symbol, Color, or Hidden. Both mixer orientations share the same state
mapping, and hiding the indicator does not disable pickup protection.
Horizontal strips reserve an empty pickup-status row for unassigned or hidden
indicators so MIDI assignment never changes the meter height.
Reordering saved layouts now resets TOML source-order metadata: parsed table
positions previously undid accepted moves during serialization, causing the
optimistic TUI swap to snap back. Regression tests cover repeated file reloads,
both move directions, separator insertion, hidden entries and comments, plus
IPC edit/refresh/Save and reordering after server restart.
Separators now have independent Slim/Standard/Thick/Fill sizes and
Plain/Line/Double line/Box decorations in their popup. Fill shares remaining
viewport space after fitting the other entries. Profile round trips,
server save/snapshot, popup accept/cancel, both orientations, and tiny
viewports are covered by regression tests.
Empty separator names are accepted in profile validation and the popup;
unnamed spacers retain unique stable IDs and survive save/reload.
- [x] **M9.5 Guided fader editor:** replace pipe-delimited table commands with a
selected-fader form. Application faders edit capture field/mode/pattern;
groups select eligible application faders and show the absolute group mode;
volume and mute assignments each expose controller selection and Learn MIDI;
`U` in the learn prompt unbinds that action. Tests: editing one field preserves unrelated
selectors/bindings, unlearn removes only the selected action, learn conflicts
preserve the draft, and group selection translates to deduplicated
application IDs.
`E` on a mixer fader opens a field-oriented form. Application capture edits
Field, Exact/Regex, and Pattern separately while preserving other selectors;
Pattern opens a cursor-aware modal for local insertion and deletion rather
than requiring the full value to be erased;
a Save and exit row validates and submits the current capture fields without
reopening Pattern. Invalid patterns retain the form and inline error; both
submission paths use domain validation before queueing the draft edit.
groups edit application-fader membership in a checked multi-select popup and
show the currently supported Absolute mode. Volume and Mute show separate
controller and Learn MIDI actions. Learning opens a modal prompt for a fader
movement or button press, with `U` to unbind and `Esc` to cancel unchanged.
Unbinding cancels capture and keeps the controller available for relearning;
relearning atomically replaces only the chosen action, and validation
conflicts retain the draft. Visibility uses the same form.
The form also persists a per-fader Slim, Bordered slim, Standard, or Thick
size in the mixer layout. Existing profiles default to Standard. Slim renders
in one terminal row; Bordered slim uses a three-row bordered card; both are
narrower strips for horizontal faders. Config stores a validated default
controller; unassigned volume and mute learn actions inherit it while explicit
bindings keep their selected surface. A new mute assignment inherits feedback
values only from one unambiguous same-surface, same-message-kind convention
and otherwise leaves device-specific feedback unset.
Application and group faders expose a Name row with a cursor-aware rename
popup. Renaming changes only the target display label; stable IDs, selectors,
membership, bindings, and layout remain intact. Output labels stay backend-owned.
- [x] **M9.6 Single-screen configuration workflow:** remove the normalized
Config table browser once all its operations are reachable from the mixer,
keep Save and draft/durable status visible, and expose hidden-item
restoration and device/backend diagnostics without a separate primary tab.
Tests: keyboard navigation and every modal work at small terminal sizes;
Escape backs out one level and never quits; invalid edits retain form input.
The normalized table browser and pipe-delimited object commands are removed.
Config is now a secondary settings/status page for the persisted profile
theme, hidden restoration, Save, learning cancellation, and backend/device
state. Hidden restoration uses one settings action that opens a popup listing
every hidden fader rather than expanding the settings page with one row per
fader. MIDI-device status rows are selectable and open a details popup where
the profile's default-controller assignment can be set or cleared. `h` and `?`
open detailed keyboard help; Shift+H hides the selected mixer fader.
Quick help now omits navigation, volume, Home/End, and alternate bindings,
while showing Add, Edit, and Delete as separate actions; detailed help retains
the complete bindings and explicitly documents Home/End.
A confirmed Config action now resets only the active profile to the safe
Master-output default. The server backs up the prior bytes as `.reset.bak`,
atomically persists the replacement, and activates it without audio writes;
editor, IPC/server, and confirmation/cancellation paths are regression-tested.
Configured MIDI devices can also be removed with `D` from their row or details
popup. Confirmation describes the binding cleanup, and the draft atomically
removes the surface, its bindings, and any default-controller reference before
Save reconfigures the running MIDI topology.
Mixer `A` now chooses a new application fader, empty absolute group, or
separator. Compound application/group creation adds the target, fader, and
visible layout entry atomically before opening its guided editor. New targets
remain visible as non-writable DRAFT rows with a Save-to-activate explanation
until activation replaces them with runtime objects. Generic `D`
confirms removal of a fader and its unshared target or a separator. The new
chooser, name editor, and confirmation popup are covered at tiny terminal
sizes, completing the remaining object-creation acceptance.
## M10 — Transactional profile swapping
Dependencies: M9, M6, M7.
- [x] **M10.1 Prepare/activate:** validate/probe candidate, pause/drain old writes, obtain new snapshot and atomically publish generation/mappings. Tests: invalid profile/unavailable manual adapter keeps old profile; late commands/events do not reach new targets; un-drainable native operations force reconciliation before activation.
`profile switch ID` now prepares a sibling profile, rejects invalid/native-only
candidates and runtime timing changes, waits for pending audio reconciliation,
then publishes matching, groups, faders, pickup, and MIDI together. Activation
advances the mixer view revision so pre-switch client commands are stale. The
Config view lists valid sibling profiles and switches through a popup using
the same safe adopt-mode transaction.
- [ ] **M10.2 Restore/adopt policy:** default switch adopts live state; explicit restore uses saved object intents and deterministic overlap ordering. Tests: no surprise startup/switch write, restore limits enforced, offline/new members follow configured policy, pickup/feedback resync happens on every surface.
Default switching is write-free. `profile switch ID --restore` now validates
the saved state before activation, restores online applications in profile
order, and retains offline intents only under `new_stream = "restore"`.
Pickup is re-armed; completion still depends on the M6 feedback lifecycle.
- [x] **M10.3 Durable selection:** save active pointer after successful activation and reconcile state namespaces. Tests: disk failure marks active runtime selection unsaved, restart selects last durably saved profile, and corruption cannot silently activate an unintended profile.
Successful activation atomically writes the strict XDG active-profile pointer.
`serve` without `--config` follows it; corrupt pointers fail before audio/socket
side effects, while pointer-write failure keeps the new runtime profile active
but visibly marks its selection unsaved.
## M11 — Native PipeWire and optional ALSA mixer
Dependencies: M4 adapter contract; native PipeWire follows a working Pulse slice.
- [ ] **M11.1 PipeWire spike:** verify playback node classification, writable SPA volume/mute parameters, channel balance, application properties, notifications and thread ownership. Acceptance: isolated native and Pulse-origin playback streams have documented coverage under a session manager; unsupported objects produce capability errors.
- [ ] **M11.2 Native implementation:** implement feature-gated worker and run shared contract suite plus real-daemon scenarios. Tests: external changes, reconnect, stream churn, snapshot races and normalized gain match domain semantics; auto never double-writes through Pulse and native APIs.
- [ ] **M11.3 ALSA hardware extension:** add explicit hardware target schema/UI selection, mixer element discovery/control, event/readback and capability reporting. Tests: unsupported mute rejected, integer/dB scaling round trips, external mixer changes observed, application profile never silently maps to master hardware gain.
- [ ] **M11.4 Feature matrix:** default Pulse, native-only, mixer-only, no backend, full-feature builds. Acceptance: each isolated feature builds with only its documented native prerequisites; manual selection of an unbuilt adapter gives a useful diagnostic.
## M12 — Reliability and release
Dependencies: all required feature milestones; hardware-only ALSA remains an explicitly scoped extension.
- [ ] **M12.1 Adversarial replay:** deterministic reconnect/churn/write-failure/echo/reordered-event/profile-switch scenarios. Property tests preserve domain invariants; command storms stay bounded and converge without starving mute or shutdown.
- [ ] **M12.2 Integration matrix:** PulseAudio, pipewire-pulse, native PipeWire, two controllers, external desktop mixer, reload/restart, read-only/full state directory. Record fixtures, supported device profiles and known limitations; never run destructive audio tests on the user's current session by default.
- [ ] **M12.3 Packaging:** example TOML profiles, schema/migration documentation, build/install guide, optional systemd user unit and troubleshooting. Acceptance: fresh user install can discover, bind, edit, save, restart and reconnect without root or manual state repair.
Managed startup now initializes a valid `default` profile and active
pointer on first run, and recreates only a missing profile referenced by a
valid existing pointer. Explicit paths and malformed existing files remain
errors rather than being overwritten. Pre-versioned/schema-0 profiles upgrade
automatically only after full candidate validation, with comment preservation,
an exact `.v0.bak` backup, and atomic replacement.
New managed profiles include a safe default-output fader so first-run setup
has an editable mixer target before any application or controller is known.
Exactly one discoverable MIDI input is adopted with its durable identity;
ambiguous first-run discovery remains unchanged. Unconfigured inputs are
otherwise listed in Config and can be added, saved, and assigned through the
existing MIDI Learn workflow without editing TOML. Config also repairs legacy
empty profiles by offering a safe Master-output fader.
- [ ] **M12.4 Release gates:** all workspace/default/feature/MSRV checks, reproducible lockfile, license review and dependency advisory review using maintained tooling selected at implementation time. Measure/control latency under multi-surface load and publish the tested envelope.
Release wrapper, offline contract tests, binstall metadata and an explicit
x86-64 GNU/Linux artifact configuration are prepared. The first release
candidate `v0.1.0-rc.1` is published; authenticated preview, Cross packaging,
archive/checksum checks and public cargo-binstall verification passed with
the publisher fix and image override recorded in [release preparation](docs/releasing.md).
Remaining reliability, hardware, advisory/license and reproducibility
qualification still blocks completion of this milestone.
RC2 (`0.1.0-rc.2`) preparation updates versions/install instructions and the
changelog. All workspace gates, default/no-default and independent MIDI/Pulse
feature tests pass on Rust 1.88.0; example assertions now match the committed
Arch profile. Release wrapper tests pass. Publication uses the same fixed
publisher and pinned Ubuntu 24.04 Cross image as RC1.
RC2 is published from `8ac222b`: all five assets, public checksums/archive and
isolated cargo-binstall verification passed. The release API confirms a
non-draft prerelease; build provenance is recorded in `docs/releasing.md`.
## M13 — Stretch goals: matching and targeted media controls
Agreed order: M13.1 and M13.2 first, then M13.3. These do not change RC2's
supported configuration or mark the remaining release qualifications complete.
The existing `media.name` selector `(?i) - YouTube$` already satisfies the
YouTube capture use case; no browser-name condition is needed.
- [x] **M13.1 AND selectors:** add explicit conjunction while preserving existing
OR-list behavior. Dependencies: M1.2, M9.5. Acceptance: configuration and TUI
express the composition clearly; exact/regex and missing-field behavior are
deterministic; existing profiles retain their matches; invalid composition
is rejected before activation; save/reload preserves the expression.
Domain/configuration slice: `selector_mode = "any"` (default OR) or `"all"`
(AND), preserving missing-field and bounded pattern validation. The fader
editor exposes Match captures Any/All, with revisioned IPC edits and a
save/reload/restart regression. Workspace formatting, check, tests, doc tests,
clippy and release build pass, as do default/no-default and individual backend
builds. Existing profile semantics remain unchanged.
- [x] **M13.2 Richer process metadata:** enrich stream metadata with available
process paths and Steam launch identity, then expose validated matcher fields
and useful diagnostics. Dependencies: M1.2, M4. Acceptance: bounded adapter
reads, PID-reuse protection, selective Steam environment keys, and explicit
unavailable state for exited/inaccessible/sandboxed processes. Tests cover
native and Proton-like fixtures, Steam IDs, non-Steam processes and path-only
hints; a `steamapps` path must not be treated as proof Steam launched a game.
Implemented: bounded Pulse-worker enrichment and four selectable fields
(executable, working_directory, steam.app_id, steam.game_id), local-machine
guard and start-time consistency check. Fixture coverage includes missing
process data, PID reuse, Steam/path-only cases, malformed IDs and bounded
reads. Config now includes per-stream normalized metadata diagnostics, including
explicit unavailable values; native/Proton-like, restricted-environment and
exit-during-read fixtures are covered. Real-process checks remain opt-in.
- [x] **M13.3 Targeted MPRIS controls:** add Play, Pause and PlayPause via matched
player identity/desktop ID/bus name, without keyboard simulation.
Dependencies: M13.1, M13.2, M5.2, M9.5. Acceptance: a QBZ-specific binding
affects only its resolved player; paused players with no audio stream remain
discoverable; ambiguous matches are surfaced; missing players, unsupported
capabilities, disconnects and timeouts are recoverable. Cover MIDI learn,
saved configuration, TUI controls and confirmed playback-state feedback with
a fake D-Bus adapter before opt-in player integration checks.
Approved implementation slices for M13.3 (each independently tested/committed):
- [x] **M13.3a Feedback switches:** persisted global MIDI-feedback gate and
per-fader/per-media-entry gates; global off overrides local settings and sends
no output, including clearing messages; re-enable resynchronizes observed state.
All three gates are implemented in configuration/runtime and TUI, applied on
Save. Tests cover no-clear suppression, observed-state resync and explicit maps.
- [x] **M13.3b MPRIS adapter:** session-bus discovery independent of audio streams,
bounded calls, capability reporting, owner-change handling and reconnects.
Verify dependency license, native prerequisites and Rust 1.88 compatibility.
Worker and native adapter implemented with pinned dbus 0.9.12; fake-adapter
tests and two isolated dbus-run-session fixtures pass: paused discovery,
transport/extended actions, readback, capability changes, timeouts/recovery and
owner replacement. Session-bus availability survives individual player errors.
- [x] **M13.3c Media entries:** stable IDs, labels, exact/regex selectors on bus
name, desktop entry or identity; live picker plus manual entry; reject ambiguous
targets rather than selecting arbitrarily. Persist MIDI action bindings.
Hardware-free contracts, bounded validated profiles, live picker/manual
selectors and MIDI press-edge routing are integrated. Save/restart/unbind/delete
regression exercises IPC and active-versus-draft boundaries.
- [x] **M13.3d Media tab:** server-advertised availability, A/E/D editing,
validated Save and exit, MIDI Learn with U to unbind; retain offline entries.
Support Play, Pause, Stop, PlayPause, Next and Previous with capability checks.
- [x] **M13.3e Playback feedback:** confirmed Playing/Paused/Stopped exclusively
lights the corresponding transport buttons; default same-note 127/0, explicit
device-specific colour values; clear unavailable targets only when enabled.
Deduplicate and resync after reconnect; failed commands never imply success.
- [x] **M13.3f Extended controls:** relative seeking with configurable steps and
absolute position where supported; shuffle toggle/set; repeat Off/Track/Playlist
set/cycle; discover/select/activate playlists with MIDI bindings and confirmed
feedback where reported. Playlist-content editing is outside this scope.
- [x] **M13.3g Qualification:** document schema/UI, save/reload/restart tests,
fake-bus failures and capability changes, workspace gates, opt-in QBZ/controller
integration checks. No keyboard simulation or playerctl dependency.
M13 automated qualification (2026-10-18, Rust 1.88.0): all six workspace gates
passed: fmt check, all-target/all-feature check and tests, doc tests, clippy with
warnings denied, and all-feature release build. Default/no-default workspace
tests, portable-library tests/builds and independent MIDI/Pulse/MPRIS feature
tests/builds passed. Both isolated private-bus fixtures passed; CI script tests
passed and Jenkins now includes the media crate plus the private-bus fixture.
The complete QBZ example validates and round-trips all action kinds. Documentation
and the opt-in real QBZ/controller checklist are updated. Real hardware/player
checks and a provisioned Jenkins execution are **not claimed**; their existing
release/manual qualification items remain open. M13 completion does not complete
native PipeWire, relative groups, M0.2 or the wider release backlog.
## User requirement coverage
| # | Requirement | Work items |
| --- | --- | --- |
| 1 | MIDI -> server records intent -> audio adapter | M3.1–M3.3, M5.1, M5.5 |
| 2 | Different sound manager adapters | M4, M11 |
| 3 | Automatic/manual selection | M4.3, M8.2, M11.4 |
| 4 | Exact/regex application selectors | M1.2, M9.1 |
| 5 | One fader controls grouped applications | M1.3–M1.4 |
| 6 | Mute/unmute | M1.5, M4.2, M6.1 |
| 7 | Load current volume/mute/state | M3.2–M3.4, M4.2, M10.2 |
| 8 | TUI tab creates/edits groups and faders | M9 |
| 9 | Fader -> virtual application/group -> adapter | M1.3, M3.1–M3.2 |
| 10 | External audio changes update state | M3.1–M3.2, M4.4, M11.2 |
| 11 | Server sends state back to MIDI surfaces | M6 |
| 12 | Concurrent surfaces and remembered bindings | M5.2–M5.5, M2.3 |
| 13 | Architecture with design improvements | architecture.md; pickup, epochs, partial failures, atomic reload |
| 14 | Swappable configuration; durable data in TOML | M2, M9.3, M10 |
| 15 | Library research | architecture.md library table; M4.1, M5.2, M11.1 |
First implementation target: M0, then a hardware-free M1/M2/M3 slice; follow with Pulse and one MIDI controller before broadening backend or device protocol support.