Skip to content

fix(mention): count bot engagement outside jq so --paginate can't split it - #840

Merged
max-sixty merged 3 commits into
mainfrom
fix/mention-paginate-count-30964604774
Aug 5, 2026
Merged

max-sixty merged 3 commits into
mainfrom
fix/mention-paginate-count-30964604774

Conversation

@tend-agent

@tend-agent tend-agent commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

tend-mention's verify step derives three engagement counts by reducing inside a --paginated --jq:

BOT_REVIEWS=$(gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/reviews" \
  --jq '[.[] | select(.user.login == "<<cfg.bot_name>>")] | length')

gh applies --jq once per page, so the reduction emits one count per page rather than one overall. --paginate requests per_page=100, so it takes more than 100 reviews or more than 100 issue comments on a single thread to cross — past that the variable holds e.g. 100\n7, and the guard immediately below it errors:

$ BOT_REVIEWS=$(printf '100\n7\n'); if [ "$BOT_REVIEWS" -gt "0" ]; then echo run; else echo "rc=$?"; fi
bash: [: 100
7: integer expression expected
rc=2

test returning 2 makes the if false, so the step falls through to should_run=false. The bot stops answering participants on exactly the threads where it has engaged the most — silently, with nothing going red. All three sites are on the engagement path that decides whether a non-mention comment gets a session at all: the issue-comment count, the PR-review count, and the PR-comment count.

These render into every adopter's tend-mention.yaml, not just ours.

Solution

Keep the filter a per-element stream — which paginates fine — capture it bare, and test it for emptiness. The values are only ever compared against zero, so no count is needed:

BOT_REVIEWS=$(gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/reviews" \
  --jq '.[] | select(.user.login == "<<cfg.bot_name>>") | .id')
if [ -n "$BOT_REVIEWS" ]; then

Reducing through a pipe (| wc -l) would fix the count but move the substitution's exit status off gh and onto wc. The step declares no shell:, so it runs under GHA's default bash -e {0} — errexit on, pipefail off — and a failing gh api would then read as "no engagement" on a green job rather than aborting the step:

$ bash -e -c 'X=$(false | wc -l); echo "survived, X=[$X]"'
survived, X=[0]
$ bash -e -c 'X=$(false); echo survived'; echo "rc=$?"
rc=1

set -o pipefail is not a safe alternative in this step: grep -qF on the review-comment scan exits on first match, gh takes SIGPIPE, and the pipeline resolves 141 — under pipefail that if goes false and a first-contact mention inside an inline comment is missed. --slurp is not available either: gh api rejects it with the --slurp option is not supported with --jq or --template.

The fourth --paginate in that step — the review-comment body scan piped to grep -qF — is already a per-element stream and is unchanged.

Testing

New test_mention_verify_engagement_lookups_survive_pagination asserts no --paginated --jq in the verify step carries a | length reduction, that the three lookups capture the raw stream, and that no -gt "0" ] numeric comparison remains. It fails against the old template. Regtest snapshots for the mention workflow are updated; uv run pytest is green (328 passed).

Mechanism verified live, forcing multiple pages with per_page=1 against this repo's PR #835 (4 bot review records):

$ gh api --paginate "repos/max-sixty/tend/pulls/835/reviews?per_page=1" \
    --jq '[.[] | select(.user.login == "tend-agent")] | length'
1
1
1
1
1

$ gh api --paginate "repos/max-sixty/tend/pulls/835/reviews?per_page=1" \
    --jq '.[] | select(.user.login == "tend-agent") | .id' | wc -l
5

The empty case is unchanged: no matching records means an empty stream, so [ -n ... ] is correctly false.

Only the template is touched — .github/workflows/tend-mention.yaml picks this up from uvx tend@latest init after the next release, per the generated-workflow rule in CLAUDE.md.

Found while reviewing #835, which fixed the same per-page---jq shape in the review skill's ORPHAN_ID guard. Separate file and separate concern, so it lands separately.

…it it

gh api --paginate applies --jq once per page, so the three engagement
counts in tend-mention's verify step (issue comments, PR reviews, PR
comments) each emitted one count per page instead of one overall. Past
100 records the variable holds e.g. `100\n7`, the `-gt` guard below it
errors with `integer expression expected` and returns 2, and the failed
test falls through to should_run=false — the bot stops answering
participants on the threads it has engaged with most, with nothing
going red.

Keep each filter a per-element stream and reduce with wc -l over the
merged output. --slurp is not an alternative: gh rejects it alongside
--jq.

@tend-agent tend-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pagination diagnosis is right and the per-element stream is the correct shape. One regression in how the count is now reduced, plus the test change it implies.

Piping into wc -l moves the assignment's exit status off gh and onto wc. Verified locally against the semantics the generated step actually runs under (no shell: on the step, so GHA's default bash -e {0} — errexit, no pipefail):

$ bash -e -c 'X=$(false | wc -l); echo "survived, X=[$X]"'
survived, X=[0]
$ bash -e -c 'X=$(false); echo survived'; echo "rc=$?"
rc=1

So a gh api failure at any of the three sites now reads as "no engagement" on a green job, where it previously failed the step loudly. Details and the suggested shape inline.

Taking the suggestions means the four regtest snapshots need regenerating as well.

Comment thread generator/tests/test_generate.py Resolved
Piping the per-element stream into `wc -l` moved the substitution's
exit status off `gh` and onto `wc`. The step declares no `shell:`, so
it runs under GHA's default `bash -e {0}` — errexit on, pipefail off —
and a failing `gh api` (secondary rate limit, a 5xx mid-pagination)
would read as "no engagement" on a green job instead of aborting the
step.

The values are only ever compared against zero, so drop the count: a
bare substitution keeps errexit live and `[ -n ... ]` is immune to the
multi-line value that started this. pipefail is not an alternative —
`grep -qF` on the review-comment scan above exits on first match, `gh`
takes SIGPIPE, and the pipeline would resolve 141.
…shape

The note still opened with "Count outside jq" and pointed at "the `-gt`
below", both of which describe the pre-fix code — the lookups now capture the
per-element stream and test it with `[ -n ... ]`. The other two sites defer to
this note, so a stale lead-in misdirects all three.
@max-sixty
max-sixty merged commit 73085bd into main Aug 5, 2026
5 checks passed
@max-sixty
max-sixty deleted the fix/mention-paginate-count-30964604774 branch August 5, 2026 16:44
@max-sixty max-sixty mentioned this pull request Aug 6, 2026
max-sixty added a commit that referenced this pull request Aug 6, 2026
Bumps the generator to 0.1.14, syncs the lockfile, and adds the CHANGELOG section the release workflow publishes verbatim as the GitHub Release notes.

12 commits since 0.1.13. The release's substance is the deployment-record fix and the environment checks around it. Generated workflows now name the environment as `{name: tend, deployment: false}`, so a job stops filing a deployment record against whatever run it belongs to — under `pull_request_target` that record landed on the PR's own head, so every push to every PR grew a `<bot> deployed to tend` line in its timeline. The branch policy that gates the operational secrets is untouched, and `tend check` grows an `environment-deployments` check that refuses a job naming the environment without the property (#852, #853). Separately, `tend check` widens its environment sweep from secret-holding to credential-holding: an environment counts if it stores a secret or a job requesting `id-token: write` deploys to it, and a ref policy no longer counts as a gate under a trigger a write-scoped actor can steer (#815).

Four silent failures on the agent's own paths are fixed. `tend-mention` reduced its engagement counts inside a `--paginate`d `--jq`, so past one page the numeric guard errored and the bot went quiet on the threads it had engaged with most (#840). The `review` skill counted synthetic reply containers as reviews, which advanced the incremental past unreviewed commits and discarded formed reviews at the close-out (#835). The review's second pass returned a tool-use error because the built-in `/code-review` carries `disable-model-invocation`, and now runs a tend-owned skill that the Codex harness resolves too (#819). And `mark-notification-read` turned a successful run red on a transient API error (#843).

After this tags, adopters pick the changes up on their next nightly regen; tend's own workflows are regenerated in the follow-up PR the release runbook's last step calls for.

Testing: 336 tests pass, `pre-commit run --all-files` is clean, and the release workflow's `awk` extraction was run against the new `## 0.1.14` section locally to confirm the GitHub Release job will find its notes.

> _This was written by Claude Code on behalf of max-sixty_
max-sixty added a commit that referenced this pull request Aug 6, 2026
Regenerates tend's own `tend-*.yaml` workflows against the published 0.1.14, the release's last step, and restamps the one hand-maintained workflow `init` doesn't reach.

All eight generated workflows move from `max-sixty/tend/[email protected]` to `@0.1.14` and name the environment as `{name: tend, deployment: false}`, so a run stops filing a deployment record against whatever it belongs to — under `pull_request_target` that record landed on the PR's own head, which is where the `tend-agent deployed to tend` lines in every PR timeline came from. The unused `id-token: write` grant, dropped from the templates in #815, goes with this regen; tend's agent runs never mint an OIDC token.

`tend-mention` picks up the engagement-count fix from #840: the issue-comment, PR-review, and PR-comment lookups each capture a per-element stream and test it for emptiness, rather than reducing inside a `--paginate`d `--jq` where `gh` emits one count per page. Past 100 results the old form left a multi-line value that the numeric guard below it rejected, so the step fell through to `should_run=false`.

`review-reviewers.yaml` is hand-maintained, so `init` leaves its ref alone; per the `running-tend` restamp convention that one-line bump is folded into the same commit, and `rg -o 'max-sixty/tend/[a-z-]+@[0-9.]+' .github/workflows/ | sort -u` now returns a single line.

`uvx [email protected] check` against `main` fails `environment-deployments`, naming all nine generated jobs; the check reads the workflow files from `HEAD`, so it clears on merge. The two other failures it reports — `claude-auth` and `repo-secret-allowlist`, both on `CLAUDE_CODE_OAUTH_TOKEN` still sitting at repo level rather than in the `tend` environment — are the outstanding half of the credential migration `TODO.md` tracks, and this PR doesn't touch them.

> _This was written by Claude Code on behalf of max-sixty_
max-sixty pushed a commit to max-sixty/worktrunk that referenced this pull request Aug 7, 2026
Automated nightly regeneration of tend's workflow files.

**tend version:** 0.1.13 → 0.1.14

## Notable changes

- **Jobs now name the `tend` environment with `deployment: false`**
(max-sixty/tend#852), so GitHub stops filing a deployment record per run
and posting it on the pull request. This is what the current `tend
check` flags as `environment-deployments` (#3729) — regenerating clears
it, and max-sixty/tend#853 makes `check` refuse the old shape going
forward.
- **`id-token: write` dropped from every tend job** — a side effect of
removing the claude-smoke workflow and its `tend-manual` environment
(max-sixty/tend#820). None of the remaining jobs use OIDC, so the
permission was unused.
- **`tend-mention` counts bot engagement outside `jq`**
(max-sixty/tend#840). `gh api --paginate` applies `--jq` once per page,
so `| length` emitted one count per page; past 100 comments the shell
variable held `100\n7`, the numeric test errored, and the bot fell
through to `should_run=false` — going quiet on exactly its most-engaged
threads.
- **Review and triage skill fixes** — the review-record guards now
ignore synthetic reply containers (max-sixty/tend#835), `/code-review`
is ported into a tend-owned skill (max-sixty/tend#819), and triage
substitutes the real issue number into its PR-body templates instead of
leaving a placeholder (max-sixty/tend#844).
- **Outage reporting is more robust** — a stranded outage row now names
the trigger it points at (max-sixty/tend#823), and marking a
notification read tolerates a transient run-metadata fetch failure
(max-sixty/tend#843).

Full compare: max-sixty/tend@0.1.13...0.1.14

Co-authored-by: worktrunk-bot <[email protected]>
max-sixty pushed a commit that referenced this pull request Aug 11, 2026
#870)

## Problem

When a session opens a PR and then stays alive polling its CI,
`tend-review` fires on that PR and posts findings — and two actors race
to fix them: the still-live session that opened the PR, and the
`tend-mention` session dispatched by the `pull_request_review` event.
Both make the same edits and run the same suite; the loser discovers the
duplication at `git push`, discards its commit, and a full
fix-and-verify cycle is paid twice. No wrong output reaches the repo —
every existing dedup guard fires — but every guard in `running-in-ci` is
anchored at the *output* boundary (`gh pr create`, `git push`, comment
posting), so the collision is only ever discovered after the cost is
sunk.

## Solution

Two rules, one per commit — the first removes the common case, the
second bounds what the first can't reach.

### 1. A role boundary: a review that lands mid-poll isn't yours to
action

Per the second of the two options in #865. The API-based sibling-run
check in the first option can't see which branch a nightly run is
working on — that's only visible from its checkout — so it can't close
the nightly-vs-mention case it was aimed at.

The rule goes in `running-in-ci`'s **CI Monitoring** section rather than
the nightly skill: the mechanism is generic to any session that opens a
PR and stays alive polling it (nightly, ci-fix, triage, weekly, the
hourly review skills), and CI Monitoring is where that "stay alive and
poll" instruction lives. The nightly skill's step 8 gets a one-line
pointer to it, since its "poll CI" step named no section to read.

The session that stands down has to be the one holding the PR: the
mention dispatch fires whether or not the holder also responds, so it is
the run that cannot be suppressed.

### 2. A cost bound: re-check the head SHA before the expensive verify

The role boundary cuts on *who owns the review*, and a [recurrence on
`max-sixty/worktrunk`](#865 (comment))
shows work colliding without the review being read at all. There,
nightly never fetched the review; `codecov/patch` — a required gate on
that repo — flagged the same new closure the reviewer had, so nightly
added the missing test as the follow-up it was gated on
([`957358b46`](max-sixty/worktrunk@957358b),
06:56) while the mention run independently built a near-identical one.
The convergence isn't luck: a reviewer and a coverage tool reading the
same new code ask for the same missing test. Rule 1 permits this by
construction, since closing a red required gate is the carve-out it
keeps.

So the second commit puts a check on the *writing* side, where the cost
is paid: record `headRefOid` before editing, re-check it immediately
before each expensive step (full suite, coverage/snapshot regeneration,
long build) rather than only at `git push`. On that occurrence it would
have caught the sibling push at ~06:56 instead of ~07:01 — before the
integration suite and the post-reset re-verify, which is where most of
the wasted ~$2.14 went.

It also records why the runs-API approach doesn't work, so it isn't
re-derived: both writing runs report `head_branch: main` (nightly runs
on `schedule`, the mention handler on `repository_dispatch`), so a live
sibling is invisible there. Only the `pull_request_target` review run
carries the PR branch — confirmed against runs
[31465475753](https://github.com/max-sixty/worktrunk/actions/runs/31465475753),
[31466280614](https://github.com/max-sixty/worktrunk/actions/runs/31466280614),
and
[31466624503](https://github.com/max-sixty/worktrunk/actions/runs/31466624503).

The other shape the report floats — making a PR-holding session
read-only after `gh pr create` — isn't taken here: that session is the
only one gated on the PR's checks, and no dispatch fires for a red gate,
so a red `codecov/patch` with no accompanying review would sit unfixed.

## What the handoff rests on — and what doesn't back it

`tend-mention`'s `verify` job short-circuits to `should_run=true` on
`PR_AUTHOR == bot_name`, so every review on a bot-authored same-repo PR
reaches the handle job, and the prompt for `client_payload.kind ==
'pull_request_review'` instructs the session to make requested changes
and push. Nightly-opened PRs are same-repo, so the fork exclusion on the
relay job doesn't apply to them.

**The handoff is unbacked — the dispatch is the only thing carrying the
review, and if it's lost nothing recovers it.** GitHub raises no
notification for an actor's own activity, so a `tend-agent` review on a
`tend-agent`-authored PR creates no notification thread at all, and the
notifications poll's "stale unanswered items" path has nothing to find.
And the dispatch can be lost silently: `tend-mention-handle-<PR#>` runs
at `cancel-in-progress: false`, and per CLAUDE.md's "GHA queue depth =
1" note a third job arriving replaces the queued one — on a PR drawing
several events, the review's handle job is exactly the one that gets
replaced. Before this change the still-live session was the fallback;
after it, the only residual is "name the outstanding review in your
summary", which lands in the session log rather than anywhere a
maintainer sees.

That is the accepted cost rather than an oversight: the duplicated
fix-and-verify cycle is the common outcome and a dropped dispatch is
rare, so paying the duplication on every review to insure against it is
the worse deal. But the property a future reader will lean on is that
the handoff has no second line of defence.

<details><summary>How the no-self-notification behaviour was
checked</summary>

`gh api "notifications?all=true&per_page=100"` returns the newest 50
threads, `updated_at` desc. The newest row is `2026-08-06T04:23:44Z`.

Absent entirely — each bot-authored, each carrying bot self-reviews
*newer* than that newest row, so they would sort first if a thread
existed:

- this PR (#870) — opened 08:56, self-review 09:02:30
- #868 — opened 08:52, self-reviews 08:57:13 / 08:59:40 / 08:59:47

Present, but only keyed to another actor's action:

- #843 — self-reviews 07:19 and 07:23 on 08-05; thread `updated_at`
`16:43:23`, ~20s after the maintainer's merge at `16:43:03`
- #840 — self-reviews 01:02–01:05; thread `updated_at` `16:44:47`, after
the merge at `16:44:26`

</details>

## Testing

None — the change is skill prose, and no test covers skill markdown.
Verified against the mention template's `verify` logic and prompt text
(`generator/src/tend/templates/mention.yaml.j2`) that the run being
handed to actually receives and actions these reviews, and against the
notifications API that no self-activity thread exists to back that
dispatch up. The second commit's premises were checked against the
public record on `max-sixty/worktrunk`: the commit order and timing on
#3799, and the `head_branch` each of the three runs reports.

---

Closes #865 — automated triage

---------

Co-authored-by: tend-agent <[email protected]>

This branch was previously deployed

1 inactive deployment
tend — 614e4275 Deployed Aug 5, 2026 by tend-agent via review #1078
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.

2 participants