diff --git a/.ytstack/DECISIONS.md b/.ytstack/DECISIONS.md index 9250e902..75e6b8e4 100644 --- a/.ytstack/DECISIONS.md +++ b/.ytstack/DECISIONS.md @@ -1219,6 +1219,28 @@ Plus: ops-layer split during the same session (yopstack created as own public re **Supersedes:** None. Extends the roadmap state values in `docs/ux/skill-structure.md`. +## 2026-11-15: PR watch bulk registration takes only your own ready PRs; bins are called through `YT_BIN` (issue #85) + +**Context:** A coordinator ran `ytstack-pr-watch register --all-open`. It registered every open PR of the repository, including another author's do-not-merge prototype, which was then injected as `action_required` 967 times; single status blocks reached 8.4k characters and 34 PRs, re-sent whole whenever one line changed; `status` printed 1,176 watches of every repository and session. The same coordinator called the bins by the versioned cache path it had seen (`.../ytstack/0.7.0/bin/ytstack-frontier`), kept doing so after an update, and one call failed with exit 127. + +**Options considered:** +- Bulk registration: A) only PRs whose author is the `gh` login, drafts and do-not-merge labels skipped, `--author`, `--include-drafts`, `--include-labelled` to widen; B) keep "every open PR" and rely on `pause`; C) filter by branch bindings of the session. +- Bins: D) print `YT_BIN=` in the `coordinate` preamble and at the end of the SessionStart context, and have the skill run bins as `"$YT_BIN/ytstack-"`; E) a stable `~/.ytstack/bin` shim that points at the active version. + +**Chose:** A and D. + +**Reason:** A coordinator's lanes open their PRs under the same login, so the author is the cheapest fact that separates them from a colleague's, and one REST call (`gh api user`) gets it. B is what failed. C misses exactly the PRs `--all-open` exists for: those a session without hooks opened. `--author` adds to the login instead of replacing it, so widening never drops one's own PRs. For bins, D needs nothing outside the plugin and gives the coordinator one current value to copy instead of a path it remembers from an earlier context. E is a file in the user's home that some command must install and keep current across hosts and versions, and it would point at whatever version was active last, not at the one the session runs; ytstack never edits host settings or `PATH`, so a shim would still need a path to be called by. + +**How to apply:** +- `register --pr N` registers one PR whatever its author or label; the filters apply to `--all-open` only, and every skipped PR is named with its reason. +- A do-not-merge label is any label that, lowercased with `-`, `_`, `/`, `:` and `.` read as spaces, contains the words "do not merge" or `dnm`. Logins compare without case and without a `[bot]` suffix. When the login cannot be read, only an explicit `--author` list is used (with a warning); without one the command stops. +- A rerun that skips a PR this session already watches pauses that watch and names it: the filter exists to stop such reports, and `resume` undoes it. +- The status block lists changed lines, `- N unchanged`, and one last `closed` line for a PR of the previous block (a merge without a bot finding has no other report); a PR `action_required` without a head or status change for 24 hours (NULL `changed_at` counts as older) gets one `pause` suggestion per stretch, remembered apart from the block fingerprint so SessionStart does not repeat it. `status` shows the current session and repository (compared without case) unless `--all`. +- The SessionStart line comes on every source but only where it still fits under the injection guard: this repository's injection sits within about 50 characters of it with a long Next action, and the excerpt matters more. The `coordinate` preamble is the source that always prints it. A session started before an update runs the old version's hooks, so after an update the line is renewed by reloading the skill (the version notice asks for that), not by the hook. +- A skill that runs ytstack bins over a long session names them through `YT_BIN`; a short skill keeps `${CLAUDE_SKILL_DIR}/../../bin`, which the host substitutes when it loads the skill. + +**Supersedes:** None. Narrows `register --all-open` of "2026-11-14: PR watch ships inside ytstack as an optional, opt-in tool" (issue #54). + ## 2026-11-15: New artifacts follow the directory a milestone already lives in (issue #70) **Context:** Reading tolerated `milestones/`, `milestones/*/`, `backlog/` and `backlog/*/` since M018-S03, but every skill and hook wrote flat into `.ytstack/`. A consumer that moved 299 files of older milestones into `.ytstack/milestones/M###/` got the next plan or summary of such a milestone back at the top level, beside the moved ones. diff --git a/.ytstack/spec/checks-and-evals.md b/.ytstack/spec/checks-and-evals.md index 1984c2e5..9a708ac9 100644 --- a/.ytstack/spec/checks-and-evals.md +++ b/.ytstack/spec/checks-and-evals.md @@ -103,7 +103,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`, the handover to a successor session in `test_handover.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`). +- `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` with its author, draft and label filters is covered in `tests/pr_watch/test_register_all.py`, the changed-lines block, the pause suggestion and the `status` scope in `test_scope.py`, the `claude:` qualification of a bare session id in `test_session_spelling.py`, the handover to a successor session in `test_handover.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 63694680..34fc770c 100644 --- a/.ytstack/spec/hooks-and-state.md +++ b/.ytstack/spec/hooks-and-state.md @@ -64,7 +64,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 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`). `handover --from [--to ]` moves a session's watches, its undelivered notices (not a Codex notice with a `dispatch_id`), bindings and candidates to its successor and writes `meta` key `handover:`; `register` follows that chain, so a PR a subagent of the old session opens later goes to the successor, and discovery counts a binding of the old session as its successor (no "Multiple sessions" ambiguity). A bare `--from`/`--to` id is qualified to `claude:` when only that is stored, and a bare `--to` naming nothing follows a Claude `--from` (`tests/pr_watch/test_handover.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 (one fingerprint per PR line in `meta` key `surface:`, reset on SessionStart) or a notice is pending, and it lists only the changed lines plus `- N unchanged`, and one `closed (merged)` / `closed` line for a watch of the last block that closed since; an `action_required` watch that is not paused and whose `changed_at` is 24 h old or NULL gets one `pause` suggestion per stretch (`meta` key `pause-hint:`, PR to `changed_at`, not reset on SessionStart) (`tests/pr_watch/test_scope.py`); 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`). `handover --from [--to ]` moves a session's watches, its undelivered notices (not a Codex notice with a `dispatch_id`), bindings and candidates to its successor and writes `meta` key `handover:`; `register` follows that chain, so a PR a subagent of the old session opens later goes to the successor, and discovery counts a binding of the old session as its successor (no "Multiple sessions" ambiguity). A bare `--from`/`--to` id is qualified to `claude:` when only that is stored, and a bare `--to` naming nothing follows a Claude `--from` (`tests/pr_watch/test_handover.py`). `register --all-open` takes only PRs whose author is the `gh` login or a login of `--author` (case-insensitive, a `[bot]` suffix ignored; without a readable login only `--author`, else an error), and skips drafts and labels that contain the words "do not merge" or `dnm` after `-_/:.` read as spaces unless `--include-drafts` / `--include-labelled` (which, like `--author`, need `--all-open`), naming each skipped PR with its reason and pausing a skipped PR this session already watches (`tests/pr_watch/test_register_all.py`). `status` is scoped to the current session and the `origin` repository of the working directory (`--session`, `--repo` compared without case; `--all` for everything; what does not resolve does not narrow) and prints the `scope` it used; `health` stays whole. | Hook | Event | Reads from the payload | Effect | Exit | |---|---|---|---|---| @@ -93,6 +93,7 @@ Every hook except `pr-watch` sources the library and resolves from the payload ` - `.ytstack` without `STATE.md`: a one-line repair notice. - Otherwise a state block, in this order: scope, project, pointer, last update, working tree with the linked-worktree flag, `.ytstack` path, a Next action excerpt, the three newest summary names, a notice when more than one milestone roadmap is `in-progress`, the manual and the latest automatic handoff, a lifecycle hint for a finished slice or a finished milestone without retro, up to five STATE lint findings, the minimal-code line when `minimal_code` is on, a "Factory tools" block with the lines of `yt_factory_notices` (only when the payload `source` is `startup` or `clear`, or absent on a SessionStart, so it is said once per session without a file), and a closing line that names the files as the source of truth. When `spec/SPEC.md` exists, the closing line names it as the place for what applies now. - Cap: the hook measures the injection without the host context. Above the guard threshold in the script, which sits just under the host's 10,000-character limit, it cuts the Next action excerpt to what still fits and marks the cut; when less than a useful rest would remain, it replaces the excerpt with a one-line note. Next, the Factory tools block shrinks to one line that counts them and names `bin/ytstack-upkeep`. If the text is still above the threshold, it warns on stderr and emits the text anyway. Nothing else is dropped. +- Last, with a state block and on every source (also resume and compaction): one line `YT_BIN=`, the directory skills run ytstack's bins from as `"$YT_BIN/ytstack-"` (issue #85). It is added only when it still fits under the guard, so it never costs the Next action excerpt; the `coordinate` preamble prints it too. - Output is the existing Claude-compatible JSON envelope by default. `YTSTACK_HOOK_FORMAT=plain` emits the raw context instead. Kimi's helper uses this mode only to prepare pending context, not as a claim that SessionStart stdout is consumed. ### Kimi pending bridge @@ -176,6 +177,7 @@ python3 -m unittest discover -s tests -p 'kimi_lifecycle_test.py' -v ## Decisions that apply now - DECISIONS.md -- "2026-11-15: SessionStart stays read-only; factory-tool notices are said on startup only, the plugin version is recorded by a prompt hook (M031-S03)" +- DECISIONS.md -- "2026-11-15: PR watch bulk registration takes only your own ready PRs; bins are called through `YT_BIN` (issue #85)" - DECISIONS.md -- "2026-11-14: Kimi uses native plugin bootstrap and pending lifecycle context (M020)" (plain output is explicit, the helper owns pending context and consumes it once) - DECISIONS.md -- "2026-11-13: Whether a person looks at a change is decided per change: a floor from the diff, the class an independent reviewer states, a ceiling per area, lenses per kind of change (M025)" (`merge_by` and `evidence_dir` in `yt_prefs`) - DECISIONS.md -- "2026-11-07: Hooks never write relative to CLAUDE_PROJECT_DIR; volatile state lives out-of-tree, per session and per worktree" diff --git a/.ytstack/spec/skills.md b/.ytstack/spec/skills.md index dbe5c7a2..9abc67d9 100644 --- a/.ytstack/spec/skills.md +++ b/.ytstack/spec/skills.md @@ -105,7 +105,7 @@ Read from `PREFERENCES.md` in the resolved `.ytstack` directory by `yt_prefs` in Formats: `docs/ux/coordinator-format.md`. The four skills below are for the session that owns a plan and delegates all of it; none of them writes product code. -- `coordinate` is a loop with a fixed order: start from the standing instructions (the entries of `standing/` in the resolved `YT_DIR`, project or user scope, newest first without superseded ones, and `STANDING.md`), `LANES.md`, the frontier and the questions (never from a conversation summary), read host facts fresh and stamp them with their read time, claim a lane before dispatching it, finish lanes through `finish-lane`, run the factory tools of Step 7 (one table of command, when and skip condition; the preamble prints `MERGE_BY`, `REVIEW_POLICY`, `OWN_REVIEWERS`, `PR_WATCH` with the heartbeat age, `RELEASE` and `SIGNALS`): the route before every merge, also one it makes itself outside `finish-lane` (then through `ytstack-finish-lane merge` and `finish-lane`'s rule of who merges), with the PR watch on (flag set and a worker heartbeat under 10 minutes old) register the repository's open pull requests to itself as their owning session (`ytstack-pr-watch register --all-open` without `--session`, at the start, after every restart or rotation and after a worker opened one) and otherwise poll through `bin/ytstack-watch`, `ytstack-watch release` after every merge to production, `signal-intake` / `incident` for signals and `review-lessons` after a merge with a bot finding, `lesson` on a red `main` and on every slip of a lane or its own (the open lessons in every status from the preamble's `LESSONS` line, a lesson proposal asked with the daily question, lesson lanes `lesson-F###` dispatched from the frontier with `ytstack-brief render --lesson` and set `fixed` after their merge), ask one question at a time from a question file, write a standing instruction down when it is given (a new file in `standing/`; `STANDING.md` only where no `standing/` exists), stop a lane that failed verification twice or needs a third review, and rotate after the first compaction in one step while lanes run: a handoff written from the files with the "Rotation" block of `docs/ux/coordinator-format.md` (PR watch session, background watches, each running worker's address), the successor's Step 3 takes the PR watches over with `ytstack-pr-watch handover --from `, and the old session stays open only as a relay that appends its workers' reports to `HANDOFF.md`. +- `coordinate` is a loop with a fixed order: start from the standing instructions (the entries of `standing/` in the resolved `YT_DIR`, project or user scope, newest first without superseded ones, and `STANDING.md`), `LANES.md`, the frontier and the questions (never from a conversation summary), read host facts fresh and stamp them with their read time, claim a lane before dispatching it, finish lanes through `finish-lane`, run the factory tools of Step 7 (one table of command, when and skip condition; the preamble prints `MERGE_BY`, `REVIEW_POLICY`, `OWN_REVIEWERS`, `PR_WATCH` with the heartbeat age, `RELEASE` and `SIGNALS`, and `YT_BIN=`, through which it runs every bin): the route before every merge, also one it makes itself outside `finish-lane` (then through `ytstack-finish-lane merge` and `finish-lane`'s rule of who merges), with the PR watch on (flag set and a worker heartbeat under 10 minutes old) register the repository's open pull requests by its own GitHub login, without drafts and do-not-merge labels, to itself as their owning session (`ytstack-pr-watch register --all-open` without `--session`, at the start, after every restart or rotation and after a worker opened one) and otherwise poll through `bin/ytstack-watch`, `ytstack-watch release` after every merge to production, `signal-intake` / `incident` for signals and `review-lessons` after a merge with a bot finding, `lesson` on a red `main` and on every slip of a lane or its own (the open lessons in every status from the preamble's `LESSONS` line, a lesson proposal asked with the daily question, lesson lanes `lesson-F###` dispatched from the frontier with `ytstack-brief render --lesson` and set `fixed` after their merge), ask one question at a time from a question file, write a standing instruction down when it is given (a new file in `standing/`; `STANDING.md` only where no `standing/` exists), stop a lane that failed verification twice or needs a third review, and rotate after the first compaction in one step while lanes run: a handoff written from the files with the "Rotation" block of `docs/ux/coordinator-format.md` (PR watch session, background watches, each running worker's address), the successor's Step 3 takes the PR watches over with `ytstack-pr-watch handover --from `, and the old session stays open only as a relay that appends its workers' reports to `HANDOFF.md`. - `spawn-milestone-team` claims each lane with `bin/ytstack-frontier` before it dispatches, keeps the lane's row current, and looks at the frontier again whenever a lane is verified or merged. - `finish-lane` takes a reported lane to a merged pull request with `bin/ytstack-finish-lane`: review pinned to the host's head, the required lenses, `route`, the gates read from the host, the merge decided by `merge_by` and the route, then `bin/ytstack-watch release` on the merge commit when `RUNTIME.md` has a "Release" section (in the background; the receipt goes into the report, nothing is rolled back). A merge without a person is reported in one line with class, ceiling and lenses. After a merge it made itself, and when `REVIEW.md` declares own reviewers, it invokes `review-lessons` for the pull request. Before a lane goes back for a review that requested changes, a failed lens or a failed check, it invokes `lesson` (its Step 14). These two are the skills it may invoke. The pipeline supports GitHub through `gh` only; on another host the skill stops after the route. - **The class of a change.** `code-review` prints the floor of `bin/ytstack-risk` and has a reviewer that is not the author end with `Risk:`, `Severity:`, `Reach:` and `Invariants touched:`, read against "Invariants and security boundaries" and "Decisions that apply now" of the touched areas, also when only code moved. The round line records class, invariants and reviewer; a session reviewing its own change writes `by: self`, which routes to a person. On a pull request `finish-lane` and `code-review` post the round and lens lines in the body of a review on the reviewed head, and `finish-lane` routes with `--pr`: the record needs no commit that would move the head away from a head-bound review. Each lens the floor names gets a separate fresh reviewer with the lens brief (`bin/ytstack-brief render --kind review --lens `) and one lens line. @@ -196,5 +196,5 @@ Formats: `docs/ux/coordinator-format.md`. The four skills below are for the sess - DECISIONS.md -- "2026-10-13: Remove generated Codex copies; load the existing skills directly" (one skill tree for both hosts) - DECISIONS.md -- "2026-11-13: The technical spec is a set of artifacts of its own under `.ytstack/spec/` (M022, issue #36)" (the spec steps in the loop) - DECISIONS.md -- "2026-11-13: Verification, review and orchestration work are bounded like code (M023, issue #35)" (the work contract; extends the ceremony entry of 2026-11-07 from code to evidence and review) -- DECISIONS.md -- "2026-11-13: Coordinator mode keeps lanes, questions and standing instructions in files and reads host facts fresh (M024, issue #34)", extended by "2026-11-14: Standing instructions are one file per entry in `.ytstack/standing/`; `STANDING.md` stays valid (issue #57)" +- DECISIONS.md -- "2026-11-13: Coordinator mode keeps lanes, questions and standing instructions in files and reads host facts fresh (M024, issue #34)", extended by "2026-11-14: Standing instructions are one file per entry in `.ytstack/standing/`; `STANDING.md` stays valid (issue #57)" and by "2026-11-15: PR watch bulk registration takes only your own ready PRs; bins are called through `YT_BIN` (issue #85)" - DECISIONS.md -- "2026-11-13: `STATE.md` is a pointer with a size bound; history leaves it through `reconcile`, a closed milestone is folded into the spec (M022-S03)" diff --git a/CHANGELOG.md b/CHANGELOG.md index 8820d531..a603207f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- **PR watch stays on your own PRs and says less** (issue #85). + `ytstack-pr-watch register --all-open` registers only open PRs you authored + (the `gh` login) and skips drafts and do-not-merge labels, each named with + the reason; `--author [,]`, `--include-drafts` and + `--include-labelled` widen it; a rerun pauses a watch of yours that the + filter now skips. The status block on each prompt lists only the PR lines + that changed plus "N unchanged", a PR that closed gets one last + `closed (merged)` / `closed` line, and a PR stuck in `action_required` for + 24 hours gets one line suggesting `pause`. + `ytstack-pr-watch status` shows the current session and repository; + `--all` shows everything. +- **Bins through `YT_BIN`** (issue #85): the `coordinate` preamble + (`coordinate` 0.5.1) and the SessionStart context (where it fits under the + injection cap) print `YT_BIN=`, and + `coordinate` runs its bins as + `"$YT_BIN/ytstack-"`, so a long session no longer calls a removed + version's path after an update. + ### Fixed - **New artifacts follow the directory their milestone lives in** (issue #70): diff --git a/bin/ytstack-pr-watch b/bin/ytstack-pr-watch index e80d3e90..b477f32d 100755 --- a/bin/ytstack-pr-watch +++ b/bin/ytstack-pr-watch @@ -7,7 +7,9 @@ # ytstack-pr-watch uninstall-worker [--yes] remove the worker, keep state # ytstack-pr-watch migrate --from DIR [--yes] copy the state of an existing local install # ytstack-pr-watch handover --from SESSION [--to SESSION] hand a session's watches to its successor -# ytstack-pr-watch status | register | create | inspect | pause | resume | tick | hook +# ytstack-pr-watch status [--all] this session and repository, or everything +# ytstack-pr-watch register --repo R --all-open your open PRs (--author, --include-drafts, --include-labelled) +# ytstack-pr-watch register | create | inspect | pause | resume | tick | hook # # Without --yes the setup commands print their plan and write nothing. # State: ${YTSTACK_PR_WATCH_HOME:-~/.ytstack/pr-watch}/state. Needs python3 (3.9+) and gh. diff --git a/docs/pr-watch.md b/docs/pr-watch.md index 5a6db4a3..6b03e339 100644 --- a/docs/pr-watch.md +++ b/docs/pr-watch.md @@ -43,7 +43,10 @@ bin/ytstack-pr-watch install-worker --yes ``` `bin/` is relative to the installed plugin; inside a session the SessionStart -context names the absolute path. The switch is per user and covers all projects. +context names the absolute path as `YT_BIN=` (the running version's +`bin/`, printed again after every resume and compaction where the +injection has room, and by the `coordinate` preamble; call +`"$YT_BIN/ytstack-pr-watch"` with it). The switch is per user and covers all projects. With it off, every PR watch hook exits after one `grep` on `~/.ytstack/config`, without starting Python and without output. @@ -69,13 +72,22 @@ Code, Codex and the worker, and stays the same across plugin updates. ```bash bin/ytstack-pr-watch create --repo OWNER/REPO --session SESSION_ID --cwd WORKTREE -- --title "..." --body-file body.md bin/ytstack-pr-watch register --repo OWNER/REPO --pr 123 --session SESSION_ID --cwd WORKTREE -bin/ytstack-pr-watch register --repo OWNER/REPO --all-open # every open PR, for this session +bin/ytstack-pr-watch register --repo OWNER/REPO --all-open # your open PRs, for this session bin/ytstack-pr-watch handover --from claude: # take over another session's watches bin/ytstack-pr-watch pause --repo OWNER/REPO --pr 123 # and resume bin/ytstack-pr-watch inspect --repo OWNER/REPO --pr 123 # read only, registers nothing -bin/ytstack-pr-watch status +bin/ytstack-pr-watch status # this session and this checkout's repository +bin/ytstack-pr-watch status --all # every session and repository ``` +`status` prints JSON: `scope` (the session and repository it shows, or +`all`), the watches and undelivered notices in that scope, and `health` (the +worker heartbeat and errors, always whole). The session is the current one +(`--session` overrides it), the repository is the GitHub `origin` of the +working directory (`--repo` overrides it; compared without case, as GitHub +does); what cannot be resolved does not +narrow the list, so outside a session and a checkout it shows everything. + Inside a session `--session` defaults to the current one (`CODEX_THREAD_ID`, or `claude:$CLAUDE_CODE_SESSION_ID`). @@ -84,9 +96,24 @@ parent's session, so a PR a subagent opens is registered to the coordinating session. **A session only has the hooks it loaded when it started**: a session that was already running when you switched the PR watch on, or when ytstack was updated to a version with these hooks, registers nothing until it is restarted. -`register --all-open` closes that gap: it registers every open PR of the +`register --all-open` closes that gap: it registers the open PRs of the repository to the current session in one listing call (one REST call per 100 -open PRs) and skips, by name, PRs another session already owns. Only the session +open PRs, plus one for your login) and skips, by name, PRs another session +already owns. It takes only PRs whose author is the login `gh` is signed in as +(subagents open theirs under it), and skips drafts and PRs with a label that +says "do not merge" (any case, with spaces, `-`, `_`, `/` or `:` between the +words, so `do-not-merge/hold` and `status: do not merge` too, or the word +`dnm`), each named with its reason. `--author [,]` adds other +authors (a bot that opens PRs for you, for example; `dependabot` matches +`dependabot[bot]`), `--include-drafts` and `--include-labelled` take drafts +and labelled PRs as well; these three flags need `--all-open`. When `gh` cannot +say who you are, `--all-open` stops with an error, or, with `--author` given, +registers only those authors and says so on stderr. A run that skips a PR this +session already watches (from an earlier run without the filter) pauses that +watch and names it, with the `resume` command to undo it. `register --pr N` +registers one PR whatever its author or label. Without these limits one bulk +run registered every open PR of a repository, including another author's +do-not-merge prototype, which was then reported 967 times (issue #85). Only the session that owns the repository's PRs runs it, typically the coordinator, once at its start and after any restart. When several independent sessions work in the same repository, each registers only its own PRs (`register --pr N`); a bulk run would @@ -125,7 +152,7 @@ it and something is under `claude:`: then it is that Claude session, and a bare `--to` that names nothing yet follows a Claude `--from`. Handovers chain (old to new to third), and a handover back to an earlier session makes it the owner again. The old session's id is in its SessionStart context ("This session -is ...") and in `status`; a coordinator writes it into its handoff when it +is ...") and in `status --all`; a coordinator writes it into its handoff when it rotates (`skills/coordinate/SKILL.md`, Step 12). ## Delivery: Claude Code pulls, Codex is woken @@ -141,8 +168,20 @@ 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 +not once per prompt. It then lists only the lines that changed, and the rest +as one line `- N unchanged`: with 34 watched PRs one changed PR is two lines, +not 34 (issue #85). A PR that was in the last block and has closed since gets +one last line, `- OWNER/REPO#N: closed (merged)` or `closed`, and leaves the +count: a merge without a bot finding sends no notice, so this line is how the +session hears of it. SessionStart (start, resume, compaction) resets this, so +the next prompt shows every open line again. + +A PR that stays `action_required` for 24 hours without a new head or status +change (a watch from before that time was recorded counts as older) gets one +suggestion on its line: `no new head or status for N h: if nobody works on it, +ytstack-pr-watch pause --repo OWNER/REPO --pr N`. It comes once per such +stretch, also across SessionStart and when only the findings change; a new head +or status starts a new stretch. A paused PR gets none. When the session pushes to a watched 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 diff --git a/hooks/session-start b/hooks/session-start index 15061ac0..d1ae3ea3 100644 --- a/hooks/session-start +++ b/hooks/session-start @@ -302,5 +302,16 @@ $STATE_CONTEXT" fi fi +# The running version's bin/ (issue #85), on every source: skills run bins as +# "$YT_BIN/ytstack-", not by a path from an earlier context. Only where it +# still fits under the guard; it never costs the Next action (coordinate's +# preamble prints it too). +_YT_BIN_LINE="YT_BIN=$(cd "$PLUGIN_ROOT/bin" 2>/dev/null && pwd -P || printf '%s' "$PLUGIN_ROOT/bin")" +if [ $(( ${#FULL_CONTEXT} - _HOST_LEN + ${#_YT_BIN_LINE} + 2 )) -le 9500 ]; then + FULL_CONTEXT="$FULL_CONTEXT + +$_YT_BIN_LINE" +fi + emit_json "$FULL_CONTEXT" exit 0 diff --git a/skills/coordinate/SKILL.md b/skills/coordinate/SKILL.md index 757c29f5..c30e841a 100644 --- a/skills/coordinate/SKILL.md +++ b/skills/coordinate/SKILL.md @@ -3,7 +3,7 @@ name: coordinate description: "Coordinator mode for the session that owns a plan and delegates all of it, writing no product code itself. Use when many lanes are in flight, when a plan has dozens of work packages, when a session with open lanes continues after a compaction or a resume, or when the user says coordinate this, run the plan, you are the coordinator, keep the lanes moving, where does each lane stand. Not for one milestone with a handful of independent slices (spawn-milestone-team) and not for doing a task yourself (plan-task)." metadata: tier: task - version: 0.5.0 + version: 0.5.1 allowed-tools: - Bash - Read @@ -108,7 +108,8 @@ _PR_HOST=none [ -n "$(git remote 2>/dev/null | head -1)" ] && command -v gh >/dev/null 2>&1 && _PR_HOST=gh echo "PR_HOST: $_PR_HOST" # Factory tools (M031): what the project switched on; Step 7 skips a tool by these lines. -_BIN="${CLAUDE_SKILL_DIR}/../../bin" +_BIN=$(cd "${CLAUDE_SKILL_DIR}/../../bin" 2>/dev/null && pwd -P || echo "${CLAUDE_SKILL_DIR}/../../bin") +echo "YT_BIN=$_BIN" _MERGE_BY=human command -v yt_prefs >/dev/null 2>&1 && { yt_prefs "$_YT_DIR" >/dev/null; _MERGE_BY="$YT_PREF_MERGE_BY"; } echo "MERGE_BY: $_MERGE_BY" @@ -189,7 +190,7 @@ echo "HANDOFF_AUTO: ${_AUTO_TS:-none} ($_AUTO)" ## Procedure -The scripts live in `${CLAUDE_SKILL_DIR}/../../bin/`; the commands below are written without that path. The work contract (`ytstack:minimal-code`) holds for orchestration as it does for code: no review round, verifier or check that the plan does not name, and evidence for the same commit in the same environment stands. +The scripts live in the directory the preamble prints as `YT_BIN=` (also in the SessionStart context); the commands below are written without that path. Run each as `"$YT_BIN/ytstack-"` with the newest printed value set in the same command (`YT_BIN=; "$YT_BIN/ytstack-frontier" list`): a shell variable does not survive a tool call, and a versioned path from before an update or a compaction can name a removed version. The work contract (`ytstack:minimal-code`) holds for orchestration as it does for code: no review round, verifier or check that the plan does not name, and evidence for the same commit in the same environment stands. **Step 2 -- HARD-GATE.** `HAS_YTSTACK: no`: stop, "run `ytstack:init-project` or `ytstack:adopt-brownfield` first". `SLICE_PLANS: 0` and `no lanes`: stop, "nothing to coordinate; run `ytstack:slice-milestone`". One milestone with a handful of independent slices and no lane yet: `ytstack:spawn-milestone-team` does that with less ceremony; say so and stop unless the user asked for coordinator mode. @@ -233,7 +234,7 @@ A lane named in the `blocks:` of an open or asked question is not ready, whateve **The route, also when you merge yourself.** A merge you make outside `finish-lane` (a pull request outside the lanes, a project rule that the coordinator merges) reads the route for the reviewed head first and follows `finish-lane` Step 11: `MERGE_BY: risk` merges only after `route: unattended`; `coordinator` merges and names the route in the status; `human`, or a standing instruction that reserves the merge, leaves the merge to a person with the `reason:` lines. The merge itself is `ytstack-finish-lane -C merge --pr --at --verdict-pattern '^Verdict: approved'`, never `gh pr merge` by hand. Exit 0 of the route means `unattended`; everything else, an error included, means a person. -**Watching pull requests.** Polling happens outside the model. The PR watch counts as on only when `pr_watch=on` is set in `~/.ytstack/config` (`docs/pr-watch.md`) and the worker runs (`PR_WATCH: on, heartbeat s ago`, under 600). The flag alone enables only the hooks; without a fresh heartbeat nothing polls. With the PR watch on, the worker reports red checks, unresolved bot threads, conflicts and merges to this session with the next prompt, also for pull requests the lanes' subagents opened. The `register` call defaults to this session; check that its output says `registered to claude:` in Claude Code. Only the coordinator runs it; a session that works in the same repository outside this coordination keeps its own PRs (`register --pr N`), and `--all-open` skips the ones another session owns. Without the PR watch, start `ytstack-watch` as a background process; on a host with a monitor tool, through that tool, so that each new line reaches you as an event. It prints a line only when a head moved, the checks changed, a review arrived, mergeability changed or a pull request closed, and it ends when all are merged or closed; start it again with the new list when a pull request opens. Act on a line or a notice: red checks go back to the lane's worker with the name of the check; a review on a commit that is not the head is no review of the head. Never read status in a loop from the conversation, with or without a sleep. The single read of Step 4 before an action is not polling. +**Watching pull requests.** Polling happens outside the model. The PR watch counts as on only when `pr_watch=on` is set in `~/.ytstack/config` (`docs/pr-watch.md`) and the worker runs (`PR_WATCH: on, heartbeat s ago`, under 600). The flag alone enables only the hooks; without a fresh heartbeat nothing polls. With the PR watch on, the worker reports red checks, unresolved bot threads, conflicts and merges to this session with the next prompt, also for pull requests the lanes' subagents opened. The `register` call defaults to this session; check that its output says `registered to claude:` in Claude Code. `--all-open` takes only open pull requests by your GitHub login (the lanes' workers open them under it) and skips drafts, a `do-not-merge` label and the ones another session owns, each by name; `--author [,]`, `--include-drafts` and `--include-labelled` widen it only where this coordination owns such a pull request. Only the coordinator runs it; a session that works in the same repository outside this coordination keeps its own PRs (`register --pr N`). Without the PR watch, start `ytstack-watch` as a background process; on a host with a monitor tool, through that tool, so that each new line reaches you as an event. It prints a line only when a head moved, the checks changed, a review arrived, mergeability changed or a pull request closed, and it ends when all are merged or closed; start it again with the new list when a pull request opens. Act on a line or a notice: red checks go back to the lane's worker with the name of the check; a review on a commit that is not the head is no review of the head. Never read status in a loop from the conversation, with or without a sleep. The single read of Step 4 before an action is not polling. **After a merge.** A pull request that merged, also when a person merged it: set its lane to `merged`, then the release watch and the review lessons of the table. A merged lesson lane also closes its lesson: `ytstack-signals set F### --state fixed` once this checkout has the merged check (the script refuses while the file is missing). The receipt goes into the next status; `not arrived` or `unhealthy` is a status at once. You deploy nothing and roll nothing back: a countermeasure on the target is a step for the human (`ytstack:handover-step`). diff --git a/tests/hooks-readonly.test.sh b/tests/hooks-readonly.test.sh index 3bf2f053..ca5509f8 100644 --- a/tests/hooks-readonly.test.sh +++ b/tests/hooks-readonly.test.sh @@ -117,6 +117,7 @@ CTX=$(printf '%s' "$OUT" | jq -r '.hookSpecificOutput.additionalContext // empty has "ss-main: long next action -> its start is kept" "$CTX" "NEXTLINE0 xxx" has "ss-main: long next action -> the cut is marked" "$CTX" "(cut: rest in STATE.md)" lacks "ss-main: long next action -> not dropped" "$CTX" "(omitted: see STATE.md" +lacks "ss-main: long next action -> YT_BIN yields first (issue #85)" "$CTX" "YT_BIN=" if [ "${#CTX}" -le 9500 ]; then ok "ss-main: cut injection fits the guard (${#CTX})"; else bad "ss-main: cut injection fits the guard" "${#CTX}"; fi cp "$TMP/state.good" "$MAIN/.ytstack/STATE.md" diff --git a/tests/pr_watch/test_claude.py b/tests/pr_watch/test_claude.py index c1c13012..e8a58a6b 100644 --- a/tests/pr_watch/test_claude.py +++ b/tests/pr_watch/test_claude.py @@ -65,6 +65,8 @@ def test_ready_pr_is_summarised_and_closed_pr_drops_out(self): self.assertIn('o/r#7: ready (head head2', text) s['closed'] = True self.watch(s) + # Its last line says it closed (PR #89 review), then it drops out. + self.assertIn('o/r#7: closed', self.prompt()['hookSpecificOutput']['additionalContext']) self.assertEqual(self.prompt(), {}) def test_qualify_is_idempotent(self): diff --git a/tests/pr_watch/test_register_all.py b/tests/pr_watch/test_register_all.py index 83a471b5..f02e9302 100644 --- a/tests/pr_watch/test_register_all.py +++ b/tests/pr_watch/test_register_all.py @@ -20,6 +20,10 @@ spec.loader.exec_module(cli) +def pull(number, author='me', draft=False, labels=()): + return {'number': number, 'user': {'login': author}, 'draft': draft, 'labels': [{'name': n} for n in labels]} + + class RegisterAllOpen(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() @@ -50,8 +54,9 @@ def test_registers_every_open_pr_and_skips_foreign_ones(self): register(db, 'o/r', 2, 'claude:coordinator', '/tmp') # already ours register(db, 'o/r', 3, 'claude:other', '/tmp') # another session's db.close() - prs = [{'number': n} for n in (4, 1, 3, 2)] - with patch.object(github, 'open_pulls', return_value=prs) as listing: + prs = [pull(n) for n in (4, 1, 3, 2)] + with patch.object(github, 'open_pulls', return_value=prs) as listing, \ + patch.object(github, 'login', return_value='me'): code, out = self.run_cli('register', '--repo', 'o/r', '--all-open', '--session', 'claude:coordinator', '--cwd', self.tmp.name) self.assertEqual(code, 0) @@ -71,7 +76,8 @@ def racing_register(db, repo, number, session, cwd): (repo, number, 'claude:worker-found', cwd)) return real_register(db, repo, number, session, cwd) - with patch.object(github, 'open_pulls', return_value=[{'number': 7}]), \ + with patch.object(github, 'open_pulls', return_value=[pull(7)]), \ + patch.object(github, 'login', return_value='me'), \ patch.object(cli, 'register', side_effect=racing_register): code, out = self.run_cli('register', '--repo', 'o/r', '--all-open', '--session', 'claude:coordinator', '--cwd', self.tmp.name) @@ -88,6 +94,77 @@ def test_insert_raced_by_the_worker_is_not_reported_as_ours(self): db.close() self.assertEqual(self.watches(), {8: 'claude:worker-found'}) + def test_only_own_ready_prs_by_default(self): + # Issue #85: --all-open adopted another author's do-not-merge prototype. + prs = [pull(1), pull(2, author='other'), pull(3, draft=True), + pull(4, labels=['Do Not Merge']), pull(5, labels=['do-not-merge/hold']), pull(6, labels=['bug'])] + with patch.object(github, 'open_pulls', return_value=prs), \ + patch.object(github, 'login', return_value='me'): + code, out = self.run_cli('register', '--repo', 'o/r', '--all-open', + '--session', 'claude:coordinator', '--cwd', self.tmp.name) + self.assertEqual(code, 0) + self.assertEqual(sorted(self.watches()), [1, 6]) + self.assertIn('skipped by filter: #2 (author other) #3 (draft) #4 (do-not-merge) #5 (do-not-merge)', out) + + def test_author_widens_and_include_flags_opt_in(self): + prs = [pull(1), pull(2, author='other'), pull(3, author='third'), pull(4, author='bot[bot]'), + pull(5, draft=True), pull(6, labels=['DO_NOT_MERGE'])] + with patch.object(github, 'open_pulls', return_value=prs), \ + patch.object(github, 'login', return_value='me'): + code, out = self.run_cli('register', '--repo', 'o/r', '--all-open', '--author', 'other,bot[bot]', + '--include-drafts', '--include-labelled', + '--session', 'claude:coordinator', '--cwd', self.tmp.name) + self.assertEqual(code, 0) + self.assertEqual(sorted(self.watches()), [1, 2, 4, 5, 6]) + self.assertIn('#3 (author third)', out) + + def test_label_spellings_and_bot_authors(self): + prs = [pull(1, labels=['DNM']), pull(2, labels=['status: do not merge']), pull(3, labels=['dnmx']), + pull(4, author='dependabot[bot]'), pull(5, labels=['Do_Not_Merge'])] + with patch.object(github, 'open_pulls', return_value=prs), \ + patch.object(github, 'login', return_value='me'): + code, out = self.run_cli('register', '--repo', 'o/r', '--all-open', '--author', 'Dependabot', + '--session', 'claude:coordinator', '--cwd', self.tmp.name) + self.assertEqual(code, 0) + self.assertEqual(sorted(self.watches()), [3, 4]) + + def test_rerun_pauses_own_watches_the_filter_now_skips(self): + # PR #89 review: a watch from an earlier unfiltered run stayed active. + db = connect() + with db: + register(db, 'o/r', 20, 'claude:coordinator', '/tmp') + register(db, 'o/r', 21, 'claude:other', '/tmp') + db.close() + with patch.object(github, 'open_pulls', return_value=[pull(20, author='someone'), pull(21, author='someone')]), \ + patch.object(github, 'login', return_value='me'): + code, out = self.run_cli('register', '--repo', 'o/r', '--all-open', + '--session', 'claude:coordinator', '--cwd', self.tmp.name) + self.assertEqual(code, 0) + db = connect() + paused = {r['number']: r['paused'] for r in db.execute('SELECT number, paused FROM watches')} + db.close() + self.assertEqual(paused, {20: 1, 21: 0}) + self.assertIn('paused (watched by this session, now skipped by the filter): #20', out) + self.assertIn('resume --repo o/r --pr N', out) + + def test_login_lookup_failure(self): + failing = patch.object(github, 'login', side_effect=github.APIError('gh api failed (exit 1)')) + with patch.object(github, 'open_pulls', return_value=[pull(1), pull(2, author='bot')]), failing, \ + patch('sys.stderr', io.StringIO()) as err: + with self.assertRaises(SystemExit): + self.run_cli('register', '--repo', 'o/r', '--all-open', '--session', 's', '--cwd', self.tmp.name) + self.assertIn('--author ', err.getvalue()) + code, out = self.run_cli('register', '--repo', 'o/r', '--all-open', '--author', 'bot', + '--session', 's', '--cwd', self.tmp.name) + self.assertIn('only --author', err.getvalue()) + self.assertEqual(code, 0) + self.assertEqual(sorted(self.watches()), [2]) + + def test_filter_flags_need_all_open(self): + for flag in (['--author', 'x'], ['--include-drafts'], ['--include-labelled']): + with self.subTest(flag=flag), self.assertRaises(SystemExit), patch('sys.stderr', io.StringIO()): + self.run_cli('register', '--repo', 'o/r', '--pr', '5', '--session', 's', *flag) + def test_needs_a_session(self): with patch.object(github, 'open_pulls', return_value=[]), self.assertRaises(SystemExit): with redirect_stdout(io.StringIO()), patch('sys.stderr', io.StringIO()): diff --git a/tests/pr_watch/test_scope.py b/tests/pr_watch/test_scope.py new file mode 100644 index 00000000..229a2778 --- /dev/null +++ b/tests/pr_watch/test_scope.py @@ -0,0 +1,169 @@ +"""Issue #85: the status block names only the lines that changed, a PR stuck in +action_required for a day gets one pause suggestion, and `status` shows the +current session and repository unless --all.""" +import importlib.util +import io +import json +import os +import sys +import time +import unittest +from contextlib import redirect_stdout +from pathlib import Path +from unittest.mock import patch +import test_findings +from test_watch import snapshot +from prwatch import github, hooks, worker +from prwatch.state import enqueue, register + +ENGINE = Path(__file__).resolve().parents[2] / 'tools/pr-watch' +spec = importlib.util.spec_from_file_location('prwatch_cli_scope', ENGINE / 'pr-watch.py') +cli = importlib.util.module_from_spec(spec) +spec.loader.exec_module(cli) + + +class ChangedLines(unittest.TestCase): + setUp = test_findings.Findings.setUp + tearDown = test_findings.Findings.tearDown + + def observe(self, number, s): + with patch.object(github, 'snapshot', return_value=s): + worker.monitor(self.db, self.db.execute('SELECT * FROM watches WHERE number=?', (number,)).fetchone()) + + def prompt(self): + out = hooks.handle({'session_id': 'abc', 'hook_event_name': 'UserPromptSubmit', 'cwd': '/tmp'}, 'claude') + return out['hookSpecificOutput']['additionalContext'] if out else None + + def test_only_changed_lines_and_a_count_of_the_rest(self): + with self.db: + for n in (7, 8, 9): + register(self.db, 'o/r', n, 'claude:abc', '/tmp') + for n in (7, 8, 9): + self.observe(n, snapshot()) + first = self.prompt() + self.assertIn('o/r#7', first); self.assertIn('o/r#9', first) + self.assertNotIn('unchanged', first) + s = snapshot(); s['pr']['mergeable'] = False + self.observe(8, s) + text = self.prompt() + self.assertIn('o/r#8: action_required', text) + self.assertNotIn('o/r#7', text); self.assertNotIn('o/r#9', text) + self.assertIn('2 unchanged', text) + self.assertIsNone(self.prompt()) + # A pending notice comes with the count, not with the unchanged lines. + watch = self.db.execute('SELECT * FROM watches WHERE number=9').fetchone() + with self.db: + enqueue(self.db, 'k9', watch, 'notice for #9') + text = self.prompt() + self.assertIn('notice for #9', text) + self.assertIn('3 unchanged', text) + self.assertNotIn('o/r#9:', text) + + def test_a_closed_pr_gets_one_last_line_and_leaves_the_count(self): + # PR #89 review: a merge without bot findings sends no notice, so the line is the only report. + with self.db: + for n in (7, 8, 9): + register(self.db, 'o/r', n, 'claude:abc', '/tmp') + for n in (7, 8, 9): + self.observe(n, snapshot()) + self.prompt() + merged = snapshot(); merged['closed'] = True; merged['pr'] = {'state': 'closed', 'merged_at': '2026-11-15T00:00:00Z'} + self.observe(8, merged) + text = self.prompt() + self.assertIn('- o/r#8: closed (merged)', text) + self.assertIn('- 2 unchanged', text) + self.assertIsNone(self.prompt()) + closed = snapshot(); closed['closed'] = True; closed['pr'] = {'state': 'closed'} + self.observe(9, closed) + text = self.prompt() + self.assertIn('- o/r#9: closed\n', text) + self.assertIn('- 1 unchanged', text) + self.assertIsNone(self.prompt()) + # The last open one closes too: still reported, nothing counted. + self.observe(7, closed) + text = self.prompt() + self.assertIn('- o/r#7: closed', text) + self.assertNotIn('unchanged', text) + self.assertIsNone(self.prompt()) + + def stale(self, changed_at): + with self.db: + register(self.db, 'o/r', 7, 'claude:abc', '/tmp') + s = snapshot(); s['pr']['mergeable'] = False + self.observe(7, s) + self.prompt() + with self.db: + self.db.execute('UPDATE watches SET changed_at=? WHERE number=7', (changed_at,)) + return s + + def test_pause_hint_comes_once_even_when_the_detail_changes(self): + s = self.stale(time.time() - 25 * 3600) + text = self.prompt() + self.assertIn('no new head or status for 25 h', text) + self.assertIn('pause --repo o/r --pr 7', text) + self.assertIsNone(self.prompt()) + s['threads'] = [test_findings.thread()] + self.observe(7, s) # same head and status: changed_at stays + text = self.prompt() + self.assertIn('o/r#7: action_required', text) + self.assertNotIn('pause --repo', text) + # A SessionStart resets the block, not the hint. + hooks.handle({'session_id': 'abc', 'hook_event_name': 'SessionStart', 'cwd': '/tmp'}, 'claude') + self.assertNotIn('pause --repo', self.prompt()) + + def test_rows_without_changed_at_count_as_long_ago(self): + self.stale(None) + text = self.prompt() + self.assertIn('no new head or status for over 24 h', text) + + def test_stale_action_required_suggests_pause_once(self): + with self.db: + register(self.db, 'o/r', 7, 'claude:abc', '/tmp') + s = snapshot(); s['pr']['mergeable'] = False + self.observe(7, s) + self.assertNotIn('pause', self.prompt()) + with self.db: + self.db.execute('UPDATE watches SET changed_at=? WHERE number=7', (time.time() - 25 * 3600,)) + text = self.prompt() + self.assertIn('no new head or status for 25 h', text) + self.assertIn('pause --repo o/r --pr 7', text) + self.assertIsNone(self.prompt()) + with self.db: + self.db.execute('UPDATE watches SET paused=1 WHERE number=7') + self.assertNotIn('pause --repo', self.prompt()) + + +class StatusScope(unittest.TestCase): + setUp = test_findings.Findings.setUp + tearDown = test_findings.Findings.tearDown + + def status(self, *argv, session='abc', repo='o/r'): + out = io.StringIO() + with patch.dict(os.environ), patch.object(sys, 'argv', ['pr-watch', 'status', *argv]), \ + patch.object(cli, 'origin_repo', return_value=repo), redirect_stdout(out): + os.environ.pop('CODEX_THREAD_ID', None) + os.environ.pop('CLAUDE_CODE_SESSION_ID', None) + if session: + os.environ['CLAUDE_CODE_SESSION_ID'] = session + self.assertEqual(cli.main(), 0) + return json.loads(out.getvalue()) + + def test_current_session_and_repository_unless_all(self): + with self.db: + register(self.db, 'o/r', 7, 'claude:abc', '/tmp') + register(self.db, 'o/other', 7, 'claude:abc', '/tmp') + register(self.db, 'o/r', 8, 'claude:else', '/tmp') + mine = self.status() + self.assertEqual([(w['repo'], w['number']) for w in mine['watches']], [('o/r', 7)]) + self.assertEqual(mine['scope'], {'session': 'claude:abc', 'repo': 'o/r'}) + self.assertIn('health', mine) + self.assertEqual(len(self.status('--all')['watches']), 4) # with the fixture's o/r#1 + self.assertEqual(len(self.status('--repo', 'o/other')['watches']), 1) + # GitHub names are case-insensitive: a remote spelled differently still matches. + self.assertEqual(len(self.status(repo='O/R')['watches']), 1) + # Outside a session and a GitHub checkout nothing narrows it. + self.assertEqual(len(self.status(session=None, repo=None)['watches']), 4) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/pr_watch/test_session_spelling.py b/tests/pr_watch/test_session_spelling.py index 51d74c58..c6c911df 100644 --- a/tests/pr_watch/test_session_spelling.py +++ b/tests/pr_watch/test_session_spelling.py @@ -31,8 +31,12 @@ def setUp(self): clear=False) self.env.start() os.environ.pop('CODEX_THREAD_ID', None) + # register --all-open asks gh for the login (issue #85); never the real one here. + self.login = patch.object(github, 'login', return_value='me') + self.login.start() def tearDown(self): + self.login.stop() self.env.stop() self.tmp.cleanup() @@ -49,7 +53,7 @@ def rows(self, sql): return rows def test_bare_id_of_the_current_claude_session_is_qualified(self): - with patch.object(github, 'open_pulls', return_value=[{'number': 5}]): + with patch.object(github, 'open_pulls', return_value=[{'number': 5, 'user': {'login': 'me'}}]): code, out = self.run_cli('register', '--repo', 'o/r', '--all-open', '--session', SID, '--cwd', self.tmp.name) self.assertEqual(code, 0) @@ -58,7 +62,7 @@ def test_bare_id_of_the_current_claude_session_is_qualified(self): def test_bare_id_of_another_session_stays_as_given(self): # A Codex thread id is bare by design. - with patch.object(github, 'open_pulls', return_value=[{'number': 5}]): + with patch.object(github, 'open_pulls', return_value=[{'number': 5, 'user': {'login': 'me'}}]): self.run_cli('register', '--repo', 'o/r', '--all-open', '--session', 'codex-thread-1', '--cwd', self.tmp.name) self.assertEqual(self.rows('SELECT session FROM watches'), [('codex-thread-1',)]) @@ -70,7 +74,7 @@ def test_register_heals_watches_stored_under_the_bare_claude_id(self): enqueue(db, 'ci:o/r#7:abc', {'repo': 'o/r', 'number': 7, 'session': SID}, 'CI failed') db.execute("UPDATE outbox SET error='RPCError', attempts=3") db.close() - with patch.object(github, 'open_pulls', return_value=[{'number': 7}]): + with patch.object(github, 'open_pulls', return_value=[{'number': 7, 'user': {'login': 'me'}}]): code, out = self.run_cli('register', '--repo', 'o/r', '--all-open', '--cwd', self.tmp.name) self.assertEqual(code, 0) self.assertEqual(self.rows('SELECT session FROM watches'), [('claude:' + SID,)]) diff --git a/tests/session-notices.test.sh b/tests/session-notices.test.sh index 1faf97cb..acf904b8 100644 --- a/tests/session-notices.test.sh +++ b/tests/session-notices.test.sh @@ -156,6 +156,9 @@ ss ""; has "no source: block" "$CTX" "Factory tools" ss resume; lacks "resume: no block" "$CTX" "Factory tools" ss compact; lacks "compact: no block" "$CTX" "Factory tools" has "compact still injects the state" "$CTX" "scope: project" +# issue #85: every SessionStart names the running version's bin directory +has "compact: YT_BIN names this version's bins" "$CTX" " +YT_BIN=$ROOT/bin" # Near the cap the list shrinks to one pointer line (a directive of ~9,000 chars). mkdir -p "$TMP/bigroot/skills/using-ytstack" awk 'BEGIN { for (i = 0; i < 90; i++) printf "%0100d\n", i }' > "$TMP/bigroot/skills/using-ytstack/SKILL.md" diff --git a/tests/skill-preambles.test.sh b/tests/skill-preambles.test.sh index 4e2d8e27..fd91385d 100644 --- a/tests/skill-preambles.test.sh +++ b/tests/skill-preambles.test.sh @@ -312,6 +312,9 @@ STANDING_ENTRIES_END" rm -rf "$WT/.ytstack/standing" "$WT/.ytstack/STANDING.md" # the factory tools (M031, issue #54): Step 7 skips by what the project switched on run_pre "$P" "$WT" + # issue #85: the bins of the running version, canonical, for "$YT_BIN/ytstack-" + has "$s: YT_BIN is the canonical bin directory" "$OUT" "YT_BIN=$ROOT/bin +" has "$s: bare fixture -> merge_by risk" "$OUT" "MERGE_BY: risk" has "$s: bare fixture -> no review policy" "$OUT" "REVIEW_POLICY: no" has "$s: bare fixture -> no own reviewers" "$OUT" "OWN_REVIEWERS: no" diff --git a/tools/pr-watch/pr-watch.py b/tools/pr-watch/pr-watch.py index ba4efa18..0329a5b3 100755 --- a/tools/pr-watch/pr-watch.py +++ b/tools/pr-watch/pr-watch.py @@ -6,6 +6,7 @@ import argparse import json import os +import re import sys import subprocess import time @@ -21,26 +22,67 @@ from prwatch.worker import tick +# A label that says "do not merge": `do-not-merge`, `DO NOT MERGE`, `do_not_merge/hold`, `status: dnm`. +DO_NOT_MERGE = re.compile(r'\b(?:do not merge|dnm)\b') + + +def login_key(login): + """A login as compared: case-insensitive, `dependabot` and `dependabot[bot]` alike.""" + login = login.strip().lower() + return login[:-len('[bot]')] if login.endswith('[bot]') else login + + +def skip_reason(pr, authors, drafts, labelled): + """Why `register --all-open` leaves an open PR alone, or None: another author, a draft, + a do-not-merge label.""" + author = (pr.get('user') or {}).get('login') or '' + if login_key(author) not in authors: + return f'author {author or "unknown"}' + if pr.get('draft') and not drafts: + return 'draft' + names = [' '.join(re.sub(r'[-_/:.]', ' ', (label.get('name') or '').lower()).split()) + for label in pr.get('labels') or []] + if not labelled and any(DO_NOT_MERGE.search(name) for name in names): + return 'do-not-merge' + return None + + +def origin_repo(cwd): + """OWNER/REPO of the origin remote of `cwd`, or None (no checkout, no GitHub origin).""" + from prwatch.hooks import REPO + p = subprocess.run(['git', '-C', cwd, 'remote', 'get-url', 'origin'], capture_output=True, text=True, timeout=3) + match = REPO.fullmatch(p.stdout.strip()) if p.returncode == 0 else None + return match[1] if match else None + + def main(): parser = argparse.ArgumentParser(prog='ytstack-pr-watch', description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = parser.add_subparsers(dest='command', required=True) hook = sub.add_parser('hook', help='Hook entrypoint (stdin: hook payload); called by hooks/pr-watch') hook.add_argument('--host', choices=('codex', 'claude'), default='codex') - sub.add_parser('status', help='Watches, pending notices and worker health as JSON') - poll = sub.add_parser('tick', help='One worker pass: discover, poll GitHub, deliver') - poll.add_argument('--no-delivery', action='store_true') - poll.add_argument('--no-discovery', action='store_true') # Codex exports CODEX_THREAD_ID; Claude Code exports CLAUDE_CODE_SESSION_ID (stored host-qualified). default_session = os.environ.get('CODEX_THREAD_ID') or ( claude.qualify(os.environ['CLAUDE_CODE_SESSION_ID']) if os.environ.get('CLAUDE_CODE_SESSION_ID') else None) + show = sub.add_parser('status', help='Watches, pending notices and worker health as JSON; by default only ' + 'the current session and the repository of the working directory') + show.add_argument('--all', action='store_true', help='every session and repository') + show.add_argument('--session', default=default_session) + show.add_argument('--repo') + poll = sub.add_parser('tick', help='One worker pass: discover, poll GitHub, deliver') + poll.add_argument('--no-delivery', action='store_true') + poll.add_argument('--no-discovery', action='store_true') add = sub.add_parser('register', help='Watch an open PR (or every open PR of a repository) for a session') add.add_argument('--repo', required=True) which = add.add_mutually_exclusive_group(required=True) which.add_argument('--pr', type=int) which.add_argument('--all-open', action='store_true', - help='every open PR of --repo, for example the ones subagents or other sessions opened; ' - 'PRs another session owns are skipped and named') + help='every open PR of --repo by you (gh login), for example the ones subagents opened; ' + 'drafts, do-not-merge labels and PRs another session owns are skipped and named') + add.add_argument('--author', help='with --all-open: also PRs of these logins (comma-separated)') + add.add_argument('--include-drafts', action='store_true', help='with --all-open: also draft PRs') + add.add_argument('--include-labelled', action='store_true', + help='with --all-open: also PRs with a do-not-merge label') add.add_argument('--session', default=default_session) add.add_argument('--cwd', default=os.getcwd()) create = sub.add_parser('create', help='Create a PR and persist ownership before returning') @@ -69,6 +111,8 @@ def main(): move.add_argument('--from', dest='source', required=True, metavar='DIR') move.add_argument('--yes', action='store_true') args = parser.parse_args() + if args.command == 'register' and not args.all_open and (args.author or args.include_drafts or args.include_labelled): + parser.error('--author, --include-drafts and --include-labelled apply to --all-open only') # The current Claude session's id given bare would be stored as a Codex thread and never delivered. own = os.environ.get('CLAUDE_CODE_SESSION_ID') if own and getattr(args, 'session', None) == own: @@ -156,11 +200,28 @@ def main(): elif args.command == 'register' and args.all_open: if not args.session: parser.error('--session or CODEX_THREAD_ID required') - # One paginated list call (one REST call per 100 open PRs). + # One paginated list call (one REST call per 100 open PRs), one for the login. cwd = str(Path(args.cwd).resolve()) - added, kept, foreign = [], [], [] + authors = {login_key(a) for a in (args.author or '').split(',') if a.strip()} + try: + authors.add(login_key(github.login())) + except github.APIError: + if not authors: + parser.error('could not read your GitHub login (gh api user); check `gh auth status` ' + 'or name the authors with --author [,]') + print('ytstack-pr-watch: could not read your GitHub login (gh api user); ' + 'registering only --author PRs', file=sys.stderr) + added, kept, foreign, filtered, paused = [], [], [], [], [] for pr in sorted(github.open_pulls(args.repo), key=lambda p: p['number']): number = pr['number'] + reason = skip_reason(pr, authors, args.include_drafts, args.include_labelled) + if reason: + filtered.append(f'#{number} ({reason})') + # A watch of this session from an earlier, unfiltered run would keep reporting. + if db.execute("UPDATE watches SET paused=1 WHERE repo=? AND number=? AND session=? " + "AND paused=0 AND status!='closed'", (args.repo, number, args.session)).rowcount: + paused.append(f'#{number}') + continue known = db.execute('SELECT session FROM watches WHERE repo=? AND number=?', (args.repo, number)).fetchone() try: @@ -173,11 +234,17 @@ def main(): continue (kept if known else added).append(f'#{number}') print(f'{args.repo}: {len(added)} registered to {args.session}, {len(kept)} already watched by it, ' - f'{len(foreign)} owned by another session') + f'{len(foreign)} owned by another session, {len(filtered)} skipped by filter') if added: print(' registered: ' + ' '.join(added)) if foreign: print(' skipped (another session owns them; pause or register them there): ' + ' '.join(foreign)) + if filtered: + print(' skipped by filter: ' + ' '.join(filtered) + + ' (widen with --author, --include-drafts, --include-labelled, or register --pr N)') + if paused: + print(' paused (watched by this session, now skipped by the filter): ' + ' '.join(paused) + + f' (undo: {cli()} resume --repo {args.repo} --pr N)') elif args.command == 'register': if not args.session: parser.error('--session or CODEX_THREAD_ID required') @@ -192,8 +259,15 @@ def main(): if not cursor.rowcount: parser.error('Unknown PR') elif args.command == 'status': - print(json.dumps(dict(watches=[dict(r) for r in db.execute('SELECT * FROM watches')], - pending_delivery=[dict(r) for r in db.execute('SELECT event_key,session,attempts,error,retry_at,dispatch_id,turn_id FROM outbox WHERE delivered IS NULL AND cancelled IS NULL')], + # Default scope: this session and the repository of the working directory (issue #85). + scope = {} if args.all else {k: v for k, v in ( + ('session', args.session), ('repo', args.repo or origin_repo(os.getcwd()))) if v} + # GitHub owner and repository names are case-insensitive. + where = ' AND '.join('lower(repo)=lower(?)' if k == 'repo' else f'{k}=?' for k in scope) or '1' + print(json.dumps(dict(scope=scope or 'all', + watches=[dict(r) for r in db.execute(f'SELECT * FROM watches WHERE {where}', tuple(scope.values()))], + pending_delivery=[dict(r) for r in db.execute('SELECT event_key,session,attempts,error,retry_at,dispatch_id,turn_id FROM outbox ' + f'WHERE delivered IS NULL AND cancelled IS NULL AND {where}', tuple(scope.values()))], health={r['key']:r['value'] for r in db.execute('SELECT * FROM meta')}), indent=2)) db.close() return 0 diff --git a/tools/pr-watch/prwatch/claude.py b/tools/pr-watch/prwatch/claude.py index ed2782ca..120fd5eb 100644 --- a/tools/pr-watch/prwatch/claude.py +++ b/tools/pr-watch/prwatch/claude.py @@ -3,16 +3,20 @@ Claude sessions are stored host-qualified (`claude:`). The worker never pushes to them; instead every user prompt surfaces the session's pending actionable notices (CI failure, unresolved bot thread, merge conflict, an -observed merge) and a -one-line readiness summary per watched PR, read from the last worker tick. +observed merge) and the +one-line readiness summaries that changed since the last injection, plus a count +of the unchanged ones, read from the last worker tick. Hooks make no GitHub calls, so the evidence is at most one tick old and the agent re-fetches before acting. """ import json import time import uuid +from .state import cli PREFIX = 'claude:' +# A PR action_required without a head or status change for this long gets one pause suggestion. +STALE = 24 * 3600 def qualify(session): @@ -23,6 +27,23 @@ def surface_key(session): return f'surface:{session}' +def hint_key(session): + """The pause hints already shown to `session`: PR key -> changed_at of that stretch. + SessionStart does not reset it, so a compaction does not repeat a hint.""" + return f'pause-hint:{session}' + + +def _meta_dict(db, key): + """A JSON object stored in meta, {} when missing or of another shape (the whole-block + fingerprint of older versions reads as {}: every line is shown once).""" + row = db.execute('SELECT value FROM meta WHERE key=?', (key,)).fetchone() + try: + value = json.loads(row['value']) if row else {} + except ValueError: + return {} + return value if isinstance(value, dict) else {} + + def is_claude(session): return bool(session) and session.startswith(PREFIX) @@ -41,32 +62,55 @@ def surface(db, session, now=None): ON w.repo=o.repo AND w.number=o.number AND w.session=o.session WHERE o.session=? AND o.delivered IS NULL AND o.cancelled IS NULL AND w.paused=0 ORDER BY o.created''', (session,)).fetchall() - if not watches and not notices: + seen = _meta_dict(db, surface_key(session)) + # A watch shown last time that closed since gets one last line: a merge without a bot + # finding queues no notice, so this line is its only report (PR #89 review). + gone = [w for w in db.execute("SELECT * FROM watches WHERE session=? AND status='closed' ORDER BY repo, number", + (session,)) if f'{w["repo"]}#{w["number"]}' in seen] + if not watches and not notices and not gone: return None - lines = ['PR Watch (silent background monitor; evidence from the last worker tick, re-fetch before acting):'] - state = [] + hinted, hints = _meta_dict(db, hint_key(session)), {} + # Each line with its fingerprint (ages excluded); only changed lines are injected (issues #61, #85). + current, due = {}, set() for w in watches: + key = f'{w["repo"]}#{w["number"]}' detail = json.loads(w['detail'] or '[]') 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') + current[key] = ((w['paused'], 'moved'), f'- {key}{paused}: head moved by a push ' + f'{_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() + line = (f'- {key}{paused}: {w["status"]} (head {w["head"][:8] or "?"}, {observed})' + + (f' -- {summary}' if summary else '')) + # changed_at NULL (rows from before it existed) counts as long ago (state.py). + changed = w['changed_at'] if 'changed_at' in w.keys() else None + if w['status'] == 'action_required' and not w['paused'] and (changed is None or now - changed >= STALE): + hints[key] = changed + if key not in hinted or hinted[key] != changed: + # Once per stale stretch (a new head or status starts a new one), also across SessionStart. + due.add(key) + age = f'{int((now - changed) // 3600)} h' if changed is not None else 'over 24 h' + line += (f'; no new head or status for {age}: if nobody works on it, ' + f'{cli()} pause --repo {w["repo"]} --pr {w["number"]}') + current[key] = ((w['paused'], w['status'], w['head'], w['detail']), line) + fingerprints = {key: json.dumps(fp) for key, (fp, _) in current.items()} with db: - db.execute('INSERT OR REPLACE INTO meta VALUES(?,?)', (surface_key(session), fingerprint)) - if not notices and last and last['value'] == fingerprint: + db.execute('INSERT OR REPLACE INTO meta VALUES(?,?)', (surface_key(session), json.dumps(fingerprints))) + db.execute('INSERT OR REPLACE INTO meta VALUES(?,?)', (hint_key(session), json.dumps(hints))) + changed_lines = [line for key, (_, line) in current.items() if key in due or seen.get(key) != fingerprints[key]] + closed_lines = [f'- {w["repo"]}#{w["number"]}: closed' + + (' (merged)' if 'merged' in json.loads(w['detail'] or '[]') else '') for w in gone] + if not notices and not changed_lines and not closed_lines: return None + unchanged = len(current) - len(changed_lines) + lines = ['PR Watch (silent background monitor; evidence from the last worker tick, re-fetch before acting):', + *changed_lines, *closed_lines] + if unchanged: + lines.append(f'- {unchanged} unchanged') if notices: lines.append('Actionable notices (delivered once):') lines.extend(n['message'] for n in notices) diff --git a/tools/pr-watch/prwatch/github.py b/tools/pr-watch/prwatch/github.py index 8f4bc2ea..0b8c9ff7 100644 --- a/tools/pr-watch/prwatch/github.py +++ b/tools/pr-watch/prwatch/github.py @@ -34,6 +34,11 @@ def open_pulls(repo): return api(f'repos/{repo}/pulls?state=open&per_page=100', True) +def login(): + """The GitHub login gh is signed in as.""" + return api('user')['login'] + + def review_threads(repo, number): owner, name = repo.split('/') query = '''query($owner:String!,$name:String!,$number:Int!,$cursor:String){