import argparse import json import re import subprocess import sys from pathlib import Path import yaml from validate_desired_state import validate_state as validate_desired_state MANAGED_ENDPOINT_PATTERN = re.compile( r"^(?:" r"alsa_input\.hw_U192k_0:capture_AUX[0-3]|" r"alsa_output\.hw_U192k_0:playback_AUX[0-3]|" r"rigforge\.direct-mix\.input:playback_AUX[0-8]|" r"rigforge\.direct-mix\.output:capture_FL|" r"rigforge\.mod-host-input:playback_AUX[0-3]|" r"rigforge\.mod-host-output:capture_AUX[0-3]|" r"sooperlooper:loop[01]_(?:in|out)_[1-4]|" r"sooperlooper:midi_in|" r"Midi-Bridge:UMC404HD 192k MIDI 1 \(capture\)" r")$" ) def load_state(path): with path.open(encoding="utf-8") as state_stream: state = yaml.safe_load(state_stream) errors = validate_desired_state(state) errors.extend(validate_managed_links(state)) if errors: raise ValueError("invalid desired state: " + "; ".join(errors)) return state def validate_managed_links(state): errors = [] if not isinstance(state, dict): return ["document root must be a mapping"] routing = state.get("routing") if not isinstance(routing, dict): return ["routing must be a mapping"] managed_ports = routing.get("managed_ports") if not isinstance(managed_ports, list): errors.append("routing.managed_ports must be a list") managed_ports = [] for index, port in enumerate(managed_ports): if not isinstance(port, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(port): errors.append( f"routing.managed_ports[{index}] is not an approved Rigforge boundary, UMC, or MIDI port" ) if len(managed_ports) != len(set(port for port in managed_ports if isinstance(port, str))): errors.append("routing.managed_ports must not contain duplicate ports") managed_links = routing.get("managed_links") if not isinstance(managed_links, list): errors.append("routing.managed_links must be a list") managed_links = [] for index, link in enumerate(managed_links): if not isinstance(link, dict): errors.append(f"routing.managed_links[{index}] must be a mapping") continue source = link.get("from") destination = link.get("to") if not isinstance(source, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(source): errors.append( f"routing.managed_links[{index}].from is not an approved Rigforge boundary, UMC, or MIDI port" ) if not isinstance(destination, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(destination): errors.append( f"routing.managed_links[{index}].to is not an approved Rigforge boundary, UMC, or MIDI port" ) if ( isinstance(source, str) and isinstance(destination, str) and (source not in managed_ports or destination not in managed_ports) ): errors.append(f"routing.managed_links[{index}] endpoints must be listed in routing.managed_ports") if source == destination: errors.append(f"routing.managed_links[{index}] cannot link a port to itself") if link.get("status") not in {"planned", "observed"}: errors.append(f"routing.managed_links[{index}].status must be planned or observed") managed_unlinks = routing.get("managed_unlinks") if not isinstance(managed_unlinks, list): errors.append("routing.managed_unlinks must be a list") managed_unlinks = [] unlink_edges = set() for index, link in enumerate(managed_unlinks): if not isinstance(link, dict): errors.append(f"routing.managed_unlinks[{index}] must be a mapping") continue source = link.get("from") destination = link.get("to") if not isinstance(source, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(source): errors.append( f"routing.managed_unlinks[{index}].from is not an approved Rigforge boundary, UMC, or MIDI port" ) if not isinstance(destination, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(destination): errors.append( f"routing.managed_unlinks[{index}].to is not an approved Rigforge boundary, UMC, or MIDI port" ) if ( isinstance(source, str) and isinstance(destination, str) and (source not in managed_ports or destination not in managed_ports) ): errors.append( f"routing.managed_unlinks[{index}] endpoints must be listed in routing.managed_ports" ) if source == destination: errors.append(f"routing.managed_unlinks[{index}] cannot unlink a port from itself") if link.get("status") not in {"planned", "observed"}: errors.append(f"routing.managed_unlinks[{index}].status must be planned or observed") if isinstance(source, str) and isinstance(destination, str): edge = (source, destination) if edge in unlink_edges: errors.append(f"duplicate managed unlink: {source} -> {destination}") unlink_edges.add(edge) managed_edges = { (link.get("from"), link.get("to")) for link in managed_links if isinstance(link, dict) and isinstance(link.get("from"), str) and isinstance(link.get("to"), str) } for source, destination in sorted(unlink_edges & managed_edges): errors.append(f"link cannot be both managed and scheduled for removal: {source} -> {destination}") return errors def parse_pw_link_output(text): links = set() current_source = None for line in text.splitlines(): if not line.strip(): continue if line.startswith(" |-> "): if current_source is None: raise ValueError("pw-link output has a destination without a source") destination = line.removeprefix(" |-> ") links.add((current_source, destination)) continue if line.startswith(" |<- "): destination = line.removeprefix(" |<- ") links.add((destination, current_source)) continue current_source = line.strip() return links def observe(state, links): managed_ports = set(state["routing"]["managed_ports"]) managed = { (link["from"], link["to"]) for link in state["routing"]["managed_links"] if link["status"] in {"planned", "observed"} } managed_unlinks = { (link["from"], link["to"]) for link in state["routing"]["managed_unlinks"] if link["status"] in {"planned", "observed"} } observed_managed = { link for link in links if link[0] in managed_ports and link[1] in managed_ports } reports = [] for source, destination in sorted(managed - observed_managed): reports.append({"kind": "missing", "from": source, "to": destination, "action": "would-link"}) for source, destination in sorted(observed_managed - managed): action = "would-unlink" if (source, destination) in managed_unlinks else "would-review" reports.append({"kind": "unexpected", "from": source, "to": destination, "action": action}) return reports def list_ports(runner, direction): result = runner( ["pw-link", direction], check=True, capture_output=True, text=True, ) return {line.strip() for line in result.stdout.splitlines() if line.strip()} def reconcile_once(state, runner=subprocess.run): initial_result = runner( ["pw-link", "-l"], check=True, capture_output=True, text=True, ) initial_links = parse_pw_link_output(initial_result.stdout) initial_reports = observe(state, initial_links) missing_links = [report for report in initial_reports if report["kind"] == "missing"] actions = [] if missing_links: outputs = list_ports(runner, "-o") inputs = list_ports(runner, "-i") for report in missing_links: source = report["from"] destination = report["to"] unavailable = [] if source not in outputs: unavailable.append({"port": source, "direction": "output"}) if destination not in inputs: unavailable.append({"port": destination, "direction": "input"}) if unavailable: action = { "kind": "unavailable-port", "from": source, "to": destination, "missing_ports": unavailable, "result": "not-linked", "reason": ( "required PipeWire port(s) are not present in the current graph" ), } if any( item["port"].startswith("rigforge.mod-host-") for item in unavailable ): action["hint"] = ( "Rigforge mod-host boundary ports must be running; mod-ui provides the " "internal NAM/IR connections" ) elif any(item["port"] == "sooperlooper:midi_in" for item in unavailable): action["hint"] = ( "SooperLooper must be running under pw-jack and expose its JACK MIDI input" ) actions.append(action) continue try: runner( ["pw-link", source, destination], check=True, capture_output=True, text=True, ) actions.append( {"kind": "link", "from": source, "to": destination, "result": "requested"} ) except (OSError, subprocess.CalledProcessError) as error: detail = str(error) if isinstance(error, subprocess.CalledProcessError) and error.stderr: detail = error.stderr.strip() or detail actions.append( { "kind": "link-failed", "from": source, "to": destination, "result": detail, } ) # Remove only explicitly declared stale edges, and only after every # desired managed link is present. This avoids disconnecting an old path # when its replacement could not be established. if missing_links: before_unlink_result = runner( ["pw-link", "-l"], check=True, capture_output=True, text=True, ) before_unlink_links = parse_pw_link_output(before_unlink_result.stdout) else: before_unlink_links = initial_links remaining_missing = [ report for report in observe(state, before_unlink_links) if report["kind"] == "missing" ] managed_ports = set(state["routing"]["managed_ports"]) scheduled_unlinks = [ (link["from"], link["to"]) for link in state["routing"]["managed_unlinks"] if link["from"] in managed_ports and link["to"] in managed_ports and (link["from"], link["to"]) in before_unlink_links ] if remaining_missing: for source, destination in scheduled_unlinks: actions.append( { "kind": "unlink-deferred", "from": source, "to": destination, "result": "desired managed links are still missing", } ) else: for source, destination in scheduled_unlinks: try: runner( ["pw-link", "-d", source, destination], check=True, capture_output=True, text=True, ) actions.append( {"kind": "unlink", "from": source, "to": destination, "result": "requested"} ) except (OSError, subprocess.CalledProcessError) as error: detail = str(error) if isinstance(error, subprocess.CalledProcessError) and error.stderr: detail = error.stderr.strip() or detail actions.append( { "kind": "unlink-failed", "from": source, "to": destination, "result": detail, } ) final_result = runner( ["pw-link", "-l"], check=True, capture_output=True, text=True, ) final_links = parse_pw_link_output(final_result.stdout) return { "mode": "reconcile-once", "managed_links": len(state["routing"]["managed_links"]), "managed_unlinks": len(state["routing"]["managed_unlinks"]), "actions": actions, "differences": observe(state, final_links), } def main(argv=None): parser = argparse.ArgumentParser() parser.add_argument( "--state", type=Path, default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml", ) parser.add_argument( "--reconcile-once", action="store_true", help=( "create missing declared links and remove only explicitly declared " "managed_unlinks once; never alter other links or restart services" ), ) parser.add_argument( "--quiet-if-clean", action="store_true", help="with --reconcile-once, suppress output when no action or difference remains", ) args = parser.parse_args(argv) if args.quiet_if_clean and not args.reconcile_once: parser.error("--quiet-if-clean requires --reconcile-once") try: state = load_state(args.state) if args.reconcile_once: result = reconcile_once(state) if args.quiet_if_clean and not result["actions"] and not result["differences"]: return 0 print(json.dumps(result, indent=2)) return 0 if not result["differences"] else 1 result = subprocess.run( ["pw-link", "-l"], check=True, capture_output=True, text=True, ) links = parse_pw_link_output(result.stdout) except (OSError, subprocess.CalledProcessError, ValueError, yaml.YAMLError) as error: print(f"ERROR: {error}", file=sys.stderr) return 2 reports = observe(state, links) print( json.dumps( { "mode": "observe-only", "managed_links": len(state["routing"]["managed_links"]), "managed_unlinks": len(state["routing"]["managed_unlinks"]), "differences": reports, }, indent=2, ) ) return 0 if __name__ == "__main__": raise SystemExit(main())