소스 검색

robust reboot with scripts/prepare_mod_ui_pedalboard.py

Johan Le Baut 1 주 전
부모
커밋
37e7d31a38
7개의 변경된 파일과 520개의 추가작업 그리고 5개의 파일을 삭제
  1. 2 1
      AGENTS.md
  2. 3 1
      README.md
  3. 1 0
      config/systemd/user/rigforge-mod-ui.service.in
  4. 69 3
      scripts/deploy.py
  5. 251 0
      scripts/prepare_mod_ui_pedalboard.py
  6. 39 0
      tests/test_deploy.py
  7. 155 0
      tests/test_prepare_mod_ui_pedalboard.py

+ 2 - 1
AGENTS.md

@@ -14,13 +14,14 @@ 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.
 - `build/arm64/patch_mod_ui_rigforge.py` reapplies the local PipeWire-boundary mapping and acknowledged MIDI WebSocket command when rebuilding the pinned mod-ui artifact; keep it consistent with the tracked artifact changes.
 - `scripts/wait_mod_host_ports.py` waits for boundary and mixer endpoints before mod-host starts, avoiding startup races after PipeWire restarts.
 - `scripts/midi_action_bridge.py` retains ALSA Note On bindings and changes NAM files through mod-ui's WebSocket, never a second mod-host control connection.
 - The old `scripts/configure_mod_host.py` is not used by the service architecture; do not reintroduce its direct plugin/link ownership alongside mod-ui.
 - `config/systemd/user/rigforge-pipewire-reconcile.service.in` and `.timer.in` define periodic reconciliation for the whole YAML-managed graph.
-- `config/systemd/user/rigforge-mod-host-ports.service.in`, `rigforge-mod-host.service.in`, and `rigforge-mod-ui.service.in` define the opt-in boundary, backend, and UI services.
+- `config/systemd/user/rigforge-mod-host-ports.service.in`, `rigforge-mod-host.service.in`, and `rigforge-mod-ui.service.in` define the opt-in boundary, backend, and UI services; mod-ui runs its clean-board preparation before launch.
 - `scripts/deploy.sh` dispatches scoped user-level install/uninstall/reload actions plus explicit `reset mod-ui` for YAML-declared services and bundles. Audio-host/UI targets and `reconcile` are opt-in, not part of `all`.
 - `tests/` contains Python `unittest` tests for state validation, observation/reconciliation, the generated pedalboard, MIDI WebSocket control, and simulated deployment operations. These validate repository-level invariants, not live audio behavior.
 - `config/sooperlooper/fcb1010.slb` is supplied controller configuration, pending target verification. No SooperLooper build definition or artifact is present.

+ 3 - 1
README.md

@@ -148,7 +148,9 @@ Remove the service with `./scripts/deploy.sh uninstall sooperlooper`.
 
 `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 then resumes its last saved board across restarts. `./scripts/deploy.sh reset mod-ui` explicitly restores the generated reference and backs up any prior default board and last-state file as adjacent `.rigforge-reset-backup` paths.
+`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.
 
 The mod-host unit runs `pw-jack mod-host -n -p 5555 -f 5556`; it no longer runs `configure_mod_host.py`. The mod-ui service starts under `pw-jack`, opens a persistent local WebSocket session so the board loads even before a browser connects, and is the sole control/feedback client for mod-host. Its boundary bridge maps four visible input/output pairs to PipeWire and applies only explicit UI Connect/Disconnect operations. Install the ARM64 artifacts, NAM/LSP bundles, and declared audio assets before activation. Sustained audio and recovery after a service restart still require on-target verification; external UMC/boundary/mixer/looper links remain observable by the graph observer.
 

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

@@ -15,6 +15,7 @@ Environment=MOD_DEFAULT_PEDALBOARD=@REFERENCE_PEDALBOARD@
 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@
 Restart=on-failure
 RestartSec=5

+ 69 - 3
scripts/deploy.py

@@ -1013,6 +1013,7 @@ def render_mod_ui_service(config):
     state_file = ROOT / "config" / "desired-state.yaml"
     launcher = ROOT / config["launcher"]
     runner_script = ROOT / config["runner_script"]
+    boot_prepare_script = ROOT / "scripts" / "prepare_mod_ui_pedalboard.py"
     service_template = ROOT / config["service_source"]
     with state_file.open(encoding="utf-8") as stream:
         state = yaml.safe_load(stream)
@@ -1038,6 +1039,7 @@ def render_mod_ui_service(config):
     for description, path in (
         ("mod-ui launcher", launcher),
         ("mod-ui service runner", runner_script),
+        ("mod-ui boot preparation script", boot_prepare_script),
         ("mod-ui service template", service_template),
     ):
         if not path.is_file():
@@ -1047,6 +1049,8 @@ def render_mod_ui_service(config):
     replacements = {
         "@PYTHON@": systemd_quote(config["python_path"]),
         "@RUNNER_SCRIPT@": systemd_quote(runner_script.resolve()),
+        "@BOOT_PREPARE_SCRIPT@": systemd_quote(boot_prepare_script.resolve()),
+        "@DESIRED_STATE@": systemd_quote(state_file.resolve()),
         "@MOD_UI_LAUNCHER@": systemd_quote(launcher.resolve()),
         "@PW_JACK@": systemd_quote(config["pw_jack_path"]),
         "@WEBSOCKET_HOST@": config["websocket_host"],
@@ -1068,6 +1072,7 @@ def render_mod_ui_service(config):
     runtime_digest = hashlib.sha256()
     runtime_digest.update(runtime_tree_sha256(artifact_root).encode("ascii"))
     runtime_digest.update(runner_script.read_bytes())
+    runtime_digest.update(boot_prepare_script.read_bytes())
     runtime_digest.update((ROOT / "scripts" / "mod_ui_websocket.py").read_bytes())
     runtime_digest.update((ROOT / "scripts" / "generate_mod_ui_pedalboard.py").read_bytes())
     for name, content_bytes in sorted(reference_files.items()):
@@ -1587,7 +1592,20 @@ def deploy_mod_ui(action, config, registry):
     unit = render_mod_ui_service(config)
     reference_sha256 = None
     if action != "uninstall":
-        reference_sha256 = prepare_mod_ui_reference_bundle(unit)
+        managed = registry.get("mod_ui", {})
+        reference_record = managed.get("reference_bundle", {})
+        trusted_reference_sha256 = None
+        if reference_record.get("destination") == str(unit["reference_bundle"]):
+            trusted_reference_sha256 = reference_record.get("installed_sha256")
+        reference_sha256 = prepare_mod_ui_reference_bundle(
+            unit, trusted_existing_sha256=trusted_reference_sha256
+        )
+        if "mod_ui" in registry:
+            registry["mod_ui"]["reference_bundle"] = {
+                "destination": str(unit["reference_bundle"]),
+                "installed_sha256": reference_sha256,
+            }
+            write_registry(registry)
     deploy_single_user_service(
         action,
         "mod_ui",
@@ -1617,7 +1635,18 @@ def next_reset_backup_path(path):
     return candidate
 
 
-def prepare_mod_ui_reference_bundle(unit):
+def next_mod_ui_reference_backup_path(destination):
+    base = destination.with_name(destination.name + ".rigforge-corrupt-backup")
+    candidate = base
+    suffix = 2
+    while candidate.exists() or candidate.is_symlink():
+        candidate = base.with_name(f"{base.name}.{suffix}")
+        suffix += 1
+    validate_user_destination(candidate)
+    return candidate
+
+
+def prepare_mod_ui_reference_bundle(unit, trusted_existing_sha256=None):
     destination = unit["reference_bundle"]
     files = unit["reference_files"]
     validate_user_destination(destination)
@@ -1631,7 +1660,35 @@ def prepare_mod_ui_reference_bundle(unit):
             if path.is_file():
                 current_files[path.relative_to(destination).as_posix()] = path.read_bytes()
         if current_files != files:
-            raise RuntimeError(f"generated mod-ui reference changed locally: {destination}")
+            current_sha256 = tree_sha256(destination)
+            if (
+                trusted_existing_sha256 is None
+                or current_sha256 != trusted_existing_sha256
+            ):
+                raise RuntimeError(f"generated mod-ui reference changed locally: {destination}")
+            destination.parent.mkdir(parents=True, exist_ok=True)
+            staged = Path(
+                tempfile.mkdtemp(prefix=f".{destination.name}.", dir=destination.parent)
+            )
+            try:
+                for relative, content in files.items():
+                    path = staged / relative
+                    path.parent.mkdir(parents=True, exist_ok=True)
+                    path.write_bytes(content)
+                if tree_sha256(staged) == current_sha256:
+                    raise RuntimeError(
+                        f"regenerated mod-ui reference unexpectedly matches corrupted data: {destination}"
+                    )
+                backup = next_mod_ui_reference_backup_path(destination)
+                os.replace(destination, backup)
+                try:
+                    os.replace(staged, destination)
+                except OSError:
+                    os.replace(backup, destination)
+                    raise
+            finally:
+                if staged.exists():
+                    shutil.rmtree(staged)
     else:
         destination.parent.mkdir(parents=True, exist_ok=True)
         staged = Path(tempfile.mkdtemp(prefix=f".{destination.name}.", dir=destination.parent))
@@ -1665,10 +1722,19 @@ def reset_mod_ui_reference(config, registry):
     reference_sha256 = reference_record.get("installed_sha256")
     if (
         reference_record.get("destination") != str(reference)
+        or reference.is_symlink()
         or not reference.is_dir()
         or tree_sha256(reference) != reference_sha256
     ):
         raise RuntimeError(f"managed mod-ui reference pedalboard changed locally: {reference}")
+    repaired_reference_sha256 = prepare_mod_ui_reference_bundle(
+        unit, trusted_existing_sha256=reference_sha256
+    )
+    if repaired_reference_sha256 != reference_sha256:
+        reference_record["installed_sha256"] = repaired_reference_sha256
+        managed["reference_bundle"] = reference_record
+        registry["mod_ui"] = managed
+        write_registry(registry)
     pedalboards = Path.home() / config["pedalboards_directory"]
     default_board = pedalboards / "default.pedalboard"
     last_state = Path.home() / config["last_state_file"]

+ 251 - 0
scripts/prepare_mod_ui_pedalboard.py

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

+ 39 - 0
tests/test_deploy.py

@@ -641,6 +641,9 @@ class DeploymentTests(unittest.TestCase):
 
         content = destination.read_text(encoding="utf-8")
         self.assertIn("run_mod_ui_service.py", content)
+        self.assertIn("prepare_mod_ui_pedalboard.py", content)
+        self.assertIn("ExecStartPre=", content)
+        self.assertIn("--runtime-dir %t/rigforge-mod-ui", content)
         self.assertIn("MOD_DEFAULT_PEDALBOARD=", content)
         self.assertIn("MOD_RIGFORGE_CAPTURE_PORTS=", content)
         self.assertIn("MOD_RIGFORGE_PLAYBACK_PORTS=", content)
@@ -718,6 +721,42 @@ class DeploymentTests(unittest.TestCase):
         with self.assertRaisesRegex(RuntimeError, "changed locally"):
             deploy.deploy_mod_ui("install", config, deploy.read_registry())
 
+    def test_mod_ui_install_repairs_registered_corrupt_reference_bundle(self):
+        config = deploy.load_deployment()["mod_ui"]
+        registry = {
+            "mod_host_ports": {},
+            "mod_host": {},
+        }
+        deploy.deploy_mod_ui("install", config, registry)
+        registry = deploy.read_registry()
+        reference = Path(registry["mod_ui"]["reference_bundle"]["destination"])
+        graph = reference / "rigforge-guitar.ttl"
+        graph.write_bytes(b"")
+        registry["mod_ui"]["reference_bundle"]["installed_sha256"] = deploy.tree_sha256(
+            reference
+        )
+        deploy.write_registry(registry)
+        self.commands.clear()
+
+        deploy.deploy_mod_ui("install", config, deploy.read_registry())
+
+        repaired_registry = deploy.read_registry()
+        repaired_reference = Path(
+            repaired_registry["mod_ui"]["reference_bundle"]["destination"]
+        )
+        self.assertGreater((repaired_reference / "rigforge-guitar.ttl").stat().st_size, 0)
+        corrupt_backup = repaired_reference.with_name(
+            repaired_reference.name + ".rigforge-corrupt-backup"
+        )
+        self.assertEqual(
+            (corrupt_backup / "rigforge-guitar.ttl").read_bytes(),
+            b"",
+        )
+        self.assertEqual(
+            repaired_registry["mod_ui"]["reference_bundle"]["installed_sha256"],
+            deploy.tree_sha256(repaired_reference),
+        )
+
     def test_mod_ui_reset_restores_reference_and_backs_up_user_state(self):
         registry = {
             "mod_host_ports": {},

+ 155 - 0
tests/test_prepare_mod_ui_pedalboard.py

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