feat: local drafter (pi against a self-run model server)
drafter: local runs the pi coding agent against the model resident on an OpenAI-compatible server at the new local_url input, keyed by the LOCAL_MODEL_API_KEY secret. It asks the server which model is loaded and names exactly that one, so it never evicts the resident model. An unreachable server or no loaded model posts the stage 1 flags with a note and exits 0; a drafter that ran and failed still exits 1. pi runs in the existing sandbox with read, ls, edit and write, every project-local pi file and AGENTS.md ignored, stdin from /dev/null, the task passed as an @file, and an allowlisted environment. As root with DOCS_REVIEW_DRAFTER_USER set, it runs as that unprivileged user, which owns only the sandbox and pi's temporary home. Both drafters now hash the checkout's .git/config and .git/hooks before drafting and stop with no further git command if either changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9dea56ce98
commit
28b993cb23
14 files changed
+1042
-30
No files matched your search
+75
-6
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -10,7 +11,7 @@ from collections.abc import Iterable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from docs_review import git, sandbox
|
||||
from docs_review import git, local, sandbox
|
||||
from docs_review.draft import DraftResult, claude_argv, parse_claude_output
|
||||
from docs_review.inputs import Inputs, expand_patterns, matches_any
|
||||
from docs_review.secrets import secret_values
|
||||
@@ -28,6 +29,8 @@ EXPORT_NOTE = "drafter failed: could not export the tree for drafting: {reason}"
|
||||
EXPORT_REASON_MAX = 200
|
||||
NO_CREDENTIAL_NOTE = "drafter: claude but no Claude credential is set"
|
||||
CREDENTIAL_VARS = ("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY")
|
||||
NO_LOCAL_KEY_NOTE = "drafter: local but LOCAL_MODEL_API_KEY is not set"
|
||||
GIT_METADATA_NOTE = "drafter changed git metadata; nothing committed"
|
||||
REFUSED_NOTE = "drafter failed: refusing to copy back `{path}` (symlink or outside the repository)"
|
||||
|
||||
|
||||
@@ -106,10 +109,17 @@ def write_step_summary(result: DraftResult, env: Mapping[str, str]) -> None:
|
||||
|
||||
|
||||
def run_drafter(inputs: Inputs, prompt: str, cwd: Path, env: Mapping[str, str],
|
||||
system_prompt_file: Path | None) -> DraftResult:
|
||||
"""Run the configured drafter in cwd. Task 12 adds `local`."""
|
||||
if inputs.drafter != "claude":
|
||||
return DraftResult(False, None, None, "", "local drafter not built yet")
|
||||
system_prompt_file: Path | None, *, local_model: str | None = None,
|
||||
run_as: tuple[int, int] | None = None) -> DraftResult:
|
||||
"""Run the configured drafter in cwd. `local` needs the resident model's id."""
|
||||
if inputs.drafter == "local":
|
||||
if local_model is None or inputs.local_url is None:
|
||||
return DraftResult(False, None, None, "", "no local model to draft with")
|
||||
result = local.run_local(
|
||||
prompt, base_url=inputs.local_url, key=env.get(local.KEY_VAR, ""),
|
||||
model=local_model, cwd=cwd, system_prompt_file=system_prompt_file, env=env,
|
||||
timeout=DRAFT_TIMEOUT_S, run_as=run_as)
|
||||
return dataclasses.replace(result, drafted_by=f"pi with {local_model}")
|
||||
argv = claude_argv(env.get("DOCS_REVIEW_CLAUDE_BIN", "claude"), inputs.model,
|
||||
str(system_prompt_file) if system_prompt_file else None)
|
||||
try:
|
||||
@@ -123,6 +133,36 @@ def run_drafter(inputs: Inputs, prompt: str, cwd: Path, env: Mapping[str, str],
|
||||
return parse_claude_output(proc.stdout, proc.returncode)
|
||||
|
||||
|
||||
def git_metadata(cwd: Path) -> dict[str, str]:
|
||||
"""Hashes of the checkout's .git/config and of everything under .git/hooks: the
|
||||
files that make a later git command run code. The drafter runs outside the
|
||||
checkout, but nothing else stops it writing here."""
|
||||
gitdir = cwd / ".git"
|
||||
if not gitdir.is_dir() or gitdir.is_symlink():
|
||||
return {".git": _entry(gitdir)}
|
||||
out = {"config": _entry(gitdir / "config")}
|
||||
hooks = gitdir / "hooks"
|
||||
out["hooks"] = _entry(hooks)
|
||||
if hooks.is_dir() and not hooks.is_symlink():
|
||||
for dirpath, dirnames, filenames in os.walk(hooks):
|
||||
for name in dirnames + filenames:
|
||||
path = Path(dirpath) / name
|
||||
out["hooks/" + path.relative_to(hooks).as_posix()] = _entry(path)
|
||||
return out
|
||||
|
||||
|
||||
def _entry(path: Path) -> str:
|
||||
"""A file's or link's hash, `dir` for a directory, `missing` when absent."""
|
||||
if path.is_symlink() or path.is_file():
|
||||
try:
|
||||
return sandbox.digest(path)
|
||||
except OSError as err:
|
||||
return f"unreadable:{err.errno}"
|
||||
if path.is_dir():
|
||||
return "dir"
|
||||
return "missing" if not os.path.lexists(path) else "other"
|
||||
|
||||
|
||||
def disallowed(change: sandbox.TreeChange, listed: frozenset[str],
|
||||
patterns: tuple[str, ...], root: Path,
|
||||
review_only: tuple[str, ...] = ()) -> list[str]:
|
||||
@@ -155,6 +195,22 @@ class Drafted:
|
||||
result: DraftResult | None
|
||||
changed: tuple[str, ...]
|
||||
note: str | None # why the run failed; None when it succeeded
|
||||
soft: bool = False # the drafter was unavailable: report the note, do not fail
|
||||
|
||||
|
||||
def _local_preflight(inputs: Inputs, env: Mapping[str, str]):
|
||||
"""For `local`: (model, run_as, None) or (None, None, Drafted) when it cannot run."""
|
||||
if not (env.get(local.KEY_VAR) or "").strip():
|
||||
return None, None, Drafted(None, (), NO_LOCAL_KEY_NOTE)
|
||||
try:
|
||||
run_as = local.drafter_user(env)
|
||||
except local.DrafterUserError as err:
|
||||
return None, None, Drafted(None, (), f"drafter failed: {err}")
|
||||
found = local.probe(inputs.local_url or "", env[local.KEY_VAR])
|
||||
if found.model is None:
|
||||
return None, None, Drafted(None, (), found.note, soft=found.soft)
|
||||
print(f"local drafter: resident model {found.model}")
|
||||
return found.model, run_as, None
|
||||
|
||||
|
||||
def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
|
||||
@@ -162,6 +218,11 @@ def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
|
||||
"""Run the drafter on an export of HEAD and copy its allowed changes into cwd."""
|
||||
if inputs.drafter == "claude" and not has_claude_credential(env):
|
||||
return Drafted(None, (), NO_CREDENTIAL_NOTE)
|
||||
model = run_as = None
|
||||
if inputs.drafter == "local":
|
||||
model, run_as, stop = _local_preflight(inputs, env)
|
||||
if stop is not None:
|
||||
return stop
|
||||
if git.run(["status", "--porcelain"], cwd).strip():
|
||||
return Drafted(None, (), DIRTY_NOTE)
|
||||
box = prompt_file = None
|
||||
@@ -175,7 +236,15 @@ def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
|
||||
listed = frozenset(expand_patterns(inputs.docs, box))
|
||||
before = sandbox.snapshot(box)
|
||||
prompt_file = write_system_prompt(box, inputs.doc_guide, env)
|
||||
result = run_drafter(inputs, prompt, box, env, prompt_file)
|
||||
if run_as is not None:
|
||||
local.chown_tree(box, run_as)
|
||||
metadata = git_metadata(cwd)
|
||||
result = run_drafter(inputs, prompt, box, env, prompt_file, local_model=model,
|
||||
run_as=run_as)
|
||||
# Checked first, and on failure no further git command runs: a hook or a
|
||||
# config change would run on the next one.
|
||||
if git_metadata(cwd) != metadata:
|
||||
return Drafted(result, (), GIT_METADATA_NOTE)
|
||||
write_step_summary(result, env)
|
||||
if not result.ok:
|
||||
return Drafted(result, (), f"drafter failed: {result.error}")
|
||||
|
||||
Reference in new issue
Block a user