Jelajahi Sumber

deploy script

Johan Le Baut 2 minggu lalu
induk
melakukan
59122cb9ef

+ 4 - 2
AGENTS.md

@@ -11,8 +11,9 @@ The current target is Debian GNU/Linux 13 on AArch64 with a Behringer UMC404HD 1
 - `config/desired-state.yaml` is the central YAML description of the intended components, four mono sources, looper channel assignments, mix, planned/forbidden connections, and the exact PipeWire links currently tracked for observation.
 - `config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf` is a PipeWire filter-chain fragment with four mono mixer inputs, one mono output, and initial gain `0.2` per input. It defines the processing graph and ports, but does not create links to hardware or implement the looper graph.
 - `scripts/validate_desired_state.py` checks the YAML's four-source/physical-input model, single four-channel looper, source-to-channel assignments, mix declaration, and prohibition on routing looper returns back to looper inputs.
-- `scripts/observe_pipewire.py` validates the state and managed endpoint declarations, reads `pw-link -l`, then compares observed links against the explicitly managed ports and links. It reports differences only; it must remain non-mutating.
-- `tests/` contains Python `unittest` tests for the state validator, observer, and mixer configuration. These validate repository-level invariants, not live audio behavior.
+- `scripts/observe_pipewire.py` validates the state and managed endpoint declarations, reads `pw-link -l`, and compares observed links against explicitly managed ports and links. Observation is the default; explicit one-shot reconciliation may create only declared missing links.
+- `scripts/deploy.sh` dispatches user-level install/uninstall/reload actions for YAML-declared PipeWire and NAM LV2 targets through `scripts/deploy.py`.
+- `tests/` contains Python `unittest` tests for state validation, observation/reconciliation, mixer configuration, and simulated deployment operations. These validate repository-level invariants, not live audio behavior.
 - `config/sooperlooper/fcb1010.slb` is supplied controller configuration, pending target verification. No SooperLooper build definition or artifact is present.
 
 The YAML is the source of truth for desired topology. The observer's scope is deliberately narrower: it compares links only when both endpoints are listed in `routing.managed_ports`. Keep unrelated WirePlumber-managed hardware links out of scope. Managed endpoint names are constrained by an explicit allowlist pattern in the observer, so a new port naming scheme must be deliberately reviewed and tested there as well as declared in YAML.
@@ -45,6 +46,7 @@ The observer invokes `pw-link -l` itself. It never creates or removes links. A c
 - The mix must declare an output and include looper returns. Looper returns must not feed any looper input; the explicit forbidden connection is policy documentation, not an active route.
 - A managed link's endpoints must both be declared in `routing.managed_ports`, and names must match the observer's approved endpoint pattern. Use concrete observed PipeWire ports rather than logical aliases.
 - Link status values used by the observer are `planned` and `observed`; both are compared against the current graph. Only declare real target observations as `observed`.
+- Deployment declarations belong in `config/desired-state.yaml`. The deploy helper must remain scoped to declared user paths, preserve and restore prior files, refuse destructive actions after local modifications, and never restart the main PipeWire or WirePlumber service as a generic update.
 - Keep observation as the default. Explicit `--reconcile-once` may create only declared missing links after confirming both ports exist; it must not remove links, alter unrelated connections, or restart services. Retain tests for simulated repair and post-check behavior.
 - Mixer gain `0.2` is an initial conservative value, not a calibrated level or clipping guarantee. Test summed sources and loop returns on hardware before live use.
 

+ 25 - 4
README.md

@@ -33,8 +33,9 @@ This records the preparation already performed on `rigforge` and is a starting p
 - `config/sooperlooper/fcb1010.slb`: supplied FCB1010 binding file, pending on-target verification.
 - `build/sooperlooper/`: reserved for the later ARM64 Docker build definition.
 - `scripts/validate_desired_state.py`: validates topology and routing invariants without changing the target.
-- `scripts/observe_pipewire.py`: read-only comparison for explicitly declared UMC AUX ports and links.
-- `tests/`: unit tests for desired-state validation and the PipeWire observer.
+- `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.
+- `tests/`: unit tests for desired-state validation, PipeWire observation/reconciliation, and deployment operations.
 - `artifacts/sooperlooper/arm64/`: reserved for an artifact and its provenance, subject to repository hosting limits and redistribution terms.
 
 The YAML describes desired state; a control surface is not a second source of truth. The initial audio profile declares 48 kHz and a quantum of 128 frames, which was reported to sound good during a temporary target test. At 48 kHz, 128 frames is about 2.7 ms per period, not the end-to-end latency. This runtime value has not yet been made persistent or measured under sustained load; apply it temporarily on the target with `pw-metadata -n settings 0 clock.force-quantum 128` and return to automatic selection with `pw-metadata -n settings 0 clock.force-quantum 0`. Concrete PipeWire ports, buffer settings, package names, services, and artifact installation path will only be recorded as verified after target tests.
@@ -62,7 +63,9 @@ An explicit one-shot mode can create missing declared links, after checking that
 python3 scripts/observe_pipewire.py --reconcile-once
 ```
 
-This mode never removes links, changes undeclared connections, or restarts services. It makes one attempt per missing managed link, then re-reads the graph and reports remaining differences. Use it only during a safe test window: a repaired link can immediately make audio audible. Do not disconnect a working link just to test repair during live use. If all desired links are already present, this mode is a no-op. This command has unit tests with simulated `pw-link` results, but has not yet been exercised on `rigforge`.
+This mode never removes links, changes undeclared connections, or restarts services. It makes one attempt per missing managed link, then re-reads the graph and reports remaining differences. Use it only during a safe test window: a repaired link can immediately make audio audible. Do not disconnect a working link just to test repair during live use. If all desired links are already present, this mode is a no-op. Unit tests use simulated `pw-link` results.
+
+On 2026-11-18, the target owner deliberately removed the managed AUX2 capture-to-mixer link during a safe test. Observation reported that single link as missing. After updating `rigforge` to commit `83fb0a7`, `--reconcile-once` requested the link, and the final check reported `differences: []`. A subsequent read-only observation also reported no differences, the microphone was confirmed audible again, and all 20 unit tests passed on the target. This verifies one-shot repair for a managed link on the current target; it does not validate continuous reconciliation, service restarts, or recovery from missing ports.
 
 ## Candidate direct mix test
 
@@ -96,6 +99,24 @@ systemctl --user restart filter-chain.service
 
 This restarts only `filter-chain.service`, not the main PipeWire daemon. The fragment and three links have passed an initial target listening test, but the test is not a sustained load, dropout, four-instrument, or headroom test. If activation or sound behaves unexpectedly, first remove the test links, perform the rollback, verify the filter service is active, and do not repeatedly restart it. Repository tests check channel/gain declarations and observer comparisons; they do not replace target runtime measurements.
 
+## User-level deployment on `rigforge`
+
+After a manual `git pull --ff-only`, run the deploy helper from any directory:
+
+```sh
+~/rigforge/scripts/deploy.sh install pipewire
+~/rigforge/scripts/deploy.sh install namlv2
+~/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.
+
+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. 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. The supplied release asset has not yet been installed or tested on the target, and runtime dependencies and compatibility remain to be confirmed there. The release archive is fetched at install time and is not committed to this repository.
+
+`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`.
+
 ## Development PC
 
 The development host is Ubuntu AMD64 with Docker. The SooperLooper source under evaluation is <https://github.com/abarker/sooperlooper-mods>. The Docker build procedure is intentionally not yet provided: first select a tag and inspect that tag's build instructions and licensing. The eventual build command must take an explicit tag, resolve and record its exact commit, build for ARM64, and record artifact architecture, runtime dependencies, provenance, and checksum. The container is for building only; SooperLooper will run natively on the Raspberry Pi.
@@ -108,7 +129,7 @@ The filter-chain fragment is installed in the user configuration on `rigforge`,
 
 The next target checks are:
 
-1. Run the read-only PipeWire observer on `rigforge`; the expected result is no differences while the three test links remain active.
+1. The read-only observer and one-shot repair have been tested on `rigforge`; all three declared links were present afterward and the repaired microphone path was audible.
 2. Later, test inputs 2 and 4 with sources when available; they are included in the mixer but not verified with instruments.
 3. Measure sustained stability and headroom at 48 kHz / 128 frames with all active sources; the current `ERR = 0` observation was brief.
 4. Inspect the user service session and resource limits before defining autonomous startup. `Linger=no` currently means the running audio session is associated with the active login; unattended startup is not established.

+ 10 - 0
config/desired-state.yaml

@@ -33,6 +33,16 @@ system:
       software: Open Stage Control
       required_for_audio: false
 
+deployment:
+  namlv2:
+    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
+    bundle_directory: neural_amp_modeler.lv2
+  pipewire:
+    fragment_source: config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf
+    fragment_destination: .config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf
+    user_service: filter-chain.service
+
 modes:
   live:
     standalone: true

TEMPAT SAMPAH
scripts/__pycache__/validate_desired_state.cpython-310.pyc


+ 484 - 0
scripts/deploy.py

@@ -0,0 +1,484 @@
+import argparse
+import hashlib
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tarfile
+import tempfile
+from pathlib import Path, PurePosixPath
+
+import yaml
+
+from validate_desired_state import validate_state
+
+
+ROOT = Path(__file__).resolve().parents[1]
+STATE_PATH = Path.home() / ".local" / "state" / "rigforge" / "deployment.json"
+NAM_RELEASE_ASSET = re.compile(
+    r"^https://github\.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/"
+    r"(?P<tag>[A-Za-z0-9._-]+)/neural_amp_modeler_lv2_rpi5\.tgz$"
+)
+
+
+def load_deployment():
+    with (ROOT / "config" / "desired-state.yaml").open(encoding="utf-8") as stream:
+        state = yaml.safe_load(stream)
+    errors = validate_state(state)
+    deployment = state.get("deployment") if isinstance(state, dict) else None
+    if not isinstance(deployment, dict):
+        raise ValueError("deployment must be a mapping")
+    namlv2 = deployment.get("namlv2")
+    pipewire = deployment.get("pipewire")
+    if not isinstance(namlv2, dict) or not isinstance(pipewire, dict):
+        raise ValueError("deployment.namlv2 and deployment.pipewire must be mappings")
+    tag = namlv2.get("tag")
+    match = NAM_RELEASE_ASSET.fullmatch(namlv2.get("archive_url", ""))
+    if not isinstance(tag, str) or not re.fullmatch(r"[A-Za-z0-9._-]+", tag):
+        errors.append("NAM LV2 tag is invalid")
+    if match is None or match.group("tag") != tag:
+        errors.append("NAM LV2 URL must be the approved release asset for the declared tag")
+    if namlv2.get("bundle_directory") != "neural_amp_modeler.lv2":
+        errors.append("NAM LV2 bundle directory is invalid")
+    source = pipewire.get("fragment_source")
+    if source != "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf":
+        errors.append("PipeWire fragment source is invalid")
+    if pipewire.get("fragment_destination") != ".config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf":
+        errors.append("PipeWire fragment destination is invalid")
+    if pipewire.get("user_service") != "filter-chain.service":
+        errors.append("PipeWire user service is invalid")
+    if errors:
+        raise ValueError("; ".join(errors))
+    return deployment
+
+
+def read_registry():
+    if not STATE_PATH.exists():
+        return {}
+    with STATE_PATH.open(encoding="utf-8") as stream:
+        registry = json.load(stream)
+    if not isinstance(registry, dict):
+        raise ValueError(f"deployment registry is not a mapping: {STATE_PATH}")
+    return registry
+
+
+def write_registry(registry):
+    STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
+    fd, temporary_name = tempfile.mkstemp(prefix="deployment.", dir=STATE_PATH.parent)
+    try:
+        with os.fdopen(fd, "w", encoding="utf-8") as stream:
+            json.dump(registry, stream, indent=2, sort_keys=True)
+            stream.write("\n")
+        os.replace(temporary_name, STATE_PATH)
+    finally:
+        if os.path.exists(temporary_name):
+            os.unlink(temporary_name)
+
+
+def run(command):
+    subprocess.run(command, check=True)
+
+
+def tree_sha256(path):
+    digest = hashlib.sha256()
+    for item in sorted(path.rglob("*")):
+        relative = item.relative_to(path).as_posix().encode()
+        digest.update(relative + b"\\0")
+        if item.is_symlink():
+            digest.update(b"link\\0" + os.readlink(item).encode())
+        elif item.is_file():
+            digest.update(b"file\\0" + item.read_bytes())
+        elif item.is_dir():
+            digest.update(b"directory\\0")
+        else:
+            raise RuntimeError(f"unsupported file type in managed bundle: {item}")
+    return digest.hexdigest()
+
+
+def validate_user_destination(destination):
+    home = Path.home().resolve()
+    parent = destination.parent.resolve()
+    if not parent.is_relative_to(home):
+        raise RuntimeError(f"deployment path escapes the user home directory: {destination}")
+    if destination.is_symlink():
+        raise RuntimeError(f"refusing to manage a symlink destination: {destination}")
+
+
+def validate_backup_path(backup, destination, is_directory=False):
+    if backup is None:
+        return None
+    backup_path = Path(backup)
+    expected = destination.with_name(destination.name + ".rigforge-backup")
+    if backup_path != expected:
+        raise RuntimeError(f"recorded backup path is outside its approved location: {backup_path}")
+    if backup_path.is_symlink():
+        raise RuntimeError(f"recorded backup must not be a symlink: {backup_path}")
+    if backup_path.exists() and backup_path.is_dir() != is_directory:
+        raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
+    return backup_path
+
+
+def atomic_install(source, destination):
+    destination.parent.mkdir(parents=True, exist_ok=True)
+    fd, temporary_name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent)
+    os.close(fd)
+    try:
+        shutil.copyfile(source, temporary_name)
+        shutil.copymode(source, temporary_name)
+        os.replace(temporary_name, destination)
+    finally:
+        if os.path.exists(temporary_name):
+            os.unlink(temporary_name)
+
+
+def apply_quantum(frames):
+    run(["pw-metadata", "-n", "settings", "0", "clock.force-quantum", str(frames)])
+
+
+def restart_filter_service(service):
+    run(["systemctl", "--user", "restart", service])
+    run(["systemctl", "--user", "is-active", "--quiet", service])
+
+
+def deploy_pipewire(action, config, registry, quantum_frames):
+    destination = Path.home() / config["fragment_destination"]
+    validate_user_destination(destination)
+    source = ROOT / config["fragment_source"]
+    managed = registry.get("pipewire")
+
+    pending_reload = registry.get("pipewire_pending_reload")
+    if pending_reload is not None:
+        apply_quantum(pending_reload["quantum_frames"])
+        restart_filter_service(config["user_service"])
+        registry.pop("pipewire_pending_reload")
+        write_registry(registry)
+        managed = registry.get("pipewire")
+
+    if action == "reload":
+        if not source.is_file() or not destination.is_file():
+            raise RuntimeError("PipeWire reload requires both the repository fragment and installed fragment")
+        apply_quantum(quantum_frames)
+        restart_filter_service(config["user_service"])
+        print("PipeWire runtime quantum applied; filter-chain user service restarted.")
+        return
+
+    if action == "install":
+        if managed is not None and managed.get("pending_uninstall"):
+            raise RuntimeError("PipeWire uninstall is incomplete; retry uninstall pipewire first")
+        if managed is not None:
+            validate_backup_path(managed.get("backup"), destination)
+            if not destination.exists():
+                raise RuntimeError(f"managed PipeWire fragment is missing: {destination}")
+        if managed is not None and destination.exists():
+            current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
+            if current_digest != managed["installed_sha256"]:
+                raise RuntimeError(f"managed file changed locally; refusing overwrite: {destination}")
+
+        was_unmanaged = managed is None
+        changed = not destination.exists() or destination.read_bytes() != source.read_bytes()
+        if managed is None:
+            backup_path = None
+            backup_sha256 = None
+            if destination.exists():
+                backup_path = str(destination.with_name(destination.name + ".rigforge-backup"))
+                if Path(backup_path).exists():
+                    raise RuntimeError(f"backup path already exists: {backup_path}")
+                shutil.copy2(destination, backup_path)
+                backup_sha256 = hashlib.sha256(Path(backup_path).read_bytes()).hexdigest()
+            managed = {
+                "installed_sha256": "",
+                "backup": backup_path,
+                "backup_sha256": backup_sha256,
+            }
+            registry["pipewire"] = managed
+        if changed:
+            atomic_install(source, destination)
+        managed["installed_sha256"] = hashlib.sha256(source.read_bytes()).hexdigest()
+        managed["pending_reload"] = changed or was_unmanaged or managed.get("pending_reload", False)
+        registry["pipewire"] = managed
+        write_registry(registry)
+        apply_quantum(quantum_frames)
+        if managed["pending_reload"]:
+            restart_filter_service(config["user_service"])
+            managed.pop("pending_reload", None)
+            registry["pipewire"] = managed
+            write_registry(registry)
+        print(f"PipeWire fragment {'updated' if changed else 'already current'} at {destination}.")
+        return
+
+    if action == "uninstall":
+        if managed is None:
+            print("No managed PipeWire fragment to uninstall.")
+            return
+        if managed.get("pending_uninstall"):
+            backup_path = validate_backup_path(managed.get("backup"), destination)
+            backup_exists = backup_path is not None and backup_path.is_file()
+            if backup_path is not None and backup_path.exists():
+                if not backup_exists:
+                    raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
+                backup_digest = hashlib.sha256(backup_path.read_bytes()).hexdigest()
+                if backup_digest != managed.get("backup_sha256"):
+                    raise RuntimeError(f"recorded backup changed locally: {backup_path}")
+            if destination.exists():
+                current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
+                if backup_exists and current_digest == managed.get("backup_sha256"):
+                    backup_path.unlink()
+                elif backup_path is not None and not backup_exists and current_digest == managed.get("backup_sha256"):
+                    pass
+                elif current_digest == managed.get("installed_sha256"):
+                    destination.unlink()
+                    if backup_exists:
+                        os.replace(backup_path, destination)
+                    elif backup_path is not None:
+                        raise RuntimeError(f"recorded backup is missing: {backup_path}")
+                else:
+                    raise RuntimeError(f"unexpected file blocks pending uninstall: {destination}")
+            elif backup_exists:
+                os.replace(backup_path, destination)
+            elif backup_path is not None:
+                raise RuntimeError(f"recorded backup is missing: {backup_path}")
+            registry.pop("pipewire")
+            write_registry(registry)
+            apply_quantum(0)
+            restart_filter_service(config["user_service"])
+            print("Completed interrupted PipeWire uninstall and restored prior state.")
+            return
+        if not destination.exists():
+            raise RuntimeError(f"managed PipeWire fragment is missing: {destination}")
+        current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
+        if current_digest != managed["installed_sha256"]:
+            raise RuntimeError(f"managed file changed locally; refusing to remove: {destination}")
+        backup_path = validate_backup_path(managed.get("backup"), destination)
+        if backup_path is not None and not backup_path.is_file():
+            raise RuntimeError(f"recorded backup is missing: {backup_path}")
+        if backup_path is not None:
+            backup_digest = hashlib.sha256(backup_path.read_bytes()).hexdigest()
+            if backup_digest != managed.get("backup_sha256"):
+                raise RuntimeError(f"recorded backup changed locally: {backup_path}")
+        managed["pending_uninstall"] = True
+        registry["pipewire"] = managed
+        write_registry(registry)
+        destination.unlink()
+        if backup_path is not None:
+            atomic_install(backup_path, destination)
+            backup_path.unlink()
+        registry.pop("pipewire")
+        registry["pipewire_pending_reload"] = {"quantum_frames": 0}
+        write_registry(registry)
+        apply_quantum(0)
+        restart_filter_service(config["user_service"])
+        registry.pop("pipewire_pending_reload")
+        write_registry(registry)
+        print("Rigforge PipeWire fragment removed or prior file restored; quantum reset to automatic.")
+        return
+
+
+def inspect_archive(archive_path, bundle_name):
+    with tarfile.open(archive_path, "r:gz") as archive:
+        members = archive.getmembers()
+        bundle_prefix = PurePosixPath(bundle_name)
+        matching = []
+        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 member_path.parts and member_path.parts[0] == bundle_prefix.name:
+                if not member_path.is_relative_to(bundle_prefix):
+                    raise RuntimeError(f"unexpected bundle path: {member.name}")
+                if not (member.isdir() or member.isfile()):
+                    raise RuntimeError(f"unsupported archive member type: {member.name}")
+                matching.append(member)
+            else:
+                raise RuntimeError(f"unexpected archive path: {member.name}")
+        if not matching or not any(member.name == bundle_name and member.isdir() for member in matching):
+            raise RuntimeError(f"archive does not contain expected bundle directory {bundle_name}")
+        return members
+
+
+def extract_bundle(archive_path, destination, bundle_name):
+    with tarfile.open(archive_path, "r:gz") as archive:
+        members = inspect_archive(archive_path, bundle_name)
+        for member in members:
+            member_path = PurePosixPath(member.name)
+            relative_parts = member_path.parts[1:]
+            output_path = destination.joinpath(*relative_parts) if relative_parts else destination
+            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)
+            extracted = archive.extractfile(member)
+            if extracted is None:
+                raise RuntimeError(f"unable to read archive member: {member.name}")
+            with extracted, output_path.open("wb") as output:
+                shutil.copyfileobj(extracted, output)
+            output_path.chmod(0o755 if member.mode & 0o111 else 0o644)
+
+
+def download_archive(url, destination):
+    run(["curl", "--fail", "--location", "--silent", "--show-error", "--output", str(destination), url])
+
+
+def deploy_namlv2(action, config, registry):
+    bundle_name = config["bundle_directory"]
+    destination = Path.home() / ".lv2" / bundle_name
+    validate_user_destination(destination)
+    managed = registry.get("namlv2")
+
+    if action == "reload":
+        print("Nothing to reload for the NAM LV2 plugin; restart its LV2 host after installation.")
+        return
+
+    if action == "uninstall":
+        if managed is None:
+            print("No managed NAM LV2 bundle to uninstall.")
+            return
+        if managed.get("pending_uninstall"):
+            backup_path = validate_backup_path(managed.get("backup"), destination, is_directory=True)
+            backup_exists = backup_path is not None and backup_path.is_dir()
+            if backup_path is not None and backup_path.exists() and not backup_exists:
+                raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
+            if backup_exists and tree_sha256(backup_path) != managed.get("backup_sha256"):
+                raise RuntimeError(f"recorded backup bundle changed locally: {backup_path}")
+            if destination.exists():
+                destination_digest = tree_sha256(destination)
+                if backup_exists and destination_digest == managed.get("backup_sha256"):
+                    shutil.rmtree(backup_path)
+                elif destination_digest == managed.get("installed_sha256"):
+                    shutil.rmtree(destination)
+                    if backup_exists:
+                        os.replace(backup_path, destination)
+                else:
+                    raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
+            elif backup_exists:
+                os.replace(backup_path, destination)
+            elif backup_path is not None:
+                raise RuntimeError(f"recorded backup bundle is missing: {backup_path}")
+            registry.pop("namlv2")
+            write_registry(registry)
+            print(f"Completed interrupted NAM LV2 uninstall at {destination}.")
+            return
+        if not destination.exists():
+            raise RuntimeError(f"managed NAM LV2 bundle is missing: {destination}")
+        if managed.get("installed_path") != str(destination):
+            raise RuntimeError(f"managed NAM LV2 path changed: {destination}")
+        if tree_sha256(destination) != managed.get("installed_sha256"):
+            raise RuntimeError(f"managed NAM LV2 bundle changed locally; refusing to remove: {destination}")
+        backup_path = validate_backup_path(managed.get("backup"), destination, is_directory=True)
+        if backup_path is not None and not backup_path.is_dir():
+            raise RuntimeError(f"recorded backup bundle is missing: {backup_path}")
+        if backup_path is not None and tree_sha256(backup_path) != managed.get("backup_sha256"):
+            raise RuntimeError(f"recorded backup bundle changed locally: {backup_path}")
+        managed["pending_uninstall"] = True
+        registry["namlv2"] = managed
+        write_registry(registry)
+        shutil.rmtree(destination)
+        if backup_path is not None:
+            os.replace(backup_path, destination)
+        registry.pop("namlv2")
+        write_registry(registry)
+        print(f"Removed managed NAM LV2 bundle from {destination}.")
+        return
+
+    if managed is not None:
+        if managed.get("pending_uninstall"):
+            raise RuntimeError("NAM LV2 uninstall is incomplete; retry uninstall namlv2 first")
+        if not destination.is_dir():
+            raise RuntimeError(f"managed NAM LV2 bundle is missing: {destination}")
+        if tree_sha256(destination) != managed.get("installed_sha256"):
+            raise RuntimeError(f"managed NAM LV2 bundle changed locally; refusing overwrite: {destination}")
+        if managed.get("tag") == config["tag"]:
+            print(f"NAM LV2 tag {config['tag']} is already installed and unchanged.")
+            return
+        backup = validate_backup_path(managed.get("backup"), destination, is_directory=True)
+        backup_sha256 = managed.get("backup_sha256")
+    elif destination.exists():
+        backup = destination.with_name(destination.name + ".rigforge-backup")
+        if backup.exists():
+            raise RuntimeError(f"backup path already exists: {backup}")
+        backup_sha256 = None
+    else:
+        backup = None
+        backup_sha256 = None
+
+    with tempfile.TemporaryDirectory(prefix="rigforge-namlv2-") as temporary_dir:
+        temporary = Path(temporary_dir)
+        archive_path = temporary / "namlv2.tgz"
+        download_archive(config["archive_url"], archive_path)
+        archive_digest = hashlib.sha256(archive_path.read_bytes()).hexdigest()
+        inspect_archive(archive_path, bundle_name)
+        extraction_root = temporary / "extract"
+        extraction_root.mkdir()
+        extracted_bundle = extraction_root / bundle_name
+        extracted_bundle.mkdir()
+        extract_bundle(archive_path, extracted_bundle, bundle_name)
+        if not extracted_bundle.is_dir():
+            raise RuntimeError(f"expected bundle missing after extraction: {extracted_bundle}")
+        destination.parent.mkdir(parents=True, exist_ok=True)
+        staged_bundle = destination.with_name(destination.name + ".rigforge-new")
+        previous_bundle = destination.with_name(destination.name + ".rigforge-old")
+        if staged_bundle.exists() or previous_bundle.exists():
+            raise RuntimeError("NAM LV2 staging or recovery path already exists")
+        backup_created = False
+        moved_previous = False
+        try:
+            shutil.copytree(extracted_bundle, staged_bundle)
+            if managed is None and backup is not None:
+                shutil.copytree(destination, backup)
+                backup_created = True
+                backup_sha256 = tree_sha256(backup)
+            if destination.exists():
+                os.replace(destination, previous_bundle)
+                moved_previous = True
+            os.replace(staged_bundle, destination)
+        except (OSError, shutil.Error):
+            if moved_previous and previous_bundle.exists() and not destination.exists():
+                os.replace(previous_bundle, destination)
+            if backup_created and backup.exists():
+                shutil.rmtree(backup)
+            raise
+        finally:
+            if staged_bundle.exists():
+                shutil.rmtree(staged_bundle)
+        if previous_bundle.exists():
+            shutil.rmtree(previous_bundle)
+
+    registry["namlv2"] = {
+        "tag": config["tag"],
+        "archive_sha256": archive_digest,
+        "installed_path": str(destination),
+        "backup": str(backup) if backup is not None else None,
+        "backup_sha256": backup_sha256,
+        "installed_sha256": tree_sha256(destination),
+    }
+    write_registry(registry)
+    print(f"Installed NAM LV2 tag {config['tag']} at {destination}.")
+    print(f"Downloaded archive SHA-256 (identity only, no publisher checksum): {archive_digest}")
+
+
+def main(argv=None):
+    parser = argparse.ArgumentParser()
+    parser.add_argument("action", choices=("install", "uninstall", "reload"))
+    parser.add_argument("target", choices=("namlv2", "pipewire"))
+    args = parser.parse_args(argv)
+    try:
+        state = yaml.safe_load((ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8"))
+        deployment = load_deployment()
+        quantum_frames = state["parameters"]["quantum_frames"]
+        if not isinstance(quantum_frames, int) or isinstance(quantum_frames, bool) or quantum_frames < 1:
+            raise ValueError("parameters.quantum_frames must be a positive integer")
+        registry = read_registry()
+        if args.target == "namlv2":
+            deploy_namlv2(args.action, deployment["namlv2"], registry)
+        else:
+            deploy_pipewire(args.action, deployment["pipewire"], registry, quantum_frames)
+    except (OSError, ValueError, RuntimeError, KeyError, TypeError, subprocess.CalledProcessError, tarfile.TarError, yaml.YAMLError) as error:
+        print(f"ERROR: {error}", file=sys.stderr)
+        return 1
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 30 - 0
scripts/deploy.sh

@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+set -u
+
+usage() {
+    printf 'Usage: %s install|uninstall|reload all|namlv2|pipewire\n' "$0" >&2
+    exit 2
+}
+
+[[ $# -eq 2 ]] || usage
+action=$1
+target=$2
+case "$action" in
+    install|uninstall|reload) ;;
+    *) usage ;;
+esac
+case "$target" in
+    all) targets=(pipewire namlv2) ;;
+    namlv2|pipewire) targets=("$target") ;;
+    *) usage ;;
+esac
+
+script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+status=0
+for component in "${targets[@]}"; do
+    printf '%s\n' "== $action $component =="
+    if ! python3 "$script_dir/deploy.py" "$action" "$component"; then
+        status=1
+    fi
+done
+exit "$status"

+ 37 - 0
scripts/validate_desired_state.py

@@ -150,6 +150,43 @@ def validate_state(state):
         ):
             errors.append(f"connections[{index}] routes looper returns into looper inputs")
 
+    deployment = state.get("deployment")
+    if not isinstance(deployment, dict):
+        errors.append("deployment must be a mapping")
+    else:
+        namlv2 = deployment.get("namlv2")
+        if not isinstance(namlv2, dict):
+            errors.append("deployment.namlv2 must be a mapping")
+        else:
+            tag = namlv2.get("tag")
+            allowed_tag_characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"
+            if not isinstance(tag, str) or not tag or any(
+                character not in allowed_tag_characters for character in tag
+            ):
+                errors.append("deployment.namlv2.tag must be a simple version tag")
+            archive_url = namlv2.get("archive_url")
+            expected_url = (
+                f"https://github.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/{tag}/"
+                "neural_amp_modeler_lv2_rpi5.tgz"
+            )
+            if archive_url != expected_url:
+                errors.append("deployment.namlv2.archive_url must match its tag and approved RPi 5 release asset")
+            if namlv2.get("bundle_directory") != "neural_amp_modeler.lv2":
+                errors.append("deployment.namlv2.bundle_directory must be neural_amp_modeler.lv2")
+
+        pipewire = deployment.get("pipewire")
+        if not isinstance(pipewire, dict):
+            errors.append("deployment.pipewire must be a mapping")
+        else:
+            expected_fragment_source = "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf"
+            if pipewire.get("fragment_source") != expected_fragment_source:
+                errors.append("deployment.pipewire.fragment_source must name the managed repository fragment")
+            expected_fragment_destination = ".config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf"
+            if pipewire.get("fragment_destination") != expected_fragment_destination:
+                errors.append("deployment.pipewire.fragment_destination must be the user filter-chain fragment path")
+            if pipewire.get("user_service") != "filter-chain.service":
+                errors.append("deployment.pipewire.user_service must be filter-chain.service")
+
     return errors
 
 

+ 225 - 0
tests/test_deploy.py

@@ -0,0 +1,225 @@
+import io
+import json
+import os
+import shutil
+import sys
+import tarfile
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+
+import deploy
+
+
+class DeploymentTests(unittest.TestCase):
+    def setUp(self):
+        self.temporary = tempfile.TemporaryDirectory()
+        self.home = Path(self.temporary.name) / "home"
+        self.home.mkdir()
+        self.registry_path = self.home / ".local/state/rigforge/deployment.json"
+        self.commands = []
+        self.run_patcher = patch.object(deploy, "run", side_effect=self.fake_run)
+        self.run_patcher.start()
+        self.home_patcher = patch.object(deploy.Path, "home", return_value=self.home)
+        self.home_patcher.start()
+        self.root_patcher = patch.object(deploy, "ROOT", ROOT)
+        self.root_patcher.start()
+        self.registry_patcher = patch.object(deploy, "STATE_PATH", self.registry_path)
+        self.registry_patcher.start()
+
+    def tearDown(self):
+        patch.stopall()
+        self.temporary.cleanup()
+
+    def fake_run(self, command):
+        self.commands.append(command)
+
+    def nam_config(self, tag="v0.2.3"):
+        return {
+            "tag": tag,
+            "archive_url": (
+                "https://github.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/"
+                f"{tag}/neural_amp_modeler_lv2_rpi5.tgz"
+            ),
+            "bundle_directory": "neural_amp_modeler.lv2",
+        }
+
+    def pipewire_config(self):
+        return {
+            "fragment_source": "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf",
+            "fragment_destination": ".config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf",
+            "user_service": "filter-chain.service",
+        }
+
+    def make_archive(self, destination, files=None):
+        files = files or {"manifest.ttl": b"<urn:nam> a <urn:Plugin> .\n", "plugin.so": b"binary"}
+        with tarfile.open(destination, "w:gz") as archive:
+            directory = tarfile.TarInfo("neural_amp_modeler.lv2")
+            directory.type = tarfile.DIRTYPE
+            archive.addfile(directory)
+            for name, content in files.items():
+                info = tarfile.TarInfo(f"neural_amp_modeler.lv2/{name}")
+                info.size = len(content)
+                archive.addfile(info, io.BytesIO(content))
+
+    def install_nam(self, config=None):
+        config = config or self.nam_config()
+
+        def download(url, destination):
+            self.make_archive(destination)
+
+        with patch.object(deploy, "download_archive", side_effect=download):
+            deploy.deploy_namlv2("install", config, deploy.read_registry())
+
+    def test_pipewire_install_is_atomic_scoped_and_idempotent(self):
+        config = self.pipewire_config()
+        deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
+        installed = self.home / config["fragment_destination"]
+        self.assertEqual(installed.read_bytes(), (ROOT / config["fragment_source"]).read_bytes())
+        self.assertEqual(
+            self.commands,
+            [
+                ["pw-metadata", "-n", "settings", "0", "clock.force-quantum", "128"],
+                ["systemctl", "--user", "restart", "filter-chain.service"],
+                ["systemctl", "--user", "is-active", "--quiet", "filter-chain.service"],
+            ],
+        )
+        self.commands.clear()
+        deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
+        self.assertEqual(
+            self.commands,
+            [["pw-metadata", "-n", "settings", "0", "clock.force-quantum", "128"]],
+        )
+        self.assertFalse(any("pipewire.service" in command for command in self.commands))
+
+    def test_pipewire_uninstall_restores_previous_file(self):
+        config = self.pipewire_config()
+        destination = self.home / config["fragment_destination"]
+        destination.parent.mkdir(parents=True)
+        destination.write_text("previous config", encoding="utf-8")
+        deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
+        self.commands.clear()
+        deploy.deploy_pipewire("uninstall", config, deploy.read_registry(), 128)
+        self.assertEqual(destination.read_text(encoding="utf-8"), "previous config")
+        self.assertEqual(self.commands[0][-1], "0")
+        self.assertEqual(self.commands[1], ["systemctl", "--user", "restart", "filter-chain.service"])
+        self.assertNotIn("pipewire", deploy.read_registry())
+        self.assertFalse(deploy.read_registry().get("pipewire_pending_reload"))
+
+    def test_pipewire_pending_uninstall_recovers_after_prior_file_restored(self):
+        config = self.pipewire_config()
+        destination = self.home / config["fragment_destination"]
+        destination.parent.mkdir(parents=True)
+        destination.write_text("prior config", encoding="utf-8")
+        deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
+        registry = deploy.read_registry()
+        registry["pipewire"]["pending_uninstall"] = True
+        deploy.write_registry(registry)
+        destination.write_text("prior config", encoding="utf-8")
+        Path(registry["pipewire"]["backup"]).unlink()
+
+        deploy.deploy_pipewire("uninstall", config, registry, 128)
+
+        self.assertEqual(destination.read_text(encoding="utf-8"), "prior config")
+        self.assertNotIn("pipewire", deploy.read_registry())
+
+    def test_pipewire_pending_uninstall_recovers_after_fragment_removal(self):
+        config = self.pipewire_config()
+        deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
+        destination = self.home / config["fragment_destination"]
+        destination.unlink()
+        registry = deploy.read_registry()
+        registry["pipewire"]["pending_uninstall"] = True
+        deploy.write_registry(registry)
+
+        deploy.deploy_pipewire("uninstall", config, registry, 128)
+
+        self.assertFalse(destination.exists())
+        self.assertNotIn("pipewire", deploy.read_registry())
+        self.assertEqual(self.commands[-3:], [
+            ["pw-metadata", "-n", "settings", "0", "clock.force-quantum", "0"],
+            ["systemctl", "--user", "restart", "filter-chain.service"],
+            ["systemctl", "--user", "is-active", "--quiet", "filter-chain.service"],
+        ])
+
+    def test_pipewire_uninstall_refuses_local_changes(self):
+        config = self.pipewire_config()
+        deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
+        destination = self.home / config["fragment_destination"]
+        destination.write_text("local edit", encoding="utf-8")
+        with self.assertRaisesRegex(RuntimeError, "changed locally"):
+            deploy.deploy_pipewire("uninstall", config, deploy.read_registry(), 128)
+        self.assertEqual(destination.read_text(encoding="utf-8"), "local edit")
+
+    def test_nam_install_and_uninstall_restore_existing_bundle(self):
+        destination = self.home / ".lv2/neural_amp_modeler.lv2"
+        destination.mkdir(parents=True)
+        (destination / "old.txt").write_text("prior plugin", encoding="utf-8")
+        self.install_nam()
+        self.assertTrue((destination / "manifest.ttl").is_file())
+        self.assertTrue((destination / "plugin.so").is_file())
+        registry = deploy.read_registry()
+        self.assertEqual(registry["namlv2"]["tag"], "v0.2.3")
+        self.assertTrue(registry["namlv2"]["archive_sha256"])
+        self.assertTrue(registry["namlv2"]["installed_sha256"])
+        deploy.deploy_namlv2("uninstall", self.nam_config(), registry)
+        self.assertEqual((destination / "old.txt").read_text(encoding="utf-8"), "prior plugin")
+        self.assertNotIn("manifest.ttl", {path.name for path in destination.iterdir()})
+        self.assertNotIn("namlv2", deploy.read_registry())
+
+    def test_nam_pending_uninstall_recovers_after_bundle_removal(self):
+        destination = self.home / ".lv2/neural_amp_modeler.lv2"
+        destination.mkdir(parents=True)
+        (destination / "old.txt").write_text("prior plugin", encoding="utf-8")
+        self.install_nam()
+        registry = deploy.read_registry()
+        registry["namlv2"]["pending_uninstall"] = True
+        deploy.write_registry(registry)
+        shutil.rmtree(destination)
+
+        deploy.deploy_namlv2("uninstall", self.nam_config(), registry)
+
+        self.assertTrue((destination / "old.txt").is_file())
+        self.assertNotIn("namlv2", deploy.read_registry())
+
+    def test_nam_install_same_tag_is_idempotent(self):
+        self.install_nam()
+        self.commands.clear()
+        with patch.object(deploy, "download_archive", side_effect=AssertionError("must not download")):
+            deploy.deploy_namlv2("install", self.nam_config(), deploy.read_registry())
+        self.assertEqual(self.commands, [])
+
+    def test_nam_install_update_refuses_local_changes_and_restore_baseline(self):
+        self.install_nam()
+        destination = self.home / ".lv2/neural_amp_modeler.lv2"
+        (destination / "manifest.ttl").write_text("user edit", encoding="utf-8")
+        with patch.object(deploy, "download_archive", side_effect=AssertionError("must not download")):
+            with self.assertRaisesRegex(RuntimeError, "changed locally"):
+                deploy.deploy_namlv2("install", self.nam_config("v0.2.4"), deploy.read_registry())
+        self.assertEqual((destination / "manifest.ttl").read_text(encoding="utf-8"), "user edit")
+
+    def test_nam_reload_is_informational_only(self):
+        deploy.deploy_namlv2("reload", self.nam_config(), {})
+        self.assertEqual(self.commands, [])
+
+    def test_nam_archive_rejects_path_traversal(self):
+        archive_path = self.home / "bad.tgz"
+        with tarfile.open(archive_path, "w:gz") 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_archive(archive_path, "neural_amp_modeler.lv2")
+
+    def test_nam_registry_is_valid_json(self):
+        self.install_nam()
+        registry = json.loads(self.registry_path.read_text(encoding="utf-8"))
+        self.assertIn("namlv2", registry)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 15 - 0
tests/test_desired_state.py

@@ -48,6 +48,21 @@ class DesiredStateValidationTests(unittest.TestCase):
         state["routing"]["mix"]["output_port"] = ""
         self.assertIn("routing.mix.output_port must be a non-empty string", validate_state(state))
 
+    def test_deployment_targets_are_declared_and_valid(self):
+        self.assertEqual(validate_state(self.state), [])
+
+        state = copy.deepcopy(self.state)
+        state["deployment"]["namlv2"]["archive_url"] = "https://example.invalid/plugin.tgz"
+        self.assertTrue(any("archive_url must match" in error for error in validate_state(state)))
+
+        state = copy.deepcopy(self.state)
+        state["deployment"]["namlv2"]["tag"] = "../latest"
+        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"]["pipewire"]["fragment_destination"] = ".config/other.conf"
+        self.assertTrue(any("fragment_destination" in error for error in validate_state(state)))
+
     def test_return_exclusion_marker_is_not_an_active_connection(self):
         self.assertEqual(validate_state(self.state), [])