fix(install): preserve OpenCode edits during reactivation (#4022)

## Description

Reapply, restart, and automatic recovery temporarily remove the Headroom
provider before reactivating it. They must not restore the original
backup and erase user configuration added after installation. Final
removal must still restore the original snapshot.

Closes #4016.

## Type of Change

- [x] Bug fix
- [x] Documentation update

## Changes Made

- Separate transient provider deactivation from final backup
restoration, and propagate the intent through the existing install
registry/manifest lifecycle.
- During reactivation and activation rollback, remove only Headroom's
provider; retain unrelated providers, MCP settings, theme, and the
original backup.
- On true removal, restore and delete the original backup as before.
- Associate backups with the actual selected `opencode.json` or
`opencode.jsonc` filename, and pin edited writes to LF.
- Persist snapshot ownership independently of active mutations,
including activation persistence failures and stop/reload/final-remove.
- Migrate historical JSONC backup names (including custom config names)
before snapshotting/restoration in installer and wrapper callers; do not
claim a sibling JSON installation's backup.
- Accept JSONC comments/trailing commas without erasing user settings;
retain quoted URLs and delimiters.
- Restore the snapshot when a successful replacement drops OpenCode, but
retain it on replacement failure.
- Document preservation during reapply/restart/recovery and
original-snapshot behavior on final removal.

## Testing

- [x] Unit tests pass (`pytest`), including JSON/JSONC and all three
reactivation paths.
- [x] Changed-file lint, configured pre-commit mypy and manual
real-filesystem checks pass.

### Test Output

Real filesystem smoke output for both config suffixes:

```json
[{"final_removal_deletes_backup": true, "final_removal_restores_original": true, "headroom_reactivated": true, "original_backup_unchanged": true, "suffix": ".json", "theme": "edited-after-install", "user_mcp_preserved": true, "user_provider_preserved": true}, {"final_removal_deletes_backup": true, "final_removal_restores_original": true, "headroom_reactivated": true, "original_backup_unchanged": true, "suffix": ".jsonc", "theme": "edited-after-install", "user_mcp_preserved": true, "user_provider_preserved": true}]
```

The mandatory pre-push `make ci-precheck` passed: workspace Rust
fmt/clippy/tests, native extension build/import verification, the
complete configured Python gate, and Commitlint. The native gate
explicitly used the installed CPU `libonnxruntime.so.1.26.0` via
`ORT_DYLIB_PATH`, with cached-model assertions enabled.

```text
[build_rust_extension] headroom._core build + install + verify: OK
================== 177 passed, 4 skipped, 1 warning in 6.31s ===================
✅ ci-precheck PASSED — safe to push.
```

```sh
python -m pytest -q tests/test_providers_opencode_install.py tests/test_cli/test_install_cli.py tests/test_install/test_providers.py
```

Original lifecycle suite: **121 passed**. After the review corrections,
the combined provider/config/wrapper/install-CLI/recovery suite passed
**240 tests in 8.32s**:

```sh
python -m pytest -q tests/test_providers_opencode_install.py tests/test_providers_opencode_config.py tests/test_cli/test_wrap_opencode.py tests/test_cli/test_install_cli.py tests/test_install/test_providers.py tests/test_install_tool_env_reconcile.py
```

The regression suite checks real original bytes and persisted recovery
ownership, not mocked call order or incidental error wording. The
obsolete JSONC-trailing-comma rejection expectation was removed.

Changed-file Ruff, formatting, installed pre-commit `mypy headroom`, and
Commitlint hooks passed. Full-tree Ruff remains blocked locally by
executable permissions on five unchanged OAuth2 plugin files (tracked
100644). A separate full dev-environment mypy run found an unchanged
optional LangChain `truthy-function` error; the configured isolated
pre-commit hook passed. Unrelated code/permissions were not modified.

## Real Behavior Proof

- Environment: Linux x86_64, CPython 3.13.14; unchanged
`dea9092e19385f286b7f67a64f4d85de2708d756` and this branch, real
temporary config files and real installer mutation helpers, no mocked
file mutation or service installed on the workstation.
- Exact command / steps: for each suffix `.json` and `.jsonc`, write an
original theme/provider/MCP config; activate a provider-scoped OpenCode
manifest with `_activate_deployment_mutations`; edit the theme and add a
user provider plus remote MCP; call `_deactivate_deployment_mutations`
then `_activate_deployment_mutations`; inspect real files and the
original backup; finally invoke `revert_mutations(...,
restore_backup=True)`.
- Before: theme reset to `original`; added provider and MCP disappeared.
JSONC's actual-name backup was absent.
- Observed result: after the fix, theme remains `edited-after-install`;
both user additions survive; Headroom is active again; both actual-name
backups remain byte-identical to the original. Final removal restores
the original bytes and deletes the backup for both suffixes.
- Review correction proof against published head `4bc8e50c`: actual
temporary files and persisted manifests cover stop/reload/final-remove
for JSON and JSONC, legacy backup migration for default and custom
filenames, JSONC trailing commas and quoted `//`/`,}` text, successful
target removal, and activation-persistence failure followed by
reload/removal. All eight scenario outcomes pass after the correction;
the published baseline leaves or consumes the wrong snapshots and loses
JSONC edits. The actual `headroom unwrap opencode --no-stop-proxy`
command also restores the historical JSONC snapshot byte-for-byte and
consumes its backup. Only external process/service management and the
explicit persistence-fault boundary are substituted; config, manifest
and snapshot IO are real.
- Second review correction against `1c0855c4`: all four new findings
reproduced on real temporary config/backup files and persisted
manifests. After the fix, failed addition consumes its newly created
snapshot (a later install restores the later user edit); changed config
selection restores the recorded original path; an existing canonical
JSONC snapshot wins without deleting the ambiguous legacy backup; and
restoration failure retains ownership in the active replacement so a
retry after reload finishes restoration. Seven permanent boundary cases
initially gave **6 failures and 1 passing control**; the complete
affected suite now gives **247 passed**. OS supervisor calls and
explicit persistence/restoration faults are the only substituted
boundaries.
- Not tested: a real launchd/systemd supervisor or Windows process on
this Linux host. CLI regression tests exercise apply/restart/recovery
boundaries while replacing service management; the filesystem mutation
smoke uses real production helpers.

## Runtime Rollout Safety

- Rollout-managed feature(s): none; lifecycle data-preservation fix.
- Minimum rollout channel: stable; no rollout-managed feature is
enabled.
- Stable/default behavior changed: transient reactivation stops
reverting unrelated user edits. Final uninstall still restores the
original snapshot.
- Kill switch / disable path: remove the persistent OpenCode
installation using its existing removal flow; no new flag.
- Unsafe override required: no.
- Qualification impact: provider-scoped OpenCode configuration only;
other providers retain their existing removal semantics.
- Rollback path: revert the commits; no deployment manifest schema
change. Backup ownership uses the existing artifact record, and legacy
JSONC snapshots migrate to the selected config's canonical filename.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] Existing registry/lifecycle interfaces reused; persistent-install
docs updated.
- [x] Consumer-visible regressions cover edits, original-backup
invariants, both config suffixes, three reactivation paths, and final
removal.
- [x] `CHANGELOG.md` not edited; Conventional Commit title supplied.

Remote CI results are reported by GitHub, not assumed from local tests.

---------

Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
Mansurshakh Japarov
2026-10-07 17:46:39 -05:00
committed by GitHub
co-authored by JD Davis
parent 9553d4292f
commit 40955b0eef
11 changed files with 1105 additions and 275 deletions
+31
View File
@@ -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 selection
+124 -10
View File
@@ -9,6 +9,7 @@ import sys
from collections.abc import Mapping
from copy import deepcopy
from dataclasses import dataclass
from pathlib import Path
import click
from click.core import ParameterSource
@@ -16,6 +17,7 @@ from click.core import ParameterSource
from headroom._subprocess import run
from headroom.install.health import probe_json, probe_ready
from 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_path
from headroom.install.planner import build_manifest, build_tool_envs
from headroom.install.providers import apply_mutations, revert_mutations
from 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_backup
from .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 = False
active_persistence_failed = False
existing = 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 = True
raise
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 exc
raise 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 exc
if 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}. "
+2
View File
@@ -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:
+8 -3
View File
@@ -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)
+13 -4
View File
@@ -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[Managed
rollback_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[Managed
return 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)
+101 -13
View File
@@ -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's
original file byte-for-byte.
"""
migrate_legacy_opencode_jsonc_backup(config_file, backup_file)
if backup_file.exists():
return
if not config_file.exists():
@@ -123,23 +145,88 @@ def _render_provider_block(port: int) -> str:
return "\n".join(lines)
def _parse_json_loose(text: str) -> dict[str, Any]:
"""Parse JSON text, stripping line comments (// ...) when needed.
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)
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.
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 and JSONC comments/trailing commas.
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 = Fals
try:
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():
+39 -16
View File
@@ -13,6 +13,7 @@ from headroom.install.paths import opencode_config_path
from .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 | None
config_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()
Restores from pre-wrap backup when available, otherwise strips the
headroom provider from the config file.
def revert_provider_scope(
mutation: ManagedMutation,
manifest: DeploymentManifest,
*,
restore_backup: bool = True,
) -> None:
"""Undo OpenCode provider-scope configuration.
Final removal restores the pre-install snapshot when available. Temporary
deactivation removes only the managed provider and retains that snapshot.
"""
del manifest
if not mutation.path:
return
path = 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))
return
except OSError:
pass
if not path.exists():
return
content = 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")
return
cleaned = 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)
+107 -221
View File
@@ -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(monkeyp
monkeypatch.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(monkeypa
lambda 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_pat
host="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:
with pytest.raises(click.ClickException):
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:
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(monkeypatc
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",
@@ -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.output
assert applied == []
@pytest.mark.parametrize("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"}
+6 -3
View File
@@ -624,27 +624,30 @@ def test_unwrap_opencode_restores_from_backup(
assert config_file.read_text(encoding="utf-8") == original
@pytest.mark.parametrize(
"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.output
assert not backup_file.exists()
assert config_file.read_text(encoding="utf-8") == original
+26 -5
View File
@@ -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 second
assert second.count("headroom") == first.count("headroom")
@pytest.mark.parametrize("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() == original
+648
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import json
from pathlib import Path
import pytest
@@ -100,6 +101,67 @@ def test_revert_provider_scope_restores_file(
assert config_file.read_text().strip() == '{"model": "openai/gpt-4o"}'
@pytest.mark.parametrize("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
@pytest.mark.windows_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": {}}}
@pytest.mark.parametrize("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()
@pytest.mark.parametrize("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
@pytest.fixture
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
@pytest.mark.parametrize("legacy_manifest", [False, True])
@pytest.mark.parametrize("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()
@pytest.mark.parametrize(
("config_name", "location"),
[
("opencode.jsonc", "override"),
("custom-settings.jsonc", "override"),
("opencode.jsonc", "opencode_home"),
("opencode.jsonc", "default_home"),
],
)
@pytest.mark.parametrize("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
@pytest.mark.parametrize("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
@pytest.mark.parametrize("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()