Johan Le Baut пре 4 дана
родитељ
комит
80e441d078

+ 7 - 9
AGENTS.md

@@ -12,21 +12,19 @@ The current target is Debian GNU/Linux 13 on AArch64 with a Behringer UMC404HD 1
 - `config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf` is a PipeWire filter-chain fragment with nine mono mixer inputs (four direct sources, four first-loop returns, and one second-loop return) implemented as two cascaded mixer stages, one mono output, and initial external-input gain `0.2`. It defines the processing graph and ports, but does not create links to hardware or implement the looper graph.
 - `scripts/validate_desired_state.py` checks the YAML's four-source/physical-input model, one SooperLooper instance with two four-channel loops, source-to-first-loop channel assignments, the unconnected second-loop inputs and single mix return, mix declaration, and prohibition on routing looper returns back to looper inputs.
 - `scripts/observe_pipewire.py` validates the state and managed endpoint declarations, reads `pw-link -l`, and compares observed links against explicitly managed ports and links. Without `--reconcile-once`, it is read-only; one-shot reconciliation and the separately deployed timer create only declared missing links and remove only declared stale links.
-- `scripts/generate_mod_ui_pedalboard.py` builds the YAML-declared guitar NAM→IR chain and three direct-through source pairs; mod-ui owns plugin instances and internal cables after loading it.
 - `scripts/run_mod_host_ports.py` runs the paired four-channel PipeWire loopbacks which form stable mod-ui-visible input/output boundaries.
-- `scripts/prepare_mod_ui_pedalboard.py` regenerates and validates the canonical mod-ui bundle once per system boot, keeps backups outside mod-ui's scanned pedalboard directory, and refuses to launch on an invalid board.
-- `scripts/run_mod_ui_service.py` launches mod-ui under `pw-jack`, holds a WebSocket session, and verifies the guitar PipeWire boundary links before reporting ready. The mod-ui patch must schedule saved-board boundary retries on Tornado's event loop; do not block pedalboard loading while plugin ports are being created.
+- `scripts/run_mod_ui_service.py` launches mod-ui under `pw-jack` and holds a WebSocket session. mod-ui owns user-created pedalboards; do not generate or replace the board during service startup. The mod-ui patch must schedule saved-board boundary retries on Tornado's event loop; do not block pedalboard loading while plugin ports are being created.
 - `build/arm64/patch_mod_ui_rigforge.py` reapplies the local PipeWire-boundary mapping and acknowledged MIDI WebSocket command when rebuilding the pinned mod-ui artifact; keep it consistent with the tracked artifact changes.
 - `scripts/wait_mod_host_ports.py` waits for boundary and mixer endpoints before mod-host starts, avoiding startup races after PipeWire restarts.
 - `scripts/midi_action_bridge.py` retains ALSA Note On bindings and changes NAM files through mod-ui's WebSocket, never a second mod-host control connection.
 - The old `scripts/configure_mod_host.py` is not used by the service architecture; do not reintroduce its direct plugin/link ownership alongside mod-ui.
 - `config/systemd/user/rigforge-pipewire-reconcile.service.in` and `.timer.in` define periodic reconciliation for the whole YAML-managed graph.
-- `config/systemd/user/rigforge-mod-host-ports.service.in`, `rigforge-mod-host.service.in`, and `rigforge-mod-ui.service.in` define the opt-in boundary, backend, and UI services; mod-ui runs its clean-board preparation before launch.
-- `scripts/deploy.sh` dispatches scoped user-level install/uninstall/reload actions plus explicit `reset mod-ui` for YAML-declared services and bundles. Audio-host/UI targets and `reconcile` are opt-in, not part of `all`.
-- `tests/` contains Python `unittest` tests for state validation, observation/reconciliation, the generated pedalboard, MIDI WebSocket control, and simulated deployment operations. These validate repository-level invariants, not live audio behavior.
+- `config/systemd/user/rigforge-mod-host-ports.service.in`, `rigforge-mod-host.service.in`, and `rigforge-mod-ui.service.in` define the opt-in boundary, backend, and UI services.
+- `scripts/deploy.sh` dispatches scoped user-level install/uninstall/reload actions for YAML-declared services and bundles. Audio-host/UI targets and `reconcile` are opt-in, not part of `all`.
+- `tests/` contains Python `unittest` tests for state validation, observation/reconciliation, MIDI WebSocket control, and simulated deployment operations. These validate repository-level invariants, not live audio behavior.
 - `config/sooperlooper/fcb1010.slb` is supplied controller configuration, pending target verification. No SooperLooper build definition or artifact is present.
 
-The YAML is the source of truth for desired topology and the generated pedalboard. mod-ui owns the guitar NAM→IR cable and the bass/voice/synth input-to-output passthrough cables; its Rigforge bridge applies those boundary Connect/Disconnect operations through `pw-link`. Rigforge's observer owns only external UMC→input-boundary and output-boundary→mixer/looper links. The observer compares only external links whose endpoints are listed in `routing.managed_ports`. Keep mod-ui-owned cables and unrelated WirePlumber links out of scope. Managed endpoint names are constrained by an explicit allowlist pattern in the observer, so a new port naming scheme must be deliberately reviewed and tested there as well as declared in YAML.
+The YAML is the source of truth for external topology, while mod-ui owns user-created pedalboards and their internal cables. Its Rigforge bridge applies boundary Connect/Disconnect operations through `pw-link`. Rigforge's observer owns only external UMC→input-boundary and output-boundary→mixer/looper links. The observer compares only external links whose endpoints are listed in `routing.managed_ports`. Keep mod-ui-owned cables and unrelated WirePlumber links out of scope. Managed endpoint names are constrained by an explicit allowlist pattern in the observer, so a new port naming scheme must be deliberately reviewed and tested there as well as declared in YAML.
 
 ## Commands
 
@@ -67,8 +65,8 @@ The observer invokes `pw-link -l` itself. Its default mode never creates or remo
 - Scripts resolve their default state file relative to their own location, so the documented commands work from any current directory, though repository-root execution is the clearest convention.
 - PipeWire's `filter-chain.conf.d` fragment is loaded by the separate filter-chain process (`pipewire -c filter-chain.conf` on the current target), not automatically by the main PipeWire daemon. It defines nodes/ports, not connections. Target service installation and restart steps are specific to the README's current test and should not be treated as an established deployment recipe.
 - The current port mapping, sample rate/quantum, and physical output details have differing verification levels recorded in YAML and README. Preserve those distinctions; do not infer a complete deployment procedure from the exploratory test notes.
-- Deployment is manual; no CI/CD or auto-pull is configured. The new loopback boundaries, paired mod-host feedback socket, mod-ui service, generated bundle loading, and MIDI WebSocket path are not target-verified. Keep unverified changes away from live audio use and follow the README's rollback procedure for target experiments.
-- `install mod-host-ports`, `install mod-host`, and `install mod-ui` activate the candidate guitar path and are intentionally excluded from `install all`. `install reconcile` separately enables graph-wide periodic link repair and is also opt-in. mod-host's control and feedback sockets listen on all interfaces without authentication by owner request; do not change that policy silently, and retain the security warning in documentation.
+- Deployment is manual; no CI/CD or auto-pull is configured. The new loopback boundaries, paired mod-host feedback socket, mod-ui service, user-created board restore, and MIDI WebSocket path are not target-verified. Keep unverified changes away from live audio use and follow the README's rollback procedure for target experiments.
+- `install mod-host-ports`, `install mod-host`, and `install mod-ui` activate the candidate audio path and are intentionally excluded from `install all`. `install reconcile` separately enables graph-wide periodic link repair and is also opt-in. mod-host's control and feedback sockets listen on all interfaces without authentication by owner request; do not change that policy silently, and retain the security warning in documentation.
 
 # Environnement local — rigforge
 

+ 8 - 11
README.md

@@ -10,7 +10,7 @@ The current target reports Debian GNU/Linux 13.7, AArch64, and a Behringer UMC40
 
 PipeWire exposed four capture channels named `capture_AUX0` through `capture_AUX3` and four playback channels named `playback_AUX0` through `playback_AUX3`. A four-channel 48 kHz recording was completed, with the guitar on physical input 1 appearing on `capture_AUX0` and the microphone on physical input 3 appearing on `capture_AUX2`; the other channels were at noise floor during that test. A temporary PipeWire link from `capture_AUX0` to `playback_AUX0` produced audible guitar. The target owner reports that `playback_AUX0` feeds output 1L and that Main Out L receives 1L with MIX set to PB and MONITOR set to A. The owner then added `capture_AUX2` and confirmed hearing both guitar and microphone with a 128-frame quantum at 48 kHz; this is an initial successful low-latency listening test, not yet a sustained dropout or headroom measurement. Monitoring duplication and clipping headroom under summed sources and loop returns remain unverified. Guitar NAM model selection via the FCB is now covered by the target report below; SooperLooper MIDI/OSC behavior remains untested.
 
-The target has `aconnect`, `amidi`, and `oscsend`; ALSA lists the UMC404HD MIDI port. On 2026-11-20 the owner ran the Rigforge MIDI bridge on the target and confirmed FCB1010 note messages on MIDI channel 1. The SooperLooper MIDI bindings and OSC availability remain unverified. `amixer -D hw:2 scontents` showed capture and playback controls at 0 dB; no mixer settings have been changed.
+The target has `aconnect`, `amidi`, and `oscsend`; ALSA lists the UMC404HD MIDI port. On 2026-11-20 the owner ran the Rigforge MIDI bridge on the target and confirmed FCB1010 note messages on MIDI channel 1. The SooperLooper MIDI bindings and OSC availability remain unverified. `amixer -D hw:2 scontents` showed capture and playback controls at 0 dB; no mixer settings have been changed. The current direction is to keep Rigforge responsible for external PipeWire boundaries and let the user create/save the mod-ui pedalboard; pedalboard generation from YAML has been removed.
 
 ## Target preparation recorded so far
 
@@ -38,7 +38,6 @@ This records the preparation already performed on `rigforge` and is a starting p
 - `scripts/observe_pipewire.py`: read-only comparison by default, with explicit one-shot repair for declared missing links.
 - `scripts/midi_action_bridge.py`: translates declared ALSA MIDI note events into NAM model changes through mod-ui's WebSocket.
 - `scripts/run_mod_ui_service.py`: keeps mod-ui's backend session alive; mod-ui remains the sole owner of pedalboard connections.
-- `scripts/generate_mod_ui_pedalboard.py`: generates the reference guitar NAM→IR and microphone-processing pedalboard from the YAML.
 - `scripts/deploy.sh` and `scripts/deploy.py`: scoped user-level installation, removal, reload, and explicit mod-ui reset of declared services, SLWeb source files, and LV2 bundles.
 - `tests/`: unit tests for desired-state validation, PipeWire observation/reconciliation, pedalboard generation, MIDI WebSocket control, the mod-ui/PipeWire boundary bridge, and deployment operations.
 - `artifacts/sooperlooper/arm64/`, `artifacts/mod-host/arm64/`, and `artifacts/mod-ui/arm64/`: generated binaries or runtime bundle, dependency reports, and build provenance; commit after reviewing licensing and repository size.
@@ -121,7 +120,7 @@ After a manual `git pull --ff-only`, run the deploy helper from any directory:
 ~/rigforge/scripts/deploy.sh install midi-bridge
 ```
 
-The helper accepts `install|uninstall|reload` plus `reset mod-ui`, and targets `all|namlv2|lsp|dragonfly-reverb|pipewire|mod-host-ports|mod-host|mod-ui|reconcile|midi-bridge|sooperlooper|slweb`. `all` deliberately excludes the audio-host/UI/MIDI services, reconciliation, and SooperLooper services, which are opt-in. Install in dependency order: ports, mod-host, then mod-ui; the MIDI bridge follows mod-ui. Install SooperLooper before SLWeb. The ports service requires `/usr/bin/pw-loopback` from the target PipeWire tools; verify it exists before installation. It reads versions, paths, URLs, and settings from `config/desired-state.yaml`; its deployment registry is stored under `~/.local/state/rigforge/`, and any pre-existing unit backup is stored next to that unit. It does not use `sudo` or change files outside declared paths, adjacent backups, the dedicated mod-ui and SLWeb user-data directories, and the registry directory.
+The helper accepts `install|uninstall|reload` and targets `all|namlv2|lsp|dragonfly-reverb|pipewire|mod-host-ports|mod-host|mod-ui|reconcile|midi-bridge|sooperlooper|slweb`. `all` deliberately excludes the audio-host/UI/MIDI services, reconciliation, and SooperLooper services, which are opt-in. Install in dependency order: ports, mod-host, then mod-ui; the MIDI bridge follows mod-ui. Install SooperLooper before SLWeb. The ports service requires `/usr/bin/pw-loopback` from the target PipeWire tools; verify it exists before installation. It reads versions, paths, URLs, and settings from `config/desired-state.yaml`; its deployment registry is stored under `~/.local/state/rigforge/`, and any pre-existing unit backup is stored next to that unit. It does not use `sudo` or change files outside declared paths, adjacent backups, the MIDI bridge's dedicated NAM model directory, SLWeb user data, and the registry directory.
 
 For PipeWire, install updates only the Rigforge filter fragment, applies the declared quantum, and installs/enables `rigforge-pipewire-quantum.service`. That oneshot is ordered after and tied to `pipewire.service`, so the desired quantum is reapplied at engine startup/restart without restarting PipeWire or WirePlumber during deployment. `filter-chain.service` is restarted only when its fragment changes. `reload pipewire` reapplies the quantum and restarts the filter-chain user service. This filter-chain restart removes its nodes and graph links; the fragment recreates ports but not links. Reconciliation is a separate explicit target; installing `mod-host` alone does not install its timer. After a PipeWire/filter restart, inspect with `python3 scripts/observe_pipewire.py`. Uninstall removes only unchanged managed files, restores prior files, disables the quantum unit, returns quantum selection to automatic, and reloads the filter service. Local edits to managed files stop removal or replacement rather than being discarded.
 
@@ -161,15 +160,13 @@ Remove SLWeb before SooperLooper with `./scripts/deploy.sh uninstall slweb`. The
 
 ### mod-host ports and mod-ui guitar board
 
-`install mod-host-ports`, `install mod-host`, and `install mod-ui` are explicit targets and are deliberately excluded from `install all`. The desired four-channel `mod-host-ports` service starts a four-channel PipeWire input boundary (`rigforge.mod-host-input` with paired source `rigforge.mod-host-input.capture`) and a four-channel output boundary (`rigforge.mod-host-output.playback` with paired source `rigforge.mod-host-output`). Channel positions AUX0–AUX3 align with UMC capture channels 1–4. Rigforge's observer manages each UMC capture → input sink edge and each output source → its mixer/looper destinations. The generated mod-ui board shows the guitar path through NAM and IR, plus direct bass, microphone, and synth passthrough cables from `capture_2..4` to `playback_2..4`. mod-ui handles Connect/Disconnect for all boundary cables through the Rigforge PipeWire bridge; NAM→IR stays a normal mod-host connection. The service runner does not repair or override pedalboard links.
+`install mod-host-ports`, `install mod-host`, and `install mod-ui` are explicit targets and are deliberately excluded from `install all`. The desired four-channel `mod-host-ports` service starts a four-channel PipeWire input boundary (`rigforge.mod-host-input` with paired source `rigforge.mod-host-input.capture`) and a four-channel output boundary (`rigforge.mod-host-output.playback` with paired source `rigforge.mod-host-output`). Channel positions AUX0–AUX3 align with UMC capture channels 1–4. Rigforge's observer manages each UMC capture → input sink edge and each output source → its mixer/looper destinations. mod-ui exposes those four inputs and outputs and handles their Connect/Disconnect operations through the Rigforge PipeWire bridge. The user creates and saves the pedalboard in mod-ui; the generator/default-board reset path has been removed. NAM→IR and other plugin cables remain owned by mod-ui/mod-host.
 
-`scripts/generate_mod_ui_pedalboard.py` builds the reference bundle from the YAML: one NAM defaulting to Vox AC15 Crystal Clean TB, one LSP mono IR using the Vox AC30 asset, the guitar NAM→IR chain, a microphone channel-3 chain (LSP high-pass, compressor and de-esser, then Dragonfly Room reverb with the dry signal retained), plus direct-through bass and synth arcs. The voice-chain settings are conservative starting points only and require listening and level adjustment on target. During `install mod-ui`, deployment copies the declared NAM models into Rigforge's dedicated `MOD_USER_FILES_DIR/NAM Models/Rigforge` directory and generates a target-specific bundle whose model path points there; the model copies are fingerprinted and removed only if unchanged when mod-ui is uninstalled. The reference bundle is also target-specific, fingerprinted, and protected from local edits. mod-ui resumes its last saved board across service restarts within the same boot. `./scripts/deploy.sh reset mod-ui` explicitly restores the generated reference and backs up any prior default board and last-state file as adjacent `.rigforge-reset-backup` paths.
+`install mod-ui` installs only the service and Rigforge's four-port boundary mapping; it does not generate or replace pedalboards. Create and save the board using the mod-ui interface. mod-ui uses its normal user pedalboard directory and `last.json` state under `~/.local/share/rigforge/mod-ui`. The MIDI bridge's NAM model copies are managed separately under `~/.local/share/rigforge/mod-ui/NAM Models/Rigforge`.
 
 Rigforge's mod-ui bridge maps NAM and IR graph ports explicitly to their mod-host LV2 ports and retries boundary restoration only after the declared PipeWire ports are visible. If the UI board is open but boundary links are absent, inspect the active plugin connections in mod-ui and run `python3 scripts/diagnose_mod_ui.py`; the diagnostic falls back to mod-ui's active pedalboard API if the saved last-state path is empty. Do not create the internal effect links manually with `pw-link`; mod-ui is their owner.
 
-On each system boot, `rigforge-mod-ui.service` runs `scripts/prepare_mod_ui_pedalboard.py` before launching mod-ui. It regenerates and validates the content-addressed reference bundle from the checkout, replaces the mutable `default.pedalboard` with that clean board, and moves any previous default and last-state file into `mod-ui/boot-backups`, outside the pedalboard scan directory. It also migrates older Rigforge backups out of that scan directory. A marker under the user runtime directory makes this happen only once per boot; a mod-ui service restart during the same boot preserves in-session changes. The Rigforge service uses a dedicated `last-rigforge.json` state file so upstream `last.json` state cannot redirect startup to an unrelated board. If generation or validation fails, mod-ui does not start with a blank board. The service runner launches mod-ui and holds its WebSocket session so mod-host remains connected; it does not treat the WebSocket's loading messages or PipeWire cable checks as service readiness. Use `python3 scripts/diagnose_mod_ui.py` for a separate read-only check of selected bundle metadata and voice-chain links. This diagnostic uses HTTP and `pw-link`, not a second WebSocket session, and its failure does not restart mod-ui. This startup behavior is covered by repository tests but has not yet been deployed or fully verified on the target.
-
-If `install mod-ui` refuses a changed but registry-managed reference bundle, first inspect why it differs. To explicitly replace only that bundle while preserving its current contents, use `./scripts/deploy.sh install mod-ui --force-reference`; the old bundle is retained in an adjacent `.rigforge-force-backup` path. This flag does not override local edits to the systemd unit, model files, or other managed paths.
+On boot, the mod-ui service no longer prepares or overwrites a default pedalboard. It launches mod-ui under `pw-jack`, retains its WebSocket session so mod-host remains connected, and lets mod-ui restore its saved user pedalboard. Rigforge supplies the four logical boundary mappings through the service environment. This keeps the external PipeWire reconciliation separate from mod-ui's internal pedalboard graph. It does not yet guarantee that every internal cable restores successfully; the Dragonfly port mapping and complete mod-ui readiness checks remain to be addressed.
 
 The mod-host unit runs `pw-jack mod-host -n -p 5555 -f 5556`; it no longer runs `configure_mod_host.py`. The mod-ui service starts under `pw-jack`, opens a persistent local WebSocket session so mod-host remains active even before a browser connects, and is the sole control/feedback client for mod-host. Its boundary bridge maps four visible input/output pairs to PipeWire and applies only explicit UI Connect/Disconnect operations. The runner supervises the processes and keeps the session alive; it does not validate pedalboard loading or cables and does not restart the UI because a link is absent. Use `python3 scripts/diagnose_mod_ui.py` for a separate non-WebSocket diagnostic and run the PipeWire observer for external links. Install the ARM64 artifacts, NAM/LSP bundles, and declared audio assets before activation. Sustained audio and recovery after a service restart still require on-target verification; external UMC/boundary/mixer/looper links remain observable by the graph observer.
 
@@ -179,7 +176,7 @@ Both mod-host TCP ports currently listen on all interfaces without authenticatio
 
 `config/midi-bindings.yaml` maps MIDI Note On events on channel 1 (channel index 0) to actions, rather than storing plugin paths or commands in the controller configuration. Notes 6–9 select the declared guitar NAM models: Crystal Clean TB, Edge of Breakup TB, Crunch TB, and Overdriven TB. Note Off and Note On with velocity zero are ignored. Each selection declares Crystal Clean TB as its missing-file fallback. If both the requested model and fallback are unavailable, the bridge reports the error and leaves the currently loaded model unchanged.
 
-The NAM model catalog and MIDI input/mod-ui WebSocket settings are declared in `config/desired-state.yaml`. Actions identify their target by chain and processor IDs; the bridge resolves the current NAM instance and sends a file-property `patch_set` through mod-ui, without opening mod-host's TCP socket. It sends the staged copy from mod-ui's `user-files/NAM Models/Rigforge` directory, not the source file in the checkout, so mod-ui can match the path to its selector entry and reflect MIDI changes. The pedalboard remains a single NAM→IR board; changing models does not load another board. SooperLooper’s `config/sooperlooper/fcb1010.slb` remains independent and unchanged.
+The NAM model catalog and MIDI input/mod-ui WebSocket settings are declared in `config/desired-state.yaml`. Actions identify their target by chain and processor IDs; the bridge resolves the current NAM instance and sends a file-property `patch_set` through mod-ui, without opening mod-host's TCP socket. It uses the model copy managed under `~/.local/share/rigforge/mod-ui/NAM Models/Rigforge`, so mod-ui can match the path to its selector entry and reflect MIDI changes. Changing the selected model does not load another board. SooperLooper’s `config/sooperlooper/fcb1010.slb` remains independent and unchanged.
 
 The bridge uses Debian’s `python3-rtmidi` package, included in the recorded target-preparation command above. Check the configuration and inspect MIDI input names with:
 
@@ -230,7 +227,7 @@ journalctl --user -u rigforge-mod-ui.service -b
 
 ### Full engine reset
 
-For recovery testing, `scripts/reset_engine.py` performs an explicit full reset of the logged-in user's audio engine. It restarts `pipewire.service` and `wireplumber.service`, which drops the current PipeWire graph, and then restarts Rigforge services that were enabled or active, along with any required dependencies. It preserves service enablement choices and starts components in dependency order. If mod-ui is deployment-managed, it restores the generated reference pedalboard and preserves the previous default board and last-state file, when present, as adjacent `.rigforge-reset-backup` files.
+For recovery testing, `scripts/reset_engine.py` performs an explicit full reset of the logged-in user's audio engine. It restarts `pipewire.service` and `wireplumber.service`, which drops the current PipeWire graph, and then restarts Rigforge services that were enabled or active, along with any required dependencies. It preserves service enablement choices and starts components in dependency order. The reset no longer generates or restores a mod-ui pedalboard; the board remains under mod-ui user control.
 
 Run it on the target from the Rigforge checkout:
 
@@ -266,7 +263,7 @@ The mod-ui artifact is a runnable bundle at `artifacts/mod-ui/arm64/current/`. I
 MOD_DEV_HOST=1 ~/rigforge/artifacts/mod-ui/arm64/current/run-mod-ui
 ```
 
-From a phone on the same LAN, open `http://<rigforge-LAN-IP>:8888/`. Stop the foreground process with Ctrl-C. This is a UI-only preview: it does not install services, start the Rigforge boundary ports, or load the generated Rigforge board. The new mod-host unit template enables the feedback connection on port 5556, but this service/UI integration has not yet been tested on the target. mod-ui is licensed AGPL-3.0-or-later, with separate trademark restrictions for MOD branding. The build and this manual preview are not yet target-verified.
+From a phone on the same LAN, open `http://<rigforge-LAN-IP>:8888/`. Stop the foreground process with Ctrl-C. This is a UI-only preview: it does not install services, start the Rigforge boundary ports, or load a saved user board. The new mod-host unit template enables the feedback connection on port 5556, but this service/UI integration has not yet been tested on the target. mod-ui is licensed AGPL-3.0-or-later, with separate trademark restrictions for MOD branding. The build and this manual preview are not yet target-verified.
 
 ## `rigforge` target
 

+ 1 - 4
config/desired-state.yaml

@@ -124,10 +124,6 @@ deployment:
     python_path: /usr/bin/python3
     websocket_host: 127.0.0.1
     websocket_port: 8888
-    reference_directory: .local/share/rigforge/mod-ui/references
-    pedalboards_directory: .local/share/rigforge/mod-ui/pedalboards
-    user_files_directory: .local/share/rigforge/mod-ui/user-files
-    last_state_file: .local/share/rigforge/mod-ui/last-rigforge.json
     hardware_input_ports:
       - rigforge.mod-host-input.capture:capture_AUX0
       - rigforge.mod-host-input.capture:capture_AUX1
@@ -154,6 +150,7 @@ deployment:
     service_destination: .config/systemd/user/rigforge-midi-bridge.service
     user_service: rigforge-midi-bridge.service
     python_path: /usr/bin/python3
+    models_directory: .local/share/rigforge/mod-ui/NAM Models/Rigforge
   pipewire:
     fragment_source: config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf
     fragment_destination: .config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf

+ 1 - 5
config/systemd/user/rigforge-mod-ui.service.in

@@ -8,14 +8,10 @@ PartOf=rigforge-mod-host.service
 Type=simple
 Environment=MOD_DEV_ENVIRONMENT=0
 Environment=MOD_DATA_DIR=@MOD_DATA_DIR@
-Environment=MOD_LAST_STATE_JSON=@MOD_LAST_STATE@
-Environment=MOD_USER_PEDALBOARDS_DIR=@PEDALBOARDS_DIR@
-Environment=MOD_USER_FILES_DIR=@USER_FILES_DIR@
-Environment=MOD_DEFAULT_PEDALBOARD=@REFERENCE_PEDALBOARD@
+Environment=MOD_DEFAULT_PEDALBOARD=@MOD_USER_DEFAULT_PEDALBOARD@
 Environment=MOD_RIGFORGE_CAPTURE_PORTS=@RIGFORGE_CAPTURE_PORTS@
 Environment=MOD_RIGFORGE_PLAYBACK_PORTS=@RIGFORGE_PLAYBACK_PORTS@
 Environment=MOD_DEVICE_WEBSERVER_PORT=8888
-ExecStartPre=@PYTHON@ @BOOT_PREPARE_SCRIPT@ --state @DESIRED_STATE@ --runtime-dir %t/rigforge-mod-ui
 ExecStart=@PYTHON@ -u @RUNNER_SCRIPT@ --launcher @MOD_UI_LAUNCHER@ --pw-jack @PW_JACK@
 Restart=on-failure
 RestartSec=5

+ 6 - 268
scripts/deploy.py

@@ -14,7 +14,6 @@ from pathlib import Path, PurePosixPath
 import yaml
 
 from validate_desired_state import validate_state
-from generate_mod_ui_pedalboard import generate_bundle_files
 
 
 ROOT = Path(__file__).resolve().parents[1]
@@ -1082,38 +1081,14 @@ def render_mod_host_ports_service(config):
 
 
 def render_mod_ui_service(config):
-    state_file = ROOT / "config" / "desired-state.yaml"
     launcher = ROOT / config["launcher"]
     runner_script = ROOT / config["runner_script"]
-    boot_prepare_script = ROOT / "scripts" / "prepare_mod_ui_pedalboard.py"
     service_template = ROOT / config["service_source"]
-    with state_file.open(encoding="utf-8") as stream:
-        state = yaml.safe_load(stream)
-    nam_processor = state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
-    nam_model_path = (
-        Path.home()
-        / config["user_files_directory"]
-        / "NAM Models"
-        / "Rigforge"
-        / Path(nam_processor["asset_path"]).name
-    )
-    reference_files = generate_bundle_files(
-        state, ROOT, nam_model_path=nam_model_path
-    )
-    bundle_digest = hashlib.sha256()
-    for name, content_bytes in sorted(reference_files.items()):
-        bundle_digest.update(name.encode("utf-8") + b"\0" + content_bytes + b"\0")
-    reference_pedalboard = (
-        Path.home()
-        / config["reference_directory"]
-        / f"rigforge-guitar-{bundle_digest.hexdigest()[:16]}.pedalboard"
-    )
     diagnostic_script = ROOT / "scripts" / "diagnose_mod_ui.py"
     for description, path in (
         ("mod-ui launcher", launcher),
         ("mod-ui service runner", runner_script),
         ("mod-ui diagnostic", diagnostic_script),
-        ("mod-ui boot preparation script", boot_prepare_script),
         ("mod-ui service template", service_template),
     ):
         if not path.is_file():
@@ -1123,15 +1098,12 @@ def render_mod_ui_service(config):
     replacements = {
         "@PYTHON@": systemd_quote(config["python_path"]),
         "@RUNNER_SCRIPT@": systemd_quote(runner_script.resolve()),
-        "@BOOT_PREPARE_SCRIPT@": systemd_quote(boot_prepare_script.resolve()),
-        "@DESIRED_STATE@": systemd_quote(state_file.resolve()),
         "@MOD_UI_LAUNCHER@": systemd_quote(launcher.resolve()),
         "@PW_JACK@": systemd_quote(config["pw_jack_path"]),
         "@MOD_DATA_DIR@": systemd_quote(home / ".local" / "share" / "rigforge" / "mod-ui"),
-        "@MOD_LAST_STATE@": systemd_quote(home / config["last_state_file"]),
-        "@PEDALBOARDS_DIR@": systemd_quote(home / config["pedalboards_directory"]),
-        "@USER_FILES_DIR@": systemd_quote(home / config["user_files_directory"]),
-        "@REFERENCE_PEDALBOARD@": systemd_quote(reference_pedalboard),
+        "@MOD_USER_DEFAULT_PEDALBOARD@": systemd_quote(
+            home / ".local" / "share" / "rigforge" / "mod-ui" / "pedalboards" / "default.pedalboard"
+        ),
         "@RIGFORGE_CAPTURE_PORTS@": systemd_quote(
             ",".join(config["hardware_input_ports"])
         ),
@@ -1148,25 +1120,19 @@ def render_mod_ui_service(config):
     runtime_digest = hashlib.sha256()
     runtime_digest.update(runtime_tree_sha256(artifact_root).encode("ascii"))
     runtime_digest.update(runner_script.read_bytes())
-    runtime_digest.update(boot_prepare_script.read_bytes())
     runtime_digest.update((ROOT / "scripts" / "mod_ui_websocket.py").read_bytes())
     runtime_digest.update((ROOT / "scripts" / "run_mod_ui_service.py").read_bytes())
     runtime_digest.update((ROOT / "scripts" / "diagnose_mod_ui.py").read_bytes())
     runtime_digest.update((ROOT / "scripts" / "observe_pipewire.py").read_bytes())
     runtime_digest.update((ROOT / "scripts" / "validate_desired_state.py").read_bytes())
-    runtime_digest.update((ROOT / "scripts" / "generate_mod_ui_pedalboard.py").read_bytes())
     runtime_digest.update((ROOT / "scripts" / "diagnose_mod_ui.py").read_bytes())
     runtime_digest.update((ROOT / "build" / "arm64" / "mod_ui_pipewire.py").read_bytes())
     runtime_digest.update((ROOT / "build" / "arm64" / "patch_mod_ui_rigforge.py").read_bytes())
-    for name, content_bytes in sorted(reference_files.items()):
-        runtime_digest.update(name.encode("utf-8") + b"\0" + content_bytes + b"\0")
     content += f"\n# Rigforge runtime fingerprint: {runtime_digest.hexdigest()}\n"
     return {
         "name": config["user_service"],
         "destination": home / config["service_destination"],
         "content": content.encode("utf-8"),
-        "reference_bundle": reference_pedalboard,
-        "reference_files": reference_files,
     }
 
 
@@ -1805,7 +1771,7 @@ def mod_ui_nam_model_sources(state):
 
 def manage_mod_ui_nam_models(action, config, registry, state):
     key = "mod_ui_nam_models"
-    root = Path.home() / config["user_files_directory"] / "NAM Models" / "Rigforge"
+    root = Path.home() / config["models_directory"]
     managed = registry.get(key)
 
     if action == "uninstall":
@@ -1888,7 +1854,7 @@ def manage_mod_ui_nam_models(action, config, registry, state):
     write_registry(registry)
 
 
-def deploy_mod_ui(action, config, registry, force_reference=False):
+def deploy_mod_ui(action, config, registry):
     if action == "install":
         if "mod_host_ports" not in registry:
             raise RuntimeError("install mod-host-ports before installing mod-ui")
@@ -1909,9 +1875,6 @@ def deploy_mod_ui(action, config, registry, force_reference=False):
                 f"an unmanaged {config['user_service']} is already active or enabled; "
                 "inspect it before installing Rigforge's unit"
             )
-    if action == "reset":
-        reset_mod_ui_reference(config, registry)
-        return
     if action == "uninstall" and "midi_bridge" in registry:
         raise RuntimeError("uninstall midi-bridge before uninstalling mod-ui")
     state = yaml.safe_load(
@@ -1920,31 +1883,6 @@ def deploy_mod_ui(action, config, registry, force_reference=False):
     if action == "install":
         manage_mod_ui_nam_models("install", config, registry, state)
     unit = render_mod_ui_service(config)
-    reference_sha256 = None
-    if action != "uninstall":
-        managed = registry.get("mod_ui", {})
-        reference_record = managed.get("reference_bundle", {})
-        trusted_reference_sha256 = None
-        if reference_record.get("destination") == str(unit["reference_bundle"]):
-            trusted_reference_sha256 = reference_record.get("installed_sha256")
-        if force_reference and (
-            not isinstance(trusted_reference_sha256, str)
-            or not trusted_reference_sha256
-        ):
-            raise RuntimeError(
-                "--force-reference requires a registry-managed reference bundle at the generated path"
-            )
-        reference_sha256 = prepare_mod_ui_reference_bundle(
-            unit,
-            trusted_existing_sha256=trusted_reference_sha256,
-            force_reference=force_reference,
-        )
-        if "mod_ui" in registry:
-            registry["mod_ui"]["reference_bundle"] = {
-                "destination": str(unit["reference_bundle"]),
-                "installed_sha256": reference_sha256,
-            }
-            write_registry(registry)
     deploy_single_user_service(
         action,
         "mod_ui",
@@ -1955,196 +1893,6 @@ def deploy_mod_ui(action, config, registry, force_reference=False):
     )
     if action == "uninstall":
         manage_mod_ui_nam_models("uninstall", config, registry, state)
-    if action == "install":
-        registry["mod_ui"]["reference_bundle"] = {
-            "destination": str(unit["reference_bundle"]),
-            "installed_sha256": reference_sha256,
-        }
-        write_registry(registry)
-
-
-def next_reset_backup_path(path):
-    base = path.with_name(path.name + ".rigforge-reset-backup")
-    candidate = base
-    suffix = 1
-    while candidate.exists() or candidate.is_symlink():
-        suffix += 1
-        candidate = base.with_name(base.name + f".{suffix}")
-    validate_user_destination(candidate)
-    return candidate
-
-
-def next_mod_ui_reference_backup_path(destination, forced=False):
-    suffix = "force-backup" if forced else "corrupt-backup"
-    base = destination.with_name(destination.name + f".rigforge-{suffix}")
-    candidate = base
-    suffix = 2
-    while candidate.exists() or candidate.is_symlink():
-        candidate = base.with_name(f"{base.name}.{suffix}")
-        suffix += 1
-    validate_user_destination(candidate)
-    return candidate
-
-
-def prepare_mod_ui_reference_bundle(
-    unit, trusted_existing_sha256=None, force_reference=False
-):
-    destination = unit["reference_bundle"]
-    files = unit["reference_files"]
-    validate_user_destination(destination)
-    if destination.exists():
-        if destination.is_symlink() or not destination.is_dir():
-            raise RuntimeError(f"generated mod-ui reference path has the wrong type: {destination}")
-        current_files = {}
-        for path in destination.rglob("*"):
-            if path.is_symlink():
-                raise RuntimeError(f"generated mod-ui reference contains a symlink: {path}")
-            if path.is_file():
-                current_files[path.relative_to(destination).as_posix()] = path.read_bytes()
-        if current_files != files:
-            current_sha256 = tree_sha256(destination)
-            matches_registry = (
-                trusted_existing_sha256 is not None
-                and current_sha256 == trusted_existing_sha256
-            )
-            if not matches_registry and not (
-                force_reference and trusted_existing_sha256 is not None
-            ):
-                raise RuntimeError(f"generated mod-ui reference changed locally: {destination}")
-            destination.parent.mkdir(parents=True, exist_ok=True)
-            staged = Path(
-                tempfile.mkdtemp(prefix=f".{destination.name}.", dir=destination.parent)
-            )
-            try:
-                for relative, content in files.items():
-                    path = staged / relative
-                    path.parent.mkdir(parents=True, exist_ok=True)
-                    path.write_bytes(content)
-                if tree_sha256(staged) == current_sha256:
-                    raise RuntimeError(
-                        f"regenerated mod-ui reference unexpectedly matches corrupted data: {destination}"
-                    )
-                backup = next_mod_ui_reference_backup_path(
-                    destination, forced=force_reference and not matches_registry
-                )
-                os.replace(destination, backup)
-                print(f"Preserved previous mod-ui reference bundle at {backup}")
-                try:
-                    os.replace(staged, destination)
-                except OSError:
-                    os.replace(backup, destination)
-                    raise
-            finally:
-                if staged.exists():
-                    shutil.rmtree(staged)
-    else:
-        destination.parent.mkdir(parents=True, exist_ok=True)
-        staged = Path(tempfile.mkdtemp(prefix=f".{destination.name}.", dir=destination.parent))
-        try:
-            for relative, content in files.items():
-                path = staged / relative
-                path.parent.mkdir(parents=True, exist_ok=True)
-                path.write_bytes(content)
-            os.replace(staged, destination)
-        finally:
-            if staged.exists():
-                shutil.rmtree(staged)
-    return tree_sha256(destination)
-
-
-def reset_mod_ui_reference(config, registry, manage_services=True):
-    managed = registry.get("mod_ui")
-    if managed is None:
-        raise RuntimeError("mod-ui is not managed; install mod-ui before resetting it")
-    if managed.get("pending_uninstall"):
-        raise RuntimeError("mod-ui uninstall is incomplete; retry uninstall mod-ui first")
-    unit = render_mod_ui_service(config)
-    destination = unit["destination"]
-    if not destination.is_file() or file_sha256(destination) != managed.get("installed_sha256"):
-        raise RuntimeError(f"managed mod-ui service file changed locally: {destination}")
-
-    reference = unit["reference_bundle"]
-    reference_record = managed.get("reference_bundle")
-    if not isinstance(reference_record, dict):
-        raise RuntimeError("mod-ui reference bundle is missing from the deployment registry")
-    reference_sha256 = reference_record.get("installed_sha256")
-    if (
-        reference_record.get("destination") != str(reference)
-        or reference.is_symlink()
-        or not reference.is_dir()
-        or tree_sha256(reference) != reference_sha256
-    ):
-        raise RuntimeError(f"managed mod-ui reference pedalboard changed locally: {reference}")
-    repaired_reference_sha256 = prepare_mod_ui_reference_bundle(
-        unit, trusted_existing_sha256=reference_sha256
-    )
-    if repaired_reference_sha256 != reference_sha256:
-        reference_record["installed_sha256"] = repaired_reference_sha256
-        managed["reference_bundle"] = reference_record
-        registry["mod_ui"] = managed
-        write_registry(registry)
-    pedalboards = Path.home() / config["pedalboards_directory"]
-    default_board = pedalboards / "default.pedalboard"
-    last_state = Path.home() / config["last_state_file"]
-    for path in (default_board, last_state):
-        validate_user_destination(path)
-        if path.is_symlink():
-            raise RuntimeError(f"refusing to reset a symlink: {path}")
-    if default_board.exists() and not default_board.is_dir():
-        raise RuntimeError(f"mod-ui default pedalboard has the wrong type: {default_board}")
-    if last_state.exists() and not last_state.is_file():
-        raise RuntimeError(f"mod-ui last-state path has the wrong type: {last_state}")
-
-    backup_board = next_reset_backup_path(default_board)
-    backup_state = next_reset_backup_path(last_state)
-
-    staged = default_board.with_name(default_board.name + ".rigforge-reset-new")
-    if staged.exists() or staged.is_symlink():
-        raise RuntimeError(f"reset staging path already exists: {staged}")
-    default_board.parent.mkdir(parents=True, exist_ok=True)
-    shutil.copytree(reference, staged, symlinks=False)
-    if manage_services:
-        run(["systemctl", "--user", "stop", config["user_service"]])
-    board_backed_up = False
-    state_backed_up = False
-    reference_installed = False
-    try:
-        if default_board.exists():
-            os.replace(default_board, backup_board)
-            board_backed_up = True
-        if last_state.exists():
-            os.replace(last_state, backup_state)
-            state_backed_up = True
-        os.replace(staged, default_board)
-        reference_installed = True
-        if manage_services:
-            run(["systemctl", "--user", "start", config["user_service"]])
-            run(["systemctl", "--user", "is-active", "--quiet", config["user_service"]])
-            if "midi_bridge" in registry:
-                run(["systemctl", "--user", "start", "rigforge-midi-bridge.service"])
-                run(["systemctl", "--user", "is-active", "--quiet", "rigforge-midi-bridge.service"])
-    except (OSError, subprocess.CalledProcessError):
-        if manage_services:
-            try:
-                run(["systemctl", "--user", "stop", config["user_service"]])
-            except subprocess.CalledProcessError:
-                pass
-        if staged.exists():
-            shutil.rmtree(staged)
-        if reference_installed and default_board.exists():
-            shutil.rmtree(default_board)
-        if board_backed_up and backup_board.exists():
-            os.replace(backup_board, default_board)
-        if state_backed_up and backup_state.exists():
-            os.replace(backup_state, last_state)
-        if manage_services:
-            run(["systemctl", "--user", "start", config["user_service"]])
-        raise
-
-    print(
-        "Rigforge reference pedalboard restored. Previous default and last-state data "
-        "were preserved as adjacent .rigforge-reset-backup files when present."
-    )
 
 
 def deploy_sooperlooper(action, config, registry, state=None):
@@ -2694,7 +2442,7 @@ def deploy_mod_host(action, config, registry):
 
 def main(argv=None):
     parser = argparse.ArgumentParser()
-    parser.add_argument("action", choices=("install", "uninstall", "reload", "reset"))
+    parser.add_argument("action", choices=("install", "uninstall", "reload"))
     parser.add_argument(
         "target",
         choices=(
@@ -2711,16 +2459,7 @@ def main(argv=None):
             "slweb",
         ),
     )
-    parser.add_argument(
-        "--force-reference",
-        action="store_true",
-        help="replace a changed registry-managed mod-ui reference after preserving it",
-    )
     args = parser.parse_args(argv)
-    if args.action == "reset" and args.target != "mod-ui":
-        parser.error("reset is only supported for mod-ui")
-    if args.force_reference and (args.action != "install" or args.target != "mod-ui"):
-        parser.error("--force-reference is only valid with install mod-ui")
     try:
         state = yaml.safe_load((ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8"))
         deployment = load_deployment()
@@ -2741,7 +2480,6 @@ def main(argv=None):
                 args.action,
                 deployment["mod_ui"],
                 registry,
-                force_reference=args.force_reference,
             )
         elif args.target == "reconcile":
             deploy_reconcile(args.action, deployment["reconcile"], registry)

+ 4 - 11
scripts/deploy.sh

@@ -2,20 +2,17 @@
 set -u
 
 usage() {
-    printf 'Usage: %s install|uninstall|reload|reset all|namlv2|lsp|dragonfly-reverb|pipewire|mod-host-ports|mod-host|mod-ui|reconcile|midi-bridge|sooperlooper|slweb [--force-reference (install mod-ui only)]\n' "$0" >&2
+    printf 'Usage: %s install|uninstall|reload all|namlv2|lsp|dragonfly-reverb|pipewire|mod-host-ports|mod-host|mod-ui|reconcile|midi-bridge|sooperlooper|slweb\n' "$0" >&2
     exit 2
 }
 
-force_args=()
-if [[ $# -eq 3 && "$3" == "--force-reference" && "$1" == "install" && "$2" == "mod-ui" ]]; then
-    force_args=(--force-reference)
-elif [[ $# -ne 2 ]]; then
+if [[ $# -ne 2 ]]; then
     usage
 fi
 action=$1
 target=$2
 case "$action" in
-    install|uninstall|reload|reset) ;;
+    install|uninstall|reload) ;;
     *) usage ;;
 esac
 case "$target" in
@@ -23,15 +20,11 @@ case "$target" in
     namlv2|lsp|dragonfly-reverb|pipewire|mod-host-ports|mod-host|mod-ui|reconcile|midi-bridge|sooperlooper|slweb) targets=("$target") ;;
     *) usage ;;
 esac
-if [[ "$action" == reset && "$target" != mod-ui ]]; then
-    usage
-fi
-
 script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
 status=0
 for component in "${targets[@]}"; do
     printf '%s\n' "== $action $component =="
-    if ! python3 "$script_dir/deploy.py" "$action" "$component" "${force_args[@]}"; then
+    if ! python3 "$script_dir/deploy.py" "$action" "$component"; then
         status=1
     fi
 done

+ 2 - 5
scripts/diagnose_mod_ui.py

@@ -127,8 +127,7 @@ def fetch_active_pedalboard_info(host, port, timeout=5):
 
 def inspect_runtime(state_path, host, port, runner=subprocess.run, timeout=5):
     state = yaml.safe_load(Path(state_path).read_text(encoding="utf-8"))
-    mod_ui = state["deployment"]["mod_ui"]
-    data_root = Path.home() / mod_ui["last_state_file"]
+    data_root = Path.home() / ".local" / "share" / "rigforge" / "mod-ui" / "last.json"
     try:
         last_state = json.loads(data_root.read_text(encoding="utf-8"))
     except (OSError, ValueError) as error:
@@ -253,9 +252,7 @@ def main(argv=None):
     try:
         if args.load:
             state = yaml.safe_load(args.state.read_text(encoding="utf-8"))
-            last_state = (
-                Path.home() / state["deployment"]["mod_ui"]["last_state_file"]
-            )
+            last_state = Path.home() / ".local" / "share" / "rigforge" / "mod-ui" / "last.json"
             last_data = json.loads(last_state.read_text(encoding="utf-8"))
             board_path = last_data.get("pedalboard")
             if not board_path:

+ 0 - 594
scripts/generate_mod_ui_pedalboard.py

@@ -1,594 +0,0 @@
-#!/usr/bin/env python3
-"""Generate Rigforge's four-source reference pedalboard bundle for mod-ui."""
-
-import argparse
-import hashlib
-import json
-import os
-import shutil
-import sys
-import tempfile
-from pathlib import Path, PurePosixPath
-
-import yaml
-
-from validate_desired_state import safe_relative_path, validate_state
-
-
-ROOT = Path(__file__).resolve().parents[1]
-
-
-def turtle_string(value):
-    return json.dumps(str(value), ensure_ascii=False)
-
-
-def plugin_state_files(processor, plugin_path):
-    instance = processor["instance"]
-    plugin_uri = processor["plugin_uri"]
-    state_dir = f"effect-{instance}"
-    if processor.get("file_property"):
-        effect_ttl = (
-            "@prefix atom: <http://lv2plug.in/ns/ext/atom#> .\n"
-            "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
-            "@prefix pset: <http://lv2plug.in/ns/ext/presets#> .\n"
-            "@prefix state: <http://lv2plug.in/ns/ext/state#> .\n\n"
-            "<>\n"
-            "    a pset:Preset ;\n"
-            f"    lv2:appliesTo <{plugin_uri}> ;\n"
-            "    state:state [\n"
-            f"        <{processor['file_property']}> {turtle_string(plugin_path)}^^atom:Path\n"
-            "    ] .\n"
-        )
-    else:
-        effect_ttl = (
-            "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
-            "@prefix pset: <http://lv2plug.in/ns/ext/presets#> .\n\n"
-            "<>\n"
-            "    a pset:Preset ;\n"
-            f"    lv2:appliesTo <{plugin_uri}> .\n"
-        )
-    manifest_ttl = (
-        "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
-        "@prefix pset: <http://lv2plug.in/ns/ext/presets#> .\n"
-        "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\n"
-        "<effect.ttl>\n"
-        f"    lv2:appliesTo <{plugin_uri}> ;\n"
-        "    a pset:Preset ;\n"
-        "    rdfs:seeAlso <effect.ttl> .\n"
-    )
-    return {
-        f"{state_dir}/effect.ttl": effect_ttl.encode("utf-8"),
-        f"{state_dir}/manifest.ttl": manifest_ttl.encode("utf-8"),
-    }
-
-
-def resolved_asset(repo_root, relative):
-    if not safe_relative_path(relative):
-        raise ValueError(f"unsafe pedalboard asset path: {relative!r}")
-    path = (repo_root / Path(*PurePosixPath(relative).parts)).resolve()
-    if not path.is_relative_to(repo_root.resolve()) or not path.is_file():
-        raise FileNotFoundError(f"pedalboard asset is missing or outside repository: {path}")
-    return path
-
-
-def generate_bundle_files(state, repo_root=ROOT, asset_root=None, nam_model_path=None):
-    errors = validate_state(state)
-    if errors:
-        raise ValueError("invalid desired state: " + "; ".join(errors))
-
-    repo_root = Path(repo_root).resolve()
-    asset_root = Path(asset_root or repo_root / "artifacts" / "mod-ui" / "arm64" / "current" / "app" / "default.pedalboard")
-    routing = state["routing"]["mod_host_chains"]["guitar"]
-    nam, ir = routing["processors"]
-    voice_chain = state["routing"]["mod_host_chains"]["voice"]
-    voice_processors = voice_chain["processors"]
-    nam_source_path = resolved_asset(repo_root, nam["asset_path"])
-    nam_path = Path(nam_model_path).resolve() if nam_model_path else nam_source_path
-    if not nam_path.is_file():
-        raise FileNotFoundError(f"NAM model file is missing: {nam_path}")
-    ir_path = resolved_asset(repo_root, ir["asset_path"])
-    output_level = nam["parameters"]["output_level"]
-    plugin_files = {}
-    for processor in voice_processors:
-        plugin_files.update(plugin_state_files(processor, ""))
-
-    nam_instance = nam["mod_ui_instance"].removeprefix("/graph/")
-    ir_instance = ir["mod_ui_instance"].removeprefix("/graph/")
-    nam_model_uri = nam["file_property"]
-    ir_file_uri = ir["file_property"]
-    source_labels = {
-        "guitar": "Guitare",
-        "bass": "Basse",
-        "voice": "Micro",
-        "synth": "Synthé",
-    }
-    source_ids = {source["id"] for source in state["sources"]}
-    passthrough_channels = [
-        (index, source_labels[source_id])
-        for index, source_id in enumerate(("guitar", "bass", "voice", "synth"), start=1)
-        if source_id not in ("guitar", "voice") and source_id in source_ids
-    ]
-    additional_ports_ttl = "\n\n".join(
-        f'''<capture_{index}>
-    lv2:index {9 + (index - 2) * 2} ;
-    lv2:name "{label} - Entrée mod-ui" ;
-    lv2:portProperty lv2:connectionOptional ;
-    lv2:symbol "capture_{index}" ;
-    a lv2:AudioPort, lv2:InputPort .
-
-<playback_{index}>
-    lv2:index {10 + (index - 2) * 2} ;
-    lv2:name "{label} - Sortie mod-ui" ;
-    lv2:portProperty lv2:connectionOptional ;
-    lv2:symbol "playback_{index}" ;
-    a lv2:AudioPort, lv2:OutputPort .'''
-        for index, label in passthrough_channels
-    )
-    additional_arcs_list = ", ".join(
-        [f"_:b{index + 2}" for index, _label in passthrough_channels]
-        + [f"_:voice{index}" for index in range(1, len(voice_processors))]
-        + ["_:voice0", "_:voice_out"]
-    )
-    additional_arcs_ttl = "\n\n".join(
-        f"_:b{index + 2} ingen:tail <capture_{index}> ;\n"
-        f"      ingen:head <playback_{index}> ."
-        for index, _label in passthrough_channels
-    )
-    additional_ports_list = ",\n             ".join(
-        f"<{symbol}_{index}>"
-        for index, _label in passthrough_channels
-        for symbol in ("capture", "playback")
-    )
-    voice_processors_ttl = []
-    voice_processor_blocks = []
-    voice_processor_arcs = []
-    for index, processor in enumerate(voice_processors):
-        instance = processor["mod_ui_instance"].removeprefix("/graph/")
-        plugin_uri = processor["plugin_uri"]
-        if processor["id"] == "voice-reverb":
-            plugin_uri = "urn:dragonfly:room"
-        input_symbol = "input_l" if processor["id"] == "voice-reverb" else "in"
-        output_symbol = "output_l" if processor["id"] == "voice-reverb" else "out"
-        label = {
-            "voice-high-pass": "Coupe-bas",
-            "voice-compressor": "Compresseur voix",
-            "voice-de-esser": "De-esser",
-            "voice-reverb": "Réverbération voix",
-        }[processor["id"]]
-        x_position = 160.0 + index * 260.0
-        port_symbols = {
-            "voice-high-pass": ("in", "out", {"mode": "mode", "filter_type": "ft", "filter_mode": "fm", "slope": "s", "frequency_hz": "f", "quality": "q"}),
-            "voice-compressor": ("in", "out", {"compression_mode": "cm", "ratio": "cr", "attack_time_ms": "at", "release_time_ms": "rt"}),
-            "voice-de-esser": ("in", "out", {}),
-            "voice-reverb": ("input_l", "output_l", {"dry_level": "dry_level", "early_level": "early_level", "late_level": "late_level", "size": "size", "predelay_ms": "predelay", "decay_seconds": "decay", "in_low_cut_hz": "in_low_cut", "in_high_cut_hz": "in_high_cut"}),
-        }
-        input_symbol, output_symbol, control_symbols = port_symbols[processor["id"]]
-        port_declarations = [
-            f"<{instance}/{input_symbol}>",
-            f"<{instance}/{output_symbol}>",
-            f"<{instance}/:bypass>",
-        ]
-        if processor["id"] == "voice-reverb":
-            port_declarations.extend(
-                (f"<{instance}/input_r>", f"<{instance}/output_r>")
-            )
-        control_declarations = []
-        for parameter in processor.get("parameters", {}):
-            if processor["id"] == "voice-de-esser":
-                continue
-            symbol = control_symbols[parameter]
-            port_declarations.append(f"<{instance}/{symbol}>")
-            value = processor["parameters"][parameter]
-            if processor["id"] == "voice-high-pass":
-                value = {
-                    "mode": 0,
-                    "filter_type": 1,
-                    "filter_mode": 2,
-                    "slope": 1,
-                    "frequency_hz": 90.0,
-                    "quality": 0.707,
-                }[parameter]
-            elif processor["id"] == "voice-compressor":
-                value = {
-                    "compression_mode": 0,
-                    "ratio": 3.0,
-                    "attack_time_ms": 10.0,
-                    "release_time_ms": 120.0,
-                }[parameter]
-            rendered_value = json.dumps(value) if isinstance(value, str) else str(value)
-            control_declarations.append(
-                f"<{instance}/{symbol}>\n"
-                f"    ingen:value {rendered_value} ;\n"
-                "    a lv2:ControlPort, lv2:InputPort ."
-            )
-        if processor["id"] == "voice-de-esser":
-            values = {
-                "Ratio": 2.0,
-                "Threshold": 0.1,
-                "Attack": 5.0,
-                "Release": 80.0,
-                "Split": 6000.0,
-            }
-            for symbol, value in values.items():
-                port_declarations.append(f"<{instance}/{symbol}>")
-                control_declarations.append(
-                    f"<{instance}/{symbol}>\n"
-                    f"    ingen:value {value} ;\n"
-                    "    a lv2:ControlPort, lv2:InputPort ."
-                )
-        extra_audio_ports = ""
-        if processor["id"] == "voice-reverb":
-            extra_audio_ports = (
-                f"\n\n<{instance}/input_r>\n"
-                "    a lv2:AudioPort, lv2:InputPort .\n"
-                f"\n<{instance}/output_r>\n"
-                "    a lv2:AudioPort, lv2:OutputPort ."
-            )
-        voice_processors_ttl.append(
-            f"""<{instance}>
-    ingen:canvasX {x_position} ;
-    ingen:canvasY 650.0 ;
-    ingen:enabled true ;
-    ingen:polyphonic false ;
-    pedal:instanceLabel "{label}" ;
-    pedal:instanceNumber {processor["instance"]} ;
-    pedal:performanceVisible true ;
-    pedal:performanceIndex {index + 2} ;
-    lv2:prototype <{plugin_uri}> ;
-    lv2:port {", ".join(port_declarations)} ;
-    a ingen:Block .
-
-<{instance}/{input_symbol}>
-    a lv2:AudioPort, lv2:InputPort .
-
-<{instance}/{output_symbol}>
-    a lv2:AudioPort, lv2:OutputPort .
-
-<{instance}/:bypass>
-    ingen:value 0 ;
-    a lv2:ControlPort, lv2:InputPort ."""
-        )
-        voice_processors_ttl[-1] += "\n\n" + "\n\n".join(control_declarations)
-        voice_processors_ttl[-1] += extra_audio_ports
-        if index > 0:
-            previous = voice_processors[index - 1]
-            previous_instance = previous["mod_ui_instance"].removeprefix("/graph/")
-            previous_output = (
-                "output_l" if previous["id"] == "voice-reverb" else "out"
-            )
-            voice_processor_arcs.append(
-                f"_:voice{index} ingen:tail <{previous_instance}/{previous_output}> ;\n"
-                f"      ingen:head <{instance}/{input_symbol}> ."
-            )
-    voice_chain_ttl = "\n\n".join(voice_processors_ttl)
-    voice_chain_arcs_ttl = "\n\n".join(voice_processor_arcs)
-    first_voice = voice_processors[0]
-    last_voice = voice_processors[-1]
-    first_voice_instance = first_voice["mod_ui_instance"].removeprefix("/graph/")
-    last_voice_instance = last_voice["mod_ui_instance"].removeprefix("/graph/")
-    first_voice_input = "in"
-    last_voice_output = "output_l" if last_voice["id"] == "voice-reverb" else "out"
-
-    ttl = f"""\
-@prefix atom:  <http://lv2plug.in/ns/ext/atom#> .
-@prefix doap:  <http://usefulinc.com/ns/doap#> .
-@prefix ingen: <http://drobilla.net/ns/ingen#> .
-@prefix lv2:   <http://lv2plug.in/ns/lv2core#> .
-@prefix midi:  <http://lv2plug.in/ns/ext/midi#> .
-@prefix mod:   <http://moddevices.com/ns/mod#> .
-@prefix patch: <http://lv2plug.in/ns/ext/patch#> .
-@prefix pedal: <http://moddevices.com/ns/modpedal#> .
-@prefix rdfs:  <http://www.w3.org/2000/01/rdf-schema#> .
-@prefix state: <http://lv2plug.in/ns/ext/state#> .
-@prefix xsd:   <http://www.w3.org/2001/XMLSchema#> .
-
-<capture_1>
-    lv2:index 5 ;
-    lv2:name "Guitare - Entrée mod-ui" ;
-    lv2:portProperty lv2:connectionOptional ;
-    lv2:symbol "capture_1" ;
-    a lv2:AudioPort, lv2:InputPort .
-
-<playback_1>
-    lv2:index 6 ;
-    lv2:name "Guitare - Sortie mod-ui" ;
-    lv2:portProperty lv2:connectionOptional ;
-    lv2:symbol "playback_1" ;
-    a lv2:AudioPort, lv2:OutputPort .
-
-{additional_ports_ttl}
-
-{voice_chain_ttl}
-
-<:bpb>
-    ingen:value 4.0 ;
-    lv2:index 0 ;
-    a lv2:ControlPort, lv2:InputPort .
-
-<:bpm>
-    ingen:value 120.0 ;
-    lv2:index 1 ;
-    a lv2:ControlPort, lv2:InputPort .
-
-<:rolling>
-    ingen:value 0 ;
-    lv2:index 2 ;
-    a lv2:ControlPort, lv2:InputPort .
-
-<control_in>
-    atom:bufferType atom:Sequence ;
-    atom:supports midi:MidiEvent ;
-    lv2:index 3 ;
-    lv2:name "Control In" ;
-    lv2:portProperty lv2:connectionOptional ;
-    lv2:symbol "control_in" ;
-    <http://lv2plug.in/ns/ext/resize-port#minimumSize> 4096 ;
-    a atom:AtomPort, lv2:InputPort .
-
-<control_out>
-    atom:bufferType atom:Sequence ;
-    atom:supports midi:MidiEvent ;
-    lv2:index 4 ;
-    lv2:name "Control Out" ;
-    lv2:portProperty lv2:connectionOptional ;
-    lv2:symbol "control_out" ;
-    <http://lv2plug.in/ns/ext/resize-port#minimumSize> 4096 ;
-    a atom:AtomPort, lv2:OutputPort .
-
-<midi_separated_mode>
-    ingen:value 0 ;
-    lv2:index 7 ;
-    a atom:AtomPort, lv2:InputPort .
-
-<midi_loopback>
-    ingen:value 0 ;
-    lv2:index 8 ;
-    a atom:AtomPort, lv2:InputPort .
-
-<{nam_instance}>
-    ingen:canvasX 160.0 ;
-    ingen:canvasY 280.0 ;
-    ingen:enabled true ;
-    ingen:polyphonic false ;
-    lv2:microVersion 0 ;
-    lv2:minorVersion 0 ;
-    mod:builderVersion 0 ;
-    mod:releaseNumber 0 ;
-    pedal:instanceLabel "NAM" ;
-    pedal:instanceNumber {nam["instance"]} ;
-    pedal:performanceVisible true ;
-    pedal:performanceIndex 0 ;
-    lv2:prototype <{nam["plugin_uri"]}> ;
-    lv2:port <{nam_instance}/control>,
-             <{nam_instance}/notify>,
-             <{nam_instance}/input>,
-             <{nam_instance}/output>,
-             <{nam_instance}/input_level>,
-             <{nam_instance}/output_level>,
-             <{nam_instance}/quality_scale>,
-             <{nam_instance}/:bypass> ;
-    state:state [ <{nam_model_uri}> {turtle_string(str(nam_path))}^^atom:Path ] ;
-    a ingen:Block .
-
-<{nam_instance}/control>
-    atom:bufferType atom:Sequence ;
-    atom:supports patch:Message ;
-    lv2:designation lv2:control ;
-    lv2:index 0 ;
-    lv2:symbol "control" ;
-    a atom:AtomPort, lv2:InputPort .
-
-<{nam_instance}/notify>
-    atom:bufferType atom:Sequence ;
-    atom:supports patch:Message ;
-    lv2:designation lv2:control ;
-    lv2:index 1 ;
-    lv2:symbol "notify" ;
-    a atom:AtomPort, lv2:OutputPort .
-
-<{nam_instance}/input>
-    a lv2:AudioPort, lv2:InputPort .
-
-<{nam_instance}/output>
-    a lv2:AudioPort, lv2:OutputPort .
-
-<{nam_instance}/input_level>
-    ingen:value 0.0 ;
-    a lv2:ControlPort, lv2:InputPort .
-
-<{nam_instance}/output_level>
-    ingen:value {output_level} ;
-    a lv2:ControlPort, lv2:InputPort .
-
-<{nam_instance}/quality_scale>
-    ingen:value 1.0 ;
-    a lv2:ControlPort, lv2:InputPort .
-
-<{nam_instance}/:bypass>
-    ingen:value 0 ;
-    a lv2:ControlPort, lv2:InputPort .
-
-<{ir_instance}>
-    ingen:canvasX 620.0 ;
-    ingen:canvasY 280.0 ;
-    ingen:enabled true ;
-    ingen:polyphonic false ;
-    lv2:microVersion 0 ;
-    lv2:minorVersion 0 ;
-    mod:builderVersion 0 ;
-    mod:releaseNumber 0 ;
-    pedal:instanceLabel "Cabinet IR" ;
-    pedal:instanceNumber {ir["instance"]} ;
-    pedal:performanceVisible true ;
-    pedal:performanceIndex 1 ;
-    lv2:prototype <{ir["plugin_uri"]}> ;
-    lv2:port <{ir_instance}/control>,
-             <{ir_instance}/notify>,
-             <{ir_instance}/in>,
-             <{ir_instance}/out>,
-             <{ir_instance}/:bypass> ;
-    state:state [ <{ir_file_uri}> {turtle_string(str(ir_path))}^^atom:Path ] ;
-    a ingen:Block .
-
-<{ir_instance}/control>
-    atom:bufferType atom:Sequence ;
-    atom:supports patch:Message ;
-    lv2:designation lv2:control ;
-    a atom:AtomPort, lv2:InputPort .
-
-<{ir_instance}/notify>
-    atom:bufferType atom:Sequence ;
-    atom:supports patch:Message ;
-    lv2:designation lv2:control ;
-    a atom:AtomPort, lv2:OutputPort .
-
-<{ir_instance}/in>
-    a lv2:AudioPort, lv2:InputPort .
-
-<{ir_instance}/out>
-    a lv2:AudioPort, lv2:OutputPort .
-
-<{ir_instance}/:bypass>
-    ingen:value 0 ;
-    a lv2:ControlPort, lv2:InputPort .
-
-<>
-    doap:name "Rigforge - Guitare NAM/IR, Basse, Micro, Synthé" ;
-    pedal:unitName "Rigforge" ;
-    pedal:unitModel "Generic" ;
-    pedal:width 1200 ;
-    pedal:height 700 ;
-    pedal:addressings <addressings.json> ;
-    pedal:screenshot <screenshot.png> ;
-    pedal:thumbnail <thumbnail.png> ;
-    pedal:formatVersion 2 ;
-    pedal:version 1 ;
-    ingen:polyphony 1 ;
-    ingen:arc _:b1, _:b2, _:b3, {additional_arcs_list} ;
-    ingen:block <{nam_instance}>, <{ir_instance}>, {", ".join(f"<{processor['mod_ui_instance'].removeprefix('/graph/')}>" for processor in voice_processors)} ;
-    lv2:port <:bpb>, <:bpm>, <:rolling>,
-             <control_in>, <control_out>,
-             <capture_1>, <playback_1>,
-             {additional_ports_list},
-             <midi_separated_mode>, <midi_loopback> ;
-    lv2:extensionData <http://lv2plug.in/ns/ext/state#interface> ;
-    a lv2:Plugin, ingen:Graph, pedal:Pedalboard .
-
-_:b1 ingen:tail <capture_1> ;
-     ingen:head <{nam_instance}/input> .
-
-_:b2 ingen:tail <{nam_instance}/output> ;
-     ingen:head <{ir_instance}/in> .
-
-_:b3 ingen:tail <{ir_instance}/out> ;
-     ingen:head <playback_1> .
-
-_:voice0 ingen:tail <capture_3> ;
-        ingen:head <{first_voice_instance}/{first_voice_input}> .
-
-{voice_chain_arcs_ttl}
-
-_:voice_out ingen:tail <{last_voice_instance}/{last_voice_output}> ;
-            ingen:head <playback_3> .
-
-{additional_arcs_ttl}
-"""
-
-    files = {
-        "manifest.ttl": (
-            "@prefix ingen: <http://drobilla.net/ns/ingen#> .\n"
-            "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
-            "@prefix pedal: <http://moddevices.com/ns/modpedal#> .\n"
-            "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\n"
-            "<rigforge-guitar.ttl>\n"
-            "    lv2:prototype ingen:GraphPrototype ;\n"
-            "    a lv2:Plugin, ingen:Graph, pedal:Pedalboard ;\n"
-            "    rdfs:seeAlso <rigforge-guitar.ttl> .\n"
-        ).encode("utf-8"),
-        "rigforge-guitar.ttl": ttl.encode("utf-8"),
-        "addressings.json": b"{}\n",
-        "snapshots.json": b'{"current":0,"snapshots":[]}\n',
-    }
-    files.update(plugin_state_files(nam, nam_path))
-    files.update(plugin_state_files(ir, ir_path))
-    files.update(plugin_files)
-    for image_name in ("screenshot.png", "thumbnail.png"):
-        image = asset_root / image_name
-        if not image.is_file():
-            raise FileNotFoundError(f"mod-ui default board image is missing: {image}")
-        files[image_name] = image.read_bytes()
-    return files
-
-
-def write_bundle(output, files, overwrite=False):
-    output = Path(output)
-    if output.exists():
-        if output.is_symlink() or not output.is_dir():
-            raise RuntimeError(f"pedalboard output is not a regular directory: {output}")
-        existing = {}
-        for path in output.rglob("*"):
-            if path.is_symlink():
-                raise RuntimeError(f"refusing symlink in pedalboard output: {path}")
-            if path.is_file():
-                existing[path.relative_to(output).as_posix()] = path.read_bytes()
-        if existing == files:
-            return
-        if not overwrite:
-            raise RuntimeError(f"pedalboard output already exists and differs: {output}")
-
-    output.parent.mkdir(parents=True, exist_ok=True)
-    temporary = Path(tempfile.mkdtemp(prefix=f".{output.name}.", dir=output.parent))
-    try:
-        for relative, content in files.items():
-            path = temporary / relative
-            path.parent.mkdir(parents=True, exist_ok=True)
-            path.write_bytes(content)
-        if output.exists():
-            backup = output.with_name(output.name + ".rigforge-backup")
-            if backup.exists():
-                raise RuntimeError(f"pedalboard recovery path already exists: {backup}")
-            os.replace(output, backup)
-            try:
-                os.replace(temporary, output)
-            except OSError:
-                os.replace(backup, output)
-                raise
-        else:
-            os.replace(temporary, output)
-    finally:
-        if temporary.exists():
-            shutil.rmtree(temporary)
-
-
-def main(argv=None):
-    parser = argparse.ArgumentParser(description=__doc__)
-    parser.add_argument("--state", type=Path, default=ROOT / "config" / "desired-state.yaml")
-    parser.add_argument("--repo-root", type=Path, default=ROOT)
-    parser.add_argument("--output", type=Path)
-    parser.add_argument("--force", action="store_true", help="replace an existing differing generated bundle")
-    args = parser.parse_args(argv)
-
-    try:
-        state = yaml.safe_load(args.state.read_text(encoding="utf-8"))
-        files = generate_bundle_files(state, args.repo_root)
-        output = args.output
-        if output is None:
-            digest = hashlib.sha256()
-            for name, content in sorted(files.items()):
-                digest.update(name.encode("utf-8") + b"\0" + content + b"\0")
-            reference_directory = state["deployment"]["mod_ui"]["reference_directory"]
-            output = (
-                Path.home()
-                / reference_directory
-                / f"rigforge-guitar-{digest.hexdigest()[:16]}.pedalboard"
-            )
-        write_bundle(output, files, overwrite=args.force)
-    except (OSError, ValueError, RuntimeError, KeyError, TypeError, yaml.YAMLError) as error:
-        print(f"ERROR: {error}", file=sys.stderr)
-        return 1
-    print(f"Generated mod-ui pedalboard: {output}")
-    return 0
-
-
-if __name__ == "__main__":
-    raise SystemExit(main())

+ 11 - 10
scripts/midi_action_bridge.py

@@ -160,17 +160,18 @@ def resolve_asset(repo_root, relative_path):
 def resolve_mod_ui_model(state, repo_root, source_path, user_files_root=None):
     """Resolve a repository NAM model to the matching mod-ui user-files copy."""
     source_path = Path(source_path).resolve()
-    deployment = state.get("deployment", {}).get("mod_ui", {})
-    user_files_directory = deployment.get("user_files_directory")
+    deployment = state.get("deployment", {}).get("midi_bridge", {})
+    user_files_directory = deployment.get("models_directory")
     if not safe_relative_path(user_files_directory):
-        raise ValueError("deployment.mod_ui.user_files_directory must be a safe relative path")
-
-    if user_files_root is None:
-        user_files_root = Path.home() / Path(*PurePosixPath(user_files_directory).parts)
-    user_files_root = Path(user_files_root).resolve()
-    ui_model = (user_files_root / "NAM Models" / "Rigforge" / source_path.name).resolve()
-    if not ui_model.is_relative_to(user_files_root):
-        raise ValueError(f"mod-ui NAM model escapes its user-files directory: {ui_model}")
+        raise ValueError("deployment.midi_bridge.models_directory must be a safe relative path")
+
+    models_root = Path.home() / Path(*PurePosixPath(user_files_directory).parts)
+    if user_files_root is not None:
+        models_root = Path(user_files_root) / "NAM Models" / "Rigforge"
+    models_root = models_root.resolve()
+    ui_model = (models_root / source_path.name).resolve()
+    if not ui_model.is_relative_to(models_root):
+        raise ValueError(f"mod-ui NAM model escapes its models directory: {ui_model}")
     if not ui_model.is_file():
         raise FileNotFoundError(
             f"mod-ui NAM model copy is missing: {ui_model}; reinstall mod-ui to stage it"

+ 0 - 365
scripts/prepare_mod_ui_pedalboard.py

@@ -1,365 +0,0 @@
-#!/usr/bin/env python3
-"""Prepare a clean, validated mod-ui pedalboard once per system boot."""
-
-import argparse
-import hashlib
-import os
-import shutil
-import sys
-import tempfile
-from pathlib import Path, PurePosixPath
-
-import yaml
-
-
-ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(ROOT / "scripts"))
-
-from generate_mod_ui_pedalboard import generate_bundle_files
-
-
-def bundle_digest(files):
-    digest = hashlib.sha256()
-    for name, content in sorted(files.items()):
-        digest.update(name.encode("utf-8") + b"\0" + content + b"\0")
-    return digest.hexdigest()
-
-
-def destination_under_home(home, relative):
-    relative = Path(relative)
-    if relative.is_absolute() or ".." in relative.parts:
-        raise ValueError(f"unsafe mod-ui path: {relative}")
-    destination = home / relative
-    if not destination.resolve().is_relative_to(home.resolve()):
-        raise ValueError(f"mod-ui path escapes the user home directory: {destination}")
-    return destination
-
-
-def validate_generated_bundle(files):
-    required = {
-        "manifest.ttl",
-        "rigforge-guitar.ttl",
-        "addressings.json",
-        "snapshots.json",
-        *{
-            f"effect-{instance}/{filename}"
-            for instance in range(6)
-            for filename in ("manifest.ttl", "effect.ttl")
-        },
-        "screenshot.png",
-        "thumbnail.png",
-    }
-    missing = required - set(files)
-    if missing:
-        raise RuntimeError(
-            "generated pedalboard is missing required files: "
-            + ", ".join(sorted(missing))
-        )
-    empty = sorted(name for name, content in files.items() if not content)
-    if empty:
-        raise RuntimeError(
-            "generated pedalboard contains empty files: " + ", ".join(empty)
-        )
-    graph = files["rigforge-guitar.ttl"].decode("utf-8")
-    if (
-        "pedal:Pedalboard" not in graph
-        or "rigforge_nam" not in graph
-        or "rigforge_ir" not in graph
-        or "rigforge_voice_high_pass" not in graph
-        or "rigforge_voice_compressor" not in graph
-        or "rigforge_voice_de_esser" not in graph
-        or "rigforge_voice_reverb" not in graph
-    ):
-        raise RuntimeError("generated pedalboard graph is incomplete")
-
-
-def read_bundle(directory):
-    if directory.is_symlink() or not directory.is_dir():
-        raise RuntimeError(f"pedalboard bundle is missing or not a directory: {directory}")
-    files = {}
-    for path in directory.rglob("*"):
-        if path.is_symlink():
-            raise RuntimeError(f"pedalboard bundle contains a symlink: {path}")
-        if path.is_file():
-            files[path.relative_to(directory).as_posix()] = path.read_bytes()
-    return files
-
-
-def validate_existing_default(directory):
-    if directory.is_symlink() or not directory.is_dir():
-        raise RuntimeError(f"prepared default pedalboard is unavailable: {directory}")
-    for name in ("manifest.ttl", "rigforge-guitar.ttl"):
-        path = directory / name
-        if path.is_symlink() or not path.is_file() or path.stat().st_size == 0:
-            raise RuntimeError(
-                f"default pedalboard is invalid after boot preparation: {path}"
-            )
-    graph = (directory / "rigforge-guitar.ttl").read_text(encoding="utf-8")
-    if "pedal:Pedalboard" not in graph:
-        raise RuntimeError(f"default pedalboard graph is invalid: {directory}")
-
-
-def reference_bundle_for_state(state, repo_root, home):
-    config = state["deployment"]["mod_ui"]
-    nam = state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
-    nam_model_path = destination_under_home(
-        home,
-        Path(config["user_files_directory"])
-        / "NAM Models"
-        / "Rigforge"
-        / Path(nam["asset_path"]).name,
-    )
-    expected_files = generate_bundle_files(
-        state, repo_root=repo_root, nam_model_path=nam_model_path
-    )
-    reference_directory = destination_under_home(home, config["reference_directory"])
-    if reference_directory.is_dir() and not reference_directory.is_symlink():
-        for candidate in sorted(reference_directory.glob("rigforge-guitar-*.pedalboard")):
-            if not candidate.is_dir() or candidate.is_symlink():
-                continue
-            try:
-                files = read_bundle(candidate)
-                validate_generated_bundle(files)
-            except (OSError, RuntimeError):
-                continue
-            if files == expected_files:
-                return candidate
-    raise RuntimeError("prepared mod-ui reference bundle is unavailable")
-
-
-def next_backup_path(path, boot_id, backup_directory=None):
-    parent = backup_directory or path.parent
-    parent.mkdir(parents=True, exist_ok=True)
-    base = parent / f"{path.name}.rigforge-boot-backup-{boot_id}"
-    candidate = base
-    suffix = 2
-    while candidate.exists() or candidate.is_symlink():
-        candidate = base.with_name(f"{base.name}.{suffix}")
-        suffix += 1
-    return candidate
-
-
-def is_legacy_pedalboard_backup(path):
-    return (
-        path.name == "default.pedalboard.rigforge-backup"
-        or path.name.startswith("default.pedalboard.rigforge-reset-backup")
-        or path.name.startswith("default.pedalboard.rigforge-boot-backup-")
-    )
-
-
-def next_migrated_backup_path(backup_directory, original, boot_id):
-    candidate = backup_directory / original.name
-    if not candidate.exists() and not candidate.is_symlink():
-        return candidate
-    base = backup_directory / f"{original.name}.migrated-{boot_id}"
-    candidate = base
-    suffix = 2
-    while candidate.exists() or candidate.is_symlink():
-        candidate = backup_directory / f"{base.name}.{suffix}"
-        suffix += 1
-    return candidate
-
-
-def migrate_legacy_pedalboard_backups(pedalboards, backup_directory, boot_id):
-    if not pedalboards.is_dir() or pedalboards.is_symlink():
-        return
-    legacy = sorted(path for path in pedalboards.iterdir() if is_legacy_pedalboard_backup(path))
-    if not legacy:
-        return
-    backup_directory.mkdir(parents=True, exist_ok=True)
-    for path in legacy:
-        if path.is_symlink():
-            raise RuntimeError(f"refusing to migrate a symlinked pedalboard backup: {path}")
-        if not path.is_dir():
-            raise RuntimeError(f"legacy pedalboard backup is not a directory: {path}")
-        destination = next_migrated_backup_path(backup_directory, path, boot_id)
-        os.replace(path, destination)
-        print(f"Moved legacy mod-ui backup outside pedalboard scan path: {destination}")
-
-
-def write_staged_bundle(files, destination):
-    destination.parent.mkdir(parents=True, exist_ok=True)
-    staged = Path(
-        tempfile.mkdtemp(prefix=f".{destination.name}.rigforge-new-", dir=destination.parent)
-    )
-    try:
-        for relative, content in files.items():
-            relative_path = PurePosixPath(relative)
-            if relative_path.is_absolute() or ".." in relative_path.parts:
-                raise RuntimeError(f"unsafe generated pedalboard path: {relative}")
-            path = staged.joinpath(*relative_path.parts)
-            path.parent.mkdir(parents=True, exist_ok=True)
-            path.write_bytes(content)
-        if read_bundle(staged) != files:
-            raise RuntimeError(f"staged pedalboard verification failed: {staged}")
-        return staged
-    except BaseException:
-        shutil.rmtree(staged, ignore_errors=True)
-        raise
-
-
-def atomic_write_marker(marker, boot_id):
-    marker.parent.mkdir(parents=True, exist_ok=True)
-    fd, temporary_name = tempfile.mkstemp(prefix=f".{marker.name}.", dir=marker.parent)
-    try:
-        with os.fdopen(fd, "w", encoding="utf-8") as stream:
-            stream.write(boot_id + "\n")
-        os.replace(temporary_name, marker)
-    finally:
-        if os.path.exists(temporary_name):
-            os.unlink(temporary_name)
-
-
-def prepare_pedalboard(state, repo_root, home, runtime_dir, boot_id):
-    config = state["deployment"]["mod_ui"]
-    marker = runtime_dir / "prepared-boot-id"
-    default_board = destination_under_home(
-        home, Path(config["pedalboards_directory"]) / "default.pedalboard"
-    )
-    last_state = destination_under_home(home, config["last_state_file"])
-    backup_directory = destination_under_home(
-        home, Path(config["last_state_file"]).parent / "boot-backups"
-    )
-    migrate_legacy_pedalboard_backups(
-        default_board.parent, backup_directory, boot_id
-    )
-
-    if marker.is_file() and marker.read_text(encoding="utf-8").strip() == boot_id:
-        validate_existing_default(default_board)
-        if last_state.is_symlink():
-            raise RuntimeError(f"refusing to move a mod-ui state symlink: {last_state}")
-        if last_state.exists() and not last_state.is_file():
-            raise RuntimeError(f"mod-ui last-state path is not a file: {last_state}")
-        reference_bundle = reference_bundle_for_state(state, repo_root, home)
-        current_state = (
-            last_state.read_text(encoding="utf-8")
-            if last_state.is_file()
-            else None
-        )
-        expected_state = (
-            f'{{"bank":-2,"pedalboard":"{reference_bundle}","supportsDividers":true}}'
-        )
-        if current_state != expected_state:
-            if last_state.exists():
-                backup = next_backup_path(last_state, boot_id, backup_directory)
-                os.replace(last_state, backup)
-                print(f"Preserved previous mod-ui state at {backup}")
-            last_state.parent.mkdir(parents=True, exist_ok=True)
-            last_state.write_text(expected_state, encoding="utf-8")
-        else:
-            print(
-                "mod-ui pedalboard already prepared during this boot; "
-                "preserving current board"
-            )
-        return
-
-    nam = state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
-    nam_model_path = destination_under_home(
-        home,
-        Path(config["user_files_directory"])
-        / "NAM Models"
-        / "Rigforge"
-        / Path(nam["asset_path"]).name,
-    )
-    files = generate_bundle_files(
-        state, repo_root=repo_root, nam_model_path=nam_model_path
-    )
-    validate_generated_bundle(files)
-    reference = destination_under_home(
-        home,
-        Path(config["reference_directory"])
-        / f"rigforge-guitar-{bundle_digest(files)[:16]}.pedalboard",
-    )
-    for path in (reference, default_board):
-        if path.is_symlink():
-            raise RuntimeError(f"refusing to replace a mod-ui symlink: {path}")
-        if path.exists() and not path.is_dir():
-            raise RuntimeError(f"mod-ui pedalboard path is not a directory: {path}")
-    if last_state.is_symlink():
-        raise RuntimeError(f"refusing to move a mod-ui state symlink: {last_state}")
-    if last_state.exists() and not last_state.is_file():
-        raise RuntimeError(f"mod-ui last-state path is not a file: {last_state}")
-    reference_files = (
-        read_bundle(reference)
-        if reference.exists()
-        else None
-    )
-    replace_reference = reference_files != files
-    staged_reference = write_staged_bundle(files, reference) if replace_reference else None
-    staged_default = write_staged_bundle(files, default_board)
-    backups = []
-    installed = []
-
-    try:
-        if replace_reference and reference.exists():
-            backup = next_backup_path(reference, boot_id)
-            os.replace(reference, backup)
-            backups.append((reference, backup))
-        if default_board.exists():
-            backup = next_backup_path(default_board, boot_id, backup_directory)
-            os.replace(default_board, backup)
-            backups.append((default_board, backup))
-        last_state_backup = None
-        if last_state.exists():
-            last_state_backup = next_backup_path(last_state, boot_id, backup_directory)
-            os.replace(last_state, last_state_backup)
-
-        if staged_reference is not None:
-            os.replace(staged_reference, reference)
-            installed.append(reference)
-        os.replace(staged_default, default_board)
-        installed.append(default_board)
-        validate_existing_default(default_board)
-        if last_state_backup is not None:
-            print(f"Preserved previous mod-ui state at {last_state_backup}")
-        last_state.parent.mkdir(parents=True, exist_ok=True)
-        last_state.write_text(
-            f'{{"bank":-2,"pedalboard":"{reference}","supportsDividers":true}}',
-            encoding="utf-8",
-        )
-        atomic_write_marker(marker, boot_id)
-    except BaseException:
-        if last_state_backup is not None and last_state_backup.exists():
-            os.replace(last_state_backup, last_state)
-        for path in reversed(installed):
-            if path.is_dir() and not path.is_symlink():
-                shutil.rmtree(path)
-            elif path.exists() or path.is_symlink():
-                path.unlink()
-        for original, backup in reversed(backups):
-            if backup.exists() or backup.is_symlink():
-                os.replace(backup, original)
-        raise
-    finally:
-        for staged in (staged_reference, staged_default):
-            if staged is not None and staged.exists():
-                shutil.rmtree(staged, ignore_errors=True)
-
-    print(f"Prepared a clean mod-ui pedalboard for boot {boot_id}")
-
-
-def main(argv=None):
-    parser = argparse.ArgumentParser(description=__doc__)
-    parser.add_argument("--state", type=Path, default=ROOT / "config" / "desired-state.yaml")
-    parser.add_argument("--runtime-dir", type=Path, required=True)
-    args = parser.parse_args(argv)
-    try:
-        state = yaml.safe_load(args.state.read_text(encoding="utf-8"))
-        boot_id = Path("/proc/sys/kernel/random/boot_id").read_text(encoding="ascii").strip()
-        if not boot_id:
-            raise RuntimeError("could not determine the current system boot ID")
-        prepare_pedalboard(
-            state,
-            repo_root=ROOT,
-            home=Path.home(),
-            runtime_dir=args.runtime_dir,
-            boot_id=boot_id,
-        )
-    except (OSError, RuntimeError, ValueError, KeyError) as error:
-        print(f"ERROR: {error}", file=sys.stderr)
-        return 1
-    return 0
-
-
-if __name__ == "__main__":
-    raise SystemExit(main())

+ 1 - 10
scripts/reset_engine.py

@@ -185,14 +185,6 @@ def reset_engine(deployment, registry, runner=subprocess.run):
         if role in roles:
             checked_command(["systemctl", "--user", "stop", units[role]], runner)
 
-    if "mod_ui" in registry:
-        print("Restoring the generated mod-ui pedalboard; existing board state is backed up.")
-        deploy.reset_mod_ui_reference(
-            deployment["mod_ui"], registry, manage_services=False
-        )
-    else:
-        print("mod-ui is not managed by Rigforge; skipping pedalboard-file reset.")
-
     print("Restarting PipeWire, then bringing WirePlumber back on its graph.")
     checked_command(["systemctl", "--user", "stop", WIREPLUMBER_UNIT], runner)
     checked_command(["systemctl", "--user", "restart", PIPEWIRE_UNIT], runner)
@@ -267,8 +259,7 @@ def confirm_reset(yes):
     print(
         "WARNING: this interrupts audio, restarts PipeWire and WirePlumber, "
         "and restarts enabled Rigforge audio services. In-memory SooperLooper "
-        "recordings may be lost. The current mod-ui board and last state will "
-        "be backed up before restoring the generated reference board."
+        "recordings may be lost. mod-ui will restore its saved user pedalboard."
     )
     if yes:
         return True

+ 7 - 4
scripts/validate_desired_state.py

@@ -820,10 +820,6 @@ def validate_state(state):
                 ("pw_jack_path", "/usr/bin/pw-jack"),
                 ("python_path", "/usr/bin/python3"),
                 ("websocket_host", "127.0.0.1"),
-                ("reference_directory", ".local/share/rigforge/mod-ui/references"),
-                ("pedalboards_directory", ".local/share/rigforge/mod-ui/pedalboards"),
-                ("user_files_directory", ".local/share/rigforge/mod-ui/user-files"),
-                ("last_state_file", ".local/share/rigforge/mod-ui/last-rigforge.json"),
             ):
                 if mod_ui.get(key) != expected:
                     errors.append(f"deployment.mod_ui.{key} must be {expected}")
@@ -921,6 +917,13 @@ def validate_state(state):
         if not isinstance(midi_bridge, dict):
             errors.append("deployment.midi_bridge must be a mapping")
         else:
+            if midi_bridge.get("models_directory") != (
+                ".local/share/rigforge/mod-ui/NAM Models/Rigforge"
+            ):
+                errors.append(
+                    "deployment.midi_bridge.models_directory must be "
+                    ".local/share/rigforge/mod-ui/NAM Models/Rigforge"
+                )
             for key, expected in (
                 ("bridge_script", "scripts/midi_action_bridge.py"),
                 (

+ 9 - 179
tests/test_deploy.py

@@ -835,7 +835,7 @@ class DeploymentTests(unittest.TestCase):
             ],
         )
 
-    def test_mod_ui_service_uses_reference_board_and_port_bridge(self):
+    def test_mod_ui_service_leaves_pedalboards_user_managed_and_configures_ports(self):
         registry = {
             "mod_host_ports": {},
             "mod_host": {},
@@ -846,10 +846,10 @@ class DeploymentTests(unittest.TestCase):
 
         content = destination.read_text(encoding="utf-8")
         self.assertIn("run_mod_ui_service.py", content)
-        self.assertIn("prepare_mod_ui_pedalboard.py", content)
-        self.assertIn("ExecStartPre=", content)
-        self.assertIn("--runtime-dir %t/rigforge-mod-ui", content)
-        self.assertIn("MOD_DEFAULT_PEDALBOARD=", content)
+        self.assertNotIn("prepare_mod_ui_pedalboard.py", content)
+        self.assertNotIn("ExecStartPre=", content)
+        self.assertNotIn("MOD_DEFAULT_PEDALBOARD=", content)
+        self.assertNotIn("MOD_LAST_STATE_JSON=", content)
         self.assertIn(
             "MOD_RIGFORGE_CAPTURE_PORTS="
             '"rigforge.mod-host-input.capture:capture_AUX0,'
@@ -863,10 +863,7 @@ class DeploymentTests(unittest.TestCase):
             content,
         )
         self.assertNotIn("--state", content.split("ExecStart=", 1)[1].splitlines()[0])
-        self.assertIn(
-            f'MOD_USER_FILES_DIR="{self.home / config["user_files_directory"]}"',
-            content,
-        )
+        self.assertNotIn("MOD_USER_FILES_DIR=", content)
         self.assertIn("Requires=rigforge-mod-host.service rigforge-mod-host-ports.service", content)
         self.assertIn("pw-jack", content)
 
@@ -876,21 +873,16 @@ class DeploymentTests(unittest.TestCase):
             "mod_host": {},
         }
         config = deploy.load_deployment()["mod_ui"]
+        midi_config = deploy.load_deployment()["midi_bridge"]
         deploy.deploy_mod_ui("install", config, registry)
 
-        model_root = self.home / config["user_files_directory"] / "NAM Models" / "Rigforge"
+        model_root = self.home / midi_config["models_directory"]
         state = deploy.yaml.safe_load(
             (ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8")
         )
         model_names = set(deploy.mod_ui_nam_model_sources(state))
         self.assertEqual({path.name for path in model_root.iterdir()}, model_names)
 
-        reference = Path(
-            deploy.read_registry()["mod_ui"]["reference_bundle"]["destination"]
-        )
-        ttl = (reference / "rigforge-guitar.ttl").read_text(encoding="utf-8")
-        self.assertIn(str(model_root / "Vox_AC15CH_Crystal_Clean_TB.nam"), ttl)
-
         deploy.deploy_mod_ui("uninstall", config, deploy.read_registry())
         self.assertFalse(model_root.exists())
         self.assertNotIn("mod_ui_nam_models", deploy.read_registry())
@@ -904,9 +896,7 @@ class DeploymentTests(unittest.TestCase):
         deploy.deploy_mod_ui("install", config, registry)
         model = (
             self.home
-            / config["user_files_directory"]
-            / "NAM Models"
-            / "Rigforge"
+            / deploy.load_deployment()["midi_bridge"]["models_directory"]
             / "Vox_AC15CH_Crunch_TB.nam"
         )
         model.write_bytes(b"local change")
@@ -917,166 +907,6 @@ class DeploymentTests(unittest.TestCase):
         self.assertEqual(model.read_bytes(), b"local change")
         self.assertIn("mod_ui_nam_models", deploy.read_registry())
 
-    def test_mod_ui_reference_bundle_is_immutable_after_install(self):
-        config = deploy.load_deployment()["mod_ui"]
-        registry = {"mod_host_ports": {}, "mod_host": {}}
-        deploy.deploy_mod_ui("install", config, registry)
-        reference = Path(deploy.read_registry()["mod_ui"]["reference_bundle"]["destination"])
-        ttl = reference / "rigforge-guitar.ttl"
-        ttl.write_bytes(ttl.read_bytes() + b"\n# local change\n")
-        with self.assertRaisesRegex(RuntimeError, "changed locally"):
-            deploy.deploy_mod_ui("install", config, deploy.read_registry())
-
-    def test_mod_ui_install_repairs_registered_corrupt_reference_bundle(self):
-        config = deploy.load_deployment()["mod_ui"]
-        registry = {
-            "mod_host_ports": {},
-            "mod_host": {},
-        }
-        deploy.deploy_mod_ui("install", config, registry)
-        registry = deploy.read_registry()
-        reference = Path(registry["mod_ui"]["reference_bundle"]["destination"])
-        graph = reference / "rigforge-guitar.ttl"
-        graph.write_bytes(b"")
-        registry["mod_ui"]["reference_bundle"]["installed_sha256"] = deploy.tree_sha256(
-            reference
-        )
-        deploy.write_registry(registry)
-        self.commands.clear()
-
-        deploy.deploy_mod_ui("install", config, deploy.read_registry())
-
-        repaired_registry = deploy.read_registry()
-        repaired_reference = Path(
-            repaired_registry["mod_ui"]["reference_bundle"]["destination"]
-        )
-        self.assertGreater((repaired_reference / "rigforge-guitar.ttl").stat().st_size, 0)
-        corrupt_backup = repaired_reference.with_name(
-            repaired_reference.name + ".rigforge-corrupt-backup"
-        )
-        self.assertEqual(
-            (corrupt_backup / "rigforge-guitar.ttl").read_bytes(),
-            b"",
-        )
-        self.assertEqual(
-            repaired_registry["mod_ui"]["reference_bundle"]["installed_sha256"],
-            deploy.tree_sha256(repaired_reference),
-        )
-
-    def test_mod_ui_force_install_backs_up_and_replaces_registry_hash_mismatch(self):
-        config = deploy.load_deployment()["mod_ui"]
-        registry = {
-            "mod_host_ports": {},
-            "mod_host": {},
-        }
-        deploy.deploy_mod_ui("install", config, registry)
-        registry = deploy.read_registry()
-        reference = Path(registry["mod_ui"]["reference_bundle"]["destination"])
-        graph = reference / "rigforge-guitar.ttl"
-        graph.write_bytes(b"changed outside deploy\n")
-        original = graph.read_bytes()
-
-        with self.assertRaisesRegex(RuntimeError, "changed locally"):
-            deploy.deploy_mod_ui("install", config, deploy.read_registry())
-        self.assertEqual(graph.read_bytes(), original)
-
-        deploy.deploy_mod_ui(
-            "install", config, deploy.read_registry(), force_reference=True
-        )
-
-        repaired_registry = deploy.read_registry()
-        repaired_reference = Path(
-            repaired_registry["mod_ui"]["reference_bundle"]["destination"]
-        )
-        backup = repaired_reference.with_name(
-            repaired_reference.name + ".rigforge-force-backup"
-        )
-        self.assertEqual((backup / "rigforge-guitar.ttl").read_bytes(), original)
-        self.assertGreater((repaired_reference / "rigforge-guitar.ttl").stat().st_size, 0)
-        self.assertEqual(
-            repaired_registry["mod_ui"]["reference_bundle"]["installed_sha256"],
-            deploy.tree_sha256(repaired_reference),
-        )
-
-    def test_mod_ui_force_install_requires_a_registered_reference_bundle(self):
-        config = deploy.load_deployment()["mod_ui"]
-        registry = {
-            "mod_host_ports": {},
-            "mod_host": {},
-        }
-        state = deploy.yaml.safe_load(
-            (ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8")
-        )
-        deploy.manage_mod_ui_nam_models("install", config, registry, state)
-        reference = Path(deploy.render_mod_ui_service(config)["reference_bundle"])
-        reference.mkdir(parents=True)
-        (reference / "local-file").write_text("do not replace", encoding="utf-8")
-
-        with self.assertRaisesRegex(RuntimeError, "requires a registry-managed"):
-            deploy.deploy_mod_ui(
-                "install", config, registry, force_reference=True
-            )
-
-        self.assertEqual(
-            (reference / "local-file").read_text(encoding="utf-8"),
-            "do not replace",
-        )
-
-    def test_mod_ui_reset_restores_reference_and_backs_up_user_state(self):
-        registry = {
-            "mod_host_ports": {},
-            "mod_host": {},
-        }
-        config = deploy.load_deployment()["mod_ui"]
-        deploy.deploy_mod_ui("install", config, registry)
-        registry = deploy.read_registry()
-        board = self.home / config["pedalboards_directory"] / "default.pedalboard"
-        board.mkdir(parents=True)
-        (board / "user-edit.txt").write_text("keep this backup", encoding="utf-8")
-        last_state = self.home / config["last_state_file"]
-        last_state.parent.mkdir(parents=True, exist_ok=True)
-        last_state.write_text('{"bank":0,"pedalboard":"/old/board"}\n', encoding="utf-8")
-        self.commands.clear()
-
-        deploy.deploy_mod_ui("reset", config, registry)
-
-        reference = Path(
-            deploy.read_registry()["mod_ui"]["reference_bundle"]["destination"]
-        )
-        self.assertEqual((board / "rigforge-guitar.ttl").read_bytes(),
-                         (reference / "rigforge-guitar.ttl").read_bytes())
-        self.assertTrue(
-            (board.with_name("default.pedalboard.rigforge-reset-backup") / "user-edit.txt").is_file()
-        )
-        self.assertFalse(last_state.exists())
-        self.assertTrue(
-            last_state.with_name(last_state.name + ".rigforge-reset-backup").is_file()
-        )
-        self.assertEqual(
-            self.commands,
-            [
-                ["systemctl", "--user", "stop", "rigforge-mod-ui.service"],
-                ["systemctl", "--user", "start", "rigforge-mod-ui.service"],
-                ["systemctl", "--user", "is-active", "--quiet", "rigforge-mod-ui.service"],
-            ],
-        )
-
-    def test_mod_ui_reset_can_restore_board_without_managing_service_lifecycle(self):
-        registry = {
-            "mod_host_ports": {},
-            "mod_host": {},
-        }
-        config = deploy.load_deployment()["mod_ui"]
-        deploy.deploy_mod_ui("install", config, registry)
-        registry = deploy.read_registry()
-        self.commands.clear()
-
-        deploy.reset_mod_ui_reference(config, registry, manage_services=False)
-
-        self.assertEqual(self.commands, [])
-        board = self.home / config["pedalboards_directory"] / "default.pedalboard"
-        self.assertTrue((board / "rigforge-guitar.ttl").is_file())
-
     def test_mod_host_install_refuses_an_existing_control_socket(self):
         self.install_mod_host_ports_prerequisite()
         with patch.object(deploy, "mod_host_port_is_open", return_value=True):

+ 1 - 1
tests/test_diagnose_mod_ui.py

@@ -75,7 +75,7 @@ class DiagnoseModUiTests(unittest.TestCase):
         self.state_path.write_text(
             "deployment:\n"
             "  mod_ui:\n"
-            "    last_state_file: .local/share/rigforge/mod-ui/last.json\n",
+            "    data_directory: .local/share/rigforge/mod-ui\n",
             encoding="utf-8",
         )
 

+ 0 - 154
tests/test_mod_ui_pedalboard.py

@@ -1,154 +0,0 @@
-import json
-import sys
-import tempfile
-import unittest
-from pathlib import Path
-
-import yaml
-
-ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(ROOT / "scripts"))
-
-from generate_mod_ui_pedalboard import generate_bundle_files, write_bundle
-from validate_desired_state import validate_state
-
-
-class ModUiPedalboardTests(unittest.TestCase):
-    @classmethod
-    def setUpClass(cls):
-        cls.state = yaml.safe_load(
-            (ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8")
-        )
-
-    def test_generated_bundle_has_nam_ir_state_and_boundary_cables(self):
-        files = generate_bundle_files(self.state, ROOT)
-        ttl = files["rigforge-guitar.ttl"].decode("utf-8")
-
-        self.assertIn(
-            'doap:name "Rigforge - Guitare NAM/IR, Basse, Micro, Synthé"',
-            ttl,
-        )
-        self.assertIn('lv2:name "Guitare - Entrée mod-ui"', ttl)
-        self.assertIn('lv2:name "Guitare - Sortie mod-ui"', ttl)
-        self.assertIn("<control_in>", ttl)
-        self.assertIn("<control_out>", ttl)
-        self.assertIn("<midi_separated_mode>", ttl)
-        self.assertIn("state:state [", ttl)
-        self.assertIn(
-            f'<{self.state["routing"]["mod_host_chains"]["guitar"]["processors"][0]["file_property"]}>',
-            ttl,
-        )
-        self.assertIn(
-            '<http://lsp-plug.in/plugins/lv2/impulse_responses_mono/ports#ifn>',
-            ttl,
-        )
-        self.assertIn("ingen:tail <rigforge_nam/output>", ttl)
-        self.assertIn("ingen:head <rigforge_ir/in>", ttl)
-        self.assertIn("ingen:tail <capture_1>", ttl)
-        self.assertIn("ingen:head <rigforge_nam/input>", ttl)
-        self.assertIn("ingen:tail <rigforge_ir/out>", ttl)
-        self.assertIn("ingen:head <playback_1>", ttl)
-        voice_chain = self.state["routing"]["mod_host_chains"]["voice"]
-        voice_processors = voice_chain["processors"]
-        self.assertIn("<rigforge_voice_high_pass>", ttl)
-        self.assertIn("<rigforge_voice_compressor>", ttl)
-        self.assertIn("<rigforge_voice_de_esser>", ttl)
-        self.assertIn("<rigforge_voice_reverb>", ttl)
-        self.assertIn('pedal:instanceLabel "Coupe-bas"', ttl)
-        self.assertIn('pedal:instanceLabel "Compresseur voix"', ttl)
-        self.assertIn('pedal:instanceLabel "De-esser"', ttl)
-        self.assertIn('pedal:instanceLabel "Réverbération voix"', ttl)
-        self.assertIn("ingen:tail <capture_3>", ttl)
-        self.assertIn("ingen:head <rigforge_voice_high_pass/in>", ttl)
-        self.assertIn(
-            "ingen:tail <rigforge_voice_high_pass/out>", ttl
-        )
-        self.assertIn(
-            "ingen:head <rigforge_voice_compressor/in>", ttl
-        )
-        self.assertIn(
-            "ingen:tail <rigforge_voice_de_esser/out>", ttl
-        )
-        self.assertIn(
-            "ingen:head <rigforge_voice_reverb/input_l>", ttl
-        )
-        self.assertIn(
-            "a lv2:AudioPort, lv2:InputPort .",
-            ttl[ttl.index("<rigforge_voice_reverb/input_r>") :],
-        )
-        self.assertIn("<rigforge_voice_reverb/output_r>", ttl)
-        self.assertIn("ingen:head <playback_3>", ttl)
-        for index, processor in enumerate(voice_processors):
-            instance = processor["mod_ui_instance"].removeprefix("/graph/")
-            self.assertIn(f"lv2:prototype <{processor['plugin_uri']}>", ttl)
-            if index:
-                previous = voice_processors[index - 1]
-                previous_instance = previous["mod_ui_instance"].removeprefix("/graph/")
-                previous_output = previous["output_port"].split(":", 1)[1]
-                input_symbol = processor["input_port"].split(":", 1)[1]
-                self.assertIn(
-                    f"ingen:tail <{previous_instance}/{previous_output}>", ttl
-                )
-                self.assertIn(f"ingen:head <{instance}/{input_symbol}>", ttl)
-        nam = self.state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
-        ir = self.state["routing"]["mod_host_chains"]["guitar"]["processors"][1]
-        nam_state = files[f"effect-{nam['instance']}/effect.ttl"].decode("utf-8")
-        ir_state = files[f"effect-{ir['instance']}/effect.ttl"].decode("utf-8")
-        self.assertIn(f"lv2:appliesTo <{nam['plugin_uri']}>", nam_state)
-        self.assertIn(
-            f'<{nam["file_property"]}> {json.dumps(str((ROOT / nam["asset_path"]).resolve()))}^^atom:Path',
-            nam_state,
-        )
-        self.assertIn(f"lv2:appliesTo <{ir['plugin_uri']}>", ir_state)
-        self.assertIn(
-            f'<{ir["file_property"]}> {json.dumps(str((ROOT / ir["asset_path"]).resolve()))}^^atom:Path',
-            ir_state,
-        )
-        self.assertIn(
-            "<effect.ttl>\n\tlv2:appliesTo",
-            files[f"effect-{nam['instance']}/manifest.ttl"].decode("utf-8").replace(
-                "    ", "\t"
-            ),
-        )
-        for channel, label in ((2, "Basse"), (4, "Synthé")):
-            self.assertIn(f'lv2:name "{label} - Entrée mod-ui"', ttl)
-            self.assertIn(f'lv2:name "{label} - Sortie mod-ui"', ttl)
-            self.assertIn(f"ingen:tail <capture_{channel}>", ttl)
-            self.assertIn(f"ingen:head <playback_{channel}>", ttl)
-        self.assertEqual(files["addressings.json"], b"{}\n")
-
-    def test_generated_plugin_state_uses_target_model_path_with_spaces(self):
-        with tempfile.TemporaryDirectory() as temporary:
-            model = Path(temporary) / "NAM Models" / "Vox Crunch.nam"
-            model.parent.mkdir()
-            model.write_bytes(b"model")
-
-            files = generate_bundle_files(
-                self.state, ROOT, nam_model_path=model
-            )
-
-        nam = self.state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
-        nam_state = files[f"effect-{nam['instance']}/effect.ttl"].decode("utf-8")
-        self.assertIn(f"{json.dumps(str(model.resolve()))}^^atom:Path", nam_state)
-
-    def test_generated_bundle_tracks_current_desired_state(self):
-        expected = generate_bundle_files(self.state, ROOT)
-        with tempfile.TemporaryDirectory() as temporary:
-            directory = Path(temporary) / "reference.pedalboard"
-            write_bundle(directory, expected)
-            actual = {
-                path.relative_to(directory).as_posix(): path.read_bytes()
-                for path in directory.rglob("*")
-                if path.is_file()
-            }
-            self.assertEqual(actual, expected)
-        self.assertEqual(validate_state(self.state), [])
-
-    def test_generation_rejects_missing_asset(self):
-        with tempfile.TemporaryDirectory() as directory:
-            with self.assertRaisesRegex(FileNotFoundError, "missing or outside repository"):
-                generate_bundle_files(self.state, Path(directory))
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 191
tests/test_prepare_mod_ui_pedalboard.py

@@ -1,191 +0,0 @@
-import shutil
-import sys
-import tempfile
-import unittest
-from pathlib import Path
-
-import yaml
-
-ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(ROOT / "scripts"))
-
-import prepare_mod_ui_pedalboard as prepare
-
-
-class PrepareModUiPedalboardTests(unittest.TestCase):
-    def setUp(self):
-        self.temporary = tempfile.TemporaryDirectory()
-        self.root = Path(self.temporary.name)
-        self.home = self.root / "home"
-        self.home.mkdir()
-        self.runtime_dir = self.root / "runtime" / "rigforge-mod-ui"
-        self.state = yaml.safe_load(
-            (ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8")
-        )
-        config = self.state["deployment"]["mod_ui"]
-        nam = self.state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
-        model_source = ROOT / nam["asset_path"]
-        self.model = (
-            self.home
-            / config["user_files_directory"]
-            / "NAM Models"
-            / "Rigforge"
-            / model_source.name
-        )
-        self.model.parent.mkdir(parents=True)
-        shutil.copy2(model_source, self.model)
-        self.default_board = (
-            self.home / config["pedalboards_directory"] / "default.pedalboard"
-        )
-        self.last_state = self.home / config["last_state_file"]
-        self.backup_directory = self.last_state.parent / "boot-backups"
-
-    def tearDown(self):
-        self.temporary.cleanup()
-
-    def prepare(self, boot_id):
-        prepare.prepare_pedalboard(
-            self.state,
-            repo_root=ROOT,
-            home=self.home,
-            runtime_dir=self.runtime_dir,
-            boot_id=boot_id,
-        )
-
-    def expected_files(self):
-        return prepare.generate_bundle_files(
-            self.state,
-            repo_root=ROOT,
-            nam_model_path=self.model,
-        )
-
-    def test_boot_creates_valid_board_and_backs_up_previous_state(self):
-        self.default_board.mkdir(parents=True)
-        (self.default_board / "manifest.ttl").write_bytes(b"")
-        self.last_state.parent.mkdir(parents=True, exist_ok=True)
-        self.last_state.write_text(
-            '{"bank":-2,"pedalboard":"","supportsDividers":true}', encoding="utf-8"
-        )
-
-        self.prepare("boot-one")
-
-        files = self.expected_files()
-        self.assertEqual(prepare.read_bundle(self.default_board), files)
-        reference = (
-            self.home
-            / self.state["deployment"]["mod_ui"]["reference_directory"]
-            / f"rigforge-guitar-{prepare.bundle_digest(files)[:16]}.pedalboard"
-        )
-        self.assertEqual(prepare.read_bundle(reference), files)
-        self.assertEqual(
-            self.last_state.read_text(encoding="utf-8"),
-            f'{{"bank":-2,"pedalboard":"{reference}","supportsDividers":true}}',
-        )
-        graph = files["rigforge-guitar.ttl"].decode("utf-8")
-        self.assertIn("<rigforge_voice_high_pass>", graph)
-        self.assertIn("<rigforge_voice_compressor>", graph)
-        self.assertIn("<rigforge_voice_de_esser>", graph)
-        self.assertIn("<rigforge_voice_reverb>", graph)
-        self.assertTrue(
-            (
-                self.backup_directory
-                / (self.default_board.name + ".rigforge-boot-backup-boot-one")
-                / "manifest.ttl"
-            ).exists()
-        )
-        self.assertFalse(
-            self.default_board.with_name(
-                self.default_board.name + ".rigforge-boot-backup-boot-one"
-            ).exists()
-        )
-
-    def test_repeated_start_same_boot_preserves_in_session_board_and_state(self):
-        self.prepare("boot-one")
-        graph = self.default_board / "rigforge-guitar.ttl"
-        graph.write_bytes(graph.read_bytes() + b"\n# session edit\n")
-
-        self.prepare("boot-one")
-
-        self.assertIn(b"# session edit", graph.read_bytes())
-        expected_reference = (
-            self.home
-            / self.state["deployment"]["mod_ui"]["reference_directory"]
-            / f"rigforge-guitar-{prepare.bundle_digest(self.expected_files())[:16]}.pedalboard"
-        )
-        self.assertEqual(
-            self.last_state.read_text(encoding="utf-8"),
-            f'{{"bank":-2,"pedalboard":"{expected_reference}","supportsDividers":true}}',
-        )
-
-    def test_new_boot_repairs_reference_and_starts_from_clean_board(self):
-        self.prepare("boot-one")
-        reference = next(
-            (self.home / self.state["deployment"]["mod_ui"]["reference_directory"]).glob(
-                "rigforge-guitar-*.pedalboard"
-            )
-        )
-        (reference / "rigforge-guitar.ttl").write_bytes(b"")
-        (self.default_board / "rigforge-guitar.ttl").write_bytes(b"session edit")
-        self.last_state.write_text('{"bank":1,"pedalboard":"/session"}\n', encoding="utf-8")
-
-        self.prepare("boot-two")
-
-        expected = self.expected_files()
-        self.assertEqual(prepare.read_bundle(reference), expected)
-        self.assertEqual(prepare.read_bundle(self.default_board), expected)
-        self.assertEqual(
-            (reference.with_name(
-                reference.name + ".rigforge-boot-backup-boot-two"
-            ) / "rigforge-guitar.ttl").read_bytes(),
-            b"",
-        )
-        self.assertEqual(
-            (
-                self.backup_directory
-                / (self.default_board.name + ".rigforge-boot-backup-boot-two")
-                / "rigforge-guitar.ttl"
-            ).read_bytes(),
-            b"session edit",
-        )
-
-    def test_legacy_sibling_backups_are_moved_out_of_mod_ui_scan_directory(self):
-        legacy_paths = (
-            self.default_board.with_name(
-                self.default_board.name + ".rigforge-boot-backup-previous"
-            ),
-            self.default_board.with_name(
-                self.default_board.name + ".rigforge-reset-backup.4"
-            ),
-        )
-        for legacy in legacy_paths:
-            legacy.mkdir(parents=True)
-            (legacy / "manifest.ttl").write_bytes(b"")
-
-        self.prepare("boot-one")
-
-        for legacy in legacy_paths:
-            self.assertFalse(legacy.exists())
-            self.assertTrue(
-                (self.backup_directory / legacy.name / "manifest.ttl").exists()
-            )
-
-    def test_generation_failure_does_not_replace_board_or_last_state(self):
-        self.model.unlink()
-        self.default_board.mkdir(parents=True)
-        (self.default_board / "manifest.ttl").write_text("old board", encoding="utf-8")
-        self.last_state.parent.mkdir(parents=True, exist_ok=True)
-        self.last_state.write_text("old state", encoding="utf-8")
-
-        with self.assertRaises(FileNotFoundError):
-            self.prepare("boot-one")
-
-        self.assertEqual(
-            (self.default_board / "manifest.ttl").read_text(encoding="utf-8"),
-            "old board",
-        )
-        self.assertEqual(self.last_state.read_text(encoding="utf-8"), "old state")
-        self.assertFalse((self.runtime_dir / "prepared-boot-id").exists())
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 11 - 20
tests/test_reset_engine.py

@@ -88,12 +88,9 @@ class ResetEngineTests(unittest.TestCase):
         ]
         return units
 
-    def test_resets_services_in_order_restores_pedalboard_and_timer(self):
+    def test_resets_services_in_order_preserves_user_pedalboard_and_timer(self):
         runner = FakeSystemd(self.all_engine_units())
-        with patch.object(reset_engine.deploy, "reset_mod_ui_reference") as reset_board:
-            reset_engine.reset_engine(
-                self.deployment, {"mod_ui": {}}, runner=runner
-            )
+        reset_engine.reset_engine(self.deployment, {"mod_ui": {}}, runner=runner)
 
         commands = runner.commands
         stop_timer = commands.index(
@@ -148,18 +145,14 @@ class ResetEngineTests(unittest.TestCase):
         self.assertLess(start_mod_ui, start_midi)
         self.assertLess(start_midi, reconcile)
         self.assertLess(reconcile, start_timer)
-        reset_board.assert_called_once_with(
-            self.deployment["mod_ui"], {"mod_ui": {}}, manage_services=False
-        )
         self.assertFalse(any("disable" in command for command in commands))
 
     def test_fails_without_resuming_reconciliation_if_graph_repair_fails(self):
         runner = FakeSystemd(self.all_engine_units(), observer_result=1)
-        with patch.object(reset_engine.deploy, "reset_mod_ui_reference"):
-            with self.assertRaisesRegex(RuntimeError, "command failed"):
-                reset_engine.reset_engine(
-                    self.deployment, {"mod_ui": {}}, runner=runner
-                )
+        with self.assertRaisesRegex(RuntimeError, "command failed"):
+            reset_engine.reset_engine(
+                self.deployment, {"mod_ui": {}}, runner=runner
+            )
 
         self.assertFalse(
             any(
@@ -178,11 +171,10 @@ class ResetEngineTests(unittest.TestCase):
             self.all_engine_units(),
             final_differences=[{"kind": "missing", "from": "a", "to": "b"}],
         )
-        with patch.object(reset_engine.deploy, "reset_mod_ui_reference"):
-            with self.assertRaisesRegex(RuntimeError, "final PipeWire graph still differs"):
-                reset_engine.reset_engine(
-                    self.deployment, {"mod_ui": {}}, runner=runner
-                )
+        with self.assertRaisesRegex(RuntimeError, "final PipeWire graph still differs"):
+            reset_engine.reset_engine(
+                self.deployment, {"mod_ui": {}}, runner=runner
+            )
 
         self.assertFalse(
             any(
@@ -213,8 +205,7 @@ class ResetEngineTests(unittest.TestCase):
                 ("rigforge-pipewire-reconcile.timer", False, False),
             ]
         )
-        with patch.object(reset_engine.deploy, "reset_mod_ui_reference"):
-            reset_engine.reset_engine(self.deployment, {}, runner=runner)
+        reset_engine.reset_engine(self.deployment, {}, runner=runner)
         self.assertIn(
             ["systemctl", "--user", "restart", "pipewire.service"], runner.commands
         )