diff --git a/.ytstack/spec/checks-and-evals.md b/.ytstack/spec/checks-and-evals.md index 7f602490..ed8984a4 100644 --- a/.ytstack/spec/checks-and-evals.md +++ b/.ytstack/spec/checks-and-evals.md @@ -95,7 +95,7 @@ Everything that tells a contributor whether a change is acceptable: the static c - Plain bash, no framework. A suite prints one line per assertion and ends with its pass and fail count; fixtures live in `mktemp` directories. The comment at the top of each file states the contract it pins. - `tests/run-all.sh` runs every suite from a neutral temporary directory and prints `PASS` or `FAIL` per suite with that suite's last line. It stops at the first failing suite, prints up to ten of its `FAIL` lines and exits 1. The last line is `ALL SUITES PASSED` or `SUITE FAILURE`. `--linux` runs the same inside an `alpine/git` container with the repository mounted read-only; without a working Docker daemon it prints a skip line and exits 0. - `tests/ytstack-check.test.sh` tests the checker on a copy of the plugin tree. `tests/ytstack-spec.test.sh` tests `bin/ytstack-spec` on fixture repositories, one case per rule. `tests/ytstack-brief.test.sh` does the same for `bin/ytstack-brief` and compares the rendered contract with the real `skills/minimal-code/SKILL.md`. `tests/evidence-rule.test.sh` pins the evidence reuse rule: the verifier, the dispatcher and the skills area reuse a PASS only for the same commit, and its git fixture shows why (an unchanged planned file, a changed imported helper, a failing check). -- `tests/pr-watch.test.sh` runs the PR watch engine's `unittest` suite (`tests/pr_watch/`, standard library, `gh` and the Codex daemon mocked) and then shell cases for `hooks/pr-watch` (off, on, malformed input), `bin/ytstack-pr-watch` (enable/disable, install-worker and migrate plans, migrate copy, the worker launcher's engine choice; `register --all-open` is covered in `tests/pr_watch/test_register_all.py`, the `claude:` qualification of a bare session id in `test_session_spelling.py`) under a temporary HOME. The resolver rule of `bin/ytstack-check` exempts `hooks/pr-watch` by name (`_HOOKS_WITHOUT_RESOLVER`). +- `tests/pr-watch.test.sh` runs the PR watch engine's `unittest` suite (`tests/pr_watch/`, standard library, `gh` and the Codex daemon mocked) and then shell cases for `hooks/pr-watch` (off, on, malformed input), `bin/ytstack-pr-watch` (enable/disable, install-worker and migrate plans, migrate copy, the worker launcher's engine choice; `register --all-open` is covered in `tests/pr_watch/test_register_all.py`, the `claude:` qualification of a bare session id in `test_session_spelling.py`, skipped checks, a moved head (with `remote_head` against a real temporary repository), the once-per-change status block and the merge suggestion in `test_under_load.py`) under a temporary HOME. The resolver rule of `bin/ytstack-check` exempts `hooks/pr-watch` by name (`_HOOKS_WITHOUT_RESOLVER`). **Python host tests: `tests/*_test.py`** diff --git a/.ytstack/spec/hooks-and-state.md b/.ytstack/spec/hooks-and-state.md index 98eccb25..f747fddf 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. 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`). +`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 when `refs/remotes/origin/` (without one, `refs/heads/`) then differs from the watched head, 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/docs/pr-watch.md b/docs/pr-watch.md index 78dbbf42..801bf65c 100644 --- a/docs/pr-watch.md +++ b/docs/pr-watch.md @@ -113,7 +113,9 @@ 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 +PR's branch (`git push` seen by the PostToolUse hook in a bound worktree, and +the branch's remote-tracking ref, or the local branch where a narrow fetch +refspec keeps none, then differs from the watched head), 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. diff --git a/tests/pr_watch/test_under_load.py b/tests/pr_watch/test_under_load.py index 5e1c0212..f0d42c22 100644 --- a/tests/pr_watch/test_under_load.py +++ b/tests/pr_watch/test_under_load.py @@ -55,10 +55,11 @@ def start(self): 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'): + def push(self, command='git push -q origin feat', remote='head3'): 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')): + with patch.object(hooks, 'git_binding', return_value=('o/r', 'feat')), \ + patch.object(hooks, 'remote_head', return_value=remote): hooks.handle(payload, 'claude') def test_own_push_marks_the_head_moved_and_polls_at_once(self): @@ -79,11 +80,34 @@ def test_own_push_marks_the_head_moved_and_polls_at_once(self): self.assertNotIn('head moved', text) self.assertIn('head head3', text) - def test_push_of_another_branch_changes_nothing(self): + def test_push_that_leaves_the_watched_branch_unchanged_marks_nothing(self): + # `git push origin other` from a checked-out `feat`: origin/feat still has the watched head. + self.start() + self.push('git push origin other', remote='head2') + self.assertIsNone(self.watch_row()['pushed_at']) + # Text that merely mentions a push, without a tracking ref, marks nothing either. + self.push('echo "git push later"', remote='') + self.assertIsNone(self.watch_row()['pushed_at']) + + def test_remote_head_falls_back_to_the_local_branch_without_a_tracking_ref(self): + # A --single-branch clone keeps no refs/remotes/origin/ after `git push -u`. + import subprocess, tempfile as tf + with tf.TemporaryDirectory() as repo: + git = lambda *a: subprocess.run(['git', '-C', repo, *a], capture_output=True, text=True, check=True).stdout.strip() + git('init', '-q', '-b', 'feat') + git('-c', 'user.name=t', '-c', 'user.email=t@t', '-c', 'commit.gpgsign=false', + 'commit', '-q', '--allow-empty', '-m', 'x') + self.assertEqual(hooks.remote_head(repo, 'feat'), git('rev-parse', 'HEAD')) + git('update-ref', 'refs/remotes/origin/feat', 'HEAD') + self.assertEqual(hooks.remote_head(repo, 'feat'), git('rev-parse', 'HEAD')) + self.assertEqual(hooks.remote_head(repo, 'nope'), '') + + def test_push_of_another_bound_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')): + with patch.object(hooks, 'git_binding', return_value=('o/r', 'other')), \ + patch.object(hooks, 'remote_head', return_value='head9'): hooks.handle(payload, 'claude') self.assertIsNone(self.watch_row()['pushed_at']) @@ -114,6 +138,18 @@ def merge(self, number): def test_merge_without_bot_findings_suggests_nothing(self): self.assertIsNone(self.merge(1)) + def test_finding_of_a_similarly_named_repository_does_not_count(self): + # `_` is a LIKE wildcard: o/r_x must not see a finding of o/rXx with the same number. + with self.db: + register(self.db, 'o/r_x', 3, 'session', '/tmp') + register(self.db, 'o/rXx', 3, 'session', '/tmp') + self.db.execute("INSERT INTO outbox(event_key,repo,number,session,message,created) " + "VALUES('bot-thread:o/rXx:3:t','o/rXx',3,'session','m',0)") + 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 repo='o/r_x'").fetchone()) + self.assertIsNone(self.db.execute("SELECT * FROM outbox WHERE event_key='merged:o/r_x:3'").fetchone()) + def test_merge_after_a_bot_finding_suggests_review_lessons(self): s = snapshot(); s['threads'] = [thread()] with patch.object(github, 'snapshot', return_value=s): diff --git a/tools/pr-watch/prwatch/hooks.py b/tools/pr-watch/prwatch/hooks.py index 5596b71b..3b6d1bc7 100644 --- a/tools/pr-watch/prwatch/hooks.py +++ b/tools/pr-watch/prwatch/hooks.py @@ -44,6 +44,17 @@ def git(*args): return match[1], branch +def remote_head(cwd, branch): + """The SHA a push left in the remote-tracking ref of `branch` (local, no GitHub call). A clone + with a narrow fetch refspec has no such ref even after a push; then the local branch head.""" + for ref in (f'refs/remotes/origin/{branch}', f'refs/heads/{branch}'): + p = subprocess.run(['git', '-C', cwd, 'rev-parse', '--verify', '-q', ref], + capture_output=True, text=True, timeout=3) + if p.returncode == 0 and p.stdout.strip(): + return p.stdout.strip() + return '' + + def handle(payload, host='codex'): session = payload.get('session_id') if not session: @@ -79,11 +90,16 @@ def handle(payload, host='codex'): # 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: + # An own push makes the stored head stale: say so, and poll on the next tick. The + # command text alone does not say which ref moved (`git push origin other` from a + # checked-out `feat`), so compare the remote-tracking ref with the stored head. + for cwd, binding in bindings: if binding: - db.execute("UPDATE watches SET pushed_at=? WHERE repo=? AND branch=? AND session=? AND status!='closed'", - (now, *binding, session)) + pushed = remote_head(cwd, binding[1]) + if pushed: + db.execute("UPDATE watches SET pushed_at=? WHERE repo=? AND branch=? AND session=? " + "AND status!='closed' AND head!='' AND head!=?", + (now, *binding, session, pushed)) 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),)) diff --git a/tools/pr-watch/prwatch/worker.py b/tools/pr-watch/prwatch/worker.py index 8a788319..94e4b5ac 100644 --- a/tools/pr-watch/prwatch/worker.py +++ b/tools/pr-watch/prwatch/worker.py @@ -112,8 +112,8 @@ def monitor(db, watch): # 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] + findings = db.execute("SELECT COUNT(*) FROM outbox WHERE repo=? AND number=? AND event_key LIKE 'bot-thread:%'", + (repo, number)).fetchone()[0] if findings: enqueue(db, merged_key(repo, number), watch, merged_notice(repo, number, head, findings)) now = time.time()