Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .ytstack/spec/hooks-and-state.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ W8 and W9 are prompts for `ytstack:reconcile`, which moves history out with cons

Every hook except `pr-watch` sources the library and resolves from the payload `cwd`. Every hook except `session-start` and `pr-watch` exits 0 silently when no `.ytstack` directory resolves.

`pr-watch` (SessionStart, UserPromptSubmit, PreToolUse and PostToolUse on `Bash|mcp__.*create_pull_request.*`; for Codex also Stop, via `bin/ytstack-codex hook pr-watch`) is the opt-in PR watch: it exits 0 with no output and without starting Python unless `~/.ytstack/config` has `pr_watch=on`, then hands the payload to `tools/pr-watch/pr-watch.py hook`. It works for any repository, with or without `.ytstack`, and fails open (an engine error is one stderr line, exit 0). Engine, state (`~/.ytstack/pr-watch/`), worker and migration are described in `docs/pr-watch.md`; `bin/ytstack-check` exempts this hook from the resolver rule by name. A merge the worker observes queues one notice per PR (outbox key `merged:<repo>:<n>`, a fixed template that names `ytstack:review-lessons`); it is delivered without the fresh GitHub read other notices get and is never cancelled by a later read (`tests/pr_watch/test_merge_notice.py`).
`pr-watch` (SessionStart, UserPromptSubmit, PreToolUse and PostToolUse on `Bash|mcp__.*create_pull_request.*`; for Codex also Stop, via `bin/ytstack-codex hook pr-watch`) is the opt-in PR watch: it exits 0 with no output and without starting Python unless `~/.ytstack/config` has `pr_watch=on`, then hands the payload to `tools/pr-watch/pr-watch.py hook`. It works for any repository, with or without `.ytstack`, and fails open (an engine error is one stderr line, exit 0). Engine, state (`~/.ytstack/pr-watch/`), worker and migration are described in `docs/pr-watch.md`; `bin/ytstack-check` exempts this hook from the resolver rule by name. For Claude Code the UserPromptSubmit output is injected only when a status line changed since the last injection in that session (fingerprint in `meta` key `surface:<session>`, reset on SessionStart) or a notice is pending; a `git push` the PostToolUse hook sees in a bound worktree sets `pushed_at` on that branch's watch, which shows `head moved` and makes the worker read it next tick (`tests/pr_watch/test_under_load.py`). A merge the worker observes queues one notice per PR when the watch saw a bot finding on it (outbox key `merged:<repo>:<n>`, a fixed template that names `ytstack:review-lessons`); it is delivered without the fresh GitHub read other notices get and is never cancelled by a later read (`tests/pr_watch/test_merge_notice.py`).

| Hook | Event | Reads from the payload | Effect | Exit |
|---|---|---|---|---|
Expand Down
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Changed

- **The PR watch stays readable under load.** With many open pull requests
and background agents, four things made its output hard to act on; now:
- a skipped or neutral check that nothing requires (no branch rule, no
label, not a review bot's check) no longer turns a pull request into
`action_required`; required and review-bot checks still have to pass;
- after a push of your own to a watched pull request, its line says
`head moved by a push ... ago, not yet polled` instead of repeating the
old head's findings (a stale merge conflict, for example), and the worker
reads that pull request on its next tick;
- the status block appears in Claude Code only when one of its lines
changed, or with a notice, instead of on every prompt; a resumed or
compacted session sees it once again;
- the suggestion to run `review-lessons` after a merge comes only for pull
requests where the watch saw a review-bot finding; `ytstack-upkeep` still
lists every merged pull request that was not checked.

## [0.9.2] - 2026-11-14

### Fixed
Expand Down
22 changes: 16 additions & 6 deletions docs/pr-watch.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ Reported to the session that created the PR, once per occurrence:
- a failed check run or commit status on the current head (checks of the review bots named in the policy excluded)
- an unresolved review thread whose first comment is from a bot (or a reviewer login from the policy), outdated threads included
- a merge conflict, when GitHub returns `mergeable: false`
- a merge, once per PR: "PR merged; if this project declares own reviewers,
run ytstack:review-lessons for #N". The worker does not know projects, so
- a merge, once per PR, when the watch saw at least one bot finding on it:
"PR merged; if this project declares own reviewers, run
ytstack:review-lessons for #N". A PR without a bot finding has nothing an
own reviewer could have missed, so it gets no suggestion. The worker does not know projects, so
the notice is conditional; the session checks `## Own reviewers` in
`.ytstack/spec/REVIEW.md` (`docs/ux/review-policy-format.md`, "Escapes").
It comes from the read that saw the PR closed as merged, costs no GitHub call
Expand Down Expand Up @@ -106,6 +108,15 @@ worker tick old and the agent re-reads GitHub before acting. A session that
owns no open watch gets no output. A red check therefore reaches the agent with
the next prompt, not on its own.

The status block is injected only when one of its lines changed since the last
injection in that session (ages do not count), or with a pending notice; a
session that gets many prompts from background agents sees it once per change,
not once per prompt. SessionStart (start, resume, compaction) resets this, so
the next prompt shows the block again. When the session pushes to a watched
PR's branch (`git push` seen by the PostToolUse hook in a bound worktree), the
line says `head moved by a push ... ago, not yet polled` instead of the old
head's findings, and the worker reads that PR on its next tick.

**Codex.** The worker talks to the running Codex app server over its local
socket and starts a turn in the owning thread when that thread is idle, after a
fresh GitHub read and a second idle check. Busy or unloaded threads keep the
Expand Down Expand Up @@ -182,7 +193,6 @@ finish before a PR counts as ready. Start from
{"login": "cursor", "app": "cursor", "check": "Cursor Bugbot"},
{"login": "greptile-apps", "completion": "review"}
],
"optional_skipped_checks": ["browser-tests"],
"label_required_checks": [{"label": "preview", "name": "Build preview"}]
}
}
Expand All @@ -191,14 +201,14 @@ finish before a PR counts as ready. Start from

- A reviewer with `check` and `app` is done when that check run succeeded on the current head.
- A reviewer with `completion: "review"` is done when it submitted a review on the current head that is not a quota or failure notice.
- `optional_skipped_checks`: a skipped check that is not required does not block.
- A skipped or neutral check run that is neither required (branch rules or a label) nor a review bot's check does not block: workflows that skip jobs by change class report their normal green state that way. A required check or a review bot's check that was skipped still blocks. The older key `optional_skipped_checks` is no longer needed and is ignored.
- `label_required_checks`: with the label set, the check must exist and pass.

Without a policy entry a repository still gets notices, but its PRs stay
`waiting` ("Expected review bots not configured"). An explicit empty
`reviewers` list with `review_policy_configured: true` means no bot review.
Neutral results, quota notices, missing checks and API errors never count as
green.
Neutral or skipped results of required and review-bot checks, quota notices,
missing checks and API errors never count as green.

## Migrating from a local install

Expand Down
2 changes: 1 addition & 1 deletion docs/ux/review-policy-format.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ Cost: one GraphQL call per 100 threads, reviews or commits (one for most pull re

From a merge to a changed role file, end to end:

1. **A pull request merges**, whoever merges it. Three ways lead to the check: with the PR watch on, the worker that sees the merge queues one notice to the owning session ("run ytstack:review-lessons for #N", `docs/pr-watch.md`); `bin/ytstack-upkeep` lists, under `review checks`, every merged pull request without a line in `.ytstack/signals/review-checks` (one `gh pr list` per run, one call per 100 merged pull requests: the window opens 14 days before the earliest time in `review-checks`, or 14 days ago without one, never further back than 90 days, and stays there, so a check of a newer pull request never hides an older unchecked one; cut at 500 with a notice); `finish-lane` invokes the skill itself after a merge it made. The skill also runs on demand.
1. **A pull request merges**, whoever merges it. Three ways lead to the check: with the PR watch on, the worker that sees the merge queues one notice to the owning session ("run ytstack:review-lessons for #N", `docs/pr-watch.md`) when it saw at least one bot finding on the pull request; `bin/ytstack-upkeep` lists, under `review checks`, every merged pull request without a line in `.ytstack/signals/review-checks` (one `gh pr list` per run, one call per 100 merged pull requests: the window opens 14 days before the earliest time in `review-checks`, or 14 days ago without one, never further back than 90 days, and stays there, so a check of a newer pull request never hides an older unchecked one; cut at 500 with a notice); `finish-lane` invokes the skill itself after a merge it made. The skill also runs on demand.
2. **`ytstack:review-lessons` reads the pull request** with `bin/ytstack-review-escapes`. Only `fixed` and `escaped` lines go on; `rejected` and `open` ones are counted in its report and recorded nowhere.
3. **It names the owning role** of each escape from the role files (the `lessons` files of this section): their stated scope, checklist and sources. An escape no role owns, for example on a planning file no role reviews, is recorded nowhere and named in the report: that is a gap in the roles, not a lesson for the nearest one.
4. **It records the escape** as `review:<role>:<class>` through `bin/ytstack-signals new --kind review`, with the merge time as the read time, and then the check line with `bin/ytstack-signals review-checked <owner/name>#<n> <merge sha> --tally <role>=<caught>/<escaped>,...`: every `fixed` bot thread counted once, a caught one for the role that caught it, an escaped one for the owning role (`-` without one). A class seen before keeps its key; its count rises.
Expand Down
5 changes: 2 additions & 3 deletions tests/pr_watch/test_claude.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,8 @@ def test_notice_is_pulled_once_and_never_pushed_to_codex(self):
row = self.db.execute("SELECT * FROM outbox WHERE session='claude:abc'").fetchone()
self.assertIsNotNone(row['delivered'])
self.assertTrue(row['dispatch_id'].startswith('claude-prompt:'))
second = self.prompt()['hookSpecificOutput']['additionalContext']
self.assertIn('o/r#7: action_required', second)
self.assertNotIn('Actionable notices', second)
# Delivered once, and the unchanged status block is not repeated (issue #61).
self.assertEqual(self.prompt(), {})

def test_ready_pr_is_summarised_and_closed_pr_drops_out(self):
s = snapshot()
Expand Down
11 changes: 10 additions & 1 deletion tests/pr_watch/test_merge_notice.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from unittest.mock import patch
import test_findings
from prwatch import github, hooks, worker
from prwatch.state import register
from prwatch.state import enqueue, register


def closed(merged):
Expand All @@ -16,9 +16,18 @@ class MergeNotice(unittest.TestCase):
tearDown = test_findings.Findings.tearDown

def observe(self, s, number=1):
if s.get('closed') and (s.get('pr') or {}).get('merged_at'):
# The notice needs a bot finding the watch saw on the PR (issue #61).
self.found(number)
with patch.object(github, 'snapshot', return_value=s):
worker.monitor(self.db, self.db.execute('SELECT * FROM watches WHERE number=?', (number,)).fetchone())

def found(self, number):
watch = self.db.execute('SELECT * FROM watches WHERE number=?', (number,)).fetchone()
with self.db:
enqueue(self.db, f'bot-thread:o/r:{number}:thread1', watch, 'Unresolved bot finding')
self.db.execute('UPDATE outbox SET delivered=1 WHERE event_key LIKE ?', (f'bot-thread:o/r:{number}:%',))

def notices(self):
return self.db.execute("SELECT * FROM outbox WHERE event_key LIKE 'merged:%'").fetchall()

Expand Down
128 changes: 128 additions & 0 deletions tests/pr_watch/test_under_load.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
"""PR watch under load (issue #61): skipped checks, a moved head, an unchanged
status block, and the review-lessons suggestion only where a bot found something."""
import unittest
from unittest.mock import patch
import test_findings
from test_findings import thread
from test_watch import snapshot, POLICY
from prwatch import github, hooks, worker
from prwatch.evaluate import evaluate
from prwatch.state import register


def with_job(s, name, conclusion):
s['checks'].append(dict(id=50 + len(s['checks']), name=name, app={'slug': 'github-actions', 'id': 1},
head_sha=s['head'], status='completed', conclusion=conclusion))
return s


class SkippedChecks(unittest.TestCase):
def test_skipped_or_neutral_optional_job_is_not_a_reason(self):
for conclusion in ('skipped', 'neutral'):
with self.subTest(conclusion=conclusion):
status, detail, _ = evaluate(with_job(snapshot(), 'Check documentation', conclusion), POLICY)
self.assertEqual(status, 'ready')
self.assertEqual(detail, [])

def test_skipped_required_check_and_skipped_bot_review_still_block(self):
s = snapshot(); s['checks'][0]['conclusion'] = 'skipped'
self.assertEqual(evaluate(s, POLICY)[0], 'action_required')
s = snapshot(); s['checks'][1]['conclusion'] = 'skipped'
self.assertEqual(evaluate(s, POLICY)[0], 'action_required')

def test_failed_optional_job_still_blocks(self):
self.assertEqual(evaluate(with_job(snapshot(), 'lint', 'failure'), POLICY)[0], 'action_required')


class UnderLoad(unittest.TestCase):
setUp = test_findings.Findings.setUp
tearDown = test_findings.Findings.tearDown

def watch_row(self):
return self.db.execute('SELECT * FROM watches WHERE number=7').fetchone()

def observe(self, s):
with patch.object(github, 'snapshot', return_value=s):
worker.monitor(self.db, self.watch_row())

def start(self):
with self.db:
register(self.db, 'o/r', 7, 'claude:abc', '/tmp')
s = snapshot(); s['pr']['head'] = {'ref': 'feat'}; s['pr']['mergeable'] = False
self.observe(s)
return s

def prompt(self):
return hooks.handle({'session_id': 'abc', 'hook_event_name': 'UserPromptSubmit', 'cwd': '/tmp'}, 'claude')

def push(self, command='git push -q origin feat'):
payload = {'session_id': 'abc', 'hook_event_name': 'PostToolUse', 'cwd': '/tmp', 'tool_name': 'Bash',
'tool_input': {'command': command}, 'tool_response': {'stdout': ''}}
with patch.object(hooks, 'git_binding', return_value=('o/r', 'feat')):
hooks.handle(payload, 'claude')

def test_own_push_marks_the_head_moved_and_polls_at_once(self):
self.start()
self.assertIn('Merge conflict', self.prompt()['hookSpecificOutput']['additionalContext'])
self.assertFalse(worker.due(self.watch_row(), self.watch_row()['updated'] + 1))
self.push()
row = self.watch_row()
self.assertTrue(worker.due(row, row['updated'] + 1))
text = self.prompt()['hookSpecificOutput']['additionalContext']
self.assertIn('head moved', text)
self.assertNotIn('Merge conflict', text)
s = snapshot(); s['pr']['head'] = {'ref': 'feat'}; s['head'] = 'head3'
for c in s['checks']:
c['head_sha'] = 'head3'
self.observe(s)
text = self.prompt()['hookSpecificOutput']['additionalContext']
self.assertNotIn('head moved', text)
self.assertIn('head head3', text)

def test_push_of_another_branch_changes_nothing(self):
self.start()
payload = {'session_id': 'abc', 'hook_event_name': 'PostToolUse', 'cwd': '/tmp', 'tool_name': 'Bash',
'tool_input': {'command': 'git push origin other'}, 'tool_response': {'stdout': ''}}
with patch.object(hooks, 'git_binding', return_value=('o/r', 'other')):
hooks.handle(payload, 'claude')
self.assertIsNone(self.watch_row()['pushed_at'])

def test_unchanged_block_is_injected_once_until_something_changes(self):
self.start()
self.assertIn('o/r#7', self.prompt()['hookSpecificOutput']['additionalContext'])
self.assertEqual(self.prompt(), {})
self.assertEqual(self.prompt(), {})
# After a compaction the context lost the block: SessionStart shows it again on the next prompt.
hooks.handle({'session_id': 'abc', 'hook_event_name': 'SessionStart', 'cwd': '/tmp'}, 'claude')
self.assertIn('o/r#7', self.prompt()['hookSpecificOutput']['additionalContext'])
self.assertEqual(self.prompt(), {})
s = snapshot(); s['pr']['head'] = {'ref': 'feat'}
self.observe(s)
self.assertIn('o/r#7: ready', self.prompt()['hookSpecificOutput']['additionalContext'])


class MergeSuggestion(unittest.TestCase):
setUp = test_findings.Findings.setUp
tearDown = test_findings.Findings.tearDown

def merge(self, number):
pr = {'state': 'closed', 'merged_at': '2026-11-14T10:00:00Z'}
with patch.object(github, 'snapshot', return_value={'head': 'h', 'closed': True, 'pr': pr}):
worker.monitor(self.db, self.db.execute('SELECT * FROM watches WHERE number=?', (number,)).fetchone())
return self.db.execute('SELECT * FROM outbox WHERE event_key=?', (f'merged:o/r:{number}',)).fetchone()

def test_merge_without_bot_findings_suggests_nothing(self):
self.assertIsNone(self.merge(1))

def test_merge_after_a_bot_finding_suggests_review_lessons(self):
s = snapshot(); s['threads'] = [thread()]
with patch.object(github, 'snapshot', return_value=s):
worker.monitor(self.db, self.db.execute('SELECT * FROM watches WHERE number=1').fetchone())
row = self.merge(1)
self.assertIsNotNone(row)
self.assertIn('ytstack:review-lessons for #1', row['message'])
self.assertIn('1 bot finding', row['message'])


if __name__ == '__main__':
unittest.main()
3 changes: 0 additions & 3 deletions tools/pr-watch/policy.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@
"completion": "review"
}
],
"optional_skipped_checks": [
"browser-tests"
],
"label_required_checks": [
{
"label": "preview",
Expand Down
Loading
Loading