Coverage for src/governed_harness/orchestration/workspace_ops.py: 91%
73 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1"""Restore and materialize workspace states for the agent-results settings.
3* ``restore_changes`` undoes the changes between a recorded state and the workspace (a
4 read-only agent call that wrote, a quarantined attempt under ``governance.stopTheLine``).
5* ``materialized`` builds a temporary copy of the workspace in which the changed paths have the
6 content of a recorded state, so a validator can run on the baseline (differential
7 verification) or on the state before a correction (reproduce-first) without touching the
8 workspace itself. Large dependency directories are linked, not copied.
10The recorded content comes from a ``Contents`` callback, so the same code serves a snapshot with
11the text of every file (1.0.0 baselines, in-memory snapshots) and a manifest baseline whose
12content Git gives back (``workspace.baseline: manifest``). A file whose recorded content cannot be
13given back is reported, never guessed."""
15from __future__ import annotations
17import contextlib
18import shutil
19import tempfile
20from collections.abc import Callable, Iterator
21from dataclasses import dataclass
22from pathlib import Path
24from governed_harness.capabilities.authorizer import contained_path
25from governed_harness.runtime.workspace import (
26 WorkspaceDiff,
27 WorkspaceSnapshot,
28 WorkspaceSnapshotter,
29 recorded_bytes,
30)
32LINKED_DIRECTORIES = frozenset({".venv", "venv", "node_modules"})
33"""Top-level directories linked into a materialized copy instead of copied (dependencies)."""
34SKIPPED_DIRECTORIES = frozenset(
35 {".harness", ".git", "__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache"}
36)
39@dataclass(frozen=True)
40class Contents:
41 """The recorded state of a path: whether it existed and its bytes (``None`` when they
42 cannot be given back)."""
44 existed: Callable[[str], bool]
45 content: Callable[[str], bytes | None]
48def snapshot_contents(snapshot: WorkspaceSnapshot) -> Contents:
49 """The contents of a snapshot that holds the text of its files; a text that is not the
50 recorded content of its file (read back from a redacted artifact, #178) cannot be given
51 back."""
53 def content(path: str) -> bytes | None:
54 state = snapshot.files.get(path)
55 return recorded_bytes(state) if state else None
57 return Contents(lambda path: path in snapshot.files, content)
60def restore_changes(
61 workspace: Path, recorded: Contents, diff: WorkspaceDiff
62) -> tuple[list[str], list[str]]:
63 """Write back the recorded content of every path in ``diff`` (delete what was added).
64 Returns the restored paths and the ones that could not be restored."""
65 restored: list[str] = []
66 unrestorable: list[str] = []
67 for change in diff.changes:
68 target = contained_path(workspace, Path(change.path))
69 if not recorded.existed(change.path):
70 target.unlink(missing_ok=True)
71 restored.append(change.path)
72 continue
73 data = recorded.content(change.path)
74 if data is None: 74 ↛ 75line 74 didn't jump to line 75 because the condition on line 74 was never true
75 unrestorable.append(change.path)
76 continue
77 target.parent.mkdir(parents=True, exist_ok=True)
78 target.write_bytes(data)
79 restored.append(change.path)
80 return restored, unrestorable
83def changes_since(workspace: Path, before: WorkspaceSnapshot) -> WorkspaceDiff:
84 """Changes between an in-memory snapshot (with texts) and the workspace."""
85 snapshotter = WorkspaceSnapshotter(workspace)
86 return snapshotter.diff(before, snapshotter.snapshot())
89def _ignore(root: Path) -> Callable[[str, list[str]], set[str]]:
90 def ignore(directory: str, names: list[str]) -> set[str]:
91 skipped = {name for name in names if name in SKIPPED_DIRECTORIES}
92 if Path(directory).resolve() == root:
93 skipped |= {name for name in names if name in LINKED_DIRECTORIES}
94 return skipped
96 return ignore
99@contextlib.contextmanager
100def materialized(
101 workspace: Path, scratch: Path, recorded: Contents, paths: list[str]
102) -> Iterator[Path | None]:
103 """A temporary copy of ``workspace`` where each of ``paths`` has its recorded content (or
104 is absent when it did not exist). Yields ``None`` when a path cannot be reverted. The copy
105 is removed on exit."""
106 root = workspace.resolve(strict=True)
107 scratch.mkdir(parents=True, exist_ok=True, mode=0o700)
108 target_root = Path(tempfile.mkdtemp(prefix="state-", dir=scratch))
109 try:
110 copy = target_root / "ws"
111 shutil.copytree(root, copy, symlinks=True, ignore=_ignore(root))
112 for name in sorted(LINKED_DIRECTORIES):
113 source = root / name
114 if source.is_dir(): 114 ↛ 115line 114 didn't jump to line 115 because the condition on line 114 was never true
115 (copy / name).symlink_to(source, target_is_directory=True)
116 for path in paths:
117 target = contained_path(copy, Path(path))
118 if not recorded.existed(path):
119 target.unlink(missing_ok=True)
120 continue
121 data = recorded.content(path)
122 if data is None: 122 ↛ 123line 122 didn't jump to line 123 because the condition on line 122 was never true
123 yield None
124 return
125 target.parent.mkdir(parents=True, exist_ok=True)
126 target.write_bytes(data)
127 yield copy
128 finally:
129 shutil.rmtree(target_root, ignore_errors=True)