소스 검색

add mic chain

Johan Le Baut 5 일 전
부모
커밋
26842a34d8

+ 3 - 3
README.md

@@ -38,7 +38,7 @@ This records the preparation already performed on `rigforge` and is a starting p
 - `scripts/observe_pipewire.py`: read-only comparison by default, with explicit one-shot repair for declared missing links.
 - `scripts/midi_action_bridge.py`: translates declared ALSA MIDI note events into NAM model changes through mod-ui's WebSocket.
 - `scripts/run_mod_ui_service.py`: keeps mod-ui's backend session alive; mod-ui remains the sole owner of pedalboard connections.
-- `scripts/generate_mod_ui_pedalboard.py`: generates the reference NAM→IR pedalboard from the YAML.
+- `scripts/generate_mod_ui_pedalboard.py`: generates the reference guitar NAM→IR and microphone-processing pedalboard from the YAML.
 - `scripts/deploy.sh` and `scripts/deploy.py`: scoped user-level installation, removal, reload, and explicit mod-ui reset of declared services, SLWeb source files, and LV2 bundles.
 - `tests/`: unit tests for desired-state validation, PipeWire observation/reconciliation, pedalboard generation, MIDI WebSocket control, the mod-ui/PipeWire boundary bridge, and deployment operations.
 - `artifacts/sooperlooper/arm64/`, `artifacts/mod-host/arm64/`, and `artifacts/mod-ui/arm64/`: generated binaries or runtime bundle, dependency reports, and build provenance; commit after reviewing licensing and repository size.
@@ -163,9 +163,9 @@ Remove SLWeb before SooperLooper with `./scripts/deploy.sh uninstall slweb`. The
 
 `install mod-host-ports`, `install mod-host`, and `install mod-ui` are explicit targets and are deliberately excluded from `install all`. The desired four-channel `mod-host-ports` service starts a four-channel PipeWire input boundary (`rigforge.mod-host-input` with paired source `rigforge.mod-host-input.capture`) and a four-channel output boundary (`rigforge.mod-host-output.playback` with paired source `rigforge.mod-host-output`). Channel positions AUX0–AUX3 align with UMC capture channels 1–4. Rigforge's observer manages each UMC capture → input sink edge and each output source → its mixer/looper destinations. The generated mod-ui board shows the guitar path through NAM and IR, plus direct bass, microphone, and synth passthrough cables from `capture_2..4` to `playback_2..4`. mod-ui handles Connect/Disconnect for all boundary cables through the Rigforge PipeWire bridge; NAM→IR stays a normal mod-host connection. The service runner does not repair or override pedalboard links.
 
-`scripts/generate_mod_ui_pedalboard.py` builds the reference bundle from the YAML: one NAM defaulting to Vox AC15 Crystal Clean TB, one LSP mono IR using the Vox AC30 asset, the declared NAM output level, the guitar NAM→IR chain, and three mod-ui-owned passthrough arcs. During `install mod-ui`, deployment copies the declared NAM models into Rigforge's dedicated `MOD_USER_FILES_DIR/NAM Models/Rigforge` directory and generates a target-specific bundle whose model path points there; the model copies are fingerprinted and removed only if unchanged when mod-ui is uninstalled. The reference bundle is also target-specific, fingerprinted, and protected from local edits. mod-ui resumes its last saved board across service restarts within the same boot. `./scripts/deploy.sh reset mod-ui` explicitly restores the generated reference and backs up any prior default board and last-state file as adjacent `.rigforge-reset-backup` paths.
+`scripts/generate_mod_ui_pedalboard.py` builds the reference bundle from the YAML: one NAM defaulting to Vox AC15 Crystal Clean TB, one LSP mono IR using the Vox AC30 asset, the guitar NAM→IR chain, a microphone channel-3 chain (LSP high-pass, compressor and de-esser, then Dragonfly Room reverb with the dry signal retained), plus direct-through bass and synth arcs. The voice-chain settings are conservative starting points only and require listening and level adjustment on target. During `install mod-ui`, deployment copies the declared NAM models into Rigforge's dedicated `MOD_USER_FILES_DIR/NAM Models/Rigforge` directory and generates a target-specific bundle whose model path points there; the model copies are fingerprinted and removed only if unchanged when mod-ui is uninstalled. The reference bundle is also target-specific, fingerprinted, and protected from local edits. mod-ui resumes its last saved board across service restarts within the same boot. `./scripts/deploy.sh reset mod-ui` explicitly restores the generated reference and backs up any prior default board and last-state file as adjacent `.rigforge-reset-backup` paths.
 
-On each system boot, `rigforge-mod-ui.service` runs `scripts/prepare_mod_ui_pedalboard.py` before launching mod-ui. It regenerates and validates the content-addressed reference bundle from the checkout, replaces the mutable `default.pedalboard` with that clean board, and moves any previous default and last-state file into `mod-ui/boot-backups`, outside the pedalboard scan directory. It also migrates older Rigforge backups out of that scan directory. A marker under the user runtime directory makes this happen only once per boot; a mod-ui service restart during the same boot preserves in-session changes. If generation or validation fails, mod-ui does not start with a blank board. During pedalboard loading, the mod-ui integration retries PipeWire boundary links asynchronously so plugin-port creation can proceed on its event loop. The service then waits up to 35 seconds for both guitar links before reporting readiness. This behavior is covered by repository tests but has not yet been deployed or verified on the target.
+On each system boot, `rigforge-mod-ui.service` runs `scripts/prepare_mod_ui_pedalboard.py` before launching mod-ui. It regenerates and validates the content-addressed reference bundle from the checkout, replaces the mutable `default.pedalboard` with that clean board, and moves any previous default and last-state file into `mod-ui/boot-backups`, outside the pedalboard scan directory. It also migrates older Rigforge backups out of that scan directory. A marker under the user runtime directory makes this happen only once per boot; a mod-ui service restart during the same boot preserves in-session changes. The Rigforge service uses a dedicated `last-rigforge.json` state file so upstream `last.json` state cannot redirect startup to an unrelated board. If generation or validation fails, mod-ui does not start with a blank board. The service waits for mod-ui to report that it loaded the prepared default board, then verifies the guitar PipeWire boundary links before reporting readiness. This behavior is covered by repository tests but has not yet been deployed or verified on the target.
 
 If `install mod-ui` refuses a changed but registry-managed reference bundle, first inspect why it differs. To explicitly replace only that bundle while preserving its current contents, use `./scripts/deploy.sh install mod-ui --force-reference`; the old bundle is retained in an adjacent `.rigforge-force-backup` path. This flag does not override local edits to the systemd unit, model files, or other managed paths.
 

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

@@ -15,16 +15,46 @@ def boundary_connection(
     capture_symbol = port_from.rsplit("/", 1)[-1]
     capture_port = capture_ports.get(capture_symbol)
     if capture_port:
-        return capture_port, resolve_host_port(port_to)
+        host_port = resolve_host_port(port_to)
+        if host_port:
+            return capture_port, host_port
+        return None
 
     playback_symbol = port_to.rsplit("/", 1)[-1]
     playback_port = playback_ports.get(playback_symbol)
     if playback_port:
-        return resolve_host_port(port_from), playback_port
+        host_port = resolve_host_port(port_from)
+        if host_port:
+            return host_port, playback_port
+        return None
 
     return None
 
 
+def resolve_pedalboard_port(port, resolve_host_port):
+    """Resolve Ingen-style graph ports and LV2 effect_N aliases for pw-link."""
+    graph_path = port.removeprefix("/graph/")
+    if "/" not in graph_path:
+        return resolve_host_port(port)
+    instance, symbol = graph_path.split("/", 1)
+    effect_index = {
+        "rigforge_voice_high_pass": 2,
+        "rigforge_voice_compressor": 3,
+        "rigforge_voice_de_esser": 4,
+        "rigforge_voice_reverb": 5,
+    }.get(instance)
+    if effect_index is None:
+        return resolve_host_port(port)
+    effect_ports = {
+        "rigforge_voice_high_pass": {"in": "in", "out": "out"},
+        "rigforge_voice_compressor": {"in": "in", "out": "out"},
+        "rigforge_voice_de_esser": {"in": "in", "out": "out"},
+        "rigforge_voice_reverb": {"input_l": "input_l", "output_l": "output_l"},
+    }
+    resolved_symbol = effect_ports.get(instance, {}).get(symbol)
+    return f"effect_{effect_index}:{resolved_symbol}" if resolved_symbol else None
+
+
 def _link_status(source, destination, runner):
     try:
         result = runner(

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

@@ -9,8 +9,8 @@
   "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": "495933893df4df7b2b5e6942b23e279a8128dfa1aaf4d80fb656da52356b8e3b",
+  "rigforge_integration_patch_sha256": "662124563f591460607a9c76a9f5d8afc39ddb85cf1a44d9d469fc73bf35fac3",
   "license": "AGPL-3.0-or-later",
   "rigforge_pipewire_helper": "build/arm64/mod_ui_pipewire.py",
-  "rigforge_pipewire_helper_sha256": "f95fd65e0a7352dc90a178b3afbce084a95db583b3ee67a7472afaebbc0d74e2"
+  "rigforge_pipewire_helper_sha256": "749ba23c5f8417e4fc449786c15db5a72562d0cc739c54c25816252c627dd78e"
 }

+ 32 - 2
build/arm64/mod_ui_pipewire.py

@@ -15,16 +15,46 @@ def boundary_connection(
     capture_symbol = port_from.rsplit("/", 1)[-1]
     capture_port = capture_ports.get(capture_symbol)
     if capture_port:
-        return capture_port, resolve_host_port(port_to)
+        host_port = resolve_host_port(port_to)
+        if host_port:
+            return capture_port, host_port
+        return None
 
     playback_symbol = port_to.rsplit("/", 1)[-1]
     playback_port = playback_ports.get(playback_symbol)
     if playback_port:
-        return resolve_host_port(port_from), playback_port
+        host_port = resolve_host_port(port_from)
+        if host_port:
+            return host_port, playback_port
+        return None
 
     return None
 
 
+def resolve_pedalboard_port(port, resolve_host_port):
+    """Resolve Ingen-style graph ports and LV2 effect_N aliases for pw-link."""
+    graph_path = port.removeprefix("/graph/")
+    if "/" not in graph_path:
+        return resolve_host_port(port)
+    instance, symbol = graph_path.split("/", 1)
+    effect_index = {
+        "rigforge_voice_high_pass": 2,
+        "rigforge_voice_compressor": 3,
+        "rigforge_voice_de_esser": 4,
+        "rigforge_voice_reverb": 5,
+    }.get(instance)
+    if effect_index is None:
+        return resolve_host_port(port)
+    effect_ports = {
+        "rigforge_voice_high_pass": {"in": "in", "out": "out"},
+        "rigforge_voice_compressor": {"in": "in", "out": "out"},
+        "rigforge_voice_de_esser": {"in": "in", "out": "out"},
+        "rigforge_voice_reverb": {"input_l": "input_l", "output_l": "output_l"},
+    }
+    resolved_symbol = effect_ports.get(instance, {}).get(symbol)
+    return f"effect_{effect_index}:{resolved_symbol}" if resolved_symbol else None
+
+
 def _link_status(source, destination, runner):
     try:
         result = runner(

+ 4 - 0
build/arm64/patch_mod_ui_rigforge.py

@@ -188,6 +188,7 @@ def apply(source_root):
                 logging.error("[host] backend failed to connect ports: '%s' => '%s'", port_from, port_to)
 
         self.send_modified("connect %s %s" % (self._fix_host_connection_port(port_from),
+            self._fix_host_connection_port(port_to)), host_callback)
 ''',
         '''        pipewire_link = self._rigforge_pipewire_boundary(port_from, port_to)
         if pipewire_link is not None:
@@ -213,6 +214,7 @@ def apply(source_root):
                 logging.error("[host] backend failed to connect ports: '%s' => '%s'", port_from, port_to)
 
         self.send_modified("connect %s %s" % (self._fix_host_connection_port(port_from),
+            self._fix_host_connection_port(port_to)), host_callback)
 ''',
     )
     replace_once(
@@ -376,6 +378,7 @@ def apply(source_root):
                 logging.error("[host] backend failed to connect ports: '%s' => '%s'", port_from, port_to)
 
         self.send_modified("connect %s %s" % (self._fix_host_connection_port(port_from),
+            self._fix_host_connection_port(port_to)), host_callback)
 ''',
         '''        pipewire_link = self._rigforge_pipewire_boundary(port_from, port_to)
         if pipewire_link is not None:
@@ -401,6 +404,7 @@ def apply(source_root):
                 logging.error("[host] backend failed to connect ports: '%s' => '%s'", port_from, port_to)
 
         self.send_modified("connect %s %s" % (self._fix_host_connection_port(port_from),
+            self._fix_host_connection_port(port_to)), host_callback)
 ''',
     )
     replace_once(

+ 63 - 0
config/desired-state.yaml

@@ -291,6 +291,69 @@ routing:
           asset_path: amp_emul/cabinet/VOX_AC30_1964/VOX_AC30_1964_celestion.wav
           input_port: effect_1:in
           output_port: effect_1:out
+    voice:
+      physical_input_port: alsa_input.hw_U192k_0:capture_AUX2
+      source_port: rigforge.mod-host-input.capture:capture_AUX2
+      pipewire_input_port: rigforge.mod-host-input:playback_AUX2
+      pipewire_output_port: rigforge.mod-host-output:capture_AUX2
+      mod_ui_input_port: capture_3
+      mod_ui_output_port: playback_3
+      processors:
+        - id: voice-high-pass
+          instance: 2
+          plugin_uri: http://lsp-plug.in/plugins/lv2/filter_mono
+          mod_ui_instance: /graph/rigforge_voice_high_pass
+          bundle_path: .lv2/lsp-plugins.lv2
+          input_port: effect_2:in
+          output_port: effect_2:out
+          parameters:
+            mode: 0
+            filter_type: 1
+            filter_mode: 2
+            slope: 1
+            frequency_hz: 90.0
+            quality: 0.707
+        - id: voice-compressor
+          instance: 3
+          plugin_uri: http://lsp-plug.in/plugins/lv2/compressor_mono
+          mod_ui_instance: /graph/rigforge_voice_compressor
+          bundle_path: .lv2/lsp-plugins.lv2
+          input_port: effect_3:in
+          output_port: effect_3:out
+          parameters:
+            compression_mode: 0
+            ratio: 3.0
+            attack_time_ms: 10.0
+            release_time_ms: 120.0
+        - id: voice-de-esser
+          instance: 4
+          plugin_uri: http://lsp-plug.in/plugins/lv2/deesser_mono
+          mod_ui_instance: /graph/rigforge_voice_de_esser
+          bundle_path: .lv2/lsp-plugins.lv2
+          input_port: effect_4:in
+          output_port: effect_4:out
+          parameters:
+            ratio: 2.0
+            threshold: 0.1
+            attack_time_ms: 5.0
+            release_time_ms: 80.0
+            split_frequency_hz: 6000.0
+        - id: voice-reverb
+          instance: 5
+          plugin_uri: urn:dragonfly:room
+          mod_ui_instance: /graph/rigforge_voice_reverb
+          bundle_path: .lv2/DragonflyRoomReverb.lv2
+          input_port: effect_5:input_l
+          output_port: effect_5:output_l
+          parameters:
+            dry_level: 100.0
+            early_level: 10.0
+            late_level: 12.0
+            size: 12.0
+            predelay_ms: 8.0
+            decay_seconds: 0.6
+            in_low_cut_hz: 100.0
+            in_high_cut_hz: 12000.0
   looper_returns:
     destination: direct_mix
     feed_looper_inputs: false

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

@@ -16,7 +16,7 @@ Environment=MOD_DEVICE_WEBSERVER_PORT=@WEBSOCKET_PORT@
 Environment=MOD_RIGFORGE_CAPTURE_PORTS=@HARDWARE_INPUT_PORTS@
 Environment=MOD_RIGFORGE_PLAYBACK_PORTS=@HARDWARE_OUTPUT_PORTS@
 ExecStartPre=@PYTHON@ @BOOT_PREPARE_SCRIPT@ --state @DESIRED_STATE@ --runtime-dir %t/rigforge-mod-ui
-ExecStart=@PYTHON@ -u @RUNNER_SCRIPT@ --launcher @MOD_UI_LAUNCHER@ --pw-jack @PW_JACK@ --host @WEBSOCKET_HOST@ --port @WEBSOCKET_PORT@
+ExecStart=@PYTHON@ -u @RUNNER_SCRIPT@ --launcher @MOD_UI_LAUNCHER@ --pw-jack @PW_JACK@ --host @WEBSOCKET_HOST@ --port @WEBSOCKET_PORT@ --state @DESIRED_STATE@
 Restart=on-failure
 RestartSec=5
 TimeoutStopSec=10

+ 163 - 21
scripts/generate_mod_ui_pedalboard.py

@@ -25,20 +25,28 @@ def turtle_string(value):
 def plugin_state_files(processor, plugin_path):
     instance = processor["instance"]
     plugin_uri = processor["plugin_uri"]
-    file_property = processor["file_property"]
     state_dir = f"effect-{instance}"
-    effect_ttl = (
-        "@prefix atom: <http://lv2plug.in/ns/ext/atom#> .\n"
-        "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
-        "@prefix pset: <http://lv2plug.in/ns/ext/presets#> .\n"
-        "@prefix state: <http://lv2plug.in/ns/ext/state#> .\n\n"
-        "<>\n"
-        "    a pset:Preset ;\n"
-        f"    lv2:appliesTo <{plugin_uri}> ;\n"
-        "    state:state [\n"
-        f"        <{file_property}> {turtle_string(plugin_path)}^^atom:Path\n"
-        "    ] .\n"
-    )
+    if processor.get("file_property"):
+        effect_ttl = (
+            "@prefix atom: <http://lv2plug.in/ns/ext/atom#> .\n"
+            "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
+            "@prefix pset: <http://lv2plug.in/ns/ext/presets#> .\n"
+            "@prefix state: <http://lv2plug.in/ns/ext/state#> .\n\n"
+            "<>\n"
+            "    a pset:Preset ;\n"
+            f"    lv2:appliesTo <{plugin_uri}> ;\n"
+            "    state:state [\n"
+            f"        <{processor['file_property']}> {turtle_string(plugin_path)}^^atom:Path\n"
+            "    ] .\n"
+        )
+    else:
+        effect_ttl = (
+            "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
+            "@prefix pset: <http://lv2plug.in/ns/ext/presets#> .\n\n"
+            "<>\n"
+            "    a pset:Preset ;\n"
+            f"    lv2:appliesTo <{plugin_uri}> .\n"
+        )
     manifest_ttl = (
         "@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n"
         "@prefix pset: <http://lv2plug.in/ns/ext/presets#> .\n"
@@ -72,12 +80,17 @@ def generate_bundle_files(state, repo_root=ROOT, asset_root=None, nam_model_path
     asset_root = Path(asset_root or repo_root / "artifacts" / "mod-ui" / "arm64" / "current" / "app" / "default.pedalboard")
     routing = state["routing"]["mod_host_chains"]["guitar"]
     nam, ir = routing["processors"]
+    voice_chain = state["routing"]["mod_host_chains"]["voice"]
+    voice_processors = voice_chain["processors"]
     nam_source_path = resolved_asset(repo_root, nam["asset_path"])
     nam_path = Path(nam_model_path).resolve() if nam_model_path else nam_source_path
     if not nam_path.is_file():
         raise FileNotFoundError(f"NAM model file is missing: {nam_path}")
     ir_path = resolved_asset(repo_root, ir["asset_path"])
     output_level = nam["parameters"]["output_level"]
+    plugin_files = {}
+    for processor in voice_processors:
+        plugin_files.update(plugin_state_files(processor, ""))
 
     nam_instance = nam["mod_ui_instance"].removeprefix("/graph/")
     ir_instance = ir["mod_ui_instance"].removeprefix("/graph/")
@@ -93,7 +106,7 @@ def generate_bundle_files(state, repo_root=ROOT, asset_root=None, nam_model_path
     passthrough_channels = [
         (index, source_labels[source_id])
         for index, source_id in enumerate(("guitar", "bass", "voice", "synth"), start=1)
-        if source_id != "guitar" and source_id in source_ids
+        if source_id not in ("guitar", "voice") and source_id in source_ids
     ]
     additional_ports_ttl = "\n\n".join(
         f'''<capture_{index}>
@@ -111,19 +124,137 @@ def generate_bundle_files(state, repo_root=ROOT, asset_root=None, nam_model_path
     a lv2:AudioPort, lv2:OutputPort .'''
         for index, label in passthrough_channels
     )
-    additional_ports_list = ",\n             ".join(
-        f"<{symbol}_{index}>"
-        for index, _label in passthrough_channels
-        for symbol in ("capture", "playback")
-    )
     additional_arcs_list = ", ".join(
-        f"_:b{index + 2}" for index, _label in passthrough_channels
+        [f"_:b{index + 2}" for index, _label in passthrough_channels]
+        + [f"_:voice{index}" for index in range(1, len(voice_processors))]
+        + ["_:voice0", "_:voice_out"]
     )
     additional_arcs_ttl = "\n\n".join(
         f"_:b{index + 2} ingen:tail <capture_{index}> ;\n"
         f"      ingen:head <playback_{index}> ."
         for index, _label in passthrough_channels
     )
+    additional_ports_list = ",\n             ".join(
+        f"<{symbol}_{index}>"
+        for index, _label in passthrough_channels
+        for symbol in ("capture", "playback")
+    )
+    voice_processors_ttl = []
+    voice_processor_blocks = []
+    voice_processor_arcs = []
+    for index, processor in enumerate(voice_processors):
+        instance = processor["mod_ui_instance"].removeprefix("/graph/")
+        plugin_uri = processor["plugin_uri"]
+        if processor["id"] == "voice-reverb":
+            plugin_uri = "urn:dragonfly:room"
+        input_symbol = "input_l" if processor["id"] == "voice-reverb" else "in"
+        output_symbol = "output_l" if processor["id"] == "voice-reverb" else "out"
+        label = {
+            "voice-high-pass": "Coupe-bas",
+            "voice-compressor": "Compresseur voix",
+            "voice-de-esser": "De-esser",
+            "voice-reverb": "Réverbération voix",
+        }[processor["id"]]
+        x_position = 160.0 + index * 260.0
+        port_symbols = {
+            "voice-high-pass": ("in", "out", {"mode": "mode", "filter_type": "ft", "filter_mode": "fm", "slope": "s", "frequency_hz": "f", "quality": "q"}),
+            "voice-compressor": ("in", "out", {"compression_mode": "cm", "ratio": "cr", "attack_time_ms": "at", "release_time_ms": "rt"}),
+            "voice-de-esser": ("in", "out", {}),
+        "voice-reverb": ("input_l", "output_l", {"dry_level": "dry_level", "early_level": "early_level", "late_level": "late_level", "size": "size", "predelay_ms": "predelay", "decay_seconds": "decay", "in_low_cut_hz": "in_low_cut", "in_high_cut_hz": "in_high_cut"}),
+        }
+        input_symbol, output_symbol, control_symbols = port_symbols[processor["id"]]
+        port_declarations = [
+            f"<{instance}/{input_symbol}>",
+            f"<{instance}/{output_symbol}>",
+            f"<{instance}/:bypass>",
+        ]
+        control_declarations = []
+        for parameter in processor.get("parameters", {}):
+            if processor["id"] == "voice-de-esser":
+                continue
+            symbol = control_symbols[parameter]
+            port_declarations.append(f"<{instance}/{symbol}>")
+            value = processor["parameters"][parameter]
+            if processor["id"] == "voice-high-pass":
+                value = {
+                    "mode": 0,
+                    "filter_type": 1,
+                    "filter_mode": 2,
+                    "slope": 1,
+                    "frequency_hz": 90.0,
+                    "quality": 0.707,
+                }[parameter]
+            elif processor["id"] == "voice-compressor":
+                value = {
+                    "compression_mode": 0,
+                    "ratio": 3.0,
+                    "attack_time_ms": 10.0,
+                    "release_time_ms": 120.0,
+                }[parameter]
+            rendered_value = json.dumps(value) if isinstance(value, str) else str(value)
+            control_declarations.append(
+                f"<{instance}/{symbol}>\n"
+                f"    ingen:value {rendered_value} ;\n"
+                "    a lv2:ControlPort, lv2:InputPort ."
+            )
+        if processor["id"] == "voice-de-esser":
+            values = {
+                "Ratio": 2.0,
+                "Threshold": 0.1,
+                "Attack": 5.0,
+                "Release": 80.0,
+                "Split": 6000.0,
+            }
+            for symbol, value in values.items():
+                port_declarations.append(f"<{instance}/{symbol}>")
+                control_declarations.append(
+                    f"<{instance}/{symbol}>\n"
+                    f"    ingen:value {value} ;\n"
+                    "    a lv2:ControlPort, lv2:InputPort ."
+                )
+        voice_processors_ttl.append(
+            f"""<{instance}>
+    ingen:canvasX {x_position} ;
+    ingen:canvasY 650.0 ;
+    ingen:enabled true ;
+    ingen:polyphonic false ;
+    pedal:instanceLabel "{label}" ;
+    pedal:instanceNumber {processor["instance"]} ;
+    pedal:performanceVisible true ;
+    pedal:performanceIndex {index + 2} ;
+    lv2:prototype <{plugin_uri}> ;
+    lv2:port {", ".join(port_declarations)} ;
+    a ingen:Block .
+
+<{instance}/{input_symbol}>
+    a lv2:AudioPort, lv2:InputPort .
+
+<{instance}/{output_symbol}>
+    a lv2:AudioPort, lv2:OutputPort .
+
+<{instance}/:bypass>
+    ingen:value 0 ;
+    a lv2:ControlPort, lv2:InputPort ."""
+        )
+        voice_processors_ttl[-1] += "\n\n" + "\n\n".join(control_declarations)
+        if index > 0:
+            previous = voice_processors[index - 1]
+            previous_instance = previous["mod_ui_instance"].removeprefix("/graph/")
+            previous_output = (
+                "output_l" if previous["id"] == "voice-reverb" else "out"
+            )
+            voice_processor_arcs.append(
+                f"_:voice{index} ingen:tail <{previous_instance}/{previous_output}> ;\n"
+                f"      ingen:head <{instance}/{input_symbol}> ."
+            )
+    voice_chain_ttl = "\n\n".join(voice_processors_ttl)
+    voice_chain_arcs_ttl = "\n\n".join(voice_processor_arcs)
+    first_voice = voice_processors[0]
+    last_voice = voice_processors[-1]
+    first_voice_instance = first_voice["mod_ui_instance"].removeprefix("/graph/")
+    last_voice_instance = last_voice["mod_ui_instance"].removeprefix("/graph/")
+    first_voice_input = "in"
+    last_voice_output = "output_l" if last_voice["id"] == "voice-reverb" else "out"
 
     ttl = f"""\
 @prefix atom:  <http://lv2plug.in/ns/ext/atom#> .
@@ -154,6 +285,8 @@ def generate_bundle_files(state, repo_root=ROOT, asset_root=None, nam_model_path
 
 {additional_ports_ttl}
 
+{voice_chain_ttl}
+
 <:bpb>
     ingen:value 4.0 ;
     lv2:index 0 ;
@@ -319,7 +452,7 @@ def generate_bundle_files(state, repo_root=ROOT, asset_root=None, nam_model_path
     pedal:version 1 ;
     ingen:polyphony 1 ;
     ingen:arc _:b1, _:b2, _:b3, {additional_arcs_list} ;
-    ingen:block <{nam_instance}>, <{ir_instance}> ;
+    ingen:block <{nam_instance}>, <{ir_instance}>, {", ".join(f"<{processor['mod_ui_instance'].removeprefix('/graph/')}>" for processor in voice_processors)} ;
     lv2:port <:bpb>, <:bpm>, <:rolling>,
              <control_in>, <control_out>,
              <capture_1>, <playback_1>,
@@ -337,6 +470,14 @@ _:b2 ingen:tail <{nam_instance}/output> ;
 _:b3 ingen:tail <{ir_instance}/out> ;
      ingen:head <playback_1> .
 
+_:voice0 ingen:tail <capture_3> ;
+        ingen:head <{first_voice_instance}/{first_voice_input}> .
+
+{voice_chain_arcs_ttl}
+
+_:voice_out ingen:tail <{last_voice_instance}/{last_voice_output}> ;
+            ingen:head <playback_3> .
+
 {additional_arcs_ttl}
 """
 
@@ -357,6 +498,7 @@ _:b3 ingen:tail <{ir_instance}/out> ;
     }
     files.update(plugin_state_files(nam, nam_path))
     files.update(plugin_state_files(ir, ir_path))
+    files.update(plugin_files)
     for image_name in ("screenshot.png", "thumbnail.png"):
         image = asset_root / image_name
         if not image.is_file():

+ 79 - 11
scripts/prepare_mod_ui_pedalboard.py

@@ -41,10 +41,11 @@ def validate_generated_bundle(files):
         "rigforge-guitar.ttl",
         "addressings.json",
         "snapshots.json",
-        "effect-0/manifest.ttl",
-        "effect-0/effect.ttl",
-        "effect-1/manifest.ttl",
-        "effect-1/effect.ttl",
+        *{
+            f"effect-{instance}/{filename}"
+            for instance in range(6)
+            for filename in ("manifest.ttl", "effect.ttl")
+        },
         "screenshot.png",
         "thumbnail.png",
     }
@@ -60,7 +61,15 @@ def validate_generated_bundle(files):
             "generated pedalboard contains empty files: " + ", ".join(empty)
         )
     graph = files["rigforge-guitar.ttl"].decode("utf-8")
-    if "pedal:Pedalboard" not in graph or "ingen:block <rigforge_nam>, <rigforge_ir>" not in graph:
+    if (
+        "pedal:Pedalboard" not in graph
+        or "rigforge_nam" not in graph
+        or "rigforge_ir" not in graph
+        or "rigforge_voice_high_pass" not in graph
+        or "rigforge_voice_compressor" not in graph
+        or "rigforge_voice_de_esser" not in graph
+        or "rigforge_voice_reverb" not in graph
+    ):
         raise RuntimeError("generated pedalboard graph is incomplete")
 
 
@@ -90,6 +99,34 @@ def validate_existing_default(directory):
         raise RuntimeError(f"default pedalboard graph is invalid: {directory}")
 
 
+def reference_bundle_for_state(state, repo_root, home):
+    config = state["deployment"]["mod_ui"]
+    nam = state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
+    nam_model_path = destination_under_home(
+        home,
+        Path(config["user_files_directory"])
+        / "NAM Models"
+        / "Rigforge"
+        / Path(nam["asset_path"]).name,
+    )
+    expected_files = generate_bundle_files(
+        state, repo_root=repo_root, nam_model_path=nam_model_path
+    )
+    reference_directory = destination_under_home(home, config["reference_directory"])
+    if reference_directory.is_dir() and not reference_directory.is_symlink():
+        for candidate in sorted(reference_directory.glob("rigforge-guitar-*.pedalboard")):
+            if not candidate.is_dir() or candidate.is_symlink():
+                continue
+            try:
+                files = read_bundle(candidate)
+                validate_generated_bundle(files)
+            except (OSError, RuntimeError):
+                continue
+            if files == expected_files:
+                return candidate
+    raise RuntimeError("prepared mod-ui reference bundle is unavailable")
+
+
 def next_backup_path(path, boot_id, backup_directory=None):
     parent = backup_directory or path.parent
     parent.mkdir(parents=True, exist_ok=True)
@@ -189,7 +226,31 @@ def prepare_pedalboard(state, repo_root, home, runtime_dir, boot_id):
 
     if marker.is_file() and marker.read_text(encoding="utf-8").strip() == boot_id:
         validate_existing_default(default_board)
-        print("mod-ui pedalboard already prepared during this boot; preserving session state")
+        if last_state.is_symlink():
+            raise RuntimeError(f"refusing to move a mod-ui state symlink: {last_state}")
+        if last_state.exists() and not last_state.is_file():
+            raise RuntimeError(f"mod-ui last-state path is not a file: {last_state}")
+        reference_bundle = reference_bundle_for_state(state, repo_root, home)
+        current_state = (
+            last_state.read_text(encoding="utf-8")
+            if last_state.is_file()
+            else None
+        )
+        expected_state = (
+            f'{{"bank":-2,"pedalboard":"{reference_bundle}","supportsDividers":true}}'
+        )
+        if current_state != expected_state:
+            if last_state.exists():
+                backup = next_backup_path(last_state, boot_id, backup_directory)
+                os.replace(last_state, backup)
+                print(f"Preserved previous mod-ui state at {backup}")
+            last_state.parent.mkdir(parents=True, exist_ok=True)
+            last_state.write_text(expected_state, encoding="utf-8")
+        else:
+            print(
+                "mod-ui pedalboard already prepared during this boot; "
+                "preserving current board"
+            )
         return
 
     nam = state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
@@ -209,7 +270,6 @@ def prepare_pedalboard(state, repo_root, home, runtime_dir, boot_id):
         Path(config["reference_directory"])
         / f"rigforge-guitar-{bundle_digest(files)[:16]}.pedalboard",
     )
-
     for path in (reference, default_board):
         if path.is_symlink():
             raise RuntimeError(f"refusing to replace a mod-ui symlink: {path}")
@@ -219,7 +279,6 @@ def prepare_pedalboard(state, repo_root, home, runtime_dir, boot_id):
         raise RuntimeError(f"refusing to move a mod-ui state symlink: {last_state}")
     if last_state.exists() and not last_state.is_file():
         raise RuntimeError(f"mod-ui last-state path is not a file: {last_state}")
-
     reference_files = (
         read_bundle(reference)
         if reference.exists()
@@ -240,10 +299,10 @@ def prepare_pedalboard(state, repo_root, home, runtime_dir, boot_id):
             backup = next_backup_path(default_board, boot_id, backup_directory)
             os.replace(default_board, backup)
             backups.append((default_board, backup))
+        last_state_backup = None
         if last_state.exists():
-            backup = next_backup_path(last_state, boot_id, backup_directory)
-            os.replace(last_state, backup)
-            backups.append((last_state, backup))
+            last_state_backup = next_backup_path(last_state, boot_id, backup_directory)
+            os.replace(last_state, last_state_backup)
 
         if staged_reference is not None:
             os.replace(staged_reference, reference)
@@ -251,8 +310,17 @@ def prepare_pedalboard(state, repo_root, home, runtime_dir, boot_id):
         os.replace(staged_default, default_board)
         installed.append(default_board)
         validate_existing_default(default_board)
+        if last_state_backup is not None:
+            print(f"Preserved previous mod-ui state at {last_state_backup}")
+        last_state.parent.mkdir(parents=True, exist_ok=True)
+        last_state.write_text(
+            f'{{"bank":-2,"pedalboard":"{reference}","supportsDividers":true}}',
+            encoding="utf-8",
+        )
         atomic_write_marker(marker, boot_id)
     except BaseException:
+        if last_state_backup is not None and last_state_backup.exists():
+            os.replace(last_state_backup, last_state)
         for path in reversed(installed):
             if path.is_dir() and not path.is_symlink():
                 shutil.rmtree(path)

+ 132 - 1
scripts/run_mod_ui_service.py

@@ -9,6 +9,8 @@ import sys
 import time
 from pathlib import Path
 
+import yaml
+
 from mod_ui_websocket import ModUiWebSocketClient
 from observe_pipewire import parse_pw_link_output
 
@@ -16,6 +18,60 @@ from observe_pipewire import parse_pw_link_output
 PIPEWIRE_BOUNDARY_TIMEOUT = 35
 
 
+def load_mod_ui_board_links(state_path):
+    state = yaml.safe_load(Path(state_path).read_text(encoding="utf-8"))
+    processors = state["routing"]["mod_host_chains"]["voice"]["processors"]
+    links = []
+    for index in range(1, len(processors)):
+        previous = processors[index - 1]
+        current = processors[index]
+        links.append(
+            (
+                f"/graph/{previous['mod_ui_instance'].removeprefix('/graph/')}/"
+                f"{previous['output_port'].split(':', 1)[1]}",
+                f"/graph/{current['mod_ui_instance'].removeprefix('/graph/')}/"
+                f"{current['input_port'].split(':', 1)[1]}",
+            )
+        )
+    links.append(
+        (
+            f"/graph/{processors[-1]['mod_ui_instance'].removeprefix('/graph/')}/"
+            f"{processors[-1]['output_port'].split(':', 1)[1]}",
+            "/graph/playback_3",
+        )
+    )
+    return tuple(links)
+
+
+def _resolve_host_alias(port):
+    graph_path = port.removeprefix("/graph/")
+    if "/" not in graph_path:
+        if graph_path.startswith("playback_"):
+            channel = int(graph_path.removeprefix("playback_"))
+            if 1 <= channel <= 4:
+                return (
+                    "rigforge.mod-host-output.playback:"
+                    f"playback_AUX{channel - 1}"
+                )
+            return port
+        if graph_path.startswith("capture_"):
+            channel = int(graph_path.removeprefix("capture_"))
+            if 1 <= channel <= 4:
+                return f"rigforge.mod-host-input.capture:capture_AUX{channel - 1}"
+            return port
+        return port
+    instance, symbol = graph_path.split("/", 1)
+    instance_indices = {
+        "rigforge_voice_high_pass": 2,
+        "rigforge_voice_compressor": 3,
+        "rigforge_voice_de_esser": 4,
+        "rigforge_voice_reverb": 5,
+    }
+    if instance in instance_indices:
+        return f"effect_{instance_indices[instance]}:{symbol}"
+    return port
+
+
 def guitar_boundary_links(capture_ports, playback_ports):
     captures = [port.strip() for port in capture_ports if port.strip()]
     playbacks = [port.strip() for port in playback_ports if port.strip()]
@@ -69,6 +125,56 @@ def wait_for_guitar_boundary_links(
         sleep(min(interval, remaining))
 
 
+def wait_for_graph_links(
+    expected,
+    resolve_host_port=lambda port: port,
+    runner=subprocess.run,
+    timeout=10,
+    interval=0.2,
+    clock=time.monotonic,
+    sleep=time.sleep,
+):
+    expected = tuple(
+        (
+            resolve_host_port(source),
+            resolve_host_port(destination),
+        )
+        for source, destination in expected
+    )
+    deadline = clock() + timeout
+    missing = list(expected)
+    last_error = None
+    while True:
+        try:
+            result = runner(
+                ["pw-link", "-l"],
+                check=False,
+                capture_output=True,
+                text=True,
+            )
+            if result.returncode == 0:
+                observed = parse_pw_link_output(result.stdout)
+                missing = [edge for edge in expected if edge not in observed]
+                if not missing:
+                    return
+                last_error = None
+            else:
+                last_error = f"pw-link exited with status {result.returncode}"
+        except (OSError, ValueError) as error:
+            last_error = str(error)
+
+        remaining = deadline - clock()
+        if remaining <= 0:
+            details = ", ".join(
+                f"{source} -> {destination}" for source, destination in missing
+            )
+            message = f"mod-ui did not restore declared pedalboard links: {details}"
+            if last_error:
+                message += f" ({last_error})"
+            raise RuntimeError(message)
+        sleep(min(interval, remaining))
+
+
 def run_service(
     launcher,
     pw_jack,
@@ -80,6 +186,7 @@ def run_service(
     capture_ports=(),
     playback_ports=(),
     pw_link_runner=subprocess.run,
+    state_path=None,
 ):
     process = popen([str(pw_jack), str(launcher)])
     stopping = [False]
@@ -105,16 +212,26 @@ def run_service(
                     )
                 time.sleep(0.25)
 
+        loading = False
+        loaded_board = False
         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 "):
+                if message and message.startswith("loading_start "):
+                    loading = True
+                    loaded_board = False
+                elif message and message.startswith("loading_end ") and loading:
+                    loaded_board = True
+                    loading = False
+                if loaded_board:
                     break
                 if time.monotonic() >= deadline:
                     raise RuntimeError("mod-ui did not finish loading a pedalboard before timeout")
+            if not loaded_board and not stopping[0]:
+                raise RuntimeError("mod-ui did not load its prepared Rigforge default pedalboard")
             if not stopping[0]:
                 print("Verifying mod-ui guitar PipeWire boundary links")
                 wait_for_guitar_boundary_links(
@@ -123,6 +240,14 @@ def run_service(
                     runner=pw_link_runner,
                     timeout=PIPEWIRE_BOUNDARY_TIMEOUT,
                 )
+                if state_path is not None:
+                    print("Verifying mod-ui voice chain links")
+                    wait_for_graph_links(
+                        load_mod_ui_board_links(state_path),
+                        resolve_host_port=_resolve_host_alias,
+                        runner=pw_link_runner,
+                        timeout=PIPEWIRE_BOUNDARY_TIMEOUT,
+                    )
             print("mod-ui pedalboard loaded; keeping its mod-host session active")
         while not stopping[0]:
             if process.poll() is not None:
@@ -149,6 +274,11 @@ def main(argv=None):
     parser.add_argument("--port", type=int, default=8888)
     parser.add_argument("--websocket-path", default="/websocket")
     parser.add_argument("--timeout", type=float, default=60)
+    parser.add_argument(
+        "--state",
+        type=Path,
+        default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
+    )
     args = parser.parse_args(argv)
     if not args.launcher.is_file():
         print(f"ERROR: mod-ui launcher is missing: {args.launcher}", file=sys.stderr)
@@ -166,6 +296,7 @@ def main(argv=None):
             args.timeout,
             capture_ports=os.environ.get("MOD_RIGFORGE_CAPTURE_PORTS", "").split(","),
             playback_ports=os.environ.get("MOD_RIGFORGE_PLAYBACK_PORTS", "").split(","),
+            state_path=args.state,
         )
     except (OSError, RuntimeError, ValueError) as error:
         print(f"ERROR: {error}", file=sys.stderr)

+ 88 - 2
scripts/validate_desired_state.py

@@ -17,8 +17,8 @@ def validate_mod_host_chain(routing, source_by_id):
     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")
+    if not isinstance(chains, dict) or set(chains) != {"guitar", "voice"}:
+        errors.append("routing.mod_host_chains must declare exactly the guitar and voice chains")
     chain = chains.get("guitar")
     if not isinstance(chain, dict):
         return errors + ["routing.mod_host_chains.guitar must be a mapping"]
@@ -168,6 +168,91 @@ def validate_mod_host_chain(routing, source_by_id):
     return errors
 
 
+def validate_voice_chain(routing, source_by_id):
+    errors = []
+    chains = routing.get("mod_host_chains")
+    chain = chains.get("voice") if isinstance(chains, dict) else None
+    if not isinstance(chain, dict):
+        return ["routing.mod_host_chains.voice must declare the microphone effects chain"]
+
+    voice = source_by_id.get("voice")
+    physical_input = voice.get("capture_port") if isinstance(voice, dict) else None
+    expected = {
+        "physical_input_port": physical_input,
+        "source_port": "rigforge.mod-host-input.capture:capture_AUX2",
+        "pipewire_input_port": "rigforge.mod-host-input:playback_AUX2",
+        "pipewire_output_port": "rigforge.mod-host-output:capture_AUX2",
+        "mod_ui_input_port": "capture_3",
+        "mod_ui_output_port": "playback_3",
+    }
+    for key, value in expected.items():
+        if chain.get(key) != value:
+            errors.append(f"routing.mod_host_chains.voice.{key} must be {value}")
+
+    processors = chain.get("processors")
+    required = (
+        ("voice-high-pass", 2, "http://lsp-plug.in/plugins/lv2/filter_mono", "effect_2:in", "effect_2:out"),
+        ("voice-compressor", 3, "http://lsp-plug.in/plugins/lv2/compressor_mono", "effect_3:in", "effect_3:out"),
+        ("voice-de-esser", 4, "http://lsp-plug.in/plugins/lv2/deesser_mono", "effect_4:in", "effect_4:out"),
+        ("voice-reverb", 5, "urn:dragonfly:room", "effect_5:input_l", "effect_5:output_l"),
+    )
+    if not isinstance(processors, list) or len(processors) != len(required):
+        return errors + ["routing.mod_host_chains.voice.processors must declare high-pass, compressor, de-esser, and reverb in order"]
+    processor_parameters = (
+        {"mode", "filter_type", "filter_mode", "slope", "frequency_hz", "quality"},
+        {"compression_mode", "ratio", "attack_time_ms", "release_time_ms"},
+        {"ratio", "threshold", "attack_time_ms", "release_time_ms", "split_frequency_hz"},
+        {"dry_level", "early_level", "late_level", "size", "predelay_ms", "decay_seconds", "in_low_cut_hz", "in_high_cut_hz"},
+    )
+    for index, (processor, expected_processor) in enumerate(zip(processors, required)):
+        location = f"routing.mod_host_chains.voice.processors[{index}]"
+        if not isinstance(processor, dict):
+            errors.append(f"{location} must be a mapping")
+            continue
+        processor_id, instance, plugin_uri, input_port, output_port = expected_processor
+        expected_instance = f"/graph/rigforge_voice_{processor_id.removeprefix('voice-').replace('-', '_')}"
+        expected_bundle = ".lv2/DragonflyRoomReverb.lv2" if index == 3 else ".lv2/lsp-plugins.lv2"
+        for key, value in {
+            "id": processor_id,
+            "instance": instance,
+            "plugin_uri": plugin_uri,
+            "mod_ui_instance": expected_instance,
+            "bundle_path": expected_bundle,
+            "input_port": input_port,
+            "output_port": output_port,
+        }.items():
+            if processor.get(key) != value:
+                errors.append(f"{location}.{key} must be {value}")
+        parameters = processor.get("parameters")
+        if not isinstance(parameters, dict):
+            errors.append(f"{location}.parameters must be a mapping")
+        elif set(parameters) != processor_parameters[index]:
+            errors.append(
+                f"{location}.parameters must declare exactly "
+                f"{sorted(processor_parameters[index])}"
+            )
+
+    if isinstance(processors[0], dict):
+        params = processors[0].get("parameters", {})
+        for key, value in {"mode": 0, "filter_type": 1, "filter_mode": 2}.items():
+            if params.get(key) != value:
+                errors.append(f"voice high-pass parameters.{key} must be {value}")
+        frequency = params.get("frequency_hz")
+        if not isinstance(frequency, (int, float)) or isinstance(frequency, bool) or not 50 <= frequency <= 150:
+            errors.append("voice high-pass frequency_hz must be between 50 and 150")
+    for index, name in ((1, "compressor"), (2, "de-esser")):
+        if isinstance(processors[index], dict):
+            ratio = processors[index].get("parameters", {}).get("ratio")
+            if not isinstance(ratio, (int, float)) or isinstance(ratio, bool) or not 1 <= ratio <= 10:
+                errors.append(f"voice {name} ratio must be between 1 and 10")
+    if isinstance(processors[3], dict):
+        params = processors[3].get("parameters", {})
+        dry, late = params.get("dry_level"), params.get("late_level")
+        if dry != 100.0 or not isinstance(late, (int, float)) or isinstance(late, bool) or not 0 <= late <= 30:
+            errors.append("voice reverb must retain full dry signal and keep late_level between 0 and 30")
+    return errors
+
+
 def validate_mod_host_channel_routes(state, source_by_id):
     errors = []
     deployment = state.get("deployment")
@@ -411,6 +496,7 @@ def validate_state(state):
         errors.append("routing.looper_returns.feed_looper_inputs must be false")
 
     errors.extend(validate_mod_host_chain(routing, source_by_id))
+    errors.extend(validate_voice_chain(routing, source_by_id))
     errors.extend(validate_mod_host_channel_routes(state, source_by_id))
     errors.extend(validate_additional_looper_routes(routing))
 

+ 1 - 1
tests/test_deploy.py

@@ -646,7 +646,7 @@ class DeploymentTests(unittest.TestCase):
             archive_urls,
             [
                 "https://github.com/jojolb/sooperlooper-mods/archive/refs/tags/"
-                "v1.7.9-mods.1-slweb.3.tar.gz"
+                "v1.7.9-mods.1-slweb.4.tar.gz"
             ],
         )
 

+ 20 - 0
tests/test_desired_state.py

@@ -166,6 +166,26 @@ class DesiredStateValidationTests(unittest.TestCase):
         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_voice_chain_declares_ordered_processing_and_safe_starting_values(self):
+        chain = self.state["routing"]["mod_host_chains"]["voice"]
+        self.assertEqual(
+            [processor["id"] for processor in chain["processors"]],
+            ["voice-high-pass", "voice-compressor", "voice-de-esser", "voice-reverb"],
+        )
+        self.assertEqual([processor["instance"] for processor in chain["processors"]], [2, 3, 4, 5])
+        self.assertEqual(chain["physical_input_port"], "alsa_input.hw_U192k_0:capture_AUX2")
+        self.assertEqual(chain["mod_ui_input_port"], "capture_3")
+        self.assertEqual(chain["mod_ui_output_port"], "playback_3")
+        self.assertEqual(validate_state(self.state), [])
+
+        state = copy.deepcopy(self.state)
+        state["routing"]["mod_host_chains"]["voice"]["processors"][0]["parameters"]["frequency_hz"] = 200
+        self.assertTrue(any("frequency_hz must be between 50 and 150" in error for error in validate_state(state)))
+
+        state = copy.deepcopy(self.state)
+        state["routing"]["mod_host_chains"]["voice"]["processors"][3]["parameters"]["dry_level"] = 0
+        self.assertTrue(any("retain full dry signal" in error for error in validate_state(state)))
+
     def test_mod_ui_boundary_channels_match_each_physical_input_and_source(self):
         for index, source_id in enumerate(("guitar", "bass", "voice", "synth"), start=1):
             source = next(item for item in self.state["sources"] if item["id"] == source_id)

+ 38 - 1
tests/test_mod_ui_pedalboard.py

@@ -48,6 +48,43 @@ class ModUiPedalboardTests(unittest.TestCase):
         self.assertIn("ingen:head <rigforge_nam/input>", ttl)
         self.assertIn("ingen:tail <rigforge_ir/out>", ttl)
         self.assertIn("ingen:head <playback_1>", ttl)
+        voice_chain = self.state["routing"]["mod_host_chains"]["voice"]
+        voice_processors = voice_chain["processors"]
+        self.assertIn("<rigforge_voice_high_pass>", ttl)
+        self.assertIn("<rigforge_voice_compressor>", ttl)
+        self.assertIn("<rigforge_voice_de_esser>", ttl)
+        self.assertIn("<rigforge_voice_reverb>", ttl)
+        self.assertIn('pedal:instanceLabel "Coupe-bas"', ttl)
+        self.assertIn('pedal:instanceLabel "Compresseur voix"', ttl)
+        self.assertIn('pedal:instanceLabel "De-esser"', ttl)
+        self.assertIn('pedal:instanceLabel "Réverbération voix"', ttl)
+        self.assertIn("ingen:tail <capture_3>", ttl)
+        self.assertIn("ingen:head <rigforge_voice_high_pass/in>", ttl)
+        self.assertIn(
+            "ingen:tail <rigforge_voice_high_pass/out>", ttl
+        )
+        self.assertIn(
+            "ingen:head <rigforge_voice_compressor/in>", ttl
+        )
+        self.assertIn(
+            "ingen:tail <rigforge_voice_de_esser/out>", ttl
+        )
+        self.assertIn(
+            "ingen:head <rigforge_voice_reverb/input_l>", ttl
+        )
+        self.assertIn("ingen:head <playback_3>", ttl)
+        for index, processor in enumerate(voice_processors):
+            instance = processor["mod_ui_instance"].removeprefix("/graph/")
+            self.assertIn(f"lv2:prototype <{processor['plugin_uri']}>", ttl)
+            if index:
+                previous = voice_processors[index - 1]
+                previous_instance = previous["mod_ui_instance"].removeprefix("/graph/")
+                previous_output = previous["output_port"].split(":", 1)[1]
+                input_symbol = processor["input_port"].split(":", 1)[1]
+                self.assertIn(
+                    f"ingen:tail <{previous_instance}/{previous_output}>", ttl
+                )
+                self.assertIn(f"ingen:head <{instance}/{input_symbol}>", ttl)
         nam = self.state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
         ir = self.state["routing"]["mod_host_chains"]["guitar"]["processors"][1]
         nam_state = files[f"effect-{nam['instance']}/effect.ttl"].decode("utf-8")
@@ -68,7 +105,7 @@ class ModUiPedalboardTests(unittest.TestCase):
                 "    ", "\t"
             ),
         )
-        for channel, label in ((2, "Basse"), (3, "Micro"), (4, "Synthé")):
+        for channel, label in ((2, "Basse"), (4, "Synthé")):
             self.assertIn(f'lv2:name "{label} - Entrée mod-ui"', ttl)
             self.assertIn(f'lv2:name "{label} - Sortie mod-ui"', ttl)
             self.assertIn(f"ingen:tail <capture_{channel}>", ttl)

+ 20 - 1
tests/test_mod_ui_pipewire.py

@@ -8,7 +8,12 @@ from types import SimpleNamespace
 ROOT = Path(__file__).resolve().parents[1]
 sys.path.insert(0, str(ROOT / "build" / "arm64"))
 
-from mod_ui_pipewire import boundary_connection, connect_link, disconnect_link
+from mod_ui_pipewire import (
+    boundary_connection,
+    connect_link,
+    disconnect_link,
+    resolve_pedalboard_port,
+)
 
 
 class FakePwLink:
@@ -132,6 +137,20 @@ class ModUiPipeWireTests(unittest.TestCase):
             )
         )
 
+    def test_resolves_microphone_effect_ports_to_mod_host_effect_aliases(self):
+        resolver = lambda port: port
+        for graph_port, expected in (
+            ("/graph/rigforge_voice_high_pass/in", "effect_2:in"),
+            ("/graph/rigforge_voice_compressor/out", "effect_3:out"),
+            ("/graph/rigforge_voice_de_esser/in", "effect_4:in"),
+            ("/graph/rigforge_voice_reverb/input_l", "effect_5:input_l"),
+        ):
+            self.assertEqual(resolve_pedalboard_port(graph_port, resolver), expected)
+        self.assertEqual(
+            resolve_pedalboard_port("/graph/rigforge_ir/out", resolver),
+            "/graph/rigforge_ir/out",
+        )
+
     def test_connect_retries_transient_startup_port_registration_failure(self):
         edge = (
             "rigforge.mod-host-input.capture:capture_AUX0",

+ 14 - 10
tests/test_prepare_mod_ui_pedalboard.py

@@ -64,7 +64,7 @@ class PrepareModUiPedalboardTests(unittest.TestCase):
         (self.default_board / "manifest.ttl").write_bytes(b"")
         self.last_state.parent.mkdir(parents=True, exist_ok=True)
         self.last_state.write_text(
-            '{"bank":0,"pedalboard":"/old/board"}\n', encoding="utf-8"
+            '{"bank":-2,"pedalboard":"","supportsDividers":true}', encoding="utf-8"
         )
 
         self.prepare("boot-one")
@@ -77,14 +77,15 @@ class PrepareModUiPedalboardTests(unittest.TestCase):
             / f"rigforge-guitar-{prepare.bundle_digest(files)[:16]}.pedalboard"
         )
         self.assertEqual(prepare.read_bundle(reference), files)
-        self.assertFalse(self.last_state.exists())
         self.assertEqual(
-            (
-                self.backup_directory
-                / (self.last_state.name + ".rigforge-boot-backup-boot-one")
-            ).read_text(encoding="utf-8"),
-            '{"bank":0,"pedalboard":"/old/board"}\n',
+            self.last_state.read_text(encoding="utf-8"),
+            f'{{"bank":-2,"pedalboard":"{reference}","supportsDividers":true}}',
         )
+        graph = files["rigforge-guitar.ttl"].decode("utf-8")
+        self.assertIn("<rigforge_voice_high_pass>", graph)
+        self.assertIn("<rigforge_voice_compressor>", graph)
+        self.assertIn("<rigforge_voice_de_esser>", graph)
+        self.assertIn("<rigforge_voice_reverb>", graph)
         self.assertTrue(
             (
                 self.backup_directory
@@ -102,14 +103,18 @@ class PrepareModUiPedalboardTests(unittest.TestCase):
         self.prepare("boot-one")
         graph = self.default_board / "rigforge-guitar.ttl"
         graph.write_bytes(graph.read_bytes() + b"\n# session edit\n")
-        self.last_state.write_text('{"bank":1,"pedalboard":"/session"}\n', encoding="utf-8")
 
         self.prepare("boot-one")
 
         self.assertIn(b"# session edit", graph.read_bytes())
+        expected_reference = (
+            self.home
+            / self.state["deployment"]["mod_ui"]["reference_directory"]
+            / f"rigforge-guitar-{prepare.bundle_digest(self.expected_files())[:16]}.pedalboard"
+        )
         self.assertEqual(
             self.last_state.read_text(encoding="utf-8"),
-            '{"bank":1,"pedalboard":"/session"}\n',
+            f'{{"bank":-2,"pedalboard":"{expected_reference}","supportsDividers":true}}',
         )
 
     def test_new_boot_repairs_reference_and_starts_from_clean_board(self):
@@ -142,7 +147,6 @@ class PrepareModUiPedalboardTests(unittest.TestCase):
             ).read_bytes(),
             b"session edit",
         )
-        self.assertFalse(self.last_state.exists())
 
     def test_legacy_sibling_backups_are_moved_out_of_mod_ui_scan_directory(self):
         legacy_paths = (

+ 85 - 0
tests/test_run_mod_ui_service.py

@@ -2,13 +2,17 @@ import sys
 import unittest
 from pathlib import Path
 from types import SimpleNamespace
+from unittest.mock import patch
 
 ROOT = Path(__file__).resolve().parents[1]
 sys.path.insert(0, str(ROOT / "scripts"))
 
 from run_mod_ui_service import (
+    _resolve_host_alias,
     guitar_boundary_links,
+    load_mod_ui_board_links,
     wait_for_guitar_boundary_links,
+    wait_for_graph_links,
 )
 
 
@@ -93,6 +97,87 @@ class ModUiStartupPipeWireTests(unittest.TestCase):
         with self.assertRaisesRegex(RuntimeError, "not configured"):
             guitar_boundary_links([], self.playbacks)
 
+    def test_voice_chain_links_resolve_to_actual_mod_host_ports(self):
+        links = load_mod_ui_board_links(
+            ROOT / "config" / "desired-state.yaml"
+        )
+        self.assertEqual(
+            links,
+            (
+                (
+                    "/graph/rigforge_voice_high_pass/out",
+                    "/graph/rigforge_voice_compressor/in",
+                ),
+                (
+                    "/graph/rigforge_voice_compressor/out",
+                    "/graph/rigforge_voice_de_esser/in",
+                ),
+                (
+                    "/graph/rigforge_voice_de_esser/out",
+                    "/graph/rigforge_voice_reverb/input_l",
+                ),
+                (
+                    "/graph/rigforge_voice_reverb/output_l",
+                    "/graph/playback_3",
+                ),
+            ),
+        )
+        self.assertEqual(
+            tuple(_resolve_host_alias(port) for edge in links for port in edge),
+            (
+                "effect_2:out",
+                "effect_3:in",
+                "effect_3:out",
+                "effect_4:in",
+                "effect_4:out",
+                "effect_5:input_l",
+                "effect_5:output_l",
+                "rigforge.mod-host-output.playback:playback_AUX2",
+            ),
+        )
+        wait_for_graph_links(
+            links,
+            _resolve_host_alias,
+            runner=lambda *_args, **_kwargs: SimpleNamespace(
+                returncode=0,
+                stdout=(
+                    "effect_2:out\n  |-> effect_3:in\n"
+                    "effect_3:out\n  |-> effect_4:in\n"
+                    "effect_4:out\n  |-> effect_5:input_l\n"
+                    f"effect_5:output_l\n  |-> {self.playbacks[2]}\n"
+                ),
+            ),
+            timeout=0,
+        )
+
+    def test_wait_for_voice_graph_links_reports_missing_edge(self):
+        runner = lambda *_args, **_kwargs: SimpleNamespace(
+            returncode=0,
+            stdout=(
+                f"effect_4:out\n  |-> effect_5:input_l\n"
+                f"effect_5:output_r\n  |-> {self.playbacks[2]}\n"
+            ),
+        )
+        with self.assertRaisesRegex(
+            RuntimeError,
+            "effect_5:output_l -> " + self.playbacks[2],
+        ):
+            wait_for_graph_links(
+                (
+                    (
+                        "/graph/rigforge_voice_de_esser/out",
+                        "/graph/rigforge_voice_reverb/input_l",
+                    ),
+                    (
+                        "/graph/rigforge_voice_reverb/output_l",
+                        "/graph/playback_3",
+                    ),
+                ),
+                resolve_host_port=_resolve_host_alias,
+                runner=runner,
+                timeout=0,
+            )
+
 
 if __name__ == "__main__":
     unittest.main()