Johan Le Baut 1 هفته پیش
والد
کامیت
57cbcfc080
32فایلهای تغییر یافته به همراه2179 افزوده شده و 216 حذف شده
  1. 15 9
      AGENTS.md
  2. 30 27
      README.md
  3. 5 3
      artifacts/mod-ui/arm64/current/app/html/js/pedalboard.js
  4. 25 14
      artifacts/mod-ui/arm64/current/app/mod/host.py
  5. 16 0
      artifacts/mod-ui/arm64/current/app/mod/session.py
  6. 13 0
      artifacts/mod-ui/arm64/current/app/mod/webserver.py
  7. 2 2
      artifacts/mod-ui/arm64/current/app/server.py
  8. 2 0
      artifacts/mod-ui/arm64/current/provenance.json
  9. 4 0
      build/arm64/build-mod-ui.sh
  10. 165 0
      build/arm64/patch_mod_ui_rigforge.py
  11. 45 17
      config/desired-state.yaml
  12. 3 1
      config/systemd/user/rigforge-midi-bridge.service.in
  13. 15 0
      config/systemd/user/rigforge-mod-host-ports.service.in
  14. 5 5
      config/systemd/user/rigforge-mod-host.service.in
  15. 23 0
      config/systemd/user/rigforge-mod-ui.service.in
  16. 362 18
      scripts/deploy.py
  17. 6 3
      scripts/deploy.sh
  18. 356 0
      scripts/generate_mod_ui_pedalboard.py
  19. 39 35
      scripts/midi_action_bridge.py
  20. 191 0
      scripts/mod_ui_websocket.py
  21. 10 10
      scripts/observe_pipewire.py
  22. 179 0
      scripts/run_mod_host_ports.py
  23. 99 0
      scripts/run_mod_ui_service.py
  24. 121 20
      scripts/validate_desired_state.py
  25. 11 3
      scripts/wait_mod_host_ports.py
  26. 127 7
      tests/test_deploy.py
  27. 26 10
      tests/test_desired_state.py
  28. 17 14
      tests/test_midi_action_bridge.py
  29. 65 0
      tests/test_mod_host_ports.py
  30. 68 0
      tests/test_mod_ui_pedalboard.py
  31. 117 0
      tests/test_mod_ui_websocket.py
  32. 17 18
      tests/test_pipewire_observer.py

+ 15 - 9
AGENTS.md

@@ -8,18 +8,24 @@ The current target is Debian GNU/Linux 13 on AArch64 with a Behringer UMC404HD 1
 
 ## Layout and architecture
 
-- `config/desired-state.yaml` is the central YAML description of the intended components, four mono sources, looper channel assignments, mix, the guitar NAM/cabinet chain, planned/forbidden connections, and the exact PipeWire links currently tracked for observation.
+- `config/desired-state.yaml` is the central YAML description of the intended components, four mono sources, looper channel assignments, mix, the guitar NAM/cabinet chain, mod-host PipeWire boundary ports, planned/forbidden connections, and exact external PipeWire links tracked for observation.
 - `config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf` is a PipeWire filter-chain fragment with four mono mixer inputs, one mono output, and initial gain `0.2` per input. 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, single four-channel looper, source-to-channel assignments, 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/configure_mod_host.py` loads the YAML-declared NAM and LSP IR instances and guitar links for the user service `config/systemd/user/rigforge-mod-host.service.in`.
-- `scripts/wait_mod_host_ports.py` waits for declared hardware and mixer endpoints before the mod-host process starts, avoiding startup races after PipeWire restarts.
+- `scripts/generate_mod_ui_pedalboard.py` builds the YAML-declared NAM→IR reference bundle; mod-ui owns plugin instances and internal cables after loading it.
+- `scripts/run_mod_host_ports.py` runs the two mono PipeWire loopbacks which form stable mod-ui-visible input/output boundaries.
+- `scripts/run_mod_ui_service.py` launches mod-ui under `pw-jack` and holds a WebSocket session so the backend loads without a browser.
+- `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.
-- `scripts/deploy.sh` dispatches scoped user-level install/uninstall/reload actions for YAML-declared PipeWire, LV2 bundles, the mod-host service, and the separate graph-reconcile timer through `scripts/deploy.py`. `mod-host` and `reconcile` are explicit targets, not part of `all`.
-- `tests/` contains Python `unittest` tests for state validation, observation/reconciliation, mixer configuration, mod-host startup configuration, 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 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/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. The observer's scope is deliberately narrower: it compares links only when both endpoints are listed in `routing.managed_ports`. Keep unrelated WirePlumber-managed hardware 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 desired topology and the generated pedalboard. mod-ui owns the NAM→IR cable; Rigforge owns the 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 plugin 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
 
@@ -47,7 +53,7 @@ The observer invokes `pw-link -l` itself. Its default mode never creates or remo
 - Preserve exactly the four named sources (`guitar`, `bass`, `voice`, `synth`) and physical inputs 1–4, each once, unless the validator and its tests are intentionally updated along with the model.
 - Preserve one looper component/instance and one four-channel loop; assign each declared source to one unique channel 1–4.
 - The mix must declare an output and include looper returns. Looper returns must not feed any looper input; the explicit forbidden connection is policy documentation, not an active route.
-- A managed link's endpoints must both be declared in `routing.managed_ports`, and names must match the observer's approved endpoint pattern. Use concrete observed PipeWire ports rather than logical aliases. The current effect allowlist is limited to the declared `effect_0` NAM and `effect_1` IR ports.
+- A managed link's endpoints must both be declared in `routing.managed_ports`, and names must match the observer's approved endpoint pattern. Use concrete PipeWire boundary ports rather than logical aliases or mod-ui plugin ports. Never add NAM→IR to Rigforge's managed links.
 - Link status values used by the observer are `planned` and `observed`; both are compared against the current graph. Only declare real target observations as `observed`.
 - Deployment declarations belong in `config/desired-state.yaml`. The deploy helper must remain scoped to declared user paths, preserve and restore prior files, refuse destructive actions after local modifications, and never restart the main PipeWire or WirePlumber service as a generic update.
 - Keep observation as the default. Explicit `--reconcile-once` and the separately installed user timer may create declared missing links and remove only exact links listed in `routing.managed_unlinks`; they must defer removals until all desired managed links are present, must not alter other connections, and must not restart PipeWire/WirePlumber. Retain tests for simulated repair, safe removal, deferral, and post-check behavior.
@@ -60,8 +66,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 mod-host user service, dependent-service restart propagation, and separately deployed 15-second reconciliation timer are implemented in the repository but the latest changes and recovery behavior still require target verification. Keep unverified changes away from live audio use and follow the README's rollback procedure for target experiments.
-- `install mod-host` activates guitar audio routing and is intentionally excluded from `install all`. `install reconcile` separately enables graph-wide periodic link repair and is also opt-in. The current mod-host build listens on `0.0.0.0:5555` 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, 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.
 
 # Environnement local — rigforge
 

+ 30 - 27
README.md

@@ -29,19 +29,20 @@ This records the preparation already performed on `rigforge` and is a starting p
 
 ## Repository layout
 
-- `config/desired-state.yaml`: versioned desired audio topology and provisional target mapping.
+- `config/desired-state.yaml`: versioned desired audio topology, mod-host boundary ports, and provisional target mapping.
 - `config/midi-bindings.yaml`: MIDI event-to-action mapping for the general MIDI bridge; SooperLooper bindings remain in their native `.slb` file.
 - `config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf`: eight-input mono mixer configuration, with four direct-source slots and four SooperLooper return slots.
 - `config/sooperlooper/fcb1010.slb`: supplied FCB1010 binding file, pending on-target verification.
-- `build/arm64/`: shared ARM64 build image and task scripts for SooperLooper, mod-host, and mod-ui.
+- `build/arm64/`: shared ARM64 build image and task scripts for SooperLooper, mod-host, and mod-ui; `patch_mod_ui_rigforge.py` reapplies Rigforge's port and WebSocket integration to the pinned source.
 - `scripts/validate_desired_state.py`: validates topology and routing invariants without changing the target.
 - `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 mod-host NAM model actions.
-- `scripts/deploy.sh` and `scripts/deploy.py`: scoped user-level installation, removal, and reload of declared PipeWire and LV2 plugin bundles.
-- `tests/`: unit tests for desired-state validation, PipeWire observation/reconciliation, and deployment operations.
+- `scripts/midi_action_bridge.py`: translates declared ALSA MIDI note events into NAM model changes through mod-ui's WebSocket.
+- `scripts/generate_mod_ui_pedalboard.py`: generates the reference NAM→IR 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 and LV2 bundles.
+- `tests/`: unit tests for desired-state validation, PipeWire observation/reconciliation, pedalboard generation, MIDI WebSocket control, 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.
 
-The YAML describes desired state; a control surface is not a second source of truth. The initial audio profile declares 48 kHz and a quantum of 128 frames, which was reported to sound good during a temporary target test. At 48 kHz, 128 frames is about 2.7 ms per period, not the end-to-end latency. This runtime value has not yet been made persistent or measured under sustained load; apply it temporarily on the target with `pw-metadata -n settings 0 clock.force-quantum 128` and return to automatic selection with `pw-metadata -n settings 0 clock.force-quantum 0`. Concrete PipeWire ports, buffer settings, package names, services, and artifact installation path will only be recorded as verified after target tests.
+The YAML describes desired state; a control surface is not a second source of truth. The initial audio profile declares 48 kHz and a quantum of 128 frames, which was reported to sound good during a temporary target test. At 48 kHz, 128 frames is about 2.7 ms per period, not the end-to-end latency. This runtime value has not yet been made persistent or measured under sustained load; apply it temporarily on the target with `pw-metadata -n settings 0 clock.force-quantum 128` and return to automatic selection with `pw-metadata -n settings 0 clock.force-quantum 0`. The new mod-host PipeWire boundary nodes and services are local candidates and remain unverified on the target.
 
 Validate the desired-state file on the development PC with:
 
@@ -58,7 +59,7 @@ For an initial read-only graph observation on a system with `pw-link`, run:
 python3 scripts/observe_pipewire.py
 ```
 
-The observer reads `pw-link -l` and compares only connections whose endpoints are explicitly listed under `routing.managed_ports`; expected edges go in `routing.managed_links`. Exact obsolete edges that may be removed by explicit reconciliation must be separately listed under `routing.managed_unlinks`. The current YAML declares the guitar NAM/cabinet edges, the voice mixer edge, the mixer output edge, the UMC MIDI bridge to SooperLooper's JACK MIDI input, and the obsolete direct guitar bypass for removal. WirePlumber's unrelated hardware links remain outside project management. The default command only reports differences and never changes the graph; declared removals appear as `would-unlink`, while all other unexpected links remain `would-review`.
+The observer reads `pw-link -l` and compares only connections whose endpoints are explicitly listed under `routing.managed_ports`; expected edges go in `routing.managed_links`. Exact obsolete edges that may be removed by explicit reconciliation must be separately listed under `routing.managed_unlinks`. Rigforge manages the UMC guitar capture into the `mod-host-input` boundary, the `mod-host-output` boundary to the mixer and guitar looper input, other declared source/looper links, the mixer output, and the UMC MIDI bridge to SooperLooper. mod-ui owns the audio cables between the boundary ports and the NAM/IR plugins; those links are deliberately outside observer scope. WirePlumber's unrelated hardware links remain outside project management. The default command only reports differences and never changes the graph; declared removals appear as `would-unlink`, while all other unexpected links remain `would-review`.
 
 An explicit one-shot mode can create missing declared links after checking that the source and destination ports exist, then remove only present links explicitly declared in `routing.managed_unlinks`:
 
@@ -109,18 +110,16 @@ This restarts only `filter-chain.service`, not the main PipeWire daemon. The fra
 After a manual `git pull --ff-only`, run the deploy helper from any directory:
 
 ```sh
-~/rigforge/scripts/deploy.sh install pipewire
-~/rigforge/scripts/deploy.sh install namlv2
-~/rigforge/scripts/deploy.sh install lsp
-~/rigforge/scripts/deploy.sh install dragonfly-reverb
+~/rigforge/scripts/deploy.sh install all
+~/rigforge/scripts/deploy.sh install mod-host-ports
 ~/rigforge/scripts/deploy.sh install mod-host
+~/rigforge/scripts/deploy.sh install mod-ui
 ~/rigforge/scripts/deploy.sh install sooperlooper
 ~/rigforge/scripts/deploy.sh install reconcile
 ~/rigforge/scripts/deploy.sh install midi-bridge
-~/rigforge/scripts/deploy.sh install all
 ```
 
-The helper accepts `install|uninstall|reload` and `all|namlv2|lsp|dragonfly-reverb|pipewire|mod-host|reconcile|midi-bridge|sooperlooper`. `all` deliberately excludes `mod-host`, `reconcile`, `midi-bridge`, and `sooperlooper`, which are opt-in services. 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 target backup is stored next to that target. It does not use `sudo` or change files outside the declared paths, adjacent backup paths, and registry directory.
+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`. `all` deliberately excludes the audio-host/UI/MIDI services and reconciliation, which are opt-in. Install in dependency order: ports, mod-host, then mod-ui; the MIDI bridge follows mod-ui. 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, mod-ui's dedicated user-data directory, and the registry directory.
 
 For PipeWire, install updates only the Rigforge filter fragment, applies the declared quantum as a runtime setting, and restarts `filter-chain.service` only when the fragment changes. It never restarts `pipewire.service` or WirePlumber. `reload pipewire` reapplies the quantum and restarts the filter-chain user service. This restart removes the filter-chain nodes and their 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 the unchanged managed fragment, restores a file that was present before the first install, returns quantum selection to automatic, and reloads the filter service. Local edits to managed files stop removal or replacement rather than being discarded. Runtime quantum is not persistent across a PipeWire daemon restart.
 
@@ -144,19 +143,21 @@ Install requires the built ARM64 artifact, the tracked `.slb` file, and target r
 
 Remove the service with `./scripts/deploy.sh uninstall sooperlooper`.
 
-### mod-host guitar chain
+### 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`. `mod-host-ports` starts two mono `/usr/bin/pw-loopback` boundaries: a PipeWire sink `rigforge.mod-host-input` with a paired source visible to mod-ui, and a sink visible to mod-ui paired with the source `rigforge.mod-host-output`. Rigforge's observer manages UMC capture → input sink and output source → guitar mixer/looper. mod-ui is configured to display one “Rigforge Mod-Host Input” and one “Rigforge Mod-Host Output” and owns the internal cables from input to NAM, NAM to IR, and IR to output.
 
-`install mod-host` is an explicit target and is deliberately not included in `install all`: it activates the guitar processing chain. It requires the ARM64 artifact under `artifacts/mod-host/arm64/current/`, the NAM and LSP bundles already installed, the tracked `amp_emul/` assets, and the runtime packages in the target preparation list. It installs and enables only the `systemd --user` mod-host service; it does not use `sudo` or directly restart PipeWire/WirePlumber. The unit refers to the repository checkout from which `deploy.sh` was run, so keep that checkout at that path or uninstall/reinstall after moving it.
+`scripts/generate_mod_ui_pedalboard.py` builds the reference bundle from the YAML: one NAM, one LSP mono IR, the Crunch TB and Vox AC30 assets, the declared NAM output level, and those three mod-ui-owned arcs. During `install mod-ui`, deployment generates a target-specific bundle under Rigforge's dedicated user data directory so the absolute model/IR paths match that checkout; the bundle is fingerprinted and protected from local edits. mod-ui then resumes its last saved board across restarts. `./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.
 
-Before starting mod-host, `scripts/wait_mod_host_ports.py` waits up to 45 seconds for the guitar capture, mixer input, and hardware playback ports. This avoids launching `pw-jack` while PipeWire's hardware ports are still appearing after a service restart. Then `scripts/configure_mod_host.py` waits for the control socket, loads the declared NAM and LSP mono-IR instances, sets their model/IR paths and the conservative NAM output level, then creates the PipeWire links. The desired chain is capture AUX0 → `Vox_AC15CH_Crunch_TB.nam` → `VOX_AC30_1964_celestion.wav` → guitar mixer input AUX0. The direct capture-to-mixer bypass is removed. Review the model and IR redistribution terms before using these assets in a public image or package.
+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 the board loads even before a browser connects, and is the sole control/feedback client for mod-host. Install the ARM64 artifacts, NAM/LSP bundles, and the declared audio assets before activation. The target ports, virtual loopback naming, pedalboard loading, and sustained audio still require an on-target test; the YAML marks newly introduced boundary links as `planned`.
 
-`reload mod-host` restarts the service and rebuilds the plugin graph, briefly interrupting the processed guitar path. `PartOf=` couples mod-host restarts to PipeWire, WirePlumber, and `filter-chain.service` restarts; its startup configurator then rebuilds the NAM/IR chain. The mod-host control socket uses TCP port 5555 and this build listens on `0.0.0.0` without authentication. This is retained for the current test by owner request and must be restricted before treating the setup as hardened.
+Both mod-host TCP ports currently listen on all interfaces without authentication, retained by owner request. The mod-ui HTTP/WebSocket server is also reachable on the LAN for the browser UI. Restrict these endpoints before treating the setup as hardened. Keep the repository checkout at its installed path, since the user units refer to it.
 
 ### FCB NAM model selection
 
 `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/socket settings are declared in `config/desired-state.yaml`. Actions identify their target by chain and processor IDs, so the bridge itself does not hard-code the guitar instance; adding a bass chain will also require extending and validating the desired audio topology. 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. 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 bridge uses Debian’s `python3-rtmidi` package, included in the recorded target-preparation command above. Check the configuration and inspect MIDI input names with:
 
@@ -173,7 +174,7 @@ Run the bridge in the foreground for manual use:
 python3 scripts/midi_action_bridge.py
 ```
 
-The bridge connects to mod-host over loopback and issues only `patch_set` for the configured NAM processor. It does not alter PipeWire links. To install and enable its user service explicitly:
+The bridge keeps the existing ALSA MIDI input and Note On bindings, but connects to mod-ui at `ws://127.0.0.1:8888/websocket`; mod-ui issues the `patch_set` to its single mod-host connection and reports an acknowledgement. The bridge does not alter PipeWire links. To install and enable its user service explicitly:
 
 ```sh
 ./scripts/deploy.sh install midi-bridge
@@ -181,7 +182,7 @@ systemctl --user status rigforge-midi-bridge.service
 journalctl --user -u rigforge-midi-bridge.service -f
 ```
 
-The service retries MIDI-port discovery if the UMC is not yet available and restarts after an unexpected process failure. It is deliberately excluded from `install all`; it does not install or start mod-host. Model selection requires the mod-host guitar chain to be running. The user systemd manager must be active for the service to run; unattended boot startup without a login also requires user lingering. Remove it with `./scripts/deploy.sh uninstall midi-bridge`, or restart it after local configuration changes with `./scripts/deploy.sh reload midi-bridge`. The current mod-host startup model remains the declared `Crunch_TB`; Crystal Clean is the runtime fallback for a selected model whose file is absent.
+The service retries MIDI-port discovery if the UMC is not yet available and restarts after an unexpected process failure. It is deliberately excluded from `install all`; it requires mod-ui, which in turn requires mod-host and the boundary-port service. Model selection changes the active NAM model for the running board; missing selections fall back to Crystal Clean. The user systemd manager must be active for the services to run; unattended boot startup without a login also requires user lingering. Remove services in reverse dependency order: `midi-bridge`, `mod-ui`, `mod-host`, then `mod-host-ports`.
 
 ### Rigforge graph reconciliation
 
@@ -194,13 +195,15 @@ systemctl --user status rigforge-pipewire-reconcile.timer
 journalctl --user -u rigforge-pipewire-reconcile.service -b
 ```
 
-The owner reports enabling lingering with `sudo loginctl enable-linger "$USER"` so the user manager can run without an interactive login. Boot startup, dependency restart propagation, and USB unplug/replug recovery from the reconciliation timer require on-target verification. Mod-host installation refuses to start if port 5555 is already occupied by an unmanaged/manual mod-host process; stop that process explicitly before retrying.
+The owner reports enabling lingering with `sudo loginctl enable-linger "$USER"` so the user manager can run without an interactive login. Boot startup, dependency restart propagation, and USB unplug/replug recovery from the reconciliation timer require on-target verification. Mod-host installation refuses to start if either TCP port 5555 or 5556 is already occupied by an unmanaged/manual process; stop that process explicitly before retrying.
 
 Inspect the service after installation with:
 
 ```sh
 systemctl --user status rigforge-mod-host.service
 journalctl --user -u rigforge-mod-host.service -b
+systemctl --user status rigforge-mod-host-ports.service rigforge-mod-ui.service
+journalctl --user -u rigforge-mod-ui.service -b
 ```
 
 On the target, `install pipewire` applied quantum 128 and reported that the installed fragment was already current; the following observer reported no differences. A later `reload pipewire` applied the quantum and restarted the filter-chain service, after which observation found all three managed links missing. One-shot reconciliation requested each link, and the subsequent observer reported `differences: []`. This confirms the graph links were present after reconciliation, not that audio was audible. `install all` and `uninstall all` attempt all four targets and report an overall failure if any action fails. `reload all` restarts the filter-chain service and prints no-op messages for the LV2 plugins. Check the target afterwards with `python3 scripts/validate_desired_state.py`, `python3 -m unittest discover -s tests -v`, and `python3 scripts/observe_pipewire.py`.
@@ -218,7 +221,7 @@ docker run --rm --platform linux/arm64 --user "$(id -u):$(id -g)" -v "$PWD:/work
 docker run --rm --platform linux/arm64 --user "$(id -u):$(id -g)" -v "$PWD:/workspace" rigforge-arm64-build:debian13 mod-ui
 ```
 
-Use task `all` to build all three programs in sequence. The shared image contains the union of their compiler/runtime build dependencies; each task retrieves the source tag from YAML, records the resolved commit, builds only its target, checks runtime dependencies, and writes its artifacts and provenance under `artifacts/<project>/arm64/current/`. The SooperLooper task builds both `sooperlooper` and `slconsole`; the mod-ui task packages its pinned web app, ARM64 `libmod_utils.so`, and vendored Python requirements. It also applies the upstream-documented Tornado compatibility adjustment and includes the SSL hostname backport needed by this Python 3.13 build. The build checks that it is running in an ARM64 Debian container. Each successful task replaces only its own prior output, and staged output is removed on failure. Run the container with the host UID/GID as above so generated files remain accessible to the host user. To update a source version, change its `deployment.sooperlooper.tag`, `deployment.mod_host.tag`, or `deployment.mod_ui.tag`, validate the YAML, then rerun the corresponding task. Buildx `--load` for one ARM64 platform and `docker run --platform linux/arm64` need binfmt/QEMU on AMD64 hosts.
+Use task `all` to build all three programs in sequence. The shared image contains the union of their compiler/runtime build dependencies; each task retrieves the source tag from YAML, records the resolved commit, builds only its target, checks runtime dependencies, and writes its artifacts and provenance under `artifacts/<project>/arm64/current/`. The SooperLooper task builds both `sooperlooper` and `slconsole`; the mod-ui task packages its pinned web app, ARM64 `libmod_utils.so`, and vendored Python requirements. It applies the upstream-documented Tornado compatibility adjustment, the SSL hostname backport needed by this Python 3.13 build, and the tracked Rigforge port-mapping/WebSocket patch from `build/arm64/patch_mod_ui_rigforge.py` (its hash is recorded in provenance). The build checks that it is running in an ARM64 Debian container. Each successful task replaces only its own prior output, and staged output is removed on failure. Run the container with the host UID/GID as above so generated files remain accessible to the host user. To update a source version, change its `deployment.sooperlooper.tag`, `deployment.mod_host.tag`, or `deployment.mod_ui.tag`, validate the YAML, then rerun the corresponding task. Buildx `--load` for one ARM64 platform and `docker run --platform linux/arm64` need binfmt/QEMU on AMD64 hosts.
 
 SooperLooper's tagged source does not define ARM64 atomics in `libs/pbd/pbd/atomic.h` or `src/atomic.h`; the build task injects GCC `__atomic` operations for AArch64 in its temporary clone, leaving the upstream source repository untouched. This local portability patch is recorded in provenance. The image only compiles; it does not deploy or run either program on the Pi. Successful compilation does not establish runtime compatibility: inspect dependencies and test on the target. Review upstream licenses and artifact size before committing generated binaries and provenance.
 
@@ -228,7 +231,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 enable or install a service, and it does not configure the existing mod-host service. Controlling the real effect graph requires mod-host's feedback port (`-f 5556`); the current Rigforge mod-host unit does not enable it. 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 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.
 
 ## `rigforge` target
 
@@ -244,14 +247,14 @@ On 2026-11-21, MIDI Note 1 was observed at the UMC ALSA port but did not reach S
 
 The remaining target checks are:
 
-1. The read-only observer and one-shot repair have been tested on `rigforge`. Repairing one missing link restored the audible microphone path; after a later filter-chain service restart, reconciliation requested all three missing links and the observer reported no differences. The observer now also tracks the three guitar NAM/cabinet links. Do not run one-shot reconciliation against an older checkout: it could restore the dry guitar bypass.
+1. The read-only observer and one-shot repair have been tested on `rigforge`. Repairing one missing link restored the audible microphone path; after a later filter-chain service restart, reconciliation requested all three missing links and the observer reported no differences. The current local model tracks the external `mod-host-input`/`mod-host-output` boundary links; it deliberately does not track the NAM→IR cable. Do not run one-shot reconciliation against an older checkout: it could restore the dry guitar bypass.
 2. Test direct mixer inputs 2 and 4 with sources when available; their direct-to-mix routes remain unverified. Looper capture inputs 2–4 are now linked but have not been tested with instruments.
 3. Measure sustained stability and headroom at 48 kHz / 128 frames with all active sources; the current `ERR = 0` observation was brief.
-4. Re-test mod-host startup after installing the new port-readiness guard, then verify reboot with lingering enabled, startup resource limits, and recovery when an LV2 plugin fails to load.
-5. The owner has manually verified FCB notes 6–9 switching the guitar NAM models through the bridge, with near-instant reported transitions. SooperLooper's supplied FCB1010 bindings were also tested successfully over the declared PipeWire MIDI edge. Verify that the updated observer restores this edge after reboot, service restart, and UMC unplug/replug; verify unattended startup, OSC initialization, audio routing, and the persistence/effect of `discrete_prefader 0` separately.
+4. Test the new PipeWire loopback boundary ports and verify that mod-ui displays and connects them; then verify mod-host feedback pairing, the generated board's initial NAM/IR state, UI edits across restart, explicit reset, and recovery after unplug/replug.
+5. The owner has manually verified FCB notes 6–9 switching the guitar NAM models through the old direct bridge path, with near-instant reported transitions. The updated bridge now uses mod-ui's WebSocket and still needs an on-target test. SooperLooper's supplied FCB1010 bindings were also tested successfully over the declared PipeWire MIDI edge. Verify that the updated observer restores this edge after reboot, service restart, and UMC unplug/replug; verify unattended startup, OSC initialization, audio routing, and the persistence/effect of `discrete_prefader 0` separately.
 
 Do not treat planned packages, commands, ports, or service settings as target-validated until these checks have been performed.
 
 ## Deployment and rollback
 
-Deployment is manual: inspect and test a change, then use `git pull` on `rigforge` only when the change is ready. No CI/CD or auto-pull is configured. The mod-host service and separate reconciliation timer have been installed on the target; the new mod-host port-readiness guard and its updated service template remain local and unverified there. Keep the last known working revision available; do not apply unverified audio or service changes during live use.
+Deployment is manual: inspect and test a change, then use `git pull` on `rigforge` only when the change is ready. No CI/CD or auto-pull is configured. The previously installed mod-host service and reconciliation timer reflect the older direct-configuration architecture. The new loopback boundaries, mod-ui service, feedback pairing, and WebSocket MIDI path are local and have not been deployed or verified on the target. Keep the last known working revision available; do not apply unverified audio or service changes during live use.

+ 5 - 3
artifacts/mod-ui/arm64/current/app/html/js/pedalboard.js

@@ -767,12 +767,14 @@ JqueryClass('pedalboard', {
                 var symbol
                 for (var i=1, count=data.hardware.audio_ins; i<=count; i++) {
                     symbol = (i < 3) ? ('/graph/capture_' + i) : ('/graph/audio_from_slave_' + (i-2))
-                    var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="' + i + '" title="Hardware Capture ' + i + '">')
+                    var captureTitle = (i === 1) ? 'Rigforge Mod-Host Input' : ('Hardware Capture ' + i)
+                    var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="' + i + '" title="' + captureTitle + '">')
                     self.pedalboard('addHardwareOutput', hw, symbol, 'audio')
                 }
                 for (var i=1, count=data.hardware.audio_outs; i<=count; i++) {
                     symbol = (i < 3) ? ('/graph/playback_' + i) : ('/graph/audio_to_slave_' + (i-2))
-                    var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="' + i + '" title="Hardware Playback ' + i + '">')
+                    var playbackTitle = (i === 1) ? 'Rigforge Mod-Host Output' : ('Hardware Playback ' + i)
+                    var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="' + i + '" title="' + playbackTitle + '">')
                     self.pedalboard('addHardwareInput', hw, '/graph/playback_' + i, 'audio')
                 }
                 for (var i=1, count=data.hardware.cv_ins; i<=count; i++) {
@@ -5120,4 +5122,4 @@ function T3KIntegration(pedalboard, pubKey) {
 
         t3kinfo?.popup?.progress?.(msg, progress)
     }
-}
+}

+ 25 - 14
artifacts/mod-ui/arm64/current/app/mod/host.py

@@ -423,6 +423,8 @@ class Host(object):
 
         # clients at the end of the chain, all managed by mod-host
         self.jack_hw_capture_prefix = "mod-host:out" if self.descriptor.get('has_noisegate', False) else "system:capture_"
+        self.rigforge_capture_port = os.environ.get("MOD_RIGFORGE_CAPTURE_PORT")
+        self.rigforge_playback_port = os.environ.get("MOD_RIGFORGE_PLAYBACK_PORT")
 
         # used for external connections
         self.jack_external_prefix = "mod-external"
@@ -1184,21 +1186,26 @@ class Host(object):
             self.hasSerialMidiOut = False
             return False
 
-        for port in get_jack_hardware_ports(True, False):
-            client_name, port_name = port.split(":",1)
-            if client_name == "mod-spi2jack":
-                cv_port_name = CV_PREFIX + port_name
-                self.cvportsIn.append(cv_port_name)
-                self.addressings.add_hw_cv_port('/cv/graph/' + cv_port_name)
-            else:
-                self.audioportsIn.append(port_name)
+        if self.rigforge_capture_port and self.rigforge_playback_port:
+            # These graph symbols map to Rigforge's stable virtual PipeWire boundary ports.
+            self.audioportsIn = ["capture_1"]
+            self.audioportsOut = ["playback_1"]
+        else:
+            for port in get_jack_hardware_ports(True, False):
+                client_name, port_name = port.split(":",1)
+                if client_name == "mod-spi2jack":
+                    cv_port_name = CV_PREFIX + port_name
+                    self.cvportsIn.append(cv_port_name)
+                    self.addressings.add_hw_cv_port('/cv/graph/' + cv_port_name)
+                else:
+                    self.audioportsIn.append(port_name)
 
-        for port in get_jack_hardware_ports(True, True):
-            client_name, port_name = port.split(":",1)
-            if client_name == "mod-jack2spi":
-                self.cvportsOut.append(CV_PREFIX + port_name)
-            else:
-                self.audioportsOut.append(port_name)
+            for port in get_jack_hardware_ports(True, True):
+                client_name, port_name = port.split(":",1)
+                if client_name == "mod-jack2spi":
+                    self.cvportsOut.append(CV_PREFIX + port_name)
+                else:
+                    self.audioportsOut.append(port_name)
 
         for port in get_jack_hardware_ports(False, True):
             if not port.startswith("system:midi_"):
@@ -3615,6 +3622,10 @@ class Host(object):
 
         if len(data) == 3:
             # Handle special cases
+            if data[2] == "capture_1" and self.rigforge_capture_port:
+                return self.rigforge_capture_port
+            if data[2] == "playback_1" and self.rigforge_playback_port:
+                return self.rigforge_playback_port
             if data[2] == "serial_midi_in":
                 return "ttymidi:MIDI_in"
             if data[2] == "serial_midi_out":

+ 16 - 0
artifacts/mod-ui/arm64/current/app/mod/session.py

@@ -343,6 +343,22 @@ class Session(object):
                                                                   1 if writable else 0,
                                                                   uri, valuetype, valuedata), ws)
 
+    def ws_rigforge_patch_set(self, request_id, instance, uri, valuetype, valuedata, ws):
+        if valuetype != "p":
+            ws.write_message("rigforge_patch_set_ack %s 0" % request_id)
+            return
+
+        def completed(ok):
+            status = 1 if ok else 0
+            if ok:
+                self.msg_callback_broadcast(
+                    "patch_set %s 1 %s %c %s" % (instance, uri, valuetype, valuedata),
+                    ws,
+                )
+            ws.write_message("rigforge_patch_set_ack %s %d" % (request_id, status))
+
+        self.host.patch_set(instance, uri, valuedata, completed)
+
     # Set a plugin block position within the canvas
     def ws_plugin_position(self, instance, x, y, ws):
         self.screenshot_needed = True

+ 13 - 0
artifacts/mod-ui/arm64/current/app/mod/webserver.py

@@ -1357,6 +1357,19 @@ class ServerWebSocket(websocket.WebSocketHandler):
             value = data[3]
             SESSION.ws_patch_set(inst, uri, vtype, value, self)
 
+        elif cmd == "rigforge_patch_set":
+            data = data[1].split(" ", 4)
+            if len(data) != 5:
+                self.write_message("rigforge_patch_set_ack invalid 0")
+                return
+            request_id, inst, uri, vtype, value = data
+            if not request_id.isalnum():
+                self.write_message("rigforge_patch_set_ack invalid 0")
+                return
+            SESSION.ws_rigforge_patch_set(
+                request_id, inst, uri, vtype, value, self
+            )
+
         elif cmd == "plugin_pos":
             data = data[1].split(" ",3)
             inst = data[0]

+ 2 - 2
artifacts/mod-ui/arm64/current/app/server.py

@@ -47,9 +47,9 @@ os.environ['MOD_DEV_ENVIRONMENT'] = os.environ.get("MOD_DEV_ENVIRONMENT", '1')
 os.environ['MOD_DATA_DIR'] = DATA_DIR
 os.environ['MOD_LOG'] = os.environ.get("MOD_LOG", '1')
 os.environ['MOD_KEY_PATH'] = os.path.join(DATA_DIR, 'keys')
-os.environ['MOD_DEVICE_WEBSERVER_PORT'] = '8888'
+os.environ.setdefault('MOD_DEVICE_WEBSERVER_PORT', '8888')
 os.environ['MOD_HTML_DIR'] = os.path.join(ROOT, 'html')
-os.environ['MOD_DEFAULT_PEDALBOARD'] = os.path.join(ROOT, 'default.pedalboard')
+os.environ.setdefault('MOD_DEFAULT_PEDALBOARD', os.path.join(ROOT, 'default.pedalboard'))
 os.environ['MOD_DEVICE_KEY'] = os.path.join(DATA_DIR, 'rsa')
 os.environ['MOD_DEVICE_TAG'] = os.path.join(DATA_DIR, 'tag')
 os.environ['MOD_DEVICE_UID'] = os.path.join(DATA_DIR, 'uid')

+ 2 - 0
artifacts/mod-ui/arm64/current/provenance.json

@@ -8,5 +8,7 @@
   "native_library_sha256": "977ef35aaf2f648ba45c9b82f851a68e49a36624ad9e2cbb66287a0e80010a40",
   "additional_python_requirement": "backports.ssl_match_hostname==3.7.0.1",
   "python_compatibility_patch": "Tornado 4.3 collections.MutableMapping to collections.abc.MutableMapping",
+  "rigforge_integration_patch": "build/arm64/patch_mod_ui_rigforge.py",
+  "rigforge_integration_patch_sha256": "a0a6135bfa05e4e1ae5843fd46589b961dd6588f02c02dc1fcdd819d2a27b8f6",
   "license": "AGPL-3.0-or-later"
 }

+ 4 - 0
build/arm64/build-mod-ui.sh

@@ -71,6 +71,7 @@ make -C "$work_directory/source/utils" -j"$(nproc)"
 mkdir -p "$staging_directory/app" "$staging_directory/vendor"
 git -C "$work_directory/source" archive --format=tar HEAD \
     | tar -xf - -C "$staging_directory/app"
+python3 "$repository_root/build/arm64/patch_mod_ui_rigforge.py" "$staging_directory/app"
 install -m 0644 \
     "$work_directory/source/utils/libmod_utils.so" \
     "$staging_directory/app/modtools/libmod_utils.so"
@@ -136,6 +137,7 @@ python3 -m pip list --path "$staging_directory/vendor" --format=freeze \
     > "$staging_directory/python-runtime-dependencies.txt"
 
 native_library_sha256=$(sha256sum "$staging_directory/app/modtools/libmod_utils.so" | cut -d ' ' -f 1)
+rigforge_patch_sha256=$(sha256sum "$repository_root/build/arm64/patch_mod_ui_rigforge.py" | cut -d ' ' -f 1)
 cat > "$staging_directory/provenance.json" <<EOF
 {
   "source_url": "$source_url",
@@ -147,6 +149,8 @@ cat > "$staging_directory/provenance.json" <<EOF
   "native_library_sha256": "$native_library_sha256",
   "additional_python_requirement": "backports.ssl_match_hostname==3.7.0.1",
   "python_compatibility_patch": "Tornado 4.3 collections.MutableMapping to collections.abc.MutableMapping",
+  "rigforge_integration_patch": "build/arm64/patch_mod_ui_rigforge.py",
+  "rigforge_integration_patch_sha256": "$rigforge_patch_sha256",
   "license": "AGPL-3.0-or-later"
 }
 EOF

+ 165 - 0
build/arm64/patch_mod_ui_rigforge.py

@@ -0,0 +1,165 @@
+#!/usr/bin/env python3
+"""Apply the small Rigforge integration patch to the pinned mod-ui source tree."""
+
+import sys
+from pathlib import Path
+
+
+def replace_once(path, original, replacement):
+    text = path.read_text(encoding="utf-8")
+    if replacement in text:
+        return
+    if text.count(original) != 1:
+        raise RuntimeError(f"expected one upstream match in {path}")
+    path.write_text(text.replace(original, replacement), encoding="utf-8")
+
+
+def apply(source_root):
+    app = Path(source_root)
+
+    replace_once(
+        app / "mod" / "host.py",
+        '''        self.jack_hw_capture_prefix = "mod-host:out" if self.descriptor.get('has_noisegate', False) else "system:capture_"
+''',
+        '''        self.jack_hw_capture_prefix = "mod-host:out" if self.descriptor.get('has_noisegate', False) else "system:capture_"
+        self.rigforge_capture_port = os.environ.get("MOD_RIGFORGE_CAPTURE_PORT")
+        self.rigforge_playback_port = os.environ.get("MOD_RIGFORGE_PLAYBACK_PORT")
+''',
+    )
+    replace_once(
+        app / "mod" / "host.py",
+        '''        for port in get_jack_hardware_ports(True, False):
+            client_name, port_name = port.split(":",1)
+            if client_name == "mod-spi2jack":
+                cv_port_name = CV_PREFIX + port_name
+                self.cvportsIn.append(cv_port_name)
+                self.addressings.add_hw_cv_port('/cv/graph/' + cv_port_name)
+            else:
+                self.audioportsIn.append(port_name)
+
+        for port in get_jack_hardware_ports(True, True):
+            client_name, port_name = port.split(":",1)
+            if client_name == "mod-jack2spi":
+                self.cvportsOut.append(CV_PREFIX + port_name)
+            else:
+                self.audioportsOut.append(port_name)
+''',
+        '''        if self.rigforge_capture_port and self.rigforge_playback_port:
+            # These graph symbols map to Rigforge's stable virtual PipeWire boundary ports.
+            self.audioportsIn = ["capture_1"]
+            self.audioportsOut = ["playback_1"]
+        else:
+            for port in get_jack_hardware_ports(True, False):
+                client_name, port_name = port.split(":",1)
+                if client_name == "mod-spi2jack":
+                    cv_port_name = CV_PREFIX + port_name
+                    self.cvportsIn.append(cv_port_name)
+                    self.addressings.add_hw_cv_port('/cv/graph/' + cv_port_name)
+                else:
+                    self.audioportsIn.append(port_name)
+
+            for port in get_jack_hardware_ports(True, True):
+                client_name, port_name = port.split(":",1)
+                if client_name == "mod-jack2spi":
+                    self.cvportsOut.append(CV_PREFIX + port_name)
+                else:
+                    self.audioportsOut.append(port_name)
+''',
+    )
+    replace_once(
+        app / "mod" / "host.py",
+        '''        if len(data) == 3:
+            # Handle special cases
+            if data[2] == "serial_midi_in":
+''',
+        '''        if len(data) == 3:
+            # Handle special cases
+            if data[2] == "capture_1" and self.rigforge_capture_port:
+                return self.rigforge_capture_port
+            if data[2] == "playback_1" and self.rigforge_playback_port:
+                return self.rigforge_playback_port
+            if data[2] == "serial_midi_in":
+''',
+    )
+
+    replace_once(
+        app / "mod" / "session.py",
+        '''    # Set a plugin block position within the canvas
+''',
+        '''    def ws_rigforge_patch_set(self, request_id, instance, uri, valuetype, valuedata, ws):
+        if valuetype != "p":
+            ws.write_message("rigforge_patch_set_ack %s 0" % request_id)
+            return
+
+        def completed(ok):
+            status = 1 if ok else 0
+            if ok:
+                self.msg_callback_broadcast(
+                    "patch_set %s 1 %s %c %s" % (instance, uri, valuetype, valuedata),
+                    ws,
+                )
+            ws.write_message("rigforge_patch_set_ack %s %d" % (request_id, status))
+
+        self.host.patch_set(instance, uri, valuedata, completed)
+
+    # Set a plugin block position within the canvas
+''',
+    )
+
+    replace_once(
+        app / "mod" / "webserver.py",
+        '''        elif cmd == "plugin_pos":
+''',
+        '''        elif cmd == "rigforge_patch_set":
+            data = data[1].split(" ", 4)
+            if len(data) != 5:
+                self.write_message("rigforge_patch_set_ack invalid 0")
+                return
+            request_id, inst, uri, vtype, value = data
+            if not request_id.isalnum():
+                self.write_message("rigforge_patch_set_ack invalid 0")
+                return
+            SESSION.ws_rigforge_patch_set(
+                request_id, inst, uri, vtype, value, self
+            )
+
+        elif cmd == "plugin_pos":
+''',
+    )
+
+    replace_once(
+        app / "server.py",
+        "os.environ['MOD_DEVICE_WEBSERVER_PORT'] = '8888'",
+        "os.environ.setdefault('MOD_DEVICE_WEBSERVER_PORT', '8888')",
+    )
+    replace_once(
+        app / "server.py",
+        "os.environ['MOD_DEFAULT_PEDALBOARD'] = os.path.join(ROOT, 'default.pedalboard')",
+        "os.environ.setdefault('MOD_DEFAULT_PEDALBOARD', os.path.join(ROOT, 'default.pedalboard'))",
+    )
+
+    replace_once(
+        app / "html" / "js" / "pedalboard.js",
+        '''                    var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="' + i + '" title="Hardware Capture ' + i + '">')
+''',
+        '''                    var captureTitle = (i === 1) ? 'Rigforge Mod-Host Input' : ('Hardware Capture ' + i)
+                    var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="' + i + '" title="' + captureTitle + '">')
+''',
+    )
+    replace_once(
+        app / "html" / "js" / "pedalboard.js",
+        '''                    var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="' + i + '" title="Hardware Playback ' + i + '">')
+''',
+        '''                    var playbackTitle = (i === 1) ? 'Rigforge Mod-Host Output' : ('Hardware Playback ' + i)
+                    var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="' + i + '" title="' + playbackTitle + '">')
+''',
+    )
+    js_file = app / "html" / "js" / "pedalboard.js"
+    if not js_file.read_bytes().endswith(b"\n"):
+        js_file.write_bytes(js_file.read_bytes() + b"\n")
+
+
+if __name__ == "__main__":
+    if len(sys.argv) != 2:
+        raise SystemExit("Usage: patch_mod_ui_rigforge.py path/to/mod-ui/app")
+    apply(Path(sys.argv[1]))

+ 45 - 17
config/desired-state.yaml

@@ -76,16 +76,42 @@ deployment:
     service_source: config/systemd/user/rigforge-mod-host.service.in
     service_destination: .config/systemd/user/rigforge-mod-host.service
     user_service: rigforge-mod-host.service
-    configure_script: scripts/configure_mod_host.py
     readiness_script: scripts/wait_mod_host_ports.py
     port_wait_timeout_seconds: 45
     socket_port: 5555
+    feedback_port: 5556
     pw_jack_path: /usr/bin/pw-jack
     python_path: /usr/bin/python3
+  mod_host_ports:
+    binary_path: /usr/bin/pw-loopback
+    runner_script: scripts/run_mod_host_ports.py
+    service_source: config/systemd/user/rigforge-mod-host-ports.service.in
+    service_destination: .config/systemd/user/rigforge-mod-host-ports.service
+    user_service: rigforge-mod-host-ports.service
+    python_path: /usr/bin/python3
+    channel_map: AUX0
+    input_sink_name: rigforge.mod-host-input
+    input_source_name: rigforge.mod-host-input.capture
+    output_sink_name: rigforge.mod-host-output.playback
+    output_source_name: rigforge.mod-host-output
   mod_ui:
     source_url: https://github.com/mod-audio/mod-ui
     tag: v1.15.0.3371
     artifact_directory: artifacts/mod-ui/arm64/current
+    launcher: artifacts/mod-ui/arm64/current/run-mod-ui
+    runner_script: scripts/run_mod_ui_service.py
+    service_source: config/systemd/user/rigforge-mod-ui.service.in
+    service_destination: .config/systemd/user/rigforge-mod-ui.service
+    user_service: rigforge-mod-ui.service
+    pw_jack_path: /usr/bin/pw-jack
+    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
+    last_state_file: .local/share/rigforge/mod-ui/last-rigforge.json
+    hardware_input_port: rigforge.mod-host-input.capture:capture_AUX0
+    hardware_output_port: rigforge.mod-host-output.playback:playback_AUX0
   reconcile:
     observer_script: scripts/observe_pipewire.py
     service_source: config/systemd/user/rigforge-pipewire-reconcile.service.in
@@ -119,9 +145,10 @@ controls:
   midi_bridge:
     bindings_file: config/midi-bindings.yaml
     input_port_name_contains: UMC404HD
-    mod_host:
+    mod_ui:
       host: 127.0.0.1
-      port: 5555
+      port: 8888
+      websocket_path: /websocket
 
 sources:
   - id: guitar
@@ -198,7 +225,11 @@ routing:
     hardware_output_status: reported-by-target-owner
   mod_host_chains:
     guitar:
-      source_port: alsa_input.hw_U192k_0:capture_AUX0
+      physical_input_port: alsa_input.hw_U192k_0:capture_AUX0
+      source_port: rigforge.mod-host-input.capture:capture_AUX0
+      pipewire_input_port: rigforge.mod-host-input:playback_AUX0
+      pipewire_output_port: rigforge.mod-host-output:capture_AUX0
+      mod_ui_output_port: rigforge.mod-host-output.playback:playback_AUX0
       bypass_link:
         from: alsa_input.hw_U192k_0:capture_AUX0
         to: rigforge.direct-mix.input:playback_AUX0
@@ -207,6 +238,7 @@ routing:
         - id: amp-head
           instance: 0
           plugin_uri: http://github.com/mikeoliphant/neural-amp-modeler-lv2
+          mod_ui_instance: /graph/rigforge_nam
           bundle_path: .lv2/neural_amp_modeler.lv2
           file_property: http://github.com/mikeoliphant/neural-amp-modeler-lv2#model
           asset_path: amp_emul/amphead/VOX_AC15/Vox_AC15CH_Crunch_TB.nam
@@ -222,6 +254,7 @@ routing:
         - id: cabinet-ir
           instance: 1
           plugin_uri: http://lsp-plug.in/plugins/lv2/impulse_responses_mono
+          mod_ui_instance: /graph/rigforge_ir
           bundle_path: .lv2/lsp-plugins.lv2
           file_property: http://lsp-plug.in/plugins/lv2/impulse_responses_mono/ports#ifn
           asset_path: amp_emul/cabinet/VOX_AC30_1964/VOX_AC30_1964_celestion.wav
@@ -235,10 +268,8 @@ routing:
     - alsa_input.hw_U192k_0:capture_AUX1
     - alsa_input.hw_U192k_0:capture_AUX2
     - alsa_input.hw_U192k_0:capture_AUX3
-    - effect_0:input
-    - effect_0:output
-    - effect_1:in
-    - effect_1:out
+    - rigforge.mod-host-input:playback_AUX0
+    - rigforge.mod-host-output:capture_AUX0
     - sooperlooper:loop0_in_1
     - sooperlooper:loop0_in_2
     - sooperlooper:loop0_in_3
@@ -261,17 +292,14 @@ routing:
     - alsa_output.hw_U192k_0:playback_AUX0
   managed_links:
     - from: alsa_input.hw_U192k_0:capture_AUX0
-      to: effect_0:input
-      status: observed
-    - from: effect_0:output
-      to: effect_1:in
-      status: observed
-    - from: effect_1:out
+      to: rigforge.mod-host-input:playback_AUX0
+      status: planned
+    - from: rigforge.mod-host-output:capture_AUX0
       to: rigforge.direct-mix.input:playback_AUX0
-      status: observed
-    - from: effect_1:out
+      status: planned
+    - from: rigforge.mod-host-output:capture_AUX0
       to: sooperlooper:loop0_in_1
-      status: observed
+      status: planned
     - from: alsa_input.hw_U192k_0:capture_AUX1
       to: sooperlooper:loop0_in_2
       status: observed

+ 3 - 1
config/systemd/user/rigforge-midi-bridge.service.in

@@ -1,6 +1,8 @@
 [Unit]
 Description=Rigforge MIDI action bridge
-After=rigforge-mod-host.service
+Requires=rigforge-mod-ui.service
+After=rigforge-mod-ui.service
+PartOf=rigforge-mod-ui.service
 
 [Service]
 Type=simple

+ 15 - 0
config/systemd/user/rigforge-mod-host-ports.service.in

@@ -0,0 +1,15 @@
+[Unit]
+Description=Rigforge PipeWire audio boundary ports for mod-host
+Wants=pipewire.service wireplumber.service
+After=pipewire.service wireplumber.service
+PartOf=pipewire.service wireplumber.service
+
+[Service]
+Type=simple
+ExecStart=@PYTHON@ -u @RUNNER_SCRIPT@ --state @DESIRED_STATE@ --pw-loopback @PW_LOOPBACK@
+Restart=on-failure
+RestartSec=2
+TimeoutStopSec=10
+
+[Install]
+WantedBy=default.target

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

@@ -1,14 +1,14 @@
 [Unit]
-Description=Rigforge guitar NAM and cabinet chain
+Description=Rigforge mod-host backend for mod-ui
+Requires=rigforge-mod-host-ports.service
 Wants=pipewire.service wireplumber.service filter-chain.service
-After=pipewire.service wireplumber.service filter-chain.service
-PartOf=pipewire.service wireplumber.service filter-chain.service
+After=pipewire.service wireplumber.service filter-chain.service rigforge-mod-host-ports.service
+PartOf=pipewire.service wireplumber.service filter-chain.service rigforge-mod-host-ports.service
 
 [Service]
 Type=simple
 ExecStartPre=@PYTHON@ @READINESS_SCRIPT@ --state @DESIRED_STATE@ --timeout @PORT_WAIT_TIMEOUT_SECONDS@
-ExecStart=@PW_JACK@ @MOD_HOST_BINARY@ -n -p @SOCKET_PORT@
-ExecStartPost=@PYTHON@ @CONFIGURE_SCRIPT@ --state @DESIRED_STATE@ --repo-root @REPOSITORY_ROOT@
+ExecStart=@PW_JACK@ @MOD_HOST_BINARY@ -n -p @SOCKET_PORT@ -f @FEEDBACK_PORT@
 Restart=on-failure
 RestartSec=5
 TimeoutStartSec=90

+ 23 - 0
config/systemd/user/rigforge-mod-ui.service.in

@@ -0,0 +1,23 @@
+[Unit]
+Description=Rigforge mod-ui pedalboard editor
+Requires=rigforge-mod-host.service rigforge-mod-host-ports.service
+After=rigforge-mod-host.service rigforge-mod-host-ports.service
+PartOf=rigforge-mod-host.service
+
+[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_DEFAULT_PEDALBOARD=@REFERENCE_PEDALBOARD@
+Environment=MOD_DEVICE_WEBSERVER_PORT=@WEBSOCKET_PORT@
+Environment=MOD_RIGFORGE_CAPTURE_PORT=@HARDWARE_INPUT_PORT@
+Environment=MOD_RIGFORGE_PLAYBACK_PORT=@HARDWARE_OUTPUT_PORT@
+ExecStart=@PYTHON@ -u @RUNNER_SCRIPT@ --launcher @MOD_UI_LAUNCHER@ --pw-jack @PW_JACK@ --host @WEBSOCKET_HOST@ --port @WEBSOCKET_PORT@
+Restart=on-failure
+RestartSec=5
+TimeoutStopSec=10
+
+[Install]
+WantedBy=default.target

+ 362 - 18
scripts/deploy.py

@@ -14,6 +14,7 @@ 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]
@@ -40,16 +41,20 @@ def load_deployment():
     pipewire = deployment.get("pipewire")
     reconcile = deployment.get("reconcile")
     midi_bridge = deployment.get("midi_bridge")
+    mod_host_ports = deployment.get("mod_host_ports")
+    mod_ui = deployment.get("mod_ui")
     if (
         not isinstance(namlv2, dict)
         or not isinstance(sooperlooper, dict)
         or not isinstance(pipewire, dict)
         or not isinstance(reconcile, dict)
         or not isinstance(midi_bridge, dict)
+        or not isinstance(mod_host_ports, dict)
+        or not isinstance(mod_ui, dict)
     ):
         raise ValueError(
             "deployment.namlv2, deployment.sooperlooper, deployment.pipewire, deployment.reconcile, "
-            "and deployment.midi_bridge must be mappings"
+            "deployment.midi_bridge, deployment.mod_host_ports, and deployment.mod_ui must be mappings"
         )
     for component, archive_format in PLUGIN_ARCHIVES.items():
         plugin = deployment.get(component)
@@ -122,6 +127,24 @@ def tree_sha256(path):
     return digest.hexdigest()
 
 
+def runtime_tree_sha256(path):
+    digest = hashlib.sha256()
+    for item in sorted(path.rglob("*")):
+        if "__pycache__" in item.parts or item.suffix in {".pyc", ".pyo"}:
+            continue
+        relative = item.relative_to(path).as_posix().encode()
+        digest.update(relative + b"\0")
+        if item.is_symlink():
+            digest.update(b"link\0" + os.readlink(item).encode())
+        elif item.is_file():
+            digest.update(b"file\0" + item.read_bytes())
+        elif item.is_dir():
+            digest.update(b"directory\0")
+        else:
+            raise RuntimeError(f"unsupported file type in runtime bundle: {item}")
+    return digest.hexdigest()
+
+
 def validate_user_destination(destination):
     home = Path.home().resolve()
     parent = destination.parent.resolve()
@@ -810,27 +833,23 @@ def systemd_quote(value):
 def render_mod_host_service(config):
     binary = ROOT / config["binary_source"]
     service_template = ROOT / config["service_source"]
-    configure_script = ROOT / config["configure_script"]
     readiness_script = ROOT / config["readiness_script"]
     state_file = ROOT / "config" / "desired-state.yaml"
     if not binary.is_file() or not os.access(binary, os.X_OK):
         raise RuntimeError(f"ARM64 mod-host artifact is missing or not executable: {binary}")
     if not service_template.is_file():
         raise RuntimeError(f"mod-host service template is missing: {service_template}")
-    if not configure_script.is_file():
-        raise RuntimeError(f"mod-host startup configurator is missing: {configure_script}")
     if not readiness_script.is_file():
         raise RuntimeError(f"mod-host PipeWire readiness checker is missing: {readiness_script}")
     replacements = {
         "@PW_JACK@": systemd_quote(config["pw_jack_path"]),
         "@MOD_HOST_BINARY@": systemd_quote(binary.resolve()),
         "@SOCKET_PORT@": str(config["socket_port"]),
+        "@FEEDBACK_PORT@": str(config["feedback_port"]),
         "@PYTHON@": systemd_quote(config["python_path"]),
         "@READINESS_SCRIPT@": systemd_quote(readiness_script.resolve()),
         "@PORT_WAIT_TIMEOUT_SECONDS@": str(config["port_wait_timeout_seconds"]),
-        "@CONFIGURE_SCRIPT@": systemd_quote(configure_script.resolve()),
         "@DESIRED_STATE@": systemd_quote(state_file.resolve()),
-        "@REPOSITORY_ROOT@": systemd_quote(ROOT.resolve()),
     }
     content = service_template.read_text(encoding="utf-8")
     for placeholder, replacement in replacements.items():
@@ -840,6 +859,104 @@ def render_mod_host_service(config):
     return content.encode("utf-8")
 
 
+def render_mod_host_ports_service(config):
+    state_file = ROOT / "config" / "desired-state.yaml"
+    runner_script = ROOT / config["runner_script"]
+    service_template = ROOT / config["service_source"]
+    binary = Path(config["binary_path"])
+    for description, path in (
+        ("mod-host port runner", runner_script),
+        ("mod-host ports service template", service_template),
+    ):
+        if not path.is_file():
+            raise RuntimeError(f"{description} is missing: {path}")
+
+    replacements = {
+        "@PYTHON@": systemd_quote(config["python_path"]),
+        "@RUNNER_SCRIPT@": systemd_quote(runner_script.resolve()),
+        "@DESIRED_STATE@": systemd_quote(state_file.resolve()),
+        "@PW_LOOPBACK@": systemd_quote(binary),
+    }
+    content = service_template.read_text(encoding="utf-8")
+    for placeholder, replacement in replacements.items():
+        content = content.replace(placeholder, replacement)
+    if re.search(r"@[A-Z_]+@", content):
+        raise RuntimeError("unexpanded placeholder remains in mod-host ports service template")
+    fingerprint = hashlib.sha256(
+        json.dumps(config, sort_keys=True, separators=(",", ":")).encode("utf-8")
+        + runner_script.read_bytes()
+        + (ROOT / "scripts" / "validate_desired_state.py").read_bytes()
+        + state_file.read_bytes()
+    ).hexdigest()
+    return {
+        "name": config["user_service"],
+        "destination": Path.home() / config["service_destination"],
+        "content": (content + f"\n# Rigforge runtime fingerprint: {fingerprint}\n").encode("utf-8"),
+    }
+
+
+def render_mod_ui_service(config):
+    state_file = ROOT / "config" / "desired-state.yaml"
+    launcher = ROOT / config["launcher"]
+    runner_script = ROOT / config["runner_script"]
+    service_template = ROOT / config["service_source"]
+    with state_file.open(encoding="utf-8") as stream:
+        state = yaml.safe_load(stream)
+    reference_files = generate_bundle_files(state, ROOT)
+    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"
+    )
+    for description, path in (
+        ("mod-ui launcher", launcher),
+        ("mod-ui service runner", runner_script),
+        ("mod-ui service template", service_template),
+    ):
+        if not path.is_file():
+            raise RuntimeError(f"{description} is missing: {path}")
+
+    home = Path.home()
+    replacements = {
+        "@PYTHON@": systemd_quote(config["python_path"]),
+        "@RUNNER_SCRIPT@": systemd_quote(runner_script.resolve()),
+        "@MOD_UI_LAUNCHER@": systemd_quote(launcher.resolve()),
+        "@PW_JACK@": systemd_quote(config["pw_jack_path"]),
+        "@WEBSOCKET_HOST@": config["websocket_host"],
+        "@WEBSOCKET_PORT@": str(config["websocket_port"]),
+        "@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"]),
+        "@REFERENCE_PEDALBOARD@": systemd_quote(reference_pedalboard),
+        "@HARDWARE_INPUT_PORT@": config["hardware_input_port"],
+        "@HARDWARE_OUTPUT_PORT@": config["hardware_output_port"],
+    }
+    content = service_template.read_text(encoding="utf-8")
+    for placeholder, replacement in replacements.items():
+        content = content.replace(placeholder, replacement)
+    if re.search(r"@[A-Z_]+@", content):
+        raise RuntimeError("unexpanded placeholder remains in mod-ui service template")
+    artifact_root = ROOT / config["artifact_directory"]
+    runtime_digest = hashlib.sha256()
+    runtime_digest.update(runtime_tree_sha256(artifact_root).encode("ascii"))
+    runtime_digest.update(runner_script.read_bytes())
+    runtime_digest.update((ROOT / "scripts" / "mod_ui_websocket.py").read_bytes())
+    runtime_digest.update((ROOT / "scripts" / "generate_mod_ui_pedalboard.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,
+    }
+
+
 def render_reconcile_units(config):
     repository_root = ROOT.resolve()
     state_file = repository_root / "config" / "desired-state.yaml"
@@ -909,6 +1026,13 @@ def render_midi_bridge_service(config):
         content = content.replace(placeholder, replacement)
     if re.search(r"@[A-Z_]+@", content):
         raise RuntimeError("unexpanded placeholder remains in MIDI bridge service template")
+    fingerprint = hashlib.sha256(
+        bridge_script.read_bytes()
+        + (ROOT / "scripts" / "mod_ui_websocket.py").read_bytes()
+        + (ROOT / "config" / "midi-bindings.yaml").read_bytes()
+        + state_file.read_bytes()
+    ).hexdigest()
+    content += f"\n# Rigforge runtime fingerprint: {fingerprint}\n"
     return {
         "name": config["user_service"],
         "destination": Path.home() / config["service_destination"],
@@ -1177,12 +1301,199 @@ def deploy_single_user_service(action, registry_key, target_name, display_name,
 
 
 def deploy_midi_bridge(action, config, registry):
+    if action == "install" and "mod_ui" not in registry:
+        raise RuntimeError("install mod-ui before installing the MIDI bridge")
     unit = render_midi_bridge_service(config)
     deploy_single_user_service(
         action, "midi_bridge", "midi-bridge", "MIDI bridge", unit, registry
     )
 
 
+def deploy_mod_host_ports(action, config, registry):
+    if action == "uninstall" and (
+        "mod_host" in registry or "mod_ui" in registry
+    ):
+        raise RuntimeError("uninstall mod-ui and mod-host before uninstalling mod-host-ports")
+    unit = render_mod_host_ports_service(config)
+    deploy_single_user_service(
+        action,
+        "mod_host_ports",
+        "mod-host-ports",
+        "mod-host PipeWire ports",
+        unit,
+        registry,
+    )
+
+
+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")
+        if "mod_host" not in registry:
+            raise RuntimeError("install mod-host before installing mod-ui")
+        if "mod_ui" not in registry and mod_ui_port_is_open(
+            config["websocket_host"], config["websocket_port"]
+        ):
+            raise RuntimeError(
+                f"mod-ui web port {config['websocket_port']} is already in use; "
+                "stop any manually launched mod-ui before installing the service"
+            )
+        if "mod_ui" not in registry and (
+            user_unit_is_active(config["user_service"])
+            or user_unit_is_enabled(config["user_service"])
+        ):
+            raise RuntimeError(
+                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")
+    unit = render_mod_ui_service(config)
+    reference_sha256 = None
+    if action != "uninstall":
+        reference_sha256 = prepare_mod_ui_reference_bundle(unit)
+    deploy_single_user_service(
+        action,
+        "mod_ui",
+        "mod-ui",
+        "mod-ui",
+        unit,
+        registry,
+    )
+    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 prepare_mod_ui_reference_bundle(unit):
+    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:
+            raise RuntimeError(f"generated mod-ui reference changed locally: {destination}")
+    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):
+    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 not reference.is_dir()
+        or tree_sha256(reference) != reference_sha256
+    ):
+        raise RuntimeError(f"managed mod-ui reference pedalboard changed locally: {reference}")
+    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)
+    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
+        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):
+        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)
+        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):
     if state is None:
         state = yaml.safe_load(
@@ -1425,7 +1736,6 @@ def deploy_reconcile(action, config, registry):
 
 def mod_host_runtime_digest(config):
     state_path = ROOT / "config" / "desired-state.yaml"
-    script_path = ROOT / config["configure_script"]
     readiness_script = ROOT / config["readiness_script"]
     validator_path = ROOT / "scripts" / "validate_desired_state.py"
     binary_path = ROOT / config["binary_source"]
@@ -1433,20 +1743,16 @@ def mod_host_runtime_digest(config):
         state = yaml.safe_load(stream)
     guitar_chain = state["routing"]["mod_host_chains"]["guitar"]
     mod_host_config = state["deployment"]["mod_host"]
-    files = [script_path, readiness_script, validator_path, binary_path]
-    for processor in guitar_chain["processors"]:
-        asset_path = PurePosixPath(processor["asset_path"])
-        if asset_path.is_absolute() or ".." in asset_path.parts:
-            raise RuntimeError(f"unsafe mod-host asset path: {processor['asset_path']!r}")
-        resolved = (ROOT / Path(*asset_path.parts)).resolve()
-        if not resolved.is_relative_to(ROOT.resolve()) or not resolved.is_file():
-            raise RuntimeError(f"declared mod-host asset is missing or escapes the repository: {resolved}")
-        files.append(resolved)
+    files = [readiness_script, validator_path, binary_path]
 
     digest = hashlib.sha256()
     digest.update(
         json.dumps(
-            {"deployment.mod_host": mod_host_config, "routing.mod_host_chains.guitar": guitar_chain},
+            {
+                "deployment.mod_host": mod_host_config,
+                "deployment.mod_host_ports": state["deployment"]["mod_host_ports"],
+                "routing.mod_host_chains.guitar": guitar_chain,
+            },
             sort_keys=True,
             separators=(",", ":"),
         ).encode("utf-8")
@@ -1469,6 +1775,14 @@ def mod_host_port_is_open(port):
         return False
 
 
+def mod_ui_port_is_open(host, port):
+    try:
+        with socket.create_connection((host, port), timeout=0.25):
+            return True
+    except OSError:
+        return False
+
+
 def user_unit_is_active(service_name):
     result = subprocess.run(
         ["systemctl", "--user", "is-active", "--quiet", service_name],
@@ -1495,6 +1809,23 @@ def deploy_mod_host(action, config, registry):
     service_name = config["user_service"]
     managed = registry.get("mod_host")
 
+    if action == "install" and "mod_host_ports" not in registry:
+        raise RuntimeError("install mod-host-ports before installing mod-host")
+    if action == "uninstall" and "mod_ui" in registry:
+        raise RuntimeError("uninstall mod-ui before uninstalling mod-host")
+    if managed is not None and not user_unit_is_active(service_name):
+        occupied_ports = [
+            port
+            for port in (config["socket_port"], config["feedback_port"])
+            if mod_host_port_is_open(port)
+        ]
+        if occupied_ports:
+            raise RuntimeError(
+                "mod-host TCP port(s) "
+                f"{occupied_ports} are open while the managed service is inactive; "
+                "stop any unmanaged/manual mod-host process before retrying"
+            )
+
     if action == "reload":
         if managed is None:
             raise RuntimeError("mod-host is not managed; install mod-host before reloading it")
@@ -1609,6 +1940,11 @@ def deploy_mod_host(action, config, registry):
                 f"mod-host control port {config['socket_port']} is already in use; "
                 "stop the unmanaged test process before installing the user service"
             )
+        if mod_host_port_is_open(config["feedback_port"]):
+            raise RuntimeError(
+                f"mod-host feedback port {config['feedback_port']} is already in use; "
+                "stop the unmanaged test process before installing the user service"
+            )
         backup = None
         backup_sha256 = None
         if destination.exists():
@@ -1671,7 +2007,7 @@ def deploy_mod_host(action, config, registry):
 
 def main(argv=None):
     parser = argparse.ArgumentParser()
-    parser.add_argument("action", choices=("install", "uninstall", "reload"))
+    parser.add_argument("action", choices=("install", "uninstall", "reload", "reset"))
     parser.add_argument(
         "target",
         choices=(
@@ -1679,13 +2015,17 @@ def main(argv=None):
             "lsp",
             "dragonfly-reverb",
             "pipewire",
+            "mod-host-ports",
             "mod-host",
+            "mod-ui",
             "reconcile",
             "midi-bridge",
             "sooperlooper",
         ),
     )
     args = parser.parse_args(argv)
+    if args.action == "reset" and args.target != "mod-ui":
+        parser.error("reset is only supported for mod-ui")
     try:
         state = yaml.safe_load((ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8"))
         deployment = load_deployment()
@@ -1699,6 +2039,10 @@ def main(argv=None):
             deploy_pipewire(args.action, deployment["pipewire"], registry, quantum_frames)
         elif args.target == "mod-host":
             deploy_mod_host(args.action, deployment["mod_host"], registry)
+        elif args.target == "mod-host-ports":
+            deploy_mod_host_ports(args.action, deployment["mod_host_ports"], registry)
+        elif args.target == "mod-ui":
+            deploy_mod_ui(args.action, deployment["mod_ui"], registry)
         elif args.target == "reconcile":
             deploy_reconcile(args.action, deployment["reconcile"], registry)
         elif args.target == "midi-bridge":

+ 6 - 3
scripts/deploy.sh

@@ -2,7 +2,7 @@
 set -u
 
 usage() {
-    printf 'Usage: %s install|uninstall|reload all|namlv2|lsp|dragonfly-reverb|pipewire|mod-host|reconcile|midi-bridge|sooperlooper\n' "$0" >&2
+    printf 'Usage: %s install|uninstall|reload|reset all|namlv2|lsp|dragonfly-reverb|pipewire|mod-host-ports|mod-host|mod-ui|reconcile|midi-bridge|sooperlooper\n' "$0" >&2
     exit 2
 }
 
@@ -10,14 +10,17 @@ usage() {
 action=$1
 target=$2
 case "$action" in
-    install|uninstall|reload) ;;
+    install|uninstall|reload|reset) ;;
     *) usage ;;
 esac
 case "$target" in
     all) targets=(pipewire namlv2 lsp dragonfly-reverb) ;;
-    namlv2|lsp|dragonfly-reverb|pipewire|mod-host|reconcile|midi-bridge|sooperlooper) targets=("$target") ;;
+    namlv2|lsp|dragonfly-reverb|pipewire|mod-host-ports|mod-host|mod-ui|reconcile|midi-bridge|sooperlooper) targets=("$target") ;;
     *) usage ;;
 esac
+if [[ "$action" == reset && "$target" != mod-ui ]]; then
+    usage
+fi
 
 script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
 status=0

+ 356 - 0
scripts/generate_mod_ui_pedalboard.py

@@ -0,0 +1,356 @@
+#!/usr/bin/env python3
+"""Generate Rigforge's reference guitar 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 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):
+    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"]
+    nam_path = resolved_asset(repo_root, nam["asset_path"])
+    ir_path = resolved_asset(repo_root, ir["asset_path"])
+    output_level = nam["parameters"]["output_level"]
+
+    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"]
+
+    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 "Rigforge Mod-Host Input" ;
+    lv2:portProperty lv2:connectionOptional ;
+    lv2:symbol "capture_1" ;
+    a lv2:AudioPort, lv2:InputPort .
+
+<playback_1>
+    lv2:index 6 ;
+    lv2:name "Rigforge Mod-Host Output" ;
+    lv2:portProperty lv2:connectionOptional ;
+    lv2:symbol "playback_1" ;
+    a lv2:AudioPort, lv2:OutputPort .
+
+<: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 Guitar NAM and IR" ;
+    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 ;
+    ingen:block <{nam_instance}>, <{ir_instance}> ;
+    lv2:port <:bpb>, <:bpm>, <:rolling>,
+             <control_in>, <control_out>,
+             <capture_1>, <playback_1>,
+             <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> .
+"""
+
+    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',
+    }
+    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())

+ 39 - 35
scripts/midi_action_bridge.py

@@ -1,14 +1,14 @@
 #!/usr/bin/env python3
-"""Translate configured MIDI events into safe mod-host actions."""
+"""Translate configured MIDI events into NAM model changes via mod-ui."""
 
 import argparse
-import socket
 import sys
 import time
 from pathlib import Path, PurePosixPath
 
 import yaml
 
+from mod_ui_websocket import ModUiWebSocketClient
 from validate_desired_state import safe_relative_path, validate_state
 
 
@@ -156,34 +156,16 @@ def resolve_asset(repo_root, relative_path):
     return resolved
 
 
-def mod_host_command(host, port, command, timeout=5):
-    payload = command.encode("utf-8") + b"\0"
-    with socket.create_connection((host, port), timeout=timeout) as connection:
-        connection.settimeout(timeout)
-        connection.sendall(payload)
-        response = bytearray()
-        while b"\0" not in response:
-            chunk = connection.recv(4096)
-            if not chunk:
-                raise RuntimeError(f"mod-host closed the socket before replying to {command!r}")
-            response.extend(chunk)
-    return bytes(response).split(b"\0", 1)[0].decode("utf-8", errors="replace")
-
-
-def check_mod_host_response(response, command):
-    fields = response.split()
-    if len(fields) < 2 or fields[0] != "resp":
-        raise RuntimeError(f"unexpected mod-host response to {command!r}: {response!r}")
-    try:
-        status = int(fields[1])
-    except ValueError as error:
-        raise RuntimeError(f"invalid mod-host response to {command!r}: {response!r}") from error
-    if status < 0:
-        raise RuntimeError(f"mod-host rejected {command!r}: {response}")
-    return status
+def mod_ui_command(config, instance, property_uri, value):
+    with ModUiWebSocketClient(
+        config["host"],
+        config["port"],
+        config["websocket_path"],
+    ) as client:
+        return client.set_patch(instance, property_uri, value)
 
 
-def select_nam_model(action, state, repo_root, command=mod_host_command):
+def select_nam_model(action, state, repo_root, command=None):
     processor = resolve_processor(state, action["target"])
     models = processor["available_models"]
     requested_id = action["model"]
@@ -206,12 +188,15 @@ def select_nam_model(action, state, repo_root, command=mod_host_command):
             file=sys.stderr,
         )
 
-    host_config = bridge_config(state)["mod_host"]
-    instance = processor["instance"]
+    ui_config = bridge_config(state)["mod_ui"]
+    instance = processor["mod_ui_instance"]
     property_uri = processor["file_property"]
-    command_text = f"patch_set {instance} {property_uri} {selected_path}"
-    response = command(host_config["host"], host_config["port"], command_text)
-    check_mod_host_response(response, command_text)
+    if command is None:
+        command = lambda instance, property_uri, value: mod_ui_command(
+            ui_config, instance, property_uri, value
+        )
+    if not command(instance, property_uri, str(selected_path)):
+        raise RuntimeError(f"mod-ui did not apply NAM model {selected_id!r}")
     return selected_id, selected_path
 
 
@@ -222,7 +207,7 @@ def binding_index(bindings):
     }
 
 
-def handle_midi_message(message, bindings, state, repo_root, command=mod_host_command):
+def handle_midi_message(message, bindings, state, repo_root, command=None):
     if not message or len(message) < 3:
         return None
     status, note, velocity = message[:3]
@@ -290,6 +275,16 @@ def run_bridge(state, bindings, repo_root, rtmidi_module=None, sleeper=time.slee
     config = bridge_config(state)
     name_contains = config["input_port_name_contains"]
     actions = binding_index(bindings)
+    ui_config = config["mod_ui"]
+    mod_ui_client = ModUiWebSocketClient(
+        ui_config["host"],
+        ui_config["port"],
+        ui_config["websocket_path"],
+    )
+
+    def set_nam_model(instance, property_uri, value):
+        return mod_ui_client.set_patch(instance, property_uri, value)
+
     print(f"Looking for ALSA MIDI input containing {name_contains!r}…")
     while True:
         midi_in = None
@@ -297,11 +292,18 @@ def run_bridge(state, bindings, repo_root, rtmidi_module=None, sleeper=time.slee
             midi_in, port_name = open_midi_input(rtmidi_module, name_contains)
             print(f"Listening on {port_name}")
             while True:
+                if mod_ui_client.connection is not None:
+                    try:
+                        mod_ui_client.serve_once(timeout=0.001)
+                    except (OSError, RuntimeError) as error:
+                        print(f"mod-ui WebSocket closed: {error}; reconnecting on next action", file=sys.stderr)
+                        mod_ui_client.close()
                 received = midi_in.get_message()
                 if received:
                     try:
                         result = handle_midi_message(
-                            received[0], actions, state, repo_root
+                            received[0], actions, state, repo_root,
+                            command=set_nam_model,
                         )
                         if result:
                             print(
@@ -310,6 +312,7 @@ def run_bridge(state, bindings, repo_root, rtmidi_module=None, sleeper=time.slee
                             )
                     except (OSError, RuntimeError, ValueError, KeyError) as error:
                         print(f"MIDI action failed: {error}", file=sys.stderr)
+                        mod_ui_client.close()
                 sleeper(0.005)
         except KeyboardInterrupt:
             return
@@ -319,6 +322,7 @@ def run_bridge(state, bindings, repo_root, rtmidi_module=None, sleeper=time.slee
         finally:
             if midi_in is not None:
                 midi_in.close_port()
+            mod_ui_client.close()
 
 
 def main(argv=None):

+ 191 - 0
scripts/mod_ui_websocket.py

@@ -0,0 +1,191 @@
+"""Small synchronous WebSocket client for mod-ui's local control endpoint."""
+
+import base64
+import hashlib
+import os
+import socket
+import struct
+import uuid
+
+
+class ModUiWebSocketClient:
+    def __init__(self, host, port, path="/websocket", timeout=5):
+        self.host = host
+        self.port = port
+        self.path = path
+        self.timeout = timeout
+        self.connection = None
+        self.buffer = bytearray()
+
+    def connect(self):
+        if self.connection is not None:
+            return
+        connection = socket.create_connection((self.host, self.port), timeout=self.timeout)
+        connection.settimeout(self.timeout)
+        key = base64.b64encode(os.urandom(16)).decode("ascii")
+        request = (
+            f"GET {self.path} HTTP/1.1\r\n"
+            f"Host: {self.host}:{self.port}\r\n"
+            "Upgrade: websocket\r\n"
+            "Connection: Upgrade\r\n"
+            f"Origin: http://{self.host}:{self.port}\r\n"
+            f"Sec-WebSocket-Key: {key}\r\n"
+            "Sec-WebSocket-Version: 13\r\n\r\n"
+        )
+        connection.sendall(request.encode("ascii"))
+        response = bytearray()
+        while not response.endswith(b"\r\n\r\n"):
+            chunk = connection.recv(1)
+            if not chunk:
+                connection.close()
+                raise RuntimeError("mod-ui closed the WebSocket handshake")
+            response.extend(chunk)
+            if len(response) > 16384:
+                connection.close()
+                raise RuntimeError("mod-ui WebSocket handshake headers are too large")
+
+        lines = response.decode("latin-1").split("\r\n")
+        if not lines or " 101 " not in f" {lines[0]} ":
+            connection.close()
+            raise RuntimeError(f"mod-ui rejected the WebSocket handshake: {lines[0] if lines else ''}")
+        headers = {}
+        for line in lines[1:]:
+            if ":" in line:
+                name, value = line.split(":", 1)
+                headers[name.strip().casefold()] = value.strip()
+        expected = base64.b64encode(
+            hashlib.sha1(
+                (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode("ascii")
+            ).digest()
+        ).decode("ascii")
+        if headers.get("sec-websocket-accept") != expected:
+            connection.close()
+            raise RuntimeError("mod-ui returned an invalid WebSocket accept key")
+        self.connection = connection
+
+    def _send_frame(self, opcode, payload=b""):
+        if self.connection is None:
+            raise RuntimeError("mod-ui WebSocket is not connected")
+        if isinstance(payload, str):
+            payload = payload.encode("utf-8")
+        mask = os.urandom(4)
+        size = len(payload)
+        if size < 126:
+            header = bytes((0x80 | opcode, 0x80 | size))
+        elif size < 65536:
+            header = bytes((0x80 | opcode, 0x80 | 126)) + struct.pack("!H", size)
+        else:
+            header = bytes((0x80 | opcode, 0x80 | 127)) + struct.pack("!Q", size)
+        masked = bytes(value ^ mask[index % 4] for index, value in enumerate(payload))
+        self.connection.sendall(header + mask + masked)
+
+    def send_text(self, text):
+        self._send_frame(0x1, text)
+
+    def _receive_exactly(self, size):
+        while len(self.buffer) < size:
+            chunk = self.connection.recv(max(4096, size - len(self.buffer)))
+            if not chunk:
+                raise RuntimeError("mod-ui closed the WebSocket connection")
+            self.buffer.extend(chunk)
+        result = bytes(self.buffer[:size])
+        del self.buffer[:size]
+        return result
+
+    def receive_frame(self):
+        first, second = self._receive_exactly(2)
+        opcode = first & 0x0F
+        masked = bool(second & 0x80)
+        size = second & 0x7F
+        if size == 126:
+            size = struct.unpack("!H", self._receive_exactly(2))[0]
+        elif size == 127:
+            size = struct.unpack("!Q", self._receive_exactly(8))[0]
+        mask = self._receive_exactly(4) if masked else b""
+        payload = self._receive_exactly(size)
+        if masked:
+            payload = bytes(value ^ mask[index % 4] for index, value in enumerate(payload))
+        return opcode, payload
+
+    def process_control_message(self, message):
+        if message == "ping":
+            self.send_text("pong")
+        elif message.startswith("data_ready "):
+            self.send_text(message)
+        elif message.startswith("rigforge_patch_set_ack "):
+            return message
+        return None
+
+    def set_patch(self, instance, property_uri, value):
+        self.connect()
+        request_id = uuid.uuid4().hex
+        self.send_text(
+            f"rigforge_patch_set {request_id} {instance} {property_uri} p {value}"
+        )
+        while True:
+            opcode, payload = self.receive_frame()
+            if opcode == 0x8:
+                raise RuntimeError("mod-ui closed the WebSocket while setting the NAM model")
+            if opcode == 0x9:
+                self._send_frame(0xA, payload)
+                continue
+            if opcode != 0x1:
+                continue
+            message = payload.decode("utf-8", errors="replace")
+            if message == "ping" or message.startswith("data_ready "):
+                self.process_control_message(message)
+                continue
+            if message.startswith(f"rigforge_patch_set_ack {request_id} "):
+                status = message.rsplit(" ", 1)[-1]
+                if status != "1":
+                    raise RuntimeError(f"mod-ui rejected NAM model update: {message}")
+                return True
+
+    def serve_once(self, timeout=1):
+        if self.connection is None:
+            self.connect()
+        self.connection.settimeout(timeout)
+        try:
+            opcode, payload = self.receive_frame()
+        except socket.timeout:
+            return
+        finally:
+            if self.connection is not None:
+                self.connection.settimeout(self.timeout)
+        if opcode == 0x8:
+            raise RuntimeError("mod-ui closed the session WebSocket")
+        if opcode == 0x9:
+            self._send_frame(0xA, payload)
+            return None
+        elif opcode == 0x1:
+            message = payload.decode("utf-8", errors="replace")
+            self.process_control_message(message)
+            return message
+        return None
+
+    def close(self):
+        connection, self.connection = self.connection, None
+        self.buffer.clear()
+        if connection is None:
+            return
+        try:
+            try:
+                self._send_close(connection)
+            except OSError:
+                pass
+        finally:
+            connection.close()
+
+    @staticmethod
+    def _send_close(connection):
+        mask = os.urandom(4)
+        payload = b""
+        header = bytes((0x88, 0x80))
+        connection.sendall(header + mask + payload)
+
+    def __enter__(self):
+        self.connect()
+        return self
+
+    def __exit__(self, _type, _value, _traceback):
+        self.close()

+ 10 - 10
scripts/observe_pipewire.py

@@ -16,8 +16,8 @@ MANAGED_ENDPOINT_PATTERN = re.compile(
     r"alsa_output\.hw_U192k_0:playback_AUX[0-3]|"
     r"rigforge\.direct-mix\.input:playback_AUX[0-7]|"
     r"rigforge\.direct-mix\.output:capture_FL|"
-    r"effect_0:(?:input|output)|"
-    r"effect_1:(?:in|out)|"
+    r"rigforge\.mod-host-input:playback_AUX0|"
+    r"rigforge\.mod-host-output:capture_AUX0|"
     r"sooperlooper:loop0_(?:in|out)_[1-4]|"
     r"sooperlooper:midi_in|"
     r"Midi-Bridge:UMC404HD 192k MIDI 1 \(capture\)"
@@ -49,7 +49,7 @@ def validate_managed_links(state):
     for index, port in enumerate(managed_ports):
         if not isinstance(port, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(port):
             errors.append(
-                f"routing.managed_ports[{index}] is not an approved observed Rigforge, UMC, or MIDI port"
+                f"routing.managed_ports[{index}] is not an approved Rigforge boundary, UMC, or MIDI port"
             )
     if len(managed_ports) != len(set(port for port in managed_ports if isinstance(port, str))):
         errors.append("routing.managed_ports must not contain duplicate ports")
@@ -66,11 +66,11 @@ def validate_managed_links(state):
         destination = link.get("to")
         if not isinstance(source, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(source):
             errors.append(
-                f"routing.managed_links[{index}].from is not an approved observed Rigforge, UMC, or MIDI port"
+                f"routing.managed_links[{index}].from is not an approved Rigforge boundary, UMC, or MIDI port"
             )
         if not isinstance(destination, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(destination):
             errors.append(
-                f"routing.managed_links[{index}].to is not an approved observed Rigforge, UMC, or MIDI port"
+                f"routing.managed_links[{index}].to is not an approved Rigforge boundary, UMC, or MIDI port"
             )
         if (
             isinstance(source, str)
@@ -96,11 +96,11 @@ def validate_managed_links(state):
         destination = link.get("to")
         if not isinstance(source, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(source):
             errors.append(
-                f"routing.managed_unlinks[{index}].from is not an approved observed Rigforge, UMC, or MIDI port"
+                f"routing.managed_unlinks[{index}].from is not an approved Rigforge boundary, UMC, or MIDI port"
             )
         if not isinstance(destination, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(destination):
             errors.append(
-                f"routing.managed_unlinks[{index}].to is not an approved observed Rigforge, UMC, or MIDI port"
+                f"routing.managed_unlinks[{index}].to is not an approved Rigforge boundary, UMC, or MIDI port"
             )
         if (
             isinstance(source, str)
@@ -223,12 +223,12 @@ def reconcile_once(state, runner=subprocess.run):
                     ),
                 }
                 if any(
-                    item["port"].startswith(("effect_0:", "effect_1:"))
+                    item["port"].startswith("rigforge.mod-host-")
                     for item in unavailable
                 ):
                     action["hint"] = (
-                        "mod-host must be running and load the NAM/IR plugins to expose "
-                        "effect_0/effect_1 ports"
+                        "Rigforge mod-host boundary ports must be running; mod-ui provides the "
+                        "internal NAM/IR connections"
                     )
                 elif any(item["port"] == "sooperlooper:midi_in" for item in unavailable):
                     action["hint"] = (

+ 179 - 0
scripts/run_mod_host_ports.py

@@ -0,0 +1,179 @@
+#!/usr/bin/env python3
+"""Keep Rigforge's mono PipeWire/mod-ui boundary loopbacks alive."""
+
+import argparse
+import signal
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import yaml
+
+from validate_desired_state import validate_state
+
+
+def loopback_command(binary, node_name, capture_name, playback_name, channel_map, latency_ms):
+    position = f"[{channel_map}]"
+    label = node_name.rsplit(".", 1)[-1].replace("-", "_")
+    capture_props = " ".join(
+        (
+            f"node.name={capture_name}",
+            f"node.description=Rigforge_{label}_Sink",
+            "media.class=Audio/Sink",
+            f"audio.position={position}",
+            "stream.dont-remix=true",
+            "node.passive=true",
+            "node.virtual=true",
+            "node.dont-reconnect=true",
+        )
+    )
+    playback_props = " ".join(
+        (
+            f"node.name={playback_name}",
+            f"node.description=Rigforge_{label}_Source",
+            "media.class=Audio/Source",
+            f"audio.position={position}",
+            "stream.dont-remix=true",
+            "node.passive=true",
+            "node.virtual=true",
+            "node.dont-reconnect=true",
+        )
+    )
+    return [
+        str(binary),
+        "--name",
+        node_name,
+        "--channels",
+        "1",
+        "--channel-map",
+        position,
+        "--latency",
+        f"{latency_ms:.6g}",
+        "--capture-props",
+        capture_props,
+        "--playback-props",
+        playback_props,
+    ]
+
+
+def required_endpoints(state):
+    chain = state["routing"]["mod_host_chains"]["guitar"]
+    return {
+        chain["pipewire_input_port"],
+        chain["source_port"],
+        chain["mod_ui_output_port"],
+        chain["pipewire_output_port"],
+    }
+
+
+def assert_boundary_ports_absent(state, runner=subprocess.run):
+    expected = required_endpoints(state)
+    observed = set()
+    for direction in ("-i", "-o"):
+        result = runner(
+            ["pw-link", direction],
+            check=True,
+            capture_output=True,
+            text=True,
+            timeout=2,
+        )
+        observed.update(line.strip() for line in result.stdout.splitlines() if line.strip())
+    collisions = expected & observed
+    if collisions:
+        raise RuntimeError(
+            "Rigforge boundary port names are already present; stop the unmanaged "
+            f"loopback process first: {sorted(collisions)}"
+        )
+
+
+def run_ports(state, binary, runner=subprocess.Popen, sleeper=time.sleep):
+    config = state["deployment"]["mod_host_ports"]
+    channel_map = config["channel_map"]
+    latency_ms = (
+        1000.0
+        * state["parameters"]["quantum_frames"]
+        / state["parameters"]["sample_rate_hz"]
+    )
+    commands = (
+        loopback_command(
+            binary,
+            "rigforge.mod-host-input",
+            config["input_sink_name"],
+            config["input_source_name"],
+            channel_map,
+            latency_ms,
+        ),
+        loopback_command(
+            binary,
+            "rigforge.mod-host-output",
+            config["output_sink_name"],
+            config["output_source_name"],
+            channel_map,
+            latency_ms,
+        ),
+    )
+    processes = []
+    stopping = [False]
+
+    def request_stop(_signum, _frame):
+        stopping[0] = True
+
+    previous_handlers = {}
+    for signum in (signal.SIGTERM, signal.SIGINT):
+        previous_handlers[signum] = signal.signal(signum, request_stop)
+    try:
+        for command in commands:
+            processes.append(runner(command))
+        while not stopping[0]:
+            for process in processes:
+                status = process.poll()
+                if status is not None:
+                    raise RuntimeError(
+                        f"pw-loopback exited unexpectedly with status {status}"
+                    )
+            sleeper(0.25)
+    finally:
+        for signum, handler in previous_handlers.items():
+            signal.signal(signum, handler)
+        for process in processes:
+            if process.poll() is None:
+                process.terminate()
+        deadline = time.monotonic() + 5
+        for process in processes:
+            if process.poll() is None:
+                remaining = max(0.0, deadline - time.monotonic())
+                try:
+                    process.wait(timeout=remaining)
+                except subprocess.TimeoutExpired:
+                    process.kill()
+                    process.wait()
+
+
+def main(argv=None):
+    root = Path(__file__).resolve().parents[1]
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("--state", type=Path, default=root / "config" / "desired-state.yaml")
+    parser.add_argument("--pw-loopback", type=Path, default=Path("/usr/bin/pw-loopback"))
+    args = parser.parse_args(argv)
+    try:
+        state = yaml.safe_load(args.state.read_text(encoding="utf-8"))
+        errors = validate_state(state)
+        if errors:
+            raise ValueError("invalid desired state: " + "; ".join(errors))
+        if not args.pw_loopback.is_file():
+            raise FileNotFoundError(f"pw-loopback was not found: {args.pw_loopback}")
+        assert_boundary_ports_absent(state)
+        print(
+            "Starting Rigforge PipeWire boundaries: "
+            + ", ".join(sorted(required_endpoints(state)))
+        )
+        run_ports(state, args.pw_loopback)
+    except (OSError, RuntimeError, ValueError, KeyError, TypeError, yaml.YAMLError) as error:
+        print(f"ERROR: {error}", file=sys.stderr)
+        return 1
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 99 - 0
scripts/run_mod_ui_service.py

@@ -0,0 +1,99 @@
+#!/usr/bin/env python3
+"""Run mod-ui under pw-jack and keep its mod-host session active."""
+
+import argparse
+import signal
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+from mod_ui_websocket import ModUiWebSocketClient
+
+
+def run_service(launcher, pw_jack, host, port, websocket_path, timeout, popen=subprocess.Popen):
+    process = popen([str(pw_jack), str(launcher)])
+    stopping = [False]
+
+    def request_stop(_signum, _frame):
+        stopping[0] = True
+
+    old_term = signal.signal(signal.SIGTERM, request_stop)
+    old_int = signal.signal(signal.SIGINT, request_stop)
+    client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
+    deadline = time.monotonic() + timeout
+    try:
+        while not stopping[0]:
+            if process.poll() is not None:
+                raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
+            try:
+                client.connect()
+                break
+            except OSError:
+                if time.monotonic() >= deadline:
+                    raise RuntimeError(
+                        f"mod-ui WebSocket did not become ready on {host}:{port}{websocket_path}"
+                    )
+                time.sleep(0.25)
+
+        if not stopping[0]:
+            print("Waiting for mod-ui to finish loading the current pedalboard")
+            while not stopping[0]:
+                if process.poll() is not None:
+                    raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
+                message = client.serve_once(timeout=0.5)
+                if message and message.startswith("loading_end "):
+                    break
+                if time.monotonic() >= deadline:
+                    raise RuntimeError("mod-ui did not finish loading a pedalboard before timeout")
+            print("mod-ui pedalboard loaded; keeping its mod-host session active")
+        while not stopping[0]:
+            if process.poll() is not None:
+                raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
+            client.serve_once(timeout=0.5)
+    finally:
+        signal.signal(signal.SIGTERM, old_term)
+        signal.signal(signal.SIGINT, old_int)
+        client.close()
+        if process.poll() is None:
+            process.terminate()
+            try:
+                process.wait(timeout=5)
+            except subprocess.TimeoutExpired:
+                process.kill()
+                process.wait()
+
+
+def main(argv=None):
+    root = Path(__file__).resolve().parents[1]
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("--launcher", type=Path, required=True)
+    parser.add_argument("--pw-jack", type=Path, default=Path("/usr/bin/pw-jack"))
+    parser.add_argument("--host", default="127.0.0.1")
+    parser.add_argument("--port", type=int, default=8888)
+    parser.add_argument("--websocket-path", default="/websocket")
+    parser.add_argument("--timeout", type=float, default=60)
+    args = parser.parse_args(argv)
+    if not args.launcher.is_file():
+        print(f"ERROR: mod-ui launcher is missing: {args.launcher}", file=sys.stderr)
+        return 1
+    if not args.pw_jack.is_file():
+        print(f"ERROR: pw-jack is missing: {args.pw_jack}", file=sys.stderr)
+        return 1
+    try:
+        run_service(
+            args.launcher,
+            args.pw_jack,
+            args.host,
+            args.port,
+            args.websocket_path,
+            args.timeout,
+        )
+    except (OSError, RuntimeError, ValueError) as error:
+        print(f"ERROR: {error}", file=sys.stderr)
+        return 1
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 121 - 20
scripts/validate_desired_state.py

@@ -24,14 +24,32 @@ def validate_mod_host_chain(routing, source_by_id):
         return errors + ["routing.mod_host_chains.guitar must be a mapping"]
 
     guitar = source_by_id.get("guitar")
-    source_port = guitar.get("capture_port") if isinstance(guitar, dict) else None
-    if chain.get("source_port") != source_port:
-        errors.append("routing.mod_host_chains.guitar.source_port must match the guitar capture port")
+    physical_input = guitar.get("capture_port") if isinstance(guitar, dict) else None
+    if chain.get("physical_input_port") != physical_input:
+        errors.append(
+            "routing.mod_host_chains.guitar.physical_input_port must match the guitar capture port"
+        )
+    if chain.get("source_port") != "rigforge.mod-host-input.capture:capture_AUX0":
+        errors.append(
+            "routing.mod_host_chains.guitar.source_port must be the mod-ui-visible input boundary"
+        )
+    if chain.get("pipewire_input_port") != "rigforge.mod-host-input:playback_AUX0":
+        errors.append(
+            "routing.mod_host_chains.guitar.pipewire_input_port must be the Rigforge input sink"
+        )
+    if chain.get("pipewire_output_port") != "rigforge.mod-host-output:capture_AUX0":
+        errors.append(
+            "routing.mod_host_chains.guitar.pipewire_output_port must be the Rigforge output source"
+        )
+    if chain.get("mod_ui_output_port") != "rigforge.mod-host-output.playback:playback_AUX0":
+        errors.append(
+            "routing.mod_host_chains.guitar.mod_ui_output_port must be the mod-ui-visible output boundary"
+        )
     bypass = chain.get("bypass_link")
     mix_input = chain.get("mix_input")
     if not isinstance(bypass, dict):
         errors.append("routing.mod_host_chains.guitar.bypass_link must be a mapping")
-    elif bypass != {"from": source_port, "to": mix_input}:
+    elif bypass != {"from": physical_input, "to": mix_input}:
         errors.append("routing.mod_host_chains.guitar.bypass_link must identify the direct capture-to-mix edge")
     if mix_input != "rigforge.direct-mix.input:playback_AUX0":
         errors.append("routing.mod_host_chains.guitar.mix_input must be the guitar mixer's AUX0 input")
@@ -45,6 +63,7 @@ def validate_mod_host_chain(routing, source_by_id):
             "id": "amp-head",
             "instance": 0,
             "plugin_uri": "http://github.com/mikeoliphant/neural-amp-modeler-lv2",
+            "mod_ui_instance": "/graph/rigforge_nam",
             "bundle_path": ".lv2/neural_amp_modeler.lv2",
             "file_property": "http://github.com/mikeoliphant/neural-amp-modeler-lv2#model",
             "asset_path": "amp_emul/amphead/VOX_AC15/Vox_AC15CH_Crunch_TB.nam",
@@ -55,6 +74,7 @@ def validate_mod_host_chain(routing, source_by_id):
             "id": "cabinet-ir",
             "instance": 1,
             "plugin_uri": "http://lsp-plug.in/plugins/lv2/impulse_responses_mono",
+            "mod_ui_instance": "/graph/rigforge_ir",
             "bundle_path": ".lv2/lsp-plugins.lv2",
             "file_property": "http://lsp-plug.in/plugins/lv2/impulse_responses_mono/ports#ifn",
             "asset_path": "amp_emul/cabinet/VOX_AC30_1964/VOX_AC30_1964_celestion.wav",
@@ -113,15 +133,23 @@ def validate_mod_host_chain(routing, source_by_id):
         }
         if isinstance(processors[0], dict) and isinstance(processors[1], dict):
             expected_candidates = (
-                (source_port, processors[0].get("input_port")),
-                (processors[0].get("output_port"), processors[1].get("input_port")),
-                (processors[1].get("output_port"), mix_input),
+                (physical_input, chain.get("pipewire_input_port")),
+                (chain.get("pipewire_output_port"), mix_input),
+                (chain.get("pipewire_output_port"), "sooperlooper:loop0_in_1"),
             )
             for edge in expected_candidates:
                 if not all(isinstance(endpoint, str) for endpoint in edge):
                     continue
                 if edge not in actual_edges:
-                    errors.append(f"mod-host guitar chain link must be declared: {edge[0]} -> {edge[1]}")
+                    errors.append(f"mod-host guitar boundary link must be declared: {edge[0]} -> {edge[1]}")
+            internal_edge = (
+                processors[0].get("output_port"),
+                processors[1].get("input_port"),
+            )
+            if internal_edge in actual_edges:
+                errors.append(
+                    "the NAM-to-IR link is owned by mod-ui and must not be a Rigforge managed link"
+                )
         if isinstance(bypass, dict):
             bypass_edge = (bypass.get("from"), bypass.get("to"))
             if all(isinstance(endpoint, str) for endpoint in bypass_edge) and bypass_edge in actual_edges:
@@ -265,6 +293,19 @@ def validate_state(state):
 
     errors.extend(validate_mod_host_chain(routing, source_by_id))
 
+    parameters = state.get("parameters")
+    if not isinstance(parameters, dict):
+        errors.append("parameters must be a mapping")
+    else:
+        for key in ("sample_rate_hz", "quantum_frames"):
+            value = parameters.get(key)
+            if (
+                not isinstance(value, int)
+                or isinstance(value, bool)
+                or value <= 0
+            ):
+                errors.append(f"parameters.{key} must be a positive integer")
+
     controls = state.get("controls")
     if not isinstance(controls, dict):
         errors.append("controls must be a mapping")
@@ -280,28 +321,31 @@ def validate_state(state):
                 or not midi_bridge["input_port_name_contains"].strip()
             ):
                 errors.append("controls.midi_bridge.input_port_name_contains must be non-empty")
-            mod_host = midi_bridge.get("mod_host")
-            if not isinstance(mod_host, dict):
-                errors.append("controls.midi_bridge.mod_host must be a mapping")
+            mod_ui = midi_bridge.get("mod_ui")
+            if not isinstance(mod_ui, dict):
+                errors.append("controls.midi_bridge.mod_ui must be a mapping")
             else:
-                if mod_host.get("host") != "127.0.0.1":
-                    errors.append("controls.midi_bridge.mod_host.host must be 127.0.0.1")
-                port = mod_host.get("port")
+                if mod_ui.get("host") != "127.0.0.1":
+                    errors.append("controls.midi_bridge.mod_ui.host must be 127.0.0.1")
+                port = mod_ui.get("port")
                 if (
                     not isinstance(port, int)
                     or isinstance(port, bool)
                     or not 1 <= port <= 65535
                 ):
-                    errors.append("controls.midi_bridge.mod_host.port must be a valid TCP port")
+                    errors.append("controls.midi_bridge.mod_ui.port must be a valid TCP port")
                 elif isinstance(deployment := state.get("deployment"), dict):
-                    host_deployment = deployment.get("mod_host")
+                    ui_deployment = deployment.get("mod_ui")
                     if (
-                        isinstance(host_deployment, dict)
-                        and host_deployment.get("socket_port") != port
+                        isinstance(ui_deployment, dict)
+                        and ui_deployment.get("websocket_port") != port
                     ):
                         errors.append(
-                            "controls.midi_bridge.mod_host.port must match deployment.mod_host.socket_port"
+                            "controls.midi_bridge.mod_ui.port must match deployment.mod_ui.websocket_port"
                         )
+                websocket_path = mod_ui.get("websocket_path")
+                if websocket_path != "/websocket":
+                    errors.append("controls.midi_bridge.mod_ui.websocket_path must be /websocket")
 
     connections = state.get("connections", [])
     if not isinstance(connections, list):
@@ -479,7 +523,6 @@ def validate_state(state):
                 ("service_source", "config/systemd/user/rigforge-mod-host.service.in"),
                 ("service_destination", ".config/systemd/user/rigforge-mod-host.service"),
                 ("user_service", "rigforge-mod-host.service"),
-                ("configure_script", "scripts/configure_mod_host.py"),
                 ("readiness_script", "scripts/wait_mod_host_ports.py"),
                 ("pw_jack_path", "/usr/bin/pw-jack"),
                 ("python_path", "/usr/bin/python3"),
@@ -493,6 +536,15 @@ def validate_state(state):
                 or not 1 <= socket_port <= 65535
             ):
                 errors.append("deployment.mod_host.socket_port must be a valid TCP port")
+            feedback_port = mod_host.get("feedback_port")
+            if (
+                not isinstance(feedback_port, int)
+                or isinstance(feedback_port, bool)
+                or not 1 <= feedback_port <= 65535
+            ):
+                errors.append("deployment.mod_host.feedback_port must be a valid TCP port")
+            elif feedback_port == socket_port:
+                errors.append("deployment.mod_host.feedback_port must differ from socket_port")
             port_wait_timeout = mod_host.get("port_wait_timeout_seconds")
             if (
                 not isinstance(port_wait_timeout, int)
@@ -518,6 +570,55 @@ def validate_state(state):
                 errors.append(
                     "deployment.mod_ui.artifact_directory must be artifacts/mod-ui/arm64/current"
                 )
+            for key, expected in (
+                ("launcher", "artifacts/mod-ui/arm64/current/run-mod-ui"),
+                ("runner_script", "scripts/run_mod_ui_service.py"),
+                ("service_source", "config/systemd/user/rigforge-mod-ui.service.in"),
+                ("service_destination", ".config/systemd/user/rigforge-mod-ui.service"),
+                ("user_service", "rigforge-mod-ui.service"),
+                ("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"),
+                ("last_state_file", ".local/share/rigforge/mod-ui/last-rigforge.json"),
+                ("hardware_input_port", "rigforge.mod-host-input.capture:capture_AUX0"),
+                ("hardware_output_port", "rigforge.mod-host-output.playback:playback_AUX0"),
+            ):
+                if mod_ui.get(key) != expected:
+                    errors.append(f"deployment.mod_ui.{key} must be {expected}")
+            ui_port = mod_ui.get("websocket_port")
+            if (
+                not isinstance(ui_port, int)
+                or isinstance(ui_port, bool)
+                or not 1 <= ui_port <= 65535
+            ):
+                errors.append("deployment.mod_ui.websocket_port must be a valid TCP port")
+            elif isinstance(mod_host, dict) and (
+                ui_port == mod_host.get("socket_port")
+                or ui_port == mod_host.get("feedback_port")
+            ):
+                errors.append("deployment.mod_ui.websocket_port must differ from mod-host TCP ports")
+
+        mod_host_ports = deployment.get("mod_host_ports")
+        if not isinstance(mod_host_ports, dict):
+            errors.append("deployment.mod_host_ports must be a mapping")
+        else:
+            for key, expected in (
+                ("binary_path", "/usr/bin/pw-loopback"),
+                ("runner_script", "scripts/run_mod_host_ports.py"),
+                ("service_source", "config/systemd/user/rigforge-mod-host-ports.service.in"),
+                ("service_destination", ".config/systemd/user/rigforge-mod-host-ports.service"),
+                ("user_service", "rigforge-mod-host-ports.service"),
+                ("python_path", "/usr/bin/python3"),
+                ("channel_map", "AUX0"),
+                ("input_sink_name", "rigforge.mod-host-input"),
+                ("input_source_name", "rigforge.mod-host-input.capture"),
+                ("output_sink_name", "rigforge.mod-host-output.playback"),
+                ("output_source_name", "rigforge.mod-host-output"),
+            ):
+                if mod_host_ports.get(key) != expected:
+                    errors.append(f"deployment.mod_host_ports.{key} must be {expected}")
 
         reconcile = deployment.get("reconcile")
         if not isinstance(reconcile, dict):

+ 11 - 3
scripts/wait_mod_host_ports.py

@@ -14,8 +14,16 @@ def required_ports(state):
     chain = routing["mod_host_chains"]["guitar"]
     mix = routing["mix"]
     return (
-        {chain["source_port"]},
-        {chain["mix_input"], mix["output_port"]},
+        {
+            chain["source_port"],
+            chain["pipewire_output_port"],
+        },
+        {
+            chain["pipewire_input_port"],
+            chain["mod_ui_output_port"],
+            chain["mix_input"],
+            mix["output_port"],
+        },
     )
 
 
@@ -72,7 +80,7 @@ def wait_for_required_ports(
 def main(argv=None):
     root = Path(__file__).resolve().parents[1]
     parser = argparse.ArgumentParser(
-        description="Wait until PipeWire exposes the hardware and mixer ports mod-host needs."
+        description="Wait until PipeWire exposes the mod-host boundaries and mixer ports."
     )
     parser.add_argument("--state", type=Path, default=root / "config" / "desired-state.yaml")
     parser.add_argument("--timeout", type=float)

+ 127 - 7
tests/test_deploy.py

@@ -105,6 +105,16 @@ class DeploymentTests(unittest.TestCase):
     def mod_host_config(self):
         return deploy.load_deployment()["mod_host"]
 
+    def install_mod_host_ports_prerequisite(self):
+        config = deploy.load_deployment()["mod_host_ports"]
+        deploy.deploy_mod_host_ports("install", config, deploy.read_registry())
+        self.commands.clear()
+
+    def install_mod_ui_registry_prerequisite(self):
+        registry = deploy.read_registry()
+        registry["mod_ui"] = {"test_dependency": True}
+        deploy.write_registry(registry)
+
     def sooperlooper_config(self):
         return deploy.load_deployment()["sooperlooper"]
 
@@ -216,20 +226,21 @@ class DeploymentTests(unittest.TestCase):
 
     def test_mod_host_install_renders_and_activates_user_service(self):
         config = self.mod_host_config()
+        self.install_mod_host_ports_prerequisite()
         with patch.object(deploy, "mod_host_port_is_open", return_value=False):
             deploy.deploy_mod_host("install", config, deploy.read_registry())
 
         destination = self.home / config["service_destination"]
         content = destination.read_text(encoding="utf-8")
         self.assertIn("WantedBy=default.target", content)
-        self.assertIn("After=pipewire.service wireplumber.service filter-chain.service", content)
-        self.assertIn("PartOf=pipewire.service wireplumber.service filter-chain.service", content)
+        self.assertIn("After=pipewire.service wireplumber.service filter-chain.service rigforge-mod-host-ports.service", content)
+        self.assertIn("PartOf=pipewire.service wireplumber.service filter-chain.service rigforge-mod-host-ports.service", content)
         self.assertIn("ExecStartPre=", content)
         self.assertIn("wait_mod_host_ports.py", content)
         self.assertIn("--timeout 45", content)
         self.assertIn("TimeoutStartSec=90", content)
-        self.assertIn("-n -p 5555", content)
-        self.assertIn("configure_mod_host.py", content)
+        self.assertIn("-n -p 5555 -f 5556", content)
+        self.assertNotIn("configure_mod_host.py", content)
         self.assertEqual(
             self.commands,
             [
@@ -246,6 +257,7 @@ class DeploymentTests(unittest.TestCase):
 
     def test_mod_host_install_is_idempotent_without_restarting_active_audio(self):
         config = self.mod_host_config()
+        self.install_mod_host_ports_prerequisite()
         with patch.object(deploy, "mod_host_port_is_open", return_value=False):
             deploy.deploy_mod_host("install", config, deploy.read_registry())
         self.commands.clear()
@@ -262,6 +274,7 @@ class DeploymentTests(unittest.TestCase):
 
     def test_mod_host_install_restarts_when_runtime_configuration_changes(self):
         config = self.mod_host_config()
+        self.install_mod_host_ports_prerequisite()
         with (
             patch.object(deploy, "mod_host_port_is_open", return_value=False),
             patch.object(deploy, "mod_host_runtime_digest", side_effect=["a" * 64, "b" * 64]),
@@ -303,8 +316,9 @@ class DeploymentTests(unittest.TestCase):
 
     def test_mod_host_uninstall_restores_previous_unit(self):
         config = self.mod_host_config()
+        self.install_mod_host_ports_prerequisite()
         destination = self.home / config["service_destination"]
-        destination.parent.mkdir(parents=True)
+        destination.parent.mkdir(parents=True, exist_ok=True)
         destination.write_text("prior unit", encoding="utf-8")
         with patch.object(deploy, "mod_host_port_is_open", return_value=False):
             deploy.deploy_mod_host("install", config, deploy.read_registry())
@@ -393,6 +407,7 @@ class DeploymentTests(unittest.TestCase):
         )
 
     def test_midi_bridge_install_and_uninstall_manage_only_user_service(self):
+        self.install_mod_ui_registry_prerequisite()
         config = self.midi_bridge_config()
         destination = self.home / config["service_destination"]
         destination.parent.mkdir(parents=True)
@@ -403,7 +418,7 @@ class DeploymentTests(unittest.TestCase):
         installed = destination.read_text(encoding="utf-8")
         self.assertIn("Description=Rigforge MIDI action bridge", installed)
         self.assertIn("midi_action_bridge.py\" --state", installed)
-        self.assertIn("After=rigforge-mod-host.service", installed)
+        self.assertIn("After=rigforge-mod-ui.service", installed)
         self.assertIn("Restart=on-failure", installed)
         self.assertEqual(
             self.commands,
@@ -429,6 +444,7 @@ class DeploymentTests(unittest.TestCase):
         )
 
     def test_midi_bridge_install_is_idempotent_and_reload_restarts_only_bridge(self):
+        self.install_mod_ui_registry_prerequisite()
         config = self.midi_bridge_config()
         deploy.deploy_midi_bridge("install", config, deploy.read_registry())
         self.commands.clear()
@@ -453,6 +469,7 @@ class DeploymentTests(unittest.TestCase):
         )
 
     def test_midi_bridge_uninstall_refuses_local_unit_edits(self):
+        self.install_mod_ui_registry_prerequisite()
         config = self.midi_bridge_config()
         deploy.deploy_midi_bridge("install", config, deploy.read_registry())
         destination = self.home / config["service_destination"]
@@ -525,6 +542,7 @@ class DeploymentTests(unittest.TestCase):
     def test_mod_host_install_and_uninstall_do_not_manage_reconcile_timer(self):
         reconcile_config = self.reconcile_config()
         mod_host_config = self.mod_host_config()
+        self.install_mod_host_ports_prerequisite()
         deploy.deploy_reconcile("install", reconcile_config, deploy.read_registry())
         reconcile_paths = {
             reconcile_config["service_destination"],
@@ -544,8 +562,9 @@ class DeploymentTests(unittest.TestCase):
 
     def test_mod_host_pending_uninstall_recovers_after_prior_unit_is_restored(self):
         config = self.mod_host_config()
+        self.install_mod_host_ports_prerequisite()
         destination = self.home / config["service_destination"]
-        destination.parent.mkdir(parents=True)
+        destination.parent.mkdir(parents=True, exist_ok=True)
         destination.write_text("prior unit", encoding="utf-8")
         with patch.object(deploy, "mod_host_port_is_open", return_value=False):
             deploy.deploy_mod_host("install", config, deploy.read_registry())
@@ -565,6 +584,7 @@ class DeploymentTests(unittest.TestCase):
 
     def test_mod_host_uninstall_refuses_local_unit_edits(self):
         config = self.mod_host_config()
+        self.install_mod_host_ports_prerequisite()
         with patch.object(deploy, "mod_host_port_is_open", return_value=False):
             deploy.deploy_mod_host("install", config, deploy.read_registry())
         destination = self.home / config["service_destination"]
@@ -575,7 +595,106 @@ class DeploymentTests(unittest.TestCase):
         self.assertEqual(destination.read_text(encoding="utf-8"), "local edit")
         self.assertEqual(self.commands, [])
 
+    def test_mod_host_ports_service_is_managed_scoped_and_ordered(self):
+        config = deploy.load_deployment()["mod_host_ports"]
+        destination = self.home / config["service_destination"]
+        deploy.deploy_mod_host_ports("install", config, deploy.read_registry())
+        content = destination.read_text(encoding="utf-8")
+        self.assertIn("Description=Rigforge PipeWire audio boundary ports for mod-host", content)
+        self.assertIn("run_mod_host_ports.py", content)
+        self.assertIn("--pw-loopback \"/usr/bin/pw-loopback\"", content)
+        self.assertIn("Wants=pipewire.service wireplumber.service", content)
+        self.assertEqual(
+            self.commands,
+            [
+                ["systemctl", "--user", "daemon-reload"],
+                ["systemctl", "--user", "enable", "rigforge-mod-host-ports.service"],
+                ["systemctl", "--user", "restart", "rigforge-mod-host-ports.service"],
+                ["systemctl", "--user", "is-active", "--quiet", "rigforge-mod-host-ports.service"],
+            ],
+        )
+        self.assertIn("mod_host_ports", deploy.read_registry())
+
+        self.commands.clear()
+        deploy.deploy_mod_host_ports("uninstall", config, deploy.read_registry())
+        self.assertNotIn("mod_host_ports", deploy.read_registry())
+        self.assertEqual(
+            self.commands,
+            [
+                ["systemctl", "--user", "disable", "--now", "rigforge-mod-host-ports.service"],
+                ["systemctl", "--user", "daemon-reload"],
+            ],
+        )
+
+    def test_mod_ui_service_uses_reference_board_and_port_bridge(self):
+        registry = {
+            "mod_host_ports": {},
+            "mod_host": {},
+        }
+        config = deploy.load_deployment()["mod_ui"]
+        destination = self.home / config["service_destination"]
+        deploy.deploy_mod_ui("install", config, registry)
+
+        content = destination.read_text(encoding="utf-8")
+        self.assertIn("run_mod_ui_service.py", content)
+        self.assertIn("MOD_DEFAULT_PEDALBOARD=", content)
+        self.assertIn("MOD_RIGFORGE_CAPTURE_PORT=", content)
+        self.assertIn("rigforge.mod-host-input.capture:capture_AUX0", content)
+        self.assertIn("rigforge.mod-host-output.playback:playback_AUX0", content)
+        self.assertIn("Requires=rigforge-mod-host.service rigforge-mod-host-ports.service", content)
+        self.assertIn("pw-jack", content)
+
+    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_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_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):
             with self.assertRaisesRegex(RuntimeError, "already in use"):
                 deploy.deploy_mod_host("install", self.mod_host_config(), deploy.read_registry())
@@ -584,6 +703,7 @@ class DeploymentTests(unittest.TestCase):
 
     def test_mod_host_reload_restarts_and_checks_the_user_service(self):
         config = self.mod_host_config()
+        self.install_mod_host_ports_prerequisite()
         with patch.object(deploy, "mod_host_port_is_open", return_value=False):
             deploy.deploy_mod_host("install", config, deploy.read_registry())
         self.commands.clear()

+ 26 - 10
tests/test_desired_state.py

@@ -48,17 +48,30 @@ class DesiredStateValidationTests(unittest.TestCase):
         state["routing"]["mix"]["output_port"] = ""
         self.assertIn("routing.mix.output_port must be a non-empty string", validate_state(state))
 
-    def test_guitar_mod_host_chain_declares_nam_then_cabinet_without_dry_bypass(self):
+    def test_guitar_mod_host_chain_declares_mod_ui_internal_cable_and_rigforge_boundaries(self):
         chain = self.state["routing"]["mod_host_chains"]["guitar"]
         processors = chain["processors"]
         self.assertEqual([item["id"] for item in processors], ["amp-head", "cabinet-ir"])
         self.assertEqual([item["instance"] for item in processors], [0, 1])
+        edges = {
+            (link["from"], link["to"])
+            for link in self.state["routing"]["managed_links"]
+        }
+        self.assertIn(
+            ("alsa_input.hw_U192k_0:capture_AUX0", "rigforge.mod-host-input:playback_AUX0"),
+            edges,
+        )
+        self.assertIn(
+            ("rigforge.mod-host-output:capture_AUX0", chain["mix_input"]),
+            edges,
+        )
+        self.assertNotIn(
+            (processors[0]["output_port"], processors[1]["input_port"]),
+            edges,
+        )
         self.assertNotIn(
             (chain["bypass_link"]["from"], chain["bypass_link"]["to"]),
-            {
-                (link["from"], link["to"])
-                for link in self.state["routing"]["managed_links"]
-            },
+            edges,
         )
         self.assertIn(
             {
@@ -89,7 +102,7 @@ class DesiredStateValidationTests(unittest.TestCase):
 
         state = copy.deepcopy(self.state)
         state["routing"]["managed_links"].pop(0)
-        self.assertTrue(any("mod-host guitar chain link must be declared" in error for error in validate_state(state)))
+        self.assertTrue(any("mod-host guitar boundary link must be declared" in error for error in validate_state(state)))
 
         state = copy.deepcopy(self.state)
         state["routing"]["managed_unlinks"] = []
@@ -115,16 +128,16 @@ class DesiredStateValidationTests(unittest.TestCase):
         self.assertTrue(any("available_models" in error for error in validate_state(state)))
 
         state = copy.deepcopy(self.state)
-        state["controls"]["midi_bridge"]["mod_host"]["host"] = "0.0.0.0"
+        state["controls"]["midi_bridge"]["mod_ui"]["host"] = "0.0.0.0"
         self.assertIn(
-            "controls.midi_bridge.mod_host.host must be 127.0.0.1",
+            "controls.midi_bridge.mod_ui.host must be 127.0.0.1",
             validate_state(state),
         )
 
         state = copy.deepcopy(self.state)
-        state["controls"]["midi_bridge"]["mod_host"]["port"] = 5556
+        state["controls"]["midi_bridge"]["mod_ui"]["port"] = 5556
         self.assertTrue(
-            any("must match deployment.mod_host.socket_port" in error for error in validate_state(state))
+            any("must match deployment.mod_ui.websocket_port" in error for error in validate_state(state))
         )
 
     def test_deployment_targets_are_declared_and_valid(self):
@@ -201,6 +214,9 @@ class DesiredStateValidationTests(unittest.TestCase):
         state = copy.deepcopy(self.state)
         state["deployment"]["mod_host"]["socket_port"] = 70000
         self.assertIn("deployment.mod_host.socket_port must be a valid TCP port", validate_state(state))
+        state = copy.deepcopy(self.state)
+        state["deployment"]["mod_host"]["feedback_port"] = 5555
+        self.assertIn("deployment.mod_host.feedback_port must differ from socket_port", validate_state(state))
 
         state = copy.deepcopy(self.state)
         state["deployment"]["mod_host"]["port_wait_timeout_seconds"] = 500

+ 17 - 14
tests/test_midi_action_bridge.py

@@ -48,16 +48,18 @@ class MidiActionBridgeTests(unittest.TestCase):
             )
         )
 
-    def test_note_on_sends_patch_set_for_declared_nam_instance(self):
+    def test_note_on_sends_model_patch_set_through_mod_ui(self):
         commands = []
 
-        def command(host, port, text):
-            commands.append((host, port, text))
-            return "resp 0"
-
         actions = binding_index(self.bindings)
         result = handle_midi_message(
-            [0x90, 7, 127], actions, self.state, ROOT, command=command
+            [0x90, 7, 127],
+            actions,
+            self.state,
+            ROOT,
+            command=lambda instance, uri, value: commands.append(
+                ("127.0.0.1", 8888, f"rigforge_patch_set {instance} {uri} p {value}")
+            ) or True,
         )
 
         model = ROOT / self.state["routing"]["mod_host_chains"]["guitar"]["processors"][0][
@@ -69,15 +71,16 @@ class MidiActionBridgeTests(unittest.TestCase):
             commands,
             [(
                 "127.0.0.1",
-                5555,
-                "patch_set 0 http://github.com/mikeoliphant/neural-amp-modeler-lv2#model "
+                8888,
+                "rigforge_patch_set /graph/rigforge_nam "
+                "http://github.com/mikeoliphant/neural-amp-modeler-lv2#model p "
                 + str(model),
             )],
         )
 
     def test_note_off_zero_velocity_and_unbound_channel_do_nothing(self):
         commands = []
-        command = lambda *_args: commands.append(_args) or "resp 0"
+        command = lambda *_args: commands.append(_args) or True
         actions = binding_index(self.bindings)
 
         self.assertIsNone(handle_midi_message([0x80, 7, 0], actions, self.state, ROOT, command))
@@ -101,9 +104,9 @@ class MidiActionBridgeTests(unittest.TestCase):
             clean_model.write_text("test fixture", encoding="utf-8")
             commands = []
 
-            def command(host, port, text):
-                commands.append((host, port, text))
-                return "resp 0"
+            def command(instance, uri, value):
+                commands.append((instance, uri, value))
+                return True
 
             selected_id, selected_path = select_nam_model(
                 action, state, root, command=command
@@ -113,7 +116,7 @@ class MidiActionBridgeTests(unittest.TestCase):
         self.assertEqual(selected_path, clean_model)
         self.assertIn("models/clean.nam", commands[0][2])
 
-    def test_missing_requested_and_fallback_model_does_not_call_mod_host(self):
+    def test_missing_requested_and_fallback_model_sends_no_ui_command(self):
         state = copy.deepcopy(self.state)
         models = state["routing"]["mod_host_chains"]["guitar"]["processors"][0][
             "available_models"
@@ -129,7 +132,7 @@ class MidiActionBridgeTests(unittest.TestCase):
                     action,
                     state,
                     Path(directory),
-                    command=lambda *args: commands.append(args) or "resp 0",
+                    command=lambda *args: commands.append(args) or True,
                 )
         self.assertEqual(commands, [])
 

+ 65 - 0
tests/test_mod_host_ports.py

@@ -0,0 +1,65 @@
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+
+import yaml
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+
+from run_mod_host_ports import assert_boundary_ports_absent, loopback_command
+
+
+class ModHostPipeWirePortTests(unittest.TestCase):
+    @classmethod
+    def setUpClass(cls):
+        cls.state = yaml.safe_load(
+            (ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8")
+        )
+
+    def test_input_and_output_loopbacks_use_stable_mono_aux0_ports(self):
+        input_command = loopback_command(
+            "/usr/bin/pw-loopback",
+            "rigforge.mod-host-input",
+            "rigforge.mod-host-input",
+            "rigforge.mod-host-input.capture",
+            "AUX0",
+            2.666666,
+        )
+        output_command = loopback_command(
+            "/usr/bin/pw-loopback",
+            "rigforge.mod-host-output",
+            "rigforge.mod-host-output.playback",
+            "rigforge.mod-host-output",
+            "AUX0",
+            2.666666,
+        )
+
+        self.assertIn("media.class=Audio/Sink", input_command[10])
+        self.assertIn("rigforge.mod-host-input.capture", input_command[12])
+        self.assertIn("rigforge.mod-host-output.playback", output_command[10])
+        self.assertIn("rigforge.mod-host-output", output_command[12])
+        for command in (input_command, output_command):
+            self.assertIn("--channels", command)
+            self.assertIn("--channel-map", command)
+            self.assertIn("--latency", command)
+            self.assertEqual(command[8], "2.66667")
+            self.assertIn("[AUX0]", command)
+            self.assertIn("media.class=Audio/Sink", command[10])
+            self.assertIn("media.class=Audio/Source", command[12])
+
+    def test_runner_refuses_duplicate_boundary_names(self):
+        def runner(command, **_kwargs):
+            if command == ["pw-link", "-o"]:
+                return SimpleNamespace(stdout="rigforge.mod-host-output:capture_AUX0\n")
+            if command == ["pw-link", "-i"]:
+                return SimpleNamespace(stdout="")
+            self.fail(f"unexpected command: {command}")
+
+        with self.assertRaisesRegex(RuntimeError, "already present"):
+            assert_boundary_ports_absent(self.state, runner)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 68 - 0
tests/test_mod_ui_pedalboard.py

@@ -0,0 +1,68 @@
+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('lv2:name "Rigforge Mod-Host Input"', ttl)
+        self.assertIn('lv2:name "Rigforge Mod-Host Output"', 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)
+        self.assertEqual(files["addressings.json"], b"{}\n")
+
+    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()

+ 117 - 0
tests/test_mod_ui_websocket.py

@@ -0,0 +1,117 @@
+import base64
+import hashlib
+import socket
+import struct
+import sys
+import threading
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+
+from mod_ui_websocket import ModUiWebSocketClient
+
+
+def recv_exact(connection, count):
+    data = bytearray()
+    while len(data) < count:
+        chunk = connection.recv(count - len(data))
+        if not chunk:
+            raise RuntimeError("client disconnected")
+        data.extend(chunk)
+    return bytes(data)
+
+
+def receive_client_text(connection):
+    first, second = recv_exact(connection, 2)
+    opcode = first & 0x0F
+    size = second & 0x7F
+    if size == 126:
+        size = struct.unpack("!H", recv_exact(connection, 2))[0]
+    elif size == 127:
+        size = struct.unpack("!Q", recv_exact(connection, 8))[0]
+    mask = recv_exact(connection, 4) if second & 0x80 else b""
+    payload = recv_exact(connection, size)
+    if mask:
+        payload = bytes(value ^ mask[index % 4] for index, value in enumerate(payload))
+    return opcode, payload.decode("utf-8")
+
+
+def send_server_text(connection, text):
+    payload = text.encode("utf-8")
+    if len(payload) < 126:
+        header = bytes((0x81, len(payload)))
+    else:
+        header = bytes((0x81, 126)) + struct.pack("!H", len(payload))
+    connection.sendall(header + payload)
+
+
+class ModUiWebSocketTests(unittest.TestCase):
+    def test_patch_request_uses_acknowledged_websocket_command(self):
+        listener = socket.socket()
+        listener.bind(("127.0.0.1", 0))
+        listener.listen(1)
+        port = listener.getsockname()[1]
+        received = []
+        errors = []
+
+        def serve():
+            try:
+                connection, _address = listener.accept()
+                with connection:
+                    request = bytearray()
+                    while not request.endswith(b"\r\n\r\n"):
+                        request.extend(connection.recv(1))
+                    headers = request.decode("latin-1").split("\r\n")
+                    key = next(
+                        line.split(":", 1)[1].strip()
+                        for line in headers
+                        if line.casefold().startswith("sec-websocket-key:")
+                    )
+                    accept = base64.b64encode(
+                        hashlib.sha1(
+                            (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode("ascii")
+                        ).digest()
+                    ).decode("ascii")
+                    connection.sendall(
+                        (
+                            "HTTP/1.1 101 Switching Protocols\r\n"
+                            "Upgrade: websocket\r\n"
+                            "Connection: Upgrade\r\n"
+                            f"Sec-WebSocket-Accept: {accept}\r\n\r\n"
+                        ).encode("ascii")
+                    )
+                    opcode, message = receive_client_text(connection)
+                    received.append((opcode, message))
+                    request_id = message.split()[1]
+                    send_server_text(connection, f"rigforge_patch_set_ack {request_id} 1")
+            except Exception as error:
+                errors.append(error)
+            finally:
+                listener.close()
+
+        thread = threading.Thread(target=serve)
+        thread.start()
+        with ModUiWebSocketClient("127.0.0.1", port, timeout=2) as client:
+            self.assertTrue(
+                client.set_patch(
+                    "/graph/rigforge_nam",
+                    "http://github.com/mikeoliphant/neural-amp-modeler-lv2#model",
+                    "/home/jojo/models/Vox Crunch.nam",
+                )
+            )
+        thread.join(timeout=2)
+
+        self.assertFalse(thread.is_alive())
+        self.assertEqual(errors, [])
+        self.assertEqual(received[0][0], 0x1)
+        self.assertIn(
+            " /graph/rigforge_nam http://github.com/mikeoliphant/neural-amp-modeler-lv2#model p "
+            "/home/jojo/models/Vox Crunch.nam",
+            received[0][1],
+        )
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 17 - 18
tests/test_pipewire_observer.py

@@ -23,10 +23,10 @@ CAPTURE_0 = "alsa_input.hw_U192k_0:capture_AUX0"
 CAPTURE_1 = "alsa_input.hw_U192k_0:capture_AUX1"
 CAPTURE_2 = "alsa_input.hw_U192k_0:capture_AUX2"
 CAPTURE_3 = "alsa_input.hw_U192k_0:capture_AUX3"
-AMP_INPUT = "effect_0:input"
+AMP_INPUT = "rigforge.mod-host-input:playback_AUX0"
 AMP_OUTPUT = "effect_0:output"
 CAB_INPUT = "effect_1:in"
-CAB_OUTPUT = "effect_1:out"
+CAB_OUTPUT = "rigforge.mod-host-output:capture_AUX0"
 MIX_INPUT_0 = "rigforge.direct-mix.input:playback_AUX0"
 MIX_INPUT_2 = "rigforge.direct-mix.input:playback_AUX2"
 MIX_INPUT_4 = "rigforge.direct-mix.input:playback_AUX4"
@@ -54,7 +54,6 @@ class PipeWireObserverTests(unittest.TestCase):
         cls.state = copy.deepcopy(cls.desired_state)
         existing_test_edges = {
             (CAPTURE_0, AMP_INPUT),
-            (AMP_OUTPUT, CAB_INPUT),
             (CAB_OUTPUT, MIX_INPUT_0),
             (CAPTURE_2, MIX_INPUT_2),
             (MIX_OUTPUT, PLAYBACK_0),
@@ -131,7 +130,7 @@ class PipeWireObserverTests(unittest.TestCase):
         state["routing"]["managed_links"] = [
             {"from": "direct_mix", "to": PLAYBACK_0, "status": "planned"}
         ]
-        self.assertTrue(any("approved observed Rigforge, UMC, or MIDI port" in error for error in validate_managed_links(state)))
+        self.assertTrue(any("approved Rigforge boundary, UMC, or MIDI port" in error for error in validate_managed_links(state)))
 
     def test_rejects_unapproved_midi_endpoint(self):
         state = copy.deepcopy(self.state)
@@ -142,10 +141,19 @@ class PipeWireObserverTests(unittest.TestCase):
         ]
         errors = validate_managed_links(state)
         self.assertEqual(
-            sum("approved observed Rigforge, UMC, or MIDI port" in error for error in errors),
+            sum("approved Rigforge boundary, UMC, or MIDI port" in error for error in errors),
             2,
         )
 
+    def test_rejects_mod_host_plugin_ports_owned_by_mod_ui(self):
+        state = copy.deepcopy(self.state)
+        state["routing"]["managed_ports"].append("effect_0:input")
+        state["routing"]["managed_links"].append(
+            {"from": CAPTURE_0, "to": "effect_0:input", "status": "planned"}
+        )
+        errors = validate_managed_links(state)
+        self.assertTrue(any("approved Rigforge boundary" in error for error in errors))
+
     def test_desired_graph_declares_the_tested_pipewire_midi_route(self):
         links = {
             (link["from"], link["to"])
@@ -397,7 +405,6 @@ class PipeWireObserverTests(unittest.TestCase):
                 edge = (command[1], command[2])
                 if edge in {
                     (CAPTURE_0, AMP_INPUT),
-                    (AMP_OUTPUT, CAB_INPUT),
                     (CAB_OUTPUT, MIX_INPUT_0),
                 }:
                     links.add(edge)
@@ -413,7 +420,6 @@ class PipeWireObserverTests(unittest.TestCase):
             result["actions"],
             [
                 {"kind": "link", "from": CAPTURE_0, "to": AMP_INPUT, "result": "requested"},
-                {"kind": "link", "from": AMP_OUTPUT, "to": CAB_INPUT, "result": "requested"},
                 {"kind": "link", "from": CAB_OUTPUT, "to": MIX_INPUT_0, "result": "requested"},
                 {"kind": "unlink", "from": CAPTURE_0, "to": MIX_INPUT_0, "result": "requested"},
             ],
@@ -457,9 +463,6 @@ class PipeWireObserverTests(unittest.TestCase):
                 return SimpleNamespace(stdout=(
                     f"{CAB_INPUT}\n{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n"
                 ))
-            if command == ["pw-link", AMP_OUTPUT, CAB_INPUT]:
-                links.add((AMP_OUTPUT, CAB_INPUT))
-                return SimpleNamespace(stdout="")
             if command == ["pw-link", CAB_OUTPUT, MIX_INPUT_0]:
                 links.add((CAB_OUTPUT, MIX_INPUT_0))
                 return SimpleNamespace(stdout="")
@@ -478,11 +481,10 @@ class PipeWireObserverTests(unittest.TestCase):
                     "result": "not-linked",
                     "reason": "required PipeWire port(s) are not present in the current graph",
                     "hint": (
-                        "mod-host must be running and load the NAM/IR plugins to expose "
-                        "effect_0/effect_1 ports"
+                        "Rigforge mod-host boundary ports must be running; mod-ui provides the "
+                        "internal NAM/IR connections"
                     ),
                 },
-                {"kind": "link", "from": AMP_OUTPUT, "to": CAB_INPUT, "result": "requested"},
                 {"kind": "link", "from": CAB_OUTPUT, "to": MIX_INPUT_0, "result": "requested"},
                 {
                     "kind": "unlink-deferred",
@@ -515,7 +517,6 @@ class PipeWireObserverTests(unittest.TestCase):
                     f"{AMP_INPUT}\n{CAB_INPUT}\n{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n"
                 ))
             if tuple(command) in {
-                ("pw-link", AMP_OUTPUT, CAB_INPUT),
                 ("pw-link", CAB_OUTPUT, MIX_INPUT_0),
                 ("pw-link", CAPTURE_0, AMP_INPUT),
                 ("pw-link", CAPTURE_2, MIX_INPUT_2),
@@ -532,9 +533,8 @@ class PipeWireObserverTests(unittest.TestCase):
             [
                 {"kind": "link", "from": CAPTURE_0, "to": AMP_INPUT, "result": "requested"},
                 {"kind": "link", "from": CAPTURE_2, "to": MIX_INPUT_2, "result": "requested"},
-                {"kind": "link", "from": AMP_OUTPUT, "to": CAB_INPUT, "result": "requested"},
-                {"kind": "link", "from": CAB_OUTPUT, "to": MIX_INPUT_0, "result": "requested"},
                 {"kind": "link", "from": MIX_OUTPUT, "to": PLAYBACK_0, "result": "requested"},
+                {"kind": "link", "from": CAB_OUTPUT, "to": MIX_INPUT_0, "result": "requested"},
             ],
         )
         self.assertEqual(result["differences"], [])
@@ -543,9 +543,8 @@ class PipeWireObserverTests(unittest.TestCase):
             [
                 ["pw-link", CAPTURE_0, AMP_INPUT],
                 ["pw-link", CAPTURE_2, MIX_INPUT_2],
-                ["pw-link", AMP_OUTPUT, CAB_INPUT],
-                ["pw-link", CAB_OUTPUT, MIX_INPUT_0],
                 ["pw-link", MIX_OUTPUT, PLAYBACK_0],
+                ["pw-link", CAB_OUTPUT, MIX_INPUT_0],
             ],
         )