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
@@ -3,9 +3,10 @@
|
|||||||
# caller and the inputs.
|
# caller and the inputs.
|
||||||
#
|
#
|
||||||
# Secrets reach only the steps that need them. The bot token is in the clone step and
|
# Secrets reach only the steps that need them. The bot token is in the clone step and
|
||||||
# the two steps that run the tool. The Claude credentials are in the drafting step only,
|
# the two steps that run the tool. The Claude credentials and the local model key are in
|
||||||
# and that step runs only when `drafter` normalizes to `claude`. Every `if:` reads the
|
# the drafting step only: the Claude ones only when `drafter` normalizes to `claude`, the
|
||||||
# normalized drafter, never the raw input.
|
# local key only when it normalizes to `local`. Every `if:` and secret expression reads
|
||||||
|
# the normalized drafter, never the raw input.
|
||||||
name: docs-review
|
name: docs-review
|
||||||
|
|
||||||
on:
|
on:
|
||||||
@@ -55,6 +56,11 @@ on:
|
|||||||
type: string
|
type: string
|
||||||
required: false
|
required: false
|
||||||
default: ""
|
default: ""
|
||||||
|
local_url:
|
||||||
|
description: "OpenAI-compatible base URL of the model server for drafter: local, e.g. http://model-host:8888/v1"
|
||||||
|
type: string
|
||||||
|
required: false
|
||||||
|
default: ""
|
||||||
model:
|
model:
|
||||||
description: "Model for drafter: claude"
|
description: "Model for drafter: claude"
|
||||||
type: string
|
type: string
|
||||||
@@ -75,6 +81,8 @@ on:
|
|||||||
required: false
|
required: false
|
||||||
ANTHROPIC_API_KEY:
|
ANTHROPIC_API_KEY:
|
||||||
required: false
|
required: false
|
||||||
|
LOCAL_MODEL_API_KEY:
|
||||||
|
required: false
|
||||||
|
|
||||||
defaults:
|
defaults:
|
||||||
run:
|
run:
|
||||||
@@ -106,6 +114,7 @@ jobs:
|
|||||||
INPUT_TRACKING_ISSUE: ${{ inputs.tracking_issue }}
|
INPUT_TRACKING_ISSUE: ${{ inputs.tracking_issue }}
|
||||||
INPUT_DOC_GUIDE: ${{ inputs.doc_guide }}
|
INPUT_DOC_GUIDE: ${{ inputs.doc_guide }}
|
||||||
INPUT_MODEL: ${{ inputs.model }}
|
INPUT_MODEL: ${{ inputs.model }}
|
||||||
|
INPUT_LOCAL_URL: ${{ inputs.local_url }}
|
||||||
# The calling repository's files are untrusted. Every python3 call takes -P, so
|
# The calling repository's files are untrusted. Every python3 call takes -P, so
|
||||||
# Python imports nothing from the working directory and a docs_review/ or os.py in
|
# Python imports nothing from the working directory and a docs_review/ or os.py in
|
||||||
# a pull request cannot replace the tool.
|
# a pull request cannot replace the tool.
|
||||||
@@ -201,7 +210,10 @@ jobs:
|
|||||||
&& steps.drafter.outputs.drafter != 'none'
|
&& steps.drafter.outputs.drafter != 'none'
|
||||||
run: sleep 180
|
run: sleep 180
|
||||||
|
|
||||||
# `local` runs here too, without the Claude credentials and without the install.
|
# `claude` gets the Claude credentials and the Claude Code install; `local` gets the
|
||||||
|
# local model key, the pi install and an unprivileged user to run pi as. pi's tool
|
||||||
|
# allowlist limits tool types, not paths, so the user is what keeps it out of the
|
||||||
|
# checkout: the checkout is root-owned and not writable by that user.
|
||||||
- name: Draft
|
- name: Draft
|
||||||
if: >-
|
if: >-
|
||||||
steps.drafter.outputs.drafter != 'none'
|
steps.drafter.outputs.drafter != 'none'
|
||||||
@@ -212,7 +224,10 @@ jobs:
|
|||||||
DOCS_REVIEW_BOT_TOKEN: ${{ secrets.DOCS_REVIEW_BOT_TOKEN }}
|
DOCS_REVIEW_BOT_TOKEN: ${{ secrets.DOCS_REVIEW_BOT_TOKEN }}
|
||||||
CLAUDE_CODE_OAUTH_TOKEN: ${{ steps.drafter.outputs.drafter == 'claude' && secrets.CLAUDE_CODE_OAUTH_TOKEN || '' }}
|
CLAUDE_CODE_OAUTH_TOKEN: ${{ steps.drafter.outputs.drafter == 'claude' && secrets.CLAUDE_CODE_OAUTH_TOKEN || '' }}
|
||||||
ANTHROPIC_API_KEY: ${{ steps.drafter.outputs.drafter == 'claude' && secrets.ANTHROPIC_API_KEY || '' }}
|
ANTHROPIC_API_KEY: ${{ steps.drafter.outputs.drafter == 'claude' && secrets.ANTHROPIC_API_KEY || '' }}
|
||||||
|
LOCAL_MODEL_API_KEY: ${{ steps.drafter.outputs.drafter == 'local' && secrets.LOCAL_MODEL_API_KEY || '' }}
|
||||||
|
DOCS_REVIEW_DRAFTER_USER: ${{ steps.drafter.outputs.drafter == 'local' && 'docs-review-drafter' || '' }}
|
||||||
CLAUDE_CODE_VERSION: 2.1.322
|
CLAUDE_CODE_VERSION: 2.1.322
|
||||||
|
PI_VERSION: 1.5.2
|
||||||
DISABLE_UPDATES: "1"
|
DISABLE_UPDATES: "1"
|
||||||
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1"
|
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1"
|
||||||
run: |
|
run: |
|
||||||
@@ -226,6 +241,16 @@ jobs:
|
|||||||
npm install -g --no-fund --no-audit "@anthropic-ai/claude-code@$CLAUDE_CODE_VERSION"
|
npm install -g --no-fund --no-audit "@anthropic-ai/claude-code@$CLAUDE_CODE_VERSION"
|
||||||
claude --version
|
claude --version
|
||||||
fi
|
fi
|
||||||
|
# Without the key the tool posts the flags with a note and fails before pi runs.
|
||||||
|
if [ "$DRAFTER" = "local" ] && [ -n "$LOCAL_MODEL_API_KEY" ]; then
|
||||||
|
npm install -g --no-fund --no-audit "@earendil-works/pi-coding-agent@$PI_VERSION"
|
||||||
|
pi --version < /dev/null
|
||||||
|
id -u "$DOCS_REVIEW_DRAFTER_USER" >/dev/null 2>&1 \
|
||||||
|
|| useradd --create-home --shell /usr/sbin/nologin "$DOCS_REVIEW_DRAFTER_USER"
|
||||||
|
# The user's sandbox and HOME are created under RUNNER_TEMP; it needs to
|
||||||
|
# traverse it, not list it.
|
||||||
|
chmod o+x "$RUNNER_TEMP"
|
||||||
|
fi
|
||||||
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0="http.${GITHUB_SERVER_URL}/.extraHeader" \
|
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0="http.${GITHUB_SERVER_URL}/.extraHeader" \
|
||||||
GIT_CONFIG_VALUE_0="Authorization: token $DOCS_REVIEW_BOT_TOKEN"
|
GIT_CONFIG_VALUE_0="Authorization: token $DOCS_REVIEW_BOT_TOKEN"
|
||||||
if [ "$EVENT" = "pull_request" ]; then
|
if [ "$EVENT" = "pull_request" ]; then
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
# docs-review
|
# docs-review
|
||||||
|
|
||||||
`docs_review` keeps living documents current. On each Gitea pull request it flags
|
`docs_review` keeps living documents current. On each Gitea pull request it flags
|
||||||
the documents the change makes stale. If the repository opts in, it also has Claude
|
the documents the change makes stale. If the repository opts in, it also has a coding
|
||||||
Code draft the edits. It is a Python package with no dependencies outside the standard
|
agent draft the edits: Claude Code, or the pi agent on a model server you run. It is a
|
||||||
library.
|
Python package with no dependencies outside the standard library.
|
||||||
|
|
||||||
## What it does
|
## What it does
|
||||||
|
|
||||||
@@ -18,14 +18,15 @@ finds, and edits that comment on later runs:
|
|||||||
modified, where the change did not regenerate it.
|
modified, where the change did not regenerate it.
|
||||||
- **unguided**: a listed document that the doc guide does not describe.
|
- **unguided**: a listed document that the doc guide does not describe.
|
||||||
|
|
||||||
Stage 2 runs only with `drafter: claude`. Claude Code reads the change, the flags and the
|
Stage 2 runs only with `drafter: claude` or `drafter: local`. The drafter reads the
|
||||||
listed documents, and decides which documents need edits; the flags are hints, not a
|
change, the flags and the listed documents, and decides which documents need edits; the
|
||||||
limit. The edits go into a second pull request into the feature branch, for the author to
|
flags are hints, not a limit. The edits go into a second pull request into the feature
|
||||||
review and merge. Later runs add commits to that pull request rather than replacing it.
|
branch, for the author to review and merge. Later runs add commits to that pull request
|
||||||
|
rather than replacing it.
|
||||||
|
|
||||||
The monthly pass runs on a schedule. It treats every file as new and reports the
|
The monthly pass runs on a schedule. It treats every file as new and reports the
|
||||||
uncovered and unguided flags for the whole repository in one issue. With
|
uncovered and unguided flags for the whole repository in one issue. With a drafter set
|
||||||
`drafter: claude` it opens a pull request with proposed edits instead.
|
it opens a pull request with proposed edits instead.
|
||||||
|
|
||||||
## What it never does
|
## What it never does
|
||||||
|
|
||||||
@@ -53,6 +54,43 @@ Its environment is an allowlist: system basics and its own Claude credential. Th
|
|||||||
token never reaches it, drafted files are checked for credential values before they are
|
token never reaches it, drafted files are checked for credential values before they are
|
||||||
committed, and everything posted to Gitea has credential values replaced with `***`.
|
committed, and everything posted to Gitea has credential values replaced with `***`.
|
||||||
|
|
||||||
|
## The local drafter
|
||||||
|
|
||||||
|
`drafter: local` runs the
|
||||||
|
[pi](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) coding agent (a
|
||||||
|
pinned version) against an OpenAI-compatible model server that you run and that reports
|
||||||
|
its loaded model the way Unsloth Studio does (below). Set `local_url` to the server's
|
||||||
|
OpenAI-compatible base URL, for example `http://model-host:8888/v1`, and the
|
||||||
|
`LOCAL_MODEL_API_KEY` secret to its key. The Actions runner must be able to reach that
|
||||||
|
address.
|
||||||
|
|
||||||
|
- **One model is resident at a time, and the tool uses whichever one is loaded.**
|
||||||
|
Before drafting it asks the server (`GET <server>/api/inference/loaded-models`, with
|
||||||
|
the key in the `Authorization` header) which model is loaded, and names exactly that
|
||||||
|
one. Naming any other model would make the server swap it in and evict the model for
|
||||||
|
every other client, so the tool never does. There is no `model` input for `local`. If
|
||||||
|
someone loads a different model while a run is drafting, the run's remaining requests
|
||||||
|
load the old model back.
|
||||||
|
- **The server is only reachable while it runs.** If nothing answers, or the server has
|
||||||
|
no model loaded, the run posts the stage 1 flags with the note "local drafter
|
||||||
|
unavailable: model server unreachable" (or "no model loaded") and succeeds. A drafter
|
||||||
|
that ran and failed still fails the job, as do a key the server rejects and an answer
|
||||||
|
that is not this server's (an HTTP error or a reply that is not the expected JSON).
|
||||||
|
- The server must expose `/api/inference/loaded-models` returning
|
||||||
|
`{"data": [{"id": ...}]}` at the root of `local_url` without its trailing `/v1`.
|
||||||
|
- Nothing is sent to Anthropic. The same material as for `claude` goes to your server.
|
||||||
|
|
||||||
|
pi runs with the read, list, edit and write tools only, no shell, and with every
|
||||||
|
project-local pi file (settings, extensions, skills, prompt templates) and `AGENTS.md`
|
||||||
|
ignored, since those come from the pull request. Any top-level `.pi*` entry is also
|
||||||
|
deleted from its working copy before it runs, and a draft that recreates one fails. Its
|
||||||
|
tool allowlist limits tool types, not paths, so the workflow runs it as an unprivileged
|
||||||
|
user that owns only the sandbox and pi's own temporary home; the checkout stays
|
||||||
|
root-owned, and the tool refuses to run pi as root. The repository's `CLAUDE.md` and the
|
||||||
|
doc guide reach it in the system prompt, as for `claude`. Its environment is the same
|
||||||
|
allowlist with `LOCAL_MODEL_API_KEY` in place of the Claude credential, and the key is
|
||||||
|
written into neither its command line nor its config file.
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
Add a workflow to the repository you want reviewed, at `.gitea/workflows/docs-review.yml`:
|
Add a workflow to the repository you want reviewed, at `.gitea/workflows/docs-review.yml`:
|
||||||
@@ -85,8 +123,8 @@ jobs:
|
|||||||
- `closed` in the pull request types lets the workflow close a docs pull request whose
|
- `closed` in the pull request types lets the workflow close a docs pull request whose
|
||||||
feature pull request merged or closed first.
|
feature pull request merged or closed first.
|
||||||
- The `concurrency` block cancels a run when the pull request is pushed again. With
|
- The `concurrency` block cancels a run when the pull request is pushed again. With
|
||||||
`drafter: claude` the workflow waits three minutes between stage 1 and drafting, so a
|
`drafter: claude` or `local` the workflow waits three minutes between stage 1 and
|
||||||
quick re-push cancels a run before it has spent anything.
|
drafting, so a quick re-push cancels a run before it has spent anything.
|
||||||
- `tool_ref` must name the same version as the `@` in `uses:`. Gitea does not tell a
|
- `tool_ref` must name the same version as the `@` in `uses:`. Gitea does not tell a
|
||||||
called workflow which ref it was called at, so the workflow fetches the tool's code at
|
called workflow which ref it was called at, so the workflow fetches the tool's code at
|
||||||
`tool_ref`.
|
`tool_ref`.
|
||||||
@@ -96,8 +134,12 @@ The job runs in the `node:22` image. It clones the repository with the bot token
|
|||||||
it needs no checkout action, and it installs Claude Code
|
it needs no checkout action, and it installs Claude Code
|
||||||
(`@anthropic-ai/claude-code`, a pinned version) only when `drafter` is `claude` and a
|
(`@anthropic-ai/claude-code`, a pinned version) only when `drafter` is `claude` and a
|
||||||
Claude credential is set. With `drafter: claude` and no credential, it posts the stage 1
|
Claude credential is set. With `drafter: claude` and no credential, it posts the stage 1
|
||||||
comment with a note saying so and fails. The drafter's cost and turn count are printed
|
comment with a note saying so and fails. With `drafter: local` it installs pi
|
||||||
in the log and appended to `$GITHUB_STEP_SUMMARY`.
|
(`@earendil-works/pi-coding-agent`, a pinned version) and creates the unprivileged user
|
||||||
|
when `LOCAL_MODEL_API_KEY` is set, and without it posts a note and fails in the same
|
||||||
|
way. The drafter's turn count, Claude's cost, and pi's tokens (output summed over the
|
||||||
|
run, and the largest input) are printed in the log and appended to
|
||||||
|
`$GITHUB_STEP_SUMMARY`.
|
||||||
|
|
||||||
The package can also be run by hand: `python3 -m docs_review pr|closed|monthly --help`.
|
The package can also be run by hand: `python3 -m docs_review pr|closed|monthly --help`.
|
||||||
|
|
||||||
@@ -105,7 +147,7 @@ The package can also be run by hand: `python3 -m docs_review pr|closed|monthly -
|
|||||||
|
|
||||||
| Input | Default | Meaning |
|
| Input | Default | Meaning |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `drafter` | `none` | `none` flags only. `claude` also drafts edits. `local` is accepted but not yet built: it fails the job with "local drafter not built yet". Any other value, including a misspelling, behaves as `none`. |
|
| `drafter` | `none` | `none` flags only. `claude` also drafts edits with Claude Code; `local` drafts them with pi on your model server. Any other value, including a misspelling, behaves as `none`. |
|
||||||
| `docs` | required | Newline-separated patterns for the living documents. |
|
| `docs` | required | Newline-separated patterns for the living documents. |
|
||||||
| `generated` | none | Patterns for generated files. |
|
| `generated` | none | Patterns for generated files. |
|
||||||
| `top_level` | `README.md` | The subset of `docs` the monthly pass re-reads in full. |
|
| `top_level` | `README.md` | The subset of `docs` the monthly pass re-reads in full. |
|
||||||
@@ -115,6 +157,7 @@ The package can also be run by hand: `python3 -m docs_review pr|closed|monthly -
|
|||||||
| `tracking_issue` | none | Issue number the monthly pass's commit messages cite. |
|
| `tracking_issue` | none | Issue number the monthly pass's commit messages cite. |
|
||||||
| `doc_guide` | none | Path to the document that says who reads each listed document and what it is for. The drafter writes for that reader. |
|
| `doc_guide` | none | Path to the document that says who reads each listed document and what it is for. The drafter writes for that reader. |
|
||||||
| `model` | `claude-sonnet-5-5` | Model used when `drafter` is `claude`. |
|
| `model` | `claude-sonnet-5-5` | Model used when `drafter` is `claude`. |
|
||||||
|
| `local_url` | none | Required when `drafter` is `local`: the model server's OpenAI-compatible base URL, such as `http://model-host:8888/v1`. Must be `http` or `https`. |
|
||||||
| `tool_ref` | `v1` | The docs-review branch or tag to run; the same as the `@` in `uses:`. |
|
| `tool_ref` | `v1` | The docs-review branch or tag to run; the same as the `@` in `uses:`. |
|
||||||
|
|
||||||
## Secrets
|
## Secrets
|
||||||
@@ -124,7 +167,9 @@ The package can also be run by hand: `python3 -m docs_review pr|closed|monthly -
|
|||||||
`write:issue` and `read:user`. An organization secret serves every repository in the
|
`write:issue` and `read:user`. An organization secret serves every repository in the
|
||||||
organization.
|
organization.
|
||||||
- `CLAUDE_CODE_OAUTH_TOKEN` or `ANTHROPIC_API_KEY` is needed only for
|
- `CLAUDE_CODE_OAUTH_TOKEN` or `ANTHROPIC_API_KEY` is needed only for
|
||||||
`drafter: claude`.
|
`drafter: claude`, and reaches only that drafter.
|
||||||
|
- `LOCAL_MODEL_API_KEY` is needed only for `drafter: local`, and reaches only that
|
||||||
|
drafter.
|
||||||
|
|
||||||
## Tests
|
## Tests
|
||||||
|
|
||||||
@@ -132,8 +177,8 @@ The package can also be run by hand: `python3 -m docs_review pr|closed|monthly -
|
|||||||
python3 -m unittest discover -s tests -v
|
python3 -m unittest discover -s tests -v
|
||||||
```
|
```
|
||||||
|
|
||||||
The tests use only the standard library and a fake `claude` executable. They need
|
The tests use only the standard library and fake `claude` and `pi` executables. They
|
||||||
Python 3.11 or later and make no network calls.
|
need Python 3.11 or later and make no network calls.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
+11
-2
@@ -107,6 +107,12 @@ class DraftResult:
|
|||||||
turns: int | None
|
turns: int | None
|
||||||
text: str
|
text: str
|
||||||
error: str | None
|
error: str | None
|
||||||
|
# Who drafted, for the PR body; None means Claude Code, which reports a cost.
|
||||||
|
drafted_by: str | None = None
|
||||||
|
# Tokens from the local drafter's event stream: the largest input (the peak
|
||||||
|
# context) and the summed output. Claude reports a cost instead.
|
||||||
|
input_tokens: int | None = None
|
||||||
|
output_tokens: int | None = None
|
||||||
|
|
||||||
|
|
||||||
def parse_claude_output(stdout: str, returncode: int) -> DraftResult:
|
def parse_claude_output(stdout: str, returncode: int) -> DraftResult:
|
||||||
@@ -207,6 +213,9 @@ def render_pr_body(
|
|||||||
if stage1:
|
if stage1:
|
||||||
parts.append("### Flags from stage 1\n\n" + "\n\n".join(stage1))
|
parts.append("### Flags from stage 1\n\n" + "\n\n".join(stage1))
|
||||||
turns = "unknown" if result.turns is None else result.turns
|
turns = "unknown" if result.turns is None else result.turns
|
||||||
cost = "unknown" if result.cost_usd is None else f"{result.cost_usd:.2f}"
|
if result.drafted_by is not None:
|
||||||
parts.append(f"Drafted by Claude Code: {turns} turns, ${cost} estimated.")
|
parts.append(f"Drafted by {result.drafted_by}: {turns} turns.")
|
||||||
|
else:
|
||||||
|
cost = "unknown" if result.cost_usd is None else f"{result.cost_usd:.2f}"
|
||||||
|
parts.append(f"Drafted by Claude Code: {turns} turns, ${cost} estimated.")
|
||||||
return "\n\n".join(parts) + "\n"
|
return "\n\n".join(parts) + "\n"
|
||||||
+90
-9
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import dataclasses
|
||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
@@ -10,7 +11,7 @@ from collections.abc import Iterable, Mapping
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
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.draft import DraftResult, claude_argv, parse_claude_output
|
||||||
from docs_review.inputs import Inputs, expand_patterns, matches_any
|
from docs_review.inputs import Inputs, expand_patterns, matches_any
|
||||||
from docs_review.secrets import secret_values
|
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
|
EXPORT_REASON_MAX = 200
|
||||||
NO_CREDENTIAL_NOTE = "drafter: claude but no Claude credential is set"
|
NO_CREDENTIAL_NOTE = "drafter: claude but no Claude credential is set"
|
||||||
CREDENTIAL_VARS = ("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY")
|
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)"
|
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:
|
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
|
"""Print the run's cost, turns and tokens, whichever the drafter reported, and
|
||||||
$GITHUB_STEP_SUMMARY when the runner sets it."""
|
append them to $GITHUB_STEP_SUMMARY when the runner sets it."""
|
||||||
lines = []
|
lines = []
|
||||||
|
if result.drafted_by is not None:
|
||||||
|
lines.append(f"- drafted_by: {result.drafted_by}")
|
||||||
if result.cost_usd is not None:
|
if result.cost_usd is not None:
|
||||||
lines.append(f"- total_cost_usd: {result.cost_usd:.2f}")
|
lines.append(f"- total_cost_usd: {result.cost_usd:.2f}")
|
||||||
if result.turns is not None:
|
if result.turns is not None:
|
||||||
lines.append(f"- num_turns: {result.turns}")
|
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:
|
if not lines:
|
||||||
return
|
return
|
||||||
print("drafter " + ", ".join(l[2:] for l in lines))
|
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],
|
def run_drafter(inputs: Inputs, prompt: str, cwd: Path, env: Mapping[str, str],
|
||||||
system_prompt_file: Path | None) -> DraftResult:
|
system_prompt_file: Path | None, *, local_model: str | None = None,
|
||||||
"""Run the configured drafter in cwd. Task 12 adds `local`."""
|
run_as: tuple[int, int] | None = None) -> DraftResult:
|
||||||
if inputs.drafter != "claude":
|
"""Run the configured drafter in cwd. `local` needs the resident model's id."""
|
||||||
return DraftResult(False, None, None, "", "local drafter not built yet")
|
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,
|
argv = claude_argv(env.get("DOCS_REVIEW_CLAUDE_BIN", "claude"), inputs.model,
|
||||||
str(system_prompt_file) if system_prompt_file else None)
|
str(system_prompt_file) if system_prompt_file else None)
|
||||||
try:
|
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)
|
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],
|
def disallowed(change: sandbox.TreeChange, listed: frozenset[str],
|
||||||
patterns: tuple[str, ...], root: Path,
|
patterns: tuple[str, ...], root: Path,
|
||||||
review_only: tuple[str, ...] = ()) -> list[str]:
|
review_only: tuple[str, ...] = ()) -> list[str]:
|
||||||
"""Changed paths the drafter may not touch. A listed document may change or go; a
|
"""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
|
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 = []
|
bad = []
|
||||||
for p in change.paths:
|
for p in change.paths:
|
||||||
ok = p in listed or (p in change.new and matches_any(p, patterns))
|
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):
|
if ok and matches_any(p, review_only):
|
||||||
ok = False
|
ok = False
|
||||||
if ok and p not in change.deleted and not sandbox.is_regular(root, p):
|
if ok and p not in change.deleted and not sandbox.is_regular(root, p):
|
||||||
ok = False
|
ok = False
|
||||||
if not ok:
|
if not ok:
|
||||||
bad.append(p)
|
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
|
return bad
|
||||||
|
|
||||||
|
|
||||||
@@ -155,6 +206,22 @@ class Drafted:
|
|||||||
result: DraftResult | None
|
result: DraftResult | None
|
||||||
changed: tuple[str, ...]
|
changed: tuple[str, ...]
|
||||||
note: str | None # why the run failed; None when it succeeded
|
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,
|
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."""
|
"""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):
|
if inputs.drafter == "claude" and not has_claude_credential(env):
|
||||||
return Drafted(None, (), NO_CREDENTIAL_NOTE)
|
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():
|
if git.run(["status", "--porcelain"], cwd).strip():
|
||||||
return Drafted(None, (), DIRTY_NOTE)
|
return Drafted(None, (), DIRTY_NOTE)
|
||||||
box = prompt_file = None
|
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:
|
except (git.GitError, subprocess.TimeoutExpired, OSError) as err:
|
||||||
return Drafted(None, (), EXPORT_NOTE.format(reason=_short_reason(err)))
|
return Drafted(None, (), EXPORT_NOTE.format(reason=_short_reason(err)))
|
||||||
sandbox.remove_symlinks(box)
|
sandbox.remove_symlinks(box)
|
||||||
|
sandbox.remove_pi_config(box)
|
||||||
listed = frozenset(expand_patterns(inputs.docs, box))
|
listed = frozenset(expand_patterns(inputs.docs, box))
|
||||||
before = sandbox.snapshot(box)
|
before = sandbox.snapshot(box)
|
||||||
prompt_file = write_system_prompt(box, inputs.doc_guide, env)
|
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)
|
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:
|
if not result.ok:
|
||||||
return Drafted(result, (), f"drafter failed: {result.error}")
|
return Drafted(result, (), f"drafter failed: {result.error}")
|
||||||
change = sandbox.compare(before, sandbox.snapshot(box))
|
change = sandbox.compare(before, sandbox.snapshot(box))
|
||||||
|
|||||||
+20
-1
@@ -3,6 +3,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
import urllib.parse
|
||||||
from collections.abc import Iterable, Mapping
|
from collections.abc import Iterable, Mapping
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -27,6 +28,8 @@ class Inputs:
|
|||||||
model: str
|
model: str
|
||||||
# Listed documents the drafter may read but not edit; each entry is within docs.
|
# Listed documents the drafter may read but not edit; each entry is within docs.
|
||||||
review_only: tuple[str, ...] = ()
|
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:
|
def normalize_drafter(raw: str | None) -> str:
|
||||||
@@ -35,6 +38,18 @@ def normalize_drafter(raw: str | None) -> str:
|
|||||||
return value if value in DRAFTERS else "none"
|
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, ...]:
|
def _lines(raw: str | None) -> tuple[str, ...]:
|
||||||
"""Split a newline-separated input, trimming and dropping blank lines."""
|
"""Split a newline-separated input, trimming and dropping blank lines."""
|
||||||
return tuple(line.strip() for line in (raw or "").splitlines() if line.strip())
|
return tuple(line.strip() for line in (raw or "").splitlines() if line.strip())
|
||||||
@@ -64,8 +79,11 @@ def parse_inputs(env: Mapping[str, str]) -> Inputs:
|
|||||||
except ValueError:
|
except ValueError:
|
||||||
raise ValueError(f"input 'tracking_issue' must be an integer, got {issue_raw!r}") from None
|
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(
|
return Inputs(
|
||||||
drafter=normalize_drafter(env.get("INPUT_DRAFTER")),
|
drafter=drafter,
|
||||||
docs=docs,
|
docs=docs,
|
||||||
generated=_lines(env.get("INPUT_GENERATED")),
|
generated=_lines(env.get("INPUT_GENERATED")),
|
||||||
top_level=_lines(env.get("INPUT_TOP_LEVEL")) or DEFAULT_TOP_LEVEL,
|
top_level=_lines(env.get("INPUT_TOP_LEVEL")) or DEFAULT_TOP_LEVEL,
|
||||||
@@ -75,6 +93,7 @@ def parse_inputs(env: Mapping[str, str]) -> Inputs:
|
|||||||
doc_guide=_text(env, "INPUT_DOC_GUIDE") or None,
|
doc_guide=_text(env, "INPUT_DOC_GUIDE") or None,
|
||||||
model=_text(env, "INPUT_MODEL") or DEFAULT_MODEL,
|
model=_text(env, "INPUT_MODEL") or DEFAULT_MODEL,
|
||||||
review_only=review_only,
|
review_only=review_only,
|
||||||
|
local_url=local_url,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,311 @@
|
|||||||
|
"""The local drafter: the pi coding agent against an OpenAI-compatible model server.
|
||||||
|
|
||||||
|
The server keeps one model resident and every client shares it. Naming any other model
|
||||||
|
makes the server load that one and evict the resident model for everyone, so the
|
||||||
|
drafter always asks which model is loaded and uses exactly that one.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import errno
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import pwd
|
||||||
|
import shutil
|
||||||
|
import socket
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from collections.abc import Callable, Mapping
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import NamedTuple
|
||||||
|
|
||||||
|
from docs_review.draft import DraftResult
|
||||||
|
from docs_review.secrets import redact
|
||||||
|
|
||||||
|
KEY_VAR = "LOCAL_MODEL_API_KEY"
|
||||||
|
USER_VAR = "DOCS_REVIEW_DRAFTER_USER"
|
||||||
|
PI_BIN_VAR = "DOCS_REVIEW_PI_BIN"
|
||||||
|
PROVIDER = "docs-review-local"
|
||||||
|
LOADED_MODELS_PATH = "/api/inference/loaded-models"
|
||||||
|
PROBE_TIMEOUT_S = 5
|
||||||
|
THINKING = "medium"
|
||||||
|
# ls lists a directory, which the monthly enumeration check needs; it is pure file
|
||||||
|
# reading, like read. There is no bash.
|
||||||
|
TOOLS = "read,ls,edit,write"
|
||||||
|
# Project-local pi files (.pi/ settings, extensions, skills, prompt templates) and
|
||||||
|
# AGENTS.md come from the pull request, so none of them load. The repository's
|
||||||
|
# CLAUDE.md and the guide arrive in the appended system prompt instead.
|
||||||
|
ISOLATION_FLAGS = ("--no-approve", "--no-extensions", "--no-skills",
|
||||||
|
"--no-prompt-templates", "--no-themes", "--no-context-files",
|
||||||
|
"--no-mcp", "--offline")
|
||||||
|
LOCAL_ENV = frozenset({"PATH", "LANG", "TMPDIR", "TERM", KEY_VAR})
|
||||||
|
ERROR_MAX = 200
|
||||||
|
INSTRUCTION = ("Your task is in the attached file {path}. Read and follow it; "
|
||||||
|
"edit files only in the current directory.")
|
||||||
|
|
||||||
|
UNREACHABLE_NOTE = "local drafter unavailable: model server unreachable"
|
||||||
|
NO_MODEL_NOTE = "local drafter unavailable: no model loaded"
|
||||||
|
REJECTED_NOTE = "local drafter: the model server rejected LOCAL_MODEL_API_KEY"
|
||||||
|
NOT_SERVER_NOTE = "{url} does not look like the model server: {reason}"
|
||||||
|
BAD_ID_NOTE = "local drafter: the model server reported an unusable model id {model!r}"
|
||||||
|
# Failures to reach anything at all. Anything else that answers is the wrong server.
|
||||||
|
_UNREACHABLE = (ConnectionError, TimeoutError, socket.timeout, socket.gaierror)
|
||||||
|
_UNREACHABLE_ERRNOS = frozenset({errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN,
|
||||||
|
errno.EHOSTDOWN})
|
||||||
|
|
||||||
|
|
||||||
|
class Probe(NamedTuple):
|
||||||
|
model: str | None
|
||||||
|
note: str | None # why there is no model; None when there is one
|
||||||
|
soft: bool # the run should report the note and still succeed
|
||||||
|
|
||||||
|
|
||||||
|
class DrafterUserError(RuntimeError):
|
||||||
|
"""Running as root without an existing DOCS_REVIEW_DRAFTER_USER account."""
|
||||||
|
|
||||||
|
|
||||||
|
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||||
|
"""Refuse redirects, so the key in the Authorization header goes to one host only."""
|
||||||
|
|
||||||
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
_OPENER = urllib.request.build_opener(_NoRedirect)
|
||||||
|
|
||||||
|
|
||||||
|
def server_root(base_url: str) -> str:
|
||||||
|
"""The server's own address: the OpenAI-compatible base URL without `/v1`."""
|
||||||
|
url = base_url.rstrip("/")
|
||||||
|
return url[: -len("/v1")] if url.endswith("/v1") else url
|
||||||
|
|
||||||
|
|
||||||
|
def _unreachable(err: BaseException) -> bool:
|
||||||
|
"""True when nothing answered: refused, reset, timed out or a name that does not
|
||||||
|
resolve. URLError wraps the socket error in .reason."""
|
||||||
|
reason = err.reason if isinstance(err, urllib.error.URLError) else err
|
||||||
|
if isinstance(reason, _UNREACHABLE):
|
||||||
|
return True
|
||||||
|
return isinstance(reason, OSError) and reason.errno in _UNREACHABLE_ERRNOS
|
||||||
|
|
||||||
|
|
||||||
|
def probe(base_url: str, key: str, *, urlopen: Callable = _OPENER.open) -> Probe:
|
||||||
|
"""Ask the server which model is resident. The key travels in a header only.
|
||||||
|
Nothing answering, or no model loaded, is soft; a rejected key, or an answer that
|
||||||
|
is not this server's (an HTTP error, a redirect, a body that is not the expected
|
||||||
|
JSON), is a hard failure."""
|
||||||
|
url = server_root(base_url) + LOADED_MODELS_PATH
|
||||||
|
request = urllib.request.Request(
|
||||||
|
url, headers={"Authorization": f"Bearer {key}", "Accept": "application/json"})
|
||||||
|
try:
|
||||||
|
with urlopen(request, timeout=PROBE_TIMEOUT_S) as response:
|
||||||
|
data = json.loads(response.read().decode("utf-8"))
|
||||||
|
except urllib.error.HTTPError as err:
|
||||||
|
if err.code in (401, 403):
|
||||||
|
return Probe(None, REJECTED_NOTE, False)
|
||||||
|
return Probe(None, NOT_SERVER_NOTE.format(url=url, reason=f"HTTP {err.code}"),
|
||||||
|
False)
|
||||||
|
except ValueError:
|
||||||
|
return Probe(None, NOT_SERVER_NOTE.format(url=url, reason="the reply is not JSON"),
|
||||||
|
False)
|
||||||
|
except OSError as err:
|
||||||
|
if _unreachable(err):
|
||||||
|
return Probe(None, UNREACHABLE_NOTE, True)
|
||||||
|
return Probe(None, NOT_SERVER_NOTE.format(url=url, reason=type(err).__name__),
|
||||||
|
False)
|
||||||
|
models = data.get("data") if isinstance(data, dict) else None
|
||||||
|
if not isinstance(models, list):
|
||||||
|
return Probe(None, NOT_SERVER_NOTE.format(url=url, reason="no `data` list"), False)
|
||||||
|
for item in models:
|
||||||
|
model = item.get("id") if isinstance(item, dict) else None
|
||||||
|
if isinstance(model, str) and model.strip():
|
||||||
|
model = model.strip()
|
||||||
|
if model.startswith("-"):
|
||||||
|
return Probe(None, BAD_ID_NOTE.format(model=model), False)
|
||||||
|
return Probe(model, None, True)
|
||||||
|
return Probe(None, NO_MODEL_NOTE, True)
|
||||||
|
|
||||||
|
|
||||||
|
def resident_model(base_url: str, key: str, *,
|
||||||
|
urlopen: Callable = _OPENER.open) -> str | None:
|
||||||
|
"""The id of the model the server has loaded; None on any error or when none is."""
|
||||||
|
return probe(base_url, key, urlopen=urlopen).model
|
||||||
|
|
||||||
|
|
||||||
|
def drafter_user(env: Mapping[str, str], *, geteuid: Callable[[], int] | None = None,
|
||||||
|
getpwnam: Callable | None = None) -> tuple[int, int] | None:
|
||||||
|
"""(uid, gid) to run pi as. Not root: None, run as the current user. Root: the
|
||||||
|
DOCS_REVIEW_DRAFTER_USER account, and DrafterUserError when it is unset or does not
|
||||||
|
exist, since pi as root could write anywhere."""
|
||||||
|
geteuid = geteuid or os.geteuid
|
||||||
|
getpwnam = getpwnam or pwd.getpwnam
|
||||||
|
if geteuid() != 0:
|
||||||
|
return None
|
||||||
|
name = (env.get(USER_VAR) or "").strip()
|
||||||
|
if not name:
|
||||||
|
raise DrafterUserError(f"running as root and {USER_VAR} is not set; "
|
||||||
|
"refusing to run pi as root")
|
||||||
|
try:
|
||||||
|
entry = getpwnam(name)
|
||||||
|
except KeyError:
|
||||||
|
raise DrafterUserError(f"drafter user {name!r} ({USER_VAR}) does not exist") \
|
||||||
|
from None
|
||||||
|
return entry.pw_uid, entry.pw_gid
|
||||||
|
|
||||||
|
|
||||||
|
def chown_tree(root: Path, ids: tuple[int, int]) -> None:
|
||||||
|
"""Give root and everything under it to ids, without following symlinks."""
|
||||||
|
os.chown(root, *ids, follow_symlinks=False)
|
||||||
|
for dirpath, dirnames, filenames in os.walk(root):
|
||||||
|
for name in dirnames + filenames:
|
||||||
|
os.chown(Path(dirpath) / name, *ids, follow_symlinks=False)
|
||||||
|
|
||||||
|
|
||||||
|
def models_config(base_url: str, model: str) -> dict:
|
||||||
|
"""pi's models.json: one provider at base_url, whose key pi reads from KEY_VAR, and
|
||||||
|
the one resident model."""
|
||||||
|
return {"providers": {PROVIDER: {
|
||||||
|
"baseUrl": base_url,
|
||||||
|
"api": "openai-completions",
|
||||||
|
"apiKey": "${" + KEY_VAR + "}",
|
||||||
|
"compat": {"supportsDeveloperRole": True, "supportsReasoningEffort": True,
|
||||||
|
"supportsUsageInStreaming": True},
|
||||||
|
"models": [{"id": model, "name": model, "reasoning": True, "input": ["text"]}],
|
||||||
|
}}}
|
||||||
|
|
||||||
|
|
||||||
|
def pi_argv(binary: str, model: str, task_file: Path,
|
||||||
|
system_prompt_file: Path | None) -> list[str]:
|
||||||
|
"""The pi command line. The task goes in as an @file, so a long prompt never lands
|
||||||
|
in argv; the key is never in it. Each option and its value are separate elements:
|
||||||
|
pi 1.5.2 rejects `--model=<id>` as an unknown option. probe() refuses a model id
|
||||||
|
starting with `-`, so the id cannot be read as an option."""
|
||||||
|
argv = [binary, "-p", "--mode", "json", "--provider", PROVIDER, "--model", model,
|
||||||
|
"--thinking", THINKING, "--tools", TOOLS, *ISOLATION_FLAGS]
|
||||||
|
if system_prompt_file is not None:
|
||||||
|
argv += ["--append-system-prompt", str(system_prompt_file)]
|
||||||
|
return argv + ["--", f"@{task_file}", INSTRUCTION.format(path=task_file)]
|
||||||
|
|
||||||
|
|
||||||
|
def pi_env(env: Mapping[str, str], home: Path) -> dict[str, str]:
|
||||||
|
"""The allowlist, a fresh HOME, and pi's own switches for no network but the model."""
|
||||||
|
out = {k: v for k, v in env.items() if k in LOCAL_ENV or k.startswith("LC_")}
|
||||||
|
out.update(HOME=str(home), PI_OFFLINE="1", PI_TELEMETRY="0")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _first_line(text: str) -> str:
|
||||||
|
"""The first non-blank line, cut to ERROR_MAX characters."""
|
||||||
|
lines = [l.strip() for l in text.splitlines() if l.strip()]
|
||||||
|
line = lines[0] if lines else ""
|
||||||
|
return line if len(line) <= ERROR_MAX else line[:ERROR_MAX] + "..."
|
||||||
|
|
||||||
|
|
||||||
|
def _text(raw: str | bytes | None) -> str:
|
||||||
|
if raw is None:
|
||||||
|
return ""
|
||||||
|
return raw.decode("utf-8", "replace") if isinstance(raw, bytes) else raw
|
||||||
|
|
||||||
|
|
||||||
|
def _count(usage: object, key: str) -> int | None:
|
||||||
|
value = usage.get(key) if isinstance(usage, dict) else None
|
||||||
|
return value if isinstance(value, int) and not isinstance(value, bool) else None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_pi_events(stdout: str, returncode: int | None, *, stderr: str = "",
|
||||||
|
env: Mapping[str, str] | None = None,
|
||||||
|
error: str | None = None) -> DraftResult:
|
||||||
|
"""Read pi's JSON event stream: the last assistant message is the answer, and each
|
||||||
|
turn_end is a turn. Tokens: output summed over assistant messages, input as the
|
||||||
|
maximum (each turn's input is the whole conversation so far, so a sum would count
|
||||||
|
it many times). pi exits 0 after a model error, so the message's stopReason decides
|
||||||
|
that. `error` (a timeout) fails the run whatever the stream says; the first stderr
|
||||||
|
line, credential values redacted, joins any failure. Nothing here raises."""
|
||||||
|
final, turns, tokens_in, tokens_out = None, 0, None, None
|
||||||
|
for line in stdout.splitlines():
|
||||||
|
try:
|
||||||
|
event = json.loads(line)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if not isinstance(event, dict):
|
||||||
|
continue
|
||||||
|
if event.get("type") == "turn_end":
|
||||||
|
turns += 1
|
||||||
|
message = event.get("message")
|
||||||
|
if (event.get("type") == "message_end" and isinstance(message, dict)
|
||||||
|
and message.get("role") == "assistant"):
|
||||||
|
final = message
|
||||||
|
usage = message.get("usage")
|
||||||
|
used_in, used_out = _count(usage, "input"), _count(usage, "output")
|
||||||
|
if used_in is not None:
|
||||||
|
tokens_in = max(tokens_in or 0, used_in)
|
||||||
|
if used_out is not None:
|
||||||
|
tokens_out = (tokens_out or 0) + used_out
|
||||||
|
text = ""
|
||||||
|
if final is not None and isinstance(final.get("content"), list):
|
||||||
|
text = "".join(c.get("text", "") for c in final["content"]
|
||||||
|
if isinstance(c, dict) and c.get("type") == "text"
|
||||||
|
and isinstance(c.get("text"), str))
|
||||||
|
if error is None and final is not None and final.get("stopReason") in ("error",
|
||||||
|
"aborted"):
|
||||||
|
reason = _first_line(str(final.get("errorMessage") or final.get("stopReason")))
|
||||||
|
error = f"pi reported an error: {reason}"
|
||||||
|
if error is None and returncode != 0:
|
||||||
|
error = f"pi exited with code {returncode}"
|
||||||
|
if error is None and not text.strip():
|
||||||
|
error = "pi gave no final text"
|
||||||
|
if error is not None:
|
||||||
|
line = _first_line(redact(stderr, env or {}))
|
||||||
|
if line:
|
||||||
|
error += f"; stderr: {line}"
|
||||||
|
return DraftResult(error is None, None, turns, text, error,
|
||||||
|
input_tokens=tokens_in, output_tokens=tokens_out)
|
||||||
|
|
||||||
|
|
||||||
|
def _write(path: Path, text: str) -> None:
|
||||||
|
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||||
|
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
||||||
|
fh.write(text)
|
||||||
|
|
||||||
|
|
||||||
|
def run_local(prompt: str, *, base_url: str, key: str, model: str, cwd: Path,
|
||||||
|
system_prompt_file: Path | None, env: Mapping[str, str], timeout: float,
|
||||||
|
run_as: tuple[int, int] | None = None) -> DraftResult:
|
||||||
|
"""Run pi on the sandbox at cwd with the resident model. Its HOME is a fresh
|
||||||
|
directory under RUNNER_TEMP holding models.json, the task and the system prompt,
|
||||||
|
removed afterwards. With run_as, pi runs as that (uid, gid) and owns the HOME."""
|
||||||
|
home = Path(tempfile.mkdtemp(prefix="docs-review-pi-home-",
|
||||||
|
dir=env.get("RUNNER_TEMP") or None))
|
||||||
|
try:
|
||||||
|
agent = home / ".pi" / "agent"
|
||||||
|
agent.mkdir(parents=True)
|
||||||
|
_write(agent / "models.json", json.dumps(models_config(base_url, model), indent=2))
|
||||||
|
task = home / "task.md"
|
||||||
|
_write(task, prompt)
|
||||||
|
system = None
|
||||||
|
if system_prompt_file is not None:
|
||||||
|
system = home / "system-prompt.md"
|
||||||
|
_write(system, Path(system_prompt_file).read_text(encoding="utf-8"))
|
||||||
|
if run_as is not None:
|
||||||
|
chown_tree(home, run_as)
|
||||||
|
argv = pi_argv(env.get(PI_BIN_VAR, "pi"), model, task, system)
|
||||||
|
user = {} if run_as is None else {"user": run_as[0], "group": run_as[1],
|
||||||
|
"extra_groups": []}
|
||||||
|
child_env = {**pi_env(env, home), KEY_VAR: key}
|
||||||
|
try:
|
||||||
|
proc = subprocess.run(argv, cwd=cwd, env=child_env, stdin=subprocess.DEVNULL,
|
||||||
|
capture_output=True, text=True, timeout=timeout,
|
||||||
|
check=False, **user)
|
||||||
|
except subprocess.TimeoutExpired as err:
|
||||||
|
# Whatever pi streamed before the kill: the turns, the last message and
|
||||||
|
# the tokens survive in the record.
|
||||||
|
return parse_pi_events(_text(err.stdout), None, stderr=_text(err.stderr),
|
||||||
|
env=child_env, error="timed out")
|
||||||
|
except OSError as err:
|
||||||
|
return DraftResult(False, None, None, "", f"could not start pi: {err}")
|
||||||
|
return parse_pi_events(proc.stdout, proc.returncode, stderr=proc.stderr,
|
||||||
|
env=child_env)
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(home, ignore_errors=True)
|
||||||
@@ -133,7 +133,7 @@ def run_monthly(inputs: Inputs, forge, env: Mapping[str, str], cwd: Path,
|
|||||||
drafted = draft_in_sandbox(inputs, prompt, cwd, env)
|
drafted = draft_in_sandbox(inputs, prompt, cwd, env)
|
||||||
if drafted.note is not None:
|
if drafted.note is not None:
|
||||||
post_issue(forge, flags, month, drafted.note)
|
post_issue(forge, flags, month, drafted.note)
|
||||||
return 1
|
return 0 if drafted.soft else 1
|
||||||
result, changed = drafted.result, list(drafted.changed)
|
result, changed = drafted.result, list(drafted.changed)
|
||||||
if not changed:
|
if not changed:
|
||||||
post_issue(forge, flags, month)
|
post_issue(forge, flags, month)
|
||||||
|
|||||||
@@ -219,7 +219,7 @@ def run_pr(inputs: Inputs, forge, env: Mapping[str, str], cwd: Path, args: PrArg
|
|||||||
drafted = draft_in_sandbox(inputs, prompt, cwd, env)
|
drafted = draft_in_sandbox(inputs, prompt, cwd, env)
|
||||||
if drafted.note is not None:
|
if drafted.note is not None:
|
||||||
post_stage1(forge, args.number, flags, args.head_sha, drafted.note, docs_pr=pr_no)
|
post_stage1(forge, args.number, flags, args.head_sha, drafted.note, docs_pr=pr_no)
|
||||||
return 1
|
return 0 if drafted.soft else 1
|
||||||
result, changed = drafted.result, list(drafted.changed)
|
result, changed = drafted.result, list(drafted.changed)
|
||||||
if not changed:
|
if not changed:
|
||||||
if flags:
|
if flags:
|
||||||
|
|||||||
+29
-2
@@ -66,11 +66,38 @@ def remove_symlinks(root: Path) -> tuple[str, ...]:
|
|||||||
return tuple(sorted(removed))
|
return tuple(sorted(removed))
|
||||||
|
|
||||||
|
|
||||||
|
PI_CONFIG_PREFIX = ".pi"
|
||||||
|
|
||||||
|
|
||||||
|
def is_pi_config(rel: str) -> bool:
|
||||||
|
"""True for a path under a top-level entry named .pi*: pi's project settings,
|
||||||
|
extensions and model config, or a config file beside them."""
|
||||||
|
return Path(rel).parts[0].startswith(PI_CONFIG_PREFIX) if rel else False
|
||||||
|
|
||||||
|
|
||||||
|
def pi_config_entries(root: Path) -> tuple[str, ...]:
|
||||||
|
"""Top-level names under root that start with .pi."""
|
||||||
|
return tuple(sorted(n for n in os.listdir(root) if n.startswith(PI_CONFIG_PREFIX)))
|
||||||
|
|
||||||
|
|
||||||
|
def remove_pi_config(root: Path) -> tuple[str, ...]:
|
||||||
|
"""Delete every top-level .pi* entry, so a pull request's pi settings or model
|
||||||
|
config cannot load whatever flags pi is given. Returns the removed names."""
|
||||||
|
removed = pi_config_entries(root)
|
||||||
|
for name in removed:
|
||||||
|
path = root / name
|
||||||
|
if path.is_dir() and not path.is_symlink():
|
||||||
|
shutil.rmtree(path)
|
||||||
|
else:
|
||||||
|
path.unlink()
|
||||||
|
return removed
|
||||||
|
|
||||||
|
|
||||||
class CopyRefused(RuntimeError):
|
class CopyRefused(RuntimeError):
|
||||||
"""A change cannot be copied back safely; the message names the path."""
|
"""A change cannot be copied back safely; the message names the path."""
|
||||||
|
|
||||||
|
|
||||||
def _digest(path: Path) -> str:
|
def digest(path: Path) -> str:
|
||||||
"""A content hash; a symlink hashes its target text and is marked as a link."""
|
"""A content hash; a symlink hashes its target text and is marked as a link."""
|
||||||
if path.is_symlink():
|
if path.is_symlink():
|
||||||
return "link:" + os.readlink(path)
|
return "link:" + os.readlink(path)
|
||||||
@@ -89,7 +116,7 @@ def snapshot(root: Path) -> dict[str, str]:
|
|||||||
names = list(filenames) + [d for d in dirnames if (base / d).is_symlink()]
|
names = list(filenames) + [d for d in dirnames if (base / d).is_symlink()]
|
||||||
for name in names:
|
for name in names:
|
||||||
path = base / name
|
path = base / name
|
||||||
out[path.relative_to(root).as_posix()] = _digest(path)
|
out[path.relative_to(root).as_posix()] = digest(path)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -4,10 +4,11 @@ in these top-level documents against what is actually in the repository:
|
|||||||
{top_level}
|
{top_level}
|
||||||
|
|
||||||
An enumeration is any list of files, scripts, modules, filename prefixes, outputs or
|
An enumeration is any list of files, scripts, modules, filename prefixes, outputs or
|
||||||
steps, and any stated count. Use Glob to list the files each one describes. Where a list
|
steps, and any stated count. Use Glob or ls to list the files each one describes.
|
||||||
or count no longer matches, correct it: add what is missing, remove what no longer
|
Where a list or count no longer matches, correct it: add what is missing, remove what no
|
||||||
exists, fix the number. A list presented as complete must be complete. If a list is
|
longer exists, fix the number.
|
||||||
deliberately partial, it should say so; when adding every missing item would make it
|
A list presented as complete must be complete. If a list is deliberately partial, it
|
||||||
unwieldy (more than about 15 new entries), add that phrase instead.
|
should say so; when adding every missing item would make it unwieldy (more than about 15
|
||||||
|
new entries), add that phrase instead.
|
||||||
|
|
||||||
Then correct anything else in these documents that no longer matches the repository.
|
Then correct anything else in these documents that no longer matches the repository.
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Stand-in for the pi binary. Prints a JSON event stream like `pi -p --mode json`.
|
||||||
|
|
||||||
|
Settings come from fake_pi.json beside this script, because the drafter's environment
|
||||||
|
is an allowlist. Keys:
|
||||||
|
sentinel (file touched when invoked), env_file (file receiving the env var names),
|
||||||
|
argv_file (file receiving argv as JSON), cwd_file (file receiving the working
|
||||||
|
directory), home_file (file receiving $HOME), models_copy (file receiving the
|
||||||
|
models.json pi would read), task_copy (file receiving the @file task), system_copy
|
||||||
|
(file receiving the --append-system-prompt file), edit (path to append a line to,
|
||||||
|
relative to the working directory or absolute), write (text to append instead),
|
||||||
|
fail (end on an assistant error), exit_code (exit with this code), no_text (end
|
||||||
|
with an empty assistant message), list_file (file receiving the names at the top of the
|
||||||
|
working directory).
|
||||||
|
|
||||||
|
Stdin must be /dev/null: a real pi waits on an open stdin until EOF. When it is
|
||||||
|
not, this exits 3 without printing anything.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
config_path = Path(__file__).resolve().with_name("fake_pi.json")
|
||||||
|
config = json.loads(config_path.read_text()) if config_path.exists() else {}
|
||||||
|
|
||||||
|
stdin, devnull = os.fstat(0), os.stat(os.devnull)
|
||||||
|
if (stdin.st_dev, stdin.st_ino, stdin.st_rdev) != (devnull.st_dev, devnull.st_ino,
|
||||||
|
devnull.st_rdev):
|
||||||
|
print("stdin is not /dev/null", file=sys.stderr)
|
||||||
|
sys.exit(3)
|
||||||
|
|
||||||
|
|
||||||
|
def emit(event):
|
||||||
|
print(json.dumps(event))
|
||||||
|
|
||||||
|
|
||||||
|
def assistant(text, stop="stop", error=None):
|
||||||
|
msg = {"role": "assistant", "content": [{"type": "text", "text": text}] if text else [],
|
||||||
|
"stopReason": stop, "usage": {"input": 100, "output": 20}}
|
||||||
|
if error:
|
||||||
|
msg["errorMessage"] = error
|
||||||
|
return msg
|
||||||
|
|
||||||
|
|
||||||
|
if config.get("sentinel"):
|
||||||
|
Path(config["sentinel"]).write_text("invoked\n", encoding="utf-8")
|
||||||
|
if config.get("env_file"):
|
||||||
|
Path(config["env_file"]).write_text("\n".join(sorted(os.environ)), encoding="utf-8")
|
||||||
|
if config.get("argv_file"):
|
||||||
|
Path(config["argv_file"]).write_text(json.dumps(sys.argv), encoding="utf-8")
|
||||||
|
if config.get("cwd_file"):
|
||||||
|
Path(config["cwd_file"]).write_text(os.getcwd(), encoding="utf-8")
|
||||||
|
if config.get("list_file"):
|
||||||
|
Path(config["list_file"]).write_text("\n".join(sorted(os.listdir("."))),
|
||||||
|
encoding="utf-8")
|
||||||
|
if config.get("home_file"):
|
||||||
|
Path(config["home_file"]).write_text(os.environ.get("HOME", ""), encoding="utf-8")
|
||||||
|
if config.get("models_copy"):
|
||||||
|
models = Path(os.environ["HOME"]) / ".pi" / "agent" / "models.json"
|
||||||
|
Path(config["models_copy"]).write_text(models.read_text(encoding="utf-8"),
|
||||||
|
encoding="utf-8")
|
||||||
|
args = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
|
||||||
|
task = next((a[1:] for a in args if a.startswith("@")), None)
|
||||||
|
if config.get("task_copy") and task:
|
||||||
|
Path(config["task_copy"]).write_text(Path(task).read_text(encoding="utf-8"),
|
||||||
|
encoding="utf-8")
|
||||||
|
if config.get("system_copy") and "--append-system-prompt" in sys.argv:
|
||||||
|
source = Path(sys.argv[sys.argv.index("--append-system-prompt") + 1])
|
||||||
|
Path(config["system_copy"]).write_text(source.read_text(encoding="utf-8"),
|
||||||
|
encoding="utf-8")
|
||||||
|
|
||||||
|
emit({"type": "session", "version": 3, "id": "s", "cwd": os.getcwd()})
|
||||||
|
emit({"type": "agent_start"})
|
||||||
|
emit({"type": "turn_start"})
|
||||||
|
emit({"type": "message_end", "message": {"role": "user", "content": [
|
||||||
|
{"type": "text", "text": "task"}]}})
|
||||||
|
|
||||||
|
edits = []
|
||||||
|
target = config.get("edit")
|
||||||
|
if target:
|
||||||
|
path = Path(target)
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with path.open("a", encoding="utf-8") as fh:
|
||||||
|
fh.write(config.get("write", "Edited by the local drafter.") + "\n")
|
||||||
|
edits.append({"path": target, "why": "updated for the change"})
|
||||||
|
tool = assistant("", stop="toolUse")
|
||||||
|
emit({"type": "message_end", "message": tool})
|
||||||
|
emit({"type": "turn_end", "message": tool, "toolResults": []})
|
||||||
|
emit({"type": "turn_start"})
|
||||||
|
|
||||||
|
if config.get("fail"):
|
||||||
|
final = assistant("", stop="error", error="Connection error.\nsecond line")
|
||||||
|
elif config.get("no_text"):
|
||||||
|
final = assistant("")
|
||||||
|
else:
|
||||||
|
summary = {"edits": edits, "declined": []}
|
||||||
|
final = assistant("Done.\n\n```json\n" + json.dumps(summary) + "\n```")
|
||||||
|
emit({"type": "message_end", "message": final})
|
||||||
|
emit({"type": "turn_end", "message": final, "toolResults": []})
|
||||||
|
emit({"type": "agent_end", "messages": [final]})
|
||||||
|
sys.exit(int(config.get("exit_code", 0)))
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
import json
|
||||||
|
import shutil
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
from docs_review import drafter, local
|
||||||
|
from tests import test_cli, test_cli_monthly
|
||||||
|
from tests.test_cli import BRANCH, git
|
||||||
|
|
||||||
|
FAKE_PI = Path(__file__).resolve().parent / "fake_pi.py"
|
||||||
|
KEY = "local-model-key-value-123456"
|
||||||
|
URL = "http://model-host:8888/v1"
|
||||||
|
|
||||||
|
|
||||||
|
def up(model="org/model-a"):
|
||||||
|
return mock.patch.object(local, "probe", return_value=local.Probe(model, None, True))
|
||||||
|
|
||||||
|
|
||||||
|
def down(note):
|
||||||
|
return mock.patch.object(local, "probe", return_value=local.Probe(None, note, True))
|
||||||
|
|
||||||
|
|
||||||
|
class LocalSetup:
|
||||||
|
def local_setup(self):
|
||||||
|
tmp = Path(self._tmp.name)
|
||||||
|
self.fake_pi = tmp / "bin" / "fake_pi.py"
|
||||||
|
shutil.copy(FAKE_PI, self.fake_pi)
|
||||||
|
self.fake_pi.chmod(0o755)
|
||||||
|
self.env.update({"INPUT_DRAFTER": "local", "INPUT_LOCAL_URL": URL,
|
||||||
|
"LOCAL_MODEL_API_KEY": KEY, "DOCS_REVIEW_PI_BIN": str(self.fake_pi)})
|
||||||
|
self.argv_file = tmp / "pi-argv"
|
||||||
|
|
||||||
|
def pi(self, **config):
|
||||||
|
config = {"sentinel": str(self.sentinel), "env_file": str(self.env_file),
|
||||||
|
"argv_file": str(self.argv_file), **config}
|
||||||
|
self.fake_pi.with_name("fake_pi.json").write_text(json.dumps(config),
|
||||||
|
encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
class LocalPrTests(LocalSetup, test_cli.CliCase):
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.local_setup()
|
||||||
|
|
||||||
|
def test_local_drafts_with_the_resident_model(self):
|
||||||
|
self.pi(edit="docs/README.md")
|
||||||
|
with up() as probe:
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 0)
|
||||||
|
probe.assert_called_once_with(URL, KEY)
|
||||||
|
self.assertEqual(len(self.fake.prs), 1)
|
||||||
|
self.assertIn("Edited by the local drafter.",
|
||||||
|
git(self.remote, "show", f"{BRANCH}:docs/README.md"))
|
||||||
|
argv = json.loads(self.argv_file.read_text())
|
||||||
|
self.assertEqual(argv[argv.index("--model") + 1], "org/model-a")
|
||||||
|
self.assertNotIn(KEY, " ".join(argv))
|
||||||
|
self.assertIn("Drafted by pi with org/model-a: 2 turns.",
|
||||||
|
self.fake.prs[0]["body"].splitlines()[-1])
|
||||||
|
|
||||||
|
def test_only_the_local_key_reaches_pi(self):
|
||||||
|
self.env["CLAUDE_CODE_OAUTH_TOKEN"] = "oauth-token-value-123456"
|
||||||
|
self.pi(edit="docs/README.md")
|
||||||
|
with up():
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 0)
|
||||||
|
names = self.env_file.read_text().split()
|
||||||
|
self.assertIn("LOCAL_MODEL_API_KEY", names)
|
||||||
|
for name in ("ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "DOCS_REVIEW_BOT_TOKEN"):
|
||||||
|
self.assertNotIn(name, names)
|
||||||
|
|
||||||
|
def test_unreachable_server_fails_soft(self):
|
||||||
|
self.pi(edit="docs/README.md")
|
||||||
|
with down(local.UNREACHABLE_NOTE):
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 0)
|
||||||
|
bodies = self.comment_bodies()
|
||||||
|
self.assertEqual(len(bodies), 1)
|
||||||
|
self.assertIn("local drafter unavailable: model server unreachable", bodies[0])
|
||||||
|
self.assertIn("Touched", bodies[0])
|
||||||
|
self.assertFalse(self.sentinel.exists())
|
||||||
|
self.assertEqual(self.fake.prs, [])
|
||||||
|
|
||||||
|
def test_no_model_loaded_fails_soft(self):
|
||||||
|
self.pi()
|
||||||
|
with down(local.NO_MODEL_NOTE):
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 0)
|
||||||
|
self.assertIn("local drafter unavailable: no model loaded", self.comment_bodies()[0])
|
||||||
|
self.assertFalse(self.sentinel.exists())
|
||||||
|
|
||||||
|
def test_rejected_key_fails_hard(self):
|
||||||
|
self.pi()
|
||||||
|
with mock.patch.object(local, "probe",
|
||||||
|
return_value=local.Probe(None, local.REJECTED_NOTE, False)):
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 1)
|
||||||
|
self.assertIn(local.REJECTED_NOTE, self.comment_bodies()[0])
|
||||||
|
|
||||||
|
def test_root_without_a_drafter_user_fails_hard(self):
|
||||||
|
self.pi()
|
||||||
|
self.env.pop("DOCS_REVIEW_DRAFTER_USER", None)
|
||||||
|
with up(), mock.patch.object(local.os, "geteuid", return_value=0):
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 1)
|
||||||
|
self.assertIn("DOCS_REVIEW_DRAFTER_USER", self.comment_bodies()[0])
|
||||||
|
self.assertFalse(self.sentinel.exists())
|
||||||
|
|
||||||
|
def test_missing_key_fails_before_probing(self):
|
||||||
|
self.pi()
|
||||||
|
self.env["LOCAL_MODEL_API_KEY"] = ""
|
||||||
|
with up() as probe:
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 1)
|
||||||
|
probe.assert_not_called()
|
||||||
|
self.assertIn("LOCAL_MODEL_API_KEY is not set", self.comment_bodies()[0])
|
||||||
|
|
||||||
|
def test_tokens_and_turns_reach_the_step_summary(self):
|
||||||
|
summary = Path(self._tmp.name) / "step-summary.md"
|
||||||
|
self.pi(edit="docs/README.md")
|
||||||
|
with up():
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit(),
|
||||||
|
GITHUB_STEP_SUMMARY=str(summary)), 0)
|
||||||
|
text = summary.read_text()
|
||||||
|
self.assertIn("num_turns: 2", text)
|
||||||
|
self.assertIn("output_tokens: 40", text)
|
||||||
|
self.assertIn("max_input_tokens: 100", text)
|
||||||
|
self.assertNotIn("total_cost_usd", text)
|
||||||
|
|
||||||
|
def test_project_pi_config_is_removed_from_the_sandbox(self):
|
||||||
|
self.write(self.seed, ".pi/settings.json", '{"defaultModel": "other"}\n')
|
||||||
|
self.write(self.seed, ".pi/extensions/x.ts", "export default () => {}\n")
|
||||||
|
self.write(self.seed, ".pi.json", "{}\n")
|
||||||
|
listing = Path(self._tmp.name) / "listing"
|
||||||
|
self.pi(edit="docs/README.md", list_file=str(listing))
|
||||||
|
with up():
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 0)
|
||||||
|
names = listing.read_text().split()
|
||||||
|
self.assertNotIn(".pi", names)
|
||||||
|
self.assertNotIn(".pi.json", names)
|
||||||
|
self.assertIn("docs", names)
|
||||||
|
self.assertEqual(len(self.fake.prs), 1)
|
||||||
|
self.assertNotIn(".pi/settings.json", git(self.remote, "show", "--stat",
|
||||||
|
"--format=", BRANCH))
|
||||||
|
|
||||||
|
def test_recreating_pi_config_is_refused(self):
|
||||||
|
self.env["INPUT_DOCS"] = "docs/*.md\n**/*.md"
|
||||||
|
self.pi(edit=".pi/notes.md")
|
||||||
|
with up():
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 1)
|
||||||
|
self.assertTrue(any(".pi/notes.md" in b for b in self.comment_bodies()))
|
||||||
|
self.assertEqual(self.fake.prs, [])
|
||||||
|
|
||||||
|
def test_drafter_that_ran_and_failed_is_exit_1(self):
|
||||||
|
self.pi(fail=True)
|
||||||
|
with up():
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 1)
|
||||||
|
self.assertIn("drafter failed: pi reported an error", self.comment_bodies()[0])
|
||||||
|
|
||||||
|
def test_outside_docs_is_refused_as_for_claude(self):
|
||||||
|
self.pi(edit="R/a.R")
|
||||||
|
with up():
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 1)
|
||||||
|
self.assertTrue(any("R/a.R" in b for b in self.comment_bodies()))
|
||||||
|
self.assertEqual(self.fake.prs, [])
|
||||||
|
|
||||||
|
def test_missing_local_url_is_a_usage_error(self):
|
||||||
|
self.env["INPUT_LOCAL_URL"] = ""
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 2)
|
||||||
|
|
||||||
|
|
||||||
|
class LocalMonthlyTests(LocalSetup, test_cli_monthly.MonthlyCase):
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.local_setup()
|
||||||
|
|
||||||
|
def test_unreachable_server_posts_issue_and_exits_0(self):
|
||||||
|
self.pi(edit="docs/README.md")
|
||||||
|
with down(local.UNREACHABLE_NOTE):
|
||||||
|
self.assertEqual(self.run_monthly("2026-12"), 0)
|
||||||
|
self.assertEqual(len(self.fake.issues), 1)
|
||||||
|
self.assertIn("model server unreachable", self.fake.issues[0]["body"])
|
||||||
|
self.assertFalse(self.sentinel.exists())
|
||||||
|
|
||||||
|
def test_monthly_pr(self):
|
||||||
|
self.pi(edit="docs/README.md")
|
||||||
|
with up():
|
||||||
|
self.assertEqual(self.run_monthly("2026-12"), 0)
|
||||||
|
self.assertEqual(len(self.fake.prs), 1)
|
||||||
|
|
||||||
|
|
||||||
|
class GitMetadataTests(LocalSetup, test_cli.CliCase):
|
||||||
|
"""The drafter writes straight into the checkout's .git, which the sandbox does not
|
||||||
|
cover; the run must stop before any further git command."""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.local_setup()
|
||||||
|
self.hook = self.work / ".git" / "hooks" / "post-commit"
|
||||||
|
|
||||||
|
def assert_stopped(self):
|
||||||
|
self.assertIn(drafter.GIT_METADATA_NOTE, self.comment_bodies()[0])
|
||||||
|
self.assertEqual(self.fake.prs, [])
|
||||||
|
self.assertNotIn(BRANCH, " ".join(self.remote_branches()))
|
||||||
|
|
||||||
|
def test_claude_writing_a_hook_fails_the_run(self):
|
||||||
|
self.env["INPUT_DRAFTER"] = "claude"
|
||||||
|
self.claude(edit=str(self.hook))
|
||||||
|
sha = self.feature_commit()
|
||||||
|
calls = []
|
||||||
|
real = drafter.subprocess.run
|
||||||
|
|
||||||
|
def record(argv, **kw):
|
||||||
|
calls.append(list(argv))
|
||||||
|
return real(argv, **kw)
|
||||||
|
|
||||||
|
with mock.patch.object(drafter.subprocess, "run", side_effect=record):
|
||||||
|
self.assertEqual(self.run_pr(sha), 1)
|
||||||
|
self.assert_stopped()
|
||||||
|
ran = [i for i, a in enumerate(calls) if a[0] == str(self.fake_claude)]
|
||||||
|
self.assertEqual(len(ran), 1)
|
||||||
|
self.assertEqual([a for a in calls[ran[0] + 1:] if a[0] == "git"], [])
|
||||||
|
|
||||||
|
def test_local_writing_a_hook_fails_the_run(self):
|
||||||
|
self.pi(edit=str(self.hook))
|
||||||
|
with up():
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 1)
|
||||||
|
self.assert_stopped()
|
||||||
|
|
||||||
|
def test_changing_git_config_fails_the_run(self):
|
||||||
|
self.pi(edit=str(self.work / ".git" / "config"), write="[core]\n\thooksPath = /tmp")
|
||||||
|
with up():
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 1)
|
||||||
|
self.assert_stopped()
|
||||||
|
|
||||||
|
def test_metadata_check_passes_an_untouched_checkout(self):
|
||||||
|
self.pi(edit="docs/README.md")
|
||||||
|
with up():
|
||||||
|
self.assertEqual(self.run_pr(self.feature_commit()), 0)
|
||||||
|
self.assertEqual(len(self.fake.prs), 1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -41,6 +41,7 @@ class ParseInputsTest(unittest.TestCase):
|
|||||||
{
|
{
|
||||||
"INPUT_DOCS": "a.md",
|
"INPUT_DOCS": "a.md",
|
||||||
"INPUT_DRAFTER": "Local",
|
"INPUT_DRAFTER": "Local",
|
||||||
|
"INPUT_LOCAL_URL": " http://model-host:8888/v1/ ",
|
||||||
"INPUT_TRACKING_ISSUE": " 42 ",
|
"INPUT_TRACKING_ISSUE": " 42 ",
|
||||||
"INPUT_DOC_GUIDE": "docs/guide.md",
|
"INPUT_DOC_GUIDE": "docs/guide.md",
|
||||||
"INPUT_MODEL": "m",
|
"INPUT_MODEL": "m",
|
||||||
@@ -51,6 +52,7 @@ class ParseInputsTest(unittest.TestCase):
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
self.assertEqual(i.drafter, "local")
|
self.assertEqual(i.drafter, "local")
|
||||||
|
self.assertEqual(i.local_url, "http://model-host:8888/v1")
|
||||||
self.assertEqual(i.tracking_issue, 42)
|
self.assertEqual(i.tracking_issue, 42)
|
||||||
self.assertEqual(i.doc_guide, "docs/guide.md")
|
self.assertEqual(i.doc_guide, "docs/guide.md")
|
||||||
self.assertEqual((i.model, i.workstream), ("m", "model"))
|
self.assertEqual((i.model, i.workstream), ("m", "model"))
|
||||||
@@ -90,6 +92,27 @@ class ParseInputsTest(unittest.TestCase):
|
|||||||
with self.assertRaisesRegex(ValueError, "tracking_issue"):
|
with self.assertRaisesRegex(ValueError, "tracking_issue"):
|
||||||
parse_inputs({"INPUT_DOCS": "a.md", "INPUT_TRACKING_ISSUE": "abc"})
|
parse_inputs({"INPUT_DOCS": "a.md", "INPUT_TRACKING_ISSUE": "abc"})
|
||||||
|
|
||||||
|
def test_local_url_required_for_local(self):
|
||||||
|
for url in (None, "", " "):
|
||||||
|
with self.assertRaisesRegex(ValueError, "local_url"):
|
||||||
|
parse_inputs({"INPUT_DOCS": "a.md", "INPUT_DRAFTER": "local",
|
||||||
|
"INPUT_LOCAL_URL": url})
|
||||||
|
|
||||||
|
def test_local_url_must_be_http(self):
|
||||||
|
for url in ("ftp://h/v1", "file:///etc/passwd", "model-host:8888/v1", "http://",
|
||||||
|
"http:///v1"):
|
||||||
|
with self.assertRaisesRegex(ValueError, "local_url"):
|
||||||
|
parse_inputs({"INPUT_DOCS": "a.md", "INPUT_DRAFTER": "local",
|
||||||
|
"INPUT_LOCAL_URL": url})
|
||||||
|
i = parse_inputs({"INPUT_DOCS": "a.md", "INPUT_DRAFTER": "local",
|
||||||
|
"INPUT_LOCAL_URL": "https://h/v1"})
|
||||||
|
self.assertEqual(i.local_url, "https://h/v1")
|
||||||
|
|
||||||
|
def test_local_url_ignored_for_other_drafters(self):
|
||||||
|
i = parse_inputs({"INPUT_DOCS": "a.md", "INPUT_DRAFTER": "claude",
|
||||||
|
"INPUT_LOCAL_URL": "ftp://x"})
|
||||||
|
self.assertIsNone(i.local_url)
|
||||||
|
|
||||||
|
|
||||||
class PatternTest(unittest.TestCase):
|
class PatternTest(unittest.TestCase):
|
||||||
def test_expand_sorted_deduplicated_posix(self):
|
def test_expand_sorted_deduplicated_posix(self):
|
||||||
|
|||||||
@@ -0,0 +1,380 @@
|
|||||||
|
import errno
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
import urllib.error
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
from docs_review import local
|
||||||
|
|
||||||
|
FAKE_SRC = Path(__file__).resolve().parent / "fake_pi.py"
|
||||||
|
KEY = "local-model-key-value-123456"
|
||||||
|
BASE = "http://model-host:8888/v1"
|
||||||
|
|
||||||
|
|
||||||
|
class FakeResponse(io.BytesIO):
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *exc):
|
||||||
|
self.close()
|
||||||
|
|
||||||
|
|
||||||
|
class ServerRootTest(unittest.TestCase):
|
||||||
|
def test_strips_v1_and_trailing_slash(self):
|
||||||
|
self.assertEqual(local.server_root("http://h:8888/v1"), "http://h:8888")
|
||||||
|
self.assertEqual(local.server_root("http://h:8888/v1/"), "http://h:8888")
|
||||||
|
self.assertEqual(local.server_root("https://h/api/openai"), "https://h/api/openai")
|
||||||
|
|
||||||
|
|
||||||
|
class ResidentModelTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.requests = []
|
||||||
|
|
||||||
|
def opener(self, body=None, error=None):
|
||||||
|
def urlopen(request, timeout):
|
||||||
|
self.requests.append((request, timeout))
|
||||||
|
if error is not None:
|
||||||
|
raise error
|
||||||
|
return FakeResponse(json.dumps(body).encode())
|
||||||
|
return urlopen
|
||||||
|
|
||||||
|
def test_first_model_id(self):
|
||||||
|
body = {"data": [{"id": "org/model-a"}, {"id": "org/model-b"}]}
|
||||||
|
self.assertEqual(local.resident_model(BASE, KEY, urlopen=self.opener(body)),
|
||||||
|
"org/model-a")
|
||||||
|
request, timeout = self.requests[0]
|
||||||
|
self.assertEqual(request.full_url,
|
||||||
|
"http://model-host:8888/api/inference/loaded-models")
|
||||||
|
self.assertEqual(request.get_header("Authorization"), f"Bearer {KEY}")
|
||||||
|
self.assertNotIn(KEY, request.full_url)
|
||||||
|
self.assertEqual(timeout, 5)
|
||||||
|
|
||||||
|
def test_errors_are_none(self):
|
||||||
|
cases = [
|
||||||
|
(None, urllib.error.URLError(ConnectionRefusedError(61, "refused"))),
|
||||||
|
(None, urllib.error.URLError(socket.gaierror(-2, "Name or service not known"))),
|
||||||
|
(None, TimeoutError("timed out")),
|
||||||
|
(None, ConnectionResetError()),
|
||||||
|
(None, urllib.error.HTTPError(BASE, 404, "Not Found", {}, None)),
|
||||||
|
({"data": []}, None),
|
||||||
|
({"nope": 1}, None),
|
||||||
|
(["x"], None),
|
||||||
|
({"data": [{"name": "no id"}]}, None),
|
||||||
|
({"data": [{"id": "--api-key=x"}]}, None),
|
||||||
|
]
|
||||||
|
for body, error in cases:
|
||||||
|
self.assertIsNone(local.resident_model(BASE, KEY,
|
||||||
|
urlopen=self.opener(body, error)))
|
||||||
|
|
||||||
|
def test_not_json_is_none(self):
|
||||||
|
def urlopen(request, timeout):
|
||||||
|
return FakeResponse(b"<html>")
|
||||||
|
self.assertIsNone(local.resident_model(BASE, KEY, urlopen=urlopen))
|
||||||
|
|
||||||
|
def test_probe_notes(self):
|
||||||
|
p = local.probe(BASE, KEY, urlopen=self.opener(
|
||||||
|
error=urllib.error.URLError(ConnectionRefusedError(61, "refused"))))
|
||||||
|
self.assertEqual((p.model, p.note, p.soft), (None, local.UNREACHABLE_NOTE, True))
|
||||||
|
p = local.probe(BASE, KEY, urlopen=self.opener({"data": []}))
|
||||||
|
self.assertEqual((p.model, p.note, p.soft), (None, local.NO_MODEL_NOTE, True))
|
||||||
|
p = local.probe(BASE, KEY, urlopen=self.opener({"data": [{"id": "m"}]}))
|
||||||
|
self.assertEqual((p.model, p.note), ("m", None))
|
||||||
|
|
||||||
|
def test_connection_failures_are_soft(self):
|
||||||
|
for error in (urllib.error.URLError(ConnectionRefusedError(61, "refused")),
|
||||||
|
urllib.error.URLError(socket.gaierror(-2, "Name or service not known")),
|
||||||
|
urllib.error.URLError(TimeoutError("timed out")),
|
||||||
|
urllib.error.URLError(OSError(errno.EHOSTUNREACH, "no route")),
|
||||||
|
TimeoutError("timed out"), ConnectionRefusedError()):
|
||||||
|
p = local.probe(BASE, KEY, urlopen=self.opener(error=error))
|
||||||
|
self.assertEqual((p.note, p.soft), (local.UNREACHABLE_NOTE, True), error)
|
||||||
|
|
||||||
|
def test_something_else_answering_is_a_hard_failure(self):
|
||||||
|
url = "http://model-host:8888/api/inference/loaded-models"
|
||||||
|
for body, error in (
|
||||||
|
(None, urllib.error.HTTPError(BASE, 404, "Not Found", {}, None)),
|
||||||
|
(None, urllib.error.HTTPError(BASE, 500, "Server Error", {}, None)),
|
||||||
|
(None, urllib.error.HTTPError(BASE, 302, "Found", {}, None)),
|
||||||
|
({"nope": 1}, None),
|
||||||
|
(["x"], None),
|
||||||
|
(None, urllib.error.URLError(ssl.SSLError(1, "wrong version number"))),
|
||||||
|
(None, urllib.error.URLError("unknown url type: htp")),
|
||||||
|
):
|
||||||
|
p = local.probe(BASE, KEY, urlopen=self.opener(body, error))
|
||||||
|
self.assertFalse(p.soft, (body, error))
|
||||||
|
self.assertIsNone(p.model)
|
||||||
|
self.assertTrue(p.note.startswith(f"{url} does not look like the model server: "),
|
||||||
|
p.note)
|
||||||
|
|
||||||
|
def test_non_json_body_is_a_hard_failure(self):
|
||||||
|
def urlopen(request, timeout):
|
||||||
|
return FakeResponse(b"<html>")
|
||||||
|
p = local.probe(BASE, KEY, urlopen=urlopen)
|
||||||
|
self.assertFalse(p.soft)
|
||||||
|
self.assertIn("does not look like the model server", p.note)
|
||||||
|
|
||||||
|
def test_model_id_starting_with_a_dash_is_refused(self):
|
||||||
|
p = local.probe(BASE, KEY, urlopen=self.opener({"data": [{"id": "-x"}]}))
|
||||||
|
self.assertEqual((p.model, p.soft), (None, False))
|
||||||
|
self.assertIn("'-x'", p.note)
|
||||||
|
|
||||||
|
def test_rejected_key_is_a_hard_failure(self):
|
||||||
|
err = urllib.error.HTTPError(BASE, 401, "Unauthorized", {}, None)
|
||||||
|
p = local.probe(BASE, KEY, urlopen=self.opener(error=err))
|
||||||
|
self.assertEqual((p.model, p.note, p.soft), (None, local.REJECTED_NOTE, False))
|
||||||
|
self.assertNotIn(KEY, p.note)
|
||||||
|
|
||||||
|
|
||||||
|
class ParseEventsTest(unittest.TestCase):
|
||||||
|
@staticmethod
|
||||||
|
def stream(*messages, junk=False):
|
||||||
|
lines = [json.dumps({"type": "session", "version": 3})]
|
||||||
|
if junk:
|
||||||
|
lines.append("not json")
|
||||||
|
for m in messages:
|
||||||
|
lines.append(json.dumps({"type": "message_end", "message": m}))
|
||||||
|
if m["role"] == "assistant":
|
||||||
|
lines.append(json.dumps({"type": "turn_end", "message": m}))
|
||||||
|
return "\n".join(lines) + "\n"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def said(text, stop="stop", **extra):
|
||||||
|
content = [{"type": "thinking", "thinking": "hmm"}]
|
||||||
|
if text:
|
||||||
|
content.append({"type": "text", "text": text})
|
||||||
|
return {"role": "assistant", "content": content, "stopReason": stop, **extra}
|
||||||
|
|
||||||
|
def test_final_text_and_turns(self):
|
||||||
|
out = self.stream({"role": "user", "content": "go"}, self.said("", "toolUse"),
|
||||||
|
self.said("All done."), junk=True)
|
||||||
|
r = local.parse_pi_events(out, 0)
|
||||||
|
self.assertTrue(r.ok, r.error)
|
||||||
|
self.assertEqual((r.text, r.turns, r.cost_usd, r.error), ("All done.", 2, None, None))
|
||||||
|
|
||||||
|
def test_tokens_sum_output_and_take_the_max_input(self):
|
||||||
|
out = self.stream(self.said("", "toolUse", usage={"input": 900, "output": 40}),
|
||||||
|
self.said("", "toolUse", usage={"input": 1500, "output": 60}),
|
||||||
|
self.said("Done.", usage={"input": 1200, "output": 5}))
|
||||||
|
r = local.parse_pi_events(out, 0)
|
||||||
|
self.assertEqual((r.input_tokens, r.output_tokens), (1500, 105))
|
||||||
|
r = local.parse_pi_events(self.stream(self.said("Done.")), 0)
|
||||||
|
self.assertEqual((r.input_tokens, r.output_tokens), (None, None))
|
||||||
|
|
||||||
|
def test_stderr_line_joins_the_error(self):
|
||||||
|
r = local.parse_pi_events("", 1, stderr="\nboom: key abc-secret-value-1\nmore\n",
|
||||||
|
env={"LOCAL_MODEL_API_KEY": "abc-secret-value-1"})
|
||||||
|
self.assertEqual(r.error, "pi exited with code 1; stderr: boom: key ***")
|
||||||
|
ok = local.parse_pi_events(self.stream(self.said("x")), 0, stderr="warning: noise")
|
||||||
|
self.assertIsNone(ok.error)
|
||||||
|
|
||||||
|
def test_assistant_error_is_not_ok_even_at_exit_zero(self):
|
||||||
|
out = self.stream(self.said("", "error", errorMessage="Connection error.\nmore"))
|
||||||
|
r = local.parse_pi_events(out, 0)
|
||||||
|
self.assertFalse(r.ok)
|
||||||
|
self.assertEqual(r.error, "pi reported an error: Connection error.")
|
||||||
|
|
||||||
|
def test_nonzero_exit_and_missing_text(self):
|
||||||
|
self.assertEqual(local.parse_pi_events(self.stream(self.said("x")), 2).error,
|
||||||
|
"pi exited with code 2")
|
||||||
|
self.assertEqual(local.parse_pi_events(self.stream(self.said("")), 0).error,
|
||||||
|
"pi gave no final text")
|
||||||
|
self.assertEqual(local.parse_pi_events("", 0).error, "pi gave no final text")
|
||||||
|
|
||||||
|
|
||||||
|
class DrafterUserTest(unittest.TestCase):
|
||||||
|
def test_not_root_runs_as_current_user(self):
|
||||||
|
env = {"DOCS_REVIEW_DRAFTER_USER": "drafter"}
|
||||||
|
self.assertIsNone(local.drafter_user(env, geteuid=lambda: 1000))
|
||||||
|
|
||||||
|
def test_root_without_a_user_raises(self):
|
||||||
|
for env in ({}, {"DOCS_REVIEW_DRAFTER_USER": " "}):
|
||||||
|
with self.assertRaisesRegex(local.DrafterUserError, "DOCS_REVIEW_DRAFTER_USER"):
|
||||||
|
local.drafter_user(env, geteuid=lambda: 0)
|
||||||
|
|
||||||
|
def test_root_with_a_user(self):
|
||||||
|
pw = mock.Mock(pw_uid=1500, pw_gid=1600)
|
||||||
|
ids = local.drafter_user({"DOCS_REVIEW_DRAFTER_USER": "drafter"},
|
||||||
|
geteuid=lambda: 0, getpwnam=lambda name: pw)
|
||||||
|
self.assertEqual(ids, (1500, 1600))
|
||||||
|
|
||||||
|
def test_root_with_a_missing_user_raises(self):
|
||||||
|
def missing(name):
|
||||||
|
raise KeyError(name)
|
||||||
|
with self.assertRaisesRegex(local.DrafterUserError, "drafter"):
|
||||||
|
local.drafter_user({"DOCS_REVIEW_DRAFTER_USER": "drafter"},
|
||||||
|
geteuid=lambda: 0, getpwnam=missing)
|
||||||
|
|
||||||
|
|
||||||
|
class RunLocalTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self._tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self._tmp.cleanup)
|
||||||
|
self.tmp = Path(self._tmp.name)
|
||||||
|
(self.tmp / "bin").mkdir()
|
||||||
|
self.pi = self.tmp / "bin" / "fake_pi.py"
|
||||||
|
shutil.copy(FAKE_SRC, self.pi)
|
||||||
|
self.pi.chmod(0o755)
|
||||||
|
self.box = self.tmp / "box"
|
||||||
|
self.box.mkdir()
|
||||||
|
(self.box / "README.md").write_text("Start.\n", encoding="utf-8")
|
||||||
|
(self.tmp / "runner").mkdir()
|
||||||
|
self.system = self.tmp / "runner" / "system.md"
|
||||||
|
self.system.write_text("SYSTEM PROMPT TEXT\n", encoding="utf-8")
|
||||||
|
self.env = {"PATH": os.environ["PATH"], "RUNNER_TEMP": str(self.tmp / "runner"),
|
||||||
|
"LOCAL_MODEL_API_KEY": KEY, "DOCS_REVIEW_BOT_TOKEN": "bot-token-123456",
|
||||||
|
"ANTHROPIC_API_KEY": "anthropic-key-123456", "LC_ALL": "C.UTF-8",
|
||||||
|
"DOCS_REVIEW_PI_BIN": str(self.pi)}
|
||||||
|
|
||||||
|
def configure(self, **config):
|
||||||
|
self.pi.with_name("fake_pi.json").write_text(json.dumps(config), encoding="utf-8")
|
||||||
|
|
||||||
|
def run_local(self, prompt="THE TASK PROMPT", system=True, **kw):
|
||||||
|
args = dict(base_url=BASE, key=KEY, model="org/model-a", cwd=self.box,
|
||||||
|
system_prompt_file=self.system if system else None, env=self.env,
|
||||||
|
timeout=30)
|
||||||
|
args.update(kw)
|
||||||
|
return local.run_local(prompt, **args)
|
||||||
|
|
||||||
|
def test_edits_a_doc_and_reports_turns(self):
|
||||||
|
self.configure(edit="README.md")
|
||||||
|
r = self.run_local()
|
||||||
|
self.assertTrue(r.ok, r.error)
|
||||||
|
self.assertEqual((r.turns, r.cost_usd), (2, None))
|
||||||
|
self.assertIn('"edits"', r.text)
|
||||||
|
self.assertIn("Edited by the local drafter.", (self.box / "README.md").read_text())
|
||||||
|
|
||||||
|
def test_argv(self):
|
||||||
|
argv_file = self.tmp / "argv"
|
||||||
|
self.configure(argv_file=str(argv_file))
|
||||||
|
self.assertTrue(self.run_local().ok)
|
||||||
|
argv = json.loads(argv_file.read_text())
|
||||||
|
self.assertEqual(argv[1:3], ["-p", "--mode"])
|
||||||
|
self.assertEqual(argv[argv.index("--mode") + 1], "json")
|
||||||
|
self.assertEqual(argv[argv.index("--provider") + 1], local.PROVIDER)
|
||||||
|
# pi 1.5.2 rejects the --flag=value form ("Unknown option: --model"), so every
|
||||||
|
# option and its value are separate elements.
|
||||||
|
self.assertEqual(argv[argv.index("--model") + 1], "org/model-a")
|
||||||
|
self.assertEqual([a for a in argv[:argv.index("--")] if a.startswith("--") and "=" in a],
|
||||||
|
[])
|
||||||
|
self.assertEqual(argv[argv.index("--thinking") + 1], "medium")
|
||||||
|
self.assertEqual(argv[argv.index("--tools") + 1], "read,ls,edit,write")
|
||||||
|
for flag in ("--no-approve", "--no-extensions", "--no-skills", "--no-context-files",
|
||||||
|
"--no-prompt-templates", "--no-mcp", "--offline"):
|
||||||
|
self.assertIn(flag, argv)
|
||||||
|
self.assertNotIn("--no-session", argv)
|
||||||
|
self.assertNotIn("--api-key", argv)
|
||||||
|
for arg in argv:
|
||||||
|
self.assertNotIn(KEY, arg)
|
||||||
|
self.assertNotIn("THE TASK PROMPT", arg)
|
||||||
|
tail = argv[argv.index("--") + 1:]
|
||||||
|
self.assertTrue(tail[0].startswith("@"))
|
||||||
|
self.assertIn(tail[0][1:], tail[1])
|
||||||
|
|
||||||
|
def test_task_and_system_prompt_are_files_outside_the_sandbox(self):
|
||||||
|
task, system, argv_file = self.tmp / "task", self.tmp / "system", self.tmp / "argv"
|
||||||
|
self.configure(task_copy=str(task), system_copy=str(system),
|
||||||
|
argv_file=str(argv_file))
|
||||||
|
big = "THE TASK PROMPT " + "x" * 300_000
|
||||||
|
self.assertTrue(self.run_local(prompt=big).ok)
|
||||||
|
self.assertEqual(task.read_text(), big)
|
||||||
|
self.assertEqual(system.read_text(), "SYSTEM PROMPT TEXT\n")
|
||||||
|
argv = json.loads(argv_file.read_text())
|
||||||
|
for path in (argv[argv.index("--") + 1][1:],
|
||||||
|
argv[argv.index("--append-system-prompt") + 1]):
|
||||||
|
self.assertFalse(Path(path).resolve().is_relative_to(self.box.resolve()))
|
||||||
|
self.assertFalse(Path(path).exists())
|
||||||
|
self.assertEqual(sorted(p.name for p in self.box.iterdir()), ["README.md"])
|
||||||
|
|
||||||
|
def test_no_system_prompt_omits_the_flag(self):
|
||||||
|
argv_file = self.tmp / "argv"
|
||||||
|
self.configure(argv_file=str(argv_file))
|
||||||
|
self.assertTrue(self.run_local(system=False).ok)
|
||||||
|
self.assertNotIn("--append-system-prompt", json.loads(argv_file.read_text()))
|
||||||
|
|
||||||
|
def test_environment_is_an_allowlist_with_an_ephemeral_home(self):
|
||||||
|
env_file, home_file, models = self.tmp / "env", self.tmp / "home", self.tmp / "m"
|
||||||
|
self.configure(env_file=str(env_file), home_file=str(home_file),
|
||||||
|
models_copy=str(models))
|
||||||
|
self.assertTrue(self.run_local().ok)
|
||||||
|
names = set(env_file.read_text().split())
|
||||||
|
self.assertIn("LOCAL_MODEL_API_KEY", names)
|
||||||
|
self.assertIn("LC_ALL", names)
|
||||||
|
self.assertNotIn("DOCS_REVIEW_BOT_TOKEN", names)
|
||||||
|
self.assertNotIn("ANTHROPIC_API_KEY", names)
|
||||||
|
self.assertNotIn("RUNNER_TEMP", names)
|
||||||
|
home = Path(home_file.read_text())
|
||||||
|
self.assertEqual(home.parent.resolve(), (self.tmp / "runner").resolve())
|
||||||
|
self.assertFalse(home.exists())
|
||||||
|
config = json.loads(models.read_text())
|
||||||
|
provider = config["providers"][local.PROVIDER]
|
||||||
|
self.assertEqual(provider["baseUrl"], BASE)
|
||||||
|
self.assertEqual(provider["apiKey"], "${LOCAL_MODEL_API_KEY}")
|
||||||
|
self.assertEqual(provider["api"], "openai-completions")
|
||||||
|
self.assertEqual([m["id"] for m in provider["models"]], ["org/model-a"])
|
||||||
|
self.assertNotIn(KEY, models.read_text())
|
||||||
|
|
||||||
|
def test_failures(self):
|
||||||
|
self.configure(fail=True)
|
||||||
|
r = self.run_local()
|
||||||
|
self.assertFalse(r.ok)
|
||||||
|
self.assertIn("Connection error.", r.error)
|
||||||
|
self.configure(exit_code=1)
|
||||||
|
self.assertEqual(self.run_local().error, "pi exited with code 1")
|
||||||
|
self.configure(no_text=True)
|
||||||
|
self.assertEqual(self.run_local().error, "pi gave no final text")
|
||||||
|
|
||||||
|
def test_timeout_and_missing_binary(self):
|
||||||
|
self.configure()
|
||||||
|
with mock.patch("docs_review.local.subprocess.run",
|
||||||
|
side_effect=local.subprocess.TimeoutExpired(["pi"], 30)):
|
||||||
|
self.assertEqual(self.run_local().error, "timed out")
|
||||||
|
partial = ParseEventsTest.stream(
|
||||||
|
ParseEventsTest.said("Halfway.", "toolUse", usage={"input": 70, "output": 9}))
|
||||||
|
for raw in (partial, partial.encode()):
|
||||||
|
err = local.subprocess.TimeoutExpired(["pi"], 30, output=raw, stderr=b"stuck\n")
|
||||||
|
with mock.patch("docs_review.local.subprocess.run", side_effect=err):
|
||||||
|
r = self.run_local()
|
||||||
|
self.assertFalse(r.ok)
|
||||||
|
self.assertEqual((r.turns, r.text, r.output_tokens), (1, "Halfway.", 9))
|
||||||
|
self.assertEqual(r.error, "timed out; stderr: stuck")
|
||||||
|
self.env["DOCS_REVIEW_PI_BIN"] = str(self.tmp / "absent")
|
||||||
|
r = self.run_local()
|
||||||
|
self.assertFalse(r.ok)
|
||||||
|
self.assertTrue(r.error.startswith("could not start pi"), r.error)
|
||||||
|
|
||||||
|
def test_runs_as_the_drafter_user_when_given(self):
|
||||||
|
self.configure()
|
||||||
|
calls = []
|
||||||
|
real = local.subprocess.run
|
||||||
|
|
||||||
|
def record(argv, **kw):
|
||||||
|
calls.append(kw)
|
||||||
|
kw = {k: v for k, v in kw.items() if k not in ("user", "group", "extra_groups")}
|
||||||
|
return real(argv, **kw)
|
||||||
|
|
||||||
|
with mock.patch("docs_review.local.subprocess.run", side_effect=record), \
|
||||||
|
mock.patch("docs_review.local.os.chown") as chown:
|
||||||
|
self.assertTrue(self.run_local(run_as=(1500, 1600)).ok)
|
||||||
|
self.assertEqual((calls[0]["user"], calls[0]["group"], calls[0]["extra_groups"]),
|
||||||
|
(1500, 1600, []))
|
||||||
|
self.assertTrue(all(c.args[1:] == (1500, 1600) for c in chown.call_args_list))
|
||||||
|
self.assertTrue(chown.call_args_list)
|
||||||
|
self.assertIs(calls[0]["stdin"], local.subprocess.DEVNULL)
|
||||||
|
|
||||||
|
def test_runs_as_the_current_user_by_default(self):
|
||||||
|
self.configure()
|
||||||
|
with mock.patch("docs_review.local.subprocess.run",
|
||||||
|
wraps=local.subprocess.run) as run:
|
||||||
|
self.assertTrue(self.run_local().ok)
|
||||||
|
self.assertNotIn("user", run.call_args.kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user