import argparse import hashlib import json import os import re import shutil import socket import subprocess import sys import tarfile import tempfile from pathlib import Path, PurePosixPath import yaml from validate_desired_state import validate_state from generate_mod_ui_pedalboard import generate_bundle_files 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[A-Za-z0-9._-]+)/neural_amp_modeler_lv2_rpi5\.tgz$" ) PLUGIN_ARCHIVES = { "lsp": "7z", "dragonfly_reverb": "tar.xz", } 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") sooperlooper = deployment.get("sooperlooper") slweb = deployment.get("slweb") pipewire = deployment.get("pipewire") reconcile = deployment.get("reconcile") midi_bridge = deployment.get("midi_bridge") mod_host_ports = deployment.get("mod_host_ports") mod_ui = deployment.get("mod_ui") if ( not isinstance(namlv2, dict) or not isinstance(sooperlooper, dict) or not isinstance(slweb, dict) or not isinstance(pipewire, dict) or not isinstance(reconcile, dict) or not isinstance(midi_bridge, dict) or not isinstance(mod_host_ports, dict) or not isinstance(mod_ui, dict) ): raise ValueError( "deployment.namlv2, deployment.sooperlooper, deployment.slweb, deployment.pipewire, " "deployment.reconcile, deployment.midi_bridge, deployment.mod_host_ports, and deployment.mod_ui " "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") match = NAM_RELEASE_ASSET.fullmatch(namlv2.get("archive_url", "")) if namlv2.get("source_url") != "https://github.com/mikeoliphant/neural-amp-modeler-lv2": errors.append("NAM LV2 source URL is invalid") 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") if namlv2.get("backup_directory") != ".local/state/rigforge/namlv2-backups": errors.append("NAM LV2 backup 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 runtime_tree_sha256(path): digest = hashlib.sha256() for item in sorted(path.rglob("*")): if "__pycache__" in item.parts or item.suffix in {".pyc", ".pyo"}: continue 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 runtime 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 namlv2_backup_path(config, destination): relative = PurePosixPath(config.get("backup_directory", "")) if relative.is_absolute() or ".." in relative.parts or not relative.parts: raise RuntimeError("NAM LV2 backup directory must be a safe relative path") home = Path.home().resolve() backup_root = (home / Path(*relative.parts)).resolve() if not backup_root.is_relative_to(home): raise RuntimeError("NAM LV2 backup directory escapes the user home directory") backup = backup_root / f"{destination.name}.rigforge-backup" validate_user_destination(backup) return backup def validate_nam_backup_path(backup, destination, config): if backup is None: return None backup_path = Path(backup) approved = { destination.with_name(destination.name + ".rigforge-backup"), namlv2_backup_path(config, destination), } if backup_path not in approved: raise RuntimeError(f"recorded NAM LV2 backup path is outside approved locations: {backup_path}") if backup_path.is_symlink(): raise RuntimeError(f"recorded NAM LV2 backup must not be a symlink: {backup_path}") if backup_path.exists() and not backup_path.is_dir(): raise RuntimeError(f"recorded NAM LV2 backup has the wrong type: {backup_path}") return backup_path def migrate_namlv2_backup(config, backup, destination, backup_sha256): """Move legacy in-~/.lv2 backups out of Lilv's plugin search path.""" if backup is None or not backup.exists(): return backup target = namlv2_backup_path(config, destination) if backup == target: return backup legacy = destination.with_name(destination.name + ".rigforge-backup") if backup != legacy: return backup if tree_sha256(backup) != backup_sha256: raise RuntimeError(f"recorded NAM LV2 backup changed locally: {backup}") if target.exists() or target.is_symlink(): raise RuntimeError(f"NAM LV2 backup destination already exists: {target}") target.parent.mkdir(parents=True, exist_ok=True) os.replace(backup, target) return target 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 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): bundle_name = config["bundle_directory"] destination = Path.home() / ".lv2" / bundle_name validate_user_destination(destination) managed = registry.get("namlv2") artifact_directory = config.get("artifact_directory") artifact_bundle = None artifact_digest = None if artifact_directory is not None: relative = PurePosixPath(artifact_directory) if relative.is_absolute() or ".." in relative.parts or not relative.parts: raise RuntimeError("NAM LV2 artifact directory must be a safe repository path") artifact_root = (ROOT / Path(*relative.parts)).resolve() if not artifact_root.is_relative_to(ROOT.resolve()): raise RuntimeError("NAM LV2 artifact directory escapes the repository") artifact_bundle = artifact_root / bundle_name provenance_path = artifact_root / "provenance.json" if not artifact_bundle.is_dir() or not provenance_path.is_file(): raise FileNotFoundError( f"built NAM LV2 artifact is missing: {artifact_bundle}" ) with provenance_path.open(encoding="utf-8") as stream: provenance = json.load(stream) if ( provenance.get("source_url") != "https://github.com/mikeoliphant/neural-amp-modeler-lv2" or provenance.get("tag") != config["tag"] or provenance.get("linkage") != "system libstdc++ and libgcc_s" ): raise RuntimeError("built NAM LV2 artifact provenance does not match desired state") plugin_binary = artifact_bundle / "neural_amp_modeler.so" if ( not (artifact_bundle / "manifest.ttl").is_file() or not (artifact_bundle / "neural_amp_modeler.ttl").is_file() or not plugin_binary.is_file() or file_sha256(plugin_binary) != provenance.get("artifact_sha256") ): raise RuntimeError("built NAM LV2 artifact failed its provenance check") artifact_digest = tree_sha256(artifact_bundle) if action == "reload": print("Nothing to reload for the NAM LV2 plugin; restart mod-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_nam_backup_path( managed.get("backup"), destination, config ) 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_nam_backup_path( managed.get("backup"), destination, config ) 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}") backup = validate_nam_backup_path(managed.get("backup"), destination, config) backup_sha256 = managed.get("backup_sha256") if backup is not None: backup = migrate_namlv2_backup( config, backup, destination, backup_sha256 ) managed["backup"] = str(backup) registry["namlv2"] = managed write_registry(registry) if managed.get("tag") == config["tag"] and ( artifact_digest is None or managed.get("artifact_sha256") == artifact_digest ): print(f"NAM LV2 tag {config['tag']} is already installed and unchanged.") return elif destination.exists(): backup = namlv2_backup_path(config, destination) 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_digest = None if artifact_bundle is not None: extracted_bundle = artifact_bundle else: 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() or not (extracted_bundle / "manifest.ttl").is_file() or not (extracted_bundle / "neural_amp_modeler.so").is_file() ): raise RuntimeError(f"expected NAM LV2 bundle missing or incomplete: {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: backup.parent.mkdir(parents=True, exist_ok=True) 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), } if artifact_digest is not None: registry["namlv2"]["artifact_sha256"] = artifact_digest registry["namlv2"]["build_provenance"] = str(artifact_root / "provenance.json") write_registry(registry) print(f"Installed NAM LV2 tag {config['tag']} at {destination}.") if artifact_digest is not None: print(f"Installed built NAM LV2 artifact SHA-256: {artifact_digest}") elif archive_digest is not None: print(f"Downloaded archive SHA-256 (identity only, no publisher checksum): {archive_digest}") def systemd_quote(value): value = str(value).replace("%", "%%").replace("\\", "\\\\").replace('"', '\\"') return f'"{value}"' def render_mod_host_service(config): binary = ROOT / config["binary_source"] service_template = ROOT / config["service_source"] readiness_script = ROOT / config["readiness_script"] state_file = ROOT / "config" / "desired-state.yaml" if not binary.is_file() or not os.access(binary, os.X_OK): raise RuntimeError(f"ARM64 mod-host artifact is missing or not executable: {binary}") if not service_template.is_file(): raise RuntimeError(f"mod-host service template is missing: {service_template}") if not readiness_script.is_file(): raise RuntimeError(f"mod-host PipeWire readiness checker is missing: {readiness_script}") replacements = { "@PW_JACK@": systemd_quote(config["pw_jack_path"]), "@MOD_HOST_BINARY@": systemd_quote(binary.resolve()), "@SOCKET_PORT@": str(config["socket_port"]), "@FEEDBACK_PORT@": str(config["feedback_port"]), "@PYTHON@": systemd_quote(config["python_path"]), "@READINESS_SCRIPT@": systemd_quote(readiness_script.resolve()), "@PORT_WAIT_TIMEOUT_SECONDS@": str(config["port_wait_timeout_seconds"]), "@DESIRED_STATE@": systemd_quote(state_file.resolve()), } content = service_template.read_text(encoding="utf-8") for placeholder, replacement in replacements.items(): content = content.replace(placeholder, replacement) if re.search(r"@[A-Z_]+@", content): raise RuntimeError("unexpanded placeholder remains in mod-host service template") return content.encode("utf-8") def render_mod_host_ports_service(config): state_file = ROOT / "config" / "desired-state.yaml" runner_script = ROOT / config["runner_script"] service_template = ROOT / config["service_source"] binary = Path(config["binary_path"]) for description, path in ( ("mod-host port runner", runner_script), ("mod-host ports service template", service_template), ): if not path.is_file(): raise RuntimeError(f"{description} is missing: {path}") replacements = { "@PYTHON@": systemd_quote(config["python_path"]), "@RUNNER_SCRIPT@": systemd_quote(runner_script.resolve()), "@DESIRED_STATE@": systemd_quote(state_file.resolve()), "@PW_LOOPBACK@": systemd_quote(binary), } content = service_template.read_text(encoding="utf-8") for placeholder, replacement in replacements.items(): content = content.replace(placeholder, replacement) if re.search(r"@[A-Z_]+@", content): raise RuntimeError("unexpanded placeholder remains in mod-host ports service template") fingerprint = hashlib.sha256( json.dumps(config, sort_keys=True, separators=(",", ":")).encode("utf-8") + runner_script.read_bytes() + (ROOT / "scripts" / "validate_desired_state.py").read_bytes() + state_file.read_bytes() ).hexdigest() return { "name": config["user_service"], "destination": Path.home() / config["service_destination"], "content": (content + f"\n# Rigforge runtime fingerprint: {fingerprint}\n").encode("utf-8"), } def render_mod_ui_service(config): state_file = ROOT / "config" / "desired-state.yaml" launcher = ROOT / config["launcher"] runner_script = ROOT / config["runner_script"] boot_prepare_script = ROOT / "scripts" / "prepare_mod_ui_pedalboard.py" service_template = ROOT / config["service_source"] with state_file.open(encoding="utf-8") as stream: state = yaml.safe_load(stream) nam_processor = state["routing"]["mod_host_chains"]["guitar"]["processors"][0] nam_model_path = ( Path.home() / config["user_files_directory"] / "NAM Models" / "Rigforge" / Path(nam_processor["asset_path"]).name ) reference_files = generate_bundle_files( state, ROOT, nam_model_path=nam_model_path ) bundle_digest = hashlib.sha256() for name, content_bytes in sorted(reference_files.items()): bundle_digest.update(name.encode("utf-8") + b"\0" + content_bytes + b"\0") reference_pedalboard = ( Path.home() / config["reference_directory"] / f"rigforge-guitar-{bundle_digest.hexdigest()[:16]}.pedalboard" ) for description, path in ( ("mod-ui launcher", launcher), ("mod-ui service runner", runner_script), ("mod-ui boot preparation script", boot_prepare_script), ("mod-ui service template", service_template), ): if not path.is_file(): raise RuntimeError(f"{description} is missing: {path}") home = Path.home() replacements = { "@PYTHON@": systemd_quote(config["python_path"]), "@RUNNER_SCRIPT@": systemd_quote(runner_script.resolve()), "@BOOT_PREPARE_SCRIPT@": systemd_quote(boot_prepare_script.resolve()), "@DESIRED_STATE@": systemd_quote(state_file.resolve()), "@MOD_UI_LAUNCHER@": systemd_quote(launcher.resolve()), "@PW_JACK@": systemd_quote(config["pw_jack_path"]), "@WEBSOCKET_HOST@": config["websocket_host"], "@WEBSOCKET_PORT@": str(config["websocket_port"]), "@MOD_DATA_DIR@": systemd_quote(home / ".local" / "share" / "rigforge" / "mod-ui"), "@MOD_LAST_STATE@": systemd_quote(home / config["last_state_file"]), "@PEDALBOARDS_DIR@": systemd_quote(home / config["pedalboards_directory"]), "@USER_FILES_DIR@": systemd_quote(home / config["user_files_directory"]), "@REFERENCE_PEDALBOARD@": systemd_quote(reference_pedalboard), "@HARDWARE_INPUT_PORTS@": systemd_quote(",".join(config["hardware_input_ports"])), "@HARDWARE_OUTPUT_PORTS@": systemd_quote(",".join(config["hardware_output_ports"])), } content = service_template.read_text(encoding="utf-8") for placeholder, replacement in replacements.items(): content = content.replace(placeholder, replacement) if re.search(r"@[A-Z_]+@", content): raise RuntimeError("unexpanded placeholder remains in mod-ui service template") artifact_root = ROOT / config["artifact_directory"] runtime_digest = hashlib.sha256() runtime_digest.update(runtime_tree_sha256(artifact_root).encode("ascii")) runtime_digest.update(runner_script.read_bytes()) runtime_digest.update(boot_prepare_script.read_bytes()) runtime_digest.update((ROOT / "scripts" / "mod_ui_websocket.py").read_bytes()) runtime_digest.update((ROOT / "scripts" / "generate_mod_ui_pedalboard.py").read_bytes()) for name, content_bytes in sorted(reference_files.items()): runtime_digest.update(name.encode("utf-8") + b"\0" + content_bytes + b"\0") content += f"\n# Rigforge runtime fingerprint: {runtime_digest.hexdigest()}\n" return { "name": config["user_service"], "destination": home / config["service_destination"], "content": content.encode("utf-8"), "reference_bundle": reference_pedalboard, "reference_files": reference_files, } def render_reconcile_units(config): repository_root = ROOT.resolve() state_file = repository_root / "config" / "desired-state.yaml" observer_script = repository_root / config["observer_script"] service_template = repository_root / config["service_source"] timer_template = repository_root / config["timer_source"] for description, path in ( ("PipeWire observer", observer_script), ("reconciliation service template", service_template), ("reconciliation timer template", timer_template), ): if not path.is_file(): raise RuntimeError(f"reconciliation {description} is missing: {path}") service_replacements = { "@PYTHON@": systemd_quote(config["python_path"]), "@OBSERVER_SCRIPT@": systemd_quote(observer_script), "@DESIRED_STATE@": systemd_quote(state_file), } service_content = service_template.read_text(encoding="utf-8") for placeholder, replacement in service_replacements.items(): service_content = service_content.replace(placeholder, replacement) if re.search(r"@[A-Z_]+@", service_content): raise RuntimeError("unexpanded placeholder remains in reconciliation service template") timer_content = timer_template.read_text(encoding="utf-8").replace( "@RECONCILE_INTERVAL_SECONDS@", str(config["interval_seconds"]), ) if re.search(r"@[A-Z_]+@", timer_content): raise RuntimeError("unexpanded placeholder remains in reconciliation timer template") return { "service": { "name": config["user_service"], "destination": Path.home() / config["service_destination"], "content": service_content.encode("utf-8"), }, "timer": { "name": config["user_timer"], "destination": Path.home() / config["timer_destination"], "content": timer_content.encode("utf-8"), }, } def render_midi_bridge_service(config): repository_root = ROOT.resolve() state_file = repository_root / "config" / "desired-state.yaml" bridge_script = repository_root / config["bridge_script"] service_template = repository_root / config["service_source"] for description, path in ( ("MIDI action bridge script", bridge_script), ("MIDI bridge service template", service_template), ): if not path.is_file(): raise RuntimeError(f"{description} is missing: {path}") replacements = { "@PYTHON@": systemd_quote(config["python_path"]), "@BRIDGE_SCRIPT@": systemd_quote(bridge_script), "@DESIRED_STATE@": systemd_quote(state_file), "@REPOSITORY_ROOT@": systemd_quote(repository_root), } content = service_template.read_text(encoding="utf-8") for placeholder, replacement in replacements.items(): content = content.replace(placeholder, replacement) if re.search(r"@[A-Z_]+@", content): raise RuntimeError("unexpanded placeholder remains in MIDI bridge service template") fingerprint = hashlib.sha256( bridge_script.read_bytes() + (ROOT / "scripts" / "mod_ui_websocket.py").read_bytes() + (ROOT / "config" / "midi-bindings.yaml").read_bytes() + state_file.read_bytes() ).hexdigest() content += f"\n# Rigforge runtime fingerprint: {fingerprint}\n" return { "name": config["user_service"], "destination": Path.home() / config["service_destination"], "content": content.encode("utf-8"), } def render_sooperlooper_service(config, state): repository_root = ROOT.resolve() binary = repository_root / config["binary_source"] service_template = repository_root / config["service_source"] binding_file = repository_root / config["binding_file"] for description, path in ( ("ARM64 SooperLooper artifact", binary), ("SooperLooper service template", service_template), ("SooperLooper MIDI binding file", binding_file), ): if not path.is_file(): raise RuntimeError(f"{description} is missing: {path}") if not os.access(binary, os.X_OK): raise RuntimeError(f"ARM64 SooperLooper artifact is not executable: {binary}") components = state.get("system", {}).get("components", []) loopers = [ component for component in components if isinstance(component, dict) and component.get("id") == "looper" ] if isinstance(components, list) else [] if len(loopers) != 1: raise RuntimeError("desired state must declare exactly one SooperLooper component") loop_count = loopers[0].get("loop_count") channels_per_loop = loopers[0].get("channels_per_loop") if ( not isinstance(loop_count, int) or isinstance(loop_count, bool) or loop_count < 1 or not isinstance(channels_per_loop, int) or isinstance(channels_per_loop, bool) or channels_per_loop < 1 ): raise RuntimeError("desired SooperLooper loop and channel counts must be positive integers") osc = config["osc"] replacements = { "@PW_JACK@": systemd_quote(config["pw_jack_path"]), "@SOOPERLOOPER_BINARY@": systemd_quote(binary.resolve()), "@LOOP_COUNT@": str(loop_count), "@CHANNELS_PER_LOOP@": str(channels_per_loop), "@TIMEOUT_SECONDS@": str(config["timeout_seconds"]), "@BINDING_FILE@": systemd_quote(binding_file.resolve()), "@POST_START_DELAY_SECONDS@": str(osc["post_start_delay_seconds"]), "@OSCSEND@": systemd_quote(config["oscsend_path"]), "@OSC_HOST@": systemd_quote(osc["host"]), "@OSC_PORT@": str(osc["port"]), "@DISCRETE_PREFADER@": str(osc["discrete_prefader"]), } content = service_template.read_text(encoding="utf-8") for placeholder, replacement in replacements.items(): content = content.replace(placeholder, replacement) if re.search(r"@[A-Z_]+@", content): raise RuntimeError("unexpanded placeholder remains in SooperLooper service template") return { "name": config["user_service"], "destination": Path.home() / config["service_destination"], "content": content.encode("utf-8"), } def slweb_tools_path(config): relative = PurePosixPath(config.get("install_directory", "")) if relative.is_absolute() or ".." in relative.parts or not relative.parts: raise RuntimeError("SLWeb install directory must be a safe relative path") destination = Path.home() / Path(*relative.parts) validate_user_destination(destination) return destination def extract_slweb_tools(archive_path, destination, source_directory): source_root = PurePosixPath(source_directory) if source_root.is_absolute() or ".." in source_root.parts or len(source_root.parts) != 1: raise RuntimeError("SLWeb source directory must be one safe repository directory") with tarfile.open(archive_path, "r:gz") as archive: selected = [] roots = set() for member in archive.getmembers(): member_path = PurePosixPath(member.name) if ( member_path.is_absolute() or ".." in member_path.parts or len(member_path.parts) < 2 or member_path.parts[1] != source_root.name ): continue roots.add(member_path.parts[0]) if not (member.isdir() or member.isfile()): raise RuntimeError(f"unsupported SLWeb source member: {member.name}") selected.append((member, member_path)) if len(roots) != 1: raise RuntimeError("SooperLooper archive does not contain one tools directory") if not selected: raise RuntimeError("SooperLooper archive has no tools directory") tools_root = destination / source_root.name tools_root.mkdir(parents=True, exist_ok=True) for member, member_path in selected: relative = PurePosixPath(*member_path.parts[2:]) if not relative.parts: continue output_path = tools_root.joinpath(*relative.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 SLWeb source member: {member.name}") with source, output_path.open("wb") as output: shutil.copyfileobj(source, output) output_path.chmod(0o755 if member.mode & 0o111 else 0o644) required_files = ( tools_root / "slweb.py", tools_root / "slweb_web" / "index.html", tools_root / "slweb_web" / "app.css", tools_root / "slweb_web" / "app.js", ) if any(not path.is_file() for path in required_files): raise RuntimeError("SooperLooper tools directory is missing SLWeb or its web assets") def install_slweb_tools(config, source_config, registry): destination = slweb_tools_path(config) managed = registry.get("slweb") if managed is not None: if managed.get("destination") != str(destination): raise RuntimeError("recorded SLWeb installation path changed") if managed.get("pending_uninstall"): raise RuntimeError("SLWeb uninstall is incomplete; retry uninstall slweb first") backup = validate_backup_path( managed.get("backup"), destination, is_directory=True ) if (backup is None) != (managed.get("backup_sha256") is None): raise RuntimeError("invalid SLWeb backup record") if backup is not None and backup.exists(): if not backup.is_dir() or tree_sha256(backup) != managed.get("backup_sha256"): raise RuntimeError(f"recorded SLWeb backup changed locally: {backup}") elif backup is not None: raise RuntimeError(f"recorded SLWeb backup is missing: {backup}") if not destination.is_dir(): raise RuntimeError(f"managed SLWeb tools directory is missing: {destination}") if tree_sha256(destination) != managed.get("installed_sha256"): raise RuntimeError(f"managed SLWeb tools changed locally; refusing overwrite: {destination}") if managed.get("tag") == source_config["tag"]: print(f"SLWeb tools from SooperLooper tag {source_config['tag']} are already installed and unchanged.") return managed backup_path = destination.with_name(destination.name + ".rigforge-backup") if managed is None and (backup_path.exists() or backup_path.is_symlink()): raise RuntimeError(f"SLWeb backup path already exists: {backup_path}") if destination.exists() and not destination.is_dir(): raise RuntimeError(f"SLWeb destination is not a directory: {destination}") staged = destination.with_name(destination.name + ".rigforge-new") previous = destination.with_name(destination.name + ".rigforge-old") if staged.exists() or staged.is_symlink() or previous.exists() or previous.is_symlink(): raise RuntimeError(f"SLWeb staging or recovery path already exists: {destination}") source_url = source_config["source_url"].rstrip("/") tag = source_config["tag"] if ( source_url != "https://github.com/jojolb/sooperlooper-mods" or not isinstance(tag, str) or not re.fullmatch(r"[A-Za-z0-9._-]+", tag) ): raise RuntimeError("SLWeb requires the approved SooperLooper GitHub source and tag") archive_url = f"{source_url}/archive/refs/tags/{tag}.tar.gz" try: with tempfile.TemporaryDirectory(prefix="rigforge-slweb-") as temporary_dir: temporary = Path(temporary_dir) archive_path = temporary / "sooperlooper-source.tar.gz" download_archive(archive_url, archive_path) archive_digest = hashlib.sha256(archive_path.read_bytes()).hexdigest() extracted = temporary / "source" extracted.mkdir() extract_slweb_tools(archive_path, extracted, config["source_directory"]) shutil.copytree(extracted, staged) except Exception: if staged.exists(): shutil.rmtree(staged) raise backup = managed.get("backup") if managed is not None else None backup_digest = managed.get("backup_sha256") if managed is not None else None backup_created = False moved_previous = False try: if managed is None and destination.exists(): shutil.copytree(destination, backup_path, symlinks=True) backup = str(backup_path) backup_digest = tree_sha256(backup_path) backup_created = True destination.parent.mkdir(parents=True, exist_ok=True) if destination.exists(): os.replace(destination, previous) moved_previous = True os.replace(staged, destination) installed_digest = tree_sha256(destination) record = { "destination": str(destination), "source_url": source_url, "tag": tag, "archive_sha256": archive_digest, "installed_sha256": installed_digest, "backup": backup, "backup_sha256": backup_digest, } registry["slweb"] = record write_registry(registry) except (OSError, shutil.Error): if destination.exists() and moved_previous: shutil.rmtree(destination) if moved_previous and previous.exists(): os.replace(previous, destination) if backup_created and backup_path.exists(): shutil.rmtree(backup_path) if staged.exists(): shutil.rmtree(staged) raise if previous.exists(): shutil.rmtree(previous) print(f"Installed SLWeb tools from {tag} at {destination}.") print(f"Downloaded SooperLooper source archive SHA-256 (identity only): {archive_digest}") return record def uninstall_slweb_tools(config, registry): managed = registry.get("slweb") if managed is None: print("No managed SLWeb tools to uninstall.") return destination = slweb_tools_path(config) if managed.get("destination") != str(destination): raise RuntimeError("recorded SLWeb installation path changed") backup = validate_backup_path(managed.get("backup"), destination, is_directory=True) backup_digest = managed.get("backup_sha256") if (backup is None) != (backup_digest is None): raise RuntimeError("invalid SLWeb backup record") if backup is not None and backup.exists(): if not backup.is_dir() or tree_sha256(backup) != backup_digest: raise RuntimeError(f"recorded SLWeb backup changed locally: {backup}") current_digest = tree_sha256(destination) if destination.is_dir() else None if destination.exists() and not destination.is_dir(): raise RuntimeError(f"SLWeb destination has the wrong type: {destination}") if managed.get("pending_uninstall"): if current_digest not in {managed.get("installed_sha256"), backup_digest, None}: raise RuntimeError(f"unexpected SLWeb files block uninstall: {destination}") elif current_digest != managed.get("installed_sha256"): raise RuntimeError(f"managed SLWeb tools changed locally; refusing removal: {destination}") if backup is not None and not backup.exists() and current_digest == managed.get("installed_sha256"): raise RuntimeError(f"recorded SLWeb backup is missing: {backup}") managed["pending_uninstall"] = True registry["slweb"] = managed write_registry(registry) if current_digest == managed.get("installed_sha256"): shutil.rmtree(destination) if backup is not None and backup.exists(): if destination.exists(): raise RuntimeError(f"unexpected destination blocks SLWeb backup restore: {destination}") os.replace(backup, destination) registry.pop("slweb") write_registry(registry) print("SLWeb tools removed; prior directory restored if present.") def render_slweb_service(config, source_config, tools_digest): destination = slweb_tools_path(config) service_template = ROOT / config["service_source"] if not service_template.is_file(): raise RuntimeError(f"SLWeb service template is missing: {service_template}") replacements = { "@SLWEB_DIRECTORY@": systemd_quote(destination), "@PYTHON@": systemd_quote(config["python_path"]), "@OSC_HOST@": source_config["osc"]["host"], "@OSC_PORT@": str(source_config["osc"]["port"]), "@HTTP_HOST@": config["http_host"], "@HTTP_PORT@": str(config["http_port"]), } content = service_template.read_text(encoding="utf-8") for placeholder, replacement in replacements.items(): content = content.replace(placeholder, replacement) if re.search(r"@[A-Z_]+@", content): raise RuntimeError("unexpanded placeholder remains in SLWeb service template") fingerprint = hashlib.sha256( json.dumps( {"slweb": config, "sooperlooper_source": source_config, "tools_sha256": tools_digest}, sort_keys=True, separators=(",", ":"), ).encode("utf-8") + content.encode("utf-8") ).hexdigest() content += f"\n# Rigforge runtime fingerprint: {fingerprint}\n" return { "name": config["user_service"], "destination": Path.home() / config["service_destination"], "content": content.encode("utf-8"), } def atomic_install_bytes(content, destination): destination.parent.mkdir(parents=True, exist_ok=True) fd, temporary_name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent) try: with os.fdopen(fd, "wb") as stream: stream.write(content) os.chmod(temporary_name, 0o644) os.replace(temporary_name, destination) finally: if os.path.exists(temporary_name): os.unlink(temporary_name) def deploy_single_user_service(action, registry_key, target_name, display_name, unit, registry): destination = unit["destination"] service_name = unit["name"] validate_user_destination(destination) if destination.exists() and not destination.is_file(): raise RuntimeError(f"{display_name} service destination has the wrong type: {destination}") managed = registry.get(registry_key) if action == "reload": if managed is None: raise RuntimeError( f"{display_name} is not managed; install {target_name} before reloading it" ) if managed.get("pending_uninstall"): raise RuntimeError( f"{display_name} uninstall is incomplete; retry uninstall {target_name} first" ) if not destination.is_file(): raise RuntimeError(f"managed {display_name} service file is missing: {destination}") if file_sha256(destination) != managed.get("installed_sha256"): raise RuntimeError(f"managed {display_name} service file changed locally: {destination}") run(["systemctl", "--user", "restart", service_name]) run(["systemctl", "--user", "is-active", "--quiet", service_name]) print(f"Rigforge {display_name} user service restarted.") return if action == "uninstall": if managed is None: print(f"No managed {display_name} service to uninstall.") return backup_path = validate_backup_path(managed.get("backup"), destination) backup_digest = managed.get("backup_sha256") if backup_path is not None and backup_path.exists(): if not backup_path.is_file() or file_sha256(backup_path) != backup_digest: raise RuntimeError( f"recorded {display_name} service backup changed locally: {backup_path}" ) elif backup_path is not None and not managed.get("pending_uninstall"): raise RuntimeError(f"recorded {display_name} service backup is missing: {backup_path}") if (backup_path is None) != (backup_digest is None): raise RuntimeError(f"invalid {display_name} service backup record") current_digest = file_sha256(destination) recoverable_digests = {managed.get("installed_sha256"), backup_digest, None} if managed.get("pending_uninstall"): if current_digest not in recoverable_digests: raise RuntimeError(f"unexpected file blocks {display_name} uninstall: {destination}") elif current_digest != managed.get("installed_sha256"): raise RuntimeError( f"managed {display_name} service file changed locally; refusing removal: {destination}" ) if ( backup_path is not None and not backup_path.exists() and current_digest == managed.get("installed_sha256") ): raise RuntimeError( f"recorded {display_name} service backup is missing; refusing removal: {backup_path}" ) managed["pending_uninstall"] = True registry[registry_key] = managed write_registry(registry) run(["systemctl", "--user", "disable", "--now", service_name]) if backup_path is not None and current_digest == backup_digest: if backup_path.exists(): backup_path.unlink() else: if current_digest == managed.get("installed_sha256"): destination.unlink() elif current_digest is not None: raise RuntimeError(f"unexpected file blocks {display_name} uninstall: {destination}") if backup_path is not None: if backup_path.exists(): os.replace(backup_path, destination) elif file_sha256(destination) != backup_digest: raise RuntimeError( f"recorded {display_name} service backup is missing: {backup_path}" ) run(["systemctl", "--user", "daemon-reload"]) registry.pop(registry_key) write_registry(registry) print(f"Rigforge {display_name} user service removed; prior unit restored if present.") return content = unit["content"] installed_digest = hashlib.sha256(content).hexdigest() if managed is not None and managed.get("pending_uninstall"): raise RuntimeError( f"{display_name} uninstall is incomplete; retry uninstall {target_name} first" ) if managed is None: if user_unit_is_active(service_name) or user_unit_is_enabled(service_name): raise RuntimeError( f"an unmanaged {service_name} is already active or enabled; " "inspect it before installing Rigforge's unit" ) backup_path = ( destination.with_name(destination.name + ".rigforge-backup") if destination.is_file() else None ) if backup_path is not None and (backup_path.exists() or backup_path.is_symlink()): raise RuntimeError(f"backup path already exists: {backup_path}") backup = str(backup_path) if destination.is_file() else None backup_digest = file_sha256(destination) previous_digest = None pending_install = True else: if managed.get("destination") != str(destination): raise RuntimeError(f"recorded {display_name} service path changed") backup_path = validate_backup_path(managed.get("backup"), destination) backup = str(backup_path) if backup_path is not None else None backup_digest = managed.get("backup_sha256") if (backup_path is None) != (backup_digest is None): raise RuntimeError(f"invalid {display_name} service backup record") if backup_path is not None and backup_path.exists(): if not backup_path.is_file() or file_sha256(backup_path) != backup_digest: raise RuntimeError( f"recorded {display_name} service backup changed locally: {backup_path}" ) elif backup_path is not None and not managed.get("pending_install"): raise RuntimeError(f"recorded {display_name} service backup is missing: {backup_path}") previous_digest = ( managed.get("previous_installed_sha256") if managed.get("pending_install") else managed.get("installed_sha256") ) current_digest = file_sha256(destination) if managed.get("pending_install"): if current_digest not in {previous_digest, backup_digest, None}: raise RuntimeError( f"{display_name} service changed locally during interrupted install: {destination}" ) elif current_digest != previous_digest: raise RuntimeError(f"managed {display_name} service file changed locally: {destination}") pending_install = current_digest != installed_digest unit_changed = file_sha256(destination) != installed_digest restart_required = managed is None or unit_changed or bool( managed and managed.get("pending_activation") ) managed = managed or {} managed.update({ "destination": str(destination), "installed_sha256": installed_digest, "previous_installed_sha256": previous_digest, "backup": backup, "backup_sha256": backup_digest, "pending_install": pending_install, "pending_activation": True, }) registry[registry_key] = managed write_registry(registry) if backup_path is not None: if backup_path.exists(): if not backup_path.is_file() or file_sha256(backup_path) != backup_digest: raise RuntimeError( f"recorded {display_name} service backup changed locally: {backup_path}" ) elif file_sha256(destination) == backup_digest: shutil.copy2(destination, backup_path) else: raise RuntimeError(f"recorded {display_name} service backup is missing: {backup_path}") if unit_changed: atomic_install_bytes(content, destination) managed.pop("previous_installed_sha256", None) managed.pop("pending_install", None) registry[registry_key] = managed write_registry(registry) run(["systemctl", "--user", "daemon-reload"]) run(["systemctl", "--user", "enable", service_name]) run([ "systemctl", "--user", "restart" if restart_required else "start", service_name, ]) run(["systemctl", "--user", "is-active", "--quiet", service_name]) managed.pop("pending_activation", None) registry[registry_key] = managed write_registry(registry) print(f"Installed and activated Rigforge {display_name} user service at {destination}.") def deploy_midi_bridge(action, config, registry): if action == "install" and "mod_ui" not in registry: raise RuntimeError("install mod-ui before installing the MIDI bridge") unit = render_midi_bridge_service(config) deploy_single_user_service( action, "midi_bridge", "midi-bridge", "MIDI bridge", unit, registry ) def deploy_mod_host_ports(action, config, registry): if action == "uninstall" and ( "mod_host" in registry or "mod_ui" in registry ): raise RuntimeError("uninstall mod-ui and mod-host before uninstalling mod-host-ports") unit = render_mod_host_ports_service(config) deploy_single_user_service( action, "mod_host_ports", "mod-host-ports", "mod-host PipeWire ports", unit, registry, ) def mod_ui_nam_model_sources(state): nam = state["routing"]["mod_host_chains"]["guitar"]["processors"][0] relative_paths = {nam["asset_path"], *nam.get("available_models", {}).values()} sources = {} for relative in sorted(relative_paths): source = (ROOT / Path(*PurePosixPath(relative).parts)).resolve() if not source.is_relative_to(ROOT.resolve()) or not source.is_file(): raise FileNotFoundError( f"declared NAM model is missing or outside repository: {source}" ) if source.name in sources and sources[source.name] != source: raise RuntimeError( f"declared NAM models have a filename collision: {source.name}" ) sources[source.name] = source return sources def manage_mod_ui_nam_models(action, config, registry, state): key = "mod_ui_nam_models" root = Path.home() / config["user_files_directory"] / "NAM Models" / "Rigforge" managed = registry.get(key) if action == "uninstall": if managed is None: return if managed.get("directory") != str(root): raise RuntimeError("managed mod-ui NAM model directory changed") recorded = managed.get("files") if not isinstance(recorded, dict): raise RuntimeError("managed mod-ui NAM model registry is invalid") for name, digest in recorded.items(): destination = root / name validate_user_destination(destination) if destination.is_symlink(): raise RuntimeError(f"managed NAM model became a symlink: {destination}") if destination.exists() and ( not destination.is_file() or file_sha256(destination) != digest ): raise RuntimeError( f"managed NAM model changed locally; refusing to remove: {destination}" ) for name in recorded: (root / name).unlink(missing_ok=True) try: root.rmdir() except OSError: pass registry.pop(key) write_registry(registry) return if action != "install": return sources = mod_ui_nam_model_sources(state) if managed is None: recorded = {} else: if managed.get("directory") != str(root): raise RuntimeError("managed mod-ui NAM model directory changed") recorded = managed.get("files") if not isinstance(recorded, dict): raise RuntimeError("managed mod-ui NAM model registry is invalid") if set(recorded) - set(sources): raise RuntimeError("managed mod-ui NAM model set changed; uninstall mod-ui first") root.mkdir(parents=True, exist_ok=True) plan = [] for name, source in sources.items(): destination = root / name validate_user_destination(destination) if destination.is_symlink(): raise RuntimeError( f"refusing to replace symlink in mod-ui NAM directory: {destination}" ) expected_digest = file_sha256(source) current_digest = file_sha256(destination) prior_digest = recorded.get(name) if prior_digest is not None: if current_digest != prior_digest: raise RuntimeError( f"managed NAM model changed locally; refusing overwrite: {destination}" ) plan.append((name, source, destination, expected_digest, current_digest != expected_digest)) elif current_digest is None: plan.append((name, source, destination, expected_digest, True)) elif current_digest != expected_digest: raise RuntimeError( f"unmanaged file conflicts with declared NAM model: {destination}" ) installed = dict(recorded) for name, source, destination, expected_digest, needs_install in plan: if needs_install: atomic_install(source, destination) installed[name] = expected_digest registry[key] = {"directory": str(root), "files": installed} write_registry(registry) def deploy_mod_ui(action, config, registry, force_reference=False): if action == "install": if "mod_host_ports" not in registry: raise RuntimeError("install mod-host-ports before installing mod-ui") if "mod_host" not in registry: raise RuntimeError("install mod-host before installing mod-ui") if "mod_ui" not in registry and mod_ui_port_is_open( config["websocket_host"], config["websocket_port"] ): raise RuntimeError( f"mod-ui web port {config['websocket_port']} is already in use; " "stop any manually launched mod-ui before installing the service" ) if "mod_ui" not in registry and ( user_unit_is_active(config["user_service"]) or user_unit_is_enabled(config["user_service"]) ): raise RuntimeError( f"an unmanaged {config['user_service']} is already active or enabled; " "inspect it before installing Rigforge's unit" ) if action == "reset": reset_mod_ui_reference(config, registry) return if action == "uninstall" and "midi_bridge" in registry: raise RuntimeError("uninstall midi-bridge before uninstalling mod-ui") state = yaml.safe_load( (ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8") ) if action == "install": manage_mod_ui_nam_models("install", config, registry, state) unit = render_mod_ui_service(config) reference_sha256 = None if action != "uninstall": managed = registry.get("mod_ui", {}) reference_record = managed.get("reference_bundle", {}) trusted_reference_sha256 = None if reference_record.get("destination") == str(unit["reference_bundle"]): trusted_reference_sha256 = reference_record.get("installed_sha256") if force_reference and ( not isinstance(trusted_reference_sha256, str) or not trusted_reference_sha256 ): raise RuntimeError( "--force-reference requires a registry-managed reference bundle at the generated path" ) reference_sha256 = prepare_mod_ui_reference_bundle( unit, trusted_existing_sha256=trusted_reference_sha256, force_reference=force_reference, ) if "mod_ui" in registry: registry["mod_ui"]["reference_bundle"] = { "destination": str(unit["reference_bundle"]), "installed_sha256": reference_sha256, } write_registry(registry) deploy_single_user_service( action, "mod_ui", "mod-ui", "mod-ui", unit, registry, ) if action == "uninstall": manage_mod_ui_nam_models("uninstall", config, registry, state) if action == "install": registry["mod_ui"]["reference_bundle"] = { "destination": str(unit["reference_bundle"]), "installed_sha256": reference_sha256, } write_registry(registry) def next_reset_backup_path(path): base = path.with_name(path.name + ".rigforge-reset-backup") candidate = base suffix = 1 while candidate.exists() or candidate.is_symlink(): suffix += 1 candidate = base.with_name(base.name + f".{suffix}") validate_user_destination(candidate) return candidate def next_mod_ui_reference_backup_path(destination, forced=False): suffix = "force-backup" if forced else "corrupt-backup" base = destination.with_name(destination.name + f".rigforge-{suffix}") candidate = base suffix = 2 while candidate.exists() or candidate.is_symlink(): candidate = base.with_name(f"{base.name}.{suffix}") suffix += 1 validate_user_destination(candidate) return candidate def prepare_mod_ui_reference_bundle( unit, trusted_existing_sha256=None, force_reference=False ): destination = unit["reference_bundle"] files = unit["reference_files"] validate_user_destination(destination) if destination.exists(): if destination.is_symlink() or not destination.is_dir(): raise RuntimeError(f"generated mod-ui reference path has the wrong type: {destination}") current_files = {} for path in destination.rglob("*"): if path.is_symlink(): raise RuntimeError(f"generated mod-ui reference contains a symlink: {path}") if path.is_file(): current_files[path.relative_to(destination).as_posix()] = path.read_bytes() if current_files != files: current_sha256 = tree_sha256(destination) matches_registry = ( trusted_existing_sha256 is not None and current_sha256 == trusted_existing_sha256 ) if not matches_registry and not ( force_reference and trusted_existing_sha256 is not None ): raise RuntimeError(f"generated mod-ui reference changed locally: {destination}") destination.parent.mkdir(parents=True, exist_ok=True) staged = Path( tempfile.mkdtemp(prefix=f".{destination.name}.", dir=destination.parent) ) try: for relative, content in files.items(): path = staged / relative path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(content) if tree_sha256(staged) == current_sha256: raise RuntimeError( f"regenerated mod-ui reference unexpectedly matches corrupted data: {destination}" ) backup = next_mod_ui_reference_backup_path( destination, forced=force_reference and not matches_registry ) os.replace(destination, backup) print(f"Preserved previous mod-ui reference bundle at {backup}") try: os.replace(staged, destination) except OSError: os.replace(backup, destination) raise finally: if staged.exists(): shutil.rmtree(staged) else: destination.parent.mkdir(parents=True, exist_ok=True) staged = Path(tempfile.mkdtemp(prefix=f".{destination.name}.", dir=destination.parent)) try: for relative, content in files.items(): path = staged / relative path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(content) os.replace(staged, destination) finally: if staged.exists(): shutil.rmtree(staged) return tree_sha256(destination) def reset_mod_ui_reference(config, registry): managed = registry.get("mod_ui") if managed is None: raise RuntimeError("mod-ui is not managed; install mod-ui before resetting it") if managed.get("pending_uninstall"): raise RuntimeError("mod-ui uninstall is incomplete; retry uninstall mod-ui first") unit = render_mod_ui_service(config) destination = unit["destination"] if not destination.is_file() or file_sha256(destination) != managed.get("installed_sha256"): raise RuntimeError(f"managed mod-ui service file changed locally: {destination}") reference = unit["reference_bundle"] reference_record = managed.get("reference_bundle") if not isinstance(reference_record, dict): raise RuntimeError("mod-ui reference bundle is missing from the deployment registry") reference_sha256 = reference_record.get("installed_sha256") if ( reference_record.get("destination") != str(reference) or reference.is_symlink() or not reference.is_dir() or tree_sha256(reference) != reference_sha256 ): raise RuntimeError(f"managed mod-ui reference pedalboard changed locally: {reference}") repaired_reference_sha256 = prepare_mod_ui_reference_bundle( unit, trusted_existing_sha256=reference_sha256 ) if repaired_reference_sha256 != reference_sha256: reference_record["installed_sha256"] = repaired_reference_sha256 managed["reference_bundle"] = reference_record registry["mod_ui"] = managed write_registry(registry) pedalboards = Path.home() / config["pedalboards_directory"] default_board = pedalboards / "default.pedalboard" last_state = Path.home() / config["last_state_file"] for path in (default_board, last_state): validate_user_destination(path) if path.is_symlink(): raise RuntimeError(f"refusing to reset a symlink: {path}") if default_board.exists() and not default_board.is_dir(): raise RuntimeError(f"mod-ui default pedalboard has the wrong type: {default_board}") if last_state.exists() and not last_state.is_file(): raise RuntimeError(f"mod-ui last-state path has the wrong type: {last_state}") backup_board = next_reset_backup_path(default_board) backup_state = next_reset_backup_path(last_state) staged = default_board.with_name(default_board.name + ".rigforge-reset-new") if staged.exists() or staged.is_symlink(): raise RuntimeError(f"reset staging path already exists: {staged}") default_board.parent.mkdir(parents=True, exist_ok=True) shutil.copytree(reference, staged, symlinks=False) run(["systemctl", "--user", "stop", config["user_service"]]) board_backed_up = False state_backed_up = False reference_installed = False try: if default_board.exists(): os.replace(default_board, backup_board) board_backed_up = True if last_state.exists(): os.replace(last_state, backup_state) state_backed_up = True os.replace(staged, default_board) reference_installed = True run(["systemctl", "--user", "start", config["user_service"]]) run(["systemctl", "--user", "is-active", "--quiet", config["user_service"]]) if "midi_bridge" in registry: run(["systemctl", "--user", "start", "rigforge-midi-bridge.service"]) run(["systemctl", "--user", "is-active", "--quiet", "rigforge-midi-bridge.service"]) except (OSError, subprocess.CalledProcessError): try: run(["systemctl", "--user", "stop", config["user_service"]]) except subprocess.CalledProcessError: pass if staged.exists(): shutil.rmtree(staged) if reference_installed and default_board.exists(): shutil.rmtree(default_board) if board_backed_up and backup_board.exists(): os.replace(backup_board, default_board) if state_backed_up and backup_state.exists(): os.replace(backup_state, last_state) run(["systemctl", "--user", "start", config["user_service"]]) raise print( "Rigforge reference pedalboard restored. Previous default and last-state data " "were preserved as adjacent .rigforge-reset-backup files when present." ) def deploy_sooperlooper(action, config, registry, state=None): if action == "uninstall" and ( "slweb" in registry or "slweb_service" in registry ): raise RuntimeError("uninstall slweb before uninstalling SooperLooper") if state is None: state = yaml.safe_load( (ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8") ) unit = render_sooperlooper_service(config, state) deploy_single_user_service( action, "sooperlooper", "sooperlooper", "SooperLooper", unit, registry ) def deploy_slweb(action, config, source_config, registry): if action == "install" and "sooperlooper" not in registry: raise RuntimeError("install sooperlooper before installing slweb") if action == "uninstall" and "slweb" not in registry and "slweb_service" not in registry: print("No managed SLWeb service or tools to uninstall.") return if action == "install": tools = install_slweb_tools(config, source_config, registry) else: tools = registry.get("slweb") if action == "reload" and tools is None: raise RuntimeError("SLWeb tools are not managed; install slweb before reloading it") if tools is not None: destination = slweb_tools_path(config) if destination.is_dir() and tree_sha256(destination) != tools.get("installed_sha256"): raise RuntimeError( f"managed SLWeb tools changed locally; refusing service operation: {destination}" ) if tools is None: raise RuntimeError("SLWeb tools are not managed; install slweb first") unit = render_slweb_service( config, source_config, tools.get("installed_sha256", "unmanaged") ) deploy_single_user_service(action, "slweb_service", "slweb", "SLWeb", unit, registry) if action == "uninstall": uninstall_slweb_tools(config, registry) def file_sha256(path): return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None def install_reconcile_units(config, registry): units = render_reconcile_units(config) managed = registry.get("reconcile") if managed is not None and managed.get("pending_uninstall"): raise RuntimeError("reconciliation units are pending uninstall; retry uninstall reconcile first") if managed is None and ( user_unit_is_active(config["user_service"]) or user_unit_is_active(config["user_timer"]) or user_unit_is_enabled(config["user_timer"]) ): raise RuntimeError( "an unmanaged Rigforge reconciliation unit is already active or enabled; " "inspect it before installing the managed timer" ) prior_files = managed.get("files", {}) if managed is not None else {} if managed is not None and set(prior_files) != set(units): raise RuntimeError("managed reconciliation unit registry has an unexpected file set") records = {} for key, unit in units.items(): destination = unit["destination"] validate_user_destination(destination) if destination.exists() and not destination.is_file(): raise RuntimeError(f"reconciliation unit destination has the wrong type: {destination}") current_digest = file_sha256(destination) prior = prior_files.get(key) if managed is not None else None if prior is None: if managed is not None: raise RuntimeError(f"reconciliation unit is missing from deployment registry: {key}") backup_path = destination.with_name(destination.name + ".rigforge-backup") if backup_path.exists() or backup_path.is_symlink(): raise RuntimeError(f"backup path already exists: {backup_path}") backup = str(backup_path) if destination.is_file() else None backup_digest = current_digest previous_digest = None else: if prior.get("destination") != str(destination): raise RuntimeError(f"recorded reconciliation unit path changed: {key}") backup_path = validate_backup_path(prior.get("backup"), destination) backup = str(backup_path) if backup_path is not None else None backup_digest = prior.get("backup_sha256") if (backup_path is None) != (backup_digest is None): raise RuntimeError(f"invalid reconciliation unit backup record: {key}") previous_digest = prior.get("installed_sha256") if backup_path is not None and backup_path.exists(): if not backup_path.is_file() or file_sha256(backup_path) != backup_digest: raise RuntimeError(f"recorded reconciliation unit backup changed locally: {backup_path}") elif ( backup_path is not None and not managed.get("pending_install") ): raise RuntimeError(f"recorded reconciliation unit backup is missing: {backup_path}") if managed.get("pending_install"): accepted_digests = { prior.get("installed_sha256"), prior.get("previous_installed_sha256"), backup_digest, None, } if current_digest not in accepted_digests: raise RuntimeError( f"reconciliation unit changed locally during interrupted install: {destination}" ) elif current_digest != prior.get("installed_sha256"): raise RuntimeError(f"managed reconciliation unit changed locally: {destination}") records[key] = { "destination": str(destination), "installed_sha256": hashlib.sha256(unit["content"]).hexdigest(), "previous_installed_sha256": previous_digest, "backup": backup, "backup_sha256": backup_digest, } managed = managed or {} managed["files"] = records managed["pending_install"] = True registry["reconcile"] = managed write_registry(registry) for key, unit in units.items(): record = records[key] backup_path = validate_backup_path(record["backup"], unit["destination"]) if backup_path is not None: if backup_path.exists(): if not backup_path.is_file() or file_sha256(backup_path) != record["backup_sha256"]: raise RuntimeError(f"reconciliation unit backup changed locally: {backup_path}") elif file_sha256(unit["destination"]) == record["backup_sha256"]: shutil.copy2(unit["destination"], backup_path) else: raise RuntimeError(f"reconciliation unit backup is missing: {backup_path}") unit_changed = ( not unit["destination"].is_file() or unit["destination"].read_bytes() != unit["content"] ) if unit_changed: atomic_install_bytes(unit["content"], unit["destination"]) for record in records.values(): record.pop("previous_installed_sha256", None) managed.pop("pending_install", None) registry["reconcile"] = managed write_registry(registry) timer_name = units["timer"]["name"] timer_changed = ( prior_files.get("timer", {}).get("installed_sha256") != records["timer"]["installed_sha256"] ) run(["systemctl", "--user", "daemon-reload"]) run(["systemctl", "--user", "enable", timer_name]) run( [ "systemctl", "--user", "restart" if timer_changed else "start", timer_name, ] ) run(["systemctl", "--user", "is-active", "--quiet", timer_name]) print(f"Installed and activated Rigforge reconciliation timer ({timer_name}).") def uninstall_reconcile_units(config, registry): managed = registry.get("reconcile") if managed is None: return units = render_reconcile_units(config) records = managed.get("files") if not isinstance(records, dict) or set(records) != set(units): raise RuntimeError("managed reconciliation unit registry has an unexpected file set") for key, unit in units.items(): record = records[key] destination = unit["destination"] validate_user_destination(destination) if record.get("destination") != str(destination): raise RuntimeError(f"recorded reconciliation unit path changed: {key}") if destination.exists() and not destination.is_file(): raise RuntimeError(f"reconciliation unit destination has the wrong type: {destination}") backup_path = validate_backup_path(record.get("backup"), destination) if backup_path is not None and backup_path.exists(): if not backup_path.is_file() or file_sha256(backup_path) != record.get("backup_sha256"): raise RuntimeError(f"recorded reconciliation unit backup changed locally: {backup_path}") elif backup_path is not None and not managed.get("pending_uninstall"): raise RuntimeError(f"recorded reconciliation unit backup is missing: {backup_path}") if (backup_path is None) != (record.get("backup_sha256") is None): raise RuntimeError(f"invalid reconciliation unit backup record: {key}") current_digest = file_sha256(destination) recoverable_digests = { record.get("installed_sha256"), record.get("backup_sha256"), None, } if managed.get("pending_uninstall"): if current_digest not in recoverable_digests: raise RuntimeError(f"unexpected file blocks reconciliation unit uninstall: {destination}") elif current_digest != record.get("installed_sha256"): raise RuntimeError(f"managed reconciliation unit changed locally; refusing removal: {destination}") managed["pending_uninstall"] = True registry["reconcile"] = managed write_registry(registry) run(["systemctl", "--user", "disable", "--now", config["user_timer"]]) run(["systemctl", "--user", "stop", config["user_service"]]) for key, unit in units.items(): record = records[key] destination = unit["destination"] backup_path = validate_backup_path(record.get("backup"), destination) current_digest = file_sha256(destination) if backup_path is not None and current_digest == record.get("backup_sha256"): if backup_path.exists(): backup_path.unlink() continue if current_digest == record.get("installed_sha256"): destination.unlink() elif current_digest is not None: raise RuntimeError(f"unexpected file blocks reconciliation unit uninstall: {destination}") if backup_path is not None: if backup_path.exists(): os.replace(backup_path, destination) elif file_sha256(destination) != record.get("backup_sha256"): raise RuntimeError(f"recorded reconciliation unit backup is missing: {backup_path}") run(["systemctl", "--user", "daemon-reload"]) registry.pop("reconcile") write_registry(registry) print("Rigforge reconciliation timer and units removed.") def deploy_reconcile(action, config, registry): if action == "install": install_reconcile_units(config, registry) return if action == "uninstall": uninstall_reconcile_units(config, registry) if "reconcile" not in registry: print("No managed reconciliation units to uninstall.") return managed = registry.get("reconcile") if managed is None: raise RuntimeError("reconciliation timer is not managed; install reconcile first") if managed.get("pending_install") or managed.get("pending_uninstall"): raise RuntimeError("reconciliation unit deployment is incomplete; retry install or uninstall reconcile") units = render_reconcile_units(config) records = managed.get("files") if not isinstance(records, dict) or set(records) != set(units): raise RuntimeError("managed reconciliation unit registry has an unexpected file set") for key, unit in units.items(): destination = unit["destination"] validate_user_destination(destination) if not destination.is_file() or file_sha256(destination) != records[key].get("installed_sha256"): raise RuntimeError(f"managed reconciliation unit changed locally or is missing: {destination}") run(["systemctl", "--user", "start", config["user_timer"]]) run(["systemctl", "--user", "is-active", "--quiet", config["user_timer"]]) run(["systemctl", "--user", "start", config["user_service"]]) print("Rigforge desired PipeWire graph reconciled once.") def mod_host_runtime_digest(config): state_path = ROOT / "config" / "desired-state.yaml" readiness_script = ROOT / config["readiness_script"] validator_path = ROOT / "scripts" / "validate_desired_state.py" binary_path = ROOT / config["binary_source"] with state_path.open(encoding="utf-8") as stream: state = yaml.safe_load(stream) guitar_chain = state["routing"]["mod_host_chains"]["guitar"] mod_host_config = state["deployment"]["mod_host"] files = [readiness_script, validator_path, binary_path] digest = hashlib.sha256() digest.update( json.dumps( { "deployment.mod_host": mod_host_config, "deployment.mod_host_ports": state["deployment"]["mod_host_ports"], "routing.mod_host_chains.guitar": guitar_chain, }, sort_keys=True, separators=(",", ":"), ).encode("utf-8") + b"\0" ) for path in files: if not path.is_file(): raise RuntimeError(f"mod-host runtime input is missing: {path}") digest.update(str(path.relative_to(ROOT.resolve())).encode("utf-8") + b"\0") digest.update(path.read_bytes()) digest.update(b"\0") return digest.hexdigest() def mod_host_port_is_open(port): try: with socket.create_connection(("127.0.0.1", port), timeout=0.25): return True except OSError: return False def mod_ui_port_is_open(host, port): try: with socket.create_connection((host, port), timeout=0.25): return True except OSError: return False def user_unit_is_active(service_name): result = subprocess.run( ["systemctl", "--user", "is-active", "--quiet", service_name], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) return result.returncode == 0 def user_unit_is_enabled(service_name): result = subprocess.run( ["systemctl", "--user", "is-enabled", "--quiet", service_name], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) return result.returncode == 0 def deploy_mod_host(action, config, registry): destination = Path.home() / config["service_destination"] validate_user_destination(destination) service_name = config["user_service"] managed = registry.get("mod_host") if action == "install" and "mod_host_ports" not in registry: raise RuntimeError("install mod-host-ports before installing mod-host") if action == "uninstall" and "mod_ui" in registry: raise RuntimeError("uninstall mod-ui before uninstalling mod-host") if managed is not None and not user_unit_is_active(service_name): occupied_ports = [ port for port in (config["socket_port"], config["feedback_port"]) if mod_host_port_is_open(port) ] if occupied_ports: raise RuntimeError( "mod-host TCP port(s) " f"{occupied_ports} are open while the managed service is inactive; " "stop any unmanaged/manual mod-host process before retrying" ) if action == "reload": if managed is None: raise RuntimeError("mod-host is not managed; install mod-host before reloading it") if managed.get("pending_uninstall"): raise RuntimeError("mod-host uninstall is incomplete; retry uninstall mod-host first") if not destination.is_file(): raise RuntimeError(f"managed mod-host service file is missing: {destination}") digest = hashlib.sha256(destination.read_bytes()).hexdigest() if digest != managed.get("installed_sha256"): raise RuntimeError(f"managed mod-host service file changed locally: {destination}") run(["systemctl", "--user", "restart", service_name]) run(["systemctl", "--user", "is-active", "--quiet", service_name]) print("Rigforge mod-host user service restarted.") return if action == "uninstall": if managed is None: print("No managed mod-host service to uninstall.") return backup_path = validate_backup_path(managed.get("backup"), destination) if backup_path is not None and backup_path.exists(): if not backup_path.is_file(): raise RuntimeError(f"recorded mod-host service backup has the wrong type: {backup_path}") if hashlib.sha256(backup_path.read_bytes()).hexdigest() != managed.get("backup_sha256"): raise RuntimeError(f"recorded mod-host service backup changed locally: {backup_path}") if not managed.get("pending_uninstall"): if not destination.is_file(): raise RuntimeError(f"managed mod-host service file is missing: {destination}") digest = hashlib.sha256(destination.read_bytes()).hexdigest() if digest != managed.get("installed_sha256"): raise RuntimeError(f"managed mod-host service file changed locally; refusing removal: {destination}") managed["pending_uninstall"] = True registry["mod_host"] = managed write_registry(registry) destination_digest = ( hashlib.sha256(destination.read_bytes()).hexdigest() if destination.is_file() else None ) backup_digest = ( hashlib.sha256(backup_path.read_bytes()).hexdigest() if backup_path is not None and backup_path.is_file() else None ) installed_digest = managed.get("installed_sha256") already_restored = ( backup_path is not None and destination_digest == managed.get("backup_sha256") ) already_removed = destination_digest is None and backup_digest is None and backup_path is None if not already_restored and not already_removed: if destination_digest not in {installed_digest, None}: raise RuntimeError(f"unexpected file blocks mod-host uninstall: {destination}") run(["systemctl", "--user", "disable", "--now", service_name]) if destination_digest == installed_digest: destination.unlink() if backup_path is not None and backup_path.exists(): os.replace(backup_path, destination) elif backup_path is not None: raise RuntimeError(f"recorded mod-host service backup is missing: {backup_path}") run(["systemctl", "--user", "daemon-reload"]) registry.pop("mod_host") write_registry(registry) print("Rigforge mod-host user service removed; prior unit state restored if present.") return # Install is intentionally an explicit target, not part of "all": it # activates the guitar processing chain and can make audio audible. content = render_mod_host_service(config) installed_digest = hashlib.sha256(content).hexdigest() runtime_digest = mod_host_runtime_digest(config) previous_runtime_digest = managed.get("runtime_sha256") if managed is not None else None restart_required = managed is None or runtime_digest != previous_runtime_digest if managed is not None: if managed.get("pending_uninstall"): raise RuntimeError("mod-host uninstall is incomplete; retry uninstall mod-host first") backup_path = validate_backup_path(managed.get("backup"), destination) if backup_path is not None: if not backup_path.is_file(): raise RuntimeError(f"recorded mod-host service backup is missing: {backup_path}") if hashlib.sha256(backup_path.read_bytes()).hexdigest() != managed.get("backup_sha256"): raise RuntimeError(f"recorded mod-host service backup changed locally: {backup_path}") if not destination.is_file(): if not managed.get("pending_install"): raise RuntimeError(f"managed mod-host service file is missing: {destination}") if destination.exists() and not destination.is_file(): raise RuntimeError(f"managed mod-host service destination has the wrong type: {destination}") current_digest = ( hashlib.sha256(destination.read_bytes()).hexdigest() if destination.is_file() else None ) if current_digest is not None and current_digest != managed.get("installed_sha256"): prior_digest = managed.get("backup_sha256") if not managed.get("pending_install") or current_digest != prior_digest: raise RuntimeError( f"managed mod-host service file changed locally; refusing overwrite: {destination}" ) elif not destination.exists() and not managed.get("pending_install"): raise RuntimeError(f"managed mod-host service file changed locally; refusing overwrite: {destination}") backup = managed.get("backup") backup_sha256 = managed.get("backup_sha256") else: if user_unit_is_active(service_name) or user_unit_is_enabled(service_name): raise RuntimeError( f"an unmanaged {service_name} is already active or enabled; " "inspect and disable it before installing Rigforge's unit" ) if mod_host_port_is_open(config["socket_port"]): raise RuntimeError( f"mod-host control port {config['socket_port']} is already in use; " "stop the unmanaged test process before installing the user service" ) if mod_host_port_is_open(config["feedback_port"]): raise RuntimeError( f"mod-host feedback port {config['feedback_port']} is already in use; " "stop the unmanaged test process before installing the user service" ) backup = None backup_sha256 = None if destination.exists(): backup_path = destination.with_name(destination.name + ".rigforge-backup") if backup_path.exists(): raise RuntimeError(f"backup path already exists: {backup_path}") shutil.copy2(destination, backup_path) backup = str(backup_path) backup_sha256 = hashlib.sha256(backup_path.read_bytes()).hexdigest() unit_changed = not destination.exists() or destination.read_bytes() != content restart_required = ( restart_required or unit_changed or (managed is not None and managed.get("pending_activation", False)) ) if managed is None: managed = { "installed_sha256": installed_digest, "runtime_sha256": runtime_digest, "backup": backup, "backup_sha256": backup_sha256, "pending_install": unit_changed, "pending_activation": True, } else: managed["installed_sha256"] = installed_digest managed["runtime_sha256"] = runtime_digest managed["pending_install"] = unit_changed managed["pending_activation"] = True registry["mod_host"] = managed write_registry(registry) if unit_changed: destination.parent.mkdir(parents=True, exist_ok=True) fd, temporary_name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent) try: with os.fdopen(fd, "wb") as stream: stream.write(content) os.chmod(temporary_name, 0o644) os.replace(temporary_name, destination) finally: if os.path.exists(temporary_name): os.unlink(temporary_name) managed.pop("pending_install", None) registry["mod_host"] = managed write_registry(registry) run(["systemctl", "--user", "daemon-reload"]) run(["systemctl", "--user", "enable", service_name]) if restart_required: run(["systemctl", "--user", "restart", service_name]) else: run(["systemctl", "--user", "start", service_name]) run(["systemctl", "--user", "is-active", "--quiet", service_name]) managed.pop("pending_activation", None) registry["mod_host"] = managed write_registry(registry) print(f"Installed and activated Rigforge mod-host user service at {destination}.") def main(argv=None): parser = argparse.ArgumentParser() parser.add_argument("action", choices=("install", "uninstall", "reload", "reset")) parser.add_argument( "target", choices=( "namlv2", "lsp", "dragonfly-reverb", "pipewire", "mod-host-ports", "mod-host", "mod-ui", "reconcile", "midi-bridge", "sooperlooper", "slweb", ), ) parser.add_argument( "--force-reference", action="store_true", help="replace a changed registry-managed mod-ui reference after preserving it", ) args = parser.parse_args(argv) if args.action == "reset" and args.target != "mod-ui": parser.error("reset is only supported for mod-ui") if args.force_reference and (args.action != "install" or args.target != "mod-ui"): parser.error("--force-reference is only valid with install mod-ui") 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) elif args.target == "pipewire": deploy_pipewire(args.action, deployment["pipewire"], registry, quantum_frames) elif args.target == "mod-host": deploy_mod_host(args.action, deployment["mod_host"], registry) elif args.target == "mod-host-ports": deploy_mod_host_ports(args.action, deployment["mod_host_ports"], registry) elif args.target == "mod-ui": deploy_mod_ui( args.action, deployment["mod_ui"], registry, force_reference=args.force_reference, ) elif args.target == "reconcile": deploy_reconcile(args.action, deployment["reconcile"], registry) elif args.target == "midi-bridge": deploy_midi_bridge(args.action, deployment["midi_bridge"], registry) elif args.target == "sooperlooper": deploy_sooperlooper( args.action, deployment["sooperlooper"], registry, state=state ) elif args.target == "slweb": deploy_slweb( args.action, deployment["slweb"], deployment["sooperlooper"], registry ) 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: print(f"ERROR: {error}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())