ソースを参照

service to reconcile config

Johan Le Baut 2 週間 前
親
コミット
aadae9196d

+ 5 - 4
AGENTS.md

@@ -11,9 +11,10 @@ The current target is Debian GNU/Linux 13 on AArch64 with a Behringer UMC404HD 1
 - `config/desired-state.yaml` is the central YAML description of the intended components, four mono sources, looper channel assignments, mix, the guitar NAM/cabinet chain, planned/forbidden connections, and the exact PipeWire links currently tracked for observation.
 - `config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf` is a PipeWire filter-chain fragment with four mono mixer inputs, one mono output, and initial gain `0.2` per input. It defines the processing graph and ports, but does not create links to hardware or implement the looper graph.
 - `scripts/validate_desired_state.py` checks the YAML's four-source/physical-input model, single four-channel looper, source-to-channel assignments, mix declaration, and prohibition on routing looper returns back to looper inputs.
-- `scripts/observe_pipewire.py` validates the state and managed endpoint declarations, reads `pw-link -l`, and compares observed links against explicitly managed ports and links. Observation is the default; explicit one-shot reconciliation may create only declared missing links.
+- `scripts/observe_pipewire.py` validates the state and managed endpoint declarations, reads `pw-link -l`, and compares observed links against explicitly managed ports and links. Observation is the default; one-shot reconciliation and the opt-in timer create only declared missing links and remove only declared stale links.
 - `scripts/configure_mod_host.py` loads the YAML-declared NAM and LSP IR instances and guitar links for the user service `config/systemd/user/rigforge-mod-host.service.in`.
-- `scripts/deploy.sh` dispatches scoped user-level install/uninstall/reload actions for YAML-declared PipeWire, LV2 bundles, and the mod-host user service through `scripts/deploy.py`. `mod-host` is an explicit target, not part of `all`.
+- `config/systemd/user/rigforge-pipewire-reconcile.service.in` and `.timer.in` define periodic link reconciliation after mod-host is installed.
+- `scripts/deploy.sh` dispatches scoped user-level install/uninstall/reload actions for YAML-declared PipeWire, LV2 bundles, and the mod-host service/timer through `scripts/deploy.py`. `mod-host` is an explicit target, not part of `all`.
 - `tests/` contains Python `unittest` tests for state validation, observation/reconciliation, mixer configuration, mod-host startup configuration, and simulated deployment operations. These validate repository-level invariants, not live audio behavior.
 - `config/sooperlooper/fcb1010.slb` is supplied controller configuration, pending target verification. No SooperLooper build definition or artifact is present.
 
@@ -48,7 +49,7 @@ The observer invokes `pw-link -l` itself. It never creates or removes links. A c
 - A managed link's endpoints must both be declared in `routing.managed_ports`, and names must match the observer's approved endpoint pattern. Use concrete observed PipeWire ports rather than logical aliases. The current effect allowlist is limited to the declared `effect_0` NAM and `effect_1` IR ports.
 - Link status values used by the observer are `planned` and `observed`; both are compared against the current graph. Only declare real target observations as `observed`.
 - Deployment declarations belong in `config/desired-state.yaml`. The deploy helper must remain scoped to declared user paths, preserve and restore prior files, refuse destructive actions after local modifications, and never restart the main PipeWire or WirePlumber service as a generic update.
-- Keep observation as the default. Explicit `--reconcile-once` may create declared missing links and remove only exact links listed in `routing.managed_unlinks`; it must defer removals until all desired managed links are present, must not alter other connections, and must not restart services. Retain tests for simulated repair, safe removal, deferral, and post-check behavior.
+- Keep observation as the default. Explicit `--reconcile-once` and the opt-in mod-host user timer may create declared missing links and remove only exact links listed in `routing.managed_unlinks`; they must defer removals until all desired managed links are present, must not alter other connections, and must not restart PipeWire/WirePlumber. Retain tests for simulated repair, safe removal, deferral, and post-check behavior.
 - Mixer gain `0.2` is an initial conservative value, not a calibrated level or clipping guarantee. Test summed sources and loop returns on hardware before live use.
 
 ## Working conventions and gotchas
@@ -58,7 +59,7 @@ The observer invokes `pw-link -l` itself. It never creates or removes links. A c
 - Scripts resolve their default state file relative to their own location, so the documented commands work from any current directory, though repository-root execution is the clearest convention.
 - PipeWire's `filter-chain.conf.d` fragment is loaded by the separate filter-chain process (`pipewire -c filter-chain.conf` on the current target), not automatically by the main PipeWire daemon. It defines nodes/ports, not connections. Target service installation and restart steps are specific to the README's current test and should not be treated as an established deployment recipe.
 - The current port mapping, sample rate/quantum, and physical output details have differing verification levels recorded in YAML and README. Preserve those distinctions; do not infer a complete deployment procedure from the exploratory test notes.
-- Deployment is manual; no CI/CD or auto-pull is configured. The mod-host user service and deployment path are implemented in the repository but target activation, reboot startup, and recovery after PipeWire restart remain unverified. Keep unverified changes away from live audio use and follow the README's rollback procedure for target experiments.
+- Deployment is manual; no CI/CD or auto-pull is configured. The mod-host user service, dependent-service restart propagation, and 15-second reconciliation timer are implemented in the repository but the latest changes and recovery behavior still require target verification. Keep unverified changes away from live audio use and follow the README's rollback procedure for target experiments.
 - `install mod-host` activates audio routing and is intentionally excluded from `install all`. The current mod-host build listens on `0.0.0.0:5555` without authentication by owner request; do not change that policy silently, and retain the security warning in documentation.
 
 # Environnement local — rigforge

+ 8 - 6
README.md

@@ -115,7 +115,7 @@ After a manual `git pull --ff-only`, run the deploy helper from any directory:
 
 The helper accepts `install|uninstall|reload` and `all|namlv2|lsp|dragonfly-reverb|pipewire|mod-host`. It reads versions, paths, URLs, and quantum from `config/desired-state.yaml`; its deployment registry is stored under `~/.local/state/rigforge/`, and any pre-existing target backup is stored next to that target. It does not use `sudo` or change files outside the declared paths, adjacent backup paths, and registry directory.
 
-For PipeWire, install updates only the Rigforge filter fragment, applies the declared quantum as a runtime setting, and restarts `filter-chain.service` only when the fragment changes. It never restarts `pipewire.service` or WirePlumber. `reload pipewire` reapplies the quantum and restarts the filter-chain user service. This restart removes the filter-chain nodes and their graph links; the fragment recreates ports but not links. The deploy helper deliberately does not reconcile links automatically. After a restart, first run `python3 scripts/observe_pipewire.py`; if declared links are missing, use `python3 scripts/observe_pipewire.py --reconcile-once` only during an appropriate safe test window, then observe again. Uninstall removes only the unchanged managed fragment, restores a file that was present before the first install, returns quantum selection to automatic, and reloads the filter service. Local edits to managed files stop removal or replacement rather than being discarded. Runtime quantum is not persistent across a PipeWire daemon restart.
+For PipeWire, install updates only the Rigforge filter fragment, applies the declared quantum as a runtime setting, and restarts `filter-chain.service` only when the fragment changes. It never restarts `pipewire.service` or WirePlumber. `reload pipewire` reapplies the quantum and restarts the filter-chain user service. This restart removes the filter-chain nodes and their graph links; the fragment recreates ports but not links. Installing the explicit `mod-host` target also installs a 15-second reconciliation timer; without that target, reconciliation remains manual. After a PipeWire/filter restart, first inspect with `python3 scripts/observe_pipewire.py`. Uninstall removes only the unchanged managed fragment, restores a file that was present before the first install, returns quantum selection to automatic, and reloads the filter service. Local edits to managed files stop removal or replacement rather than being discarded. Runtime quantum is not persistent across a PipeWire daemon restart.
 
 For NAM LV2, install downloads the declared Raspberry Pi 5 archive with `curl`, checks the archive structure, extracts the `neural_amp_modeler.lv2` bundle under `~/.lv2/`, and records the archive SHA-256 and managed bundle fingerprint. This is a locally computed identity hash, not an independent publisher checksum. An existing same-name bundle is preserved for uninstall; locally modified managed bundles are not overwritten or removed. `reload namlv2` does nothing because plugin installation itself requires no host reload; restart `mod-host` after installing or removing the plugin. On the target, tag `v0.2.3` was installed at `~/.lv2/neural_amp_modeler.lv2`; the observed contents were `manifest.ttl`, `modgui/`, `modgui.ttl`, `neural_amp_modeler.so`, and `neural_amp_modeler.ttl`. The downloaded archive SHA-256 was `80d1a711d573afb7323cbf2ea1a79e39386e58ba449d076c5d89e10b50de3212`; this is an identity hash only, not an independent publisher checksum. The selected NAM model was loaded during the initial manual mod-host chain test; sustained performance and automated startup remain unverified. The release archive is fetched at install time and is not committed to this repository.
 
@@ -123,19 +123,21 @@ For LSP and Dragonfly Reverb, the YAML declares tags and release URLs, and the i
 
 ### mod-host guitar chain
 
-`install mod-host` is an explicit target and is deliberately not included in `install all`: it activates the guitar processing chain. It requires the ARM64 artifact under `artifacts/mod-host/arm64/current/`, the NAM and LSP bundles already installed, the tracked `amp_emul/` assets, and the runtime packages in the target preparation list. It installs and enables a `systemd --user` unit; it does not use `sudo` or restart PipeWire/WirePlumber. The generated unit refers to the repository checkout from which `deploy.sh` was run, so keep the checkout at that path or uninstall/reinstall after moving it.
+`install mod-host` is an explicit target and is deliberately not included in `install all`: it activates the guitar processing chain. It requires the ARM64 artifact under `artifacts/mod-host/arm64/current/`, the NAM and LSP bundles already installed, the tracked `amp_emul/` assets, and the runtime packages in the target preparation list. It installs and enables a `systemd --user` service and a 15-second reconciliation timer; it does not use `sudo` or directly restart PipeWire/WirePlumber. The generated units refer to the repository checkout from which `deploy.sh` was run, so keep the checkout at that path or uninstall/reinstall after moving it.
 
 At service startup, `scripts/configure_mod_host.py` waits for the control socket, loads the declared NAM and LSP mono-IR instances, sets their model/IR paths and the conservative NAM output level, then creates the PipeWire links. The desired chain is capture AUX0 → `Vox_AC15CH_Crunch_TB.nam` → `VOX_AC30_1964_celestion.wav` → guitar mixer input AUX0. The direct capture-to-mixer bypass is removed. Review the model and IR redistribution terms before using these assets in a public image or package.
 
-`reload mod-host` restarts the service and rebuilds the plugin graph, briefly interrupting the processed guitar path. `uninstall mod-host` disables/stops the unit and restores any prior unit file; it does not create a dry bypass. The mod-host control socket uses TCP port 5555 and this build listens on `0.0.0.0` without authentication. This is retained for the current test by owner request and must be restricted before treating the setup as hardened.
+`reload mod-host` restarts the service and rebuilds the plugin graph, briefly interrupting the processed guitar path. `PartOf=` couples mod-host restarts to PipeWire, WirePlumber, and `filter-chain.service` restarts; its startup configurator then rebuilds the NAM/IR chain. The separate timer invokes `observe_pipewire.py --reconcile-once --quiet-if-clean` every 15 seconds to repair declared links after graph changes such as an interface reconnect. It removes only explicitly declared stale links and defers removal until every desired managed link exists; other unexpected links are never pruned. It verifies graph topology, not audio signal quality. Inspect it with `systemctl --user status rigforge-pipewire-reconcile.timer` and `journalctl --user -u rigforge-pipewire-reconcile.service -b`. `uninstall mod-host` disables the timer and service and restores any prior unit files; it does not create a dry bypass. The mod-host control socket uses TCP port 5555 and this build listens on `0.0.0.0` without authentication. This is retained for the current test by owner request and must be restricted before treating the setup as hardened.
 
-The owner reports enabling lingering with `sudo loginctl enable-linger "$USER"` so the user manager can run without an interactive login. Automatic boot startup and recovery after PipeWire restarts still require on-target verification. Installation refuses to start if port 5555 is already occupied by an unmanaged/manual mod-host process; stop that process explicitly before retrying.
+The owner reports enabling lingering with `sudo loginctl enable-linger "$USER"` so the user manager can run without an interactive login. Boot startup, dependency restart propagation, and USB unplug/replug recovery from the new timer require on-target verification. Installation refuses to start if port 5555 is already occupied by an unmanaged/manual mod-host process; stop that process explicitly before retrying.
 
-Inspect the service after installation with:
+Inspect the service and timer after installation with:
 
 ```sh
 systemctl --user status rigforge-mod-host.service
 journalctl --user -u rigforge-mod-host.service -b
+systemctl --user status rigforge-pipewire-reconcile.timer
+journalctl --user -u rigforge-pipewire-reconcile.service -b
 ```
 
 On the target, `install pipewire` applied quantum 128 and reported that the installed fragment was already current; the following observer reported no differences. A later `reload pipewire` applied the quantum and restarted the filter-chain service, after which observation found all three managed links missing. One-shot reconciliation requested each link, and the subsequent observer reported `differences: []`. This confirms the graph links were present after reconciliation, not that audio was audible. `install all` and `uninstall all` attempt all four targets and report an overall failure if any action fails. `reload all` restarts the filter-chain service and prints no-op messages for the LV2 plugins. Check the target afterwards with `python3 scripts/validate_desired_state.py`, `python3 -m unittest discover -s tests -v`, and `python3 scripts/observe_pipewire.py`.
@@ -165,7 +167,7 @@ The next target checks are:
 1. The read-only observer and one-shot repair have been tested on `rigforge`. Repairing one missing link restored the audible microphone path; after a later filter-chain service restart, reconciliation requested all three missing links and the observer reported no differences. The observer now also tracks the three guitar NAM/cabinet links. Do not run one-shot reconciliation against an older checkout: it could restore the dry guitar bypass.
 2. Later, test inputs 2 and 4 with sources when available; they are included in the mixer but not verified with instruments.
 3. Measure sustained stability and headroom at 48 kHz / 128 frames with all active sources; the current `ERR = 0` observation was brief.
-4. Verify the new `rigforge-mod-host.service` on the target, including reboot with lingering enabled, PipeWire restart behavior, resource limits, and recovery when an LV2 plugin fails to load.
+4. Verify the `rigforge-mod-host.service` and reconciliation timer on the target, including reboot with lingering enabled, PipeWire/service restart propagation, USB unplug/replug recovery, resource limits, and recovery when an LV2 plugin fails to load.
 5. Verify FCB1010 MIDI messages and the supplied bindings with the eventual SooperLooper build. Verify OSC port readiness and the effect and persistence of `discrete_prefader 0` separately.
 
 Do not treat planned packages, commands, ports, or service settings as target-validated until these checks have been performed.

+ 8 - 0
config/desired-state.yaml

@@ -67,6 +67,14 @@ deployment:
     socket_port: 5555
     pw_jack_path: /usr/bin/pw-jack
     python_path: /usr/bin/python3
+    observer_script: scripts/observe_pipewire.py
+    reconcile_service_source: config/systemd/user/rigforge-pipewire-reconcile.service.in
+    reconcile_service_destination: .config/systemd/user/rigforge-pipewire-reconcile.service
+    reconcile_service: rigforge-pipewire-reconcile.service
+    reconcile_timer_source: config/systemd/user/rigforge-pipewire-reconcile.timer.in
+    reconcile_timer_destination: .config/systemd/user/rigforge-pipewire-reconcile.timer
+    reconcile_timer: rigforge-pipewire-reconcile.timer
+    reconcile_interval_seconds: 15
   pipewire:
     fragment_source: config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf
     fragment_destination: .config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf

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

@@ -2,6 +2,7 @@
 Description=Rigforge guitar NAM and cabinet chain
 Wants=pipewire.service wireplumber.service filter-chain.service
 After=pipewire.service wireplumber.service filter-chain.service
+PartOf=pipewire.service wireplumber.service filter-chain.service
 
 [Service]
 Type=simple

+ 9 - 0
config/systemd/user/rigforge-pipewire-reconcile.service.in

@@ -0,0 +1,9 @@
+[Unit]
+Description=Reconcile declared Rigforge PipeWire links
+After=pipewire.service wireplumber.service filter-chain.service rigforge-mod-host.service
+
+[Service]
+Type=oneshot
+ExecStart=@PYTHON@ @OBSERVER_SCRIPT@ --state @DESIRED_STATE@ --reconcile-once --quiet-if-clean
+SuccessExitStatus=1
+TimeoutStartSec=30

+ 11 - 0
config/systemd/user/rigforge-pipewire-reconcile.timer.in

@@ -0,0 +1,11 @@
+[Unit]
+Description=Periodically reconcile Rigforge PipeWire links
+
+[Timer]
+OnBootSec=@RECONCILE_INTERVAL_SECONDS@s
+OnUnitActiveSec=@RECONCILE_INTERVAL_SECONDS@s
+AccuracySec=1s
+Unit=rigforge-pipewire-reconcile.service
+
+[Install]
+WantedBy=timers.target

+ 260 - 0
scripts/deploy.py

@@ -823,6 +823,263 @@ def render_mod_host_service(config):
     return content.encode("utf-8")
 
 
+def render_mod_host_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["reconcile_service_source"]
+    timer_template = repository_root / config["reconcile_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"mod-host {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["reconcile_interval_seconds"]),
+    )
+    if re.search(r"@[A-Z_]+@", timer_content):
+        raise RuntimeError("unexpanded placeholder remains in reconciliation timer template")
+
+    return {
+        "service": {
+            "name": config["reconcile_service"],
+            "destination": Path.home() / config["reconcile_service_destination"],
+            "content": service_content.encode("utf-8"),
+        },
+        "timer": {
+            "name": config["reconcile_timer"],
+            "destination": Path.home() / config["reconcile_timer_destination"],
+            "content": timer_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 file_sha256(path):
+    return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None
+
+
+def install_mod_host_reconcile_units(config, registry):
+    units = render_mod_host_reconcile_units(config)
+    managed = registry.get("mod_host_reconcile")
+    if managed is not None and managed.get("pending_uninstall"):
+        raise RuntimeError("reconciliation units are pending uninstall; retry uninstall mod-host first")
+    if managed is None and (
+        mod_host_unit_is_active(config["reconcile_service"])
+        or mod_host_unit_is_active(config["reconcile_timer"])
+        or mod_host_unit_is_enabled(config["reconcile_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["mod_host_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["mod_host_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 PipeWire reconciliation timer ({timer_name}).")
+
+
+def uninstall_mod_host_reconcile_units(config, registry):
+    managed = registry.get("mod_host_reconcile")
+    if managed is None:
+        return
+    units = render_mod_host_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["mod_host_reconcile"] = managed
+    write_registry(registry)
+
+    run(["systemctl", "--user", "disable", "--now", config["reconcile_timer"]])
+    run(["systemctl", "--user", "stop", config["reconcile_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("mod_host_reconcile")
+    write_registry(registry)
+    print("Rigforge PipeWire reconciliation timer and units removed.")
+
+
 def mod_host_runtime_digest(config):
     state_path = ROOT / "config" / "desired-state.yaml"
     script_path = ROOT / config["configure_script"]
@@ -918,6 +1175,8 @@ def deploy_mod_host(action, config, registry):
             registry["mod_host"] = managed
             write_registry(registry)
 
+        uninstall_mod_host_reconcile_units(config, registry)
+
         destination_digest = (
             hashlib.sha256(destination.read_bytes()).hexdigest()
             if destination.is_file()
@@ -1054,6 +1313,7 @@ def deploy_mod_host(action, config, registry):
     managed.pop("pending_activation", None)
     registry["mod_host"] = managed
     write_registry(registry)
+    install_mod_host_reconcile_units(config, registry)
     print(f"Installed and activated Rigforge mod-host user service at {destination}.")
 
 

+ 20 - 1
scripts/observe_pipewire.py

@@ -338,11 +338,20 @@ def main(argv=None):
             "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
 
@@ -358,7 +367,17 @@ def main(argv=None):
         return 2
 
     reports = observe(state, links)
-    print(json.dumps({"mode": "observe-only", "managed_links": len(state["routing"]["managed_links"]), "differences": reports}, indent=2))
+    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
 
 

+ 28 - 0
scripts/validate_desired_state.py

@@ -375,6 +375,25 @@ def validate_state(state):
                 ("configure_script", "scripts/configure_mod_host.py"),
                 ("pw_jack_path", "/usr/bin/pw-jack"),
                 ("python_path", "/usr/bin/python3"),
+                ("observer_script", "scripts/observe_pipewire.py"),
+                (
+                    "reconcile_service_source",
+                    "config/systemd/user/rigforge-pipewire-reconcile.service.in",
+                ),
+                (
+                    "reconcile_service_destination",
+                    ".config/systemd/user/rigforge-pipewire-reconcile.service",
+                ),
+                ("reconcile_service", "rigforge-pipewire-reconcile.service"),
+                (
+                    "reconcile_timer_source",
+                    "config/systemd/user/rigforge-pipewire-reconcile.timer.in",
+                ),
+                (
+                    "reconcile_timer_destination",
+                    ".config/systemd/user/rigforge-pipewire-reconcile.timer",
+                ),
+                ("reconcile_timer", "rigforge-pipewire-reconcile.timer"),
             ):
                 if mod_host.get(key) != expected:
                     errors.append(f"deployment.mod_host.{key} must be {expected}")
@@ -385,6 +404,15 @@ def validate_state(state):
                 or not 1 <= socket_port <= 65535
             ):
                 errors.append("deployment.mod_host.socket_port must be a valid TCP port")
+            interval = mod_host.get("reconcile_interval_seconds")
+            if (
+                not isinstance(interval, int)
+                or isinstance(interval, bool)
+                or not 5 <= interval <= 300
+            ):
+                errors.append(
+                    "deployment.mod_host.reconcile_interval_seconds must be between 5 and 300"
+                )
 
         pipewire = deployment.get("pipewire")
         if not isinstance(pipewire, dict):

+ 62 - 1
tests/test_deploy.py

@@ -214,8 +214,14 @@ class DeploymentTests(unittest.TestCase):
         content = destination.read_text(encoding="utf-8")
         self.assertIn("WantedBy=default.target", content)
         self.assertIn("After=pipewire.service wireplumber.service filter-chain.service", content)
+        self.assertIn("PartOf=pipewire.service wireplumber.service filter-chain.service", content)
         self.assertIn("-n -p 5555", content)
         self.assertIn("configure_mod_host.py", content)
+        reconcile_service = self.home / config["reconcile_service_destination"]
+        reconcile_timer = self.home / config["reconcile_timer_destination"]
+        self.assertIn("--reconcile-once --quiet-if-clean", reconcile_service.read_text(encoding="utf-8"))
+        self.assertIn("SuccessExitStatus=1", reconcile_service.read_text(encoding="utf-8"))
+        self.assertIn("OnUnitActiveSec=15s", reconcile_timer.read_text(encoding="utf-8"))
         self.assertEqual(
             self.commands,
             [
@@ -223,11 +229,16 @@ class DeploymentTests(unittest.TestCase):
                 ["systemctl", "--user", "enable", "rigforge-mod-host.service"],
                 ["systemctl", "--user", "restart", "rigforge-mod-host.service"],
                 ["systemctl", "--user", "is-active", "--quiet", "rigforge-mod-host.service"],
+                ["systemctl", "--user", "daemon-reload"],
+                ["systemctl", "--user", "enable", "rigforge-pipewire-reconcile.timer"],
+                ["systemctl", "--user", "restart", "rigforge-pipewire-reconcile.timer"],
+                ["systemctl", "--user", "is-active", "--quiet", "rigforge-pipewire-reconcile.timer"],
             ],
         )
         registry = deploy.read_registry()
         self.assertTrue(registry["mod_host"]["installed_sha256"])
         self.assertNotIn("pending_activation", registry["mod_host"])
+        self.assertEqual(set(registry["mod_host_reconcile"]["files"]), {"service", "timer"})
 
     def test_mod_host_install_is_idempotent_without_restarting_active_audio(self):
         config = self.mod_host_config()
@@ -242,6 +253,10 @@ class DeploymentTests(unittest.TestCase):
                 ["systemctl", "--user", "enable", "rigforge-mod-host.service"],
                 ["systemctl", "--user", "start", "rigforge-mod-host.service"],
                 ["systemctl", "--user", "is-active", "--quiet", "rigforge-mod-host.service"],
+                ["systemctl", "--user", "daemon-reload"],
+                ["systemctl", "--user", "enable", "rigforge-pipewire-reconcile.timer"],
+                ["systemctl", "--user", "start", "rigforge-pipewire-reconcile.timer"],
+                ["systemctl", "--user", "is-active", "--quiet", "rigforge-pipewire-reconcile.timer"],
             ],
         )
 
@@ -273,10 +288,48 @@ class DeploymentTests(unittest.TestCase):
         self.assertEqual(
             self.commands,
             [
+                ["systemctl", "--user", "disable", "--now", "rigforge-pipewire-reconcile.timer"],
+                ["systemctl", "--user", "stop", "rigforge-pipewire-reconcile.service"],
+                ["systemctl", "--user", "daemon-reload"],
                 ["systemctl", "--user", "disable", "--now", "rigforge-mod-host.service"],
                 ["systemctl", "--user", "daemon-reload"],
             ],
         )
+        self.assertFalse((self.home / config["reconcile_service_destination"]).exists())
+        self.assertFalse((self.home / config["reconcile_timer_destination"]).exists())
+
+    def test_mod_host_uninstall_restores_prior_reconcile_units(self):
+        config = self.mod_host_config()
+        prior_contents = {
+            config["reconcile_service_destination"]: "prior reconcile service",
+            config["reconcile_timer_destination"]: "prior reconcile timer",
+        }
+        for relative_path, content in prior_contents.items():
+            destination = self.home / relative_path
+            destination.parent.mkdir(parents=True, exist_ok=True)
+            destination.write_text(content, encoding="utf-8")
+
+        with patch.object(deploy, "mod_host_port_is_open", return_value=False):
+            deploy.deploy_mod_host("install", config, deploy.read_registry())
+        deploy.deploy_mod_host("uninstall", config, deploy.read_registry())
+
+        for relative_path, content in prior_contents.items():
+            self.assertEqual((self.home / relative_path).read_text(encoding="utf-8"), content)
+        self.assertNotIn("mod_host_reconcile", deploy.read_registry())
+
+    def test_mod_host_uninstall_refuses_local_reconcile_unit_edits(self):
+        config = self.mod_host_config()
+        with patch.object(deploy, "mod_host_port_is_open", return_value=False):
+            deploy.deploy_mod_host("install", config, deploy.read_registry())
+        timer = self.home / config["reconcile_timer_destination"]
+        timer.write_text("local edit", encoding="utf-8")
+        self.commands.clear()
+
+        with self.assertRaisesRegex(RuntimeError, "changed locally"):
+            deploy.deploy_mod_host("uninstall", config, deploy.read_registry())
+
+        self.assertEqual(timer.read_text(encoding="utf-8"), "local edit")
+        self.assertEqual(self.commands, [])
 
     def test_mod_host_pending_uninstall_recovers_after_prior_unit_is_restored(self):
         config = self.mod_host_config()
@@ -297,7 +350,15 @@ class DeploymentTests(unittest.TestCase):
 
         self.assertEqual(destination.read_text(encoding="utf-8"), "prior unit")
         self.assertNotIn("mod_host", deploy.read_registry())
-        self.assertEqual(self.commands, [["systemctl", "--user", "daemon-reload"]])
+        self.assertEqual(
+            self.commands,
+            [
+                ["systemctl", "--user", "disable", "--now", "rigforge-pipewire-reconcile.timer"],
+                ["systemctl", "--user", "stop", "rigforge-pipewire-reconcile.service"],
+                ["systemctl", "--user", "daemon-reload"],
+                ["systemctl", "--user", "daemon-reload"],
+            ],
+        )
 
     def test_mod_host_uninstall_refuses_local_unit_edits(self):
         config = self.mod_host_config()

+ 22 - 0
tests/test_pipewire_observer.py

@@ -1,8 +1,11 @@
+import io
 import copy
 import sys
 import unittest
+from contextlib import redirect_stdout
 from pathlib import Path
 from types import SimpleNamespace
+from unittest.mock import patch
 
 ROOT = Path(__file__).resolve().parents[1]
 sys.path.insert(0, str(ROOT / "scripts"))
@@ -12,6 +15,7 @@ from observe_pipewire import (
     observe,
     parse_pw_link_output,
     reconcile_once,
+    main,
     validate_managed_links,
 )
 
@@ -75,6 +79,24 @@ class PipeWireObserverTests(unittest.TestCase):
         )
         self.assertEqual(links, {(CAPTURE_0, PLAYBACK_0)})
 
+    def test_quiet_reconcile_suppresses_output_only_when_clean(self):
+        with (
+            patch("observe_pipewire.load_state", return_value=self.state),
+            patch(
+                "observe_pipewire.reconcile_once",
+                return_value={
+                    "actions": [],
+                    "differences": [],
+                },
+            ),
+        ):
+            output = io.StringIO()
+            with redirect_stdout(output):
+                result = main(["--reconcile-once", "--quiet-if-clean"])
+
+        self.assertEqual(result, 0)
+        self.assertEqual(output.getvalue(), "")
+
     def test_rejects_logical_mix_endpoint(self):
         state = copy.deepcopy(self.state)
         state["routing"]["managed_ports"] = [PLAYBACK_0]