diff --git a/.ytstack/spec/hooks-and-state.md b/.ytstack/spec/hooks-and-state.md index 3ae80af4..98eccb25 100644 --- a/.ytstack/spec/hooks-and-state.md +++ b/.ytstack/spec/hooks-and-state.md @@ -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::`, 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:`, 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::`, 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 | |---|---|---|---|---| diff --git a/CHANGELOG.md b/CHANGELOG.md index 40ee8577..765c8b44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/pr-watch.md b/docs/pr-watch.md index 8c9e7253..78dbbf42 100644 --- a/docs/pr-watch.md +++ b/docs/pr-watch.md @@ -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 @@ -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 @@ -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"}] } } @@ -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 diff --git a/docs/ux/review-policy-format.md b/docs/ux/review-policy-format.md index 14e2b514..a9ceb83a 100644 --- a/docs/ux/review-policy-format.md +++ b/docs/ux/review-policy-format.md @@ -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::` 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 # --tally =/,...`: 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. diff --git a/tests/pr_watch/test_claude.py b/tests/pr_watch/test_claude.py index e4ef3050..c1c13012 100644 --- a/tests/pr_watch/test_claude.py +++ b/tests/pr_watch/test_claude.py @@ -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() diff --git a/tests/pr_watch/test_merge_notice.py b/tests/pr_watch/test_merge_notice.py index 3e11704a..c34895ca 100644 --- a/tests/pr_watch/test_merge_notice.py +++ b/tests/pr_watch/test_merge_notice.py @@ -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): @@ -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() diff --git a/tests/pr_watch/test_under_load.py b/tests/pr_watch/test_under_load.py new file mode 100644 index 00000000..5e1c0212 --- /dev/null +++ b/tests/pr_watch/test_under_load.py @@ -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() diff --git a/tools/pr-watch/policy.example.json b/tools/pr-watch/policy.example.json index 387040d2..6c935dd2 100644 --- a/tools/pr-watch/policy.example.json +++ b/tools/pr-watch/policy.example.json @@ -18,9 +18,6 @@ "completion": "review" } ], - "optional_skipped_checks": [ - "browser-tests" - ], "label_required_checks": [ { "label": "preview", diff --git a/tools/pr-watch/prwatch/claude.py b/tools/pr-watch/prwatch/claude.py index 16e6bb3f..ed2782ca 100644 --- a/tools/pr-watch/prwatch/claude.py +++ b/tools/pr-watch/prwatch/claude.py @@ -19,6 +19,10 @@ def qualify(session): return session if session.startswith(PREFIX) else PREFIX + session +def surface_key(session): + return f'surface:{session}' + + def is_claude(session): return bool(session) and session.startswith(PREFIX) @@ -40,13 +44,29 @@ def surface(db, session, now=None): if not watches and not notices: return None lines = ['PR Watch (silent background monitor; evidence from the last worker tick, re-fetch before acting):'] + state = [] for w in watches: detail = json.loads(w['detail'] or '[]') - observed = _age(now - w['updated']) + ' ago' if w['updated'] else 'not yet polled' paused = ' [paused]' if w['paused'] else '' + pushed = w['pushed_at'] if 'pushed_at' in w.keys() else None + if pushed and pushed > (w['updated'] or 0): + # The old head's findings would mislead: the session pushed since the last read. + state.append((w['repo'], w['number'], w['paused'], 'moved')) + lines.append(f'- {w["repo"]}#{w["number"]}{paused}: head moved by a push {_age(now - pushed)} ago, ' + 'not yet polled') + continue + state.append((w['repo'], w['number'], w['paused'], w['status'], w['head'], w['detail'])) + observed = _age(now - w['updated']) + ' ago' if w['updated'] else 'not yet polled' summary = '; '.join(detail[:4]) + (f'; +{len(detail) - 4} more' if len(detail) > 4 else '') lines.append(f'- {w["repo"]}#{w["number"]}{paused}: {w["status"]} (head {w["head"][:8] or "?"}, {observed})' + (f' -- {summary}' if summary else '')) + # Inject the block only when a line changed since the last injection (ages excluded). + fingerprint = json.dumps(state) + last = db.execute('SELECT value FROM meta WHERE key=?', (surface_key(session),)).fetchone() + with db: + db.execute('INSERT OR REPLACE INTO meta VALUES(?,?)', (surface_key(session), fingerprint)) + if not notices and last and last['value'] == fingerprint: + return None if notices: lines.append('Actionable notices (delivered once):') lines.extend(n['message'] for n in notices) diff --git a/tools/pr-watch/prwatch/evaluate.py b/tools/pr-watch/prwatch/evaluate.py index 902464c1..a3502f6e 100644 --- a/tools/pr-watch/prwatch/evaluate.py +++ b/tools/pr-watch/prwatch/evaluate.py @@ -39,12 +39,13 @@ def evaluate(s, policy): status = statuses.get(need['context']) if not need.get('integration_id') else None if not matches and status is None: pending.append('Required check missing: ' + need['context']) - optional_skips = set(policy.get('optional_skipped_checks', [])) + # A skipped or neutral job that nothing requires is the normal green state of + # change-class workflows; required checks and review-bot checks still need a pass. + review_checks = {r.get('check') for r in policy.get('reviewers', []) if r.get('check')} labels = {label['name'] for label in s['pr'].get('labels', [])} for condition in policy.get('label_required_checks', []): if condition['label'] in labels: name = condition['name'] - optional_skips.discard(name) required_names.add(name) if not any(c['name'] == name for c in latest.values()) and name not in statuses: pending.append('Label-required check missing: ' + name) @@ -56,7 +57,7 @@ def evaluate(s, policy): pending.append('Check running: ' + name) elif c['conclusion'] == 'success': pass - elif c['conclusion'] == 'skipped' and name in optional_skips and name not in required_names: + elif c['conclusion'] in ('skipped', 'neutral') and name not in required_names and name not in review_checks: pass else: issues.append(f'Check {name}: {c["conclusion"]}') diff --git a/tools/pr-watch/prwatch/hooks.py b/tools/pr-watch/prwatch/hooks.py index ab08183b..5596b71b 100644 --- a/tools/pr-watch/prwatch/hooks.py +++ b/tools/pr-watch/prwatch/hooks.py @@ -78,6 +78,15 @@ def handle(payload, host='codex'): tool = payload.get('tool_name', '') # Explicit create output gives provenance even for -R/--head and MCP paths. create = bool(re.search(r'\bgh\s+(?:[^;&|]*\s)?pr\s+create\b', text)) or 'create_pull_request' in tool + if event == 'PostToolUse' and re.search(r'\bgit\s+(?:-C\s+\S+\s+)?push\b', text): + # An own push makes the stored head stale: say so, and poll on the next tick. + for _, binding in bindings: + if binding: + db.execute("UPDATE watches SET pushed_at=? WHERE repo=? AND branch=? AND session=? AND status!='closed'", + (now, *binding, session)) + if event == 'SessionStart': + # A new or compacted context has lost the last status block: show it again. + db.execute('DELETE FROM meta WHERE key=?', (claude.surface_key(session),)) if event == 'PostToolUse' and create: for repo, number in PR.findall(json.dumps(payload.get('tool_response', ''))): db.execute('INSERT OR IGNORE INTO candidates VALUES(?,?,?,?,?)', diff --git a/tools/pr-watch/prwatch/state.py b/tools/pr-watch/prwatch/state.py index 9bd59a96..fa8cf79c 100644 --- a/tools/pr-watch/prwatch/state.py +++ b/tools/pr-watch/prwatch/state.py @@ -61,6 +61,11 @@ def connect(): # saw them closed (an older install: weeks back, so never rechecked). db.execute('ALTER TABLE watches ADD COLUMN closed_at REAL') db.execute("UPDATE watches SET closed_at=updated WHERE status='closed'") + # The PR's head branch (set by the worker) lets an own `git push` mark the + # watch: pushed_at newer than updated means the stored head is stale. + for name, kind in [('branch', 'TEXT'), ('pushed_at', 'REAL')]: + if name not in watch_columns: + db.execute(f'ALTER TABLE watches ADD COLUMN {name} {kind}') return db diff --git a/tools/pr-watch/prwatch/worker.py b/tools/pr-watch/prwatch/worker.py index 15a86f11..8a788319 100644 --- a/tools/pr-watch/prwatch/worker.py +++ b/tools/pr-watch/prwatch/worker.py @@ -108,12 +108,18 @@ def monitor(db, watch): if row['event_key'] not in active and not conflict_unknown(s, row['event_key'], repo, number): db.execute('UPDATE outbox SET cancelled=? WHERE event_key=?', (time.time(), row['event_key'])) if status == 'closed' and 'merged' in details: - # The merge is the trigger of the review-lessons intake (M030). The - # worker does not know projects, so the notice is conditional; the - # key makes it once per PR, and it costs no GitHub call of its own. - enqueue(db, merged_key(repo, number), watch, merged_notice(repo, number, head)) + # The merge is the trigger of the review-lessons intake (M030), but only + # where a review bot left a finding the watch saw: without one there is + # nothing an own reviewer could have missed. The key makes it once per + # PR, and it costs no GitHub call of its own. + findings = db.execute('SELECT COUNT(*) FROM outbox WHERE event_key LIKE ?', + (f'bot-thread:{repo}:{number}:%',)).fetchone()[0] + if findings: + enqueue(db, merged_key(repo, number), watch, merged_notice(repo, number, head, findings)) now = time.time() + branch = ((s.get('pr') or {}).get('head') or {}).get('ref') # SET expressions see the old row: changed_at moves only when head or status changed. + db.execute('UPDATE watches SET branch=COALESCE(?, branch) WHERE repo=? AND number=?', (branch, repo, number)) db.execute('UPDATE watches SET head=?,status=?,detail=?,updated=?,' "closed_at=CASE WHEN ?='closed' THEN COALESCE(closed_at, ?) ELSE NULL END," 'changed_at=CASE WHEN head IS NOT ? OR status IS NOT ? THEN ? ELSE changed_at END ' @@ -125,9 +131,11 @@ def merged_key(repo, number): return f'merged:{repo}:{number}' -def merged_notice(repo, number, head): +def merged_notice(repo, number, head, findings): """Trusted template: no text from GitHub goes into it.""" - return (f'PR Watch: https://github.com/{repo}/pull/{number} was merged (observed head {head}).\n' + noun = 'bot finding' if findings == 1 else 'bot findings' + return (f'PR Watch: https://github.com/{repo}/pull/{number} was merged (observed head {head}); ' + f'the watch saw {findings} {noun} on it.\n' f'PR merged; if this project declares own reviewers (## Own reviewers in .ytstack/spec/REVIEW.md), ' f'run ytstack:review-lessons for #{number}.\n' 'This notice authorizes nothing else.') @@ -278,6 +286,10 @@ def due(watch, now): return False if status == 'registered': return True + pushed = watch['pushed_at'] if 'pushed_at' in watch.keys() else None + if pushed and pushed > (watch['updated'] or 0): + # The owning session pushed since the last read: the stored head is stale. + return True changed = watch['changed_at'] if 'changed_at' in watch.keys() else None if status == 'waiting' and changed is not None and now - changed < FAST_WINDOW: return True