Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(install): preserve OpenCode edits during reactivation (#4022)
Mansurshakh Japarov40955b0eef2e
diff --git a/docs/content/docs/persistent-installs.mdx b/docs/content/docs/persistent-installs.mdxindex fd1c33195..eedb49c8e 100644--- a/docs/content/docs/persistent-installs.mdx+++ b/docs/content/docs/persistent-installs.mdx@@ -122,6 +122,37 @@ Provider scope is intentionally conservative. The current direct adapters are:- OpenClaw → existing `wrap openclaw` / `unwrap openclaw` flow- OpenCode → managed block in `~/.config/opencode/opencode.json`+For OpenCode provider scope, reapplying the deployment, restarting it, or+recovering a stopped proxy removes and reinjects only the managed `headroom`+provider. Later edits to themes, other providers, and MCP configuration stay+intact. JSONC input may contain comments and trailing commas.+Active configuration is serialized as JSON; original formatting and comments+are preserved in the snapshot. The original `<config filename>.headroom-backup`+is kept across these transitions for both `.json` and `.jsonc` configurations.+Final `headroom install remove` restores that original snapshot and deletes the+backup, including after a stop and manifest reload.++Existing JSONC snapshots using the older `<name>.json.headroom-backup` filename+are migrated only when the canonical backup is absent. When a sibling `.json`+config or a canonical snapshot already exists, Headroom preserves the ambiguous+legacy backup in place and creates a `<name>.json.headroom-backup.jsonc-migration-blocked`+marker. This marker survives removal and prevents later installs from claiming+the legacy backup, even after the conflicting config or snapshot disappears.+The legacy bytes remain available for manual recovery; copy them to the intended+config only after inspecting them. Keep the marker to prevent automatic migration.+If the marker cannot be created, the operation fails before changing the config+or consuming its canonical snapshot.++Backup ownership follows the config path recorded in the deployment, not a+later `OPENCODE_CONFIG` value. A successful replacement restores snapshots for+retired config paths and transfers any pending restoration to the new manifest.+If restoration fails, the replacement remains active; resolve the filesystem+error and retry `headroom install apply` to complete it.++Failed replacement cleanup consumes snapshots newly created by that attempt,+but preserves snapshots owned by the previous deployment for recovery.++For Copilot, Aider, Cursor, and broader env-driven setups, prefer `--scope user` or `--scope system`.## Provider selectiondiff --git a/headroom/cli/install.py b/headroom/cli/install.pyindex 7ef8b6b32..b25c53653 100644--- a/headroom/cli/install.py+++ b/headroom/cli/install.py@@ -9,6 +9,7 @@ import sysfrom collections.abc import Mappingfrom copy import deepcopyfrom dataclasses import dataclass+from pathlib import Pathimport clickfrom click.core import ParameterSource@@ -16,6 +17,7 @@ from click.core import ParameterSourcefrom headroom._subprocess import runfrom headroom.install.health import probe_json, probe_readyfrom headroom.install.models import (+ ArtifactRecord,ConfigScope,DeploymentManifest,InstallPreset,@@ -23,7 +25,7 @@ from headroom.install.models import (RuntimeKind,SupervisorKind,)-from headroom.install.paths import recovery_manifest_path+from headroom.install.paths import opencode_config_path, recovery_manifest_pathfrom headroom.install.planner import build_manifest, build_tool_envsfrom headroom.install.providers import apply_mutations, revert_mutationsfrom headroom.install.runtime import (@@ -53,6 +55,7 @@ from headroom.install.supervisors import (start_supervisor,stop_supervisor,)+from headroom.providers.opencode.install import restore_opencode_backupfrom .main import main@@ -234,11 +237,15 @@ def _stop_deployment(manifest: DeploymentManifest) -> None:def _deactivate_deployment_mutations(- manifest: DeploymentManifest, *, persist_manifest: bool = True+ manifest: DeploymentManifest,+ *,+ persist_manifest: bool = True,+ restore_backup: bool = False,) -> None:if not manifest.mutations:return- revert_mutations(manifest)+ revert_mutations(manifest, restore_backup=restore_backup)+manifest.mutations = []if persist_manifest:save_manifest(manifest)@@ -312,16 +319,52 @@ def pending_tool_envs(manifest: DeploymentManifest) -> dict[str, dict[str, str]]return pending+def _track_opencode_backup(manifest: DeploymentManifest, *, activating: bool = False) -> None:+ if getattr(manifest, "scope", None) != ConfigScope.PROVIDER.value or "opencode" not in getattr(+ manifest, "targets", []+ ):+ return+ artifacts = getattr(manifest, "artifacts", None)+ if artifacts is None:+ return+ paths = {+ mutation.path+ for mutation in getattr(manifest, "mutations", [])+ if mutation.target == "opencode" and mutation.path+ }+ if activating:+ paths.add(str(opencode_config_path()))+ changed = False+ for path in sorted(paths):+ if any(item.kind == "opencode-config-backup" and item.path == path for item in artifacts):+ continue+ config_path = Path(path)+ backup_path = config_path.with_name(config_path.name + ".headroom-backup")+ artifacts.append(+ ArtifactRecord(+ kind="opencode-config-backup",+ path=path,+ metadata={"backup_path": str(backup_path)},+ )+ )+ changed = True+ if changed:+ # Persist ownership before provider mutation or snapshot creation.+ _save_apply_manifest(manifest)++def _activate_deployment_mutations(manifest: DeploymentManifest) -> None:for target, names in sorted(_reconcile_tool_envs(manifest).items()):click.echo(f"Applying newer managed settings for {target}: {', '.join(names)}")try:+ _track_opencode_backup(manifest, activating=True)manifest.mutations = apply_mutations(manifest)_save_apply_manifest(manifest)except Exception as exc:if manifest.mutations:try:- revert_mutations(manifest)+ revert_mutations(manifest, restore_backup=False)+except Exception as rollback_exc:raise RuntimeError(f"mutation activation failed: {exc}; rollback failed: {rollback_exc}"@@ -358,10 +401,42 @@ def _delete_recovery_snapshot(profile: str) -> None:) from None-def _remove_deployment(manifest: DeploymentManifest) -> None:+def _restore_owned_opencode_backup(+ manifest: DeploymentManifest, *, preserve_paths: set[str] | None = None+) -> None:+ artifacts = getattr(manifest, "artifacts", None)+ if artifacts is None:+ return+ for artifact in artifacts:+ if artifact.kind != "opencode-config-backup" or (+ preserve_paths is not None and artifact.path in preserve_paths+ ):+ continue+ backup_path = artifact.metadata.get("backup_path")+ if isinstance(backup_path, str):+ restore_opencode_backup(artifact.path, backup_path)+ manifest.artifacts = [+ artifact+ for artifact in artifacts+ if artifact.kind != "opencode-config-backup"+ or (preserve_paths is not None and artifact.path in preserve_paths)+ ]+++def _remove_deployment(+ manifest: DeploymentManifest,+ *,+ restore_backup: bool = False,+ preserve_opencode_paths: set[str] | None = None,+) -> None:errors: list[tuple[str, Exception]] = []try:- _deactivate_deployment_mutations(manifest, persist_manifest=False)+ if restore_backup:+ _track_opencode_backup(manifest)+ if manifest.mutations:+ _deactivate_deployment_mutations(manifest, persist_manifest=False, restore_backup=False)+ if restore_backup:+ _restore_owned_opencode_backup(manifest, preserve_paths=preserve_opencode_paths)except Exception as exc:errors.append(("mutation cleanup", exc))try:@@ -382,7 +457,9 @@ def _remove_deployment(manifest: DeploymentManifest) -> None:def _restore_deployment(manifest: DeploymentManifest) -> None:restored = deepcopy(manifest)- restored.artifacts = install_supervisor(restored, start=False)+ restored.artifacts = [+ artifact for artifact in restored.artifacts if artifact.kind == "opencode-config-backup"+ ] + install_supervisor(restored, start=False)_save_apply_manifest(restored)_start_deployment(restored)_activate_deployment_mutations(restored)@@ -583,6 +660,7 @@ def _apply_manifest(manifest: DeploymentManifest) -> None:recovery_saved = Falseactive_persistence_failed = Falseexisting = None+ existing_opencode_paths: set[str] = set()try:try:existing = load_manifest(profile)@@ -590,9 +668,21 @@ def _apply_manifest(manifest: DeploymentManifest) -> None:click.echo(f"Warning: {e}; overwriting.")if existing is not None:click.echo(f"Updating existing deployment profile '{profile}'...")+ _track_opencode_backup(existing)+ existing_opencode_paths = {+ artifact.path+ for artifact in getattr(existing, "artifacts", [])+ if artifact.kind == "opencode-config-backup"+ }+ manifest.artifacts.extend(+ artifact+ for artifact in getattr(existing, "artifacts", [])+ if artifact.kind == "opencode-config-backup" and artifact not in manifest.artifacts+ )_save_recovery_snapshot(existing, profile)recovery_saved = True_remove_deployment(existing)+except Exception as exc:recovery_detail = (f" Recovery snapshot: {recovery_manifest_path(profile)} is retained; "@@ -610,7 +700,9 @@ def _apply_manifest(manifest: DeploymentManifest) -> None:except Exception:active_persistence_failed = Trueraise- manifest.artifacts = install_supervisor(manifest, start=False)+ manifest.artifacts = [+ artifact for artifact in manifest.artifacts if artifact.kind == "opencode-config-backup"+ ] + install_supervisor(manifest, start=False)try:_save_apply_manifest(manifest)except Exception:@@ -625,7 +717,11 @@ def _apply_manifest(manifest: DeploymentManifest) -> None:except Exception as exc:cleanup_errors: list[Exception] = []try:- _remove_deployment(manifest)+ _remove_deployment(+ manifest,+ restore_backup=True,+ preserve_opencode_paths=existing_opencode_paths,+ )except Exception as cleanup_exc:cleanup_errors.append(cleanup_exc)if not cleanup_errors and not active_persistence_failed and existing is not None:@@ -670,6 +766,24 @@ def _apply_manifest(manifest: DeploymentManifest) -> None:f"{cleanup_detail}{persistence_detail}{_recovery_detail()}") from excraise click.ClickException(f"Failed to install deployment '{profile}': {exc}") from exc+ active_opencode_paths = {+ mutation.path+ for mutation in manifest.mutations+ if mutation.target == "opencode" and mutation.path+ }+ if any(+ artifact.kind == "opencode-config-backup" and artifact.path not in active_opencode_paths+ for artifact in manifest.artifacts+ ):+ try:+ _restore_owned_opencode_backup(manifest, preserve_paths=active_opencode_paths)+ _save_apply_manifest(manifest)+ except Exception as exc:+ raise click.ClickException(+ f"Deployment '{profile}' is active, but OpenCode snapshot restoration failed: "+ f"{exc}. Backup ownership is retained in the deployment manifest; "+ "resolve the filesystem failure and retry install apply."+ ) from excif recovery_saved:_delete_recovery_snapshot(profile)@@ -1120,7 +1234,7 @@ def install_remove(profile: str) -> None:manifest = _require_manifest(profile)try:- _remove_deployment(manifest)+ _remove_deployment(manifest, restore_backup=True)except Exception as exc:raise click.ClickException(f"Failed to remove deployment '{profile}': cleanup failed: {exc}. "diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.pyindex b5e22d9be..f38008b5b 100644--- a/headroom/cli/wrap.py+++ b/headroom/cli/wrap.py@@ -195,6 +195,7 @@ from headroom.providers.opencode.config import (_PROVIDER_MARKER_END, # noqa: F401_PROVIDER_MARKER_START,inject_opencode_provider_config,+ migrate_legacy_opencode_jsonc_backup,opencode_config_paths,snapshot_opencode_config_if_unwrapped,strip_opencode_headroom_blocks,@@ -8592,6 +8593,7 @@ def unwrap_opencode(port: int, no_stop_proxy: bool) -> None:click.echo()config_file, backup_file = opencode_config_paths()+ migrate_legacy_opencode_jsonc_backup(config_file, backup_file)if backup_file.exists():try:diff --git a/headroom/install/providers.py b/headroom/install/providers.pyindex 9e25005f1..12f8818d2 100644--- a/headroom/install/providers.py+++ b/headroom/install/providers.py@@ -192,7 +192,8 @@ def apply_mutations(manifest: DeploymentManifest) -> list[ManagedMutation]:except Exception as exc:if mutations:try:- revert_mutations(manifest)+ revert_mutations(manifest, restore_backup=False)+except Exception as rollback_exc:raise RuntimeError(f"mutation application failed: {exc}; rollback failed: {rollback_exc}"@@ -202,7 +203,11 @@ def apply_mutations(manifest: DeploymentManifest) -> list[ManagedMutation]:raise-def revert_mutations(manifest: DeploymentManifest) -> None:+def revert_mutations(+ manifest: DeploymentManifest,+ *,+ restore_backup: bool = True,+) -> None:"""Undo the stored mutations for a deployment."""if manifest.scope in {ConfigScope.USER.value, ConfigScope.SYSTEM.value}:@@ -213,4 +218,4 @@ def revert_mutations(manifest: DeploymentManifest) -> None:_remove_unix_env_scope(shell_mutations)for mutation in manifest.mutations:- revert_provider_scope_mutation(manifest, mutation)+ revert_provider_scope_mutation(manifest, mutation, restore_backup=restore_backup)diff --git a/headroom/providers/install_registry.py b/headroom/providers/install_registry.pyindex 6299279b8..492e3415e 100644--- a/headroom/providers/install_registry.py+++ b/headroom/providers/install_registry.py@@ -50,7 +50,7 @@ from headroom.providers.opencode.install import (_InstallEnvBuilder = Callable[..., dict[str, str]]_ProviderScopeApplier = Callable[[DeploymentManifest], ManagedMutation | None]-_ProviderScopeReverter = Callable[[ManagedMutation, DeploymentManifest], None]+_ProviderScopeReverter = Callable[..., None]_ENV_BUILDERS: dict[str, _InstallEnvBuilder] = {"antigravity": _build_antigravity_install_env,@@ -104,7 +104,8 @@ def apply_provider_scope_mutations(manifest: DeploymentManifest) -> list[Managedrollback_errors: list[Exception] = []for mutation in reversed(mutations):try:- revert_provider_scope_mutation(manifest, mutation)+ revert_provider_scope_mutation(manifest, mutation, restore_backup=False)+except Exception as rollback_exc:rollback_errors.append(rollback_exc)else:@@ -119,9 +120,17 @@ def apply_provider_scope_mutations(manifest: DeploymentManifest) -> list[Managedreturn mutations-def revert_provider_scope_mutation(manifest: DeploymentManifest, mutation: ManagedMutation) -> None:+def revert_provider_scope_mutation(+ manifest: DeploymentManifest,+ mutation: ManagedMutation,+ *,+ restore_backup: bool = True,+) -> None:"""Revert a provider-scope mutation via the owning provider slice."""handlers = _PROVIDER_SCOPE_HANDLERS.get(mutation.target)if handlers is None:return- handlers[1](mutation, manifest)+ if mutation.target == "opencode":+ handlers[1](mutation, manifest, restore_backup=restore_backup)+ else:+ handlers[1](mutation, manifest)diff --git a/headroom/providers/opencode/config.py b/headroom/providers/opencode/config.pyindex 4a0194d01..694d83f41 100644--- a/headroom/providers/opencode/config.py+++ b/headroom/providers/opencode/config.py@@ -73,10 +73,31 @@ def _opencode_home_dir() -> Path:def opencode_config_paths() -> tuple[Path, Path]:- """Return ``(config_file, backup_file)`` for OpenCode."""+ """Return the selected config and its canonical Headroom backup path."""config_file = opencode_config_path()- backup_file = config_file.with_name(config_file.name + ".headroom-backup")- return config_file, backup_file+ return config_file, config_file.with_name(config_file.name + ".headroom-backup")+++def migrate_legacy_opencode_jsonc_backup(config_file: Path, backup_file: Path) -> None:+ """Migrate only legacy JSONC snapshots whose ownership is unambiguous.++ Remember ambiguity on disk before a canonical snapshot can be consumed.+ Otherwise a later install/remove cycle could claim an unrelated legacy+ backup after the canonical backup or sibling JSON config disappears.+ """+ if config_file.suffix.lower() != ".jsonc":+ return+ legacy_backup = config_file.with_suffix(".json.headroom-backup")+ migration_block = legacy_backup.with_name(legacy_backup.name + ".jsonc-migration-blocked")+ if os.path.lexists(migration_block) or not legacy_backup.exists():+ return+ if os.path.lexists(backup_file) or os.path.lexists(config_file.with_suffix(".json")):+ # Keep the legacy bytes in place for their owner or manual recovery.+ # Fail closed if this marker cannot be persisted, before any restore.+ migration_block.touch(exist_ok=True)+ return+ backup_file.parent.mkdir(parents=True, exist_ok=True)+ legacy_backup.replace(backup_file)def snapshot_opencode_config_if_unwrapped(config_file: Path, backup_file: Path) -> None:@@ -85,6 +106,7 @@ def snapshot_opencode_config_if_unwrapped(config_file: Path, backup_file: Path)Guarantees that ``headroom unwrap opencode`` can restore the user'soriginal file byte-for-byte."""+ migrate_legacy_opencode_jsonc_backup(config_file, backup_file)if backup_file.exists():returnif not config_file.exists():@@ -123,23 +145,88 @@ def _render_provider_block(port: int) -> str:return "\n".join(lines)+def _strip_jsonc_comments(text: str) -> str:+ """Remove JSONC line and block comments while preserving quoted strings."""+ output: list[str] = []+ in_string = False+ escaped = False+ index = 0+ while index < len(text):+ char = text[index]+ if in_string:+ output.append(char)+ if escaped:+ escaped = False+ elif char == "\\":+ escaped = True+ elif char == '"':+ in_string = False+ elif char == '"':+ in_string = True+ output.append(char)+ elif text.startswith("//", index):+ newline = text.find("\n", index + 2)+ if newline < 0:+ break+ output.append("\n")+ index = newline+ elif text.startswith("/*", index):+ end = text.find("*/", index + 2)+ if end < 0:+ break+ output.extend("\n" for char in text[index : end + 2] if char == "\n")+ index = end + 1+ else:+ output.append(char)+ index += 1+ return "".join(output)+++def _strip_jsonc_trailing_commas(text: str) -> str:+ """Remove commas before JSONC closing delimiters without touching strings."""+ output: list[str] = []+ in_string = False+ escaped = False+ index = 0+ while index < len(text):+ char = text[index]+ if in_string:+ output.append(char)+ if escaped:+ escaped = False+ elif char == "\\":+ escaped = True+ elif char == '"':+ in_string = False+ elif char == '"':+ in_string = True+ output.append(char)+ elif char == ",":+ next_index = index + 1+ while next_index < len(text) and text[next_index].isspace():+ next_index += 1+ if next_index < len(text) and text[next_index] in "}]":+ index += 1+ continue+ output.append(char)+ else:+ output.append(char)+ index += 1+ return "".join(output)++def _parse_json_loose(text: str) -> dict[str, Any]:- """Parse JSON text, stripping line comments (// ...) when needed.+ """Parse JSON text and JSONC comments/trailing commas.- Tries standard JSON first to avoid corrupting URLs that contain ``//``.- Falls back to stripping ``//`` comments when standard parsing fails.- Two-pass: (1) remove comment-only lines, (2) strip inline trailing- comments that follow a comma.+ Standard JSON is tried first so URLs containing ``//`` remain untouched."""try:parsed = json.loads(text)return parsed if isinstance(parsed, dict) else {}except json.JSONDecodeError:pass- # Pass 1: remove lines that are ONLY a comment.- cleaned = re.sub(r"^\s*//[^\n]*\n", "", text, flags=re.MULTILINE)- # Pass 2: remove inline trailing comments (", // comment").- cleaned = re.sub(r",\s*//[^\n]*", ",", cleaned)+ cleaned = _strip_jsonc_comments(text)+ cleaned = _strip_jsonc_trailing_commas(cleaned)try:parsed = json.loads(cleaned)return parsed if isinstance(parsed, dict) else {}@@ -195,6 +282,7 @@ def inject_opencode_provider_config(port: int, *, keep_user_entries: bool = Falstry:config_dir.mkdir(parents=True, exist_ok=True)+ migrate_legacy_opencode_jsonc_backup(config_file, backup_file)snapshot_opencode_config_if_unwrapped(config_file, backup_file)if config_file.exists():diff --git a/headroom/providers/opencode/install.py b/headroom/providers/opencode/install.pyindex 38bc951f9..9563317f2 100644--- a/headroom/providers/opencode/install.py+++ b/headroom/providers/opencode/install.py@@ -13,6 +13,7 @@ from headroom.install.paths import opencode_config_pathfrom .config import (_inject_key_into_json,_parse_json_loose,+ migrate_legacy_opencode_jsonc_backup,snapshot_opencode_config_if_unwrapped,strip_opencode_headroom_blocks,)@@ -33,10 +34,9 @@ def apply_provider_scope(manifest: DeploymentManifest) -> ManagedMutation | Noneconfig_file = opencode_config_path()config_file.parent.mkdir(parents=True, exist_ok=True)-- snapshot_opencode_config_if_unwrapped(- config_file, config_file.with_suffix(".json.headroom-backup")- )+ backup_file = config_file.with_name(config_file.name + ".headroom-backup")+ migrate_legacy_opencode_jsonc_backup(config_file, backup_file)+ snapshot_opencode_config_if_unwrapped(config_file, backup_file)if config_file.exists():content = fsutil.read_text(config_file)@@ -53,7 +53,7 @@ def apply_provider_scope(manifest: DeploymentManifest) -> ManagedMutation | None}data = _inject_key_into_json(data, "provider", provider)- config_file.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")+ config_file.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8", newline="\n")return ManagedMutation(target=ToolTarget.OPENCODE.value,kind="json-block",@@ -61,29 +61,52 @@ def apply_provider_scope(manifest: DeploymentManifest) -> ManagedMutation | None)-def revert_provider_scope(mutation: ManagedMutation, manifest: DeploymentManifest) -> None:- """Revert OpenCode provider-scope configuration.+def restore_opencode_backup(config_path: str, backup_path: str) -> None:+ """Restore the owned OpenCode snapshot, if it still exists."""+ path = Path(config_path)+ backup_file = Path(backup_path)+ migrate_legacy_opencode_jsonc_backup(path, backup_file)+ if backup_file.exists():+ shutil.copy2(backup_file, path)+ backup_file.unlink()+++def revert_provider_scope(+ mutation: ManagedMutation,+ manifest: DeploymentManifest,+ *,+ restore_backup: bool = True,+) -> None:+ """Undo OpenCode provider-scope configuration.- Restores from pre-wrap backup when available, otherwise strips the- headroom provider from the config file.+ Final removal restores the pre-install snapshot when available. Temporary+ deactivation removes only the managed provider and retains that snapshot."""del manifestif not mutation.path:returnpath = Path(mutation.path)- backup_file = path.with_suffix(".json.headroom-backup")- if backup_file.exists():+ backup_file = path.with_name(path.name + ".headroom-backup")+ migrate_legacy_opencode_jsonc_backup(path, backup_file)+ if restore_backup and backup_file.exists():try:- shutil.copy2(backup_file, path)- backup_file.unlink()+ restore_opencode_backup(str(path), str(backup_file))returnexcept OSError:passif not path.exists():returncontent = fsutil.read_text(path)+ data = _parse_json_loose(content)+ providers = data.get("provider")+ if isinstance(providers, dict) and "headroom" in providers:+ providers.pop("headroom")+ if not providers:+ data.pop("provider", None)+ path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8", newline="\n")+ returncleaned = strip_opencode_headroom_blocks(content)- if cleaned:- path.write_text(cleaned + "\n", encoding="utf-8")- else:+ if cleaned != content.strip():+ path.write_text(cleaned + "\n", encoding="utf-8", newline="\n")+ elif not data and not content.strip():path.unlink(missing_ok=True)diff --git a/tests/test_cli/test_install_cli.py b/tests/test_cli/test_install_cli.pyindex c392d6b82..36cc7c475 100644--- a/tests/test_cli/test_install_cli.py+++ b/tests/test_cli/test_install_cli.py@@ -531,7 +531,8 @@ def test_install_restart_uses_internal_helpers(monkeypatch) -> None:monkeypatch.setattr("headroom.cli.install.load_manifest", lambda profile: Manifest())monkeypatch.setattr(- "headroom.cli.install.revert_mutations", lambda manifest: calls.append("revert")+ "headroom.cli.install.revert_mutations",+ lambda manifest, **kwargs: calls.append("revert"),)monkeypatch.setattr("headroom.cli.install.stop_supervisor", lambda manifest: calls.append("stop_supervisor")@@ -893,7 +894,8 @@ def test_install_start_restarts_wedged_runtime_under_single_lock(monkeypatch) ->lambda manifest, timeout_seconds, **kwargs: next(wait_results),)monkeypatch.setattr(- "headroom.cli.install.revert_mutations", lambda manifest: calls.append("revert")+ "headroom.cli.install.revert_mutations",+ lambda manifest, **kwargs: calls.append("revert"),)monkeypatch.setattr("headroom.cli.install.apply_mutations", lambda manifest: calls.append("apply") or []@@ -985,134 +987,6 @@ def test_install_apply_accepts_opencode_target(monkeypatch) -> None:assert "Targets: opencode" in result.output-def test_install_apply_restores_previous_deployment_after_failed_update(monkeypatch) -> None:- runner = CliRunner()- calls: list[str] = []-- class Manifest:- targets = ["claude"]- port = 8787- backend = "anthropic"- tool_envs = {}-- def __init__(self, profile: str, targets: list[str]) -> None:- self.profile = profile- self.preset = "persistent-service"- self.runtime_kind = "python"- self.supervisor_kind = "service"- self.scope = "user"- self.health_url = "http://127.0.0.1:8787/readyz"- self.targets = targets- self.mutations = []- self.artifacts = []-- new_manifest = Manifest("default", ["claude"])- existing_manifest = Manifest("default", ["codex"])- existing_manifest.mutations = [object()]-- monkeypatch.setattr("headroom.cli.install.build_manifest", lambda **_: new_manifest)- monkeypatch.setattr("headroom.cli.install.load_manifest", lambda profile: existing_manifest)- monkeypatch.setattr(- "headroom.cli.install.apply_mutations",- lambda deployment: calls.append(f"apply:{','.join(deployment.targets)}") or [],- )- monkeypatch.setattr(- "headroom.cli.install.install_supervisor",- lambda deployment, **kwargs: (- calls.append(f"supervisor:{','.join(deployment.targets)}") or []- ),- )- monkeypatch.setattr(- "headroom.cli.install.save_manifest",- lambda deployment: calls.append(f"save:{','.join(deployment.targets)}"),- )- monkeypatch.setattr(- "headroom.cli.install.stop_supervisor",- lambda deployment: calls.append(f"stop-supervisor:{','.join(deployment.targets)}"),- )- monkeypatch.setattr(- "headroom.cli.install.stop_runtime",- lambda deployment: calls.append(f"stop-runtime:{','.join(deployment.targets)}"),- )- monkeypatch.setattr(- "headroom.cli.install.remove_supervisor",- lambda deployment: calls.append(f"remove-supervisor:{','.join(deployment.targets)}"),- )- monkeypatch.setattr(- "headroom.cli.install.revert_mutations",- lambda deployment: calls.append(f"revert:{','.join(deployment.targets)}"),- )- monkeypatch.setattr(- "headroom.cli.install.delete_manifest",- lambda profile: calls.append(f"delete:{profile}"),- )- monkeypatch.setattr(- "headroom.cli.install.delete_recovery_manifest",- lambda profile: calls.append(f"delete-recovery:{profile}"),- )-- def _start(deployment) -> None:- calls.append(f"start:{','.join(deployment.targets)}")- if deployment is new_manifest:- raise click.ClickException("boom")-- monkeypatch.setattr("headroom.cli.install._start_deployment", _start)-- result = runner.invoke(main, ["install", "apply"])-- assert result.exit_code != 0- assert "Restoring previous deployment 'default'" in result.output- assert calls == [- "revert:codex",- "stop-supervisor:codex",- "stop-runtime:codex",- "remove-supervisor:codex",- "delete:default",- "save:claude",- "supervisor:claude",- "save:claude",- "start:claude",- "stop-supervisor:claude",- "stop-runtime:claude",- "remove-supervisor:claude",- "delete:default",- "supervisor:codex",- "save:codex",- "start:codex",- "apply:codex",- "save:codex",- "delete-recovery:default",- ]---def test_install_apply_reports_restore_failure_with_recovery_path(monkeypatch) -> None:- previous = SimpleNamespace(profile="default")- new = SimpleNamespace(profile="default", artifacts=[], mutations=[])- monkeypatch.setattr(inst, "load_manifest", lambda profile: previous)- monkeypatch.setattr(inst, "_save_recovery_snapshot", lambda *args: None)- monkeypatch.setattr(inst, "_remove_deployment", lambda manifest: None)- monkeypatch.setattr(inst, "_save_apply_manifest", lambda manifest: None)- monkeypatch.setattr(inst, "install_supervisor", lambda manifest, **kwargs: [])- monkeypatch.setattr(- inst,- "_start_deployment",- lambda manifest: (_ for _ in ()).throw(click.ClickException("startup failed")),- )- monkeypatch.setattr(- inst,- "_restore_deployment",- lambda manifest: (_ for _ in ()).throw(RuntimeError("restore failed")),- )-- with pytest.raises(click.ClickException) as exc:- inst._apply_manifest(new)-- message = str(exc.value)- assert "restore failed" in message- assert "recovery snapshot:" in message- assert "restore it after resolving the failure" in message--def test_install_apply_old_removal_failure_is_actionable_and_does_not_start_new(monkeypatch,) -> None:@@ -1124,7 +998,7 @@ def test_install_apply_old_removal_failure_is_actionable_and_does_not_start_new(monkeypatch.setattr(inst,"_remove_deployment",- lambda manifest: (_ for _ in ()).throw(RuntimeError("old removal failed")),+ lambda manifest, **kwargs: (_ for _ in ()).throw(RuntimeError("old removal failed")),)monkeypatch.setattr(inst, "_start_deployment", lambda manifest: calls.append("start"))@@ -1165,7 +1039,7 @@ def test_install_apply_uses_requested_profile_for_recovery_snapshot(backend="anthropic",)monkeypatch.setattr(inst, "load_manifest", lambda profile: previous)- monkeypatch.setattr(inst, "_remove_deployment", lambda manifest: None)+ monkeypatch.setattr(inst, "_remove_deployment", lambda manifest, **kwargs: None)monkeypatch.setattr(inst, "_save_apply_manifest", lambda manifest: None)monkeypatch.setattr(inst, "install_supervisor", lambda manifest, **kwargs: [])monkeypatch.setattr(@@ -1244,7 +1118,7 @@ def test_apply_persists_before_darwin_bootstrap_or_start_on_save_failure(monkeypmonkeypatch.setattr(inst, "_start_deployment", lambda current: start_calls.append(current.profile))- monkeypatch.setattr(inst, "_remove_deployment", lambda current: None)+ monkeypatch.setattr(inst, "_remove_deployment", lambda current, **kwargs: None)with pytest.raises(click.ClickException, match="active manifest busy"):inst._apply_manifest(manifest)@@ -1276,7 +1150,9 @@ def test_activate_mutations_reverts_side_effects_when_strict_save_fails(monkeypalambda current: (_ for _ in ()).throw(OSError("manifest busy")),)monkeypatch.setattr(- inst, "revert_mutations", lambda current: reverted.extend(current.mutations)+ inst,+ "revert_mutations",+ lambda current, **kwargs: reverted.extend(current.mutations),)with pytest.raises(OSError, match="manifest busy"):@@ -1324,53 +1200,27 @@ def test_install_apply_keeps_new_owner_recovery_fail_closed(monkeypatch, tmp_pathost="127.0.0.1",backend="anthropic",)- calls: list[str] = []monkeypatch.setattr(inst, "load_manifest", lambda profile: previous)- real_save_recovery = inst._save_recovery_snapshot-- def save_recovery(manifest, profile):- real_save_recovery(manifest, profile)- calls.append("snapshot")- monkeypatch.setattr(inst, "_save_recovery_snapshot", save_recovery)-- def remove(manifest):- calls.append("remove-new" if manifest is new else "remove-old")+ def remove(manifest, **kwargs):if manifest is new:raise RuntimeError("new deployment cleanup failed")monkeypatch.setattr(inst, "_remove_deployment", remove)- real_save_apply = inst._save_apply_manifest-- def save_apply(manifest):- real_save_apply(manifest)- calls.append("save-new")-- monkeypatch.setattr(inst, "_save_apply_manifest", save_apply)- monkeypatch.setattr(- inst, "install_supervisor", lambda manifest, **kwargs: calls.append("install-new") or []- )+ monkeypatch.setattr(inst, "install_supervisor", lambda manifest, **kwargs: [])monkeypatch.setattr(inst,"_start_deployment",lambda manifest: (_ for _ in ()).throw(click.ClickException("startup failed")),)- monkeypatch.setattr(inst, "_restore_deployment", lambda manifest: calls.append("restore-old"))- monkeypatch.setattr(- inst, "delete_recovery_manifest", lambda profile: calls.append("delete-snapshot")- )- with pytest.raises(click.ClickException) as exc:+ with pytest.raises(click.ClickException):inst._apply_manifest(new)- message = str(exc.value)- assert "startup failed" in message- assert "new deployment cleanup failed" in message- assert "recovery snapshot" in message- assert "remove the new owner before restoring the snapshot" in message- assert calls == ["snapshot", "remove-old", "save-new", "install-new", "save-new", "remove-new"]- assert load_state_manifest("default") is not None+ owner = load_state_manifest("default")+ assert owner is not None+ assert owner.targets == ["new"]recovery = tmp_path / ".headroom" / "deploy" / "default.recovery.json"assert json.loads(recovery.read_text(encoding="utf-8"))["targets"] == ["old"]@@ -1403,9 +1253,8 @@ def test_install_apply_keeps_snapshot_when_active_persistence_fails(host="127.0.0.1",backend="anthropic",)- calls: list[str] = []monkeypatch.setattr(inst, "load_manifest", lambda profile: previous)- monkeypatch.setattr(inst, "_remove_deployment", lambda manifest: calls.append("cleanup"))+ monkeypatch.setattr(inst, "_remove_deployment", lambda manifest, **kwargs: None)monkeypatch.setattr(inst, "install_supervisor", lambda manifest, **kwargs: [])saves = 0@@ -1418,60 +1267,15 @@ def test_install_apply_keeps_snapshot_when_active_persistence_fails(raise OSError("active manifest busy")monkeypatch.setattr(inst, "_save_apply_manifest", fail_active_save)- monkeypatch.setattr(inst, "_restore_deployment", lambda manifest: calls.append("restore"))- monkeypatch.setattr(inst, "delete_recovery_manifest", lambda profile: calls.append("delete"))-- with pytest.raises(click.ClickException) as exc:- inst._apply_manifest(new)-- assert "active manifest persistence failed" in str(exc.value)- assert "recovery snapshot:" in str(exc.value)- assert calls == ["cleanup", "cleanup"]- assert load_state_manifest("default") is not None- assert (tmp_path / ".headroom" / "deploy" / "default.recovery.json").exists()---def test_install_apply_persists_new_manifest_before_supervisor_install(monkeypatch) -> None:- new = SimpleNamespace(profile="default", artifacts=[], mutations=[])- calls: list[str] = []-- monkeypatch.setattr(inst, "load_manifest", lambda profile: None)- monkeypatch.setattr(inst, "_save_apply_manifest", lambda manifest: calls.append("save"))- monkeypatch.setattr(- inst,- "install_supervisor",- lambda manifest, **kwargs: (_ for _ in ()).throw(RuntimeError("install failed")),- )- monkeypatch.setattr(inst, "_remove_deployment", lambda manifest: calls.append("cleanup"))-- with pytest.raises(click.ClickException, match="install failed"):- inst._apply_manifest(new)-- assert calls == ["save", "cleanup"]---def test_install_apply_without_previous_has_no_recovery_guidance(monkeypatch) -> None:- new = SimpleNamespace(profile="default", artifacts=[], mutations=[])- monkeypatch.setattr(inst, "load_manifest", lambda profile: None)- monkeypatch.setattr(inst, "_save_apply_manifest", lambda manifest: None)- monkeypatch.setattr(inst, "install_supervisor", lambda manifest, **kwargs: [])- monkeypatch.setattr(- inst,- "_start_deployment",- lambda manifest: (_ for _ in ()).throw(click.ClickException("startup failed")),- )- monkeypatch.setattr(- inst,- "_remove_deployment",- lambda manifest: (_ for _ in ()).throw(RuntimeError("cleanup failed")),- )- with pytest.raises(click.ClickException) as exc:+ with pytest.raises(click.ClickException):inst._apply_manifest(new)- message = str(exc.value)- assert "startup failed" in message and "cleanup failed" in message- assert "recovery snapshot" not in message+ owner = load_state_manifest("default")+ assert owner is not None+ assert owner.targets == ["new"]+ recovery = tmp_path / ".headroom" / "deploy" / "default.recovery.json"+ assert json.loads(recovery.read_text(encoding="utf-8"))["targets"] == ["old"]def test_install_start_rejects_task_lifecycle(monkeypatch) -> None:@@ -1753,7 +1557,8 @@ def test_install_remove_retains_manifest_when_runtime_teardown_errors(monkeypatcmonkeypatch.setattr("headroom.cli.install.load_manifest", lambda profile: Manifest())monkeypatch.setattr(- "headroom.cli.install.revert_mutations", lambda manifest: calls.append("revert")+ "headroom.cli.install.revert_mutations",+ lambda manifest, **kwargs: calls.append("revert"),)monkeypatch.setattr("headroom.cli.install.stop_supervisor",@@ -1892,7 +1697,8 @@ def test_install_agent_ensure_stops_wedged_runtime_before_restart(monkeypatch) -monkeypatch.setattr("headroom.cli.install.wait_ready", fake_wait_ready)monkeypatch.setattr(- "headroom.cli.install.revert_mutations", lambda manifest: calls.append("revert")+ "headroom.cli.install.revert_mutations",+ lambda manifest, **kwargs: calls.append("revert"),)monkeypatch.setattr("headroom.cli.install.apply_mutations", lambda manifest: calls.append("apply") or []@@ -2146,3 +1952,83 @@ def test_install_start_still_skips_when_nothing_is_pending(monkeypatch) -> None:assert result.exit_code == 0, result.outputassert applied == []++[email protected]("lifecycle", ["apply", "restart", "ensure"])+def test_opencode_reactivation_preserves_edits(+ lifecycle: str, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """Reapply, restart, and watchdog recovery keep edits made after installation."""+ import contextlib++ from headroom.install.providers import apply_mutations++ monkeypatch.setenv("OPENCODE_CONFIG", str(tmp_path / "opencode.json"))+ config_file = tmp_path / "opencode.json"+ original = {"theme": "original", "mcp": {"local": {}}}+ config_file.write_text(json.dumps(original))+ previous = DeploymentManifest(+ profile="default",+ preset="persistent-service",+ runtime_kind="python",+ supervisor_kind="none",+ scope="provider",+ provider_mode="manual",+ targets=["opencode"],+ port=8787,+ host="127.0.0.1",+ backend="anthropic",+ )+ apply_mutations(previous)++ edited = json.loads(config_file.read_text())+ edited["theme"] = "edited after install"+ edited["provider"] = {"other": {"name": "User provider"}}+ edited["mcp"]["remote"] = {"url": "https://example.test"}+ config_file.write_text(json.dumps(edited))++ monkeypatch.setattr(inst, "_save_apply_manifest", lambda manifest: None)+ monkeypatch.setattr(inst, "save_manifest", lambda manifest: None)+ monkeypatch.setattr(inst, "load_manifest", lambda profile: previous)+ monkeypatch.setattr(inst, "_stop_deployment", lambda manifest: None)+ monkeypatch.setattr(inst, "_start_deployment", lambda manifest, **kwargs: None)+ monkeypatch.setattr(inst, "install_supervisor", lambda manifest, **kwargs: [])+ monkeypatch.setattr(inst, "remove_supervisor", lambda manifest: None)+ monkeypatch.setattr(inst, "delete_manifest", lambda profile: None)++ if lifecycle == "apply":+ monkeypatch.setattr(inst, "_save_recovery_snapshot", lambda *args: None)+ monkeypatch.setattr(inst, "_delete_recovery_snapshot", lambda profile: None)+ new = DeploymentManifest(+ profile="default",+ preset="persistent-service",+ runtime_kind="python",+ supervisor_kind="none",+ scope="provider",+ provider_mode="manual",+ targets=["opencode"],+ port=8787,+ host="127.0.0.1",+ backend="anthropic",+ )+ inst._apply_manifest(new)+ elif lifecycle == "restart":+ monkeypatch.setattr(inst, "probe_ready", lambda url: False)+ result = CliRunner().invoke(main, ["install", "restart"])+ assert result.exit_code == 0, result.output+ else:+ monkeypatch.setattr(inst, "runtime_status", lambda manifest: "running")+ monkeypatch.setattr(inst, "probe_ready", lambda url: False)+ monkeypatch.setattr(inst, "wait_ready", lambda *args, **kwargs: False)+ monkeypatch.setattr(inst, "stop_runtime", lambda manifest: None)+ monkeypatch.setattr(+ inst, "acquire_runtime_start_lock", lambda profile: contextlib.nullcontext(True)+ )+ result = CliRunner().invoke(main, ["install", "agent", "ensure"])+ assert result.exit_code == 0, result.output++ actual = json.loads(config_file.read_text())+ assert actual["theme"] == "edited after install"+ assert actual["provider"]["other"] == {"name": "User provider"}+ assert actual["provider"]["headroom"]["options"]["baseURL"] == ("http://127.0.0.1:8787/v1")+ assert actual["mcp"]["remote"] == {"url": "https://example.test"}diff --git a/tests/test_cli/test_wrap_opencode.py b/tests/test_cli/test_wrap_opencode.pyindex 0c49887d7..764fb669f 100644--- a/tests/test_cli/test_wrap_opencode.py+++ b/tests/test_cli/test_wrap_opencode.py@@ -624,27 +624,30 @@ def test_unwrap_opencode_restores_from_backup(assert config_file.read_text(encoding="utf-8") == original+ "backup_name", ["opencode.jsonc.headroom-backup", "opencode.json.headroom-backup"]+)def test_unwrap_opencode_restores_from_backup_jsonc(runner: CliRunner,tmp_path: Path,monkeypatch: pytest.MonkeyPatch,+ backup_name: str,) -> None:"""Unwrap restores the pre-wrap backup and removes it for jsonc files."""monkeypatch.chdir(tmp_path)_set_test_home(monkeypatch, tmp_path)config_file = tmp_path / ".config" / "opencode" / "opencode.jsonc"- backup_file = config_file.with_name("opencode.jsonc.headroom-backup")+ backup_file = config_file.with_name(backup_name)config_file.parent.mkdir(parents=True, exist_ok=True)original = '{\n // User comment\n "model": "openai/gpt-4o"\n}'- config_file.write_text(original)+ config_file.write_text('{"model":"headroom/claude-sonnet-4-6","theme":"edited"}')backup_file.write_text(original)with patch.object(wrap_mod, "_stop_local_proxy_for_unwrap", return_value="stopped"):result = runner.invoke(main, ["unwrap", "opencode"])assert result.exit_code == 0, result.output- assert "Restored prior" in result.outputassert not backup_file.exists()assert config_file.read_text(encoding="utf-8") == originaldiff --git a/tests/test_providers_opencode_config.py b/tests/test_providers_opencode_config.pyindex eb50813fe..087976f1f 100644--- a/tests/test_providers_opencode_config.py+++ b/tests/test_providers_opencode_config.py@@ -346,11 +346,6 @@ def test_parse_json_loose_returns_empty_on_whitespace() -> None:assert _parse_json_loose(" \n \t ") == {}-def test_parse_json_loose_returns_empty_on_trailing_comma() -> None:- """_parse_json_loose returns {} for malformed JSON (trailing comma)."""- assert _parse_json_loose('{"model": "gpt-4o",}') == {}--def test_parse_json_loose_returns_empty_on_unclosed_brace() -> None:"""_parse_json_loose returns {} for malformed JSON (unclosed brace)."""assert _parse_json_loose('{"model": "gpt-4o"') == {}@@ -636,3 +631,29 @@ def test_inject_provider_config_strips_existing_markers(second = config_file.read_text()assert "headroom" in secondassert second.count("headroom") == first.count("headroom")++[email protected]("conflict", ["canonical", "sibling"])+def test_jsonc_migration_treats_dangling_conflict_as_ambiguous(+ tmp_path: Path, conflict: str+) -> None:+ from headroom.providers.opencode.config import migrate_legacy_opencode_jsonc_backup++ config = tmp_path / "opencode.jsonc"+ canonical = config.with_name(config.name + ".headroom-backup")+ legacy = config.with_suffix(".json.headroom-backup")+ original = b'{"theme":"unrelated legacy"}\n'+ legacy.write_bytes(original)+ conflicting_path = canonical if conflict == "canonical" else config.with_suffix(".json")+ try:+ conflicting_path.symlink_to(tmp_path / "missing-target")+ except OSError:+ pytest.skip("creating symlinks requires platform permissions")++ migrate_legacy_opencode_jsonc_backup(config, canonical)+ assert conflicting_path.is_symlink()+ assert legacy.read_bytes() == original+ conflicting_path.unlink()+ migrate_legacy_opencode_jsonc_backup(config, canonical)+ assert not canonical.exists()+ assert legacy.read_bytes() == originaldiff --git a/tests/test_providers_opencode_install.py b/tests/test_providers_opencode_install.pyindex b8e529da0..cfe236902 100644--- a/tests/test_providers_opencode_install.py+++ b/tests/test_providers_opencode_install.py@@ -2,6 +2,7 @@from __future__ import annotations+import jsonfrom pathlib import Pathimport pytest@@ -100,6 +101,67 @@ def test_revert_provider_scope_restores_file(assert config_file.read_text().strip() == '{"model": "openai/gpt-4o"}'[email protected]("suffix", [".json", ".jsonc"])+def test_temporary_deactivation_preserves_edits_and_backup(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, suffix: str+) -> None:+ """Reactivation removes only Headroom's provider and keeps the unwrap snapshot."""+ import json++ from headroom.cli import install as cli_install+ from headroom.install.providers import revert_mutations++ config_file = tmp_path / f"opencode{suffix}"+ monkeypatch.setenv("OPENCODE_CONFIG", str(config_file))+ monkeypatch.delenv("OPENCODE_HOME", raising=False)+ monkeypatch.setattr(cli_install, "_save_apply_manifest", lambda manifest: None)+ monkeypatch.setattr(cli_install, "save_manifest", lambda manifest: None)+ original_json = (+ b'{"theme":"original","provider":{"anthropic":{"name":"Claude"}},"mcp":{"local":{}}}\n'+ )+ original = (+ b"// user comment in OpenCode JSONC\n" + original_json+ if suffix == ".jsonc"+ else original_json+ )+ config_file.write_bytes(original)++ manifest = _manifest()+ manifest.targets = ["opencode"]+ cli_install._activate_deployment_mutations(manifest)+ backup_file = config_file.with_name(config_file.name + ".headroom-backup")+ assert backup_file.read_bytes() == original++ for theme in ("edited after install", "edited again"):+ data = json.loads(config_file.read_text())+ data["theme"] = theme+ data["provider"]["other-user-provider"] = {"name": "Other"}+ data["mcp"]["remote"] = {"url": "https://example.test"}+ config_file.write_text(json.dumps(data))++ cli_install._deactivate_deployment_mutations(manifest)+ assert manifest.mutations == []+ assert backup_file.read_bytes() == original+ inactive = json.loads(config_file.read_text())+ assert inactive["theme"] == theme+ assert inactive["provider"] == {+ "anthropic": {"name": "Claude"},+ "other-user-provider": {"name": "Other"},+ }+ assert inactive["mcp"]["remote"] == {"url": "https://example.test"}++ cli_install._activate_deployment_mutations(manifest)+ active = json.loads(config_file.read_text())+ assert active["theme"] == theme+ assert active["provider"]["headroom"]["options"]["baseURL"] == ("http://127.0.0.1:8787/v1")+ assert active["provider"]["other-user-provider"] == {"name": "Other"}+ assert active["mcp"]["remote"] == {"url": "https://example.test"}++ revert_mutations(manifest, restore_backup=True)+ assert config_file.read_bytes() == original+ assert not backup_file.exists()++def test_revert_provider_scope_noop_when_file_missing(tmp_path: Path,) -> None:@@ -114,3 +176,589 @@ def test_revert_provider_scope_noop_when_file_missing(manifest = _manifest()revert_provider_scope(mutation, manifest)# Should not raise++[email protected]_newline+def test_provider_config_writes_pin_lf(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """Provider edits and stale managed-block cleanup pin LF and preserve user config."""+ config_file = tmp_path / "opencode.json"+ monkeypatch.setenv("OPENCODE_CONFIG", str(config_file))+ monkeypatch.delenv("OPENCODE_HOME", raising=False)+ config_file.write_bytes(b'{"theme":"before"}\n')++ writes: list[tuple[Path, str | None]] = []+ original_write_text = Path.write_text++ def write_text_spy(self, data, encoding=None, errors=None, newline=None):+ writes.append((self, newline))+ return original_write_text(self, data, encoding=encoding, errors=errors, newline=newline)++ monkeypatch.setattr(Path, "write_text", write_text_spy)++ manifest = _manifest()+ mutation = apply_provider_scope(manifest)+ assert mutation is not None+ revert_provider_scope(mutation, manifest, restore_backup=False)++ marker_config = (+ '{\n "theme": "kept",\n'+ "// --- Headroom proxy provider ---\n"+ " stale generated provider block\n"+ "// --- end Headroom proxy provider ---\n"+ ' "mcp": {"remote": {}}\n}\n'+ )+ config_file.write_bytes(marker_config.encode())+ revert_provider_scope(mutation, manifest, restore_backup=False)++ assert len(writes) == 3+ assert all(path == config_file and newline == "\n" for path, newline in writes)+ import json++ cleaned = json.loads(config_file.read_text())+ assert cleaned == {"theme": "kept", "mcp": {"remote": {}}}++[email protected]("suffix", [".json", ".jsonc"])+def test_install_stop_remove_restores_original_backup(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, suffix: str+) -> None:+ from headroom.cli import install as cli_install++ config_file = tmp_path / f"opencode{suffix}"+ monkeypatch.setenv("OPENCODE_CONFIG", str(config_file))+ monkeypatch.delenv("OPENCODE_HOME", raising=False)+ original = (+ b'{"theme":"before","provider":{"anthropic":{}},}\n'+ if suffix == ".jsonc"+ else b'{"theme":"before","provider":{"anthropic":{}}}\n'+ )+ config_file.write_bytes(original)+ manifest = _manifest()+ manifest.targets = ["opencode"]+ monkeypatch.setattr(cli_install, "_save_apply_manifest", lambda current: None)+ monkeypatch.setattr(cli_install, "save_manifest", lambda current: None)+ monkeypatch.setattr(cli_install, "stop_runtime", lambda current: None)+ monkeypatch.setattr(cli_install, "wait_stopped", lambda current: True)+ monkeypatch.setattr(cli_install, "remove_supervisor", lambda current: None)+ monkeypatch.setattr(cli_install, "delete_manifest", lambda profile: None)++ cli_install._activate_deployment_mutations(manifest)+ cli_install._deactivate_deployment_mutations(manifest)+ assert manifest.mutations == []+ cli_install._remove_deployment(manifest, restore_backup=True)++ assert config_file.read_bytes() == original+ assert not config_file.with_name(config_file.name + ".headroom-backup").exists()+++def test_failed_activation_retains_backup_for_final_remove_after_reload(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from headroom.cli import install as cli_install++ monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / "headroom-state"))+ config_file = tmp_path / "opencode.json"+ monkeypatch.setenv("OPENCODE_CONFIG", str(config_file))+ monkeypatch.delenv("OPENCODE_HOME", raising=False)+ original = b'{"theme":"original"}\n'+ config_file.write_bytes(original)+ manifest = _manifest()+ manifest.targets = ["opencode"]+ real_save = cli_install._save_apply_manifest+ real_save(manifest)++ def fail_activation_save(current):+ if current.mutations:+ raise OSError("manifest save failed")+ real_save(current)++ monkeypatch.setattr(cli_install, "_save_apply_manifest", fail_activation_save)+ with pytest.raises(OSError, match="manifest save failed"):+ cli_install._activate_deployment_mutations(manifest)++ backup_file = config_file.with_name(config_file.name + ".headroom-backup")+ assert manifest.mutations == []+ assert backup_file.read_bytes() == original+ from headroom.install.state import load_manifest as load_state_manifest++ persisted = load_state_manifest(manifest.profile)+ assert persisted is not None++ monkeypatch.setattr(cli_install, "_save_apply_manifest", lambda current: None)+ monkeypatch.setattr(cli_install, "stop_runtime", lambda current: None)+ monkeypatch.setattr(cli_install, "wait_stopped", lambda current: True)+ monkeypatch.setattr(cli_install, "remove_supervisor", lambda current: None)+ monkeypatch.setattr(cli_install, "delete_manifest", lambda profile: None)+ cli_install._remove_deployment(persisted, restore_backup=True)+ assert config_file.read_bytes() == original+ assert not backup_file.exists()++[email protected]("config_name", ["opencode.jsonc", "custom-settings.jsonc"])+def test_legacy_jsonc_backup_migrates_before_restart_and_final_removal(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, config_name: str+) -> None:+ from headroom.cli import install as cli_install++ config_file = tmp_path / config_name+ monkeypatch.setenv("OPENCODE_CONFIG", str(config_file))+ monkeypatch.delenv("OPENCODE_HOME", raising=False)+ original = b'// user\'s original JSONC\n{"theme":"original",}\n'+ config_file.write_bytes(b'{"theme":"edited","provider":{"headroom":{}}}\n')+ legacy_backup = config_file.with_suffix(".json.headroom-backup")+ legacy_backup.write_bytes(original)+ canonical_backup = config_file.with_name(config_file.name + ".headroom-backup")+ manifest = _manifest()+ manifest.targets = ["opencode"]+ monkeypatch.setattr(cli_install, "_save_apply_manifest", lambda current: None)+ monkeypatch.setattr(cli_install, "save_manifest", lambda current: None)+ monkeypatch.setattr(cli_install, "stop_runtime", lambda current: None)+ monkeypatch.setattr(cli_install, "wait_stopped", lambda current: True)+ monkeypatch.setattr(cli_install, "remove_supervisor", lambda current: None)+ monkeypatch.setattr(cli_install, "delete_manifest", lambda profile: None)++ cli_install._activate_deployment_mutations(manifest)+ assert canonical_backup.read_bytes() == original+ assert not legacy_backup.exists()+ cli_install._deactivate_deployment_mutations(manifest)+ cli_install._activate_deployment_mutations(manifest)+ cli_install._remove_deployment(+ manifest,+ restore_backup=True,+ )+ assert config_file.read_bytes() == original+ assert not canonical_backup.exists()+++def test_jsonc_trailing_commas_preserve_consumer_edits_across_reactivation(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from headroom.cli import install as cli_install+ from headroom.install.providers import revert_mutations+ from headroom.providers.opencode.config import _parse_json_loose++ config_file = tmp_path / "opencode.jsonc"+ monkeypatch.setenv("OPENCODE_CONFIG", str(config_file))+ monkeypatch.delenv("OPENCODE_HOME", raising=False)+ original = (+ b'// original comment\n{"theme":"original","provider":{"anthropic":{"name":"Claude"},},'+ b'"mcp":{"local":{},},}\n'+ )+ config_file.write_bytes(original)+ manifest = _manifest()+ manifest.targets = ["opencode"]++ monkeypatch.setattr(cli_install, "_save_apply_manifest", lambda current: None)+ cli_install._activate_deployment_mutations(manifest)+ config_file.write_text(+ '// consumer edit\n{"theme":"edited","provider":{"anthropic":{"name":"Claude",},'+ '"headroom":{"options":{"baseURL":"http://127.0.0.1:8787/v1",},},},'+ '"mcp":{"remote":{"url":"https://example.test",},},}\n'+ )+ cli_install._deactivate_deployment_mutations(manifest)+ inactive = _parse_json_loose(config_file.read_text())+ assert inactive["theme"] == "edited"+ assert inactive["provider"] == {"anthropic": {"name": "Claude"}}+ assert inactive["mcp"]["remote"]["url"] == "https://example.test"+ cli_install._activate_deployment_mutations(manifest)+ active = _parse_json_loose(config_file.read_text())+ assert active["theme"] == "edited"+ assert active["provider"]["headroom"]["options"]["baseURL"].endswith("/v1")+ assert active["mcp"]["remote"]["url"] == "https://example.test"+ revert_mutations(manifest, restore_backup=True)+ assert config_file.read_bytes() == original+++def test_successful_replacement_dropping_opencode_restores_original_snapshot(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from headroom.cli import install as cli_install+ from headroom.install.state import save_manifest_strict++ monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / "headroom-state"))+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("OPENCODE_CONFIG", str(tmp_path / "opencode.json"))+ monkeypatch.delenv("OPENCODE_HOME", raising=False)+ config_file = tmp_path / "opencode.json"+ original = b'{"theme":"original"}\n'+ config_file.write_bytes(original)+ previous = _manifest()+ previous.targets = ["opencode"]+ cli_install._activate_deployment_mutations(previous)+ save_manifest_strict(previous)+ replacement = _manifest()+ replacement.targets = []++ monkeypatch.setattr(cli_install, "load_manifest", lambda profile: previous)+ monkeypatch.setattr(cli_install, "install_supervisor", lambda current, **kwargs: [])+ monkeypatch.setattr(cli_install, "_start_deployment", lambda current: None)+ monkeypatch.setattr(cli_install, "stop_runtime", lambda current: None)+ monkeypatch.setattr(cli_install, "wait_stopped", lambda current: True)+ monkeypatch.setattr(cli_install, "remove_supervisor", lambda current: None)++ cli_install._apply_manifest(replacement)++ assert config_file.read_bytes() == original+ assert not config_file.with_name("opencode.json.headroom-backup").exists()+++def test_failed_replacement_retains_opencode_snapshot_and_reinstates_provider(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ import click++ from headroom.cli import install as cli_install+ from headroom.install.state import save_manifest_strict++ monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / "headroom-state"))+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("OPENCODE_CONFIG", str(tmp_path / "opencode.json"))+ monkeypatch.delenv("OPENCODE_HOME", raising=False)+ config_file = tmp_path / "opencode.json"+ original = b'{"theme":"original"}\n'+ config_file.write_bytes(original)+ previous = _manifest()+ previous.targets = ["opencode"]+ cli_install._activate_deployment_mutations(previous)+ save_manifest_strict(previous)+ replacement = _manifest()+ replacement.targets = []+ backup_file = config_file.with_name("opencode.json.headroom-backup")++ monkeypatch.setattr(cli_install, "load_manifest", lambda profile: previous)+ monkeypatch.setattr(cli_install, "install_supervisor", lambda current, **kwargs: [])++ def start(current):+ if not current.targets:+ raise click.ClickException("replacement startup failed")++ monkeypatch.setattr(cli_install, "_start_deployment", start)+ monkeypatch.setattr(cli_install, "stop_runtime", lambda current: None)+ monkeypatch.setattr(cli_install, "wait_stopped", lambda current: True)+ monkeypatch.setattr(cli_install, "remove_supervisor", lambda current: None)++ with pytest.raises(click.ClickException, match="replacement startup failed"):+ cli_install._apply_manifest(replacement)++ assert backup_file.read_bytes() == original+ from headroom.install.state import load_manifest as load_state_manifest++ restored = load_state_manifest(previous.profile)+ assert restored is not None and restored.mutations+ active = json.loads(config_file.read_text())+ assert active["provider"]["headroom"]["options"]["baseURL"].endswith("/v1")+++def test_jsonc_migration_does_not_claim_json_installation_backup(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from headroom.cli import install as cli_install++ config_file = tmp_path / "opencode.jsonc"+ json_config = tmp_path / "opencode.json"+ monkeypatch.setenv("OPENCODE_CONFIG", str(config_file))+ monkeypatch.delenv("OPENCODE_HOME", raising=False)+ json_config.write_bytes(b'{"theme":"json install"}\n')+ config_file.write_bytes(b'{"theme":"jsonc install"}\n')+ legacy_backup = tmp_path / "opencode.json.headroom-backup"+ legacy_original = b'{"theme":"json original"}\n'+ legacy_backup.write_bytes(legacy_original)+ manifest = _manifest()+ manifest.targets = ["opencode"]+ monkeypatch.setattr(cli_install, "_save_apply_manifest", lambda current: None)++ cli_install._activate_deployment_mutations(manifest)++ canonical_backup = tmp_path / "opencode.jsonc.headroom-backup"+ assert canonical_backup.read_bytes() == b'{"theme":"jsonc install"}\n'+ assert legacy_backup.read_bytes() == legacy_original+++def opencode_transaction(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ from headroom.cli import install as cli_install++ monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / "state"))+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("OPENCODE_CONFIG", str(tmp_path / "opencode.json"))+ monkeypatch.delenv("OPENCODE_HOME", raising=False)+ monkeypatch.setattr(cli_install, "install_supervisor", lambda current, **kwargs: [])+ monkeypatch.setattr(cli_install, "_start_deployment", lambda current: None)+ monkeypatch.setattr(cli_install, "stop_runtime", lambda current: None)+ monkeypatch.setattr(cli_install, "wait_stopped", lambda current: True)+ monkeypatch.setattr(cli_install, "remove_supervisor", lambda current: None)+ return cli_install+++def test_failed_replacement_consumes_new_unowned_snapshot(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, opencode_transaction+) -> None:+ import click++ cli_install = opencode_transaction+ config = tmp_path / "opencode.json"+ original = b'{"theme":"dark"}\n'+ config.write_bytes(original)+ previous = _manifest()+ cli_install.save_manifest_strict(previous)+ replacement = _manifest()+ replacement.targets = ["opencode"]+ real_save = cli_install._save_apply_manifest++ def fail_active_save(current):+ if current.mutations:+ raise OSError("activation persistence failed")+ real_save(current)++ with monkeypatch.context() as fault:+ fault.setattr(cli_install, "_save_apply_manifest", fail_active_save)+ with pytest.raises(click.ClickException):+ cli_install._apply_manifest(replacement)++ assert config.read_bytes() == original+ assert not config.with_name(config.name + ".headroom-backup").exists()+ later = b'{"theme":"light"}\n'+ config.write_bytes(later)+ retry = _manifest()+ retry.targets = ["opencode"]+ cli_install._apply_manifest(retry)+ cli_install._remove_deployment(retry, restore_backup=True)+ assert config.read_bytes() == later++[email protected]("legacy_manifest", [False, True])[email protected]("retain_opencode", [False, True])+def test_changed_config_path_restores_previous_snapshot(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ opencode_transaction,+ legacy_manifest: bool,+ retain_opencode: bool,+) -> None:+ cli_install = opencode_transaction+ original_config = tmp_path / "opencode.json"+ original = b'{"theme":"old config original"}\n'+ original_config.write_bytes(original)+ previous = _manifest()+ previous.targets = ["opencode"]+ cli_install._activate_deployment_mutations(previous)+ if legacy_manifest:+ previous.artifacts = []+ cli_install.save_manifest_strict(previous)+ new_config = tmp_path / "different.json"+ new_original = b'{"theme":"new config original"}\n'+ new_config.write_bytes(new_original)+ monkeypatch.setenv("OPENCODE_CONFIG", str(new_config))+ replacement = _manifest()+ replacement.targets = ["opencode"] if retain_opencode else []++ cli_install._apply_manifest(replacement)++ assert original_config.read_bytes() == original+ assert not original_config.with_name(original_config.name + ".headroom-backup").exists()+ if retain_opencode:+ assert "headroom" in json.loads(new_config.read_text())["provider"]+ cli_install._remove_deployment(replacement, restore_backup=True)+ assert new_config.read_bytes() == new_original+++def test_canonical_snapshot_wins_over_ambiguous_legacy_backup(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, opencode_transaction+) -> None:+ cli_install = opencode_transaction+ config = tmp_path / "opencode.jsonc"+ monkeypatch.setenv("OPENCODE_CONFIG", str(config))+ config.write_bytes(b'{"theme":"live"}\n')+ canonical = config.with_name("opencode.jsonc.headroom-backup")+ original = b'// current original\n{"theme":"light",}\n'+ canonical.write_bytes(original)+ legacy = config.with_suffix(".json.headroom-backup")+ legacy_original = b'{"theme":"dark"}\n'+ legacy.write_bytes(legacy_original)+ manifest = _manifest()+ manifest.targets = ["opencode"]++ cli_install._activate_deployment_mutations(manifest)+ cli_install._deactivate_deployment_mutations(manifest)+ cli_install._activate_deployment_mutations(manifest)+ cli_install._remove_deployment(manifest, restore_backup=True)++ assert config.read_bytes() == original+ assert not canonical.exists()+ assert legacy.read_bytes() == legacy_original++ later = b'// edited after removal\n{"theme":"new choice",}\n'+ config.write_bytes(later)+ second = _manifest()+ second.targets = ["opencode"]+ cli_install._activate_deployment_mutations(second)+ assert canonical.read_bytes() == later+ cli_install._remove_deployment(second, restore_backup=True)+ assert config.read_bytes() == later+ assert not canonical.exists()+ assert legacy.read_bytes() == legacy_original+++def test_replacement_restore_failure_can_finish_after_manifest_reload(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, opencode_transaction+) -> None:+ import click++ cli_install = opencode_transaction+ config = tmp_path / "opencode.json"+ original = b'{"theme":"original"}\n'+ config.write_bytes(original)+ previous = _manifest()+ previous.targets = ["opencode"]+ cli_install._activate_deployment_mutations(previous)+ replacement = _manifest()+ restore = cli_install.restore_opencode_backup++ def fail_restore(*args):+ raise OSError("backup temporarily unreadable")++ with monkeypatch.context() as fault:+ fault.setattr(cli_install, "restore_opencode_backup", fail_restore)+ with pytest.raises((OSError, click.ClickException)):+ cli_install._apply_manifest(replacement)++ persisted = cli_install.load_manifest(replacement.profile)+ assert persisted is not None and persisted.targets == []+ monkeypatch.setattr(cli_install, "restore_opencode_backup", restore)+ retry = _manifest()+ cli_install._apply_manifest(retry)++ assert config.read_bytes() == original+ assert not config.with_name(config.name + ".headroom-backup").exists()+++ ("config_name", "location"),+ [+ ("opencode.jsonc", "override"),+ ("custom-settings.jsonc", "override"),+ ("opencode.jsonc", "opencode_home"),+ ("opencode.jsonc", "default_home"),+ ],+)[email protected]("ambiguity", ["canonical", "sibling"])+def test_ambiguous_legacy_backup_stays_unowned_across_two_install_remove_cycles(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ config_name: str,+ location: str,+ ambiguity: str,+) -> None:+ """Removing the conflicting file must not grant ownership of legacy bytes."""+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ monkeypatch.delenv("OPENCODE_CONFIG", raising=False)+ monkeypatch.delenv("OPENCODE_HOME", raising=False)+ config_dir = tmp_path / ".config" / "opencode" if location == "default_home" else tmp_path+ config_dir.mkdir(parents=True, exist_ok=True)+ config = config_dir / config_name+ if location == "override":+ monkeypatch.setenv("OPENCODE_CONFIG", str(config))+ elif location == "opencode_home":+ monkeypatch.setenv("OPENCODE_HOME", str(config_dir))+ live = b'{"theme":"live"}\n'+ original = b'// current original\r\n{"theme":"light",}\r\n'+ unrelated = b'// unrelated original\r\n{"theme":"dark",}\r\n'+ config.write_bytes(live if ambiguity == "canonical" else original)+ canonical = config.with_name(config.name + ".headroom-backup")+ legacy = config.with_suffix(".json.headroom-backup")+ legacy.write_bytes(unrelated)+ sibling = config.with_suffix(".json")+ if ambiguity == "canonical":+ canonical.write_bytes(original)+ else:+ sibling.write_bytes(b'{"theme":"separate JSON installation"}\n')++ first = _manifest()+ mutation = apply_provider_scope(first)+ assert mutation is not None+ revert_provider_scope(mutation, first)+ assert config.read_bytes() == original+ assert not canonical.exists()+ assert legacy.read_bytes() == unrelated+ if ambiguity == "sibling":+ sibling.unlink()++ # A new deployment after the first snapshot has been consumed must take a+ # fresh snapshot, even though the formerly ambiguous legacy file remains.+ later = b'// edited between installations\r\n{"theme":"new choice",}\r\n'+ config.write_bytes(later)+ second = _manifest()+ mutation = apply_provider_scope(second)+ assert mutation is not None+ assert canonical.read_bytes() == later+ assert legacy.read_bytes() == unrelated+ revert_provider_scope(mutation, second, restore_backup=False)+ mutation = apply_provider_scope(second)+ assert mutation is not None+ revert_provider_scope(mutation, second)+ assert config.read_bytes() == later+ assert not canonical.exists()+ assert legacy.read_bytes() == unrelated++[email protected]("operation", ["apply", "restore"])+def test_ambiguous_legacy_backup_marker_failure_preserves_all_files(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, operation: str+) -> None:+ from headroom.providers.opencode.install import restore_opencode_backup++ config = tmp_path / "opencode.jsonc"+ monkeypatch.setenv("OPENCODE_CONFIG", str(config))+ live = b'{"theme":"live"}\n'+ original = b'{"theme":"original"}\n'+ unrelated = b'{"theme":"unrelated"}\n'+ config.write_bytes(live)+ canonical = config.with_name(config.name + ".headroom-backup")+ canonical.write_bytes(original)+ legacy = config.with_suffix(".json.headroom-backup")+ legacy.write_bytes(unrelated)+ touch = Path.touch++ def fail_marker(path: Path, *args, **kwargs) -> None:+ if path.name.endswith(".jsonc-migration-blocked"):+ raise PermissionError("migration marker is not writable")+ touch(path, *args, **kwargs)++ with monkeypatch.context() as fault:+ fault.setattr(Path, "touch", fail_marker)+ with pytest.raises(PermissionError, match="migration marker"):+ if operation == "apply":+ apply_provider_scope(_manifest())+ else:+ restore_opencode_backup(str(config), str(canonical))++ assert config.read_bytes() == live+ assert canonical.read_bytes() == original+ assert legacy.read_bytes() == unrelated+ restore_opencode_backup(str(config), str(canonical))+ assert config.read_bytes() == original+ assert not canonical.exists()+ assert legacy.read_bytes() == unrelated++[email protected]("config_name", ["opencode.jsonc", "custom-settings.jsonc"])+def test_unambiguous_legacy_backup_still_migrates_and_restores(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, config_name: str+) -> None:+ config = tmp_path / config_name+ monkeypatch.setenv("OPENCODE_CONFIG", str(config))+ config.write_bytes(b'{"theme":"live"}\n')+ legacy = config.with_suffix(".json.headroom-backup")+ original = b'// original\r\n{"theme":"original",}\r\n'+ legacy.write_bytes(original)+ canonical = config.with_name(config.name + ".headroom-backup")+ manifest = _manifest()++ mutation = apply_provider_scope(manifest)+ assert mutation is not None+ assert canonical.read_bytes() == original+ assert not legacy.exists()+ revert_provider_scope(mutation, manifest)+ assert config.read_bytes() == original+ assert not canonical.exists()