浏览代码

robustify startup: missing modui border links

Johan Le Baut 1 周之前
父节点
当前提交
83cb653d22

+ 2 - 2
AGENTS.md

@@ -14,8 +14,8 @@ The current target is Debian GNU/Linux 13 on AArch64 with a Behringer UMC404HD 1
 - `scripts/observe_pipewire.py` validates the state and managed endpoint declarations, reads `pw-link -l`, and compares observed links against explicitly managed ports and links. Without `--reconcile-once`, it is read-only; one-shot reconciliation and the separately deployed timer create only declared missing links and remove only declared stale links.
 - `scripts/generate_mod_ui_pedalboard.py` builds the YAML-declared guitar NAM→IR chain and three direct-through source pairs; mod-ui owns plugin instances and internal cables after loading it.
 - `scripts/run_mod_host_ports.py` runs the paired four-channel PipeWire loopbacks which form stable mod-ui-visible input/output boundaries.
-- `scripts/prepare_mod_ui_pedalboard.py` regenerates and validates the canonical mod-ui bundle once per system boot, backs up mutable default/last-state data, and refuses to launch on an invalid board.
-- `scripts/run_mod_ui_service.py` launches mod-ui under `pw-jack` and holds a WebSocket session so the backend loads without a browser.
+- `scripts/prepare_mod_ui_pedalboard.py` regenerates and validates the canonical mod-ui bundle once per system boot, keeps backups outside mod-ui's scanned pedalboard directory, and refuses to launch on an invalid board.
+- `scripts/run_mod_ui_service.py` launches mod-ui under `pw-jack`, holds a WebSocket session, and verifies the guitar PipeWire boundary links before reporting ready.
 - `build/arm64/patch_mod_ui_rigforge.py` reapplies the local PipeWire-boundary mapping and acknowledged MIDI WebSocket command when rebuilding the pinned mod-ui artifact; keep it consistent with the tracked artifact changes.
 - `scripts/wait_mod_host_ports.py` waits for boundary and mixer endpoints before mod-host starts, avoiding startup races after PipeWire restarts.
 - `scripts/midi_action_bridge.py` retains ALSA Note On bindings and changes NAM files through mod-ui's WebSocket, never a second mod-host control connection.

+ 1 - 1
README.md

@@ -150,7 +150,7 @@ Remove the service with `./scripts/deploy.sh uninstall sooperlooper`.
 
 `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.
 
-On each system boot, `rigforge-mod-ui.service` now 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 to boot-ID-suffixed backups. 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. This startup 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` now 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. At readiness, the service waits for both guitar PipeWire boundary links; saved-board connection restoration retries briefly while mod-host plugin ports appear. These changes are covered by repository tests but have 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.
 

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

@@ -4403,7 +4403,7 @@ class Host(object):
                     continue
                 pipewire_link = self._rigforge_pipewire_boundary(port_from, port_to)
                 if pipewire_link is not None:
-                    if not connect_link(*pipewire_link):
+                    if not connect_link(*pipewire_link, retries=60, retry_interval=0.1):
                         logging.error(
                             "[host] PipeWire backend failed to restore ports: '%s' => '%s'",
                             pipewire_link[0], pipewire_link[1]

+ 23 - 11
artifacts/mod-ui/arm64/current/app/mod/rigforge_pipewire.py

@@ -1,6 +1,7 @@
 """PipeWire link helpers used by the Rigforge mod-ui host integration."""
 
 import subprocess
+import time
 
 
 def boundary_connection(
@@ -50,17 +51,28 @@ def _link_status(source, destination, runner):
     return False
 
 
-def connect_link(source, destination, runner=subprocess.run):
-    try:
-        result = runner(
-            ["pw-link", source, destination],
-            check=False,
-            capture_output=True,
-            text=True,
-        )
-    except OSError:
-        return False
-    return result.returncode == 0 or _link_status(source, destination, runner) is True
+def connect_link(
+    source,
+    destination,
+    runner=subprocess.run,
+    retries=0,
+    retry_interval=0.1,
+):
+    for attempt in range(retries + 1):
+        try:
+            result = runner(
+                ["pw-link", source, destination],
+                check=False,
+                capture_output=True,
+                text=True,
+            )
+        except OSError:
+            return False
+        if result.returncode == 0 or _link_status(source, destination, runner) is True:
+            return True
+        if attempt < retries:
+            time.sleep(retry_interval)
+    return False
 
 
 def disconnect_link(source, destination, runner=subprocess.run):

+ 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": "0a3dfb8cb69e9affaed5fb24169af36608d63e74b1fc2b3c8d980b07c2da2126",
+  "rigforge_integration_patch_sha256": "d2f8a85b8b73975cd78f37b4d0f9ebc5bc8f743d74aee1f66c7c5cb5215e9418",
   "license": "AGPL-3.0-or-later",
   "rigforge_pipewire_helper": "build/arm64/mod_ui_pipewire.py",
-  "rigforge_pipewire_helper_sha256": "4a4fad67ba2f62df2c98d12af371b74e148123cf8d72bae7ce3516ef655f59e1"
+  "rigforge_pipewire_helper_sha256": "f95fd65e0a7352dc90a178b3afbce084a95db583b3ee67a7472afaebbc0d74e2"
 }

+ 23 - 11
build/arm64/mod_ui_pipewire.py

@@ -1,6 +1,7 @@
 """PipeWire link helpers used by the Rigforge mod-ui host integration."""
 
 import subprocess
+import time
 
 
 def boundary_connection(
@@ -50,17 +51,28 @@ def _link_status(source, destination, runner):
     return False
 
 
-def connect_link(source, destination, runner=subprocess.run):
-    try:
-        result = runner(
-            ["pw-link", source, destination],
-            check=False,
-            capture_output=True,
-            text=True,
-        )
-    except OSError:
-        return False
-    return result.returncode == 0 or _link_status(source, destination, runner) is True
+def connect_link(
+    source,
+    destination,
+    runner=subprocess.run,
+    retries=0,
+    retry_interval=0.1,
+):
+    for attempt in range(retries + 1):
+        try:
+            result = runner(
+                ["pw-link", source, destination],
+                check=False,
+                capture_output=True,
+                text=True,
+            )
+        except OSError:
+            return False
+        if result.returncode == 0 or _link_status(source, destination, runner) is True:
+            return True
+        if attempt < retries:
+            time.sleep(retry_interval)
+    return False
 
 
 def disconnect_link(source, destination, runner=subprocess.run):

+ 1 - 20
build/arm64/patch_mod_ui_rigforge.py

@@ -252,7 +252,7 @@ def apply(source_root):
 ''',
         '''                pipewire_link = self._rigforge_pipewire_boundary(port_from, port_to)
                 if pipewire_link is not None:
-                    if not connect_link(*pipewire_link):
+                    if not connect_link(*pipewire_link, retries=60, retry_interval=0.1):
                         logging.error(
                             "[host] PipeWire backend failed to restore ports: '%s' => '%s'",
                             pipewire_link[0], pipewire_link[1]
@@ -365,25 +365,6 @@ def apply(source_root):
         def host_callback(ok):
 ''',
     )
-    replace_once(
-        app / "mod" / "host.py",
-        '''                self.send_notmodified("connect %s %s" % (port_from_2, port_to_2))
-                self.connections.append((port_from, port_to))
-''',
-        '''                pipewire_link = self._rigforge_pipewire_boundary(port_from, port_to)
-                if pipewire_link is not None:
-                    if not connect_link(*pipewire_link):
-                        logging.error(
-                            "[host] PipeWire backend failed to restore ports: '%s' => '%s'",
-                            pipewire_link[0], pipewire_link[1]
-                        )
-                        continue
-                else:
-                    self.send_notmodified("connect %s %s" % (port_from_2, port_to_2))
-                self.connections.append((port_from, port_to))
-''',
-    )
-
     replace_once(
         app / "mod" / "session.py",
         '''    # Set a plugin block position within the canvas

+ 50 - 4
scripts/prepare_mod_ui_pedalboard.py

@@ -90,8 +90,10 @@ def validate_existing_default(directory):
         raise RuntimeError(f"default pedalboard graph is invalid: {directory}")
 
 
-def next_backup_path(path, boot_id):
-    base = path.with_name(f"{path.name}.rigforge-boot-backup-{boot_id}")
+def next_backup_path(path, boot_id, backup_directory=None):
+    parent = backup_directory or path.parent
+    parent.mkdir(parents=True, exist_ok=True)
+    base = parent / f"{path.name}.rigforge-boot-backup-{boot_id}"
     candidate = base
     suffix = 2
     while candidate.exists() or candidate.is_symlink():
@@ -100,6 +102,44 @@ def next_backup_path(path, boot_id):
     return candidate
 
 
+def is_legacy_pedalboard_backup(path):
+    return (
+        path.name == "default.pedalboard.rigforge-backup"
+        or path.name.startswith("default.pedalboard.rigforge-reset-backup")
+        or path.name.startswith("default.pedalboard.rigforge-boot-backup-")
+    )
+
+
+def next_migrated_backup_path(backup_directory, original, boot_id):
+    candidate = backup_directory / original.name
+    if not candidate.exists() and not candidate.is_symlink():
+        return candidate
+    base = backup_directory / f"{original.name}.migrated-{boot_id}"
+    candidate = base
+    suffix = 2
+    while candidate.exists() or candidate.is_symlink():
+        candidate = backup_directory / f"{base.name}.{suffix}"
+        suffix += 1
+    return candidate
+
+
+def migrate_legacy_pedalboard_backups(pedalboards, backup_directory, boot_id):
+    if not pedalboards.is_dir() or pedalboards.is_symlink():
+        return
+    legacy = sorted(path for path in pedalboards.iterdir() if is_legacy_pedalboard_backup(path))
+    if not legacy:
+        return
+    backup_directory.mkdir(parents=True, exist_ok=True)
+    for path in legacy:
+        if path.is_symlink():
+            raise RuntimeError(f"refusing to migrate a symlinked pedalboard backup: {path}")
+        if not path.is_dir():
+            raise RuntimeError(f"legacy pedalboard backup is not a directory: {path}")
+        destination = next_migrated_backup_path(backup_directory, path, boot_id)
+        os.replace(path, destination)
+        print(f"Moved legacy mod-ui backup outside pedalboard scan path: {destination}")
+
+
 def write_staged_bundle(files, destination):
     destination.parent.mkdir(parents=True, exist_ok=True)
     staged = Path(
@@ -140,6 +180,12 @@ def prepare_pedalboard(state, repo_root, home, runtime_dir, boot_id):
         home, Path(config["pedalboards_directory"]) / "default.pedalboard"
     )
     last_state = destination_under_home(home, config["last_state_file"])
+    backup_directory = destination_under_home(
+        home, Path(config["last_state_file"]).parent / "boot-backups"
+    )
+    migrate_legacy_pedalboard_backups(
+        default_board.parent, backup_directory, boot_id
+    )
 
     if marker.is_file() and marker.read_text(encoding="utf-8").strip() == boot_id:
         validate_existing_default(default_board)
@@ -191,11 +237,11 @@ def prepare_pedalboard(state, repo_root, home, runtime_dir, boot_id):
             os.replace(reference, backup)
             backups.append((reference, backup))
         if default_board.exists():
-            backup = next_backup_path(default_board, boot_id)
+            backup = next_backup_path(default_board, boot_id, backup_directory)
             os.replace(default_board, backup)
             backups.append((default_board, backup))
         if last_state.exists():
-            backup = next_backup_path(last_state, boot_id)
+            backup = next_backup_path(last_state, boot_id, backup_directory)
             os.replace(last_state, backup)
             backups.append((last_state, backup))
 

+ 67 - 0
scripts/run_mod_ui_service.py

@@ -2,6 +2,7 @@
 """Run mod-ui under pw-jack and keep its mod-host session active."""
 
 import argparse
+import os
 import signal
 import subprocess
 import sys
@@ -9,6 +10,60 @@ import time
 from pathlib import Path
 
 from mod_ui_websocket import ModUiWebSocketClient
+from observe_pipewire import parse_pw_link_output
+
+
+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()]
+    if not captures or not playbacks:
+        raise RuntimeError("Rigforge guitar PipeWire boundary ports are not configured")
+    return (
+        (captures[0], "effect_0:input"),
+        ("effect_1:out", playbacks[0]),
+    )
+
+
+def wait_for_guitar_boundary_links(
+    capture_ports,
+    playback_ports,
+    runner=subprocess.run,
+    timeout=10,
+    interval=0.2,
+    clock=time.monotonic,
+    sleep=time.sleep,
+):
+    expected = guitar_boundary_links(capture_ports, playback_ports)
+    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 guitar PipeWire boundary links: {details}"
+            if last_error:
+                message += f" ({last_error})"
+            raise RuntimeError(message)
+        sleep(min(interval, remaining))
 
 
 def run_service(
@@ -19,6 +74,9 @@ def run_service(
     websocket_path,
     timeout,
     popen=subprocess.Popen,
+    capture_ports=(),
+    playback_ports=(),
+    pw_link_runner=subprocess.run,
 ):
     process = popen([str(pw_jack), str(launcher)])
     stopping = [False]
@@ -54,6 +112,13 @@ def run_service(
                     break
                 if time.monotonic() >= deadline:
                     raise RuntimeError("mod-ui did not finish loading a pedalboard before timeout")
+            if not stopping[0]:
+                print("Verifying mod-ui guitar PipeWire boundary links")
+                wait_for_guitar_boundary_links(
+                    capture_ports,
+                    playback_ports,
+                    runner=pw_link_runner,
+                )
             print("mod-ui pedalboard loaded; keeping its mod-host session active")
         while not stopping[0]:
             if process.poll() is not None:
@@ -95,6 +160,8 @@ def main(argv=None):
             args.port,
             args.websocket_path,
             args.timeout,
+            capture_ports=os.environ.get("MOD_RIGFORGE_CAPTURE_PORTS", "").split(","),
+            playback_ports=os.environ.get("MOD_RIGFORGE_PLAYBACK_PORTS", "").split(","),
         )
     except (OSError, RuntimeError, ValueError) as error:
         print(f"ERROR: {error}", file=sys.stderr)

+ 24 - 2
tests/test_mod_ui_pipewire.py

@@ -12,9 +12,10 @@ from mod_ui_pipewire import boundary_connection, connect_link, disconnect_link
 
 
 class FakePwLink:
-    def __init__(self, links=()):
+    def __init__(self, links=(), transient_failures=0):
         self.links = set(links)
         self.commands = []
+        self.transient_failures = transient_failures
 
     def __call__(self, command, **_kwargs):
         self.commands.append(command)
@@ -25,6 +26,11 @@ class FakePwLink:
             )
             return SimpleNamespace(returncode=0, stdout=output, stderr="")
         if len(command) == 3 and command[0] == "pw-link" and command[1] != "-d":
+            if self.transient_failures:
+                self.transient_failures -= 1
+                return SimpleNamespace(
+                    returncode=1, stdout="", stderr="port not registered yet"
+                )
             edge = (command[1], command[2])
             if edge in self.links:
                 return SimpleNamespace(returncode=1, stdout="", stderr="already linked")
@@ -122,9 +128,21 @@ class ModUiPipeWireTests(unittest.TestCase):
                 "rigforge.mod-host-input.capture:capture_AUX0",
                 "effect_0:input",
                 runner=fail_connect,
+                retries=0,
             )
         )
 
+    def test_connect_retries_transient_startup_port_registration_failure(self):
+        edge = (
+            "rigforge.mod-host-input.capture:capture_AUX0",
+            "effect_0:input",
+        )
+        runner = FakePwLink(transient_failures=3)
+
+        self.assertTrue(connect_link(*edge, runner=runner, retries=4, retry_interval=0))
+        self.assertIn(edge, runner.links)
+        self.assertEqual(runner.transient_failures, 0)
+
     def test_tracked_mod_ui_artifact_matches_its_rebuild_patch_and_provenance(self):
         artifact = ROOT / "artifacts/mod-ui/arm64/current"
         helper_source = (ROOT / "build/arm64/mod_ui_pipewire.py").read_bytes()
@@ -134,7 +152,11 @@ class ModUiPipeWireTests(unittest.TestCase):
 
         self.assertEqual(helper_artifact.read_bytes(), helper_source)
         self.assertIn("from mod.rigforge_pipewire import", host_source)
-        self.assertIn("connect_link(*pipewire_link)", host_source)
+        self.assertIn(
+            "connect_link(*pipewire_link, retries=60, retry_interval=0.1)",
+            host_source,
+        )
+        self.assertEqual(host_source.count("PipeWire backend failed to restore ports"), 1)
         self.assertIn("disconnect_link(*pipewire_link)", host_source)
         self.assertEqual(
             provenance["rigforge_integration_patch_sha256"],

+ 40 - 8
tests/test_prepare_mod_ui_pedalboard.py

@@ -38,6 +38,7 @@ class PrepareModUiPedalboardTests(unittest.TestCase):
             self.home / config["pedalboards_directory"] / "default.pedalboard"
         )
         self.last_state = self.home / config["last_state_file"]
+        self.backup_directory = self.last_state.parent / "boot-backups"
 
     def tearDown(self):
         self.temporary.cleanup()
@@ -78,15 +79,23 @@ class PrepareModUiPedalboardTests(unittest.TestCase):
         self.assertEqual(prepare.read_bundle(reference), files)
         self.assertFalse(self.last_state.exists())
         self.assertEqual(
-            (self.last_state.with_name(
-                self.last_state.name + ".rigforge-boot-backup-boot-one"
-            )).read_text(encoding="utf-8"),
+            (
+                self.backup_directory
+                / (self.last_state.name + ".rigforge-boot-backup-boot-one")
+            ).read_text(encoding="utf-8"),
             '{"bank":0,"pedalboard":"/old/board"}\n',
         )
         self.assertTrue(
-            (self.default_board.with_name(
+            (
+                self.backup_directory
+                / (self.default_board.name + ".rigforge-boot-backup-boot-one")
+                / "manifest.ttl"
+            ).exists()
+        )
+        self.assertFalse(
+            self.default_board.with_name(
                 self.default_board.name + ".rigforge-boot-backup-boot-one"
-            ) / "manifest.ttl").exists()
+            ).exists()
         )
 
     def test_repeated_start_same_boot_preserves_in_session_board_and_state(self):
@@ -126,13 +135,36 @@ class PrepareModUiPedalboardTests(unittest.TestCase):
             b"",
         )
         self.assertEqual(
-            (self.default_board.with_name(
-                self.default_board.name + ".rigforge-boot-backup-boot-two"
-            ) / "rigforge-guitar.ttl").read_bytes(),
+            (
+                self.backup_directory
+                / (self.default_board.name + ".rigforge-boot-backup-boot-two")
+                / "rigforge-guitar.ttl"
+            ).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 = (
+            self.default_board.with_name(
+                self.default_board.name + ".rigforge-boot-backup-previous"
+            ),
+            self.default_board.with_name(
+                self.default_board.name + ".rigforge-reset-backup.4"
+            ),
+        )
+        for legacy in legacy_paths:
+            legacy.mkdir(parents=True)
+            (legacy / "manifest.ttl").write_bytes(b"")
+
+        self.prepare("boot-one")
+
+        for legacy in legacy_paths:
+            self.assertFalse(legacy.exists())
+            self.assertTrue(
+                (self.backup_directory / legacy.name / "manifest.ttl").exists()
+            )
+
     def test_generation_failure_does_not_replace_board_or_last_state(self):
         self.model.unlink()
         self.default_board.mkdir(parents=True)

+ 98 - 0
tests/test_run_mod_ui_service.py

@@ -0,0 +1,98 @@
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+
+from run_mod_ui_service import (
+    guitar_boundary_links,
+    wait_for_guitar_boundary_links,
+)
+
+
+class ModUiStartupPipeWireTests(unittest.TestCase):
+    def setUp(self):
+        self.captures = [
+            "rigforge.mod-host-input.capture:capture_AUX0",
+            "rigforge.mod-host-input.capture:capture_AUX1",
+            "rigforge.mod-host-input.capture:capture_AUX2",
+            "rigforge.mod-host-input.capture:capture_AUX3",
+        ]
+        self.playbacks = [
+            "rigforge.mod-host-output.playback:playback_AUX0",
+            "rigforge.mod-host-output.playback:playback_AUX1",
+            "rigforge.mod-host-output.playback:playback_AUX2",
+            "rigforge.mod-host-output.playback:playback_AUX3",
+        ]
+
+    def test_checks_only_the_guitar_cable_boundaries(self):
+        self.assertEqual(
+            guitar_boundary_links(self.captures, self.playbacks),
+            (
+                (self.captures[0], "effect_0:input"),
+                ("effect_1:out", self.playbacks[0]),
+            ),
+        )
+
+    def test_waits_for_both_saved_guitar_boundary_links(self):
+        outputs = [
+            SimpleNamespace(
+                returncode=0,
+                stdout="effect_0:output\n  |-> effect_1:in\n",
+            ),
+            SimpleNamespace(
+                returncode=0,
+                stdout=(
+                    f"{self.captures[0]}\n  |-> effect_0:input\n"
+                    f"effect_1:out\n  |-> {self.playbacks[0]}\n"
+                ),
+            ),
+        ]
+        elapsed = [0.0]
+        commands = []
+
+        def runner(command, **_kwargs):
+            commands.append(command)
+            return outputs.pop(0)
+
+        def sleep(seconds):
+            elapsed[0] += seconds
+
+        wait_for_guitar_boundary_links(
+            self.captures,
+            self.playbacks,
+            runner=runner,
+            timeout=1,
+            interval=0.1,
+            clock=lambda: elapsed[0],
+            sleep=sleep,
+        )
+
+        self.assertEqual(len(commands), 2)
+        self.assertGreater(elapsed[0], 0)
+
+    def test_missing_boundary_link_fails_readiness_check(self):
+        runner = lambda *_args, **_kwargs: SimpleNamespace(
+            returncode=0,
+            stdout=f"{self.captures[0]}\n  |-> effect_0:input\n",
+        )
+
+        with self.assertRaisesRegex(
+            RuntimeError, "effect_1:out -> " + self.playbacks[0]
+        ):
+            wait_for_guitar_boundary_links(
+                self.captures,
+                self.playbacks,
+                runner=runner,
+                timeout=0,
+            )
+
+    def test_missing_port_configuration_is_rejected(self):
+        with self.assertRaisesRegex(RuntimeError, "not configured"):
+            guitar_boundary_links([], self.playbacks)
+
+
+if __name__ == "__main__":
+    unittest.main()