|
| 1 | +"""Backup witnesses describe archived bytes, never a later source reread.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import hashlib |
| 5 | +import json |
| 6 | +import os |
| 7 | +from pathlib import Path |
| 8 | +import subprocess |
| 9 | +import sqlite3 |
| 10 | +import sys |
| 11 | +import tarfile |
| 12 | + |
| 13 | +import pytest |
| 14 | + |
| 15 | +from loopx.state_backup import build_state_backup_plan, execute_state_backup_plan |
| 16 | + |
| 17 | + |
| 18 | +def fixture(root: Path): |
| 19 | + project, runtime = root / "project", root / "runtime" |
| 20 | + state = project / ".codex/goals/example/ACTIVE_GOAL_STATE.md" |
| 21 | + state.parent.mkdir(parents=True) |
| 22 | + state.write_bytes(b"## Agent Todo\n- [ ] Current work\n## Agent Todo Archive\n" |
| 23 | + b"- [x] Unreferenced history\n <!-- future_metadata=null -->\n") |
| 24 | + registry = project / ".loopx/registry.json" |
| 25 | + registry.parent.mkdir(parents=True) |
| 26 | + registry.write_text(json.dumps({"common_runtime_root": str(runtime), "goals": [ |
| 27 | + {"id": "example", "repo": str(project), "state_file": str(state), |
| 28 | + "future_configuration": {"disabled": False, "unset": None}}]})) |
| 29 | + historical = runtime / "goals/example/task-leases/retained.json" |
| 30 | + historical.parent.mkdir(parents=True) |
| 31 | + historical.write_bytes(b'{"status":"released","future":{"null":null,"flag":false}}\n') |
| 32 | + receipt = runtime / "goals/example/receipts/original.json" |
| 33 | + receipt.parent.mkdir(parents=True) |
| 34 | + receipt.write_bytes(b'{"operation_id":"original","unknown":[false,null]}\n') |
| 35 | + (runtime / "receipt-link").symlink_to("goals/example/receipts/original.json") |
| 36 | + os.link(receipt, runtime / "receipt-hardlink") |
| 37 | + return project, runtime, state, registry |
| 38 | + |
| 39 | + |
| 40 | +def plan(root: Path): |
| 41 | + project, runtime, state, registry = fixture(root) |
| 42 | + return build_state_backup_plan(project=project, runtime_root=runtime, |
| 43 | + output_dir=root / "backups", backup_id="fixture", include_automations=False, |
| 44 | + include_skills=False, include_registry_projects=False, registry_path=registry), state |
| 45 | + |
| 46 | + |
| 47 | +def assert_members(payload): |
| 48 | + members = payload["execution"]["file_members"] |
| 49 | + by_path = {row["archive_path"]: row for row in members} |
| 50 | + assert len(by_path) == len(members) |
| 51 | + with tarfile.open(payload["archive_path"]) as archive: |
| 52 | + expected = {row.name for row in archive if row.isfile() and row.name != "manifest.json"} |
| 53 | + assert set(by_path) == expected |
| 54 | + for path, row in by_path.items(): |
| 55 | + data = archive.extractfile(path).read() |
| 56 | + assert row == {"archive_path": path, "size_bytes": len(data), |
| 57 | + "sha256": hashlib.sha256(data).hexdigest()} |
| 58 | + internal = json.load(archive.extractfile("manifest.json")) |
| 59 | + assert internal["execution"]["file_members"] == members |
| 60 | + external = json.loads(Path(payload["manifest_path"]).read_text()) |
| 61 | + assert external["execution"]["file_members"] == members |
| 62 | + |
| 63 | + |
| 64 | +@pytest.mark.parametrize("with_sqlite", [False, True]) |
| 65 | +def test_real_cli_inventory_binds_raw_history_and_generated_configuration(tmp_path, with_sqlite): |
| 66 | + project, runtime, state, registry = fixture(tmp_path) |
| 67 | + original = state.read_bytes() |
| 68 | + if with_sqlite: |
| 69 | + with sqlite3.connect(runtime / "retained.data") as database: |
| 70 | + database.execute("CREATE TABLE receipts(value TEXT)") |
| 71 | + database.execute("INSERT INTO receipts VALUES(?)", ('{"future":[false,null]}',)) |
| 72 | + result = subprocess.run([sys.executable, "-I", "-m", "loopx.cli", "--registry", str(registry), |
| 73 | + "--runtime-root", str(runtime), "--format", "json", "backup-state", "--project", str(project), |
| 74 | + "--output-dir", str(tmp_path / "backups"), "--current-project-only", "--no-automations", |
| 75 | + "--no-skills", "--execute"], env={**os.environ, "LOOPX_USAGE_PING": "0"}, |
| 76 | + capture_output=True, text=True, check=True) |
| 77 | + payload = json.loads(result.stdout) |
| 78 | + assert payload["ok"] is True |
| 79 | + assert_members(payload) |
| 80 | + restored = tmp_path / "restored" |
| 81 | + with tarfile.open(payload["archive_path"]) as archive: |
| 82 | + archive.extractall(restored, filter="data") |
| 83 | + assert (restored / "project/.codex/goals/example/ACTIVE_GOAL_STATE.md").read_bytes() == original |
| 84 | + assert (restored / "runtime-root/receipt-link").is_symlink() |
| 85 | + assert (restored / "runtime-root/receipt-hardlink").read_bytes() == ( |
| 86 | + runtime / "goals/example/receipts/original.json").read_bytes() |
| 87 | + if with_sqlite: |
| 88 | + with sqlite3.connect(restored / "runtime-root/retained.data") as database: |
| 89 | + assert database.execute("PRAGMA integrity_check").fetchone()[0] == "ok" |
| 90 | + assert database.execute("SELECT value FROM receipts").fetchone()[0] == '{"future":[false,null]}' |
| 91 | + assert state.read_bytes() == original |
| 92 | + |
| 93 | + |
| 94 | +def test_member_digest_uses_the_copied_stream_not_a_later_source_reread(tmp_path, monkeypatch): |
| 95 | + payload, state = plan(tmp_path) |
| 96 | + original = state.read_bytes() |
| 97 | + addfile = tarfile.TarFile.addfile |
| 98 | + |
| 99 | + def change_after_copy(archive, info, fileobj=None): |
| 100 | + result = addfile(archive, info, fileobj) |
| 101 | + if info.name == "project/.codex/goals/example/ACTIVE_GOAL_STATE.md": |
| 102 | + state.write_bytes(b"later source contents\n") |
| 103 | + return result |
| 104 | + |
| 105 | + monkeypatch.setattr(tarfile.TarFile, "addfile", change_after_copy) |
| 106 | + completed = execute_state_backup_plan(payload) |
| 107 | + assert_members(completed) |
| 108 | + row = next(row for row in completed["execution"]["file_members"] |
| 109 | + if row["archive_path"] == "project/.codex/goals/example/ACTIVE_GOAL_STATE.md") |
| 110 | + assert row["sha256"] == hashlib.sha256(original).hexdigest() |
| 111 | + assert row["sha256"] != hashlib.sha256(state.read_bytes()).hexdigest() |
| 112 | + |
| 113 | + |
| 114 | +def test_short_source_read_cannot_publish_partial_inventory_or_replace_backup(tmp_path, monkeypatch): |
| 115 | + payload, state = plan(tmp_path) |
| 116 | + output = Path(payload["output_dir"]) |
| 117 | + output.mkdir() |
| 118 | + archive, manifest = Path(payload["archive_path"]), Path(payload["manifest_path"]) |
| 119 | + archive.write_bytes(b"previous archive") |
| 120 | + manifest.write_bytes(b"previous manifest") |
| 121 | + addfile = tarfile.TarFile.addfile |
| 122 | + |
| 123 | + def truncate_before_copy(archive, info, fileobj=None): |
| 124 | + if info.name == "project/.codex/goals/example/ACTIVE_GOAL_STATE.md": |
| 125 | + state.write_bytes(b"") |
| 126 | + return addfile(archive, info, fileobj) |
| 127 | + |
| 128 | + monkeypatch.setattr(tarfile.TarFile, "addfile", truncate_before_copy) |
| 129 | + with pytest.raises(OSError, match="unexpected end of data"): |
| 130 | + execute_state_backup_plan(payload) |
| 131 | + assert archive.read_bytes() == b"previous archive" |
| 132 | + assert manifest.read_bytes() == b"previous manifest" |
| 133 | + assert sorted(path.name for path in output.iterdir()) == sorted([archive.name, manifest.name]) |
0 commit comments