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:
co-authored by
Claude Opus 5
parent
36d5d01d43
commit
c918bd8373
+122
-14
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user