Преглед изворни кода

add deployment of mod-host

Johan Le Baut пре 2 недеља
родитељ
комит
78a8b8741e

+ 8 - 6
AGENTS.md

@@ -4,16 +4,17 @@
 
 Rigforge is a Raspberry Pi audio pedalboard project. Treat this repository as a desired-state model plus a small set of tested candidates and read-only tools, not as a finished deployable system. Hardware routing and operational settings remain partly provisional. The root `README.md` is the authoritative record of current target observations, validation status, test procedure, and rollback details; check it before changing target-facing configuration.
 
-The current target is Debian GNU/Linux 13 on AArch64 with a Behringer UMC404HD 192k, PipeWire, and WirePlumber. Guitar on physical input 1 and microphone on input 3 have been heard through the candidate mixer; the remaining inputs, sustained stability, headroom, looper integration, MIDI bindings, and unattended startup are not verified. Do not turn reported or candidate settings into claims of verified behavior.
+The current target is Debian GNU/Linux 13 on AArch64 with a Behringer UMC404HD 192k, PipeWire, and WirePlumber. Guitar on physical input 1 and microphone on input 3 have been heard through the candidate mixer. The target owner also reports an initial guitar test through the Vox AC15 NAM model and Vox AC30 cabinet IR with pleasing crunch and no crackles. Sustained stability, headroom, remaining inputs, looper integration, MIDI bindings, and automatic service startup are not verified. Do not turn reported or candidate settings into claims of verified behavior.
 
 ## Layout and architecture
 
-- `config/desired-state.yaml` is the central YAML description of the intended components, four mono sources, looper channel assignments, mix, 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, planned/forbidden connections, and the exact PipeWire links currently 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. Observation is the default; explicit one-shot reconciliation may create only declared missing links.
-- `scripts/deploy.sh` dispatches user-level install/uninstall/reload actions for YAML-declared PipeWire and NAM LV2 targets through `scripts/deploy.py`.
-- `tests/` contains Python `unittest` tests for state validation, observation/reconciliation, mixer configuration, and simulated deployment operations. These validate repository-level invariants, not live audio behavior.
+- `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/deploy.sh` dispatches scoped user-level install/uninstall/reload actions for YAML-declared PipeWire, LV2 bundles, and the mod-host user service through `scripts/deploy.py`. `mod-host` is an explicit target, 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/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.
@@ -44,7 +45,7 @@ The observer invokes `pw-link -l` itself. It never creates or removes links. A c
 - 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.
+- 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.
 - 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` may create only declared missing links after confirming both ports exist; it must not remove links, alter unrelated connections, or restart services. Retain tests for simulated repair and post-check behavior.
@@ -57,7 +58,8 @@ The observer invokes `pw-link -l` itself. It never creates or removes links. A c
 - 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, auto-pull, or production service-installation workflow is configured. Keep unverified changes away from live audio use and follow the README's rollback procedure for target experiments.
+- Deployment is manual; no CI/CD or auto-pull is configured. The mod-host user service and deployment path are implemented in the repository but target activation, reboot startup, and recovery after PipeWire restart remain unverified. Keep unverified changes away from live audio use and follow the README's rollback procedure for target experiments.
+- `install mod-host` activates audio routing and is intentionally excluded from `install all`. 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.
 
 # Environnement local — rigforge
 

+ 25 - 7
README.md

@@ -109,16 +109,34 @@ After a manual `git pull --ff-only`, run the deploy helper from any directory:
 ~/rigforge/scripts/deploy.sh install namlv2
 ~/rigforge/scripts/deploy.sh install lsp
 ~/rigforge/scripts/deploy.sh install dragonfly-reverb
+~/rigforge/scripts/deploy.sh install mod-host
 ~/rigforge/scripts/deploy.sh install all
 ```
 
-The helper accepts `install|uninstall|reload` and `all|namlv2|lsp|dragonfly-reverb|pipewire`. It reads versions, paths, URLs, and quantum 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` and `all|namlv2|lsp|dragonfly-reverb|pipewire|mod-host`. It reads versions, paths, URLs, and quantum 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.
 
 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. The deploy helper deliberately does not reconcile links automatically. After a restart, first run `python3 scripts/observe_pipewire.py`; if declared links are missing, use `python3 scripts/observe_pipewire.py --reconcile-once` only during an appropriate safe test window, then observe again. 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.
 
-For NAM LV2, install downloads the declared Raspberry Pi 5 archive with `curl`, checks the archive structure, extracts the `neural_amp_modeler.lv2` bundle under `~/.lv2/`, and records the archive SHA-256 and managed bundle fingerprint. This is a locally computed identity hash, not an independent publisher checksum. An existing same-name bundle is preserved for uninstall; locally modified managed bundles are not overwritten or removed. `reload namlv2` intentionally does nothing because no LV2 host is declared; restart the eventual host after installing or removing the plugin. On the target, tag `v0.2.3` was installed at `~/.lv2/neural_amp_modeler.lv2`; the observed contents were `manifest.ttl`, `modgui/`, `modgui.ttl`, `neural_amp_modeler.so`, and `neural_amp_modeler.ttl`. `reload namlv2` printed the expected no-op message. The downloaded archive SHA-256 was `80d1a711d573afb7323cbf2ea1a79e39386e58ba449d076c5d89e10b50de3212`; this is an identity hash only, not a publisher checksum. Host discovery, runtime dependencies, compatibility, and plugin operation remain unverified. The release archive is fetched at install time and is not committed to this repository.
+For NAM LV2, install downloads the declared Raspberry Pi 5 archive with `curl`, checks the archive structure, extracts the `neural_amp_modeler.lv2` bundle under `~/.lv2/`, and records the archive SHA-256 and managed bundle fingerprint. This is a locally computed identity hash, not an independent publisher checksum. An existing same-name bundle is preserved for uninstall; locally modified managed bundles are not overwritten or removed. `reload namlv2` does nothing because plugin installation itself requires no host reload; restart `mod-host` after installing or removing the plugin. On the target, tag `v0.2.3` was installed at `~/.lv2/neural_amp_modeler.lv2`; the observed contents were `manifest.ttl`, `modgui/`, `modgui.ttl`, `neural_amp_modeler.so`, and `neural_amp_modeler.ttl`. The downloaded archive SHA-256 was `80d1a711d573afb7323cbf2ea1a79e39386e58ba449d076c5d89e10b50de3212`; this is an identity hash only, not an independent publisher checksum. The selected NAM model was loaded during the initial manual mod-host chain test; sustained performance and automated startup remain unverified. The release archive is fetched at install time and is not committed to this repository.
 
-For LSP and Dragonfly Reverb, the YAML declares tags and release URLs, and the installer places only LV2 bundles in `~/.lv2/`. LSP installs `lsp-plugins.lv2`; Dragonfly installs its Early Reflections, Hall, Plate, and Room Reverb bundles. LSP extraction requires `7z`, `7zz`, or `7za` on `PATH`, with support for the compression methods used in the release; install or update that system package separately if needed. A listing or extraction error aborts the install before any bundle is changed. The installers hash archives for identity tracking, check archive paths and expected manifests, preserve existing same-name bundles for uninstall, and refuse to remove locally modified managed bundles. `reload lsp` and `reload dragonfly-reverb` do not restart an LV2 host; restart the host after installation or removal. The release bundle layouts were checked, but the plugins and runtime dependencies have not been tested on the target.
+For LSP and Dragonfly Reverb, the YAML declares tags and release URLs, and the installer places only LV2 bundles in `~/.lv2/`. LSP installs `lsp-plugins.lv2`; Dragonfly installs its Early Reflections, Hall, Plate, and Room Reverb bundles. LSP extraction requires `7z`, `7zz`, or `7za` on `PATH`, with support for the compression methods used in the release; install or update that system package separately if needed. A listing or extraction error aborts the install before any bundle is changed. The installers hash archives for identity tracking, check archive paths and expected manifests, preserve existing same-name bundles for uninstall, and refuse to remove locally modified managed bundles. `reload lsp` and `reload dragonfly-reverb` do not restart an LV2 host; restart the host after installation or removal. The LSP mono impulse-response plugin was instantiated and used in the initial manual chain test; its `libcairo2` dependency is included in target preparation. Other LSP plugins and Dragonfly runtime dependencies remain unverified on target.
+
+### mod-host guitar chain
+
+`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 a `systemd --user` unit; it does not use `sudo` or restart PipeWire/WirePlumber. The generated unit refers to the repository checkout from which `deploy.sh` was run, so keep the checkout at that path or uninstall/reinstall after moving it.
+
+At service startup, `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.
+
+`reload mod-host` restarts the service and rebuilds the plugin graph, briefly interrupting the processed guitar path. `uninstall mod-host` disables/stops the unit and restores any prior unit file; it does not create a dry bypass. 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.
+
+The owner reports enabling lingering with `sudo loginctl enable-linger "$USER"` so the user manager can run without an interactive login. Automatic boot startup and recovery after PipeWire restarts still require on-target verification. Installation refuses to start if port 5555 is already occupied by an unmanaged/manual mod-host 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
+```
 
 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`.
 
@@ -140,18 +158,18 @@ SooperLooper's tagged source does not define ARM64 atomics in `libs/pbd/pbd/atom
 
 ## `rigforge` target
 
-The filter-chain fragment is installed in the user configuration on `rigforge`, and `filter-chain.service` was restarted to load it. The user confirmed guitar and microphone are audible together through the filter. Three managed links are currently present after explicit one-shot reconciliation; they remain declared in `routing.managed_links` for observation. This is an initial listening check, not a sustained load, dropout, four-instrument, or headroom test.
+The filter-chain fragment is installed in the user configuration on `rigforge`, and `filter-chain.service` was restarted to load it. The user confirmed guitar and microphone are audible together through the filter. The guitar now has a tested NAM → cabinet-IR chain before mixer AUX0; the owner reported a pleasing crunch and no crackle during the initial listening test. The direct guitar bypass link is absent while the mod-host chain is connected. This is not a sustained load, dropout, headroom, or unattended-startup test. A brief mod-host CPU-load reading was about 42%; one `pw-top` snapshot showed no reported errors but does not establish stability.
 
 The next 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. Audibility after that later repair remains unconfirmed.
+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.
 2. Later, test inputs 2 and 4 with sources when available; they are included in the mixer but not verified 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. Inspect the user service session and resource limits before defining autonomous startup. `Linger=no` currently means the running audio session is associated with the active login; unattended startup is not established.
+4. Verify the new `rigforge-mod-host.service` on the target, including reboot with lingering enabled, PipeWire restart behavior, resource limits, and recovery when an LV2 plugin fails to load.
 5. Verify FCB1010 MIDI messages and the supplied bindings with the eventual SooperLooper build. Verify OSC port readiness and the effect and persistence 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. Service installation, activation, logs, diagnostics, and rollback commands will be documented after their units and target paths have been tested. 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 mod-host service unit and deploy commands are now declared in the repository, but installation/activation, logs, diagnostics, and rollback remain unverified on the target. Keep the last known working revision available; do not apply unverified audio or service changes during live use.

+ 44 - 0
config/desired-state.yaml

@@ -59,6 +59,14 @@ deployment:
   mod_host:
     source_url: https://github.com/mod-audio/mod-host
     tag: v1.15.0.3371
+    binary_source: artifacts/mod-host/arm64/current/mod-host
+    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
+    socket_port: 5555
+    pw_jack_path: /usr/bin/pw-jack
+    python_path: /usr/bin/python3
   pipewire:
     fragment_source: config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf
     fragment_destination: .config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf
@@ -141,11 +149,41 @@ routing:
       mix: PB
       monitor: A
     hardware_output_status: reported-by-target-owner
+  mod_host_chains:
+    guitar:
+      source_port: alsa_input.hw_U192k_0:capture_AUX0
+      bypass_link:
+        from: alsa_input.hw_U192k_0:capture_AUX0
+        to: rigforge.direct-mix.input:playback_AUX0
+      mix_input: rigforge.direct-mix.input:playback_AUX0
+      processors:
+        - id: amp-head
+          instance: 0
+          plugin_uri: http://github.com/mikeoliphant/neural-amp-modeler-lv2
+          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
+          input_port: effect_0:input
+          output_port: effect_0:output
+          parameters:
+            output_level: -12.0
+        - id: cabinet-ir
+          instance: 1
+          plugin_uri: http://lsp-plug.in/plugins/lv2/impulse_responses_mono
+          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
+          input_port: effect_1:in
+          output_port: effect_1:out
   looper_returns:
     destination: direct_mix
     feed_looper_inputs: false
   managed_ports:
     - alsa_input.hw_U192k_0:capture_AUX0
+    - effect_0:input
+    - effect_0:output
+    - effect_1:in
+    - effect_1:out
     - rigforge.direct-mix.input:playback_AUX0
     - alsa_input.hw_U192k_0:capture_AUX2
     - rigforge.direct-mix.input:playback_AUX2
@@ -153,6 +191,12 @@ 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.direct-mix.input:playback_AUX0
       status: observed
     - from: alsa_input.hw_U192k_0:capture_AUX2

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

@@ -0,0 +1,16 @@
+[Unit]
+Description=Rigforge guitar NAM and cabinet chain
+Wants=pipewire.service wireplumber.service filter-chain.service
+After=pipewire.service wireplumber.service filter-chain.service
+
+[Service]
+Type=simple
+ExecStart=@PW_JACK@ @MOD_HOST_BINARY@ -n -p @SOCKET_PORT@
+ExecStartPost=@PYTHON@ @CONFIGURE_SCRIPT@ --state @DESIRED_STATE@ --repo-root @REPOSITORY_ROOT@
+Restart=on-failure
+RestartSec=5
+TimeoutStartSec=60
+TimeoutStopSec=10
+
+[Install]
+WantedBy=default.target

+ 219 - 0
scripts/configure_mod_host.py

@@ -0,0 +1,219 @@
+import argparse
+import socket
+import subprocess
+import sys
+import time
+from pathlib import Path, PurePosixPath
+
+import yaml
+
+from validate_desired_state import validate_state
+
+
+def run(command):
+    return subprocess.run(command, check=True, capture_output=True, text=True)
+
+
+def mod_host_command(port, command, timeout=10):
+    payload = command.encode("utf-8") + b"\0"
+    with socket.create_connection(("127.0.0.1", 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 response_status(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 ensure_plugin(port, processor, bundle_path, command=mod_host_command):
+    instance = processor["instance"]
+    add_command = f"add {processor['plugin_uri']} {instance}"
+    response = command(port, add_command)
+    fields = response.split()
+    if fields == ["resp", "-101"]:
+        bundle_command = f"bundle_add {bundle_path}"
+        response_status(command(port, bundle_command), bundle_command)
+        response = command(port, add_command)
+    status = response_status(response, add_command)
+    if status != instance:
+        raise RuntimeError(
+            f"mod-host returned instance {status} for requested instance {instance}"
+        )
+
+
+def wait_for_mod_host(port, timeout=20, command=mod_host_command, sleeper=time.sleep):
+    deadline = time.monotonic() + timeout
+    last_error = None
+    while True:
+        try:
+            response_status(command(port, "cpu_load"), "cpu_load")
+            return
+        except OSError as error:
+            last_error = error
+        if time.monotonic() >= deadline:
+            raise RuntimeError(f"mod-host control socket did not become ready: {last_error}")
+        sleeper(0.2)
+
+
+def parse_links(text):
+    links = set()
+    current_source = None
+    for line in text.splitlines():
+        if not line.strip():
+            continue
+        if line.startswith("  |-> "):
+            if current_source is None:
+                raise RuntimeError("pw-link output has a destination without a source")
+            links.add((current_source, line.removeprefix("  |-> ")))
+        elif line.startswith("  |<- "):
+            if current_source is None:
+                raise RuntimeError("pw-link output has a destination without a source")
+            links.add((line.removeprefix("  |<- "), current_source))
+        else:
+            current_source = line.strip()
+    return links
+
+
+def list_ports(direction, runner=run):
+    result = runner(["pw-link", direction])
+    return {line.strip() for line in result.stdout.splitlines() if line.strip()}
+
+
+def wait_for_ports(required_outputs, required_inputs, timeout=20, runner=run, sleeper=time.sleep):
+    deadline = time.monotonic() + timeout
+    while True:
+        outputs = list_ports("-o", runner)
+        inputs = list_ports("-i", runner)
+        missing_outputs = required_outputs - outputs
+        missing_inputs = required_inputs - inputs
+        if not missing_outputs and not missing_inputs:
+            return
+        if time.monotonic() >= deadline:
+            raise RuntimeError(
+                "mod-host ports did not appear; "
+                f"missing outputs={sorted(missing_outputs)}, inputs={sorted(missing_inputs)}"
+            )
+        sleeper(0.2)
+
+
+def resolve_asset(repo_root, relative_path):
+    path = PurePosixPath(relative_path)
+    if path.is_absolute() or ".." in path.parts or not path.parts:
+        raise RuntimeError(f"unsafe repository asset path: {relative_path!r}")
+    resolved = (repo_root / Path(*path.parts)).resolve()
+    if not resolved.is_relative_to(repo_root.resolve()) or not resolved.is_file():
+        raise RuntimeError(f"declared mod-host asset is missing or escapes the repository: {resolved}")
+    return resolved
+
+
+def configure(state, repo_root, runner=run, sleeper=time.sleep, command=mod_host_command):
+    deployment = state["deployment"]["mod_host"]
+    chain = state["routing"]["mod_host_chains"]["guitar"]
+    port = deployment["socket_port"]
+    processors = chain["processors"]
+
+    # A short, read-only command both waits for socket readiness and exercises
+    # the same NUL-terminated protocol used for all subsequent control requests.
+    wait_for_mod_host(port, command=command, sleeper=sleeper)
+
+    for processor in processors:
+        bundle_relative = PurePosixPath(processor["bundle_path"])
+        if bundle_relative.is_absolute() or ".." in bundle_relative.parts:
+            raise RuntimeError(f"unsafe LV2 bundle path: {processor['bundle_path']!r}")
+        bundle_path = Path.home().joinpath(*bundle_relative.parts)
+        asset_path = resolve_asset(repo_root, processor["asset_path"])
+
+        ensure_plugin(port, processor, bundle_path, command=command)
+        patch_command = (
+            f"patch_set {processor['instance']} {processor['file_property']} {asset_path}"
+        )
+        response_status(command(port, patch_command), patch_command)
+        for symbol, value in processor.get("parameters", {}).items():
+            parameter_command = f"param_set {processor['instance']} {symbol} {value}"
+            response_status(command(port, parameter_command), parameter_command)
+
+    first = processors[0]
+    required_outputs = {chain["source_port"]}
+    required_inputs = {chain["mix_input"]}
+    for processor in processors:
+        required_inputs.add(processor["input_port"])
+        required_outputs.add(processor["output_port"])
+    wait_for_ports(required_outputs, required_inputs, runner=runner, sleeper=sleeper)
+
+    result = runner(["pw-link", "-l"])
+    links = parse_links(result.stdout)
+    expected_links = []
+    for source, destination in zip(processors, processors[1:]):
+        expected_links.append((source["output_port"], destination["input_port"]))
+    expected_links.append((processors[-1]["output_port"], chain["mix_input"]))
+
+    for source, destination in expected_links:
+        if (source, destination) not in links:
+            runner(["pw-link", source, destination])
+            links.add((source, destination))
+
+    bypass = (chain["bypass_link"]["from"], chain["bypass_link"]["to"])
+    if bypass in links:
+        runner(["pw-link", "-d", bypass[0], bypass[1]])
+        links.remove(bypass)
+
+    source_link = (chain["source_port"], first["input_port"])
+    if source_link not in links:
+        runner(["pw-link", source_link[0], source_link[1]])
+        links.add(source_link)
+
+    result = runner(["pw-link", "-l"])
+    final_links = parse_links(result.stdout)
+    expected_links.append(source_link)
+    missing = [link for link in expected_links if link not in final_links]
+    if missing:
+        raise RuntimeError(f"mod-host chain links are still missing: {missing}")
+    if bypass in final_links:
+        raise RuntimeError("direct guitar bypass link remains connected")
+
+    return {
+        "instances": [processor["instance"] for processor in processors],
+        "links": expected_links,
+        "bypass_disconnected": bypass not in final_links,
+    }
+
+
+def main(argv=None):
+    root = Path(__file__).resolve().parents[1]
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--state", type=Path, default=root / "config" / "desired-state.yaml")
+    parser.add_argument("--repo-root", type=Path, default=root)
+    args = parser.parse_args(argv)
+    try:
+        with args.state.open(encoding="utf-8") as stream:
+            state = yaml.safe_load(stream)
+        errors = validate_state(state)
+        if errors:
+            raise ValueError("invalid desired state: " + "; ".join(errors))
+        result = configure(state, args.repo_root.resolve())
+    except (OSError, RuntimeError, ValueError, KeyError, TypeError, yaml.YAMLError,
+            subprocess.CalledProcessError) as error:
+        print(f"ERROR: {error}", file=sys.stderr)
+        return 1
+    print(f"Configured mod-host chain: {result}")
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 274 - 1
scripts/deploy.py

@@ -4,6 +4,7 @@ import json
 import os
 import re
 import shutil
+import socket
 import subprocess
 import sys
 import tarfile
@@ -789,10 +790,280 @@ def deploy_namlv2(action, config, registry):
     print(f"Downloaded archive SHA-256 (identity only, no publisher checksum): {archive_digest}")
 
 
+def systemd_quote(value):
+    value = str(value).replace("%", "%%").replace("\\", "\\\\").replace('"', '\\"')
+    return f'"{value}"'
+
+
+def render_mod_host_service(config):
+    binary = ROOT / config["binary_source"]
+    service_template = ROOT / config["service_source"]
+    configure_script = ROOT / config["configure_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}")
+    replacements = {
+        "@PW_JACK@": systemd_quote(config["pw_jack_path"]),
+        "@MOD_HOST_BINARY@": systemd_quote(binary.resolve()),
+        "@SOCKET_PORT@": str(config["socket_port"]),
+        "@PYTHON@": systemd_quote(config["python_path"]),
+        "@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():
+        content = content.replace(placeholder, replacement)
+    if re.search(r"@[A-Z_]+@", content):
+        raise RuntimeError("unexpanded placeholder remains in mod-host service template")
+    return content.encode("utf-8")
+
+
+def mod_host_runtime_digest(config):
+    state_path = ROOT / "config" / "desired-state.yaml"
+    script_path = ROOT / config["configure_script"]
+    binary_path = ROOT / config["binary_source"]
+    with state_path.open(encoding="utf-8") as stream:
+        state = yaml.safe_load(stream)
+    files = [state_path, script_path, binary_path]
+    for processor in state["routing"]["mod_host_chains"]["guitar"]["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)
+
+    digest = hashlib.sha256()
+    for path in files:
+        if not path.is_file():
+            raise RuntimeError(f"mod-host runtime input is missing: {path}")
+        digest.update(str(path.relative_to(ROOT.resolve())).encode("utf-8") + b"\0")
+        digest.update(path.read_bytes())
+        digest.update(b"\0")
+    return digest.hexdigest()
+
+
+def mod_host_port_is_open(port):
+    try:
+        with socket.create_connection(("127.0.0.1", port), timeout=0.25):
+            return True
+    except OSError:
+        return False
+
+
+def mod_host_unit_is_active(service_name):
+    result = subprocess.run(
+        ["systemctl", "--user", "is-active", "--quiet", service_name],
+        check=False,
+        stdout=subprocess.DEVNULL,
+        stderr=subprocess.DEVNULL,
+    )
+    return result.returncode == 0
+
+
+def mod_host_unit_is_enabled(service_name):
+    result = subprocess.run(
+        ["systemctl", "--user", "is-enabled", "--quiet", service_name],
+        check=False,
+        stdout=subprocess.DEVNULL,
+        stderr=subprocess.DEVNULL,
+    )
+    return result.returncode == 0
+
+
+def deploy_mod_host(action, config, registry):
+    destination = Path.home() / config["service_destination"]
+    validate_user_destination(destination)
+    service_name = config["user_service"]
+    managed = registry.get("mod_host")
+
+    if action == "reload":
+        if managed is None:
+            raise RuntimeError("mod-host is not managed; install mod-host before reloading it")
+        if managed.get("pending_uninstall"):
+            raise RuntimeError("mod-host uninstall is incomplete; retry uninstall mod-host first")
+        if not destination.is_file():
+            raise RuntimeError(f"managed mod-host service file is missing: {destination}")
+        digest = hashlib.sha256(destination.read_bytes()).hexdigest()
+        if digest != managed.get("installed_sha256"):
+            raise RuntimeError(f"managed mod-host service file changed locally: {destination}")
+        run(["systemctl", "--user", "restart", service_name])
+        run(["systemctl", "--user", "is-active", "--quiet", service_name])
+        print("Rigforge mod-host user service restarted.")
+        return
+
+    if action == "uninstall":
+        if managed is None:
+            print("No managed mod-host service to uninstall.")
+            return
+        backup_path = validate_backup_path(managed.get("backup"), destination)
+        if backup_path is not None and backup_path.exists():
+            if not backup_path.is_file():
+                raise RuntimeError(f"recorded mod-host service backup has the wrong type: {backup_path}")
+            if hashlib.sha256(backup_path.read_bytes()).hexdigest() != managed.get("backup_sha256"):
+                raise RuntimeError(f"recorded mod-host service backup changed locally: {backup_path}")
+        if not managed.get("pending_uninstall"):
+            if not destination.is_file():
+                raise RuntimeError(f"managed mod-host service file is missing: {destination}")
+            digest = hashlib.sha256(destination.read_bytes()).hexdigest()
+            if digest != managed.get("installed_sha256"):
+                raise RuntimeError(f"managed mod-host service file changed locally; refusing removal: {destination}")
+            managed["pending_uninstall"] = True
+            registry["mod_host"] = managed
+            write_registry(registry)
+
+        destination_digest = (
+            hashlib.sha256(destination.read_bytes()).hexdigest()
+            if destination.is_file()
+            else None
+        )
+        backup_digest = (
+            hashlib.sha256(backup_path.read_bytes()).hexdigest()
+            if backup_path is not None and backup_path.is_file()
+            else None
+        )
+        installed_digest = managed.get("installed_sha256")
+        already_restored = (
+            backup_path is not None
+            and destination_digest == managed.get("backup_sha256")
+        )
+        already_removed = destination_digest is None and backup_digest is None and backup_path is None
+        if not already_restored and not already_removed:
+            if destination_digest not in {installed_digest, None}:
+                raise RuntimeError(f"unexpected file blocks mod-host uninstall: {destination}")
+            run(["systemctl", "--user", "disable", "--now", service_name])
+            if destination_digest == installed_digest:
+                destination.unlink()
+            if backup_path is not None and backup_path.exists():
+                os.replace(backup_path, destination)
+            elif backup_path is not None:
+                raise RuntimeError(f"recorded mod-host service backup is missing: {backup_path}")
+        run(["systemctl", "--user", "daemon-reload"])
+        registry.pop("mod_host")
+        write_registry(registry)
+        print("Rigforge mod-host user service removed; prior unit state restored if present.")
+        return
+
+    # Install is intentionally an explicit target, not part of "all": it
+    # activates the guitar processing chain and can make audio audible.
+    content = render_mod_host_service(config)
+    installed_digest = hashlib.sha256(content).hexdigest()
+    runtime_digest = mod_host_runtime_digest(config)
+    previous_runtime_digest = managed.get("runtime_sha256") if managed is not None else None
+    restart_required = managed is None or runtime_digest != previous_runtime_digest
+    if managed is not None:
+        if managed.get("pending_uninstall"):
+            raise RuntimeError("mod-host uninstall is incomplete; retry uninstall mod-host first")
+        backup_path = validate_backup_path(managed.get("backup"), destination)
+        if backup_path is not None:
+            if not backup_path.is_file():
+                raise RuntimeError(f"recorded mod-host service backup is missing: {backup_path}")
+            if hashlib.sha256(backup_path.read_bytes()).hexdigest() != managed.get("backup_sha256"):
+                raise RuntimeError(f"recorded mod-host service backup changed locally: {backup_path}")
+        if not destination.is_file():
+            if not managed.get("pending_install"):
+                raise RuntimeError(f"managed mod-host service file is missing: {destination}")
+        if destination.exists() and not destination.is_file():
+            raise RuntimeError(f"managed mod-host service destination has the wrong type: {destination}")
+        current_digest = (
+            hashlib.sha256(destination.read_bytes()).hexdigest()
+            if destination.is_file()
+            else None
+        )
+        if current_digest is not None and current_digest != managed.get("installed_sha256"):
+            prior_digest = managed.get("backup_sha256")
+            if not managed.get("pending_install") or current_digest != prior_digest:
+                raise RuntimeError(
+                    f"managed mod-host service file changed locally; refusing overwrite: {destination}"
+                )
+        elif not destination.exists() and not managed.get("pending_install"):
+            raise RuntimeError(f"managed mod-host service file changed locally; refusing overwrite: {destination}")
+        backup = managed.get("backup")
+        backup_sha256 = managed.get("backup_sha256")
+    else:
+        if mod_host_unit_is_active(service_name) or mod_host_unit_is_enabled(service_name):
+            raise RuntimeError(
+                f"an unmanaged {service_name} is already active or enabled; "
+                "inspect and disable it before installing Rigforge's unit"
+            )
+        if mod_host_port_is_open(config["socket_port"]):
+            raise RuntimeError(
+                f"mod-host control port {config['socket_port']} is already in use; "
+                "stop the unmanaged test process before installing the user service"
+            )
+        backup = None
+        backup_sha256 = None
+        if destination.exists():
+            backup_path = destination.with_name(destination.name + ".rigforge-backup")
+            if backup_path.exists():
+                raise RuntimeError(f"backup path already exists: {backup_path}")
+            shutil.copy2(destination, backup_path)
+            backup = str(backup_path)
+            backup_sha256 = hashlib.sha256(backup_path.read_bytes()).hexdigest()
+
+    unit_changed = not destination.exists() or destination.read_bytes() != content
+    restart_required = (
+        restart_required
+        or unit_changed
+        or (managed is not None and managed.get("pending_activation", False))
+    )
+    if managed is None:
+        managed = {
+            "installed_sha256": installed_digest,
+            "runtime_sha256": runtime_digest,
+            "backup": backup,
+            "backup_sha256": backup_sha256,
+            "pending_install": unit_changed,
+            "pending_activation": True,
+        }
+    else:
+        managed["installed_sha256"] = installed_digest
+        managed["runtime_sha256"] = runtime_digest
+        managed["pending_install"] = unit_changed
+        managed["pending_activation"] = True
+    registry["mod_host"] = managed
+    write_registry(registry)
+    if unit_changed:
+        destination.parent.mkdir(parents=True, exist_ok=True)
+        fd, temporary_name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent)
+        try:
+            with os.fdopen(fd, "wb") as stream:
+                stream.write(content)
+            os.chmod(temporary_name, 0o644)
+            os.replace(temporary_name, destination)
+        finally:
+            if os.path.exists(temporary_name):
+                os.unlink(temporary_name)
+
+    managed.pop("pending_install", None)
+    registry["mod_host"] = managed
+    write_registry(registry)
+    run(["systemctl", "--user", "daemon-reload"])
+    run(["systemctl", "--user", "enable", service_name])
+    if restart_required:
+        run(["systemctl", "--user", "restart", service_name])
+    else:
+        run(["systemctl", "--user", "start", service_name])
+    run(["systemctl", "--user", "is-active", "--quiet", service_name])
+    managed.pop("pending_activation", None)
+    registry["mod_host"] = managed
+    write_registry(registry)
+    print(f"Installed and activated Rigforge mod-host user service at {destination}.")
+
+
 def main(argv=None):
     parser = argparse.ArgumentParser()
     parser.add_argument("action", choices=("install", "uninstall", "reload"))
-    parser.add_argument("target", choices=("namlv2", "lsp", "dragonfly-reverb", "pipewire"))
+    parser.add_argument(
+        "target",
+        choices=("namlv2", "lsp", "dragonfly-reverb", "pipewire", "mod-host"),
+    )
     args = parser.parse_args(argv)
     try:
         state = yaml.safe_load((ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8"))
@@ -805,6 +1076,8 @@ def main(argv=None):
             deploy_namlv2(args.action, deployment["namlv2"], registry)
         elif args.target == "pipewire":
             deploy_pipewire(args.action, deployment["pipewire"], registry, quantum_frames)
+        elif args.target == "mod-host":
+            deploy_mod_host(args.action, deployment["mod_host"], registry)
         else:
             component = "dragonfly_reverb" if args.target == "dragonfly-reverb" else args.target
             deploy_lv2_archives(args.action, component, deployment[component], registry)

+ 2 - 2
scripts/deploy.sh

@@ -2,7 +2,7 @@
 set -u
 
 usage() {
-    printf 'Usage: %s install|uninstall|reload all|namlv2|lsp|dragonfly-reverb|pipewire\n' "$0" >&2
+    printf 'Usage: %s install|uninstall|reload all|namlv2|lsp|dragonfly-reverb|pipewire|mod-host\n' "$0" >&2
     exit 2
 }
 
@@ -15,7 +15,7 @@ case "$action" in
 esac
 case "$target" in
     all) targets=(pipewire namlv2 lsp dragonfly-reverb) ;;
-    namlv2|lsp|dragonfly-reverb|pipewire) targets=("$target") ;;
+    namlv2|lsp|dragonfly-reverb|pipewire|mod-host) targets=("$target") ;;
     *) usage ;;
 esac
 

+ 3 - 1
scripts/observe_pipewire.py

@@ -15,7 +15,9 @@ MANAGED_ENDPOINT_PATTERN = re.compile(
     r"alsa_input\.hw_U192k_0:capture_AUX[0-3]|"
     r"alsa_output\.hw_U192k_0:playback_AUX[0-3]|"
     r"rigforge\.direct-mix\.input:playback_AUX[0-3]|"
-    r"rigforge\.direct-mix\.output:capture_FL"
+    r"rigforge\.direct-mix\.output:capture_FL|"
+    r"effect_0:(?:input|output)|"
+    r"effect_1:(?:in|out)"
     r")$"
 )
 

+ 131 - 1
scripts/validate_desired_state.py

@@ -1,10 +1,120 @@
 import argparse
 import sys
-from pathlib import Path
+from pathlib import Path, PurePosixPath
 
 import yaml
 
 
+def safe_relative_path(value):
+    if not isinstance(value, str) or not value:
+        return False
+    path = PurePosixPath(value)
+    return not path.is_absolute() and ".." not in path.parts
+
+
+def validate_mod_host_chain(routing, source_by_id):
+    errors = []
+    chains = routing.get("mod_host_chains")
+    if not isinstance(chains, dict):
+        return ["routing.mod_host_chains must be a mapping"]
+    if set(chains) != {"guitar"}:
+        errors.append("routing.mod_host_chains must declare the guitar chain exactly once")
+    chain = chains.get("guitar")
+    if not isinstance(chain, dict):
+        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")
+    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}:
+        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")
+
+    processors = chain.get("processors")
+    if not isinstance(processors, list) or len(processors) != 2:
+        return errors + ["routing.mod_host_chains.guitar.processors must contain NAM followed by one cabinet IR"]
+
+    expected_processors = (
+        {
+            "id": "amp-head",
+            "instance": 0,
+            "plugin_uri": "http://github.com/mikeoliphant/neural-amp-modeler-lv2",
+            "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",
+            "input_port": "effect_0:input",
+            "output_port": "effect_0:output",
+        },
+        {
+            "id": "cabinet-ir",
+            "instance": 1,
+            "plugin_uri": "http://lsp-plug.in/plugins/lv2/impulse_responses_mono",
+            "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",
+            "input_port": "effect_1:in",
+            "output_port": "effect_1:out",
+        },
+    )
+    for index, (processor, expected) in enumerate(zip(processors, expected_processors)):
+        location = f"routing.mod_host_chains.guitar.processors[{index}]"
+        if not isinstance(processor, dict):
+            errors.append(f"{location} must be a mapping")
+            continue
+        for key, value in expected.items():
+            if processor.get(key) != value:
+                errors.append(f"{location}.{key} must be {value}")
+        for key in ("bundle_path", "asset_path"):
+            if not safe_relative_path(processor.get(key)):
+                errors.append(f"{location}.{key} must be a safe relative path")
+    if isinstance(processors[0], dict):
+        parameters = processors[0].get("parameters")
+        if not isinstance(parameters, dict):
+            errors.append("routing.mod_host_chains.guitar.processors[0].parameters must be a mapping")
+        else:
+            output_level = parameters.get("output_level")
+            if (
+                not isinstance(output_level, (int, float))
+                or isinstance(output_level, bool)
+                or not -20.0 <= output_level <= 20.0
+            ):
+                errors.append("NAM output_level must be between -20 and 20 dB")
+
+    links = routing.get("managed_links")
+    if isinstance(links, list) and len(processors) == 2:
+        actual_edges = {
+            (link.get("from"), link.get("to"))
+            for link in links
+            if (
+                isinstance(link, dict)
+                and isinstance(link.get("from"), str)
+                and isinstance(link.get("to"), str)
+            )
+        }
+        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),
+            )
+            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]}")
+        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:
+                errors.append("the guitar capture-to-mix bypass must not be a managed link")
+    return errors
+
+
 def validate_state(state):
     errors = []
     if not isinstance(state, dict):
@@ -128,6 +238,8 @@ def validate_state(state):
     elif returns.get("feed_looper_inputs") is not False:
         errors.append("routing.looper_returns.feed_looper_inputs must be false")
 
+    errors.extend(validate_mod_host_chain(routing, source_by_id))
+
     connections = state.get("connections", [])
     if not isinstance(connections, list):
         errors.append("connections must be a list")
@@ -244,6 +356,24 @@ def validate_state(state):
                 character not in allowed_tag_characters for character in tag
             ):
                 errors.append("deployment.mod_host.tag must be a simple version tag")
+            for key, expected in (
+                ("binary_source", "artifacts/mod-host/arm64/current/mod-host"),
+                ("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"),
+                ("pw_jack_path", "/usr/bin/pw-jack"),
+                ("python_path", "/usr/bin/python3"),
+            ):
+                if mod_host.get(key) != expected:
+                    errors.append(f"deployment.mod_host.{key} must be {expected}")
+            socket_port = mod_host.get("socket_port")
+            if (
+                not isinstance(socket_port, int)
+                or isinstance(socket_port, bool)
+                or not 1 <= socket_port <= 65535
+            ):
+                errors.append("deployment.mod_host.socket_port must be a valid TCP port")
 
         pipewire = deployment.get("pipewire")
         if not isinstance(pipewire, dict):

+ 119 - 0
tests/test_configure_mod_host.py

@@ -0,0 +1,119 @@
+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 configure_mod_host import configure, wait_for_mod_host
+
+
+class ModHostConfigurationTests(unittest.TestCase):
+    @classmethod
+    def setUpClass(cls):
+        with (ROOT / "config" / "desired-state.yaml").open(encoding="utf-8") as stream:
+            cls.state = yaml.safe_load(stream)
+
+    def test_loads_nam_and_ir_then_replaces_only_declared_dry_link(self):
+        routing = self.state["routing"]
+        chain = routing["mod_host_chains"]["guitar"]
+        bypass = (chain["bypass_link"]["from"], chain["bypass_link"]["to"])
+        links = {bypass}
+        control_commands = []
+        bundle_added = False
+
+        def control(port, command):
+            nonlocal bundle_added
+            control_commands.append(command)
+            if command == "cpu_load":
+                return "resp 0 12.5"
+            if command.startswith("add http://lsp.plug.in/"):
+                return "resp -101"
+            if command.startswith("add http://lsp-plug.in/") and not bundle_added:
+                return "resp -101"
+            if command.startswith("bundle_add "):
+                bundle_added = True
+                return "resp 0"
+            if command.startswith("add "):
+                return f"resp {command.rsplit(' ', 1)[1]}"
+            return "resp 0"
+
+        def render_links():
+            return "".join(
+                f"{source}\n  |-> {destination}\n"
+                for source, destination in sorted(links)
+            )
+
+        outputs = {
+            chain["source_port"],
+            *(processor["output_port"] for processor in chain["processors"]),
+        }
+        inputs = {
+            chain["mix_input"],
+            *(processor["input_port"] for processor in chain["processors"]),
+        }
+
+        def runner(command):
+            if command == ["pw-link", "-o"]:
+                return SimpleNamespace(stdout="\n".join(sorted(outputs)) + "\n")
+            if command == ["pw-link", "-i"]:
+                return SimpleNamespace(stdout="\n".join(sorted(inputs)) + "\n")
+            if command == ["pw-link", "-l"]:
+                return SimpleNamespace(stdout=render_links())
+            if command[:2] == ["pw-link", "-d"]:
+                links.discard((command[2], command[3]))
+                return SimpleNamespace(stdout="")
+            if command[0] == "pw-link" and len(command) == 3:
+                links.add((command[1], command[2]))
+                return SimpleNamespace(stdout="")
+            self.fail(f"unexpected command: {command}")
+
+        result = configure(
+            self.state,
+            ROOT,
+            runner=runner,
+            sleeper=lambda _duration: None,
+            command=control,
+        )
+
+        expected = {
+            (chain["source_port"], chain["processors"][0]["input_port"]),
+            (chain["processors"][0]["output_port"], chain["processors"][1]["input_port"]),
+            (chain["processors"][1]["output_port"], chain["mix_input"]),
+        }
+        self.assertEqual(links, expected)
+        self.assertNotIn(bypass, links)
+        self.assertEqual(result["instances"], [0, 1])
+        self.assertTrue(result["bypass_disconnected"])
+        self.assertIn(
+            "patch_set 0 http://github.com/mikeoliphant/neural-amp-modeler-lv2#model "
+            + str(ROOT / "amp_emul/amphead/VOX_AC15/Vox_AC15CH_Crunch_TB.nam"),
+            control_commands,
+        )
+        self.assertIn(
+            "patch_set 1 http://lsp-plug.in/plugins/lv2/impulse_responses_mono/ports#ifn "
+            + str(ROOT / "amp_emul/cabinet/VOX_AC30_1964/VOX_AC30_1964_celestion.wav"),
+            control_commands,
+        )
+        self.assertIn("param_set 0 output_level -12.0", control_commands)
+        self.assertTrue(any(command.startswith("bundle_add ") for command in control_commands))
+
+    def test_waits_for_the_mod_host_control_socket(self):
+        calls = []
+
+        def command(_port, name):
+            calls.append(name)
+            if len(calls) == 1:
+                raise ConnectionRefusedError("not ready")
+            return "resp 0 8.0"
+
+        wait_for_mod_host(5555, timeout=1, command=command, sleeper=lambda _duration: None)
+
+        self.assertEqual(calls, ["cpu_load", "cpu_load"])
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 132 - 0
tests/test_deploy.py

@@ -27,6 +27,8 @@ class DeploymentTests(unittest.TestCase):
         self.run_patcher.start()
         self.home_patcher = patch.object(deploy.Path, "home", return_value=self.home)
         self.home_patcher.start()
+        patch.object(deploy, "mod_host_unit_is_active", return_value=False).start()
+        patch.object(deploy, "mod_host_unit_is_enabled", return_value=False).start()
         self.root_patcher = patch.object(deploy, "ROOT", ROOT)
         self.root_patcher.start()
         self.registry_patcher = patch.object(deploy, "STATE_PATH", self.registry_path)
@@ -100,6 +102,9 @@ class DeploymentTests(unittest.TestCase):
             "user_service": "filter-chain.service",
         }
 
+    def mod_host_config(self):
+        return deploy.load_deployment()["mod_host"]
+
     def make_archive(self, destination, files=None):
         files = files or {"manifest.ttl": b"<urn:nam> a <urn:Plugin> .\n", "plugin.so": b"binary"}
         with tarfile.open(destination, "w:gz") as archive:
@@ -200,6 +205,133 @@ class DeploymentTests(unittest.TestCase):
             deploy.deploy_pipewire("uninstall", config, deploy.read_registry(), 128)
         self.assertEqual(destination.read_text(encoding="utf-8"), "local edit")
 
+    def test_mod_host_install_renders_and_activates_user_service(self):
+        config = self.mod_host_config()
+        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("-n -p 5555", content)
+        self.assertIn("configure_mod_host.py", content)
+        self.assertEqual(
+            self.commands,
+            [
+                ["systemctl", "--user", "daemon-reload"],
+                ["systemctl", "--user", "enable", "rigforge-mod-host.service"],
+                ["systemctl", "--user", "restart", "rigforge-mod-host.service"],
+                ["systemctl", "--user", "is-active", "--quiet", "rigforge-mod-host.service"],
+            ],
+        )
+        registry = deploy.read_registry()
+        self.assertTrue(registry["mod_host"]["installed_sha256"])
+        self.assertNotIn("pending_activation", registry["mod_host"])
+
+    def test_mod_host_install_is_idempotent_without_restarting_active_audio(self):
+        config = self.mod_host_config()
+        with patch.object(deploy, "mod_host_port_is_open", return_value=False):
+            deploy.deploy_mod_host("install", config, deploy.read_registry())
+        self.commands.clear()
+        deploy.deploy_mod_host("install", config, deploy.read_registry())
+        self.assertEqual(
+            self.commands,
+            [
+                ["systemctl", "--user", "daemon-reload"],
+                ["systemctl", "--user", "enable", "rigforge-mod-host.service"],
+                ["systemctl", "--user", "start", "rigforge-mod-host.service"],
+                ["systemctl", "--user", "is-active", "--quiet", "rigforge-mod-host.service"],
+            ],
+        )
+
+    def test_mod_host_install_restarts_when_runtime_configuration_changes(self):
+        config = self.mod_host_config()
+        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]),
+        ):
+            deploy.deploy_mod_host("install", config, deploy.read_registry())
+            self.commands.clear()
+            deploy.deploy_mod_host("install", config, deploy.read_registry())
+        self.assertIn(
+            ["systemctl", "--user", "restart", "rigforge-mod-host.service"],
+            self.commands,
+        )
+
+    def test_mod_host_uninstall_restores_previous_unit(self):
+        config = self.mod_host_config()
+        destination = self.home / config["service_destination"]
+        destination.parent.mkdir(parents=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())
+        self.commands.clear()
+        deploy.deploy_mod_host("uninstall", config, deploy.read_registry())
+        self.assertEqual(destination.read_text(encoding="utf-8"), "prior unit")
+        self.assertNotIn("mod_host", deploy.read_registry())
+        self.assertEqual(
+            self.commands,
+            [
+                ["systemctl", "--user", "disable", "--now", "rigforge-mod-host.service"],
+                ["systemctl", "--user", "daemon-reload"],
+            ],
+        )
+
+    def test_mod_host_pending_uninstall_recovers_after_prior_unit_is_restored(self):
+        config = self.mod_host_config()
+        destination = self.home / config["service_destination"]
+        destination.parent.mkdir(parents=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())
+        registry = deploy.read_registry()
+        backup = Path(registry["mod_host"]["backup"])
+        registry["mod_host"]["pending_uninstall"] = True
+        deploy.write_registry(registry)
+        destination.write_text("prior unit", encoding="utf-8")
+        backup.unlink()
+        self.commands.clear()
+
+        deploy.deploy_mod_host("uninstall", config, registry)
+
+        self.assertEqual(destination.read_text(encoding="utf-8"), "prior unit")
+        self.assertNotIn("mod_host", deploy.read_registry())
+        self.assertEqual(self.commands, [["systemctl", "--user", "daemon-reload"]])
+
+    def test_mod_host_uninstall_refuses_local_unit_edits(self):
+        config = self.mod_host_config()
+        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"]
+        destination.write_text("local edit", encoding="utf-8")
+        self.commands.clear()
+        with self.assertRaisesRegex(RuntimeError, "changed locally"):
+            deploy.deploy_mod_host("uninstall", config, deploy.read_registry())
+        self.assertEqual(destination.read_text(encoding="utf-8"), "local edit")
+        self.assertEqual(self.commands, [])
+
+    def test_mod_host_install_refuses_an_existing_control_socket(self):
+        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())
+        self.assertEqual(self.commands, [])
+        self.assertFalse((self.home / self.mod_host_config()["service_destination"]).exists())
+
+    def test_mod_host_reload_restarts_and_checks_the_user_service(self):
+        config = self.mod_host_config()
+        with patch.object(deploy, "mod_host_port_is_open", return_value=False):
+            deploy.deploy_mod_host("install", config, deploy.read_registry())
+        self.commands.clear()
+        deploy.deploy_mod_host("reload", config, deploy.read_registry())
+        self.assertEqual(
+            self.commands,
+            [
+                ["systemctl", "--user", "restart", "rigforge-mod-host.service"],
+                ["systemctl", "--user", "is-active", "--quiet", "rigforge-mod-host.service"],
+            ],
+        )
+
     def test_lsp_install_uninstall_restores_existing_bundle_and_is_idempotent(self):
         component = "lsp"
         config = self.plugin_config(component)

+ 43 - 0
tests/test_desired_state.py

@@ -48,6 +48,45 @@ 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):
+        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])
+        self.assertNotIn(
+            (chain["bypass_link"]["from"], chain["bypass_link"]["to"]),
+            {
+                (link["from"], link["to"])
+                for link in self.state["routing"]["managed_links"]
+            },
+        )
+
+        state = copy.deepcopy(self.state)
+        state["routing"]["mod_host_chains"]["guitar"]["processors"][0]["asset_path"] = "../../outside.nam"
+        self.assertTrue(any("asset_path must be a safe relative path" in error for error in validate_state(state)))
+
+        state = copy.deepcopy(self.state)
+        state["routing"]["mod_host_chains"]["guitar"]["processors"][1]["instance"] = 0
+        self.assertTrue(any("processors[1].instance must be 1" in error for error in validate_state(state)))
+
+        state = copy.deepcopy(self.state)
+        state["routing"]["managed_links"].append(
+            {
+                "from": state["routing"]["mod_host_chains"]["guitar"]["bypass_link"]["from"],
+                "to": state["routing"]["mod_host_chains"]["guitar"]["bypass_link"]["to"],
+                "status": "planned",
+            }
+        )
+        self.assertIn("the guitar capture-to-mix bypass must not be a managed link", validate_state(state))
+
+        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)))
+
+        state = copy.deepcopy(self.state)
+        state["routing"]["mod_host_chains"]["guitar"]["processors"][0]["parameters"]["output_level"] = 30
+        self.assertIn("NAM output_level must be between -20 and 20 dB", validate_state(state))
+
     def test_deployment_targets_are_declared_and_valid(self):
         self.assertEqual(validate_state(self.state), [])
 
@@ -103,6 +142,10 @@ class DesiredStateValidationTests(unittest.TestCase):
         del state["deployment"]["mod_host"]
         self.assertIn("deployment.mod_host must be a mapping", validate_state(state))
 
+        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))
+
     def test_return_exclusion_marker_is_not_an_active_connection(self):
         self.assertEqual(validate_state(self.state), [])
 

+ 69 - 21
tests/test_pipewire_observer.py

@@ -18,6 +18,10 @@ from observe_pipewire import (
 CAPTURE_0 = "alsa_input.hw_U192k_0:capture_AUX0"
 CAPTURE_2 = "alsa_input.hw_U192k_0:capture_AUX2"
 CAPTURE_3 = "alsa_input.hw_U192k_0:capture_AUX3"
+AMP_INPUT = "effect_0:input"
+AMP_OUTPUT = "effect_0:output"
+CAB_INPUT = "effect_1:in"
+CAB_OUTPUT = "effect_1:out"
 MIX_INPUT_0 = "rigforge.direct-mix.input:playback_AUX0"
 MIX_INPUT_2 = "rigforge.direct-mix.input:playback_AUX2"
 MIX_OUTPUT = "rigforge.direct-mix.output:capture_FL"
@@ -79,18 +83,22 @@ class PipeWireObserverTests(unittest.TestCase):
         ]
         self.assertTrue(any("approved observed Rigforge or UMC port" in error for error in validate_managed_links(state)))
 
-    def test_declared_filter_mix_links_are_valid_and_match_observed_graph(self):
+    def test_declared_guitar_effect_chain_and_voice_mix_links_match_observed_graph(self):
         links = {
-            (CAPTURE_0, MIX_INPUT_0),
+            (CAPTURE_0, AMP_INPUT),
+            (AMP_OUTPUT, CAB_INPUT),
+            (CAB_OUTPUT, MIX_INPUT_0),
             (CAPTURE_2, MIX_INPUT_2),
             (MIX_OUTPUT, PLAYBACK_0),
         }
         self.assertEqual(validate_managed_links(self.state), [])
         self.assertEqual(observe(self.state, links), [])
 
-    def test_reports_missing_filter_mix_link(self):
+    def test_reports_missing_voice_mix_link_without_expectation_of_dry_guitar(self):
         links = {
-            (CAPTURE_0, MIX_INPUT_0),
+            (CAPTURE_0, AMP_INPUT),
+            (AMP_OUTPUT, CAB_INPUT),
+            (CAB_OUTPUT, MIX_INPUT_0),
             (MIX_OUTPUT, PLAYBACK_0),
         }
         reports = observe(self.state, links)
@@ -110,7 +118,9 @@ class PipeWireObserverTests(unittest.TestCase):
         state = copy.deepcopy(self.state)
         state["routing"]["managed_ports"].append(CAPTURE_3)
         links = {
-            (CAPTURE_0, MIX_INPUT_0),
+            (CAPTURE_0, AMP_INPUT),
+            (AMP_OUTPUT, CAB_INPUT),
+            (CAB_OUTPUT, MIX_INPUT_0),
             (CAPTURE_2, MIX_INPUT_2),
             (MIX_OUTPUT, PLAYBACK_0),
             (CAPTURE_3, MIX_INPUT_2),
@@ -134,7 +144,9 @@ class PipeWireObserverTests(unittest.TestCase):
         def runner(command, **kwargs):
             calls.append(command)
             return SimpleNamespace(stdout=(
-                f"{CAPTURE_0}\n  |-> {MIX_INPUT_0}\n"
+                f"{CAPTURE_0}\n  |-> {AMP_INPUT}\n"
+                f"{AMP_OUTPUT}\n  |-> {CAB_INPUT}\n"
+                f"{CAB_OUTPUT}\n  |-> {MIX_INPUT_0}\n"
                 f"{CAPTURE_2}\n  |-> {MIX_INPUT_2}\n"
                 f"{MIX_OUTPUT}\n  |-> {PLAYBACK_0}\n"
             ))
@@ -148,7 +160,9 @@ class PipeWireObserverTests(unittest.TestCase):
     def test_reconcile_once_links_only_declared_missing_edges_and_verifies(self):
         state = copy.deepcopy(self.state)
         links = {
-            (CAPTURE_0, MIX_INPUT_0),
+            (CAPTURE_0, AMP_INPUT),
+            (AMP_OUTPUT, CAB_INPUT),
+            (CAB_OUTPUT, MIX_INPUT_0),
             (MIX_OUTPUT, PLAYBACK_0),
         }
         calls = []
@@ -161,9 +175,13 @@ class PipeWireObserverTests(unittest.TestCase):
             if command == ["pw-link", "-l"]:
                 return SimpleNamespace(stdout=render_links())
             if command == ["pw-link", "-o"]:
-                return SimpleNamespace(stdout=f"{CAPTURE_0}\n{CAPTURE_2}\n{MIX_OUTPUT}\n")
+                return SimpleNamespace(stdout=(
+                    f"{AMP_OUTPUT}\n{CAB_OUTPUT}\n{CAPTURE_0}\n{CAPTURE_2}\n{MIX_OUTPUT}\n"
+                ))
             if command == ["pw-link", "-i"]:
-                return SimpleNamespace(stdout=f"{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n")
+                return SimpleNamespace(stdout=(
+                    f"{AMP_INPUT}\n{CAB_INPUT}\n{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n"
+                ))
             if command == ["pw-link", CAPTURE_2, MIX_INPUT_2]:
                 links.add((CAPTURE_2, MIX_INPUT_2))
                 return SimpleNamespace(stdout="")
@@ -190,11 +208,17 @@ class PipeWireObserverTests(unittest.TestCase):
             if command == ["pw-link", "-l"]:
                 return SimpleNamespace(stdout=render_links())
             if command == ["pw-link", "-o"]:
-                return SimpleNamespace(stdout=f"{CAPTURE_0}\n{CAPTURE_2}\n{MIX_OUTPUT}\n")
+                return SimpleNamespace(stdout=(
+                    f"{AMP_OUTPUT}\n{CAB_OUTPUT}\n{CAPTURE_0}\n{CAPTURE_2}\n{MIX_OUTPUT}\n"
+                ))
             if command == ["pw-link", "-i"]:
-                return SimpleNamespace(stdout=f"{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n")
+                return SimpleNamespace(stdout=(
+                    f"{AMP_INPUT}\n{CAB_INPUT}\n{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n"
+                ))
             if tuple(command) in {
-                ("pw-link", CAPTURE_0, MIX_INPUT_0),
+                ("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),
                 ("pw-link", MIX_OUTPUT, PLAYBACK_0),
             }:
@@ -207,8 +231,10 @@ class PipeWireObserverTests(unittest.TestCase):
         self.assertEqual(
             result["actions"],
             [
-                {"kind": "link", "from": CAPTURE_0, "to": MIX_INPUT_0, "result": "requested"},
+                {"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"},
             ],
         )
@@ -216,15 +242,24 @@ class PipeWireObserverTests(unittest.TestCase):
         self.assertEqual(
             [command for command in calls if len(command) == 3 and command[0] == "pw-link"],
             [
-                ["pw-link", CAPTURE_0, MIX_INPUT_0],
+                ["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],
             ],
         )
 
     def test_reconcile_once_does_not_link_when_endpoint_is_unavailable(self):
         state = copy.deepcopy(self.state)
-        links = {(CAPTURE_0, MIX_INPUT_0), (MIX_OUTPUT, PLAYBACK_0)}
+        links = {
+            (CAPTURE_0, AMP_INPUT),
+            (AMP_OUTPUT, CAB_INPUT),
+            (CAB_OUTPUT, MIX_INPUT_0),
+            (CAPTURE_2, MIX_INPUT_2),
+            (MIX_OUTPUT, PLAYBACK_0),
+        }
+        links.remove((CAPTURE_2, MIX_INPUT_2))
         calls = []
 
         def render_links():
@@ -235,9 +270,11 @@ class PipeWireObserverTests(unittest.TestCase):
             if command == ["pw-link", "-l"]:
                 return SimpleNamespace(stdout=render_links())
             if command == ["pw-link", "-o"]:
-                return SimpleNamespace(stdout=f"{CAPTURE_0}\n{MIX_OUTPUT}\n")
+                return SimpleNamespace(stdout=f"{AMP_OUTPUT}\n{CAB_OUTPUT}\n{CAPTURE_0}\n{MIX_OUTPUT}\n")
             if command == ["pw-link", "-i"]:
-                return SimpleNamespace(stdout=f"{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n")
+                return SimpleNamespace(stdout=(
+                    f"{AMP_INPUT}\n{CAB_INPUT}\n{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n"
+                ))
             self.fail(f"unexpected command: {command}")
 
         result = reconcile_once(state, runner)
@@ -258,7 +295,9 @@ class PipeWireObserverTests(unittest.TestCase):
         state = copy.deepcopy(self.state)
         state["routing"]["managed_ports"].append(CAPTURE_3)
         links = {
-            (CAPTURE_0, MIX_INPUT_0),
+            (CAPTURE_0, AMP_INPUT),
+            (AMP_OUTPUT, CAB_INPUT),
+            (CAB_OUTPUT, MIX_INPUT_0),
             (CAPTURE_2, MIX_INPUT_2),
             (MIX_OUTPUT, PLAYBACK_0),
             (CAPTURE_3, MIX_INPUT_2),
@@ -280,7 +319,12 @@ class PipeWireObserverTests(unittest.TestCase):
 
     def test_reconcile_once_reports_link_still_missing_after_request(self):
         state = copy.deepcopy(self.state)
-        links = {(CAPTURE_0, MIX_INPUT_0), (MIX_OUTPUT, PLAYBACK_0)}
+        links = {
+            (CAPTURE_0, AMP_INPUT),
+            (AMP_OUTPUT, CAB_INPUT),
+            (CAB_OUTPUT, MIX_INPUT_0),
+            (MIX_OUTPUT, PLAYBACK_0),
+        }
 
         def render_links():
             return "".join(f"{source}\n  |-> {destination}\n" for source, destination in sorted(links))
@@ -289,9 +333,13 @@ class PipeWireObserverTests(unittest.TestCase):
             if command == ["pw-link", "-l"]:
                 return SimpleNamespace(stdout=render_links())
             if command == ["pw-link", "-o"]:
-                return SimpleNamespace(stdout=f"{CAPTURE_0}\n{CAPTURE_2}\n{MIX_OUTPUT}\n")
+                return SimpleNamespace(stdout=(
+                    f"{AMP_OUTPUT}\n{CAB_OUTPUT}\n{CAPTURE_0}\n{CAPTURE_2}\n{MIX_OUTPUT}\n"
+                ))
             if command == ["pw-link", "-i"]:
-                return SimpleNamespace(stdout=f"{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n")
+                return SimpleNamespace(stdout=(
+                    f"{AMP_INPUT}\n{CAB_INPUT}\n{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n"
+                ))
             if command == ["pw-link", CAPTURE_2, MIX_INPUT_2]:
                 return SimpleNamespace(stdout="")
             self.fail(f"unexpected command: {command}")