Procházet zdrojové kódy

add lv2 lsp & reverb plugins

Johan Le Baut před 2 týdny
rodič
revize
7c2bdb23d6

+ 8 - 4
README.md

@@ -21,7 +21,7 @@ sudo apt update
 sudo apt upgrade
 sudo apt upgrade
 sudo apt install --no-install-recommends \\
 sudo apt install --no-install-recommends \\
   rtkit pipewire pipewire-jack wireplumber \\
   rtkit pipewire pipewire-jack wireplumber \\
-  libspa-0.2-modules liblo-tools git
+  libspa-0.2-modules liblo-tools git librubberband2
 ```
 ```
 
 
 This records the preparation already performed on `rigforge` and is a starting point for documenting a second Pi. It is not yet a verified, version-pinned rebuild procedure: package versions, additional runtime dependencies, audio configuration, and service setup still need to be confirmed before reusing it as a complete deployment recipe.
 This records the preparation already performed on `rigforge` and is a starting point for documenting a second Pi. It is not yet a verified, version-pinned rebuild procedure: package versions, additional runtime dependencies, audio configuration, and service setup still need to be confirmed before reusing it as a complete deployment recipe.
@@ -34,7 +34,7 @@ This records the preparation already performed on `rigforge` and is a starting p
 - `build/arm64/`: shared ARM64 build image and task scripts for SooperLooper and mod-host.
 - `build/arm64/`: shared ARM64 build image and task scripts for SooperLooper and mod-host.
 - `scripts/validate_desired_state.py`: validates topology and routing invariants without changing the target.
 - `scripts/validate_desired_state.py`: validates topology and routing invariants without changing the target.
 - `scripts/observe_pipewire.py`: read-only comparison by default, with explicit one-shot repair for declared missing links.
 - `scripts/observe_pipewire.py`: read-only comparison by default, with explicit one-shot repair for declared missing links.
-- `scripts/deploy.sh` and `scripts/deploy.py`: scoped user-level installation, removal, and reload of declared PipeWire and NAM LV2 files.
+- `scripts/deploy.sh` and `scripts/deploy.py`: scoped user-level installation, removal, and reload of declared PipeWire and LV2 plugin bundles.
 - `tests/`: unit tests for desired-state validation, PipeWire observation/reconciliation, and deployment operations.
 - `tests/`: unit tests for desired-state validation, PipeWire observation/reconciliation, and deployment operations.
 - `artifacts/sooperlooper/arm64/` and `artifacts/mod-host/arm64/`: generated binaries, runtime dependency reports, and build provenance; commit after reviewing licensing and repository size.
 - `artifacts/sooperlooper/arm64/` and `artifacts/mod-host/arm64/`: generated binaries, runtime dependency reports, and build provenance; commit after reviewing licensing and repository size.
 
 
@@ -106,16 +106,20 @@ After a manual `git pull --ff-only`, run the deploy helper from any directory:
 ```sh
 ```sh
 ~/rigforge/scripts/deploy.sh install pipewire
 ~/rigforge/scripts/deploy.sh install pipewire
 ~/rigforge/scripts/deploy.sh install namlv2
 ~/rigforge/scripts/deploy.sh install namlv2
+~/rigforge/scripts/deploy.sh install lsp
+~/rigforge/scripts/deploy.sh install dragonfly-reverb
 ~/rigforge/scripts/deploy.sh install all
 ~/rigforge/scripts/deploy.sh install all
 ```
 ```
 
 
-The helper accepts `install|uninstall|reload` and `all|namlv2|pipewire`. It reads versions, paths, URL, and quantum from `config/desired-state.yaml`; its deployment registry is stored under `~/.local/state/rigforge/`, and any pre-existing target backup is stored next to that target. It does not use `sudo` or change files outside the declared paths, adjacent backup paths, and registry directory.
+The helper accepts `install|uninstall|reload` and `all|namlv2|lsp|dragonfly-reverb|pipewire`. It reads versions, paths, URLs, and quantum from `config/desired-state.yaml`; its deployment registry is stored under `~/.local/state/rigforge/`, and any pre-existing target backup is stored next to that target. It does not use `sudo` or change files outside the declared paths, adjacent backup paths, and registry directory.
 
 
 For PipeWire, install updates only the Rigforge filter fragment, applies the declared quantum as a runtime setting, and restarts `filter-chain.service` only when the fragment changes. It never restarts `pipewire.service` or WirePlumber. `reload pipewire` reapplies the quantum and restarts the filter-chain user service. This restart removes the filter-chain nodes and their graph links; the fragment recreates ports but not links. The deploy helper deliberately does not reconcile links automatically. After a restart, first run `python3 scripts/observe_pipewire.py`; if declared links are missing, use `python3 scripts/observe_pipewire.py --reconcile-once` only during an appropriate safe test window, then observe again. Uninstall removes only the unchanged managed fragment, restores a file that was present before the first install, returns quantum selection to automatic, and reloads the filter service. Local edits to managed files stop removal or replacement rather than being discarded. Runtime quantum is not persistent across a PipeWire daemon restart.
 For PipeWire, install updates only the Rigforge filter fragment, applies the declared quantum as a runtime setting, and restarts `filter-chain.service` only when the fragment changes. It never restarts `pipewire.service` or WirePlumber. `reload pipewire` reapplies the quantum and restarts the filter-chain user service. This restart removes the filter-chain nodes and their graph links; the fragment recreates ports but not links. The deploy helper deliberately does not reconcile links automatically. After a restart, first run `python3 scripts/observe_pipewire.py`; if declared links are missing, use `python3 scripts/observe_pipewire.py --reconcile-once` only during an appropriate safe test window, then observe again. Uninstall removes only the unchanged managed fragment, restores a file that was present before the first install, returns quantum selection to automatic, and reloads the filter service. Local edits to managed files stop removal or replacement rather than being discarded. Runtime quantum is not persistent across a PipeWire daemon restart.
 
 
 For NAM LV2, install downloads the declared Raspberry Pi 5 archive with `curl`, checks the archive structure, extracts the `neural_amp_modeler.lv2` bundle under `~/.lv2/`, and records the archive SHA-256 and managed bundle fingerprint. This is a locally computed identity hash, not an independent publisher checksum. An existing same-name bundle is preserved for uninstall; locally modified managed bundles are not overwritten or removed. `reload namlv2` intentionally does nothing because no LV2 host is declared; restart the eventual host after installing or removing the plugin. On the target, tag `v0.2.3` was installed at `~/.lv2/neural_amp_modeler.lv2`; the observed contents were `manifest.ttl`, `modgui/`, `modgui.ttl`, `neural_amp_modeler.so`, and `neural_amp_modeler.ttl`. `reload namlv2` printed the expected no-op message. The downloaded archive SHA-256 was `80d1a711d573afb7323cbf2ea1a79e39386e58ba449d076c5d89e10b50de3212`; this is an identity hash only, not a publisher checksum. Host discovery, runtime dependencies, compatibility, and plugin operation remain unverified. The release archive is fetched at install time and is not committed to this repository.
 For NAM LV2, install downloads the declared Raspberry Pi 5 archive with `curl`, checks the archive structure, extracts the `neural_amp_modeler.lv2` bundle under `~/.lv2/`, and records the archive SHA-256 and managed bundle fingerprint. This is a locally computed identity hash, not an independent publisher checksum. An existing same-name bundle is preserved for uninstall; locally modified managed bundles are not overwritten or removed. `reload namlv2` intentionally does nothing because no LV2 host is declared; restart the eventual host after installing or removing the plugin. On the target, tag `v0.2.3` was installed at `~/.lv2/neural_amp_modeler.lv2`; the observed contents were `manifest.ttl`, `modgui/`, `modgui.ttl`, `neural_amp_modeler.so`, and `neural_amp_modeler.ttl`. `reload namlv2` printed the expected no-op message. The downloaded archive SHA-256 was `80d1a711d573afb7323cbf2ea1a79e39386e58ba449d076c5d89e10b50de3212`; this is an identity hash only, not a publisher checksum. Host discovery, runtime dependencies, compatibility, and plugin operation remain unverified. The release archive is fetched at install time and is not committed to this repository.
 
 
-On the target, `install pipewire` applied quantum 128 and reported that the installed fragment was already current; the following observer reported no differences. A later `reload pipewire` applied the quantum and restarted the filter-chain service, after which observation found all three managed links missing. One-shot reconciliation requested each link, and the subsequent observer reported `differences: []`. This confirms the graph links were present after reconciliation, not that audio was audible. `install all` and `uninstall all` attempt both targets and report an overall failure if either action fails. `reload all` restarts the filter-chain service and prints the NAM no-op message. Check the target afterwards with `python3 scripts/validate_desired_state.py`, `python3 -m unittest discover -s tests -v`, and `python3 scripts/observe_pipewire.py`.
+For LSP and Dragonfly Reverb, the YAML declares tags and release URLs, and the installer places only LV2 bundles in `~/.lv2/`. LSP installs `lsp-plugins.lv2`; Dragonfly installs its Early Reflections, Hall, Plate, and Room Reverb bundles. LSP extraction requires `7z`, `7zz`, or `7za` on `PATH`, with support for the compression methods used in the release; install or update that system package separately if needed. A listing or extraction error aborts the install before any bundle is changed. The installers hash archives for identity tracking, check archive paths and expected manifests, preserve existing same-name bundles for uninstall, and refuse to remove locally modified managed bundles. `reload lsp` and `reload dragonfly-reverb` do not restart an LV2 host; restart the host after installation or removal. The release bundle layouts were checked, but the plugins and runtime dependencies have not been tested on the target.
+
+On the target, `install pipewire` applied quantum 128 and reported that the installed fragment was already current; the following observer reported no differences. A later `reload pipewire` applied the quantum and restarted the filter-chain service, after which observation found all three managed links missing. One-shot reconciliation requested each link, and the subsequent observer reported `differences: []`. This confirms the graph links were present after reconciliation, not that audio was audible. `install all` and `uninstall all` attempt all four targets and report an overall failure if any action fails. `reload all` restarts the filter-chain service and prints no-op messages for the LV2 plugins. Check the target afterwards with `python3 scripts/validate_desired_state.py`, `python3 -m unittest discover -s tests -v`, and `python3 scripts/observe_pipewire.py`.
 
 
 ## Development PC
 ## Development PC
 
 

+ 15 - 0
config/desired-state.yaml

@@ -38,6 +38,21 @@ deployment:
     tag: v0.2.3
     tag: v0.2.3
     archive_url: https://github.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/v0.2.3/neural_amp_modeler_lv2_rpi5.tgz
     archive_url: https://github.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/v0.2.3/neural_amp_modeler_lv2_rpi5.tgz
     bundle_directory: neural_amp_modeler.lv2
     bundle_directory: neural_amp_modeler.lv2
+  lsp:
+    tag: "1.2.37"
+    archive_url: https://github.com/lsp-plugins/lsp-plugins/releases/download/1.2.37/lsp-plugins-1.2.37-Linux-aarch64.7z
+    archive_format: 7z
+    bundle_paths:
+      lsp-plugins.lv2: lsp-plugins-1.2.37-Linux-aarch64/LV2/lsp-plugins.lv2
+  dragonfly_reverb:
+    tag: "3.2.10"
+    archive_url: https://github.com/michaelwillis/dragonfly-reverb/releases/download/3.2.10/dragonfly-reverb-3.2.10-linux-arm64.tar.xz
+    archive_format: tar.xz
+    bundle_paths:
+      DragonflyEarlyReflections.lv2: dragonfly-reverb-3.2.10/DragonflyEarlyReflections.lv2
+      DragonflyHallReverb.lv2: dragonfly-reverb-3.2.10/DragonflyHallReverb.lv2
+      DragonflyPlateReverb.lv2: dragonfly-reverb-3.2.10/DragonflyPlateReverb.lv2
+      DragonflyRoomReverb.lv2: dragonfly-reverb-3.2.10/DragonflyRoomReverb.lv2
   sooperlooper:
   sooperlooper:
     source_url: https://github.com/abarker/sooperlooper-mods
     source_url: https://github.com/abarker/sooperlooper-mods
     tag: v1.7.9-mods.1
     tag: v1.7.9-mods.1

+ 336 - 2
scripts/deploy.py

@@ -21,6 +21,10 @@ NAM_RELEASE_ASSET = re.compile(
     r"^https://github\.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/"
     r"^https://github\.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/"
     r"(?P<tag>[A-Za-z0-9._-]+)/neural_amp_modeler_lv2_rpi5\.tgz$"
     r"(?P<tag>[A-Za-z0-9._-]+)/neural_amp_modeler_lv2_rpi5\.tgz$"
 )
 )
+PLUGIN_ARCHIVES = {
+    "lsp": "7z",
+    "dragonfly_reverb": "tar.xz",
+}
 
 
 
 
 def load_deployment():
 def load_deployment():
@@ -34,6 +38,14 @@ def load_deployment():
     pipewire = deployment.get("pipewire")
     pipewire = deployment.get("pipewire")
     if not isinstance(namlv2, dict) or not isinstance(pipewire, dict):
     if not isinstance(namlv2, dict) or not isinstance(pipewire, dict):
         raise ValueError("deployment.namlv2 and deployment.pipewire must be mappings")
         raise ValueError("deployment.namlv2 and deployment.pipewire must be mappings")
+    for component, archive_format in PLUGIN_ARCHIVES.items():
+        plugin = deployment.get(component)
+        if not isinstance(plugin, dict):
+            raise ValueError(f"deployment.{component} must be a mapping")
+        if plugin.get("archive_format") != archive_format:
+            errors.append(f"{component} archive format is invalid")
+        if not isinstance(plugin.get("bundle_paths"), dict) or not plugin["bundle_paths"]:
+            errors.append(f"{component} bundle paths are invalid")
     tag = namlv2.get("tag")
     tag = namlv2.get("tag")
     match = NAM_RELEASE_ASSET.fullmatch(namlv2.get("archive_url", ""))
     match = NAM_RELEASE_ASSET.fullmatch(namlv2.get("archive_url", ""))
     if not isinstance(tag, str) or not re.fullmatch(r"[A-Za-z0-9._-]+", tag):
     if not isinstance(tag, str) or not re.fullmatch(r"[A-Za-z0-9._-]+", tag):
@@ -321,6 +333,325 @@ def download_archive(url, destination):
     run(["curl", "--fail", "--location", "--silent", "--show-error", "--output", str(destination), url])
     run(["curl", "--fail", "--location", "--silent", "--show-error", "--output", str(destination), url])
 
 
 
 
+def inspect_tar_archive(archive_path, bundle_paths):
+    expected_roots = {PurePosixPath(path) for path in bundle_paths.values()}
+    with tarfile.open(archive_path, "r:xz") as archive:
+        members = archive.getmembers()
+        for member in members:
+            member_path = PurePosixPath(member.name)
+            if member_path.is_absolute() or ".." in member_path.parts:
+                raise RuntimeError(f"unsafe archive path: {member.name}")
+            if not member.isfile() and not member.isdir():
+                raise RuntimeError(f"unsupported archive member type: {member.name}")
+        for bundle_root in expected_roots:
+            if not any(member.name.rstrip("/") == str(bundle_root) and member.isdir() for member in members):
+                raise RuntimeError(f"archive does not contain expected bundle directory {bundle_root}")
+            if not any(member.name == f"{bundle_root}/manifest.ttl" and member.isfile() for member in members):
+                raise RuntimeError(f"archive bundle is missing manifest.ttl: {bundle_root}")
+    return expected_roots
+
+
+def extract_tar_bundles(archive_path, bundle_paths, extraction_root):
+    expected_roots = inspect_tar_archive(archive_path, bundle_paths)
+    extracted = {bundle_name: extraction_root / bundle_name for bundle_name in bundle_paths}
+    with tarfile.open(archive_path, "r:xz") as archive:
+        for member in archive.getmembers():
+            member_path = PurePosixPath(member.name)
+            bundle_root = next(
+                (root for root in expected_roots if member_path == root or member_path.is_relative_to(root)),
+                None,
+            )
+            if bundle_root is None:
+                continue
+            bundle_name = next(name for name, path in bundle_paths.items() if PurePosixPath(path) == bundle_root)
+            output_path = extracted[bundle_name].joinpath(*member_path.parts[len(bundle_root.parts):])
+            if member.isdir():
+                output_path.mkdir(parents=True, exist_ok=True)
+                output_path.chmod(0o755)
+                continue
+            output_path.parent.mkdir(parents=True, exist_ok=True)
+            source = archive.extractfile(member)
+            if source is None:
+                raise RuntimeError(f"unable to read archive member: {member.name}")
+            with source, output_path.open("wb") as destination:
+                shutil.copyfileobj(source, destination)
+            output_path.chmod(0o755 if member.mode & 0o111 else 0o644)
+    return extracted
+
+
+def inspect_7z_archive(bundle_paths, listing):
+    paths = []
+    current = {}
+    for line in listing.splitlines() + [""]:
+        if not line and current:
+            path = current.get("Path")
+            attributes = current.get("Attributes", "")
+            if path and attributes:
+                member_path = PurePosixPath(path)
+                if member_path.is_absolute() or ".." in member_path.parts:
+                    raise RuntimeError(f"unsafe archive path: {path}")
+                if "L" in attributes or "H" in attributes:
+                    raise RuntimeError(f"unsupported archive member type: {path}")
+                paths.append((member_path, "D" in attributes))
+            current = {}
+        elif " = " in line:
+            key, value = line.split(" = ", 1)
+            current[key] = value
+    expected_roots = {PurePosixPath(path) for path in bundle_paths.values()}
+    present_roots = {path for path, is_directory in paths if is_directory and path in expected_roots}
+    if present_roots != expected_roots:
+        raise RuntimeError(f"7z archive is missing expected LV2 bundles: {sorted(map(str, expected_roots - present_roots))}")
+    for root in expected_roots:
+        if not any(path == root / "manifest.ttl" and not is_directory for path, is_directory in paths):
+            raise RuntimeError(f"7z archive bundle is missing manifest.ttl: {root}")
+    return expected_roots, paths
+
+
+def extract_7z_bundles(archive_path, bundle_paths, extraction_root):
+    executable = shutil.which("7z") or shutil.which("7zz") or shutil.which("7za")
+    if executable is None:
+        raise RuntimeError("installing LSP plugins requires 7z, 7zz, or 7za on PATH")
+    listing = subprocess.run(
+        [executable, "l", "-slt", str(archive_path)],
+        check=True,
+        capture_output=True,
+        text=True,
+    ).stdout
+    expected_roots, paths = inspect_7z_archive(bundle_paths, listing)
+    temporary_output = extraction_root / "7z-output"
+    temporary_output.mkdir()
+    result = subprocess.run(
+        [executable, "x", "-y", f"-o{temporary_output}", str(archive_path)],
+        check=False,
+        capture_output=True,
+        text=True,
+    )
+    if result.returncode != 0:
+        missing_files = [
+            path
+            for path, is_directory in paths
+            if not is_directory
+            and any(path.is_relative_to(root) for root in expected_roots)
+            and not temporary_output.joinpath(*path.parts).is_file()
+        ]
+        if missing_files:
+            raise subprocess.CalledProcessError(
+                result.returncode,
+                result.args,
+                output=result.stdout,
+                stderr=result.stderr,
+            )
+    extracted = {}
+    for bundle_name, path in bundle_paths.items():
+        bundle_root = PurePosixPath(path)
+        source = temporary_output.joinpath(*bundle_root.parts)
+        if not source.is_dir():
+            raise RuntimeError(f"expected LV2 bundle missing after extraction: {source}")
+        target = extraction_root / bundle_name
+        shutil.copytree(source, target, symlinks=False)
+        extracted[bundle_name] = target
+    return extracted
+
+
+def deploy_lv2_archives(action, component, config, registry):
+    bundle_paths = config["bundle_paths"]
+    bundle_names = list(bundle_paths)
+    destinations = {name: Path.home() / ".lv2" / name for name in bundle_names}
+    for destination in destinations.values():
+        validate_user_destination(destination)
+    managed = registry.get(component)
+
+    if action == "reload":
+        print(f"Nothing to reload for {component}; restart its LV2 host after installation.")
+        return
+
+    if action == "uninstall":
+        if managed is None:
+            print(f"No managed {component} bundles to uninstall.")
+            return
+        recorded = managed.get("bundles")
+        if not isinstance(recorded, dict) or set(recorded) != set(bundle_names):
+            raise RuntimeError(f"managed {component} bundle declaration changed")
+        if managed.get("pending_uninstall"):
+            for name, destination in destinations.items():
+                record = recorded[name]
+                backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
+                backup_exists = backup is not None and backup.is_dir()
+                if backup is not None and backup.exists() and not backup_exists:
+                    raise RuntimeError(f"recorded backup has the wrong type: {backup}")
+                if backup_exists and tree_sha256(backup) != record.get("backup_sha256"):
+                    raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
+                if destination.exists():
+                    current = tree_sha256(destination)
+                    if backup_exists and current == record.get("backup_sha256"):
+                        continue
+                    if backup is None and record.get("backup_sha256") is None:
+                        if current == record.get("installed_sha256"):
+                            continue
+                        raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
+                    if not backup_exists and current == record.get("backup_sha256"):
+                        continue
+                    if current != record.get("installed_sha256"):
+                        raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
+                elif backup is not None and not backup_exists:
+                    raise RuntimeError(f"recorded backup bundle is missing: {backup}")
+            for name, destination in destinations.items():
+                record = recorded[name]
+                backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
+                backup_exists = backup is not None and backup.is_dir()
+                if destination.exists() and tree_sha256(destination) == record.get("installed_sha256"):
+                    shutil.rmtree(destination)
+                if backup_exists:
+                    os.replace(backup, destination)
+            registry.pop(component)
+            write_registry(registry)
+            print(f"Completed interrupted {component} uninstall at {Path.home() / '.lv2'}.")
+            return
+        for name, destination in destinations.items():
+            record = recorded[name]
+            backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
+            if not destination.is_dir():
+                raise RuntimeError(f"managed {component} bundle is missing: {destination}")
+            if record.get("installed_path") != str(destination):
+                raise RuntimeError(f"managed {component} path changed: {destination}")
+            if tree_sha256(destination) != record.get("installed_sha256"):
+                raise RuntimeError(f"managed {component} bundle changed locally; refusing to remove: {destination}")
+            if backup is not None:
+                if not backup.is_dir():
+                    raise RuntimeError(f"recorded backup bundle is missing: {backup}")
+                if tree_sha256(backup) != record.get("backup_sha256"):
+                    raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
+        managed["pending_uninstall"] = True
+        registry[component] = managed
+        write_registry(registry)
+        for name, destination in destinations.items():
+            record = recorded[name]
+            shutil.rmtree(destination)
+            backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
+            if backup is not None:
+                os.replace(backup, destination)
+        registry.pop(component)
+        write_registry(registry)
+        print(f"Removed managed {component} bundles from {Path.home() / '.lv2'}.")
+        return
+
+    if managed is not None:
+        if managed.get("pending_uninstall"):
+            raise RuntimeError(f"{component} uninstall is incomplete; retry uninstall {component} first")
+        recorded = managed.get("bundles")
+        if not isinstance(recorded, dict) or set(recorded) != set(bundle_names):
+            raise RuntimeError(f"managed {component} bundle declaration changed")
+        for name, destination in destinations.items():
+            record = recorded[name]
+            backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
+            if backup is not None:
+                if not backup.is_dir() or tree_sha256(backup) != record.get("backup_sha256"):
+                    raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
+            if not destination.is_dir():
+                raise RuntimeError(f"managed {component} bundle is missing: {destination}")
+            if tree_sha256(destination) != record.get("installed_sha256"):
+                raise RuntimeError(f"managed {component} bundle changed locally; refusing overwrite: {destination}")
+        if managed.get("tag") == config["tag"]:
+            print(f"{component} tag {config['tag']} is already installed and unchanged.")
+            return
+
+    for name, destination in destinations.items():
+        previous = managed.get("bundles", {}).get(name) if managed else None
+        if previous is not None:
+            backup = validate_backup_path(previous.get("backup"), destination, is_directory=True)
+            if backup is not None:
+                if not backup.is_dir():
+                    raise RuntimeError(f"recorded backup bundle is missing: {backup}")
+                if tree_sha256(backup) != previous.get("backup_sha256"):
+                    raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
+        if previous is None and destination.exists():
+            backup = destination.with_name(destination.name + ".rigforge-backup")
+            if backup.exists():
+                raise RuntimeError(f"backup path already exists: {backup}")
+        staged = destination.with_name(destination.name + ".rigforge-new")
+        previous_path = destination.with_name(destination.name + ".rigforge-old")
+        if staged.exists() or previous_path.exists():
+            raise RuntimeError(f"{component} staging or recovery path already exists: {destination}")
+
+    with tempfile.TemporaryDirectory(prefix=f"rigforge-{component}-") as temporary_dir:
+        temporary = Path(temporary_dir)
+        archive_path = temporary / (
+            "plugin.tar.xz" if config["archive_format"] == "tar.xz" else "plugin.7z"
+        )
+        download_archive(config["archive_url"], archive_path)
+        archive_digest = hashlib.sha256(archive_path.read_bytes()).hexdigest()
+        extraction_root = temporary / "extract"
+        extraction_root.mkdir()
+        if config["archive_format"] == "tar.xz":
+            extracted = extract_tar_bundles(archive_path, config["bundle_paths"], extraction_root)
+        else:
+            extracted = extract_7z_bundles(archive_path, config["bundle_paths"], extraction_root)
+        records = {}
+        created_backups = []
+        installed_destinations = []
+        try:
+            for name, destination in destinations.items():
+                previous = managed.get("bundles", {}).get(name) if managed else None
+                backup = (
+                    validate_backup_path(previous.get("backup"), destination, is_directory=True)
+                    if previous is not None
+                    else destination.with_name(destination.name + ".rigforge-backup")
+                    if destination.exists()
+                    else None
+                )
+                backup_digest = previous.get("backup_sha256") if previous is not None else None
+                if backup is not None and previous is None:
+                    shutil.copytree(destination, backup, symlinks=True)
+                    created_backups.append(backup)
+                    backup_digest = tree_sha256(backup)
+                destination.parent.mkdir(parents=True, exist_ok=True)
+                staged = destination.with_name(destination.name + ".rigforge-new")
+                previous_path = destination.with_name(destination.name + ".rigforge-old")
+                shutil.copytree(extracted[name], staged, symlinks=False)
+                try:
+                    if destination.exists():
+                        os.replace(destination, previous_path)
+                    os.replace(staged, destination)
+                    installed_destinations.append((destination, previous_path))
+                except OSError:
+                    if previous_path.exists() and not destination.exists():
+                        os.replace(previous_path, destination)
+                    if staged.exists():
+                        shutil.rmtree(staged)
+                    raise
+                records[name] = {
+                    "installed_path": str(destination),
+                    "backup": str(backup) if backup is not None else None,
+                    "backup_sha256": backup_digest,
+                    "installed_sha256": tree_sha256(destination),
+                }
+            for _, previous_path in installed_destinations:
+                if previous_path.exists():
+                    shutil.rmtree(previous_path)
+        except (OSError, shutil.Error):
+            for destination, previous_path in reversed(installed_destinations):
+                if destination.exists():
+                    shutil.rmtree(destination)
+                if previous_path.exists():
+                    os.replace(previous_path, destination)
+            for destination in destinations.values():
+                staged = destination.with_name(destination.name + ".rigforge-new")
+                if staged.exists():
+                    shutil.rmtree(staged)
+            for backup in created_backups:
+                if backup.exists():
+                    shutil.rmtree(backup)
+            raise
+    registry[component] = {
+        "tag": config["tag"],
+        "archive_sha256": archive_digest,
+        "bundles": records,
+    }
+    write_registry(registry)
+    print(f"Installed {component} tag {config['tag']} under {Path.home() / '.lv2'}.")
+    print(f"Downloaded archive SHA-256 (identity only, no publisher checksum): {archive_digest}")
+
+
 def deploy_namlv2(action, config, registry):
 def deploy_namlv2(action, config, registry):
     bundle_name = config["bundle_directory"]
     bundle_name = config["bundle_directory"]
     destination = Path.home() / ".lv2" / bundle_name
     destination = Path.home() / ".lv2" / bundle_name
@@ -461,7 +792,7 @@ def deploy_namlv2(action, config, registry):
 def main(argv=None):
 def main(argv=None):
     parser = argparse.ArgumentParser()
     parser = argparse.ArgumentParser()
     parser.add_argument("action", choices=("install", "uninstall", "reload"))
     parser.add_argument("action", choices=("install", "uninstall", "reload"))
-    parser.add_argument("target", choices=("namlv2", "pipewire"))
+    parser.add_argument("target", choices=("namlv2", "lsp", "dragonfly-reverb", "pipewire"))
     args = parser.parse_args(argv)
     args = parser.parse_args(argv)
     try:
     try:
         state = yaml.safe_load((ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8"))
         state = yaml.safe_load((ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8"))
@@ -472,8 +803,11 @@ def main(argv=None):
         registry = read_registry()
         registry = read_registry()
         if args.target == "namlv2":
         if args.target == "namlv2":
             deploy_namlv2(args.action, deployment["namlv2"], registry)
             deploy_namlv2(args.action, deployment["namlv2"], registry)
-        else:
+        elif args.target == "pipewire":
             deploy_pipewire(args.action, deployment["pipewire"], registry, quantum_frames)
             deploy_pipewire(args.action, deployment["pipewire"], registry, quantum_frames)
+        else:
+            component = "dragonfly_reverb" if args.target == "dragonfly-reverb" else args.target
+            deploy_lv2_archives(args.action, component, deployment[component], registry)
     except (OSError, ValueError, RuntimeError, KeyError, TypeError, subprocess.CalledProcessError, tarfile.TarError, yaml.YAMLError) as error:
     except (OSError, ValueError, RuntimeError, KeyError, TypeError, subprocess.CalledProcessError, tarfile.TarError, yaml.YAMLError) as error:
         print(f"ERROR: {error}", file=sys.stderr)
         print(f"ERROR: {error}", file=sys.stderr)
         return 1
         return 1

+ 3 - 3
scripts/deploy.sh

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

+ 45 - 0
scripts/validate_desired_state.py

@@ -154,6 +154,51 @@ def validate_state(state):
     if not isinstance(deployment, dict):
     if not isinstance(deployment, dict):
         errors.append("deployment must be a mapping")
         errors.append("deployment must be a mapping")
     else:
     else:
+        for component, repository, asset, archive_format, bundle_paths in (
+            (
+                "lsp",
+                "lsp-plugins/lsp-plugins",
+                "lsp-plugins-{tag}-Linux-aarch64.7z",
+                "7z",
+                {"lsp-plugins.lv2": "lsp-plugins-{tag}-Linux-aarch64/LV2/lsp-plugins.lv2"},
+            ),
+            (
+                "dragonfly_reverb",
+                "michaelwillis/dragonfly-reverb",
+                "dragonfly-reverb-{tag}-linux-arm64.tar.xz",
+                "tar.xz",
+                {
+                    "DragonflyEarlyReflections.lv2": "dragonfly-reverb-{tag}/DragonflyEarlyReflections.lv2",
+                    "DragonflyHallReverb.lv2": "dragonfly-reverb-{tag}/DragonflyHallReverb.lv2",
+                    "DragonflyPlateReverb.lv2": "dragonfly-reverb-{tag}/DragonflyPlateReverb.lv2",
+                    "DragonflyRoomReverb.lv2": "dragonfly-reverb-{tag}/DragonflyRoomReverb.lv2",
+                },
+            ),
+        ):
+            plugin = deployment.get(component)
+            if not isinstance(plugin, dict):
+                errors.append(f"deployment.{component} must be a mapping")
+                continue
+            tag = plugin.get("tag")
+            if not isinstance(tag, str) or not tag or any(
+                character not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"
+                for character in tag
+            ):
+                errors.append(f"deployment.{component}.tag must be a simple version tag")
+            expected_url = f"https://github.com/{repository}/releases/download/{tag}/{asset.format(tag=tag)}"
+            if plugin.get("archive_url") != expected_url:
+                errors.append(f"deployment.{component}.archive_url must match its tag and approved release asset")
+            if plugin.get("archive_format") != archive_format:
+                errors.append(f"deployment.{component}.archive_format must be {archive_format}")
+            expected_paths = {
+                name: path.format(tag=tag) for name, path in bundle_paths.items()
+            }
+            if plugin.get("bundle_paths") != expected_paths:
+                errors.append(f"deployment.{component}.bundle_paths are invalid")
+            for bundle_name, bundle_path in expected_paths.items():
+                if bundle_name not in bundle_path:
+                    errors.append(f"deployment.{component}.bundle_paths keys must name their bundle directories")
+
         namlv2 = deployment.get("namlv2")
         namlv2 = deployment.get("namlv2")
         if not isinstance(namlv2, dict):
         if not isinstance(namlv2, dict):
             errors.append("deployment.namlv2 must be a mapping")
             errors.append("deployment.namlv2 must be a mapping")

+ 183 - 0
tests/test_deploy.py

@@ -1,4 +1,5 @@
 import io
 import io
+import io
 import json
 import json
 import os
 import os
 import shutil
 import shutil
@@ -48,6 +49,50 @@ class DeploymentTests(unittest.TestCase):
             "bundle_directory": "neural_amp_modeler.lv2",
             "bundle_directory": "neural_amp_modeler.lv2",
         }
         }
 
 
+    def plugin_config(self, component):
+        return deploy.load_deployment()[component]
+
+    def make_plugin_archive(self, destination, config):
+        if config["archive_format"] == "7z":
+            destination.write_bytes(b"simulated 7z archive")
+            return
+        with tarfile.open(destination, "w:xz") as archive:
+            for bundle_name, bundle_path in config["bundle_paths"].items():
+                directory = tarfile.TarInfo(bundle_path)
+                directory.type = tarfile.DIRTYPE
+                archive.addfile(directory)
+                for filename, content in {
+                    "manifest.ttl": b"<urn:plugin> a <urn:Plugin> .\\n",
+                    "plugin.so": b"binary",
+                }.items():
+                    info = tarfile.TarInfo(f"{bundle_path}/{filename}")
+                    info.size = len(content)
+                    info.mode = 0o755 if filename.endswith(".so") else 0o644
+                    archive.addfile(info, io.BytesIO(content))
+
+    def install_plugin(self, component, config=None):
+        config = config or self.plugin_config(component)
+
+        def download(url, destination):
+            self.make_plugin_archive(destination, config)
+
+        with patch.object(deploy, "download_archive", side_effect=download):
+            if config["archive_format"] == "7z":
+                def extract_7z(archive_path, bundle_paths, extraction_root):
+                    extracted = {}
+                    for name in bundle_paths:
+                        bundle = extraction_root / name
+                        bundle.mkdir()
+                        (bundle / "manifest.ttl").write_text("plugin manifest", encoding="utf-8")
+                        (bundle / "plugin.so").write_bytes(b"binary")
+                        extracted[name] = bundle
+                    return extracted
+
+                with patch.object(deploy, "extract_7z_bundles", side_effect=extract_7z):
+                    deploy.deploy_lv2_archives("install", component, config, deploy.read_registry())
+            else:
+                deploy.deploy_lv2_archives("install", component, config, deploy.read_registry())
+
     def pipewire_config(self):
     def pipewire_config(self):
         return {
         return {
             "fragment_source": "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf",
             "fragment_source": "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf",
@@ -155,6 +200,144 @@ class DeploymentTests(unittest.TestCase):
             deploy.deploy_pipewire("uninstall", config, deploy.read_registry(), 128)
             deploy.deploy_pipewire("uninstall", config, deploy.read_registry(), 128)
         self.assertEqual(destination.read_text(encoding="utf-8"), "local edit")
         self.assertEqual(destination.read_text(encoding="utf-8"), "local edit")
 
 
+    def test_lsp_install_uninstall_restores_existing_bundle_and_is_idempotent(self):
+        component = "lsp"
+        config = self.plugin_config(component)
+        destination = self.home / ".lv2/lsp-plugins.lv2"
+        destination.mkdir(parents=True)
+        (destination / "old.txt").write_text("prior plugin", encoding="utf-8")
+        self.install_plugin(component, config)
+        self.assertTrue((destination / "manifest.ttl").is_file())
+        registry = deploy.read_registry()
+        self.assertEqual(registry[component]["tag"], "1.2.37")
+        self.assertTrue(registry[component]["archive_sha256"])
+        self.commands.clear()
+        with patch.object(deploy, "download_archive", side_effect=AssertionError("must not download")):
+            deploy.deploy_lv2_archives("install", component, config, registry)
+        deploy.deploy_lv2_archives("uninstall", component, config, registry)
+        self.assertEqual((destination / "old.txt").read_text(encoding="utf-8"), "prior plugin")
+        self.assertNotIn(component, deploy.read_registry())
+
+    def test_dragonfly_install_and_uninstall_manage_all_bundles(self):
+        component = "dragonfly_reverb"
+        config = self.plugin_config(component)
+        first_name = next(iter(config["bundle_paths"]))
+        first_destination = self.home / ".lv2" / first_name
+        first_destination.mkdir(parents=True)
+        (first_destination / "old.txt").write_text("prior plugin", encoding="utf-8")
+        self.install_plugin(component, config)
+        registry = deploy.read_registry()
+        self.assertEqual(set(registry[component]["bundles"]), set(config["bundle_paths"]))
+        for name in config["bundle_paths"]:
+            self.assertTrue((self.home / ".lv2" / name / "manifest.ttl").is_file())
+        deploy.deploy_lv2_archives("uninstall", component, config, registry)
+        self.assertEqual((first_destination / "old.txt").read_text(encoding="utf-8"), "prior plugin")
+        self.assertNotIn(component, deploy.read_registry())
+
+    def test_plugin_update_preserves_old_bundles_when_staging_fails(self):
+        component = "dragonfly_reverb"
+        config = self.plugin_config(component)
+        self.install_plugin(component, config)
+        destinations = {
+            name: self.home / ".lv2" / name for name in config["bundle_paths"]
+        }
+        original_hashes = {name: deploy.tree_sha256(path) for name, path in destinations.items()}
+        updated = dict(config, tag="3.2.11")
+
+        def fail_copy(source, destination, **kwargs):
+            if Path(destination).name == "DragonflyPlateReverb.lv2.rigforge-new":
+                raise OSError("simulated staging failure")
+            return original_copytree(source, destination, **kwargs)
+
+        original_copytree = deploy.shutil.copytree
+        with patch.object(deploy, "download_archive", side_effect=lambda url, path: self.make_plugin_archive(path, config)):
+            with patch.object(deploy, "extract_tar_bundles", return_value={name: self.home / "source" / name for name in config["bundle_paths"]}):
+                source_root = self.home / "source"
+                for name in config["bundle_paths"]:
+                    bundle = source_root / name
+                    bundle.mkdir(parents=True)
+                    (bundle / "manifest.ttl").write_text("new plugin", encoding="utf-8")
+                with patch.object(deploy.shutil, "copytree", side_effect=fail_copy):
+                    with self.assertRaisesRegex(OSError, "simulated staging failure"):
+                        deploy.deploy_lv2_archives("install", component, updated, deploy.read_registry())
+        self.assertEqual(
+            {name: deploy.tree_sha256(path) for name, path in destinations.items()},
+            original_hashes,
+        )
+        leftover_names = {path.name for path in (self.home / ".lv2").iterdir()}
+        self.assertFalse(any(name.endswith(".rigforge-new") or name.endswith(".rigforge-old") for name in leftover_names))
+
+    def test_plugin_pending_uninstall_recovers_after_bundle_removal(self):
+        component = "dragonfly_reverb"
+        config = self.plugin_config(component)
+        self.install_plugin(component, config)
+        registry = deploy.read_registry()
+        registry[component]["pending_uninstall"] = True
+        deploy.write_registry(registry)
+        removed_name = "DragonflyEarlyReflections.lv2"
+        destination = self.home / ".lv2" / removed_name
+        shutil.rmtree(destination)
+        deploy.deploy_lv2_archives("uninstall", component, config, registry)
+        self.assertFalse(destination.exists())
+        self.assertNotIn(component, deploy.read_registry())
+
+    def test_plugin_install_refuses_local_edits_and_reload_is_noop(self):
+        component = "dragonfly_reverb"
+        config = self.plugin_config(component)
+        self.install_plugin(component, config)
+        destination = self.home / ".lv2/DragonflyHallReverb.lv2"
+        (destination / "manifest.ttl").write_text("local edit", encoding="utf-8")
+        with self.assertRaisesRegex(RuntimeError, "changed locally"):
+            deploy.deploy_lv2_archives("uninstall", component, config, deploy.read_registry())
+        self.assertEqual((destination / "manifest.ttl").read_text(encoding="utf-8"), "local edit")
+        self.commands.clear()
+        deploy.deploy_lv2_archives("reload", component, config, deploy.read_registry())
+        self.assertEqual(self.commands, [])
+
+    def test_release_archive_layouts_match_declarations(self):
+        lsp_listing = """Path = /tmp/lsp.7z
+Type = 7z
+Physical Size = 456
+
+Path = lsp-plugins-1.2.37-Linux-aarch64/LV2/lsp-plugins.lv2
+Attributes = D_ drwxr-xr-xr
+
+Path = lsp-plugins-1.2.37-Linux-aarch64/LV2/lsp-plugins.lv2/manifest.ttl
+Attributes = A_ -rw-r--r--
+"""
+        self.assertEqual(
+            deploy.inspect_7z_archive(
+                self.plugin_config("lsp")["bundle_paths"], lsp_listing
+            ),
+            (
+                {Path("lsp-plugins-1.2.37-Linux-aarch64/LV2/lsp-plugins.lv2")},
+                [
+                    (Path("lsp-plugins-1.2.37-Linux-aarch64/LV2/lsp-plugins.lv2"), True),
+                    (Path("lsp-plugins-1.2.37-Linux-aarch64/LV2/lsp-plugins.lv2/manifest.ttl"), False),
+                ],
+            ),
+        )
+
+    def test_7z_plugin_archive_rejects_path_traversal(self):
+        listing = """Path = /tmp/lsp.7z
+Type = 7z
+Physical Size = 456
+
+Path = ../escape
+Attributes = A_ -rw-r--r--
+"""
+        with self.assertRaisesRegex(RuntimeError, "unsafe archive path"):
+            deploy.inspect_7z_archive(self.plugin_config("lsp")["bundle_paths"], listing)
+
+    def test_tar_plugin_archive_rejects_path_traversal(self):
+        archive_path = self.home / "bad.tar.xz"
+        with tarfile.open(archive_path, "w:xz") as archive:
+            info = tarfile.TarInfo("../escape")
+            info.size = 1
+            archive.addfile(info, io.BytesIO(b"x"))
+        with self.assertRaisesRegex(RuntimeError, "unsafe archive path"):
+            deploy.inspect_tar_archive(archive_path, self.plugin_config("dragonfly_reverb")["bundle_paths"])
+
     def test_nam_install_and_uninstall_restore_existing_bundle(self):
     def test_nam_install_and_uninstall_restore_existing_bundle(self):
         destination = self.home / ".lv2/neural_amp_modeler.lv2"
         destination = self.home / ".lv2/neural_amp_modeler.lv2"
         destination.mkdir(parents=True)
         destination.mkdir(parents=True)

+ 16 - 0
tests/test_desired_state.py

@@ -59,6 +59,22 @@ class DesiredStateValidationTests(unittest.TestCase):
         state["deployment"]["namlv2"]["tag"] = "../latest"
         state["deployment"]["namlv2"]["tag"] = "../latest"
         self.assertTrue(any("tag must be a simple version tag" in error for error in validate_state(state)))
         self.assertTrue(any("tag must be a simple version tag" in error for error in validate_state(state)))
 
 
+        state = copy.deepcopy(self.state)
+        state["deployment"]["lsp"]["tag"] = "../latest"
+        self.assertTrue(any("deployment.lsp.tag must be a simple version tag" in error for error in validate_state(state)))
+
+        state = copy.deepcopy(self.state)
+        state["deployment"]["lsp"]["archive_url"] = "https://example.invalid/plugin.7z"
+        self.assertTrue(any("deployment.lsp.archive_url must match" in error for error in validate_state(state)))
+
+        state = copy.deepcopy(self.state)
+        state["deployment"]["dragonfly_reverb"]["archive_format"] = "tar.gz"
+        self.assertTrue(any("deployment.dragonfly_reverb.archive_format" in error for error in validate_state(state)))
+
+        state = copy.deepcopy(self.state)
+        del state["deployment"]["dragonfly_reverb"]
+        self.assertIn("deployment.dragonfly_reverb must be a mapping", validate_state(state))
+
         state = copy.deepcopy(self.state)
         state = copy.deepcopy(self.state)
         state["deployment"]["pipewire"]["fragment_destination"] = ".config/other.conf"
         state["deployment"]["pipewire"]["fragment_destination"] = ".config/other.conf"
         self.assertTrue(any("fragment_destination" in error for error in validate_state(state)))
         self.assertTrue(any("fragment_destination" in error for error in validate_state(state)))