diff --git a/.ytstack/KNOWLEDGE.md b/.ytstack/KNOWLEDGE.md index 694bfe97..0751758a 100644 --- a/.ytstack/KNOWLEDGE.md +++ b/.ytstack/KNOWLEDGE.md @@ -52,6 +52,7 @@ Patterns, rules, and lessons learned while building ytstack. This file is read b ## Gotchas +- **A running session keeps the hooks it started with.** (2026-11-14, issue #54) Plugin hooks load at session start; removing user-level hooks from `~/.claude/settings.json` takes effect in running sessions at once. During the PR watch switch, a coordinator session started on ytstack 0.7.0 lost the old local hooks and never got the new plugin hooks: from about 14:30 UTC on, roughly 60 PRs its subagents opened were not registered (subagent hook calls carry the parent's session, so before the switch they were). Any hook switch: restart running sessions, then re-register: the session owning the repository's PRs runs `ytstack-pr-watch register --all-open`, independent sessions register only their own PRs (`--pr N`), else ownership follows restart order. Measure the gap from the host (PRs created vs. watches registered), not from `status`, which shows only what is registered. - **Anything launchd runs must not be a version-manager shim.** (0.8.2) launchd starts jobs without a shell profile; an asdf shim (`~/.asdf/shims/gh`) execs `asdf`, which is not on the job's `PATH`, and fails with `exec: asdf: not found`. The PR watch worker recorded the shim's directory, so every GitHub read failed and all watches turned `unavailable` while `health.heartbeat` looked fine. Resolve the binary by running it with only its own directory and the system directories on `PATH` (`runs_alone` in `tools/pr-watch/prwatch/admin.py`). Read `status` watch states after installing a worker, not only the heartbeat. - **A state migrated from an older tool carries history the new logic never saw.** (0.8.1) The local PR watch held 1,148 closed watches without the `merged` marker 0.8.0 introduced; 0.8.0 would have treated all of them as reopen candidates. Before switching a live install over, simulate the first tick's selection on a copy of the real state. - **gstack's `./setup` registers every gstack skill globally; there is no switch to stop it for Claude Code.** (2026-11-14) A gstack install for ytstack's sake left 63 folders with a `.gstack-owned` marker (symlinks into `~/.claude/skills/gstack//`) in `~/.claude/skills/`, plus `gstack` itself: every session listed ~65 skills ytstack never curated. `--prefix` only renames them, `--no-harness-auto` concerns OpenClaw/Hermes. A plain copy of gstack's skill folders does not run either: the six skills referenced 54 `bin/gstack-*` helpers (29 Bun scripts, one compiled binary), `node_modules` (~560 MB) and hard-coded `~/.claude/skills/gstack/` paths. Hence the adaptation (DECISIONS 2026-11-14). Cleaning up a machine: delete only folders carrying `.gstack-owned` (their content is symlinks plus the marker; `_gstack-command` and `connect-chrome` hold a generated SKILL.md), or run gstack's `bin/gstack-uninstall --keep-state` after reading its `--help` (it also removes other agents' gstack installs). diff --git a/.ytstack/spec/checks-and-evals.md b/.ytstack/spec/checks-and-evals.md index fb76d72e..7ffcea0d 100644 --- a/.ytstack/spec/checks-and-evals.md +++ b/.ytstack/spec/checks-and-evals.md @@ -26,7 +26,7 @@ sources: - docs/ux/review-policy-format.md - docs/ux/runtime-format.md - docs/ux/signal-format.md -verified_at: d6001bb +verified_at: 1b7bfc8 --- # checks-and-evals @@ -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) 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`) 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/host-adapters.md b/.ytstack/spec/host-adapters.md index 4da9c02b..c1844848 100644 --- a/.ytstack/spec/host-adapters.md +++ b/.ytstack/spec/host-adapters.md @@ -14,7 +14,7 @@ paths: sources: - docs/codex.md - docs/kimi.md -verified_at: 4207daa +verified_at: 449fee7 --- # host-adapters diff --git a/.ytstack/spec/skills.md b/.ytstack/spec/skills.md index c674e395..dc915487 100644 --- a/.ytstack/spec/skills.md +++ b/.ytstack/spec/skills.md @@ -8,7 +8,7 @@ sources: - docs/ux/skill-structure.md - docs/ux/askuserquestion-format.md - docs/ux/agent-structure.md -verified_at: 08dab40 +verified_at: 1b7bfc8 --- # skills @@ -105,7 +105,7 @@ No other skill reads the flag. 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 `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`, poll through `bin/ytstack-watch`, ask one question at a time from a question file, write a standing instruction down when it is given, stop a lane that failed verification twice or needs a third review, and rotate through a handoff after the first compaction. +- `coordinate` is a loop with a fixed order: start from `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`, 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`, at the start and after every restart) and otherwise poll through `bin/ytstack-watch`, ask one question at a time from a question file, write a standing instruction down when it is given, stop a lane that failed verification twice or needs a third review, and rotate through a handoff after the first compaction. - `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: the one skill 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. 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. diff --git a/CHANGELOG.md b/CHANGELOG.md index 71341245..9f818cac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `ytstack-pr-watch register --repo OWNER/REPO --all-open` registers every open + PR of a repository to the current session in one listing call and names the + ones another session owns. Only the session owning the repository's PRs (a + coordinator) runs it, at its start and after a restart; independent sessions + register their own PRs with `--pr` (issue #54). `register` now checks the + owner after its insert, so a PR the worker registered at the same moment is + reported as foreign instead of as registered. + +### Fixed + +- PR watch: the docs and the `migrate` steps now say that running sessions + keep the hooks they started with. A session that was running when the PR + watch was switched on (or when ytstack gained the hooks) registered nothing + until it restarted; on the maintainer's machine a coordinator's subagents + opened about 60 PRs in that window that were never watched. `coordinate` + (0.2.1) registers the open PRs with `--all-open` when the PR watch is on, + and counts it as on only with a worker heartbeat younger than 10 minutes; + otherwise it keeps polling through `ytstack-watch`. + ## [0.9.0] - 2026-11-14 ### Added diff --git a/docs/pr-watch.md b/docs/pr-watch.md index 85d593a8..47dfd873 100644 --- a/docs/pr-watch.md +++ b/docs/pr-watch.md @@ -67,6 +67,7 @@ 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 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 @@ -75,6 +76,19 @@ bin/ytstack-pr-watch status Inside a session `--session` defaults to the current one (`CODEX_THREAD_ID`, or `claude:$CLAUDE_CODE_SESSION_ID`). +Subagents run inside their parent session, and their hook calls carry the +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 +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 +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 +claim the others' PRs for whichever session restarted first. + ## Delivery: Claude Code pulls, Codex is woken **Claude Code.** Sessions are stored as `claude:` and are never @@ -203,6 +217,7 @@ remaining steps, which are yours to run: 2. Remove the old `pr-watch hook --host claude` entries from `~/.claude/settings.json` (back the file up first). Otherwise both hook sets run. 3. Disable or remove the old Codex plugin `pr-watch@local-pr-watch`. 4. `bin/ytstack-pr-watch enable`, then `bin/ytstack-pr-watch install-worker --yes`. +5. Restart every running Claude Code and Codex session. A running session keeps the hooks it loaded at start: once step 2 removed the old ones, it registers no PR until it restarts, and what it opened in between is not watched. After the restart, the one session that owns a repository's PRs (a coordinator in particular) runs `bin/ytstack-pr-watch register --repo OWNER/REPO --all-open` once to pick up the PRs opened meanwhile; independent sessions in the same repository register only their own PRs with `register --pr N`. ## Limits diff --git a/skills/coordinate/SKILL.md b/skills/coordinate/SKILL.md index 6780aace..b87f990b 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.2.0 + version: 0.2.1 allowed-tools: - Bash - Read @@ -182,6 +182,8 @@ A lane named in the `blocks:` of an open or asked question is not ready, whateve ytstack-watch --pr --interval 60 ``` +The PR watch counts as on only when `pr_watch=on` is set in `~/.ytstack/config` (`docs/pr-watch.md`) and the worker runs: `ytstack-pr-watch status` shows `health.heartbeat` (Unix seconds of the last finished tick) less than 10 minutes old. The flag alone enables only the hooks; without a fresh heartbeat nothing polls, so use `ytstack-watch` as below and tell the person to run `install-worker --yes` or check the worker. With the PR watch on, the background worker already reports red checks, unresolved bot threads and conflicts to this session with the next prompt, also for pull requests the lanes' subagents opened. Register the repository's open pull requests to this session once at the start of coordination and after every restart: `ytstack-pr-watch register --repo --all-open`. Only the coordinator runs it; a session that works in the same repository but outside this coordination keeps its own PRs (`register --pr N`), and `--all-open` skips the ones it already owns. Without it, start `ytstack-watch` as below. + Start it 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. Act on the line: 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. A pull request that merged, also when a person merged it: set its lane to `merged` and watch the release of its merge commit as `ytstack:finish-lane` describes ("Watch the release"), with `ytstack-watch release --commit ` in the background. Its 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`). Start the watcher again with the new list when a pull request opens. 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. **Step 8 -- Queue and ask questions.** First look the question up: the plan, `DECISIONS.md`, the answered files in `questions/`. What they answer is not asked. Otherwise `ytstack-questions new --question "" --decides "" --blocks ""` and fill Context, Options and Recommendation until the human can answer from the file alone. The state is `open` and the lanes that do not depend on it go on. Ask as late as the work allows: when nothing ready is left that is independent of it, or at a boundary from `STANDING.md`. Ask one (`ytstack-questions next`), mark it (`ytstack-questions ask `), and use AskUserQuestion: diff --git a/tests/pr_watch/test_register_all.py b/tests/pr_watch/test_register_all.py new file mode 100644 index 00000000..83a471b5 --- /dev/null +++ b/tests/pr_watch/test_register_all.py @@ -0,0 +1,102 @@ +"""`register --all-open`: a coordinator takes over every open PR of a repository, +including the ones subagents or earlier sessions opened (issue #54).""" +import importlib.util +import io +import os +import sys +import tempfile +import unittest +from contextlib import redirect_stdout +from pathlib import Path +from unittest.mock import patch + +ENGINE = Path(__file__).resolve().parents[2] / 'tools/pr-watch' +sys.path.insert(0, str(ENGINE)) +from prwatch import github +from prwatch.state import connect, register + +spec = importlib.util.spec_from_file_location('prwatch_cli', ENGINE / 'pr-watch.py') +cli = importlib.util.module_from_spec(spec) +spec.loader.exec_module(cli) + + +class RegisterAllOpen(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.env = patch.dict(os.environ, {'PR_WATCH_HOME': self.tmp.name}, clear=False) + self.env.start() + os.environ.pop('CLAUDE_CODE_SESSION_ID', None) + os.environ.pop('CODEX_THREAD_ID', None) + + def tearDown(self): + self.env.stop() + self.tmp.cleanup() + + def run_cli(self, *argv): + out = io.StringIO() + with patch.object(sys, 'argv', ['pr-watch', *argv]), redirect_stdout(out): + code = cli.main() + return code, out.getvalue() + + def watches(self): + db = connect() + rows = {r['number']: r['session'] for r in db.execute('SELECT number, session FROM watches')} + db.close() + return rows + + def test_registers_every_open_pr_and_skips_foreign_ones(self): + db = connect() + with db: + 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: + code, out = self.run_cli('register', '--repo', 'o/r', '--all-open', + '--session', 'claude:coordinator', '--cwd', self.tmp.name) + self.assertEqual(code, 0) + listing.assert_called_once_with('o/r') + self.assertEqual(self.watches(), {1: 'claude:coordinator', 2: 'claude:coordinator', + 3: 'claude:other', 4: 'claude:coordinator'}) + self.assertIn('2 registered to claude:coordinator, 1 already watched by it, 1 owned by another session', out) + self.assertIn('registered: #1 #4', out) + self.assertIn('#3 (claude:other)', out) + + def test_pr_registered_by_another_process_after_the_lookup_is_skipped(self): + real_register = cli.register + + def racing_register(db, repo, number, session, cwd): + # The worker registers the PR between the CLI's lookup and its register call. + db.execute('INSERT OR IGNORE INTO watches(repo,number,session,cwd) VALUES(?,?,?,?)', + (repo, number, 'claude:worker-found', cwd)) + return real_register(db, repo, number, session, cwd) + + with patch.object(github, 'open_pulls', return_value=[{'number': 7}]), \ + 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) + self.assertEqual(code, 0) + self.assertIn('#7 (claude:worker-found)', out) + + def test_insert_raced_by_the_worker_is_not_reported_as_ours(self): + # The worker commits its watch after any pre-check: register itself must notice. + db = connect() + with db: + db.execute("INSERT INTO watches(repo,number,session,cwd) VALUES('o/r',8,'claude:worker-found','/tmp')") + with self.assertRaises(ValueError): + register(db, 'o/r', 8, 'claude:coordinator', '/tmp') + db.close() + self.assertEqual(self.watches(), {8: 'claude:worker-found'}) + + 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()): + self.run_cli('register', '--repo', 'o/r', '--all-open') + + def test_pr_and_all_open_are_exclusive(self): + with self.assertRaises(SystemExit), patch('sys.stderr', io.StringIO()): + self.run_cli('register', '--repo', 'o/r', '--all-open', '--pr', '5', '--session', 's') + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/pr-watch/pr-watch.py b/tools/pr-watch/pr-watch.py index 4d021b73..05b468ef 100755 --- a/tools/pr-watch/pr-watch.py +++ b/tools/pr-watch/pr-watch.py @@ -33,9 +33,13 @@ def main(): # 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) - add = sub.add_parser('register', help='Watch an open PR for a session') + 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) - add.add_argument('--pr', required=True, type=int) + 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') 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') @@ -117,7 +121,32 @@ def main(): else: db = connect() with db: - if args.command == 'register': + if 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). + cwd = str(Path(args.cwd).resolve()) + added, kept, foreign = [], [], [] + for pr in sorted(github.open_pulls(args.repo), key=lambda p: p['number']): + number = pr['number'] + known = db.execute('SELECT session FROM watches WHERE repo=? AND number=?', + (args.repo, number)).fetchone() + try: + register(db, args.repo, number, args.session, cwd) + except ValueError: + # Re-read: the worker may have registered the PR after the lookup above. + owner = db.execute('SELECT session FROM watches WHERE repo=? AND number=?', + (args.repo, number)).fetchone() + foreign.append(f'#{number} ({owner["session"] if owner else "unknown"})') + 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') + if added: + print(' registered: ' + ' '.join(added)) + if foreign: + print(' skipped (another session owns them; pause or register them there): ' + ' '.join(foreign)) + elif args.command == 'register': if not args.session: parser.error('--session or CODEX_THREAD_ID required') pr = github.api(f'repos/{args.repo}/pulls/{args.pr}') diff --git a/tools/pr-watch/prwatch/admin.py b/tools/pr-watch/prwatch/admin.py index 5d69b234..866c6aeb 100644 --- a/tools/pr-watch/prwatch/admin.py +++ b/tools/pr-watch/prwatch/admin.py @@ -325,4 +325,8 @@ def _migrate(db_path, policy_path, state, target, scratch, yes): print(' 2. remove the old `pr-watch hook --host claude` entries from ~/.claude/settings.json (back it up first)') print(' 3. disable or remove the old Codex plugin pr-watch@local-pr-watch (Codex plugin settings)') print(f' 4. {cli()} enable, then {cli()} install-worker --yes') + print(' 5. restart every running Claude Code and Codex session (a running session keeps the hooks it ' + f'started with); then the one session owning a repository\'s PRs (a coordinator) runs ' + f'{cli()} register --repo OWNER/REPO --all-open, independent sessions register only their own ' + f'PRs with register --repo OWNER/REPO --pr N') return 0 diff --git a/tools/pr-watch/prwatch/state.py b/tools/pr-watch/prwatch/state.py index 5c3b84f3..9952e8a0 100644 --- a/tools/pr-watch/prwatch/state.py +++ b/tools/pr-watch/prwatch/state.py @@ -70,12 +70,13 @@ def enqueue(db, key, watch, message): def register(db, repo, number, session, cwd): - existing = db.execute('SELECT session FROM watches WHERE repo=? AND number=?', (repo, number)).fetchone() - if existing and existing['session'] != session: - raise ValueError('PR already belongs to another session; explicit reassignment required') - db.execute('DELETE FROM meta WHERE key IN (?,?)', (f'ownership:{repo}:{number}', f'registration:{repo}:{number}')) + # Insert first, then read the owner: a check before the insert races with the worker. db.execute('INSERT OR IGNORE INTO watches(repo,number,session,cwd) VALUES(?,?,?,?)', (repo, number, session, cwd)) + owner = db.execute('SELECT session FROM watches WHERE repo=? AND number=?', (repo, number)).fetchone() + if owner['session'] != session: + raise ValueError('PR already belongs to another session; explicit reassignment required') + db.execute('DELETE FROM meta WHERE key IN (?,?)', (f'ownership:{repo}:{number}', f'registration:{repo}:{number}')) # Registering again revives a watch that was closed (for example a PR that was reopened). db.execute("UPDATE watches SET status='registered', updated=0, closed_at=NULL WHERE repo=? AND number=? AND status='closed'", (repo, number))