diff --git a/.github/workflows/agent-review.yml b/.github/workflows/agent-review.yml index d28af3b..2e23eea 100644 --- a/.github/workflows/agent-review.yml +++ b/.github/workflows/agent-review.yml @@ -361,6 +361,10 @@ jobs: outcome: ${{ steps.agent.outcome }} exit_code: ${{ steps.agent.outputs.exit_code }} skipped: ${{ steps.key.outputs.skipped }} + # Empty if the job reported no step: GitHub ended it before it got a + # runner (refused by the environment, or cancelled while queued), or + # the runner was lost. 'publish' then says so. + started: ${{ steps.started.outputs.started }} env: &review-env # The sandbox's working area. AWF mounts the workspace read-write, so # everything under it is untrusted once the sandbox has run. @@ -372,6 +376,11 @@ jobs: # the host either (no 'services:', no daemon in a step): the sandbox # reaches every host port bound to 0.0.0.0 through AWF's network gateway. steps: + - &mark-started + name: Record that the job started + id: started + run: echo "started=true" >> "$GITHUB_OUTPUT" + - *fetch-trusted # Caller configuration: the validated inputs, and the addendum from the @@ -702,6 +711,7 @@ jobs: outputs: *review-outputs env: *review-env steps: + - *mark-started - *fetch-trusted - *fetch-config - *prepare-inputs @@ -822,23 +832,34 @@ jobs: { echo "result=posted"; echo "comment_url=${url}"; } >> "$GITHUB_OUTPUT" # A failed or rejected review is a warning, not a red run: the check is - # advisory. + # advisory. 'publish-comment explain' words the reason from the review + # job's result and outputs only (no token, nothing from the review): a + # job that reported no step (refused by the environment's protection + # rules, cancelled while queued, or its runner lost) has no sandbox + # logs to point at. At most one of the two review jobs ran. - name: Report a missing review if: steps.render.outputs.result == 'missing' || steps.render.outputs.result == 'invalid' env: RESULT: ${{ steps.render.outputs.result }} + KEYED: ${{ needs.authorize.outputs.keyed }} + REVIEW_RESULT: ${{ needs.authorize.outputs.keyed == 'true' && needs.review.result || needs.review-keyless.result }} + STARTED: ${{ needs.review.outputs.started || needs.review-keyless.outputs.started }} + ENVIRONMENT: ${{ inputs.environment }} FETCH_OUTCOME: ${{ needs.review.outputs.fetch_outcome || needs.review-keyless.outputs.fetch_outcome }} OUTCOME: ${{ needs.review.outputs.outcome || needs.review-keyless.outputs.outcome }} EXIT_CODE: ${{ needs.review.outputs.exit_code || needs.review-keyless.outputs.exit_code }} + PATH: /usr/bin:/bin run: | - case "${RESULT}" in - missing) reason="the agent produced no review (fetch outcome '${FETCH_OUTCOME}', review outcome '${OUTCOME}', exit code '${EXIT_CODE}')" ;; - invalid) reason="the review was rejected as invalid (not UTF-8, empty, or not a regular file within the size cap)" ;; - esac - echo "::warning title=Agent review failed::No review was posted: ${reason}. See the 'Fetch the pull request in the sandbox' and 'Run the review in the sandbox' logs." + text=$(/usr/bin/python3 -I -S -B "${RUNNER_TEMP}/trusted/bin/publish-comment" explain \ + --result "${RESULT}" --keyed "${KEYED}" --review-result "${REVIEW_RESULT}" --started "${STARTED}" \ + --environment "${ENVIRONMENT}" --fetch-outcome "${FETCH_OUTCOME}" --outcome "${OUTCOME}" \ + --exit-code "${EXIT_CODE}") + { IFS= read -r reason; IFS= read -r where; } <<< "${text}" + echo "::warning title=Agent review failed::No review was posted: ${reason}. ${where}" { echo "### Agent review failed" echo echo "No review was posted: ${reason}; the run is green because the check is advisory." - echo "The cause is in the \`Fetch the pull request in the sandbox\` or \`Run the review in the sandbox\` log of the \`review\` job; see https://github.com/GridTools/ci-workflows/blob/main/docs/agent-review.md." + echo + echo "${where} See https://github.com/GridTools/ci-workflows/blob/main/docs/agent-review.md#troubleshooting." } >> "$GITHUB_STEP_SUMMARY" diff --git a/agent-review/harnesses/README.md b/agent-review/harnesses/README.md index 85a9891..447d4bb 100644 --- a/agent-review/harnesses/README.md +++ b/agent-review/harnesses/README.md @@ -8,7 +8,7 @@ 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; 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`, 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. | | `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. | diff --git a/agent-review/harnesses/opencode/README.md b/agent-review/harnesses/opencode/README.md index 029779a..19433d5 100644 --- a/agent-review/harnesses/opencode/README.md +++ b/agent-review/harnesses/opencode/README.md @@ -36,6 +36,22 @@ release still has the flags and environment variables used in `run.sh`. `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. + ## Outbound calls `models.opencode.ai` (model catalogue), suppressed with diff --git a/agent-review/harnesses/opencode/run.sh b/agent-review/harnesses/opencode/run.sh index 12ba8d3..b1bfcba 100755 --- a/agent-review/harnesses/opencode/run.sh +++ b/agent-review/harnesses/opencode/run.sh @@ -16,6 +16,23 @@ adapter_init opencode # at the last step tools are disabled and the model has to answer. readonly MAX_STEPS=35 +# Request timeouts, in milliseconds. opencode retries a timed-out request, +# but at most 3 times per run, and that count cannot be configured: the +# 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 +# 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 +# silent there just as long. So it gets the same value as the header wait, +# not less; opencode's default is 900 s, with which one stream that stops +# uses most of the harness time limit. A stream that keeps sending is never +# cut, however long it takes. +readonly HEADER_TIMEOUT_MS=300000 CHUNK_TIMEOUT_MS=300000 + bin="${HARNESS_PREFIX}/node_modules/@opencode/cli-linux-x64-baseline/bin/opencode" # Ignore the repository's opencode.json(c) and .opencode/ (plugins there are @@ -31,7 +48,7 @@ check_version "opencode v$(head -n 1 "${HARNESS_PREFIX}/VERSION")" "${bin}" --ve # token and replaced by AWF's sidecar. Tools that edit, reach the web, ask # questions or spawn subagents are denied; 'shell' stays for git and grep. OPENCODE_CONFIG_CONTENT=$(jq -n --arg model "${MODEL}" --arg base "${AWF_API_PROXY_OPENAI_URL%/}/v1" \ - --argjson steps "${MAX_STEPS}" '{ + --argjson steps "${MAX_STEPS}" --argjson header "${HEADER_TIMEOUT_MS}" --argjson chunk "${CHUNK_TIMEOUT_MS}" '{ model: ("awf-proxy/" + $model), update: "disable", share: "disabled", experimental: {policies: [ {action: "provider.use", resource: "*", effect: "deny"}, @@ -40,7 +57,8 @@ OPENCODE_CONFIG_CONTENT=$(jq -n --arg model "${MODEL}" --arg base "${AWF_API_PRO | map({action: ., resource: "*", effect: "deny"})), agents: {build: {steps: $steps}}, providers: {"awf-proxy": {name: "AWF proxy", package: "@opencode/ai/providers/openai-compatible", - settings: {baseURL: $base, apiKey: "awf-placeholder"}, models: {($model): {name: $model}}}}}') + settings: {baseURL: $base, apiKey: "awf-placeholder", headerTimeout: $header, chunkTimeout: $chunk}, + models: {($model): {name: $model}}}}}') export OPENCODE_CONFIG_CONTENT cd "${REPO_DIR}" || exit 1 diff --git a/agent-review/harnesses/pi/README.md b/agent-review/harnesses/pi/README.md index 327f879..ccb3779 100644 --- a/agent-review/harnesses/pi/README.md +++ b/agent-review/harnesses/pi/README.md @@ -35,9 +35,23 @@ To upgrade, set the version in `package.json` and regenerate the lockfile with cannot be restricted; the sandbox is the boundary. - The prompt is passed on stdin: with stdin open and no prompt, Pi waits forever. -- **No turn cap and no stall detection**: AWF's `apiProxy.maxTurns` stops a - well-behaved run; the bound is AWF's request rate limits and the harness - timeout (see `../../awf.yaml`). +- **No turn cap**: AWF's `apiProxy.maxTurns` stops a well-behaved run; the + 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. ## Outbound calls diff --git a/agent-review/harnesses/pi/run.sh b/agent-review/harnesses/pi/run.sh index b6b28ba..27906d4 100755 --- a/agent-review/harnesses/pi/run.sh +++ b/agent-review/harnesses/pi/run.sh @@ -7,9 +7,10 @@ # CSCS does not serve). Exit codes: 0 review written, 2 no final answer, # other: failure. # -# Pi has no turn cap and no stall detection, and exits 0 when every request -# failed: AWF's apiProxy.maxTurns stops a well-behaved run; AWF's rate limits -# and run-review's timeout bound it (see awf.yaml). +# Pi has no turn cap, and exits 0 when every request failed: AWF's +# apiProxy.maxTurns stops a well-behaved run; AWF's rate limits and +# run-review's timeout bound it (see awf.yaml). A request that stalls is +# ended by the idle timeout below and retried. set -uo pipefail # shellcheck source=SCRIPTDIR/../common.sh @@ -20,6 +21,19 @@ adapter_init pi # Model metadata Pi needs for context management. 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. +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 mkdir -p "${PI_CODING_AGENT_DIR}" pi_cli="${HARNESS_PREFIX}/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js" @@ -32,6 +46,9 @@ jq -n --arg id "${MODEL}" --arg base "${AWF_API_PROXY_OPENAI_URL%/}/v1" \ {providers: {"awf-proxy": {baseUrl: $base, api: "openai-completions", apiKey: "awf-placeholder", models: [{id: $id, name: $id, reasoning: false, input: ["text"], contextWindow: $ctx, maxTokens: $max}]}}}' \ >"${PI_CODING_AGENT_DIR}/models.json" +jq -n --argjson idle "${IDLE_TIMEOUT_MS}" --argjson retries "${MAX_RETRIES}" --argjson delay "${RETRY_BASE_DELAY_MS}" \ + '{httpIdleTimeoutMs: $idle, retry: {enabled: true, maxRetries: $retries, baseDelayMs: $delay}}' \ + >"${PI_CODING_AGENT_DIR}/settings.json" cd "${REPO_DIR}" || exit 1 # --no-approve ignores the repository's .pi/ (extensions there are executed, diff --git a/agent-review/lib/agent_review/publish_comment.py b/agent-review/lib/agent_review/publish_comment.py index 24065fd..9cb9a35 100644 --- a/agent-review/lib/agent_review/publish_comment.py +++ b/agent-review/lib/agent_review/publish_comment.py @@ -5,12 +5,21 @@ publish-comment sanitize < review > safe-review publish-comment render --harness H --version V --model M --head-sha SHA --run-url U --review FILE publish-comment post --repo R --pr N --harness H --body-file FILE + publish-comment explain --result missing|invalid --keyed true|false --review-result R --started S + --environment E --fetch-outcome F --outcome O --exit-code X Runs in the ``publish`` job: a fresh VM with a write-capable token, no model and no PR code. The review is hostile text (agent_review.sanitize). ``sanitize`` and ``render`` read only stdin and files and write stdout; the workflow runs ``render`` in a step without a token. Only ``post`` runs -``gh`` (agent_review.gh), with the token of its step. +``gh`` (agent_review.gh), with the token of its step. ``explain`` reads +only its arguments, which the workflow takes from ``needs.*`` (job results +and step outputs) and the ``environment`` input, never from the review: it +prints two lines for the "no review" warning, why there is no review and +where to look. It tells a review job that reported no step (refused by the +environment's protection rules, cancelled while queued, or its runner +lost) and one that ended before the sandbox ran from a failure inside the +sandbox. Exit codes: 0 on success; 3 if the review is not valid UTF-8, is empty, or its file is not a regular file (a symlink, a FIFO, ...) within the size cap @@ -54,6 +63,21 @@ LISTING_JQ = f'.[] | [.id, .user.login, (.body | split("\\n") | .[0] | .[0:{FIRST_LINE_CHARS}])] | @tsv' ASCII_WHITESPACE = " \t\n\v\f\r" +# The values 'explain' is given: job results, step outcomes, an exit code, +# an environment name. Nothing here can end a line or a workflow command. +EXPLAIN_VALUE = validate.pattern(r"[A-Za-z0-9_.-]{0,64}") +EXPLAIN_OPTIONS = ( + "--result", + "--keyed", + "--review-result", + "--started", + "--environment", + "--fetch-outcome", + "--outcome", + "--exit-code", +) +SANDBOX_LOGS = "See the 'Fetch the pull request in the sandbox' and 'Run the review in the sandbox' logs" + RENDER_OPTIONS = ("--harness", "--version", "--model", "--head-sha", "--run-url", "--review") POST_OPTIONS = ("--repo", "--pr", "--harness", "--body-file") @@ -266,9 +290,100 @@ def cmd_post(args: Sequence[str]) -> bytes: return (text + "\n").encode("utf-8") +def explain( + *, + result: str, + keyed: bool, + review_result: str, + started: bool, + environment: str, + fetch_outcome: str, + outcome: str, + exit_code: str, +) -> tuple[str, str]: + """Why no review was posted, and where to look: two single-line texts. + + ``started`` is the review job's own first output. Its absence means + that the job reported no step: usually GitHub ended it before it got a + runner, but a runner lost during the job reports nothing either. + """ + job = "review" if keyed else "review-keyless" + if result == "invalid": + return ( + "the review was rejected as invalid (not UTF-8, empty, or not a regular file within the size cap)", + f"{SANDBOX_LOGS} of the '{job}' job.", + ) + cancelled = review_result == "cancelled" + if not started: + # No step reported: GitHub never gave the job a runner, or the + # runner was lost (out of memory, disk full, shut down) before the + # job's outputs were sent. The two cannot be told apart from here. + if cancelled: + cause = ( + "A newer review request for the same pull request replaced it in the keyed job's queue, or the run" + " was cancelled." + if keyed + else "The run was cancelled." + ) + return ( + f"the '{job}' job was cancelled before it reported a step (job result 'cancelled')", + f"{cause} See the '{job}' job.", + ) + reason = ( + f"the '{job}' job reported no step: it never got a runner, or its runner was lost (job result" + f" '{review_result}')" + ) + if keyed: + return ( + reason, + f"The usual cause is that the environment '{environment}' refused the job: its deployment branch" + " rule (a keyed review runs only from the default branch), a required reviewer, or another" + " protection rule. See the annotation on the 'review' job and the environment's settings" + " (Settings > Environments). If the environment refused it, no sandbox ran and the inference key" + " was not used.", + ) + return (reason, f"See the annotation on the '{job}' job.") + # A step after a failed one is 'skipped'; the output is empty if the job + # ended in its first steps. + if fetch_outcome in ("", "skipped"): + how = "was cancelled" if cancelled else "failed" + return ( + f"the '{job}' job {how} before the sandbox ran (job result '{review_result}')", + f"See the {'log' if cancelled else 'failed step'} of the '{job}' job. No sandbox ran, so there are no" + " sandbox logs.", + ) + return ( + f"the agent produced no review (fetch outcome '{fetch_outcome}', review outcome '{outcome}'," + f" exit code '{exit_code}')", + f"{SANDBOX_LOGS} of the '{job}' job.", + ) + + +def cmd_explain(args: Sequence[str]) -> bytes: + opts = parse_options(args, EXPLAIN_OPTIONS) + for name, value in opts.items(): + if not validate.matches(EXPLAIN_VALUE, value): + raise Failure(f"Invalid value for '{name}'.") + if opts["--result"] not in ("missing", "invalid"): + raise Failure(f"Invalid result '{opts['--result']}'.") + if opts["--keyed"] not in ("true", "false"): + raise Failure(f"Invalid keyed flag '{opts['--keyed']}'.") + reason, where = explain( + result=opts["--result"], + keyed=opts["--keyed"] == "true", + review_result=opts["--review-result"], + started=opts["--started"] == "true", + environment=opts["--environment"], + fetch_outcome=opts["--fetch-outcome"], + outcome=opts["--outcome"], + exit_code=opts["--exit-code"], + ) + return f"{reason}\n{where}\n".encode() + + def run(argv: Sequence[str]) -> bytes: if not argv: - raise Failure("Usage: publish-comment sanitize|render|post [options]") + raise Failure("Usage: publish-comment sanitize|render|post|explain [options]") command, args = argv[0], argv[1:] if command == "sanitize": # Extra arguments are ignored (part of the CLI contract). @@ -277,6 +392,8 @@ def run(argv: Sequence[str]) -> bytes: return cmd_render(args) if command == "post": return cmd_post(args) + if command == "explain": + return cmd_explain(args) raise Failure(f"Unknown command '{command}'.") diff --git a/agent-review/tests/fake_inference.py b/agent-review/tests/fake_inference.py new file mode 100644 index 0000000..f4ffc0a --- /dev/null +++ b/agent-review/tests/fake_inference.py @@ -0,0 +1,198 @@ +"""A local stand-in for the inference service that can stall (test-harness-stall.sh). + +Usage:: + + fake_inference.py --port P --log FILE [--stall-headers N] [--stall-midstream N] + [--ready-at SECONDS] [--min-wait SECONDS] [--first-event-delay SECONDS] + [--stream-gap SECONDS] [--stream-chunks N] + +Answers every ``POST`` with a short final answer in the OpenAI chat format +(streamed if the request asks for it), and never asks for a tool call. The +options make it misbehave the way the real service was seen to: + +- ``--stall-headers N``: the first N requests get no response at all; +- ``--stall-midstream N``: the next N get headers and one chunk, then nothing; +- ``--ready-at S``: no request is answered before S seconds after the first + one arrived; a request waiting at that moment is answered then; +- ``--min-wait S``: every request is answered only once it has waited S + seconds, so giving up earlier and asking again never helps; +- ``--first-event-delay S``: a streamed response's headers are sent at + once, its first event S seconds later (a service that accepts a request + and then queues it, or a model that thinks before its first token); +- ``--stream-gap``, ``--stream-chunks``: a slow stream that stays alive. + +A stalled request is held until the client closes the connection. ``FILE`` +gets one JSON line per event, with the seconds since the first request: +``start``, ``headers``, ``done``, ``stalled`` and ``client-abort``. + +Listens on 127.0.0.1 only. Test tool: never imported, never run by the +workflow. +""" + +import argparse +import json +import select +import socket +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any + +ANSWER = ("### Summary\n\n", "Fake ", "review ", "answer.\n") + + +class State: + def __init__(self, options: argparse.Namespace) -> None: + self.options = options + self.lock = threading.Lock() + self.count = 0 + self.first: float | None = None + + def arrival(self) -> tuple[int, float, float]: + """The request's number, its arrival time and the first request's.""" + now = time.monotonic() + with self.lock: + self.count += 1 + if self.first is None: + self.first = now + return self.count, now, self.first + + def log(self, **event: object) -> None: + with self.lock, open(self.options.log, "a", encoding="utf-8") as f: + f.write(json.dumps(event) + "\n") + + +def client_gone(connection: socket.socket) -> bool: + readable, _, _ = select.select([connection], [], [], 0) + if not readable: + return False + try: + return connection.recv(1, socket.MSG_PEEK) == b"" + except OSError: + return True + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + state: State + + def log_message(self, format: str, *args: Any) -> None: # the base class's parameter name + pass + + def _json(self, payload: object) -> None: + body = json.dumps(payload).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self) -> None: + self._json({"object": "list", "data": []}) + + def do_POST(self) -> None: + state, options = self.state, self.state.options + raw = self.rfile.read(int(self.headers.get("Content-Length") or 0)) + try: + request = json.loads(raw) + except ValueError: + request = {} + if not isinstance(request, dict): + request = {} + number, arrived, first = state.arrival() + + def seconds() -> float: + return round(time.monotonic() - first, 1) + + def hold(until: float | None) -> bool: + """Waits until ``until`` (forever if None); True if the client left first.""" + while until is None or time.monotonic() < until: + if client_gone(self.connection): + state.log(i=number, ev="client-abort", t=seconds(), waited=round(time.monotonic() - arrived, 1)) + self.close_connection = True + return True + time.sleep(0.1) + return False + + state.log(i=number, ev="start", t=seconds()) + if number <= options.stall_headers: + state.log(i=number, ev="stalled", t=seconds(), where="headers") + hold(None) + return + if hold(max(first + options.ready_at, arrived + options.min_wait)): + return + state.log(i=number, ev="headers", t=seconds(), waited=round(time.monotonic() - arrived, 1)) + words = [*ANSWER, *(["more. "] * max(0, options.stream_chunks - len(ANSWER)))] + usage = {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15} + model = request.get("model") + if not request.get("stream"): + message = {"role": "assistant", "content": "".join(words)} + self._json( + { + "id": "fake", + "object": "chat.completion", + "created": 1, + "model": model, + "choices": [{"index": 0, "message": message, "finish_reason": "stop"}], + "usage": usage, + } + ) + state.log(i=number, ev="done", t=seconds()) + return + + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Transfer-Encoding", "chunked") + self.end_headers() + base = {"id": "fake", "object": "chat.completion.chunk", "created": 1, "model": model} + + def event(payload: object) -> None: + text = payload if isinstance(payload, str) else json.dumps(payload) + data = f"data: {text}\n\n".encode() + self.wfile.write(b"%x\r\n%s\r\n" % (len(data), data)) + self.wfile.flush() + + def delta(content: dict[str, str], finish: str | None = None) -> dict[str, object]: + return {**base, "choices": [{"index": 0, "delta": content, "finish_reason": finish}]} + + try: + if options.first_event_delay and hold(time.monotonic() + options.first_event_delay): + return + event(delta({"role": "assistant", "content": ""})) + if number <= options.stall_headers + options.stall_midstream: + state.log(i=number, ev="stalled", t=seconds(), where="stream") + hold(None) + return + for word in words: + time.sleep(options.stream_gap) + event(delta({"content": word})) + event(delta({}, "stop")) + event({**base, "choices": [], "usage": usage}) + event("[DONE]") + self.wfile.write(b"0\r\n\r\n") + self.wfile.flush() + state.log(i=number, ev="done", t=seconds()) + except OSError: + state.log(i=number, ev="client-abort", t=seconds(), waited=round(time.monotonic() - arrived, 1)) + self.close_connection = True + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.split("\n", maxsplit=1)[0]) + parser.add_argument("--port", type=int, required=True) + parser.add_argument("--log", required=True) + parser.add_argument("--stall-headers", type=int, default=0) + parser.add_argument("--stall-midstream", type=int, default=0) + parser.add_argument("--ready-at", type=float, default=0) + parser.add_argument("--min-wait", type=float, default=0) + parser.add_argument("--first-event-delay", type=float, default=0) + parser.add_argument("--stream-gap", type=float, default=0.05) + parser.add_argument("--stream-chunks", type=int, default=len(ANSWER)) + Handler.state = State(parser.parse_args()) + server = ThreadingHTTPServer(("127.0.0.1", Handler.state.options.port), Handler) + server.daemon_threads = True + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/agent-review/tests/python/test_publish_comment.py b/agent-review/tests/python/test_publish_comment.py index 82055e4..6217bb7 100644 --- a/agent-review/tests/python/test_publish_comment.py +++ b/agent-review/tests/python/test_publish_comment.py @@ -452,3 +452,105 @@ def test_projection_keeps_matching_exact( else "POST repos/example-org/example/issues/9/comments" ) assert (directory / "requests.log").read_text() == want + "\n" + + +# --- explain: why no review was posted ------------------------------------------------- + + +def explain(**overrides: object) -> tuple[str, str]: + args: dict[str, object] = { + "result": "missing", + "keyed": True, + "review_result": "failure", + "started": False, + "environment": "agent-review", + "fetch_outcome": "", + "outcome": "", + "exit_code": "", + } + return pc.explain(**{**args, **overrides}) # type: ignore[arg-type] + + +def test_explain_environment_denial() -> None: + reason, where = explain() + assert reason == ( + "the 'review' job reported no step: it never got a runner, or its runner was lost (job result 'failure')" + ) + assert "environment 'agent-review' refused the job" in where + # Only conditionally: an empty 'started' does not prove that no step ran. + assert "If the environment refused it, no sandbox ran and the inference key was not used." in where + assert "Run the review in the sandbox" not in reason + where + + +def test_explain_cancelled_before_start() -> None: + reason, where = explain(review_result="cancelled") + assert reason == "the 'review' job was cancelled before it reported a step (job result 'cancelled')" + assert "replaced it in the keyed job's queue" in where + # The keyless job has no concurrency group: no queue to be replaced in. + reason, where = explain(keyed=False, review_result="cancelled") + assert "the 'review-keyless' job was cancelled before it reported a step" in reason + assert where == "The run was cancelled. See the 'review-keyless' job." + for keyed in (True, False): + text = " ".join(explain(keyed=keyed, review_result="cancelled")) + assert "refused" not in text and "sandbox' logs" not in text + + +def test_explain_keyless_job_without_runner_does_not_name_the_environment() -> None: + reason, where = explain(keyed=False) + assert "the 'review-keyless' job reported no step" in reason + assert "environment" not in reason + where and "inference key" not in where + + +def test_explain_failure_before_the_sandbox() -> None: + # As seen in a run: the steps after a failed one report 'skipped'. + for fetch_outcome, outcome in (("skipped", "skipped"), ("", "")): + reason, where = explain(started=True, fetch_outcome=fetch_outcome, outcome=outcome) + assert reason == "the 'review' job failed before the sandbox ran (job result 'failure')" + assert "See the failed step of the 'review' job" in where + + +def test_explain_cancelled_before_the_sandbox() -> None: + reason, where = explain(started=True, review_result="cancelled", fetch_outcome="skipped", outcome="skipped") + assert reason == "the 'review' job was cancelled before the sandbox ran (job result 'cancelled')" + assert "failed" not in reason + where + + +def test_explain_harness_failure_keeps_its_message() -> None: + reason, where = explain( + started=True, review_result="success", fetch_outcome="success", outcome="failure", exit_code="124" + ) + assert reason == "the agent produced no review (fetch outcome 'success', review outcome 'failure', exit code '124')" + assert where == ( + "See the 'Fetch the pull request in the sandbox' and 'Run the review in the sandbox' logs of the 'review' job." + ) + # A fetch failure is a sandbox failure too. + assert "fetch outcome 'failure'" in explain(started=True, fetch_outcome="failure", outcome="skipped")[0] + + +def test_explain_invalid_review() -> None: + reason, where = explain(result="invalid", started=True, fetch_outcome="success") + assert "rejected as invalid" in reason and "sandbox' logs" in where + + +@pytest.mark.parametrize( + "argv", + [ + ["explain", "--result", "posted", "--keyed", "true"], + ["explain", "--result", "missing", "--keyed", "yes"], + ["explain", "--result", "missing", "--keyed", "true", "--environment", "a\n::error::x"], + ["explain", "--result", "missing", "--keyed", "true", "--review-result", "a b"], + ["explain", "--result", "missing", "--keyed", "true", "--exit-code", "##[error]"], + ["explain", "--result", "missing", "--keyed", "true", "--unknown", "x"], + ], +) +def test_explain_rejects(argv: list[str]) -> None: + done = subprocess.run([*ENTRY, *argv], capture_output=True, check=False) + assert done.returncode == 1 and done.stdout == b"" + + +def test_explain_prints_two_lines() -> None: + argv = ["explain", "--result", "missing", "--keyed", "true", "--review-result", "failure", "--started", ""] + done = subprocess.run([*ENTRY, *argv, "--environment", "agent-review"], capture_output=True, check=True) + lines = done.stdout.decode().split("\n") + assert len(lines) == 3 and lines[2] == "" and all(lines[:2]) + assert "::" not in done.stdout.decode() and "##[" not in done.stdout.decode() diff --git a/agent-review/tests/python/test_workflow_structure.py b/agent-review/tests/python/test_workflow_structure.py index bcb16f3..e6087ed 100644 --- a/agent-review/tests/python/test_workflow_structure.py +++ b/agent-review/tests/python/test_workflow_structure.py @@ -654,6 +654,69 @@ def test_diag_breaks_legacy_commands(tmp_path: pathlib.Path) -> None: assert result.stderr == "t| a #\u200b#[warning]x\nt| ::error::y\nt| b #\u200b#[error]z\n".encode() +# --- The started signal ------------------------------------------------------------ + + +def test_real_started_signal_passes() -> None: + assert ws.started_signal_problems(WORKFLOW) == [] + + +def test_started_step_must_be_first_and_unconditional() -> None: + for change in ("move", "if", "continue", "run"): + workflow = copy.deepcopy(WORKFLOW) + # The two jobs share their steps (YAML aliases): change one job's own copies. + steps = [dict(step) for step in workflow["jobs"]["review"]["steps"]] + workflow["jobs"]["review"]["steps"] = steps + if change == "move": + steps.insert(1, steps.pop(0)) + elif change == "if": + steps[0]["if"] = "github.event_name == 'workflow_dispatch'" + elif change == "continue": + steps[0]["continue-on-error"] = True + else: + steps[0]["run"] = 'echo "started=false" >> "$GITHUB_OUTPUT"' + found = ws.started_signal_problems(workflow) + assert len(found) == 1 and found[0].startswith("review: the first step"), (change, found) + + +def test_started_output_is_required_in_both_review_jobs() -> None: + for job_id in ws.REVIEW_JOBS: + workflow = copy.deepcopy(WORKFLOW) + workflow["jobs"][job_id]["outputs"] = { + k: v for k, v in workflow["jobs"][job_id]["outputs"].items() if k != "started" + } + assert ws.started_signal_problems(workflow) == [f"{job_id}: no output 'started' from the first step"] + + +def report_step(workflow: dict[str, Any]) -> dict[str, Any]: + steps: list[dict[str, Any]] = workflow["jobs"]["publish"]["steps"] + (step,) = [s for s in steps if s.get("name") == ws.REPORT_STEP] + return step + + +@pytest.mark.parametrize("key", sorted(ws.REPORT_ENV)) +def test_report_step_env_is_pinned(key: str) -> None: + workflow = copy.deepcopy(WORKFLOW) + report_step(workflow)["env"][key] = "${{ needs.review.result }}" + found = ws.started_signal_problems(workflow) + assert len(found) == 1 and f"env {key} " in found[0], found + + +@pytest.mark.parametrize("argument", ws.REPORT_ARGUMENTS) +def test_report_step_passes_every_argument(argument: str) -> None: + workflow = copy.deepcopy(WORKFLOW) + step = report_step(workflow) + step["run"] = step["run"].replace(argument, "") + found = ws.started_signal_problems(workflow) + assert len(found) == 1 and argument in found[0], found + + +def test_report_step_must_exist_once() -> None: + workflow = copy.deepcopy(WORKFLOW) + report_step(workflow)["name"] = "Report" + assert ws.started_signal_problems(workflow) == ["publish: 0 steps named 'Report a missing review'"] + + # --- The collect gate ------------------------------------------------------------- GATE = "always() && steps.key.outputs.skipped != 'true' && steps.teardown.outcome == 'success'" diff --git a/agent-review/tests/test-harness-stall.sh b/agent-review/tests/test-harness-stall.sh new file mode 100644 index 0000000..081e317 --- /dev/null +++ b/agent-review/tests/test-harness-stall.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +# The adapters' request timeouts against an inference service that stalls +# (fake_inference.py): a request that stalls must end and be retried, a +# slow but live stream must not be cut, and a run must still get through +# long waits: a request answered only after 185 s (as in the v0.1.0 release +# validation), the same wait between the headers and the first event of a +# stream, and a service that answers nothing for 17 minutes (13 in the +# validation; more than Pi's default of 3 retries can sit out, so the case +# fails if its raised retry count is lost). +# +# Usage: test-harness-stall.sh [--fast] [opencode] [pi] +# +# NOT part of the self-test: it installs the pinned harnesses (about +# 400 MB) and RUNS them on this machine, outside any sandbox, against a +# local server and an empty repository; they get no key. Run it after +# changing an adapter's timeouts or its pinned version. Needs jq, npm, +# curl and python3. +# +# By default the adapters run unchanged and the cases take the real times +# (about 18 minutes; the cases run in parallel). --fast runs copies of the +# adapters with every timeout and retry delay divided by 30 (about 1 minute): it checks the +# behaviour, not the values. + +set -uo pipefail +# shellcheck source=lib.sh +. "$(dirname "$0")/lib.sh" + +HARNESSES_DIR=$(cd "${BIN_DIR}/../harnesses" && pwd) +FAKE="$(dirname "${BIN_DIR}")/tests/fake_inference.py" +SCALE=1 +SELECTED=() +for arg in "$@"; do + case "${arg}" in + --fast) SCALE=30 ;; + opencode | pi) SELECTED+=("${arg}") ;; + *) + echo "Usage: test-harness-stall.sh [--fast] [opencode] [pi]" >&2 + exit 1 + ;; + esac +done +[ "${#SELECTED[@]}" -gt 0 ] || SELECTED=(opencode pi) + +WORK=$(mktemp -d) +trap 'kill $(jobs -p) 2>/dev/null; rm -rf "${WORK}"' EXIT + +# The constants an adapter declares, in milliseconds ('readonly NAME=value'). +constant() { # harness name + sed -n -E "s/^readonly (.* )?$2=([0-9]+)( .*)?\$/\\2/p" "${ADAPTERS}/$1/run.sh" | head -n 1 +} + +ADAPTERS=${HARNESSES_DIR} +if [ "${SCALE}" -ne 1 ]; then + ADAPTERS="${WORK}/harnesses" + cp -R "${HARNESSES_DIR}" "${ADAPTERS}" + for name in HEADER_TIMEOUT_MS CHUNK_TIMEOUT_MS IDLE_TIMEOUT_MS RETRY_BASE_DELAY_MS; do + for file in "${ADAPTERS}"/*/run.sh; do + value=$(sed -n -E "s/^readonly (.* )?${name}=([0-9]+)( .*)?\$/\\2/p" "${file}" | head -n 1) + [ -z "${value}" ] || sed -i -E "s/^(readonly (.* )?${name}=)${value}/\\1$((value / SCALE))/" "${file}" + done + done +fi + +# Seconds: how long each harness waits for headers and between chunks; the +# wait of the validation's slow answer; and a silence longer than 4 +# attempts of Pi's timeout (3 retries, Pi's default) but shorter than what +# either harness must sit out. +OPENCODE_HEADER=$(($(constant opencode HEADER_TIMEOUT_MS) / 1000)) +OPENCODE_CHUNK=$(($(constant opencode CHUNK_TIMEOUT_MS) / 1000)) +PI_IDLE=$(($(constant pi IDLE_TIMEOUT_MS) / 1000)) +SILENCE=$((1050 / SCALE)) +SLOW_ANSWER=$((185 / SCALE)) +echo "opencode: headers ${OPENCODE_HEADER} s, chunks ${OPENCODE_CHUNK} s; pi: idle ${PI_IDLE} s; silence ${SILENCE} s" + +PORT=${STALL_TEST_PORT:-18200} +# Starts one case in the background: a server with the given options and +# the adapter against it. Results go to ${WORK}//. +start_case() { # case harness server-options... + local name=$1 harness=$2 dir="${WORK}/$1" port + shift 2 + PORT=$((PORT + 1)) + port=${PORT} + mkdir -p "${dir}/repo" "${dir}/out" "${dir}/tmp" + git -C "${dir}/repo" init -q + echo "A file." >"${dir}/repo/README.md" + echo 'Reply with a short review that starts with "### Summary". Use no tools.' >"${dir}/prompt.md" + ( + python3 -I "${FAKE}" --port "${port}" --log "${dir}/server.jsonl" "$@" & + server=$! + sleep 1 + begin=${SECONDS} + env -i PATH=/usr/bin:/bin HOME=/nonexistent TMPDIR="${dir}/tmp" PROMPT_FILE="${dir}/prompt.md" \ + REPO_DIR="${dir}/repo" OUT_DIR="${dir}/out" CONTEXT_DIR="${dir}/out" MODEL=fake/model PR_NUMBER=1 \ + HARNESS_PREFIX="${PREFIXES}/${harness}" AWF_API_PROXY_OPENAI_URL="http://127.0.0.1:${port}" \ + timeout 1500 bash "${ADAPTERS}/${harness}/run.sh" >"${dir}/adapter.log" 2>&1 + echo "$?" >"${dir}/exit" + echo "$((SECONDS - begin))" >"${dir}/elapsed" + kill "${server}" 2>/dev/null + ) & +} + +events() { jq -c 'select(.ev == "'"$2"'")' "${WORK}/$1/server.jsonl" | wc -l; } # case event +succeeded() { [ "$(cat "${WORK}/$1/exit")" = 0 ] && grep -q '^### Summary' "${WORK}/$1/out/review.md"; } +elapsed_between() { # case min max + local t + t=$(cat "${WORK}/$1/elapsed") + [ "${t}" -ge "$2" ] && [ "${t}" -le "$3" ] +} +# The longest a stalled request was held before the adapter gave it up. +longest_wait() { jq -s '[.[] | select(.ev == "client-abort") | .waited] | max // 0 | floor' "${WORK}/$1/server.jsonl"; } + +check_case() { # description command... + TESTS_RUN=$((TESTS_RUN + 1)) + local msg=$1 + shift + if "$@"; then echo "- ok: ${msg}"; else fail "${msg}"; fi +} + +PREFIXES="${WORK}/prefix" +for harness in "${SELECTED[@]}"; do + echo "Installing ${harness} ..." + bash "${HARNESSES_DIR}/${harness}/install.sh" "${PREFIXES}/${harness}" || exit 1 +done + +for harness in "${SELECTED[@]}"; do + # opencode makes a second request (the session title) next to the first + # one, so two requests must stall for the review's own request to. + start_case "${harness}-headers" "${harness}" --stall-headers 2 + start_case "${harness}-stream" "${harness}" --stall-midstream 2 + start_case "${harness}-slow" "${harness}" --stream-gap "$((330 / SCALE / 9 + 1))" --stream-chunks 9 + start_case "${harness}-late" "${harness}" --min-wait "${SLOW_ANSWER}" + start_case "${harness}-first" "${harness}" --first-event-delay "${SLOW_ANSWER}" + start_case "${harness}-silence" "${harness}" --ready-at "${SILENCE}" +done +echo "Running $((6 * ${#SELECTED[@]})) cases ..." +wait + +for harness in "${SELECTED[@]}"; do + if [ "${harness}" = opencode ]; then header=${OPENCODE_HEADER} chunk=${OPENCODE_CHUNK}; else header=${PI_IDLE} chunk=${PI_IDLE}; fi + check_case "${harness}: a request without response headers ends after ${header} s and the retry succeeds" \ + eval "succeeded ${harness}-headers && [ \"\$(longest_wait ${harness}-headers)\" -ge $((header - 1)) ] && [ \"\$(longest_wait ${harness}-headers)\" -le $((header + 5)) ]" + check_case "${harness}: a stream that stops ends after ${chunk} s and the retry succeeds" \ + eval "succeeded ${harness}-stream && [ \"\$(longest_wait ${harness}-stream)\" -ge $((chunk - 1)) ] && [ \"\$(longest_wait ${harness}-stream)\" -le $((chunk + 5)) ]" + check_case "${harness}: a slow stream longer than the chunk timeout is not cut" \ + eval "succeeded ${harness}-slow && [ \"\$(events ${harness}-slow client-abort)\" -eq 0 ] && elapsed_between ${harness}-slow $((chunk + 1)) 100000" + check_case "${harness}: a request answered only after ${SLOW_ANSWER} s succeeds at the first attempt" \ + eval "succeeded ${harness}-late && [ \"\$(events ${harness}-late client-abort)\" -eq 0 ]" + check_case "${harness}: a stream whose first event comes ${SLOW_ANSWER} s after its headers is not cut" \ + eval "succeeded ${harness}-first && [ \"\$(events ${harness}-first client-abort)\" -eq 0 ]" + check_case "${harness}: a run sits out ${SILENCE} s of silence and then succeeds" \ + eval "succeeded ${harness}-silence && elapsed_between ${harness}-silence ${SILENCE} $((SILENCE + header + 20))" +done +for dir in "${WORK}"/*-*/; do + [ -f "${dir}/server.jsonl" ] || continue + echo "$(basename "${dir}"): exit $(cat "${dir}/exit"), $(cat "${dir}/elapsed") s: $(jq -c '[.i, .ev, .t]' "${dir}/server.jsonl" | tr '\n' ' ')" +done +summary diff --git a/agent-review/tests/test-publish-comment.sh b/agent-review/tests/test-publish-comment.sh index 13f4b8e..56473bd 100755 --- a/agent-review/tests/test-publish-comment.sh +++ b/agent-review/tests/test-publish-comment.sh @@ -189,5 +189,60 @@ test_post_refuses_body_without_marker() { run_entry "${PC}" post --repo example-org/example --pr 9 --harness stub --body-file body.md >/dev/null 2>&1 } +explain() { run_entry "${PC}" explain "$@"; } + +# The keyed job never got a runner: the message names the environment's +# rules and does not point at sandbox logs. +test_explain_environment_denial() { + local out + out=$(explain --result missing --keyed true --review-result failure --started "" --environment agent-review \ + --fetch-outcome "" --outcome "" --exit-code "") && + assert "two lines" test "$(wc -l <<<"${out}")" -eq 2 && + assert "says the job reported no step" grep -qF "the 'review' job reported no step: it never got a runner, or its runner was lost" <<<"${out}" && + assert "names the environment" grep -qF "environment 'agent-review' refused the job" <<<"${out}" && + assert "the key claim is conditional" grep -qF "If the environment refused it, no sandbox ran and the inference key was not used" <<<"${out}" && + assert "no pointer to sandbox logs" lacks "Run the review in the sandbox" "${out}" +} + +test_explain_cancelled_while_queued() { + local out + out=$(explain --result missing --keyed true --review-result cancelled --started "" --environment agent-review) && + assert "says cancelled" grep -qF "was cancelled before it reported a step" <<<"${out}" && + assert "does not blame the environment" lacks "refused the job" "${out}" && + assert "no pointer to sandbox logs" lacks "Run the review in the sandbox" "${out}" +} + +test_explain_failure_before_the_sandbox() { + local out + out=$(explain --result missing --keyed false --review-result failure --started true \ + --fetch-outcome skipped --outcome skipped --exit-code "") && + assert "says before the sandbox" grep -qF "the 'review-keyless' job failed before the sandbox ran" <<<"${out}" && + assert "points at the failed step" grep -qF "See the failed step of the 'review-keyless' job" <<<"${out}" +} + +# A real harness failure keeps the message it had. +test_explain_harness_failure() { + local out + out=$(explain --result missing --keyed true --review-result success --started true --environment agent-review \ + --fetch-outcome success --outcome failure --exit-code 124) && + assert "the harness message" grep -qF \ + "the agent produced no review (fetch outcome 'success', review outcome 'failure', exit code '124')" <<<"${out}" && + assert "points at the sandbox logs" grep -qF "'Run the review in the sandbox' logs of the 'review' job" <<<"${out}" && + assert "does not blame the environment" lacks "refused the job" "${out}" +} + +test_explain_invalid_review() { + local out + out=$(explain --result invalid --keyed true --review-result success --started true --fetch-outcome success) && + assert "the invalid message" grep -qF "the review was rejected as invalid" <<<"${out}" +} + +test_explain_rejects_unexpected_values() { + ! explain --result posted --keyed true 2>/dev/null && + ! explain --result missing --keyed maybe 2>/dev/null && + ! explain --result missing --keyed true --environment $'a\n::error::x' 2>/dev/null && + ! explain --result missing --keyed true --review-result 'a b' 2>/dev/null +} + for t in $(declare -F | awk '$3 ~ /^test_/ {print $3}'); do run_test "$t"; done summary diff --git a/agent-review/tests/test-workflow-structure.py b/agent-review/tests/test-workflow-structure.py index 970091c..741e90c 100644 --- a/agent-review/tests/test-workflow-structure.py +++ b/agent-review/tests/test-workflow-structure.py @@ -27,6 +27,7 @@ secret_refs, shebang_problems, shell_python_problems, + started_signal_problems, strings, token_reach_problems, tree_problems, @@ -176,6 +177,10 @@ def main() -> int: "sandbox output: prefixed, no carriage return, no legacy '##[' (awf steps and diag)", ) check_problems(collect_gate_problems(workflow), "'Collect the result' runs only after a successful teardown") + check_problems( + started_signal_problems(workflow), + "a review job that never started is reported as such: 'started' output, passed to 'explain'", + ) check_problems(entry_problems(repo["entries"], repo["lib"]), "bin/: only the exact Python entry-point template") check_problems(tree_problems(repo["index"]), "tree: no symlink, .pth, .pyc, __pycache__, *customize.py") check_problems(shebang_problems(repo["first_lines"]), "no Python shebang outside lib/agent_review/ and tests/") diff --git a/agent-review/tests/workflow_structure.py b/agent-review/tests/workflow_structure.py index 2e06c16..6a0411a 100644 --- a/agent-review/tests/workflow_structure.py +++ b/agent-review/tests/workflow_structure.py @@ -31,6 +31,12 @@ - the collect gate (collect_gate_problems): 'Collect the result' runs only if 'Stop the sandbox' succeeded, because collect-result's single-link check relies on no sandbox process being alive. +- the started signal (started_signal_problems): the first step of both + review jobs sets the 'started' output unconditionally, and 'Report a + missing review' passes it, the review job's result and the 'keyed' flag + to 'publish-comment explain', so a job that reported no step (refused + by the environment, cancelled while queued, its runner lost) is not + reported as a failure inside the sandbox. Python (invariant 13, docs/adr/0004-python-runtime.md): @@ -210,6 +216,56 @@ def call_site_problems(workflow: Mapping[str, Any], kinds: Mapping[str, str | No return problems +REVIEW_JOBS = ("review", "review-keyless") +STARTED_STEP = { + "name": "Record that the job started", + "id": "started", + "run": 'echo "started=true" >> "$GITHUB_OUTPUT"', +} +STARTED_OUTPUT = "${{ steps.started.outputs.started }}" +REPORT_STEP = "Report a missing review" +REPORT_ENV = { + "KEYED": "${{ needs.authorize.outputs.keyed }}", + "REVIEW_RESULT": ( + "${{ needs.authorize.outputs.keyed == 'true' && needs.review.result || needs.review-keyless.result }}" + ), + "STARTED": "${{ needs.review.outputs.started || needs.review-keyless.outputs.started }}", + "ENVIRONMENT": "${{ inputs.environment }}", +} +REPORT_ARGUMENTS = ( + '--keyed "${KEYED}"', + '--review-result "${REVIEW_RESULT}"', + '--started "${STARTED}"', + '--environment "${ENVIRONMENT}"', +) + + +def started_signal_problems(workflow: Mapping[str, Any]) -> list[str]: + """The review jobs say that they started, and 'publish' reads it when no review arrived.""" + problems = [] + jobs = workflow["jobs"] + for job_id in REVIEW_JOBS: + job = jobs.get(job_id, {}) + steps = job.get("steps", []) + # Exactly this step, first: no 'if:', no 'continue-on-error', nothing before it that can fail. + if not steps or steps[0] != STARTED_STEP: + problems.append(f"{job_id}: the first step is not exactly {STARTED_STEP['name']!r}") + if job.get("outputs", {}).get("started") != STARTED_OUTPUT: + problems.append(f"{job_id}: no output 'started' from the first step") + report = [s for s in jobs.get("publish", {}).get("steps", []) if s.get("name") == REPORT_STEP] + if len(report) != 1: + return [*problems, f"publish: {len(report)} steps named {REPORT_STEP!r}"] + env = report[0].get("env", {}) + for key, value in REPORT_ENV.items(): + if env.get(key) != value: + problems.append(f"publish/{REPORT_STEP}: env {key} is not {value!r}") + script = str(report[0].get("run", "")) + for argument in REPORT_ARGUMENTS: + if argument not in script: + problems.append(f"publish/{REPORT_STEP}: 'explain' is not called with {argument!r}") + return problems + + def strings(node: Any, path: tuple[str, ...] = ()) -> Iterator[tuple[tuple[str, ...], str]]: """Yields (path, string) for every string value in a YAML tree.""" if isinstance(node, dict): diff --git a/docs/agent-review.md b/docs/agent-review.md index 68b745a..40bf902 100644 --- a/docs/agent-review.md +++ b/docs/agent-review.md @@ -5,7 +5,7 @@ The reusable `Agent Review` workflow ([`.github/workflows/agent-review.yml`](../ An adopting repository adds a small **caller workflow** that calls this one pinned by commit SHA, and keeps its own triggers, environment, key, label and event policy. The design is in [ADR 0001](adr/0001-sandboxed-agent-pr-review.md) (the sandboxed review) and [ADR 0002](adr/0002-reusable-workflow.md) (packaging it as a reusable workflow). > [!NOTE] -> **Status: `v0.1.0`, the first release.** The pipeline was security-reviewed as an in-repository workflow, before it moved here. The [release checklist](#release-checklist) has since been run from a separate test caller on the release candidate: keyed `opencode` and Pi reviews, the label path with real posts, a fork PR by an account without write access carrying hostile content, a git-level fixture and an audit run. **Not verified**: the labeller-denial case (it needs an organization repository, where the `triage` role exists); runs in an organization repository and calls from another organization (the test caller is user-owned), and organization-level settings such as an actions allowlist; invariant 6 end to end with files named in the addendum; and the key-isolation canaries with the final AWF flags (they ran in separate configurations in the AWF probe). In the hostile fork PR the harnesses named the injected text and followed none of it, which shows the models' behaviour, not that the sandbox contained an attack; containment rests on the canary and offline tests. +> **Status: `v0.1.0`, the first release.** The pipeline was security-reviewed as an in-repository workflow, before it moved here. The [release checklist](#release-checklist) has since been run from a separate test caller on the release candidate: keyed `opencode` and Pi reviews, the label path with real posts, a fork PR by an account without write access carrying hostile content, a git-level fixture and an audit run. **Not verified**: the labeller-denial case (it needs an organization repository, where the `triage` role exists); runs in an organization repository and calls from another organization (the test caller is user-owned), and organization-level settings such as an actions allowlist; and the key-isolation canaries with the final AWF flags (they ran in separate configurations in the AWF probe). In the hostile fork PR the harnesses named the injected text and followed none of it, which shows the models' behaviour, not that the sandbox contained an attack; containment rests on the canary and offline tests. For `v0.1.1`, invariant 6 was also run end to end from the test caller with a file named in the addendum: a pull request changing that file, and one replacing it with a symlink to a path no pattern covers; in both the reset restored the base file and the review was posted (see [Release checklist](#release-checklist), item 3.11). The fail-closed post-conditions did not fire in these runs; they are shown by the offline tests. ## Calling it @@ -175,7 +175,7 @@ Each harness keeps one comment per PR, updated in place by later runs. The comme | `authorize` | read token, **no secrets** | Records this workflow's own commit (`job.workflow_repository`@`job.workflow_sha`), fetches `agent-review/` from it, and runs [`bin/authorize`](../agent-review/bin/authorize): validates the inputs, picks the endpoint from the allowlist, decides from its harness allowlist whether the run is **keyed**, applies the event rules, checks permissions (fails closed on API errors) and pins the PR head and base sha. Every other job requires its `allowed` output. | | `prepare` | read token, **no secrets** | Fetches [`agent-review/`](../agent-review/) from this workflow's own commit (checking that its own `job.workflow_sha` is the one recorded), runs the harness's `install.sh`, which downloads the pinned harness without running any of its code, and uploads it as an artifact. | | `review` (keyed) or `review-keyless` | read token; for `review` only: inference key in **one step's** env (caller's environment) | The two jobs run the same steps (YAML aliases); only `review` declares the environment and references the secret, and only keyed harnesses under `pull_request_target` or `workflow_dispatch` run it, one at a time per PR (its own concurrency group). Fetches `agent-review/` as above and the caller's addendum from the caller repository at the caller's `github.workflow_sha`, copies them to `/opt/agent-review` (root-owned, read-only in the sandbox), writes the PR metadata as raw bytes, and runs AWF twice. First without a key and with only `github.com` allowed: [`run-review`](../agent-review/bin/run-review) `--phase fetch` fetches the PR with git, resets agent instruction files and rule files to the base version and renders the prompt; no agent runs. Then with the key (keyed job only) and no allowed domain: `run-review --phase review` runs the harness. Afterwards leftover containers are removed and [`collect-result`](../agent-review/bin/collect-result) copies only `review.md` and `meta.json` out; it starts no process and opens the output directory one component at a time from `/`, none a symlink, then reads both files through that descriptor. | -| `publish` | write token (`pull-requests`), no model | On a fresh VM, [`publish-comment`](../agent-review/bin/publish-comment) validates and renders the review in a step without a token, then upserts the comment. | +| `publish` | write token (`pull-requests`), no model | On a fresh VM, [`publish-comment`](../agent-review/bin/publish-comment) validates and renders the review in a step without a token, then upserts the comment. If no review arrived, it warns and says why (`publish-comment explain`): a failure inside the sandbox, a review job that failed before the sandbox ran, or one that reported no step (refused by the environment's protection rules, cancelled while queued, or its runner lost). | The trusted code is in [`agent-review/`](../agent-review/): `bin/` holds the entry points the workflow calls, `lib/agent_review/` the Python package they use (standard library only), `harnesses/` the adapters, `tests/` the tests. The scripts in `bin/` are Python. Each is a fixed template that refuses to run unless started as `/usr/bin/python3 -I -S -B /bin/` ([ADR 0004](adr/0004-python-runtime.md)). [`bin/probe`](../agent-review/bin/probe) prints the interpreter's version and flags; the `stub` harness runs it on the host (in `prepare`) and in the sandbox. @@ -194,7 +194,7 @@ Callers use `pull_request_target` because fork PRs get no secrets under `pull_re The structure test checks those steps, what they inherit and the teardown gate ([`workflow_structure.py`](../agent-review/tests/workflow_structure.py) lists the checks). 04. **The agent has no network access** except AWF's API-proxy listener: its sandbox run allows no domain. Only the first, keyless run, which runs no agent, reaches `github.com`. AWF still allows the inference host for its sidecar in the shared egress proxy, so the agent can probably reach it directly too (not tried), without a key. -05. **Write tokens exist only in `publish`**, which runs no model and no PR code, and treats the review as hostile ([`sanitize.py`](../agent-review/lib/agent_review/sanitize.py)): it must be valid UTF-8 (strict: no surrogates, nothing above U+10FFFF); control characters other than tab and newline are dropped, and so are invisible characters: a fixed list of ranges (zero-width, bidirectional controls, variation selectors, tag characters) plus every character of Unicode category `Cf` (the list stays, because variation selectors are `Mn` and a character newer than Python's Unicode version is `Cn`); no raw HTML can form: a zero-width space follows every `<` that is followed by an ASCII letter, `/`, `!` or `?`, so there is no tag, end tag, HTML block, comment, processing instruction, declaration or CDATA section (GitHub strips attributes and hides some HTML content, and the review cannot imitate the comment marker); comment ends (`-->`) 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 ([`sanitize.py`](../agent-review/lib/agent_review/sanitize.py)): it must be valid UTF-8 (strict: no surrogates, nothing above U+10FFFF); C0 control characters other than tab and newline, and DEL, are dropped (C1 controls, U+0080 to U+009F, pass: GitHub's Markdown render API, with which this was checked, shows each as a visible U+FFFD, and none forms a mention, tag or reference), and so are invisible characters: a fixed list of ranges (zero-width, bidirectional controls, variation selectors, tag characters) plus every character of Unicode category `Cf` (the list stays, because variation selectors are `Mn` and a character newer than Python's Unicode version is `Cn`); no raw HTML can form: a zero-width space follows every `<` that is followed by an ASCII letter, `/`, `!` or `?`, so there is no tag, end tag, HTML block, comment, processing instruction, declaration or CDATA section (GitHub strips attributes and hides some HTML content, and the review cannot imitate the comment marker); comment ends (`-->`) 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. 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: @@ -213,10 +213,10 @@ Callers use `pull_request_target` because fork PRs get no secrets under `pull_re ## What remains risky -- **A base that links an instruction file or directory to a path no reset pattern covers gets no review** (fail closed, invariant 6), because the agent would read the PR's version of the target: for example `AGENTS.md -> CONTRIBUTING.md`, `.github/copilot-instructions.md -> ../docs/copilot.md`, a rule file `docs/RULES.md -> guide.md`, or `.claude/skills -> ../tools/skills`. The run ends green with a "no review" warning, and the fetch log names the link, its target and the fix: add the target to the caller's `instruction_files` input (a file as `CONTRIBUTING.md`, a directory as `tools/skills/`), which resets it to the base version as well. Patterns apply at any depth and case-insensitively, so `CONTRIBUTING.md` resets every file of that name. Following links in the reset itself is a candidate for v0.2.0. +- **A base that links an instruction file or directory to a path no reset pattern covers gets no review** (fail closed, invariant 6), because the agent would read the PR's version of the target: for example `AGENTS.md -> CONTRIBUTING.md`, `.github/copilot-instructions.md -> ../docs/copilot.md`, a rule file `docs/RULES.md -> guide.md`, or `.claude/skills -> ../tools/skills`. The run ends green with a "no review" warning, and the fetch log names the link, its target and the fix: add the target to the caller's `instruction_files` input (a file as `CONTRIBUTING.md`, a directory as `tools/skills/`), which resets it to the base version as well. Patterns apply at any depth and case-insensitively, so `CONTRIBUTING.md` resets every file of that name. This is an accepted risk: the failure is loud, and the fix is one line in the caller's `instruction_files`, where the caller sees which target a link adds; the reset does not follow links itself. - **The PR's `.gitattributes` applies to the checkout.** A PR adding `* -diff` makes git write `Binary files differ` instead of the changes into the context's `diff.patch`, which steers what the agent sees of the diff (it can still read the files); this breaks no invariant. Attributes such as `eol=crlf` or `working-tree-encoding` also transform the base files the reset restores: a rule file then is not its base version, so the run stops (fail closed); another instruction file keeps the base text, transformed, never the PR's (tests in `test_run_review.py`). -- **Prompt injection can steer the review's content**: a false approval, misleading findings, links. Mitigations: the comment is labelled advisory, never a status, names the reviewed commit and says the PR can steer it; mentions are neutralised and the size is capped. Cross-references such as `owner/repo#123` are not neutralised and can create backlinks in other repositories. The caller's rule files are reset to base (invariant 6), but files they in turn point at (`CONTRIBUTING.md`, the ADRs) are not, so injected text there is still read as context; it can only steer review content. Visible content (links, images) is not filtered; raw HTML such as `
` cannot form. **Markdown-level hiding remains** (accepted for v0.1.0, candidates for v0.2.0): math such as `$\phantom{text}$` or `$\color{white}{text}$`, image alt text, link titles (`[a](u "text")`), link destinations in angle brackets (`[]()`), and code-fence info strings (the words after an opening ```` ``` ````) carry text that the comment does not show. -- **A steered review can carry command lines for other bots.** The workflow itself uses no comment commands, but the review text may contain lines such as `/approve`, `/lgtm` or `bors r+`, which the sanitiser passes unchanged. Whether a bot installed in the caller acts on them depends on that bot's own checks of the comment's author (here the workflow's bot account); check those before adopting. Breaking up a line-initial `/` is a candidate for v0.2.0. +- **Prompt injection can steer the review's content**: a false approval, misleading findings, links. Mitigations: the comment is labelled advisory, never a status, names the reviewed commit and says the PR can steer it; mentions are neutralised and the size is capped. Cross-references such as `owner/repo#123` are not neutralised and can create backlinks in other repositories. The caller's rule files are reset to base (invariant 6), but files they in turn point at (`CONTRIBUTING.md`, the ADRs) are not, so injected text there is still read as context; it can only steer review content. Visible content (links, images) is not filtered; raw HTML such as `
` cannot form. **Markdown-level hiding remains**, as an accepted risk: math such as `$\phantom{text}$` or `$\color{white}{text}$`, image alt text, link titles (`[a](u "text")`), link destinations in angle brackets (`[]()`), and code-fence info strings (the words after an opening ```` ``` ````) carry text that the comment does not show. Text a reader cannot see can only matter to a program reading the comment, and the pull request can already put visible steering text into the review; closing these would mean parsing Markdown in the job that holds the write token. +- **A steered review can carry command lines for other bots.** The workflow itself uses no comment commands, but the review text may contain lines such as `/approve`, `/lgtm` or `bors r+`, which the sanitiser passes unchanged. `publish` posts with `github.token`, and events created with `GITHUB_TOKEN` start no workflow runs (`issue_comment` included), so no Actions-based bot can react, PR Agent in the same repository included. Only a bot that receives webhooks (an App, Prow, bors) could, and whether it acts depends on its own checks of the comment's author (here the workflow's bot account); check those before adopting. This is an accepted risk: such commands have no common form (`bors r+` starts with no `/`), so breaking them up would need an open-ended denylist, and the pull request's author can post the same line directly. - **Budget burn, driven by the content of any reviewed PR.** The agent has a shell and can call AWF's listener directly, so the per-run bound is AWF's rate limiter, not the turn cap: at most **100 upstream requests per run** (`rateLimiting.requestsPerHour`; the run is shorter than an hour), paced at 30 per minute, each up to the model's context and output limits. AWF's `maxTurns` (80) stops a well-behaved harness but is not a hard cap: it counts only `POST`s to chat-completions, responses and messages paths, when the response ends. Other paths are forwarded with the real key and not counted (the key works for `/v1/completions`), and concurrent calls are all admitted before any is counted. AWF forwards every method and path under `/v1` (dot segments cannot leave `/v1`; encoded separators such as `%2f` are passed through), has no `max_tokens` clamp, and skips the model allowlist when the body has no string `model` or is not JSON. All of this was checked in a test fork against a fake upstream: 100 concurrent chat calls all reached it under a turn cap of 20, and 100 calls to uncounted paths reached it under the production limits before the hourly limit answered 429. Hence the dedicated key's budget (Required settings, item 2) is the real cap. - **A sandbox escape** would expose the key on the host. Beyond kernel and Docker bugs, this includes AWF itself: it runs as root on the host, and its API-proxy sidecar, which holds the key, parses requests from the sandbox; both are young code (the AWF probe worked around three of its bugs). Mitigations: the dedicated, low-budget key, quick to rotate; gVisor (`--container-runtime gvisor`) is planned once the harnesses are known to work with it. - **Egress**: the keyless fetch run reaches `github.com` and its subdomains, with git only. The agent's run reaches the API proxy, the inference host (without a key) and the runner's `sshd` through AWF's gateway, and runs for up to 25 minutes. @@ -237,10 +237,23 @@ Callers use `pull_request_target` because fork PRs get no secrets under `pull_re **Audit and proxy logs** (`upload_audit: true`) show what the sandbox connected to and which model was called. AWF redacts the key in the compose environment and logs no request headers, but the artifact (kept 7 days) is readable by any signed-in user of a public repository, so treat it as public. Never set the input in the standing caller configuration. Pass it for one run, through a dispatch input mapped to `upload_audit`, or a separate dispatch-only workflow that calls this one with the same pin, `dry_run: true` and the same environment and secret mapping. -Known limitations of `v0.1.0` (no workaround in the workflow): +**"No review was posted"** (the `Agent review failed` warning of `publish`, also in the run summary) names the cause: + +- _the agent produced no review_ (with the fetch and review outcomes and the exit code): a failure inside the sandbox; the cause is in the `Fetch the pull request in the sandbox` or `Run the review in the sandbox` log of the review job. +- _the review job failed_ (or _was cancelled_) _before the sandbox ran_: see the failed step of that job (for example a `prompt_addendum` path that does not exist). +- _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`: + +- 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. + +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. + +Known limitation (no workaround in the workflow): -- **Inference stalls.** Requests to the inference service sometimes hang for about 300 s before a retry succeeds. A review of a few model calls can then take 17 to 19 minutes, close to the 20-minute harness limit; one more stall ends in the "no review" warning (the run stays green). Re-request the review, or try again when the service is faster. -- **Environment denial.** When the environment refuses the keyed job, `publish` still warns that the agent produced no review and points at sandbox logs, which do not exist. The cause is the environment rule (the branch rule, a required reviewer, or another protection rule of the environment), shown on the `review` job and as a failed deployment, not anything in the sandbox; see [Required settings](#required-settings-in-the-calling-repository), item 1. - **The reset logs no per-file list.** `run-review` logs that the rule files and the files the addendum names are their base versions, but not which instruction files it removed or kept as data. ## Configuration notes @@ -258,7 +271,7 @@ The `stub` harness makes no model call and posts a fixed review containing hosti 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, 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. +- `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`. @@ -277,7 +290,7 @@ This repository's [`self-test.yml`](../.github/workflows/self-test.yml) runs on 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. +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. ### Caller test mode @@ -304,5 +317,6 @@ Before tagging (`v0.1.0` and every later release): 8. A pin to a commit that exists only in a fork of this repository: record what the notice prints, and that the caller-side check in [Pinning and updating](#pinning-and-updating) rejects it. 9. A tag-pinned call, re-run after the tag moved (in a scratch repository, never with release tags here): record which commit the re-run uses. 10. A PR from a fork, by an account without write access, labelled by a writer (`pull_request_target`): the keyed review runs on the fork's head inside the sandbox, the instruction-file reset and its post-conditions hold, and the comment is posted; nothing from the fork runs on the host. + 11. Invariant 6 with a file the addendum names in backticks: a PR that changes that file (the fetch log says `1 file(s) named by the addendum are their base versions`, and the comment is posted), and a PR that replaces it with a symlink to a path no reset pattern covers (the reset restores the base file: the same log line, and the comment is posted). `stub` is enough. 4. Release notes list breaking changes and the evidence (run URLs) of step 3. 5. Callers update their pin to the tag's SHA and check it ([Pinning and updating](#pinning-and-updating)).