Skip to content

fix(mark-notification-read): tolerate a transient run-metadata fetch failure - #843

Merged
max-sixty merged 2 commits into
mainfrom
fix/mark-notification-transient
Aug 5, 2026
Merged

max-sixty merged 2 commits into
mainfrom
fix/mark-notification-transient

Conversation

@tend-agent

Copy link
Copy Markdown
Collaborator

Problem

shared/steps/mark-notification-read.sh runs under set -eo pipefail, and its run_started_at fetch is unguarded:

RUN_STARTED_AT=$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" \
  --jq '.run_started_at')

A transient gh api error there aborts the script non-zero. Both harness actions gate the step on if: success() (claude/action.yaml:514, codex/action.yaml:325), so it only ever runs after the agent already finished its work — and its failure turns a fully-successful run into a red job.

The very next call in the same file is already wrapped for exactly this reason ("a transient API error (non-JSON response) must not fail the composite action"), so this is the one call in the script that doesn't hold the line the file sets for itself.

Reproduced with a gh stub that fails only on the run-metadata call: the script exits 1.

Solution

Guard the fetch and skip the cycle when the timestamp can't be read. Skipping is the right disposition rather than marking unconditionally: without run_started_at the updated_at <= started comparison can't be evaluated, and marking anyway would swallow activity that arrived mid-run. The scheduled tend-notifications poll picks up anything left unread.

Testing

New generator/tests/test_shared_steps.py drives the script with a fake gh on PATH — the same technique test_notifications_precheck_tolerates_transient_non_json already uses for the notifications pre-check. Three cases:

  • run-metadata fetch fails → exit 0, and no thread is marked read
  • activity predating the run → thread marked read (unchanged behaviour)
  • activity newer than the run → left unread (unchanged behaviour)

The first fails on main (exit 1) and passes with the fix. Full suite: 330 passed. shellcheck -S warning and ruff check/format clean.

This is the first test in the repo covering shared/steps/; until now those scripts had only shellcheck, which can't see runtime behaviour. The module docstring notes why they live under generator/tests/ despite not being part of the generator package.

@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 script change is right, and the -z arm isn't redundant: gh api --jq on a field the response doesn't carry yields an empty string rather than null, so an otherwise-well-formed degraded response is caught too (verified against the live API).

One problem in the fixture. The fake gh's canned timestamp is passed in as RUN_STARTED_AT — the same name the script assigns to — so the script inherits the value from its environment. Both happy-path tests therefore pass whether or not the script uses what it fetched. I confirmed it: mutating the script to assign the fetch into a different variable and leave RUN_STARTED_AT untouched still gives 3 passed. With the fixture variable renamed, that same mutant fails test_mark_notification_read_marks_thread_predating_the_run, which is the regression those two tests exist to catch. The failure-path test is unaffected either way.

Comment thread generator/tests/test_shared_steps.py Resolved
Comment thread generator/tests/test_shared_steps.py Resolved
The fake gh's canned timestamp travelled as RUN_STARTED_AT, the name the
script assigns to, so the script inherited it from the environment and both
happy-path tests passed even against a script that discarded what it
fetched. Rename it so those tests exercise the fetch-then-use path.

@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.

Fixture rename addresses the earlier finding. Re-ran the mutant to confirm the tests now have the power they're meant to: with the script's fetch assigned into a different variable and RUN_STARTED_AT left untouched, test_mark_notification_read_marks_thread_predating_the_run fails (api notifications/threads/999 -X PATCH never issued) instead of passing on the inherited value. Unmutated, all three pass. No further concerns; self-authored so no approval from me.

@max-sixty
max-sixty merged commit 1fb1c0d into main Aug 5, 2026
8 checks passed
@max-sixty
max-sixty deleted the fix/mark-notification-transient branch August 5, 2026 16:43
@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 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 8, 2026
)

## Problem

#843 added a guard so a transient failure fetching `run_started_at`
leaves the notification unread rather than failing the step. It tests `[
-z "$RUN_STARTED_AT" ]`, which covers a `gh api` that exits non-zero —
but not a 200 whose body lacks the field. `gh --jq` prints the literal
string `null` there, which is non-empty and passes `-z`.

`null` then reaches the filter as a *string*:

```bash
jq -r --arg started "$RUN_STARTED_AT" '.[] | select(.subject.url == $url and .updated_at <= $started) | .id'
```

Every ISO-8601 timestamp sorts before `null` by codepoint (`2` is
`0x32`, `n` is `0x6e`), so `updated_at <= "null"` is true for every
thread. The step marks read exactly the mid-run activity the guard
exists to preserve — silently, since it's the success path.

Reproduced against the real script with the existing
`test_shared_steps.py` fake `gh`, using a notification dated two months
*after* the run started:

```console
$ FAKE_RUN_STARTED_AT=null bash shared/steps/mark-notification-read.sh
$ cat gh-calls.log
api repos/owner/repo/actions/runs/12345 --jq .run_started_at
api notifications
api notifications/threads/999 -X PATCH     # ← marked read anyway
```

## Fix

Extend the guard to treat `null` as absent, so the missing-field case
takes the same skip-this-cycle path as a failed fetch:

```bash
|| [ -z "$RUN_STARTED_AT" ] || [ "$RUN_STARTED_AT" = "null" ]; then
```

Plus a regression test that asserts nothing is marked read against a
`null` timestamp. It fails on `main` with `marked a thread read against
a null run_started_at` and passes with the fix.

## On reachability

I want to be straight about this: I could not construct a live case
where `/actions/runs/{id}` returns 200 without `run_started_at` — the
field has been on that endpoint for years, and an HTTP error exits `gh`
non-zero and is already handled. So this is hardening against a shape
the API doesn't currently produce, not a bug anyone is hitting.

What makes it worth the two lines is the failure mode rather than its
likelihood: the wrong branch is the *success* path, it swallows unread
notifications instead of erroring, and #843 already decided this is a
place where being wrong should cost a skipped cycle and not silent data
loss. Happy for it to be closed if that's the wrong trade.

Co-authored-by: tend-agent <[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 — 061a4239 Deployed Aug 5, 2026 by tend-agent via review #1082
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