Files
docs-review/docs_review/inputs.py
T
jaredandClaude Opus 5.5 1ef68f12fb
tests / unittest (push) Failing after 28s
feat: local drafter (pi against an OpenAI-compatible server on your own hardware)
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>
2026-11-12 17:12:42 -05:00

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)