fix(adopt): confine, gate and splice writes instead of overwriting blindly

apply_plan was the only path in the package that writes to disk and the only one
that skipped confined_path, so an absolute path in a hand-edited plan file
replaced the repository root outright (pathlib join semantics) and wrote
anywhere. It also treated patch-managed-block as a full-file write, meaning the
first plan to emit that action would have destroyed the target CLAUDE.md rather
than patching it -- two bugs that only stayed harmless because build_plan never
emitted the action. Learned that forbiddenChanges and the plan's own
"path-confinement" validation entry were decorative: nothing ever checked them.

- confine every change path via the existing confined_path helper
- implement real managed-block splicing between markers; refuse malformed or
  duplicated markers rather than guessing
- enforce forbiddenChanges at apply time
- re-check the worktree at apply time and refuse only when a dirty path is one
  the plan writes, leaving unrelated user edits alone
- restore rollback by what was on disk, not by what we think we finished
- add gitutil.dirty_paths/ignored; is_dirty threw the path list away
- replace the CLI's guess-the-code-from-the-message mapping with AdoptionError

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Alexander Baranov
2026-08-24 18:25:45 +03:00
co-authored by Claude Opus 5
parent 36d5d01d43
commit c918bd8373
3 changed files with 179 additions and 17 deletions
+122 -14
View File
@@ -16,8 +16,67 @@ from typing import Any
from . import gitutil, io
from .bootstrap import BootstrapAnswers, render_agents_md, render_claude_md
from .constants import API_VERSION
from .paths import PathViolation, confined_path
from .validate import validate_repository
MANAGED_BLOCK_START = "<!-- stewardship:managed:start -->"
MANAGED_BLOCK_END = "<!-- stewardship:managed:end -->"
class AdoptionError(ValueError):
"""An adoption step refused to proceed, carrying a stable finding code.
Subclasses ``ValueError`` so existing callers that catch ``ValueError`` keep
working, while ``code`` lets the CLI report the precise reason instead of
guessing one from the message text.
"""
def __init__(self, code: str, message: str) -> None:
super().__init__(f"{code}: {message}")
self.code = code
def render_managed_block(body: str) -> str:
"""Wrap ``body`` in the stewardship managed-block markers."""
return f"{MANAGED_BLOCK_START}\n{body.strip()}\n{MANAGED_BLOCK_END}\n"
def splice_managed_block(text: str, block: str) -> str:
"""Insert or replace the managed block inside ``text``, leaving the rest intact.
Adoption must never rewrite a shared agent entrypoint wholesale (runbook
section 3 and 11.2), so this only ever touches the marked region. When no
markers are present the block is inserted just below the first level-1
heading, keeping the stewardship pointer above the document body where an
agent reads it first. Malformed or duplicated markers raise rather than
guess at the author's intent.
"""
start_count = text.count(MANAGED_BLOCK_START)
end_count = text.count(MANAGED_BLOCK_END)
if start_count > 1 or end_count > 1:
raise AdoptionError("ADOPT_MANAGED_BLOCK_MALFORMED", "Duplicate managed-block markers")
if bool(start_count) != bool(end_count):
raise AdoptionError("ADOPT_MANAGED_BLOCK_MALFORMED", "Unpaired managed-block marker")
normalized = block if block.endswith("\n") else block + "\n"
if start_count == 1:
start = text.index(MANAGED_BLOCK_START)
end = text.index(MANAGED_BLOCK_END) + len(MANAGED_BLOCK_END)
if end < start:
raise AdoptionError("ADOPT_MANAGED_BLOCK_MALFORMED", "End marker precedes start marker")
tail = text[end:].removeprefix("\n")
return text[:start] + normalized + tail
lines = text.splitlines(keepends=True)
for position, line in enumerate(lines):
if line.startswith("# "):
insert_at = position + 1
if insert_at < len(lines) and not lines[insert_at].strip():
insert_at += 1
return "".join(lines[:insert_at]) + "\n" + normalized + "".join(lines[insert_at:])
return normalized + "\n" + text
_COLLISION_PATHS = [
"ops/contract.yaml",
"kdb/kdb.yaml",
@@ -326,36 +385,85 @@ def _knowledge_entrypoint(assessment: dict[str, Any]) -> str:
return "kdb/kdb.yaml"
def is_forbidden(rel_path: str, forbidden: list[str]) -> bool:
"""True when ``rel_path`` is covered by any ``forbiddenChanges`` pattern."""
return any(fnmatch.fnmatch(rel_path, pattern) for pattern in forbidden)
def _resolve_change_target(root: Path, rel_path: str) -> Path:
"""Confine a plan-supplied path to the repository before it is ever written.
A plan is an ordinary file that can be edited or moved between machines, and
``root / rel_path`` silently discards ``root`` when ``rel_path`` is absolute,
so this is the boundary that keeps `apply` from writing outside the repo.
"""
try:
return confined_path(root, rel_path)
except PathViolation as exc:
raise AdoptionError("ADOPT_PATH_OUTSIDE_REPOSITORY", f"{rel_path}: {exc}") from exc
def apply_plan(root: Path, plan: dict[str, Any], approve_hash: str) -> list[str]:
expected_hash = io.sha256({k: v for k, v in plan.items() if k != "planHash"})
if expected_hash != plan.get("planHash"):
raise ValueError("Plan hash does not match plan content; re-plan before apply")
raise AdoptionError("APPROVAL_FAILED", "Plan hash does not match plan content; re-plan before apply")
if approve_hash != plan["planHash"]:
raise ValueError("Approval hash does not match plan hash")
raise AdoptionError("APPROVAL_FAILED", "Approval hash does not match plan hash")
current_head = gitutil.head_revision(root)
if current_head != plan["baselineRevision"]:
raise ValueError("ADOPT_BASELINE_CHANGED: baseline revision changed since plan was built; re-plan")
raise AdoptionError(
"ADOPT_BASELINE_CHANGED", "Baseline revision changed since plan was built; re-plan"
)
forbidden = list(plan.get("forbiddenChanges", []))
to_write = [c for c in plan["changes"] if c["action"] in ("create", "patch-managed-block")]
for change in to_write:
target = root / change["path"]
if change["action"] == "create" and target.exists():
raise FileExistsError(f"ADOPT_PATH_COLLISION: refusing to overwrite existing path: {change['path']}")
written: list[str] = []
targets: dict[str, Path] = {}
for change in to_write:
rel = change["path"]
target = _resolve_change_target(root, rel)
if is_forbidden(rel, forbidden):
raise AdoptionError("ADOPT_FORBIDDEN_PATH", f"Plan writes into a forbidden path: {rel}")
if change["action"] == "create" and target.exists():
raise AdoptionError("ADOPT_PATH_COLLISION", f"Refusing to overwrite existing path: {rel}")
if change["action"] == "patch-managed-block" and not target.exists():
raise AdoptionError(
"ADOPT_PATH_COLLISION", f"Cannot patch a managed block into a missing file: {rel}"
)
targets[rel] = target
# Re-check the worktree immediately before writing rather than trusting the
# `assess` that preceded it: a dirty path unrelated to the plan is the user's
# business, but overwriting a file they have uncommitted edits in is not.
contested = gitutil.dirty_paths(root) & set(targets)
if contested:
raise AdoptionError(
"ADOPT_WORKTREE_DIRTY",
"Uncommitted changes in paths this plan writes: " + ", ".join(sorted(contested)),
)
backups: dict[str, bytes | None] = {}
written: list[str] = []
try:
for change in to_write:
target = root / change["path"]
backups[change["path"]] = target.read_bytes() if target.exists() else None
io.write_text_atomic(target, change["content"])
written.append(change["path"])
rel = change["path"]
target = targets[rel]
backups[rel] = target.read_bytes() if target.exists() else None
if change["action"] == "patch-managed-block":
current = target.read_text(encoding="utf-8")
content = splice_managed_block(current, change["content"])
else:
content = change["content"]
io.write_text_atomic(target, content)
written.append(rel)
except Exception:
# Restore by what was on disk before, not by what we believe we finished:
# a write that failed part-way still leaves a file that never existed.
for rel, original in backups.items():
target = root / rel
target = targets[rel]
if original is None:
if target.exists() and rel in written:
if target.exists():
target.unlink()
else:
target.write_bytes(original)
+5 -3
View File
@@ -232,10 +232,12 @@ def cmd_adopt(args: argparse.Namespace) -> int:
plan = _load_plan(Path(args.plan))
try:
written = adoption.apply_plan(repo_path, plan, args.approve)
except adoption.AdoptionError as exc:
_write(build_envelope("adopt apply", "failure", None, [Finding("error", exc.code, str(exc))]), args.output)
return EXIT_APPROVAL if exc.code == "APPROVAL_FAILED" else EXIT_VALIDATION_FAILURE
except ValueError as exc:
code = "APPROVAL_FAILED" if "Approval" in str(exc) or "hash" in str(exc) else "ADOPT_BASELINE_CHANGED"
_write(build_envelope("adopt apply", "failure", None, [Finding("error", code, str(exc))]), args.output)
return EXIT_APPROVAL
_write(build_envelope("adopt apply", "failure", None, [Finding("error", "ADOPT_VALIDATION_FAILED", str(exc))]), args.output)
return EXIT_VALIDATION_FAILURE
except FileExistsError as exc:
_write(build_envelope("adopt apply", "failure", None, [Finding("error", "ADOPT_PATH_COLLISION", str(exc))]), args.output)
return EXIT_VALIDATION_FAILURE
+52
View File
@@ -33,3 +33,55 @@ def tracked_files(root: Path) -> set[str]:
if result.returncode != 0:
return set()
return {line.strip() for line in result.stdout.splitlines() if line.strip()}
def dirty_paths(root: Path) -> set[str]:
"""Return every repository-relative path with staged, unstaged or untracked changes.
`is_dirty` collapses this to a bool; adoption needs the paths themselves so
`apply` can refuse to write into a file the user is already editing. Uses ``-z``
so paths containing spaces or non-ASCII are neither quoted nor mangled, and so
rename entries split reliably: a rename emits the destination path, then a
second NUL-terminated field holding the original path.
"""
result = _run(["status", "--porcelain", "-z"], root)
if result.returncode != 0:
return set()
fields = [field for field in result.stdout.split("\0") if field]
paths: set[str] = set()
index = 0
while index < len(fields):
entry = fields[index]
index += 1
if len(entry) < 4:
continue
status, path = entry[:2], entry[3:]
paths.add(path)
if ("R" in status or "C" in status) and index < len(fields):
paths.add(fields[index])
index += 1
return paths
def ignored(root: Path, relative_paths: list[str]) -> set[str]:
"""Return the subset of ``relative_paths`` that Git ignores.
Used to keep the secret-shaped scan quiet about gitignored material and to
avoid walking large ignored trees. Returns an empty set when Git is
unavailable, so callers degrade to reporting everything rather than nothing.
"""
if not relative_paths:
return set()
# `check-ignore` needs the candidates on stdin; `_run` does not pipe input,
# so issue the call directly here rather than widening the shared helper.
result = subprocess.run(
["git", "check-ignore", "-z", "--stdin"],
cwd=root,
input="\0".join(relative_paths),
capture_output=True,
text=True,
check=False,
)
if result.returncode not in (0, 1):
return set()
return {field for field in result.stdout.split("\0") if field}