feat: local drafter (pi against an OpenAI-compatible server on your own hardware)
tests / unittest (push) Failing after 28s
tests / unittest (push) Failing after 28s
drafter: local runs the pi agent against the model already loaded on a self-hosted server, as an unprivileged user, in the same sandbox as the Claude drafter. It fails soft when the server is unreachable or has no model loaded. Both drafters now refuse to continue if git metadata changed during drafting, and strip project pi configuration from the sandbox. Tested live against a self-hosted server: one run, 12 turns, docs PR opened. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9dea56ce98
commit
1ef68f12fb
14 files changed
+1303
-42
No files matched your search
+90
-9
@@ -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)"
|
||||
|
||||
|
||||
@@ -85,13 +88,19 @@ def has_claude_credential(env: Mapping[str, str]) -> bool:
|
||||
|
||||
|
||||
def write_step_summary(result: DraftResult, env: Mapping[str, str]) -> None:
|
||||
"""Print the run's cost and turns, whichever Claude reported, and append them to
|
||||
$GITHUB_STEP_SUMMARY when the runner sets it."""
|
||||
"""Print the run's cost, turns and tokens, whichever the drafter reported, and
|
||||
append them to $GITHUB_STEP_SUMMARY when the runner sets it."""
|
||||
lines = []
|
||||
if result.drafted_by is not None:
|
||||
lines.append(f"- drafted_by: {result.drafted_by}")
|
||||
if result.cost_usd is not None:
|
||||
lines.append(f"- total_cost_usd: {result.cost_usd:.2f}")
|
||||
if result.turns is not None:
|
||||
lines.append(f"- num_turns: {result.turns}")
|
||||
if result.output_tokens is not None:
|
||||
lines.append(f"- output_tokens: {result.output_tokens}")
|
||||
if result.input_tokens is not None:
|
||||
lines.append(f"- max_input_tokens: {result.input_tokens}")
|
||||
if not lines:
|
||||
return
|
||||
print("drafter " + ", ".join(l[2:] for l in lines))
|
||||
@@ -106,10 +115,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,21 +139,56 @@ 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]:
|
||||
"""Changed paths the drafter may not touch. A listed document may change or go; a
|
||||
new file must match a docs pattern; anything written must be a regular file. Nothing
|
||||
matching a review_only pattern may change, appear or go."""
|
||||
matching a review_only pattern may change, appear or go, and nothing may recreate
|
||||
the pi configuration removed before drafting."""
|
||||
bad = []
|
||||
for p in change.paths:
|
||||
ok = p in listed or (p in change.new and matches_any(p, patterns))
|
||||
if ok and sandbox.is_pi_config(p):
|
||||
ok = False
|
||||
if ok and matches_any(p, review_only):
|
||||
ok = False
|
||||
if ok and p not in change.deleted and not sandbox.is_regular(root, p):
|
||||
ok = False
|
||||
if not ok:
|
||||
bad.append(p)
|
||||
bad += [name + "/" for name in sandbox.pi_config_entries(root)
|
||||
if (root / name).is_dir() and not any(p.startswith(name + "/") for p in bad)]
|
||||
return bad
|
||||
|
||||
|
||||
@@ -155,6 +206,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 +229,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
|
||||
@@ -172,11 +244,20 @@ def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
|
||||
except (git.GitError, subprocess.TimeoutExpired, OSError) as err:
|
||||
return Drafted(None, (), EXPORT_NOTE.format(reason=_short_reason(err)))
|
||||
sandbox.remove_symlinks(box)
|
||||
sandbox.remove_pi_config(box)
|
||||
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)
|
||||
write_step_summary(result, env)
|
||||
# Checked before anything else, 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)
|
||||
if not result.ok:
|
||||
return Drafted(result, (), f"drafter failed: {result.error}")
|
||||
change = sandbox.compare(before, sandbox.snapshot(box))
|
||||
|
||||
Reference in new issue
Block a user