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>
182 lines
6.4 KiB
Python
182 lines
6.4 KiB
Python
"""Read the workflow's INPUT_* environment into an Inputs record."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import urllib.parse
|
|
from collections.abc import Iterable, Mapping
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
DRAFTERS = ("claude", "local", "none")
|
|
DEFAULT_MODEL = "claude-sonnet-5-5"
|
|
DEFAULT_WORKSTREAM = "docs"
|
|
DEFAULT_SOURCE_DIRS = ("R", "scripts")
|
|
DEFAULT_TOP_LEVEL = ("README.md",)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Inputs:
|
|
drafter: str
|
|
docs: tuple[str, ...]
|
|
generated: tuple[str, ...]
|
|
top_level: tuple[str, ...]
|
|
source_dirs: tuple[str, ...]
|
|
workstream: str
|
|
tracking_issue: int | None
|
|
doc_guide: str | None
|
|
model: str
|
|
# Listed documents the drafter may read but not edit; each entry is within docs.
|
|
review_only: tuple[str, ...] = ()
|
|
# The local drafter's OpenAI-compatible base URL; set only when drafter is local.
|
|
local_url: str | None = None
|
|
|
|
|
|
def normalize_drafter(raw: str | None) -> str:
|
|
"""Return claude, local or none; anything else, including missing, is none."""
|
|
value = (raw or "").strip().lower()
|
|
return value if value in DRAFTERS else "none"
|
|
|
|
|
|
def parse_local_url(raw: str | None) -> str:
|
|
"""The local_url input without a trailing slash. Raises ValueError unless it is an
|
|
http(s) URL with a host."""
|
|
url = (raw or "").strip().rstrip("/")
|
|
if not url:
|
|
raise ValueError("input 'local_url' is required when drafter is local")
|
|
parts = urllib.parse.urlsplit(url)
|
|
if parts.scheme not in ("http", "https") or not parts.hostname:
|
|
raise ValueError(f"input 'local_url' must be an http or https URL, got {url!r}")
|
|
return url
|
|
|
|
|
|
def _lines(raw: str | None) -> tuple[str, ...]:
|
|
"""Split a newline-separated input, trimming and dropping blank lines."""
|
|
return tuple(line.strip() for line in (raw or "").splitlines() if line.strip())
|
|
|
|
|
|
def _text(env: Mapping[str, str], key: str) -> str:
|
|
return (env.get(key) or "").strip()
|
|
|
|
|
|
def parse_inputs(env: Mapping[str, str]) -> Inputs:
|
|
"""Build Inputs from env. Raises ValueError when docs is missing or blank."""
|
|
docs = _lines(env.get("INPUT_DOCS"))
|
|
if not docs:
|
|
raise ValueError("input 'docs' is required: list at least one document pattern")
|
|
|
|
review_only = _lines(env.get("INPUT_REVIEW_ONLY"))
|
|
for entry in review_only:
|
|
if not matches_any(entry, docs):
|
|
raise ValueError(
|
|
f"input 'review_only' entry {entry!r} matches no 'docs' pattern; "
|
|
"every review_only entry must also be a listed document"
|
|
)
|
|
|
|
issue_raw = _text(env, "INPUT_TRACKING_ISSUE")
|
|
try:
|
|
tracking_issue = int(issue_raw) if issue_raw else None
|
|
except ValueError:
|
|
raise ValueError(f"input 'tracking_issue' must be an integer, got {issue_raw!r}") from None
|
|
|
|
drafter = normalize_drafter(env.get("INPUT_DRAFTER"))
|
|
local_url = parse_local_url(env.get("INPUT_LOCAL_URL")) if drafter == "local" else None
|
|
|
|
return Inputs(
|
|
drafter=drafter,
|
|
docs=docs,
|
|
generated=_lines(env.get("INPUT_GENERATED")),
|
|
top_level=_lines(env.get("INPUT_TOP_LEVEL")) or DEFAULT_TOP_LEVEL,
|
|
source_dirs=_lines(env.get("INPUT_SOURCE_DIRS")) or DEFAULT_SOURCE_DIRS,
|
|
workstream=_text(env, "INPUT_WORKSTREAM") or DEFAULT_WORKSTREAM,
|
|
tracking_issue=tracking_issue,
|
|
doc_guide=_text(env, "INPUT_DOC_GUIDE") or None,
|
|
model=_text(env, "INPUT_MODEL") or DEFAULT_MODEL,
|
|
review_only=review_only,
|
|
local_url=local_url,
|
|
)
|
|
|
|
|
|
def split_review_only(
|
|
paths: tuple[str, ...], review_only: tuple[str, ...]
|
|
) -> tuple[tuple[str, ...], tuple[str, ...]]:
|
|
"""The listed documents split into (editable, review-only), each in the given order."""
|
|
read_only = tuple(p for p in paths if matches_any(p, review_only))
|
|
return tuple(p for p in paths if p not in read_only), read_only
|
|
|
|
|
|
def _glob_files(pattern: str, repo_root: Path) -> list[str]:
|
|
"""Repository-relative POSIX paths of files matching one pattern."""
|
|
return [
|
|
p.relative_to(repo_root).as_posix()
|
|
for p in repo_root.glob(pattern)
|
|
if p.is_file()
|
|
]
|
|
|
|
|
|
def expand_patterns(patterns: Iterable[str], repo_root: Path) -> tuple[str, ...]:
|
|
"""Files matching the patterns: repository-relative, sorted, de-duplicated."""
|
|
found: set[str] = set()
|
|
for pattern in patterns:
|
|
found.update(_glob_files(pattern, repo_root))
|
|
return tuple(sorted(found))
|
|
|
|
|
|
def unmatched_patterns(patterns: Iterable[str], repo_root: Path) -> tuple[str, ...]:
|
|
"""Patterns that match no file, in the order given."""
|
|
return tuple(p for p in patterns if not _glob_files(p, repo_root))
|
|
|
|
|
|
def _class(pattern: str, i: int) -> tuple[str, int] | None:
|
|
"""Translate the [...] class starting at pattern[i]; None when it never closes.
|
|
The class never matches /, so it stays inside one path segment."""
|
|
j = i + 1
|
|
negate = j < len(pattern) and pattern[j] == "!"
|
|
if negate:
|
|
j += 1
|
|
start = j
|
|
if j < len(pattern) and pattern[j] == "]":
|
|
j += 1 # a ] first in the class is literal
|
|
while j < len(pattern) and pattern[j] != "]":
|
|
j += 1
|
|
if j >= len(pattern):
|
|
return None
|
|
body = pattern[start:j].replace("\\", "\\\\").replace("^", "\\^")
|
|
if negate:
|
|
return f"[^/{body}]", j + 1
|
|
return f"(?!/)[{body}]", j + 1
|
|
|
|
|
|
def _pattern_regex(pattern: str) -> str:
|
|
"""A glob pattern as a regex: `*`, `?` and `[...]` stay inside one path segment,
|
|
and `**/` matches zero or more whole directories. A `**` not followed by `/` acts
|
|
as `*`."""
|
|
out: list[str] = []
|
|
i, n = 0, len(pattern)
|
|
while i < n:
|
|
if pattern.startswith("**/", i):
|
|
out.append("(?:[^/]+/)*")
|
|
i += 3
|
|
elif pattern.startswith("**", i):
|
|
out.append("[^/]*")
|
|
i += 2
|
|
elif pattern[i] == "*":
|
|
out.append("[^/]*")
|
|
i += 1
|
|
elif pattern[i] == "?":
|
|
out.append("[^/]")
|
|
i += 1
|
|
elif pattern[i] == "[" and (cls := _class(pattern, i)) is not None:
|
|
out.append(cls[0])
|
|
i = cls[1]
|
|
else:
|
|
out.append(re.escape(pattern[i]))
|
|
i += 1
|
|
return "".join(out)
|
|
|
|
|
|
def matches_any(path: str, patterns: Iterable[str]) -> bool:
|
|
"""True when path matches any pattern, segment-aware and consistent with
|
|
expand_patterns: wildcards never cross `/`; `**/` matches zero or more directories."""
|
|
return any(re.fullmatch(_pattern_regex(p), path) for p in patterns)
|