Skip to content

feat: add security preflight checks - #1

Merged
max-sixty merged 1 commit into
mainfrom
security
Mar 23, 2026
Merged

max-sixty merged 1 commit into
mainfrom
security

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

Adds runtime verification that the default branch is protected — the primary security boundary from docs/security-model.md. Two enforcement points:

action.yaml preflight — checks branch protection via GitHub API before running Claude. Hard fails if the default branch is unprotected, preventing the bot from operating without the merge restriction that caps its blast radius.

continuous check CLI command — local verification of three security prerequisites: branch protection on default branch, bot permission level (should be write, not admin), and required secrets. Degrades gracefully when gh isn't installed or the token lacks permission (checks show as SKIP, not FAIL).

continuous init now prints a reminder to run continuous check after generating workflows.

This was written by Claude Code on behalf of @max-sixty

Add runtime verification that the default branch is protected (the
primary security boundary from docs/security-model.md). Two enforcement
points:

- action.yaml: preflight step checks branch protection before running
  Claude, hard fails if unprotected
- `continuous check` CLI command: verifies branch protection, bot
  permission level, and required secrets using gh CLI

`continuous init` now prints a reminder to run `continuous check`.

Co-Authored-By: Claude <[email protected]>
@max-sixty
max-sixty merged commit a1c3791 into main Mar 23, 2026
@max-sixty max-sixty mentioned this pull request May 11, 2026
max-sixty pushed a commit that referenced this pull request Aug 12, 2026
… and stop the fetch limit re-truncating it (#838)

`list-recent-runs.sh`'s dropped-tick recovery anchors the window floor
on the previous **completed** run of the analyzing workflow. `completed`
is a status, not a conclusion, so a run that failed before its agent
produced any analysis advances the anchor exactly as if it had covered
its hour. After an outage the next green run therefore resumes one tick
back and reports an all-clear for a window nothing ever looked at — and
the gap is unrecoverable, because the following run's floor advances
past it too.

This is not hypothetical: it just consumed ~15 hours of
`review-reviewers` coverage.

## What happened

Every `review-reviewers` run from
[30897445507](https://github.com/max-sixty/tend/actions/runs/30897445507)
(09:41Z) through
[30959115609](https://github.com/max-sixty/tend/actions/runs/30959115609)
(23:10Z) failed — 16 consecutive runs, all five matrix legs, `claude -p`
exiting 1 after ~4s. The `result` event in every leg's session log is
identical: `is_error: true`, `num_turns: 1`, `result: "You've hit your
weekly limit · resets 12am (UTC)"`, with `token-usage.json` all zeros.
The agent never started, so none of those runs analyzed anything. (The
outage itself is already tracked by #831 and the annotation-legibility
work in #816 / #818 — this PR is only about the window the outage
swallowed.)

The last run that did analyze anything is
[30893072876](https://github.com/max-sixty/tend/actions/runs/30893072876)
at 08:42Z, which is also the last entry in the `numbagg/numbagg`
evidence gist. At this run's tick (23:47Z intended), the recovery query
picked
`{"conclusion":"failure","createdAt":"2026-08-04T23:10:57Z","databaseId":30959115609}`
and floored the window at 22:47Z, so `list-recent-runs.sh` returned
exactly one row: a `tend-notifications` pre-check no-op.

Everything `numbagg-bot` actually did in the swallowed window sat
outside that floor — PRs
[#719](numbagg/numbagg#719) and
[#720](numbagg/numbagg#720), issue
[#721](numbagg/numbagg#721), three reviews and
four inline comments on #719, and comments on #716, #721 and #1. That is
the densest window numbagg has had in days, and per the skill's Step 1
("If empty, record the run as all-clear … then skip to Step 6") it would
have been recorded as a quiet hour. I only found it by diffing the run
list against the gist's last recorded boundary by hand.

## The change

Anchor on the previous **successful** run rather than any completed one,
filtering server-side with `--status success` (the flag takes
conclusions as well as statuses), and when the existing 6h cap clamps
the recovered floor, say so on stderr so the caller records a coverage
gap instead of a false all-clear. A partially-failed matrix run counts
as a failure here, which only ever widens the window — overlap is
re-offered work the caller dedups against its own evidence log, whereas
a gap is silently unanalyzed.

Widening the window then exposed a second truncation one layer down, so
the fetch loop moves with it. It passed `--limit 50` while a recovered
window spans up to 8h, and `gh run list` returns newest-first — so a
workflow over the limit silently drops its *oldest* runs, which are
exactly the ones in the gap the anchor just reached back for. On
`max-sixty/tend`, `tend-mention` alone produces 57 runs in an 8h window.
The limit is now 200, and a workflow returning exactly the limit warns
rather than truncating in silence.

Two smaller pieces: the anchor query routes through `gh_retry` and exits
non-zero instead of `2>/dev/null || true`, so a transient API error can
no longer masquerade as "no successful run" and emit a confident warning
naming a cause that didn't happen; and `review-reviewers/SKILL.md`,
which still said "if empty, record all-clear" with nothing about the
stderr warnings, now treats any `WARNING:` as a coverage gap — without
that, an agent following the skill literally would print the warning and
record an all-clear anyway.

When every tick fires and succeeds the anchor is the previous tick,
`prev_intended == intended - 3600 == COMPLETED_AFTER`, and the
comparison is a no-op — output is byte-identical to today's on the
healthy path.

<details><summary>Verification against live data</summary>

Same tick, same repo, before vs. after:

```
# anchor query — before (--limit 10, no conclusion filter)
{"conclusion":"failure","createdAt":"2026-08-04T23:10:57Z","databaseId":30959115609}

# anchor query — after (--limit 50, conclusion == "success")
{"conclusion":"success","createdAt":"2026-08-04T08:42:12Z","databaseId":30893072876}
```

`TARGET_REPO=numbagg/numbagg ./list-recent-runs.sh` after the change
returns 5 runs instead of 1, preceded by:

```
WARNING: the last successful 'review-reviewers' run started 2026-08-04T08:42:12Z, more than 6h back. Window floored at 2026-08-04T17:47:00Z; runs that completed before it are NOT in this list. Record a coverage gap, not an all-clear.
```

The recovered anchor (08:42:12Z) matches the gist's last recorded
coverage boundary exactly. Also exercised: the no-successful-run branch
(warns, floors at the cap, exits 0) and the unset-`GITHUB_WORKFLOW`
branch (recovery skipped, unchanged). `shellcheck` clean; `bash -n`
clean. Also exercised after the review follow-ups: the fetch-limit
truncation warning (via a copy with `RUN_LIMIT=5`) and the anchor-query
failure path (exits 1 rather than degrading). See [the follow-up
comment](#838 (comment))
for the full branch table.

</details>

## Gates

- **Evidence level**: Critical — a clearly wrong outcome (the analysis
records an all-clear for a window it never examined, and the window is
then unreachable), which acts on 1 occurrence. Occurrences: 1 this run,
0 historical (no prior gist entry records an outage of a length that
would trigger it).
- **Structural, not stochastic**: no decision point. The anchor query is
deterministic; replayed ten times it picks the failed run ten times.
- **Change type**: targeted fix — one predicate, one query limit, two
stderr warnings. Normal evidence bar under Gate 2, met.
- **Dedup**: checked open issues #831, #830, #829, #828, #827, #824,
#822, #817, #816, #801, #799, #750, #624 and open PRs #826, #825, #823,
#821, #819, #818, #809. #816 / #818 / #823 / #809 all concern outage
*reporting* — naming the cause in the annotation, the stranded trigger,
per-run comment dedup — none touch window recovery. Searching issues and
PRs for `list-recent-runs` surfaces only the three merged predecessors
#526, #753 and #784.

Evidence log: https://gist.github.com/19b5ab297bb7ac7e1e9a44d595ccde0f

---------

Co-authored-by: tend-agent <[email protected]>
max-sixty pushed a commit that referenced this pull request Aug 15, 2026
## Problem

`tend-mention` put the 👀 on in `verify` and took it off in `handle`.
`always()` on the remove step only governs step execution *within a job
that started* — a job cancelled while still queued allocates no runner
and runs no steps at all. `handle`'s `cancel-in-progress: false` holds a
*running* job; GitHub still evicts a *pending* one when a newer run
arrives
([workflow-syntax](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#concurrency)).
So a burst of three mentions on one thread evicts run 2's pending
`handle` after its `verify` already reacted, leaving a 👀 that claims a
session is working with no session and nothing left to remove it.
Eviction is the routine path; any route where `handle` never starts (a
`verify` failure after the react, an environment-protection refusal) has
the same shape. `review` and `triage` were never exposed — both halves
are steps of one job there.

Separately, the remove step listed reactions with no `--paginate`, so it
read only the first 30. On `review` and `triage` the target is the
issue/PR itself, where 👀 is also the ordinary "watching this" reaction —
past 30 of them the bot's own falls off page 1, `REACTION_ID` comes back
empty, and the step exits 0 having silently kept the reaction.

Both bugs strand the same signal, so they're fixed together.

## Solution

Move `react_eyes` into `handle` as its first step, matching `review` and
`triage`: the eyes can only go on once the job that removes them has
started. Its `if:` drops the `should_run` conjunct (the job's own `if`
already carries it) and reads `needs.verify.outputs.reason` instead of
`steps.check.outputs.reason`.

Add `--paginate` (and `per_page=100`) to the reaction lookup in
`unreact_eyes`; the existing `--jq` filter and `head -n1` already handle
the rest.

Of the issue's three options this is #1. #3 (`queue: max`) would run
every queued session instead of dropping the redundant ones — a cost
change, not a fix.

## The trade this makes

What a user sees changes, and not only by a few seconds. On an idle
thread the 👀 now lands after `verify` finishes rather than at the end of
it — seconds, on a signal that already lags the comment by the length of
`verify`. On a busy thread — the burst case this fix exists for —
`handle` queues behind the in-flight session under
`tend-mention-handle-<number>` with `cancel-in-progress: false`, so the
second mention's 👀 waits out that whole session, and a third mention
evicts the queued `handle` before it ever reacts, leaving the second
comment with no acknowledgment at all. Before this change that comment
got its 👀 immediately — stranded, which is the bug.

That's the intended trade: 👀 means "a session is working on this right
now", and under the new placement it is never claimed falsely. Silence
on a queued comment is recoverable — the handling prompt already tells
the session to pick up other unaddressed comments on the thread —
whereas a stranded 👀 is a standing false claim nothing clears.

## Testing

`test_eyes_come_off_when_the_session_ends` now asserts the invariant the
bug violated — that exactly one job in each workflow carries eyes steps
— plus `--paginate` on the lookup. Both assertions fail on the old
templates (`mention: the eyes are split across {'handle', 'verify'}`;
`triage/review: the reaction lookup only reads the first page`) and pass
after. Regtest snapshots regenerated; full Python suite green (554
passed).

The generated `tend-*.yaml` in this repo are untouched — they track the
released generator and update on the nightly regen.

---
Closes #989 — automated triage

Co-authored-by: tend-agent <[email protected]>
max-sixty added a commit that referenced this pull request Aug 29, 2026
Every question worth asking of the fleet's spend is per-subject — cost
per PR, repeat reviews of one branch, two agents racing on one commit —
and `token-usage.json` recorded none of it. It carried `input_tokens`,
`output_tokens`, the cache fields, `turns`, `model` and `cost_usd`, so
each of those questions cost a hand-rolled join against `gh run list`
and the API behind it.

## The record

`shared/steps/token_usage.py` now writes `repo`, `workflow`, `run_id`,
`run_attempt`, `event`, `number` (the PR or issue) and `head_sha`
alongside the counts, on both harnesses. Two of those are not on the run
listing at all: the PR/issue number, and a `head_sha` read from the
event rather than from the ref the run was queued on. The rest are there
so the record stands on its own, read out of a gist or a downloaded
artifact.

The subject fields follow one rule: an event's subject is a thread or a
commit, and each field reports its own half. So a `pull_request_target`
run records the PR's head rather than the default-branch commit
`GITHUB_SHA` gives it, and a mention on a PR records the PR number with
no commit rather than the default-branch tip it never touched. Every key
resolves independently — the step is `if: always()` and may not fail the
job.

The event-payload readers move from `_issue.py` to `_common.py`
(`event_payload`, `dig`, `as_int`, `subject_number`, `subject_sha`), so
the outage-issue row and the usage record resolve a trigger the same
way.

## The report

`plugins/tend-ci-runner/scripts/token-report.sh` leads with cost, and
the rollup tables sort by it — a cached input token is priced far below
an output token, so the old cache-read ordering ranked volume rather
than spend. A new table groups by subject, collapsing repeat work on one
PR or commit into a single row with a run count. Runs that emitted no
result event can't be priced, and booking them at `$0` buried them under
that sort, so they get their own table ranked by tokens.

The script was also rebuilt around one canonical stream. The download
loop writes one JSON line per job — the `token-usage.json` plus the
run's row from `gh run list` — and two jq programs read it: jobs to runs
to totals, and the summary. That replaced a per-run aggregate, an entry
builder, a totals pass, a header pass, a `JQ_DEFS` shell variable
concatenated into four table programs, `column -t`, three of its four
bash counters, three bash conditionals for the footnotes, and two
hardcoded empty-report literals.

<details>
<summary>Bugs found in review, each with a test that fails without its
fix</summary>

- `head_sha` reported the default branch's tip for `issue_comment` and
`repository_dispatch` — the commit a mention run leaves behind when it
`gh pr checkout`s the PR head, so a mention record and a review record
for the same PR revision named different commits.
- `as_int` coerced bools and floats. Anyone holding `contents: write`
can POST a `repository_dispatch` with `client_payload.pr: true`, and
`_issue.ref()` renders the result into a public issue comment — `#1` is
a plausible reference to somebody else's PR.
- One unparseable `token-usage.json` aborted the whole report under `set
-e`, losing every other run's data with it.
- An artifact holding no usable object put a null into the cost
arithmetic and killed two tables after stdout had already been written.
It is now skipped and counted: a torn upload's spend is unknown, not
zero.
- `column -t` splits on whitespace, so a workflow name containing a
space shifted every column right. The summary pads its own columns now.
- Cost truncated in the per-run row and rounded in the rollups, so a
matrix run read a cent below the workflow total it was the whole of.

</details>

`conclusion` leaves the report's stdout JSON; nothing read it, and it
was only there because the run row was merged in wholesale.

> _This was written by Claude Code on behalf of max-sixty_
@tend-agent tend-agent mentioned this pull request Sep 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant