Skip to content

Commit d283f2e

Browse files
committed
refactor: move the routine call to Python so every answer is tested
The fire step was shell and curl, which could only be checked by firing the real routine. It is now standard-library Python (3.10 syntax), inline in the reusable workflow with id "send", and tests/test_fire.py runs it against the stub on 127.0.0.1. The routine API's address is a constant in the script; the tests swap it through the harness's substitutions, so no input or event field can change where the token goes. Kept as before: the token is checked first, then the trigger id against trig_[A-Za-z0-9]+; one POST to the same endpoint with the same four headers; the body is {"text": <decision text>} written by a JSON encoder; short timeouts (10 s to connect and per read, 30 s in all); no retry; continue-on-error keeps a failure from turning the check red. Pinned by the tests, with these deliberate differences from curl: - Only a 2xx answer counts as sent. curl's --fail-with-body passed a 3xx; a redirect is now an error and is not followed. - A failure is one ::error:: annotation with the HTTP status and at most 200 characters of the answer, on one line, with the token taken out. curl printed the whole answer as plain text, so an answer that repeated the token printed it. - A decision with no string text is an error and nothing is sent. jq would have sent {"text": null}. - The step writes sent=true only when the request was accepted, which the react job (#16) will read. Refs #15 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012Jmn7ot2xooXpcuW44QqtU
1 parent b090948 commit d283f2e

4 files changed

Lines changed: 313 additions & 25 deletions

File tree

‎.github/workflows/claude-review.yml‎

Lines changed: 145 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -379,31 +379,157 @@ jobs:
379379
cancel-in-progress: false
380380
steps:
381381
- name: Fire the code-review routine
382+
id: send
382383
# The review is advisory: a failed request (an outage, a revoked token) shows as a failed step in this run, not
383384
# as a red check on the pull request.
384385
continue-on-error: true
385386
env:
386387
CLAUDE_ROUTINE_TOKEN: ${{ secrets.CLAUDE_ROUTINE_TOKEN }}
387388
TRIGGER_ID: ${{ inputs.routine-trigger-id }}
388389
DECISION: ${{ needs.decide.outputs.decision }}
390+
# Python's standard library only (3.10 features), so nothing is installed; tests/test_fire.py runs this script.
391+
shell: python3 {0}
389392
run: |
390-
if [ -z "$CLAUDE_ROUTINE_TOKEN" ]; then
391-
echo "::error::CLAUDE_ROUTINE_TOKEN is empty: pass it to the reusable workflow as a secret"
392-
exit 1
393-
fi
393+
# Only a 2xx answer counts as sent. Anything else is an error annotation and a failed step, which the job's
394+
# continue-on-error keeps from turning the check red.
395+
import http.client
396+
import json
397+
import os
398+
import re
399+
import signal
400+
import sys
401+
import urllib.error
402+
import urllib.request
403+
import uuid
404+
405+
# The routine API's address. It is fixed here: no input or event field can change where the token goes.
406+
API_BASE_URL = "https://api.anthropic.com"
407+
# Seconds to wait to connect, and then for each read of the answer.
408+
TIMEOUT_SECONDS = 10
409+
# Seconds the whole request may take, however slowly the answer arrives.
410+
TOTAL_SECONDS = 30
411+
# The most of an error answer's body shown in the annotation.
412+
EXCERPT_CHARACTERS = 200
413+
394414
# The id goes into the URL, so anything but a trigger id is refused.
395-
if ! [[ "$TRIGGER_ID" =~ ^trig_[A-Za-z0-9]+$ ]]; then
396-
echo "::error::routine-trigger-id is not a trigger id (trig_…): pass vars.CLAUDE_ROUTINE_TRIGGER_ID, set under Settings > Secrets and variables > Actions > Variables"
397-
exit 1
398-
fi
399-
# jq writes the body, so nothing in the pull request's fields can break the JSON.
400-
body="$(jq --compact-output '{text: .text}' <<<"$DECISION")"
401-
# No retry: a request that timed out may still have started a session, and a second would review twice. A
402-
# failed request is re-run by hand. The token goes in on standard input, never on curl's command line.
403-
curl --fail-with-body --silent --show-error --connect-timeout 10 --max-time 30 -X POST \
404-
"https://api.anthropic.com/v1/claude_code/routines/$TRIGGER_ID/fire" \
405-
-H @- \
406-
-H "anthropic-version: 2023-06-01" \
407-
-H "anthropic-beta: experimental-cc-routine-2026-04-01" \
408-
-H "Content-Type: application/json" \
409-
-d "$body" <<<"Authorization: Bearer $CLAUDE_ROUTINE_TOKEN"
415+
TRIGGER_ID = re.compile(r"trig_[A-Za-z0-9]+")
416+
417+
418+
class NotSent(Exception):
419+
"""The request was not sent, or the routine trigger did not accept it; the message says why."""
420+
421+
422+
class TotalTimeout(Exception):
423+
"""The whole request took longer than TOTAL_SECONDS."""
424+
425+
426+
def error(message):
427+
# Escaped as GitHub's workflow commands require, so no value can end the annotation or start another.
428+
escaped = message.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
429+
print(f"::error::{escaped}", flush=True)
430+
431+
432+
def output(name, value):
433+
# A random delimiter makes any value safe, even one with a newline in it.
434+
delimiter = f"ghadelim_{uuid.uuid4()}"
435+
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as file:
436+
file.write(f"{name}<<{delimiter}\n{value}\n{delimiter}\n")
437+
438+
439+
def excerpt(body, token):
440+
"""The start of an answer's body, on one line, with the token taken out in case the answer repeats it."""
441+
text = body.decode("utf-8", errors="replace").replace(token, "[token]")
442+
text = " ".join("".join(c if c.isprintable() else " " for c in text).split())
443+
if len(text) > EXCERPT_CHARACTERS:
444+
text = text[:EXCERPT_CHARACTERS] + "…"
445+
return text
446+
447+
448+
class NoRedirects(urllib.request.HTTPRedirectHandler):
449+
# A redirect is an answer to report, not to follow: following it could send the token somewhere else.
450+
def redirect_request(self, *args, **kwargs):
451+
return None
452+
453+
454+
# Proxy settings in the environment are honoured, as curl honoured them before.
455+
opener = urllib.request.build_opener(NoRedirects)
456+
457+
458+
def on_total_timeout(signum, frame):
459+
raise TotalTimeout()
460+
461+
462+
def post(url, token, body):
463+
"""POSTs body to url once and returns (status, the start of the answer's body). There is no retry: a request
464+
that timed out may still have started a session, and a second would review twice. A failed request is re-run
465+
by hand. The token is only ever a request header."""
466+
request = urllib.request.Request(
467+
url,
468+
data=body,
469+
method="POST",
470+
headers={
471+
"Authorization": f"Bearer {token}",
472+
"anthropic-version": "2023-06-01",
473+
"anthropic-beta": "experimental-cc-routine-2026-04-01",
474+
"Content-Type": "application/json",
475+
},
476+
)
477+
signal.signal(signal.SIGALRM, on_total_timeout)
478+
signal.setitimer(signal.ITIMER_REAL, TOTAL_SECONDS)
479+
try:
480+
try:
481+
with opener.open(request, timeout=TIMEOUT_SECONDS) as response:
482+
return response.status, response.read(4096)
483+
except urllib.error.HTTPError as answer:
484+
try:
485+
answer_body = answer.read(4096)
486+
except (OSError, http.client.HTTPException):
487+
answer_body = b""
488+
return answer.code, answer_body
489+
except (OSError, http.client.HTTPException, ValueError, TotalTimeout) as failure:
490+
# URLError, timeouts, refused or dropped connections, a cut-off answer. Only the failure's kind is
491+
# reported.
492+
reason = getattr(failure, "reason", failure)
493+
raise NotSent(f"Could not reach the routine trigger ({type(reason).__name__}); no review was requested")
494+
finally:
495+
signal.setitimer(signal.ITIMER_REAL, 0)
496+
497+
498+
def fire(token, trigger_id, decision):
499+
if not token:
500+
raise NotSent("CLAUDE_ROUTINE_TOKEN is empty: pass it to the reusable workflow as a secret")
501+
if not TRIGGER_ID.fullmatch(trigger_id):
502+
raise NotSent(
503+
"routine-trigger-id is not a trigger id (trig_…): pass vars.CLAUDE_ROUTINE_TRIGGER_ID, set under "
504+
"Settings > Secrets and variables > Actions > Variables"
505+
)
506+
try:
507+
text = json.loads(decision).get("text")
508+
except (ValueError, AttributeError):
509+
text = None
510+
if not isinstance(text, str):
511+
raise NotSent("The request decision has no request text; no review was requested")
512+
# json writes the body, so nothing in the pull request's fields can break it.
513+
body = json.dumps({"text": text}, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
514+
status, answer = post(f"{API_BASE_URL}/v1/claude_code/routines/{trigger_id}/fire", token, body)
515+
if not 200 <= status < 300:
516+
message = f"The routine trigger answered HTTP {status}; no review was requested"
517+
shown = excerpt(answer, token)
518+
raise NotSent(f"{message}: {shown}" if shown else message)
519+
print(f"Sent the review request to the routine trigger (HTTP {status})", flush=True)
520+
521+
522+
try:
523+
fire(
524+
os.environ.get("CLAUDE_ROUTINE_TOKEN", ""),
525+
os.environ.get("TRIGGER_ID", ""),
526+
os.environ.get("DECISION", ""),
527+
)
528+
# Only a request the routine trigger accepted counts as sent.
529+
output("sent", "true")
530+
except NotSent as failure:
531+
error(str(failure))
532+
sys.exit(1)
533+
except Exception as failure: # Anything unexpected is reported by its kind only, and is not sent.
534+
error(f"Could not send the review request: the step broke ({type(failure).__name__})")
535+
sys.exit(1)

‎README.md‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ All three secrets, `CLAUDE_ROUTINE_TOKEN`, `CLAUDE_REVIEW_APP_ID` and `CLAUDE_RE
5252
A run has two jobs:
5353

5454
- `decide` reads the event and decides. It writes a one-line summary, such as `Claude review: skipped (draft)`, to the run's summary page. It does not fail: every step that can fail is allowed to, and the decision then becomes a skip with the reason `decision-failed`.
55-
- `fire` sends the request to the routine trigger. It runs only when `decide` decided to fire. A failed request shows as a failed step, but the job and the check stay green.
55+
- `fire` sends the request to the routine trigger. It runs only when `decide` decided to fire. It sends the request once, with no retry, and does not follow a redirect. Only a `2xx` answer counts as sent. A failed request shows as a failed step with an error giving the HTTP status, but the job and the check stay green.
5656

5757
`fire` holds no permissions.
5858
Only one `fire` runs per pull request at a time: a second waits rather than cancelling the first.
@@ -101,7 +101,7 @@ An event that has no pull request author, such as a payload whose `user` is `nul
101101

102102
## Python steps
103103

104-
Some steps, such as the membership lookup, are written in Python.
104+
Some steps, such as the membership lookup and the request to the routine trigger, are written in Python.
105105
They use only Python's standard library and keep to Python 3.10, so nothing is installed when they run.
106106
Like the request decision, each one is kept inline in the reusable workflow, with `shell: python3 {0}` and an `id`, because a reusable workflow cannot read files from this repository.
107107
The unit tests in `tests/` read each step's script out of the workflow, so they test exactly what ships.
@@ -129,7 +129,7 @@ request-decision/test
129129

130130
### Running the unit tests
131131

132-
The unit tests need `python3` (3.10 or later), `bash` and `yq`, and no network: a test that needs GitHub's API starts a stand-in server on 127.0.0.1.
132+
The unit tests need `python3` (3.10 or later), `bash` and `yq`, and no network: a test that needs GitHub's API or the routine trigger starts a stand-in server on 127.0.0.1.
133133

134134
```sh
135135
python3 -m unittest discover --start-directory tests
@@ -140,8 +140,8 @@ python3 -m unittest discover --start-directory tests
140140
`tests/harness.py` runs one step of the reusable workflow on its own:
141141

142142
- `run_step(job, step_id, env, api_url=...)` reads the step's script out of the workflow with `yq`, runs it with the step's shell, and returns what it left: its exit code, standard output and error, its outputs (`.outputs`), its summary (`.summary`) and its `::error::` annotations (`.errors()`). The step sees only the `env` the test gives it, which must be names the step declares in its `env`, plus the runner's own variables, such as `GITHUB_OUTPUT`.
143-
- `StubServer(routes)` stands in for GitHub's API. `routes` maps a path to a status and body, to `StubServer.HANG` for an answer that never comes, or to `StubServer.DROP` for a connection closed without one. It records every request.
144-
- `substitutions` replaces text in the script before it runs, such as a timeout constant lowered so a test does not wait. Each piece of text must appear exactly once in the script.
143+
- `StubServer(routes)` stands in for GitHub's API or the routine trigger. `routes` maps a path to a status and body, to `StubServer.HANG` for an answer that never comes, or to `StubServer.DROP` for a connection closed without one, for `GET` and `POST` alike. It records every request's method, path and headers in `.requests`, and its body in `.bodies`.
144+
- `substitutions` replaces text in the script before it runs, such as a timeout constant lowered so a test does not wait, or the routine API's fixed address swapped for the stand-in server's. Each piece of text must appear exactly once in the script.
145145

146146
1. Add a test method to the step's test file, such as `tests/test_lookup.py`, or a new `tests/test_<step>.py` for a new step. Name it for what the step does, such as `test_a_pending_membership_is_not_a_member`.
147147
2. Run the unit tests and check the new test passes.

0 commit comments

Comments
 (0)