diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 89d758b..2345ba0 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,3 +1,3 @@ -# Owners of everything in this repository. Add a second owner before the -# first release: one approval is required to merge into 'main'. -* @egparedes +# One approval from an owner is required to merge into 'main'; a team keeps +# that ownership with more than one person. +* @GridTools/infrastructure diff --git a/.github/workflows/agent-review.yml b/.github/workflows/agent-review.yml index 2e23eea..2590307 100644 --- a/.github/workflows/agent-review.yml +++ b/.github/workflows/agent-review.yml @@ -9,12 +9,12 @@ name: Agent Review (reusable) # (agent-review/bin/authorize); decides whether the run is keyed. # prepare downloads the pinned harness, without secrets; runs none of # its code (no install scripts, no version check). -# review keyed harnesses: two AWF sandbox runs: a keyless one fetches -# the PR from github.com, then the agent runs with no network -# access but the API proxy. The inference key is in ONE step's -# env and reaches only AWF's API-proxy sidecar. The host never -# touches PR content and is treated as tainted once 'awf' -# returns. The only job with the caller's environment. +# review keyed harnesses, and the only job with the caller's +# environment. Two AWF sandbox runs: a keyless one fetches the +# PR from github.com, then the agent runs with no network access +# but the API proxy. The inference key is in ONE step's env and +# reaches only AWF's API-proxy sidecar. The host never touches +# PR content and is treated as tainted once 'awf' returns. # review-keyless # the same steps for a harness that calls no model ('stub'): # no environment and no secret, so a test needs no key and no @@ -42,9 +42,10 @@ name: Agent Review (reusable) # accepts only the 'pull_request_target' actions it lists, and the keyed job # has its own concurrency group. # -# Compatibility: a new permission in any job below, a new required input, a -# raised ceiling or a new allowed endpoint breaks callers or widens what they -# agreed to; release it as a breaking change. +# Compatibility: a change that breaks callers or widens what they agreed to +# (a new permission in any job below, a new required input, a raised ceiling, +# a new allowed endpoint) is a breaking release (docs/agent-review.md, +# Releases). on: workflow_call: @@ -321,10 +322,10 @@ jobs: if-no-files-found: error retention-days: 1 - # The keyed review: the only job with the caller's environment, and the - # only one that can read the key. 'review-keyless' below runs the same - # steps (YAML aliases) without environment and without any 'secrets.' - # reference; tests/test-workflow-structure.py checks both properties. + # The only job with the caller's environment, so the only one that can + # read the key. 'review-keyless' runs the same steps (YAML aliases) with + # no environment and no 'secrets.' reference; the structure test checks + # both properties. review: needs: [authorize, prepare] # 'authorize' decides 'keyed' from its harness allowlist, never from an @@ -672,8 +673,9 @@ jobs: | /usr/bin/tee -a "${GITHUB_STEP_SUMMARY}" # Off by default: artifacts of public repositories are downloadable by - # any signed-in user. The Phase 0 probe found no key or auth header in - # the audit files or the proxy logs. + # any signed-in user. The AWF probe found no key or auth header in the + # audit files or the proxy logs, nor did a count-only scan of an audit + # artifact from a keyed run with these flags. - &audit-readable name: Make the AWF audit log readable if: always() && steps.key.outputs.skipped != 'true' && inputs.upload_audit @@ -698,10 +700,9 @@ jobs: if-no-files-found: ignore retention-days: 7 - # The same steps for a harness that calls no model: no 'environment:', no - # 'secrets.' reference, so neither a key nor a deployment, and it runs on - # any ref (a caller's PR, a branch dispatch). Only the key check and the - # agent step's environment differ from 'review'. + # No 'environment:' and no 'secrets.' reference, so neither a key nor a + # deployment, and it runs on any ref (a caller's PR, a branch dispatch). + # Only the key check and the agent step's 'env:' differ from 'review'. review-keyless: needs: [authorize, prepare] if: needs.authorize.outputs.allowed == 'true' && needs.authorize.outputs.keyed == 'false' diff --git a/.github/workflows/self-test.yml b/.github/workflows/self-test.yml index dc6b7d0..99f2148 100644 --- a/.github/workflows/self-test.yml +++ b/.github/workflows/self-test.yml @@ -42,7 +42,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - # actionlint, shellcheck and file checks, hooks pinned by commit sha. + # The hooks of .pre-commit-config.yaml. - name: pre-commit run: pipx run pre-commit==4.7.0 run --all-files --show-diff-on-failure @@ -82,8 +82,7 @@ jobs: echo "::endgroup::" done exit "${rc}" - # The workflow's structural invariants (environment, secrets, - # permissions, expressions in scripts, the keyless twin). + # The invariants listed in agent-review/tests/workflow_structure.py. - name: Workflow structure run: python3 agent-review/tests/test-workflow-structure.py # Offline; the '--' filter is checked against a copy of PR Agent's diff --git a/README.md b/README.md index 0b75894..6914e5b 100644 --- a/README.md +++ b/README.md @@ -32,9 +32,9 @@ jobs: Never call a branch (`@main`) or a moving tag: a change here would reach your repository unreviewed. Check every new pin, including Dependabot's, before merging it: a commit that exists only in a fork resolves through this -repository's name in the REST API (Actions refused it as a pin in one test (from a fork with Actions disabled), but -that may change), and a tag can resolve to another commit even between -attempts of one run. +repository's name in the REST API (in one test, from a fork with Actions +disabled, Actions refused it as a pin, but that may change), and a tag can +resolve to another commit even between attempts of one run. ```bash gh api repos/GridTools/ci-workflows/compare/main... --jq .status # 'identical' or 'behind' diff --git a/agent-review/awf.yaml b/agent-review/awf.yaml index d50cd88..efd6dc9 100644 --- a/agent-review/awf.yaml +++ b/agent-review/awf.yaml @@ -10,10 +10,10 @@ # --container-workdir) and image digests (--image-tag) are passed as # command-line flags. # -# Verified by a probe on AWF v0.29.12 (runs on a fork, listed in the pull -# request that added this file): the dummy key is unreadable in the sandbox in every mode; the -# CSCS path mapping; the model pattern format; 'maxTurns' and -# 'rateLimiting' answer 429; 'agentTimeout' ends the agent with exit 124. +# Verified by a probe on AWF v0.29.12: a dummy key is unreadable in the +# sandbox in every mode; the CSCS path mapping; the model pattern format; +# 'maxTurns' and 'rateLimiting' answer 429; 'agentTimeout' ends the agent +# with exit 124. # The bounds the agent can actually hit are in the 'Spend' notes below. network: @@ -47,10 +47,10 @@ apiProxy: # sidecar otherwise makes ~7 GETs per run to api.github.com (the # github/gh-aw-firewall 'catalogue-data' branch) to refresh its pricing # snapshot. Those carry no data about the run (GET only, no Authorization), - # but we do not use AWF's AI-credit accounting (see 'Spend' below), so the - # egress and the up-to-5 s first-request wait are - # pointless. Pricing then falls back to the bundled tables. - # (AWF v0.29.12: containers/api-proxy/catalogue-loader.js:91,237.) + # but AWF's AI-credit accounting is not used (see 'Spend' below), so the + # egress and the up-to-5 s first-request wait are pointless. Pricing then + # falls back to the bundled tables (AWF v0.29.12, + # containers/api-proxy/catalogue-loader.js). modelCatalogue: enabled: false # Spend. The only hard cap is the dedicated CSCS key's own token budget; @@ -86,8 +86,8 @@ container: # one triggers first and the result is still collected. agentTimeout: 25 memoryLimit: 6g - # TODO(phase0): pin images by digest with 'container.images' if passing - # the setup action's 'image-tag' output (with digests) is not enough. + # No 'container.images': the images are pinned by digest through the + # setup action's 'image-tag' output, passed as '--image-tag'. filesystem: # Placeholder; the 'review' job sets it to the review workspace, the only diff --git a/agent-review/harnesses/README.md b/agent-review/harnesses/README.md index 447d4bb..d64ce11 100644 --- a/agent-review/harnesses/README.md +++ b/agent-review/harnesses/README.md @@ -1,16 +1,16 @@ # Harness adapters Each subdirectory adapts one coding-agent harness to the agent review -pipeline (see `docs/agent-review.md`). All files here are -read from the reusable workflow's own commit (`job.workflow_sha`), never from -the pull request or the calling repository. +pipeline (see `docs/agent-review.md`). All files here are read from the +reusable workflow's own commit (`job.workflow_sha`), never from the pull +request or the calling repository. | File | Contract | | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `install.sh` | `install.sh `. Runs in the secretless `prepare` job. Installs an **exact** version with integrity checks (npm: `npm ci` against a committed `package-lock.json`; binaries: release URL plus SHA-256) into ``, and writes the version to `/VERSION`. It must not execute any harness code (no install scripts, no `--version`): `prepare` runs on the host with sudo and a cache-capable token; `run.sh` checks the version inside the sandbox with `check_version` from `common.sh`. The prefix is unpacked to `/opt/agent-review/harness/` (read-only) and must run from there without network access. | -| `run.sh` | Runs inside the sandbox from the PR checkout, under `timeout`. Environment: `PROMPT_FILE`, `REPO_DIR`, `OUT_DIR`, `CONTEXT_DIR`, `MODEL`, `HARNESS_PREFIX`, `PR_NUMBER`, and AWF's `AWF_API_PROXY_OPENAI_URL`. Keeps its configuration in a scratch home under `$TMPDIR` (a directory in the workspace), built from environment variables only; disables auto-update, telemetry, sharing and remote model catalogues; sets the harness's request timeouts so that a request that stalls ends and is retried, without shortening how long the run waits for a silent service (`../tests/test-harness-stall.sh`); runs headless and writes `$OUT_DIR/review.md`. Exit codes: 0 review written, 2 ran but no review, anything else a failure. **Return 2, not 0, when the harness exits 0 without a real answer** (a step cap, a stall detector or a tool-call-only last turn can all do that): `run-review` posts whatever `review.md` holds after exit 0. Harness output goes to files in `$OUT_DIR`, which are not collected; print diagnostics only through `diag` in `common.sh`, which prefixes every line so that the harness's output cannot be read as a workflow command. | +| `run.sh` | Runs inside the sandbox from the PR checkout, under `timeout`. Environment: `PROMPT_FILE`, `REPO_DIR`, `OUT_DIR`, `CONTEXT_DIR`, `MODEL`, `HARNESS_PREFIX`, `PR_NUMBER`, `STUB_PADDING_KIB` (stub only: KiB of padding added to the fixed review, to test the size caps), and AWF's `AWF_API_PROXY_OPENAI_URL`, on top of the inherited environment; `run-review` also sets `HOME` and `TMPDIR` to directories in the workspace and forces the `GIT_*` settings of `sandbox_git.py`, so the harness's own git calls get them too. Keeps its configuration in a scratch home under `$TMPDIR` (a directory in the workspace), built from environment variables only; disables auto-update, telemetry, sharing and remote model catalogues; sets the harness's request timeouts so that a request that stalls ends and is retried, without shortening how long the run waits for a silent service (`../tests/test-harness-stall.sh`); runs headless and writes `$OUT_DIR/review.md`. Exit codes: 0 review written, 2 ran but no review, anything else a failure. **Return 2, not 0, when the harness exits 0 without a real answer** (a step cap, a stall detector or a tool-call-only last turn can all do that): `run-review` posts whatever `review.md` holds after exit 0. Harness output goes to files in `$OUT_DIR`, which are not collected; print diagnostics only through `diag` in `common.sh`, which prefixes every line so that the harness's output cannot be read as a workflow command. | | `wire` | One line: `openai-chat` or `none`. `openai-chat` passes the key to AWF as `OPENAI_API_KEY`; every harness uses AWF's OpenAI listener, `$AWF_API_PROXY_OPENAI_URL` (an origin): clients that append only `/chat/completions` (opencode, Pi) need `$AWF_API_PROXY_OPENAI_URL/v1`. There is no `anthropic-messages` wire: with `ANTHROPIC_API_KEY`, AWF v0.29.12 opens an Anthropic listener whose `POST /messages` is not counted by `maxTurns`, and its entrypoint fails under `filesystem.allowWrite`. An Anthropic-API client can use the OpenAI listener, which forwards `/v1/messages` with a Bearer token (CSCS accepts it). | -| `README.md` | Pinned version, how to upgrade it, the paths it reads as instructions or configuration (add them to `../instruction-files.txt`), and any outbound calls it tries to make. | +| `README.md` | How the version is pinned and upgraded, the paths it reads as instructions or configuration (add them to `../instruction-files.txt`), and any outbound calls it tries to make. | The harness name must also be added to the harness allowlist in `agent-review/lib/agent_review/authorize.py` (`KEYED_HARNESSES` or @@ -19,14 +19,15 @@ The harness name must also be added to the harness allowlist in `none`: the `review-keyless` job); both jobs check that the `wire` agrees. Callers that offer it add it to their `workflow_dispatch` choice. -Recommended: `opencode` with `zai-org/GLM-5.3-Flash`, `pi` as the alternative. - `common.sh` holds the helpers the adapters share: the scratch `HOME`, `NO_PROXY` for loopback and the listeners, and bounded diagnostics. -| Harness | Version | Wire | Ignores the repository's configuration with | Own turn cap | -| --------------------- | ------- | ------------- | ------------------------------------------- | ------------ | -| [opencode](opencode/) | 2.2.7 | `openai-chat` | `OPENCODE_DISABLE_PROJECT_CONFIG=1` | 35 steps | -| [pi](pi/) | 1.5.2 | `openai-chat` | `--no-approve --no-context-files` | none | +| Harness | Wire | Ignores the repository's configuration with | Own turn cap | +| --------------------- | ------------- | ------------------------------------------- | ------------------------ | +| [opencode](opencode/) | `openai-chat` | `OPENCODE_DISABLE_PROJECT_CONFIG=1` | `MAX_STEPS` in `run.sh` | +| [pi](pi/) | `openai-chat` | `--no-approve --no-context-files` | none | + +Each harness's version is pinned in its `package.json`; which harness and +model to use is in `docs/agent-review.md` (Configuration notes). `stub` makes no model call and writes a fixed review with hostile content (@mentions of a handle that is not a valid login, HTML comments imitating diff --git a/agent-review/harnesses/opencode/README.md b/agent-review/harnesses/opencode/README.md index 19433d5..a8212d7 100644 --- a/agent-review/harnesses/opencode/README.md +++ b/agent-review/harnesses/opencode/README.md @@ -6,8 +6,7 @@ product). Wire: OpenAI chat, through AWF's OpenAI listener. ## Version and upgrades -Pinned to 2.2.7 through `package.json` and `package-lock.json` (npm integrity -hash). The adapter installs the platform package +Pinned through `package.json` and `package-lock.json` (npm integrity hash). The adapter installs the platform package `@opencode/cli-linux-x64-baseline` directly: the `@opencode/cli` wrapper only hard-links that same binary in a postinstall script, and its lockfile pulls the binaries of every platform (992 MB instead of 247 MB). `baseline` also @@ -32,25 +31,19 @@ release still has the flags and environment variables used in `run.sh`. `execute`, `opencode_*`. Left: `glob`, `grep`, `read`, `shell`, `skill`. `shell` is not restricted (an allowlist is possible but would block harmless read-only commands); the sandbox is the boundary. -- `agents.build.steps` caps a run at 35 model steps, below AWF's - `apiProxy.maxTurns`. opencode makes one more request first, for the session - title. At the last step tools are disabled, so the model has to answer. - -- **Request timeouts** are provider settings, both 300 s. `headerTimeout` - is the wait for response headers (opencode's default, set explicitly). - `chunkTimeout` is the wait for the next event of a streamed response, - including the first one after the headers (the default is 900 s, most of - the harness timeout); a stream that keeps sending is never cut. opencode - retries a timed-out request after 2, 4 and 8 s, but at most 3 times per - run, and that limit cannot be configured: a run waits at most 4 x the - timeout for a service that answers nothing. That is why neither value is - lower: in the v0.1.0 release validation, a review succeeded after 13 - minutes without an answer, and one request was answered after 185 s - without headers. A service that sends its headers at once and then - queues the request is silent in the same way under `chunkTimeout`, so it - gets the same wait. `../../tests/test-harness-stall.sh` checks this - against a server that stalls; run it after changing these values or the - pinned version, since the retry limit may change with it. +- `agents.build.steps` caps a run at `MAX_STEPS` model steps (`run.sh`), + below AWF's `apiProxy.maxTurns`. opencode makes one more request first, for + the session title. At the last step tools are disabled, so the model has + to answer. +- **Request timeouts** are the provider settings `headerTimeout` (the wait + for response headers) and `chunkTimeout` (the wait for the next event of a + streamed response, including the first one after the headers); a stream + that keeps sending is never cut. opencode retries a timed-out request + after 2, 4 and 8 s, but at most 3 times per run, and that limit cannot be + configured. The values, and why neither is lower, are in `run.sh`. + `../../tests/test-harness-stall.sh` checks them against a server that + stalls; run it after changing them or the pinned version, since the retry + limit may change with it. ## Outbound calls @@ -63,5 +56,6 @@ vLLM ports), which is harmless. `opencode run --format json` writes JSONL. The review is the text after the last `tool_use` event (`run-review` then drops anything before its first -`### ` heading, such as a note that the step cap was reached). opencode exits 0 when the step cap ends a run without -an answer (then `run.sh` exits 2) and 1 when the endpoint is unreachable. +`### ` heading, such as a note that the step cap was reached). opencode +exits 0 when the step cap ends a run without an answer (then `run.sh` exits +2) and 1 when the endpoint is unreachable. diff --git a/agent-review/harnesses/opencode/install.sh b/agent-review/harnesses/opencode/install.sh index e986552..07df37f 100755 --- a/agent-review/harnesses/opencode/install.sh +++ b/agent-review/harnesses/opencode/install.sh @@ -5,11 +5,11 @@ # # Runs in the secretless 'prepare' job, and never executes the harness # there: that job runs on the host with sudo and the runner's cache token. -# run.sh checks the version inside the sandbox. Depends on the Linux x64 'baseline' -# platform package directly (it runs on CPUs without AVX2, too) instead of -# the '@opencode/cli' wrapper, whose postinstall script only hard-links this -# same binary and whose lockfile pulls the binaries of every platform. No -# install scripts run. +# run.sh checks the version inside the sandbox. Depends on the Linux x64 +# 'baseline' platform package directly (it runs on CPUs without AVX2, too) +# instead of the '@opencode/cli' wrapper, whose postinstall script only +# hard-links this same binary and whose lockfile pulls the binaries of every +# platform. No install scripts run. set -euo pipefail diff --git a/agent-review/harnesses/opencode/run.sh b/agent-review/harnesses/opencode/run.sh index b1bfcba..e195168 100755 --- a/agent-review/harnesses/opencode/run.sh +++ b/agent-review/harnesses/opencode/run.sh @@ -21,9 +21,9 @@ readonly MAX_STEPS=35 # time a run can wait for a service that answers nothing is 4 x the # timeout. So the wait for response headers stays at opencode's default, # set here so that an upgrade cannot change it unnoticed: a lower value -# would end runs that succeed today after a long wait (in the v0.1.0 -# release validation, 13 minutes without an answer, and a request answered -# after 185 s without headers). The chunk timeout is the wait for the next +# would end runs that succeed after a long wait (seen with the real +# service: 13 minutes without an answer, and a request answered after +# 185 s without headers). The chunk timeout is the wait for the next # event of a streamed response, and also for the FIRST one after the # headers: a service that sends headers at once and then queues the # request, or a model that thinks for a while before its first token, is diff --git a/agent-review/harnesses/pi/README.md b/agent-review/harnesses/pi/README.md index ccb3779..27d090e 100644 --- a/agent-review/harnesses/pi/README.md +++ b/agent-review/harnesses/pi/README.md @@ -8,8 +8,8 @@ Responses API, which CSCS does not serve). ## Version and upgrades -Pinned to 1.5.2 through `package.json` and `package-lock.json` (npm integrity -hashes for all 123 packages). Pi needs Node.js >= 22.19.0, so the adapter +Pinned through `package.json` and `package-lock.json` (npm integrity hashes +for every package). Pi needs Node.js >= 22.19.0, so the adapter ships its own: `node.pin` holds the version and the SHA-256 of the official `linux-x64` tarball, from `SHASUMS256.txt`. `npm ci --ignore-scripts` skips the install scripts of two dependencies (`@google/genai`, `protobufjs`); Pi @@ -39,19 +39,16 @@ To upgrade, set the version in `package.json` and regenerate the lockfile with bound is AWF's request rate limits and the harness timeout (see `../../awf.yaml`). - **Request timeouts and retries** come from `settings.json` in the same - directory. `httpIdleTimeoutMs` is 240 s (Pi's default is 300 s; one - setting for both waits): a request that gets no response headers, or no - further chunk of a streamed response, for that long is ended and retried; - a stream that keeps sending is never cut. It is not lower because, in the - v0.1.0 release validation, a request was answered after 185 s without - headers. `retry.maxRetries` is 5 (default 3; the delay doubles from - `retry.baseDelayMs`, 2 s as by default, and the count starts again after - a successful request): 6 attempts of - 240 s exceed the harness timeout, so a run waits for a silent service as - long as it did with the defaults (4 x 300 s). Every attempt counts - against AWF's request limits. `../../tests/test-harness-stall.sh` checks - this against a server that stalls; run it after changing these values or - the pinned version. + directory. `httpIdleTimeoutMs` is one setting for both waits: a request + that gets no response headers, or no further chunk of a streamed + response, for that long is ended and retried; a stream that keeps sending + is never cut. `retry.maxRetries` is raised above Pi's default (the delay + doubles from `retry.baseDelayMs`, and the count starts again after a + successful request), so that the shorter timeout does not shorten how long + a run waits for a silent service. The values and their reasons are in + `run.sh`. Every attempt counts against AWF's request limits. + `../../tests/test-harness-stall.sh` checks this against a server that + stalls; run it after changing these values or the pinned version. ## Outbound calls diff --git a/agent-review/harnesses/pi/install.sh b/agent-review/harnesses/pi/install.sh index 8a2c378..6b7afc7 100755 --- a/agent-review/harnesses/pi/install.sh +++ b/agent-review/harnesses/pi/install.sh @@ -6,8 +6,8 @@ # # Runs in the secretless 'prepare' job, and never executes the harness or its # Node.js there: that job runs on the host with sudo and the runner's cache -# token. run.sh checks the version inside the sandbox. Pi is pure JavaScript and WebAssembly -# without native addons; no install scripts run. +# token. run.sh checks the version inside the sandbox. Pi is pure JavaScript +# and WebAssembly without native addons; no install scripts run. set -euo pipefail diff --git a/agent-review/harnesses/pi/run.sh b/agent-review/harnesses/pi/run.sh index 27906d4..75b287a 100755 --- a/agent-review/harnesses/pi/run.sh +++ b/agent-review/harnesses/pi/run.sh @@ -24,14 +24,14 @@ readonly CONTEXT_WINDOW=128000 MAX_TOKENS=16384 # A request that sends nothing for this long (no response headers, or no # further chunk of a streamed response) is ended and retried; Pi's default # is 300 s, and it has one setting for both waits. A live stream sends a -# chunk every few seconds; its total duration is not limited. Not lower: in -# the v0.1.0 release validation a request was answered after 185 s without -# headers, and whether a new request would have been answered sooner is not -# known. The retries (Pi's default is 3; the delay doubles from 2 s, Pi's -# default, set here so that the stall test can scale it) are -# raised so that the time a run can wait for a service that answers nothing -# is not shortened: 6 attempts of 240 s exceed the harness time limit, which -# stays the bound. Each attempt counts against AWF's request limits. +# chunk every few seconds; its total duration is not limited. Not lower: +# the real service has answered a request after 185 s without headers, and +# whether a new request would have been answered sooner is not known. The +# retries are raised from Pi's default of 3 so that the lower timeout does +# not shorten how long a run can wait for a service that answers nothing: +# 6 attempts of 240 s exceed the harness time limit, which stays the bound. +# The delay (doubling from Pi's default of 2 s) is set here so that the +# stall test can scale it. Each attempt counts against AWF's request limits. readonly IDLE_TIMEOUT_MS=240000 MAX_RETRIES=5 RETRY_BASE_DELAY_MS=2000 export PI_CODING_AGENT_DIR="${SCRATCH}/agent" PI_OFFLINE=1 PI_TELEMETRY=0 diff --git a/agent-review/instruction-files.txt b/agent-review/instruction-files.txt index 45c2d5c..df464c8 100644 --- a/agent-review/instruction-files.txt +++ b/agent-review/instruction-files.txt @@ -29,8 +29,7 @@ # Shared conventions. AGENTS.md AGENTS.override.md -# Named by the trusted AGENTS.md as a per-machine override; ignored by -# .gitignore, but a PR can still force-add it. +# A per-machine override, normally in .gitignore; a PR can still force-add it. AGENTS.local.md CLAUDE.md CLAUDE.local.md diff --git a/agent-review/lib/agent_review/authorize.py b/agent-review/lib/agent_review/authorize.py index 6d92954..93cebac 100644 --- a/agent-review/lib/agent_review/authorize.py +++ b/agent-review/lib/agent_review/authorize.py @@ -298,7 +298,7 @@ def choose_model(keyed: bool, model: str, harness: str) -> str: def parse_api_bases(text: str) -> list[str]: - """``grep -v -e '^#' -e '^$'``, one entry per line.""" + """The entries, one per line; empty lines and lines starting with '#' are skipped.""" return [line for line in text.split("\n") if line != "" and not line.startswith("#")] @@ -350,11 +350,7 @@ def decide( pr_shas: Callable[[str, str], tuple[str, str]] = lookup_pr_shas, permission: Callable[[str, str], str] = lookup_permission, ) -> list[tuple[str, str]]: - """The outputs of an allowed run, in order; raises Fail or Skip. - - The checks run in a fixed order, which tests/test-authorize.sh pins, so - that the same input stops at the same check. - """ + """The outputs of an allowed run, in order; raises Fail or Skip.""" # This workflow's own commit, from which every trusted file is read. trusted_repo, trusted_sha, repo = env["TRUSTED_REPO"], env["TRUSTED_SHA"], env["REPO"] if not validate.matches(REPO, trusted_repo): @@ -365,7 +361,6 @@ def decide( raise Fail(f"Invalid repository '{repo}'.") notice(f"Agent review workflow {trusted_repo}@{trusted_sha}; caller {repo}@{env['CALLER_WF_SHA']}.") - # Harness and key mode. harness = env["IN_HARNESS"] keyed = key_mode(harness) check_shared_key(env["HAS_SHARED_KEY"]) diff --git a/agent-review/lib/agent_review/gh.py b/agent-review/lib/agent_review/gh.py index a93fe57..2f6c73f 100644 --- a/agent-review/lib/agent_review/gh.py +++ b/agent-review/lib/agent_review/gh.py @@ -4,8 +4,8 @@ ``authorize`` and ``publish-comment`` reach it (and with it the job token, which ``gh`` reads from ``GH_TOKEN``; it never passes through Python). ``gh`` rather than ``urllib``: the token stays out of this process, proxy -variables are not honoured by accident, and the tests' fake ``gh`` on -``PATH`` keeps working. +variables are not honoured by accident, and the tests can put a fake +``gh`` on ``PATH``. Keep the projections in ``gh --jq``: a PR object or a comment body is untrusted, so it is handled only by gh's JSON decoder and our code never diff --git a/agent-review/lib/agent_review/publish_comment.py b/agent-review/lib/agent_review/publish_comment.py index 9cb9a35..d2dbc23 100644 --- a/agent-review/lib/agent_review/publish_comment.py +++ b/agent-review/lib/agent_review/publish_comment.py @@ -58,7 +58,7 @@ # comment adds at most about 1 KB to the listing (300 comments with 60 KB # first lines would otherwise pass runner's output cap). Many thousands of # comments still can, or hit the time limit: 'post' then fails. Longer -# than any marker (at most 150 characters), so the comparison stays exact. +# than any marker ('post' checks it), so the comparison stays exact. FIRST_LINE_CHARS = 256 LISTING_JQ = f'.[] | [.id, .user.login, (.body | split("\\n") | .[0] | .[0:{FIRST_LINE_CHARS}])] | @tsv' ASCII_WHITESPACE = " \t\n\v\f\r" diff --git a/agent-review/lib/agent_review/run_review.py b/agent-review/lib/agent_review/run_review.py index 2b5466a..5d4d6dc 100644 --- a/agent-review/lib/agent_review/run_review.py +++ b/agent-review/lib/agent_review/run_review.py @@ -29,12 +29,9 @@ Exit codes: 0 review written (or, for ``fetch``, the checkout prepared), 2 the harness ran but produced no review, 1 anything else. -The harness contract (harnesses/README.md): ``bash /run.sh`` under -``timeout``, in the checkout, with ``PROMPT_FILE``, ``REPO_DIR``, -``OUT_DIR``, ``CONTEXT_DIR``, ``MODEL``, ``HARNESS_PREFIX``, ``PR_NUMBER`` -and ``STUB_PADDING_KIB`` set, and the run's ``HOME``, ``TMPDIR`` and forced -``GIT_*`` variables on top of the inherited environment; exit 0 means a -review, 2 none. +The harness runs as ``bash /run.sh`` under ``timeout``, in the +checkout; its environment and exit codes are the adapter contract in +harnesses/README.md. """ import contextlib diff --git a/agent-review/tests/python/test_files.py b/agent-review/tests/python/test_files.py index 696d6d2..03d062c 100644 --- a/agent-review/tests/python/test_files.py +++ b/agent-review/tests/python/test_files.py @@ -132,7 +132,7 @@ def growing_read(fd: int, n: int) -> bytes: def test_unsafe_file_error_old_form() -> None: - """Raising it with a message only still works; 'reason' is then 'other'.""" + """A message alone is enough; 'reason' is then 'other'.""" e = files.UnsafeFileError("x: refused") assert (str(e), e.reason, e.st) == ("x: refused", "other", None) assert isinstance(e, OSError) diff --git a/agent-review/tests/python/test_prompt.py b/agent-review/tests/python/test_prompt.py index 29f64f1..5678cb4 100644 --- a/agent-review/tests/python/test_prompt.py +++ b/agent-review/tests/python/test_prompt.py @@ -1,4 +1,4 @@ -"""agent_review.prompt: the PR title and body as data, caps, nonce delimiters, bash-identical rendering.""" +"""agent_review.prompt: the PR title and body as data, caps, nonce delimiters, rendering against a jq oracle.""" import json import pathlib @@ -12,7 +12,7 @@ AR_DIR = pathlib.Path(__file__).resolve().parents[2] -# The bash version's pipelines, run as the oracle on the same pr.json. +# Independent oracle: jq and iconv pipelines on the same pr.json. BASH_FIELDS = r""" set -euo pipefail clip() { head -c "$1" | { iconv -f UTF-8 -t UTF-8 -c 2>/dev/null || true; }; } @@ -180,8 +180,8 @@ def test_render_is_one_pass() -> None: def test_title_cannot_multiply_the_body() -> None: - """With sequential substitution, each '{{PR_BODY}}' in the title expanded the body: - 46 of them in a 512-byte title gave a prompt of about 774 KB.""" + """Sequential substitution would expand the body at each '{{PR_BODY}}' in the title: + 46 of them fit in a 512-byte title, for a prompt of about 774 KB.""" template = (AR_DIR / "prompt.md.tmpl").read_bytes() title = prompt.title_bytes("{{PR_BODY}}" * 46) body = prompt.body_bytes("b" * 20000) diff --git a/agent-review/tests/python/test_publish_comment.py b/agent-review/tests/python/test_publish_comment.py index 6217bb7..1e87a52 100644 --- a/agent-review/tests/python/test_publish_comment.py +++ b/agent-review/tests/python/test_publish_comment.py @@ -413,13 +413,13 @@ def comment(cid: int, login: str, body: str) -> dict[str, object]: def test_huge_foreign_first_lines_do_not_block_the_upsert(jq_gh: tuple[pathlib.Path, dict[str, str]]) -> None: - """300 comments with 60 KB first lines: the unbounded projection passed runner's 16 MiB cap.""" + """300 comments with 60 KB first lines: an unbounded projection would pass runner's output cap.""" directory, env = jq_gh huge = [comment(1000 + i, "some-user", "x" * 60000 + "\nrest") for i in range(300)] comments = [*huge, comment(42, "github-actions[bot]", f"{MARKER}\nold review")] path = directory / "comments.json" path.write_text(json.dumps(comments)) - # Negative control: the old projection's output is over the cap. + # Negative control: the unbounded projection's output is over the cap. old_jq = '.[] | [.id, .user.login, (.body | split("\\n") | .[0])] | @tsv' old = subprocess.run(["/usr/bin/jq", "-r", old_jq, str(path)], capture_output=True, check=True).stdout assert len(old) > runner.MAX_STDOUT_BYTES diff --git a/agent-review/tests/python/test_reset.py b/agent-review/tests/python/test_reset.py index 8057b19..2180781 100644 --- a/agent-review/tests/python/test_reset.py +++ b/agent-review/tests/python/test_reset.py @@ -419,7 +419,7 @@ def test_container_specs() -> None: @pytest.mark.parametrize("addendum", [b"{\xff{PR_BODY}}", b"notes \xc3"]) def test_load_config_rejects_an_addendum_that_is_not_utf8(tmp_path: pathlib.Path, addendum: bytes) -> None: - """'{\\xff{PR_BODY}}' passed a byte check, then clipping dropped the byte and formed a placeholder.""" + """'{\\xff{PR_BODY}}' passes a byte check for '{{'; clipping then drops the byte and forms a placeholder.""" with pytest.raises(Fatal, match=r"prompt-addendum\.md' is not valid UTF-8\."): reset.load_config(make_root(tmp_path, addendum=addendum)) diff --git a/agent-review/tests/python/test_run_review.py b/agent-review/tests/python/test_run_review.py index 3a51b47..f842064 100644 --- a/agent-review/tests/python/test_run_review.py +++ b/agent-review/tests/python/test_run_review.py @@ -384,7 +384,7 @@ def test_out_holds_only_run_reviews_files( def test_deep_history_deepens_the_fetch(tmp_path: pathlib.Path, upstream: Upstream) -> None: - """The merge base lies beyond the first fetch's depth (50), so the fetch deepens.""" + """The merge base lies beyond the first fetch's depth, so the fetch deepens.""" fork_sha, base_sha, head_sha = upstream.make(FORK, {}, {"AGENTS.md": "PR\n"}, depth=60) root = make_root(tmp_path / "root", rules="AGENTS.md\n") ws = make_ws(tmp_path / "ws", head=head_sha, base=base_sha) @@ -628,7 +628,7 @@ def test_pr_changing_an_intermediate_hop_fails_closed(tmp_path: pathlib.Path, up def test_out_that_cannot_be_emptied_is_replaced(tmp_path: pathlib.Path, upstream: Upstream) -> None: - """A read-only directory in out/ made removing out/ fail: no meta.json, a planted review left.""" + """A read-only directory in out/ makes removing out/ fail; out/ is replaced, so no planted review stays.""" _, base_sha, head_sha = upstream.make(FORK, {}, {}) root = make_root(tmp_path / "root") ws = make_ws(tmp_path / "ws", head=head_sha, base=base_sha) @@ -765,7 +765,7 @@ def test_base_symlink_to_an_uncovered_path_fails_closed( # noqa: PLR0917 (pytes def test_existing_case_fails_closed_under_wildcard_caller_patterns( tmp_path: pathlib.Path, upstream: Upstream, extra: str ) -> None: - """'.claude/skills -> ../skills' must fail whatever the caller's patterns (it passed under '*/x.md').""" + """'.claude/skills -> ../skills' must fail whatever the caller's patterns, wildcard ones included.""" fork = {**FORK, "skills/s.md": "x\n", ".claude/settings.json": "{}\n", ".claude/skills": "-> ../skills"} ws, log = fetch(tmp_path, upstream, fork, {"skills/s.md": "PR\n"}, extra=extra) assert_stopped(ws, log) diff --git a/agent-review/tests/python/test_sanitize.py b/agent-review/tests/python/test_sanitize.py index 36fd4e4..bb906a2 100644 --- a/agent-review/tests/python/test_sanitize.py +++ b/agent-review/tests/python/test_sanitize.py @@ -1,10 +1,9 @@ """agent_review.sanitize: the review sanitiser of publish-comment (invariant 5). The oracles here are independent of the module's tables: the invisible -characters are the bash version's UTF-8 byte pattern, copied verbatim and -matched on each character's encoding, plus Unicode category Cf from -``unicodedata``. The property tests use seeded ``random`` (no extra -dependency) over random and adversarial inputs. +characters are a UTF-8 byte pattern matched on each character's encoding, +plus Unicode category Cf from ``unicodedata``. The property tests use +seeded ``random`` (no extra dependency) over random and adversarial inputs. """ import random @@ -19,12 +18,12 @@ ZWSP, ZWJ = "\u200b", "\u200d" MARKER = "`) and link reference definitions (`[label]: url`) are broken up too; character references are escaped (`@` and `@` would become mentions, `‏` an invisible character; without HTML, a named reference needs its `;`); `@mentions` are neutralised with a zero-width joiner; the length is capped, never inside a character or a neutralisation, and the comment says so if and only if content was cut. Rendering needs no token. The marker is matched only on the first line of the bot's own comments, never with `--edit-last`, because other tools (such as PR Agent) may post as the same bot; the comment listing is a `gh --jq` projection (id, login, and at most the first 256 characters of the first line, so that a long comment adds at most about 1 KB to it; a pull request with many thousands of comments can still exceed the output cap or the time limit, and then `post` fails without posting), so the comment bodies are handled only by `gh`'s JSON decoder and our code receives only the projected fields. In `publish`, the review never reaches a log: the rendered body goes to a file, then to the comment or, in a dry run, to the run summary; `post` prints only the comment URL, and `gh`'s errors prefixed and with `##[` broken up. +05. **Write tokens exist only in `publish`**, which runs no model and no PR code, and treats the review as hostile text. [`sanitize.py`](../agent-review/lib/agent_review/sanitize.py) states the exact rules and the reason for each: the review must be strict UTF-8; C0 controls other than tab and newline, DEL, and invisible characters are dropped; no raw HTML, comment end or link reference definition can form (GitHub strips attributes and hides some HTML content, and the review must not imitate the comment marker); character references are escaped (GitHub decodes `@` and `@` into mentions, `‏` into an invisible character); `@mentions` are neutralised; the length is capped, never inside a character or a neutralisation, and the comment says so if and only if content was cut. C1 controls (U+0080 to U+009F) pass: GitHub's Markdown render API shows each as a visible U+FFFD, and none forms a mention, tag or reference. Rendering needs no token. The marker is matched only on the first line of the bot's own comments, never with `--edit-last`, because other tools (such as PR Agent) may post as the same bot. The comment listing is a `gh --jq` projection (id, login and a bounded prefix of the first line), so comment bodies are handled only by `gh`'s JSON decoder (invariant 2); a pull request with many thousands of comments can still exceed the output cap or the time limit, and then `post` fails without posting. In `publish`, the review never reaches a log: the rendered body goes to a file, then to the comment or, in a dry run, to the run summary; `post` prints only the comment URL, and `gh`'s errors prefixed and with `##[` broken up. 06. **Harness, prompt and AWF configuration come from this workflow's own commit** (`job.workflow_repository` at `job.workflow_sha`, the commit the caller pinned, fetched as a tarball and checked to be the same in every job), never from the PR or the caller. **The caller's configuration** (inputs and the addendum) comes from the caller's workflow commit: the default branch under `pull_request_target`, the dispatched ref under `workflow_dispatch` (which the environment rule gates). **Instruction files** matching [`instruction-files.txt`](../agent-review/instruction-files.txt) (the central list; the fetch phase fails if it is missing or holds no pattern) or the caller's `instruction_files`, and every `rule_files` entry, at any depth, are reset to the version in the PR's **base commit** (or removed): that is the branch the PR targets, not necessarily the default one. The PR's versions are kept as data for the review. A pattern's directories are reset too, so a PR cannot keep its files reachable through a link such as `.opencode -> evil/`. Whether a pattern matches a path is always git's decision (`:(glob,icase)**/`), both in the reset and in the earlier check that some pattern covers each file the addendum names, so the two cannot disagree. Two post-conditions on the result then enforce the invariant, whatever the matching does. If either fails, the fetch phase stops before the prompt exists, with a message naming the path and the reason, and the run ends green with a "no review" warning (fail closed, advisory check): - every rule file and every file the addendum names (in backticks, with one of the listed extensions) is byte-identical to its base version or absent in both, with no symlinked parent directory; - - no symlink or gitlink remains where a pattern matches, at a directory pattern's directory, or at a directory leading to a pattern with `/`, except: - - a gitlink that is the base commit's own, with an empty directory (submodules are never fetched); - - a base symlink linking one instruction file or directory to another (`AGENTS.md -> CLAUDE.md`, `.claude/skills -> ../.agents/skills`), if its target is relative, inside the repository and covered by the reset; otherwise the agent would read the PR's version of the target (see [What remains risky](#what-remains-risky)); - - a base symlink standing only where a wildcard pattern expects a directory on the way (`docs/*/RULES.md`), if it leads to a regular file or to nothing, since no instruction file can lie below it. + - no symlink or gitlink remains where a pattern matches, at a directory pattern's directory, or at a directory leading to a pattern with `/`. The exceptions are links of the base commit itself through which the agent can reach nothing the reset does not cover: a base gitlink with an empty directory (submodules are never fetched), a base symlink from one instruction file or directory to another that the reset covers (`AGENTS.md -> CLAUDE.md`, `.claude/skills -> ../.agents/skills`), and a base symlink that stands only where a wildcard pattern expects a directory on the way (`docs/*/RULES.md`) and leads to a regular file or to nothing. Any other link stops the run (see [What remains risky](#what-remains-risky)). The exact conditions are in `verify_no_linked_directories` ([`reset.py`](../agent-review/lib/agent_review/reset.py)). `tests/test-run-review.sh` and `tests/test-instruction-coverage.sh` check both post-conditions, and [`test_run_review.py`](../agent-review/tests/python/test_run_review.py) runs the fetch phase with the reset subverted (a PR-version, added or deleted rule file, a symlinked parent) to show that they stop it. Under `pull_request` (caller test mode) the caller's configuration is PR content, so this invariant does not hold there. 07. **The `review` job starts no service on the host.** The sandbox can connect to any host port bound to `0.0.0.0` through AWF's network gateway (`172.30.0.1`); on a stock runner that is only `sshd`. No `services:` containers, no daemons started in a step. 08. **AWF's logs are read only from `$RUNNER_TEMP`** (`--proxy-logs-dir`, `--audit-dir`). Without `--proxy-logs-dir`, AWF moves them to `/tmp` after the run, where the sandbox can plant fake ones. 09. **Only AWF's OpenAI listener is configured**: never an `anthropic` target or `ANTHROPIC_API_KEY`. In AWF v0.29.12 the Anthropic listener's `POST /messages` is not counted by `maxTurns`, and the key breaks the entrypoint under `filesystem.allowWrite`. The run log shows `API proxy enabled: OpenAI=true, Anthropic=false`. 10. **Pinned**: actions by commit SHA, the runner image (`ubuntu-24.04`, which is the sandbox's userland since AWF chroots into the host filesystem), the AWF version, AWF images by digest (the setup action's `image-tag` output, taken from the attested release at run time), and each harness by exact version with an integrity check. Not pinned: the runner image's own updates, and the model behind its id. -11. **The sandbox's output cannot issue workflow commands**: every line of `awf` output is prefixed, so none starts with `::`; NUL bytes are dropped, and every `##[` in it is then broken up with a zero-width space, because the runner also accepts the legacy `##[command]` syntax anywhere in a line (verified: before this, a sandbox line `##[warning]…` became an annotation). Harness diagnostics go through `diag` in `common.sh`, which does the same. The stub prints such a line on stdout and through `diag` in every self-test run, also with a NUL between the two `#`, and the `check` job asserts that no annotation results; the structure test checks that every `awf` call sends stdout and stderr through the filter, that nothing else in its step can print, and that `diag` is the one filtered definition ([`workflow_structure.py`](../agent-review/tests/workflow_structure.py)). +11. **The sandbox's output cannot issue workflow commands**: every line of `awf` output is prefixed, so none starts with `::`; NUL bytes are dropped, and every `##[` in it is then broken up with a zero-width space, because the runner also accepts the legacy `##[command]` syntax anywhere in a line (verified: unfiltered, a sandbox line `##[warning]…` becomes an annotation). Harness diagnostics go through `diag` in `common.sh`, which does the same. The stub prints such a line on stdout and through `diag` in every self-test run, also with a NUL between the two `#`, and the `check` job asserts that no annotation results; the structure test checks that every `awf` call sends stdout and stderr through the filter, that nothing else in its step can print, and that `diag` is the one filtered definition ([`workflow_structure.py`](../agent-review/tests/workflow_structure.py)). 12. **Per-job least privilege under the caller's ceiling**: top-level `permissions: {}`; `authorize`, `review` and `review-keyless` read contents and pull requests, `prepare` reads contents, `publish` adds `pull-requests: write` (the structure test checks that no other job can write). The caller grants exactly `contents: read` and `pull-requests: write`; a job asking for more fails every caller at startup, so a new permission is a breaking change. 13. **Python runs only as `/usr/bin/python3 -I -S -B /bin/`**: the standard library only, nothing from `PYTHON*` variables, the working directory, `site`, `sitecustomize` or `.pth` files, and no bytecode written. The root is `${RUNNER_TEMP}/trusted` in `authorize`, `prepare` and `publish`, and the root-owned `/opt/agent-review` in the review jobs. Entry points exit unless started with those flags; processes start from argument lists, with tool lookup and environment per trust zone (no process starts on the tainted host today; one that did would get an absolute program and a fixed environment); only `authorize` and `publish-comment` can reach the `gh` wrapper (which steps hold the token is decided by their `env:`); no Python file or Python shebang exists outside `lib/agent_review/` and `tests/` ([ADR 0004](adr/0004-python-runtime.md)). The structure test checks the call sites, the entry points, the imports and the tree ([`workflow_structure.py`](../agent-review/tests/workflow_structure.py)). @@ -223,7 +220,7 @@ Callers use `pull_request_target` because fork PRs get no secrets under `pull_re - **Live logs**: the review step's log shows the agent's output (prefixed) while it runs; it carries no secret. - **Central changes reach every caller that updates its pin.** Callers pin a full SHA and review Dependabot's update PRs; releases flag new permissions, inputs, ceilings, endpoints, harness pins and AWF versions as breaking. The protection of `main` (pull request with an approval, no force pushes) does not by itself protect what callers pin: tags, releases and commits pushed only to a fork are outside it, and required status checks are a separate setting. Callers must check each pin ([Pinning and updating](#pinning-and-updating)). - **Compromise of this repository's `main` or of one admin account.** Admins cannot bypass the ruleset but can edit it. A SHA-pinned caller is unaffected until it updates its pin, so the review of the pin update is the only gate, and the central diff is not shown in the caller's PR. A tag- or branch-pinned caller is hit on its next run. A malicious central commit gets, in a caller: the inference key (in `review`), `pull-requests: write` (in `publish`), and write access to the caller's Actions cache in the default-branch scope under `pull_request_target`, which other workflows restore. It gets no other secret, thanks to the explicit mapping. -- **Tag and branch pins.** The ref is resolved once per run; every job fetches by SHA and checks that it runs the recorded commit, so one run never mixes commits (verified in the spike for tag and branch pins). A re-run after the tag moved re-resolves the called workflow's tag (it runs the moved commit) while keeping the caller's commit, so a tag pin is not reproducible, not even across attempts of one run; only SHA pins are. +- **Tag and branch pins.** The ref is resolved once per run; every job fetches by SHA and checks that it runs the recorded commit, so one run never mixes commits (verified for tag and branch pins). A re-run after the tag moved re-resolves the called workflow's tag (it runs the moved commit) while keeping the caller's commit, so a tag pin is not reproducible, not even across attempts of one run; only SHA pins are. - **Inputs are as trusted as the caller's workflow file** on its default branch. Never derive `environment`, `model`, `rule_files`, `instruction_files`, `prompt_addendum`, `label` or `api_base` from an event payload, a dispatch input or a repository variable: whoever can change a variable needs no review. The endpoint allowlist limits where the key can go, but not the other inputs. - **Caller test mode** (`pull_request`, `stub`): the caller's workflow file, inputs, rule files and addendum are PR content there, and fork PRs are protected by GitHub's rules (read-only token, no secrets), not by this workflow. It proves the plumbing only, never the reset invariant. - **The self-test's "nothing can be spent or posted"** holds inside the reviewed file: stub, keyless job, forced dry run. For a fork or branch PR of this repository the file itself is the PR's, so the guarantee there is GitHub's fork rules plus the absence of secrets in this repository, not these checks. **Never store a key or any secret in this repository**: keyed tests run from a separate test caller. @@ -244,13 +241,12 @@ Callers use `pull_request_target` because fork PRs get no secrets under `pull_re - _the `review` job reported no step: it never got a runner, or its runner was lost_: for the keyed job the usual cause is that the environment refused it, through one of its protection rules: the deployment branch rule (a keyed dispatch from a branch other than the default one), a required reviewer who rejected or did not answer, or another rule. GitHub shows that as an annotation on the `review` job and as a failed deployment; the key was then not used and there are no sandbox logs. See [Required settings](#required-settings-in-the-calling-repository), item 1. A runner lost during the job (out of memory, disk full, shut down) reports no step either, and cannot be told apart from here; the job's own page shows which it was. `publish` also shows an `Artifact not found` error annotation from its download step; it is a consequence, not the cause. The same message for the `review-keyless` job, which has no environment, means that it got no runner or lost it. - _the review job was cancelled before it reported a step_: someone cancelled the run or, for the keyed job only, a newer review request for the same pull request replaced this one in its queue. -**Slow or missing keyed reviews: requests that stall.** A request to the inference service sometimes gets no answer for minutes. In the release validation, four keyed reviews in a row took 17 to 19 of the 20 minutes of `harness_timeout_minutes`. The proxy log of one of them shows why: two requests ended by the harness after 300 s without response headers, a third answered after 185 s, then a normal review of two to three minutes. The other three had the same duration and are assumed to have had the same cause. What the adapters do about it since `v0.1.1`: +**Slow or missing keyed reviews: requests that stall.** A request to the inference service sometimes gets no answer for minutes: keyed reviews have taken 17 to 19 of the 20 minutes of `harness_timeout_minutes`; the proxy log of one of them shows two requests ended after 300 s without response headers and one answered after 185 s (the others are assumed to share the cause). Each adapter bounds these waits without shortening how long a run waits for a silent service; the values and their reasons are in its `run.sh`: -- A **streamed response that stops** is ended and the request retried, after 300 s without an event in opencode (its default was 900 s, most of the time limit) and 240 s in Pi (300 s). A response that keeps sending is never cut, however long it takes. The same wait applies between the response headers and the first event, where a service that queues an accepted request, or a model that thinks before its first token, is silent too; that is why it is not shorter. -- **Pi** also ends a request that gets **no response headers** within 240 s (it has one setting for both waits), and retries up to 5 times instead of 3, so a run waits for a silent service as long as before, up to the harness time limit. -- **opencode** keeps its 300 s wait for response headers. It retries a timed-out request at most 3 times per run, a limit that cannot be configured, so a run can wait 4 × that time; a shorter wait would end reviews that succeed today after a long silence. +- A **streamed response that stops** is ended and the request retried, after `CHUNK_TIMEOUT_MS` in opencode and `IDLE_TIMEOUT_MS` in Pi. A response that keeps sending is never cut, however long it takes. The same wait applies between the response headers and the first event, where a service that queues an accepted request, or a model that thinks before its first token, is silent too; that is why it is not shorter. +- A request that gets **no response headers** is ended and retried after `HEADER_TIMEOUT_MS` in opencode, at most 3 times per run (a limit that cannot be configured), and after `IDLE_TIMEOUT_MS` in Pi, up to `MAX_RETRIES` times. -No wait is much shorter than before, except opencode's for a stream that stops, on purpose: the validation's one slow answer needed 185 s, and it is not known whether a new request would have been answered sooner. So a review that meets such a silence is still slow, and when the service answers nothing for longer than about 15 minutes, it still ends at the harness time limit with the "no review" warning (the log says `status 'timeout'`; the run stays green). The limit is a ceiling, and raising it is a breaking change. Re-request the review. In short: a stream that stalls is recovered; a long silence before the first response headers still makes the review slow, or ends it without a review. That silence is the service holding requests, which no setting here can shorten: if it happens regularly, raise it with the service's operators (one possible cause, not verified, is a rate limit of the key that holds requests instead of refusing them). Every retried request counts against the run's request limits (`requests_per_hour`). One that ends before any response does not count against `max_turns`; whether a stream cut after its headers does was not checked. +So a stream that stalls is recovered, but a long silence before the first response headers still makes the review slow, and when the service answers nothing for longer than about 15 minutes the run ends at the harness time limit with the "no review" warning (the log says `status 'timeout'`; the run stays green). Re-request the review. That silence is the service holding requests, which no setting here can shorten: if it happens regularly, raise it with the service's operators (one possible cause, not verified, is a rate limit of the key that holds requests instead of refusing them). The time limit is a ceiling, and raising it is a breaking change. Every retried request counts against the run's request limits (`requests_per_hour`). One that ends before any response does not count against `max_turns`; whether a stream cut after its headers does was not checked. Known limitation (no workaround in the workflow): @@ -260,41 +256,36 @@ Known limitation (no workaround in the workflow): **Recommended**: `opencode` with `zai-org/GLM-5.3-Flash`; `pi` with the same model is the alternative (more findings per PR, 1.5–2× the tokens). `zai-org/GLM-5.3` (non-Flash) with opencode is not recommended at the current caps: on real PRs it produced no review, timing out at the 20-minute harness limit. This is from a quality evaluation of dry runs on three merged PRs of a large Python project. -Ceilings, changed by a reviewed PR here; callers can only lower the first four ([`awf.yaml`](../agent-review/awf.yaml)): 100 requests per hour and 30 per minute to the API proxy (the per-run bound), `apiProxy.maxTurns` 80 (stops a well-behaved harness; opencode also stops itself after 35 steps, Pi has no cap of its own), 20 minutes for the harness, 25 for AWF's `agentTimeout`, 30 for the review step and 45 for the job. AWF's AI-credit cap is not used, since it prices CSCS models with an estimate, after the response. +Ceilings, changed only by a reviewed PR here: the request rates to the API proxy (the per-run bound), `apiProxy.maxTurns` and AWF's `agentTimeout` in [`awf.yaml`](../agent-review/awf.yaml), and the time limits of the review step and job in the workflow. Callers can lower the request rates, the turn cap and the harness time limit (see [Inputs](#inputs)). `maxTurns` stops a well-behaved harness; opencode also stops itself earlier (`MAX_STEPS` in its `run.sh`), Pi has no cap of its own. AWF's AI-credit cap is not used, since it prices CSCS models with an estimate, after the response. -AWF's runtime model catalogue is disabled (`apiProxy.modelCatalogue.enabled: false`): otherwise its API-proxy sidecar makes ~7 GETs per run to `api.github.com` (`github/gh-aw-firewall`'s pricing snapshot). Those carry no data about the run and no token, but the AI-credit accounting they feed is unused here. Note that the inference host (added via `baseUrlEnv`) is marked _sensitive_ by AWF and is therefore excluded from Squid's `access.log` and `audit.jsonl`, so model traffic does not appear in the egress logs by design; it is visible only in the API-proxy's own `token-usage.jsonl`. +AWF's runtime model catalogue is disabled ([`awf.yaml`](../agent-review/awf.yaml) says why). The inference host (added via `baseUrlEnv`) is marked _sensitive_ by AWF and is therefore excluded from Squid's `access.log` and `audit.jsonl`, so model traffic does not appear in the egress logs by design; it is visible only in the API-proxy's own `token-usage.jsonl`. -The `stub` harness makes no model call and posts a fixed review containing hostile content; it is for testing the pipeline only. It also prints the probe line of `bin/probe` (the Python runtime) on the host in `prepare` and inside the sandbox. +The `stub` harness makes no model call and posts a fixed review containing hostile content; it is for testing the pipeline only. ## Harness adapters -A harness is a directory `agent-review/harnesses//`; the name must also be added to the harness allowlist in [`lib/agent_review/authorize.py`](../agent-review/lib/agent_review/authorize.py) (`KEYED_HARNESSES` or `KEYLESS_HARNESSES`), as keyed (it calls a model; `wire` `openai-chat`) or keyless (`wire` `none`; both review jobs check that the two agree), and callers may add it to their `workflow_dispatch` choice. The contract is in [`harnesses/README.md`](../agent-review/harnesses/README.md): - -- `install.sh ` runs in `prepare` and installs an exact version, integrity-checked, into ``, writing the version to `/VERSION`, without executing any harness code. The prefix is unpacked to `/opt/agent-review/harness/` and must run from there without network access. -- `run.sh` runs inside the sandbox, from the PR checkout, with `PROMPT_FILE`, `REPO_DIR`, `OUT_DIR`, `CONTEXT_DIR`, `MODEL`, `HARNESS_PREFIX` and `PR_NUMBER` set, plus AWF's `AWF_API_PROXY_OPENAI_URL`. It checks the harness version, keeps its configuration in a scratch home under `$TMPDIR` (in the workspace), disables updates, telemetry and sharing, sets the harness's request timeouts (a request that stalls must end and be retried well within the harness time limit, without shortening how long the run waits for a silent service; see [Troubleshooting](#troubleshooting)), and writes `$OUT_DIR/review.md`. Exit codes: 0 review written, 2 no review, anything else a failure; it must return 2, not 0, when the harness exits 0 without a real answer. -- `wire` says whether the harness calls a model: `openai-chat` (through AWF's OpenAI listener) or `none`. -- File names the harness reads as instructions or configuration, at any depth, go into `instruction-files.txt`. - -The [adapters README](../agent-review/harnesses/README.md) compares the harnesses (version, wire, how the repository's own agent configuration is disabled, turn cap); each adapter's `README.md` explains its pins, upgrades and isolation. In short: both use the OpenAI chat API on AWF's OpenAI listener, the only one configured (AWF v0.29.12 must not get `ANTHROPIC_API_KEY`: its Anthropic listener's `POST /messages` escapes the turn count, and its entrypoint fails under `filesystem.allowWrite`); opencode and Pi have switches that ignore the repository's agent configuration (which can otherwise execute code from the PR). +A harness is a directory `agent-review/harnesses//` plus an entry in the harness allowlist of [`lib/agent_review/authorize.py`](../agent-review/lib/agent_review/authorize.py), as keyed (it calls a model) or keyless; callers may add it to their `workflow_dispatch` choice. The [adapters README](../agent-review/harnesses/README.md) holds the contract (`install.sh`, `run.sh`, `wire`) and compares the harnesses; each adapter's `README.md` explains its pins, upgrades and isolation. File names a harness reads as instructions or configuration, at any depth, go into [`instruction-files.txt`](../agent-review/instruction-files.txt). ## Testing changes This repository's [`self-test.yml`](../.github/workflows/self-test.yml) runs on every pull request, on `main`, weekly and on demand: -- pre-commit (actionlint, shellcheck, ruff, mypy on `agent-review/lib/`, file checks) and [zizmor](https://docs.zizmor.sh/) on the workflows; -- the script tests: `agent-review/tests/test-collect-result.sh`, `test-publish-comment.sh`, `test-instruction-coverage.sh` (offline) and `test-run-review.sh` (fetches real commits from github.com, no AWF; includes the reset post-condition); -- the unit tests of `authorize` ([`test-authorize.sh`](../agent-review/tests/test-authorize.sh), offline: every input, the event and harness matrix, the writer check) and the [workflow structure test](../agent-review/tests/test-workflow-structure.py), which also enforces the Python runtime rules of invariant 13 ([`workflow_structure.py`](../agent-review/tests/workflow_structure.py) lists every check). The script suites are the black-box specification of each entry point's command-line contract (arguments, exit codes, outputs, notices); they run each `bin/` entry point through `run_entry` in [`tests/lib.sh`](../agent-review/tests/lib.sh), with the production Python command line; -- the `python` job: the pytest suites in [`tests/python/`](../agent-review/tests/python/) (the package's helpers; the entry points' own cases, such as `collect-result`'s simulated swaps between check and open; the review sanitiser against an independent oracle on every code point, and property tests over random and adversarial reviews: no marker, no live mention or reference, no `Cf` or listed invisible character except those the sanitiser inserts, where it inserts them; `run-review`'s reset, prompt rendering and review collection, also through its entry point on crafted pull requests served from a local repository; each Python entry point run with the production command line from a directory holding a planted `json.py`, `agent_review/` and `sitecustomize.py`, with hostile `PYTHONPATH`, `PYTHONSTARTUP` and `PYTHONHOME`; the flag guard; the structure checks on crafted inputs) and mypy, with the test tools of the hash-pinned [`requirements.txt`](../agent-review/tests/requirements.txt). Locally: `python3 -B -m pytest` and `python3 -m mypy` from the repository root; +- pre-commit ([`.pre-commit-config.yaml`](../.pre-commit-config.yaml)) and [zizmor](https://docs.zizmor.sh/) on the workflows; +- the script suites in [`agent-review/tests/`](../agent-review/tests/) (`test-*.sh`), the black-box specification of each entry point's command-line contract (arguments, exit codes, outputs, notices): they run each `bin/` entry point through `run_entry` in [`tests/lib.sh`](../agent-review/tests/lib.sh), with the production Python command line. All are offline except `test-run-review.sh`, which fetches real commits from github.com (no AWF); +- the [workflow structure test](../agent-review/tests/test-workflow-structure.py), which enforces the structural parts of the invariants, the Python runtime rules of invariant 13 included ([`workflow_structure.py`](../agent-review/tests/workflow_structure.py) lists every check); +- the `python` job: the pytest suites in [`tests/python/`](../agent-review/tests/python/) and mypy, with the test tools of the hash-pinned [`requirements.txt`](../agent-review/tests/requirements.txt). They cover the package's helpers, cases the script suites cannot reach (such as `collect-result`'s simulated swaps between check and open), the review sanitiser against an independent oracle and with property tests, `run-review` on crafted pull requests served from a local repository, each entry point run with the production command line in a hostile environment (planted modules in the working directory, hostile `PYTHON*` variables), and the structure checks on crafted inputs. Locally: `python3 -B -m pytest` and `python3 -m mypy` from the repository root; - the whole pipeline through a **local** call (`uses: ./.github/workflows/agent-review.yml`), so the files fetched at `job.workflow_sha` are the commit under test, with the `stub` harness (keyless job), no key and a forced dry run, against a fixed public PR of another repository (`test_repository`); the dry-run comment is in the run summary; -- the `check` job: the keyed job skipped and the keyless one run, nothing posted, the sandbox's allowed domains, the clamped caps, no key in AWF, the reset post-condition, no deployment for the commit, `gh` found as `/usr/bin/gh` under the publish steps' fixed `PATH: /usr/bin:/bin` (the self-test never posts), and the probe's line from the host (`prepare`) and from inside the sandbox: Python 3.12, `/usr/bin/python3`, the isolation flags, no `site`, only the standard library and the trusted `lib/` on `sys.path`. +- the `check` job: the keyed job skipped and the keyless one run, nothing posted, the sandbox's allowed domains, the clamped caps, no key in AWF, the reset post-condition, no deployment for the commit, `gh` found as `/usr/bin/gh` under the publish steps' fixed `PATH` (the self-test never posts), and the probe's line from the host (`prepare`) and from inside the sandbox: the same interpreter, the isolation flags, no `site`, only the standard library and the trusted `lib/` on `sys.path`. The self-test path (`test_repository`, and the `push` and `schedule` events) is accepted only with the `stub` harness when `job.workflow_repository` equals the calling repository: this repository, or a fork or copy calling its own file, which is harmless (stub, no key, dry run). It skips the writer check, since nothing can be spent or posted; the intent is that Dependabot's and outside contributors' PRs can run it too (not yet observed: their read-only token might still fail the permission ceiling at startup). -The self-test is a local call, where `job.workflow_repository` and `job.workflow_sha` equal the caller's own `github.*` values, so it cannot notice a regression that confuses them (such a regression fails closed); only a cross-repository call can (see [Release checklist](#release-checklist)). To try an adapter without a key, run `install.sh `, then `run-review` with `AWF_API_PROXY_OPENAI_URL` pointing at a local fake OpenAI server. [`tests/test-harness-stall.sh`](../agent-review/tests/test-harness-stall.sh) does this for the request timeouts, with a server that stalls ([`tests/fake_inference.py`](../agent-review/tests/fake_inference.py)): no response headers, a stream that stops, a slow stream that must not be cut, a request answered only after 185 s, the same wait between the headers and the first event, and a service that answers nothing for 17 minutes (more than Pi's default of 3 retries can sit out). It runs the real harnesses on the local machine, outside any sandbox, so it is deliberately not part of the self-test (whose `adapters` job only installs them). Run it locally after changing an adapter's timeouts or its pinned version: `bash agent-review/tests/test-harness-stall.sh` (about 18 minutes, the real values), or with `--fast` (about a minute, every timeout and retry delay divided by 30: the behaviour, not the values); add `opencode` or `pi` to run one harness. It needs `jq`, `npm`, `curl` and `python3`, and downloads about 400 MB. +The self-test is a local call, where `job.workflow_repository` and `job.workflow_sha` equal the caller's own `github.*` values, so it cannot notice a regression that confuses them (such a regression fails closed); only a cross-repository call can (see [Release checklist](#release-checklist)). + +To try an adapter without a key, run `install.sh `, then `run-review` with `AWF_API_PROXY_OPENAI_URL` pointing at a local fake OpenAI server. [`tests/test-harness-stall.sh`](../agent-review/tests/test-harness-stall.sh) does this for the request timeouts, with a server that stalls ([`tests/fake_inference.py`](../agent-review/tests/fake_inference.py)); its header lists the cases, the options and what it needs. It runs the real harnesses on the local machine, outside any sandbox, so it is deliberately not part of the self-test (whose `adapters` job only installs them): run it locally after changing an adapter's timeouts or its pinned version. ### Caller test mode -Any caller may call the workflow under `pull_request` with the **`stub`** harness only (the job in [Calling it](#calling-it)): the dry run is forced by the event name, there is no writer check, and the run uses the keyless job, so it needs no key and no environment and is not limited to the default branch (run from another repository in the release validation; not observed for fork PRs, whose read-only token might fail the permission ceiling at startup). If the caller's Actions event policy for its workflow file exists, it must list `pull_request` too: `allowed_events` is an exhaustive allowlist. A keyed harness is rejected under `pull_request` (and under every event but `pull_request_target` and `workflow_dispatch`), and `test_repository` stays limited to this repository. A notice says what follows: the caller's workflow file, its inputs, rule files and addendum are **PR content** in this mode (the caller's `github.workflow_sha` is the PR's merge commit). The mode proves the plumbing (the cross-repository call, the inputs, the addendum fetch, the sandbox, the dry-run rendering), never the reset invariant. +Any caller may call the workflow under `pull_request` with the **`stub`** harness only (the job in [Calling it](#calling-it)): the dry run is forced by the event name, there is no writer check, and the run uses the keyless job, so it needs no key and no environment and is not limited to the default branch (verified from another repository; not observed for fork PRs, whose read-only token might fail the permission ceiling at startup). If the caller's Actions event policy for its workflow file exists, it must list `pull_request` too: `allowed_events` is an exhaustive allowlist. A keyed harness is rejected under `pull_request` (and under every event but `pull_request_target` and `workflow_dispatch`), and `test_repository` stays limited to this repository. A notice says what follows: the caller's workflow file, its inputs, rule files and addendum are **PR content** in this mode (the caller's `github.workflow_sha` is the PR's merge commit). The mode proves the plumbing (the cross-repository call, the inputs, the addendum fetch, the sandbox, the dry-run rendering), never the reset invariant. ## Releases diff --git a/docs/pr-agent.md b/docs/pr-agent.md index 67bb76d..37ff177 100644 --- a/docs/pr-agent.md +++ b/docs/pr-agent.md @@ -5,7 +5,7 @@ The reusable `PR Agent` workflow ([`.github/workflows/pr-agent.yml`](../.github/ An adopting repository adds a small **caller workflow** that calls this one pinned by commit SHA, and keeps its own triggers, environment, key, event policy, `.pr_agent.toml` and review rules. The design is in [ADR 0003](adr/0003-pr-agent-reusable-workflow.md). > [!NOTE] -> **Status: `v0.1.0`, the first release.** The workflow has run through this repository's self-test (a local call in dry run, which never starts the keyed job) and from a separate test caller with a real key: a posted review, `pull_request_target` and `issue_comment` runs (`/review`), and refusals for a non-writer's PR, a non-writer's comment and a `--` argument. The caller tests recorded in the PR that added it (caller test mode, with a real key) covered a refused environment, a missing and a wrong key, forced timeouts, and the failure comment's update and removal. It ships in `v0.1.0` together with the agent review; see the [release checklist](#release-checklist). +> **Status: `v0.1.0`, the first release.** The workflow has run through this repository's self-test (a local call in dry run, which never starts the keyed job) and from a separate test caller with a real key: a posted review, `pull_request_target` and `issue_comment` runs (`/review`), and refusals for a non-writer's PR, a non-writer's comment and a `--` argument. The caller tests recorded in the pull request that added it ([caller test mode](#caller-test-mode), real key) covered a refused environment, a missing and a wrong key, forced timeouts, and the failure comment's update and removal. See the [release checklist](#release-checklist). ## Calling it @@ -134,7 +134,7 @@ Callers use `pull_request_target` because fork PRs get no secrets under `pull_re - The step limit is `ceil(chain × ai_timeout / 60) + 2` minutes, so a model that times out is not retried: the next one is tried. `Resolve models` rejects a chain whose step limit plus two minutes exceeds the job's 45 minutes, since a job timeout is a cancellation, which `continue-on-error` does not cover. A rejected request (429, 5xx) is retried twice on the same model first (`num_retries`); slow rejections can still use up the step limit, which the failure comment then reports. - `enable_large_pr_chunking` in `.pr_agent.toml` sends the chunks in parallel, so it does not extend the step time. - `output_run_details = true` in `.pr_agent.toml` (a `[config]` key, as is `repo_context_files`) makes the review name the model that answered, so a fallback answer is visible. It also shows the tokens, the time and the number of AI calls. -- Run time and tokens depend on the size of the PR and on the endpoint's latency. A tiny PR takes about 2k input tokens and one call; larger diffs and the review rules in `repo_context_files` raise it (13–17k in earlier tests). In periods of slow inference a single call takes several minutes (about 4.5 to 6 minutes in testing), so a run of a few minutes is not a failure; size `ai_timeout` for the slowest case. +- Run time and tokens depend on the size of the PR and on the endpoint's latency. A tiny PR takes about 2k input tokens and one call; larger diffs and the review rules in `repo_context_files` raise it (13–17k in tests). In periods of slow inference a single call takes several minutes (about 4.5 to 6 minutes in testing), so a run of a few minutes is not a failure; size `ai_timeout` for the slowest case. ### Reading a run's log @@ -148,8 +148,8 @@ Callers use `pull_request_target` because fork PRs get no secrets under `pull_re This repository's [`self-test.yml`](../.github/workflows/self-test.yml) runs on every pull request, on `main`, weekly and on demand: -- pre-commit (actionlint, shellcheck) and zizmor on the workflows; -- the script tests: [`test-authorize.sh`](../pr-agent/tests/test-authorize.sh) (permission levels, API errors, the event matrix, inputs, setting arguments, long comments), [`test-command-filter.py`](../pr-agent/tests/test-command-filter.py) (differential, against PR Agent 0.50.0's parser), [`test-resolve-models.sh`](../pr-agent/tests/test-resolve-models.sh) (every validation and the derived timeout), [`test-report-outcome.sh`](../pr-agent/tests/test-report-outcome.sh) (0, 1 and several comments, success and failure, job results) and the [structure test](../pr-agent/tests/test-workflow-structure.py); +- pre-commit and zizmor on the workflows; +- the script tests: [`test-authorize.sh`](../pr-agent/tests/test-authorize.sh) (permission levels, API errors, the event matrix, inputs, setting arguments, long comments), [`test-command-filter.py`](../pr-agent/tests/test-command-filter.py) (differential, against a copy of the pinned image's comment parser), [`test-resolve-models.sh`](../pr-agent/tests/test-resolve-models.sh) (every validation and the derived timeout), [`test-report-outcome.sh`](../pr-agent/tests/test-report-outcome.sh) (0, 1 and several comments, success and failure, job results) and the [structure test](../pr-agent/tests/test-workflow-structure.py); - that the pinned image digest exists, and a warning if its tag has moved; - the keyless path through a **local** call with `test_pr` (this repository's merged PR 1, forced dry run): `authorize` and `Resolve models` run on the commit under test, `pr-agent` and `report` are skipped, and no deployment is recorded.