diff --git a/.github/workflows/housekeeping.yml b/.github/workflows/housekeeping.yml index 59d8661..d69a2c8 100644 --- a/.github/workflows/housekeeping.yml +++ b/.github/workflows/housekeeping.yml @@ -163,6 +163,8 @@ jobs: echo "allowed=$tools" >> "$GITHUB_OUTPUT" - name: Claude if: steps.check.outputs.run == 'true' + # Below the job timeout, so the roadmap finish below still runs when the model is cut off. + timeout-minutes: 80 uses: anthropics/claude-code-action@eb56b6666facdbd501035f4a0269d8caee2e7a8b # v1.0.289 env: GH_TOKEN: ${{ steps.app.outputs.token }} @@ -188,6 +190,24 @@ jobs: node=$(GH_TOKEN="$APP_TOKEN" gh pr view "$pr" --repo "$GITHUB_REPOSITORY" --json id --jq .id) python3 "$GOV/scripts/po_inbox.py" add --node-id "$node" + # The pre-filter labelled the issue in-progress. Whatever happened to the run (timeout, turn cap, + # usage limit, WIP stop), release the label unless a PR exists. App tokens expire after an hour: mint a new one. + - name: Governance app token (roadmap finish) + if: always() && matrix.task == 'roadmap' && steps.check.outputs.run == 'true' + id: finish-app + uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2 + with: + app-id: ${{ vars.GOVERNANCE_APP_ID }} + private-key: ${{ secrets.GOVERNANCE_APP_PRIVATE_KEY }} + - name: Release in-progress when the run opened no PR + if: always() && matrix.task == 'roadmap' && steps.check.outputs.run == 'true' + env: + GH_TOKEN: ${{ steps.finish-app.outputs.token }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + issue=$(jq -r .issue "$RUNNER_TEMP/housekeeping-vars.json") + python3 "$GOV/scripts/housekeeping.py" roadmap-finish --issue "$issue" --run-url "$RUN_URL" + deterministic: name: deterministic needs: plan diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 03a07df..64645be 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -24,7 +24,7 @@ Branch and release model per project repository: `main` is released, `next` coll | `feat` with its user docs | `next` | CI + Claude review + docs-required + WIP limit, squash auto-merge | | `feat!` / breaking | `next` | only from an issue the owner released after a `po:decision` | -- Issue → triage (small model) → owner applies `po:ready` → po-ready-gate verifies the actor in the issue timeline → nightly roadmap pre-filter picks one issue → implementer PR. +- Issue → triage (small model) → owner applies `po:ready` → po-ready-gate verifies the actor in the issue timeline → nightly roadmap pre-filter picks one issue and labels it `in-progress` → implementer PR. A run that ends without a PR removes `in-progress` and comments the run link; the second such run labels the issue `blocked`. - Push to `main` → release-please (release PR auto-merges; minor/major only after an owner-accepted candidate) → docs to Pages, deploy, smoke test, automatic rollback to the previous tag; plus sync PR `main → next` (merge commit). - Push to `next` with commits `main` lacks (sync merges do not count; without any, an open candidate PR is closed) → RC tag, preview (deployment, TestPyPI or build artifact), screenshots, candidate PR with changes, preview link, test script from the feature PRs → owner approves the current head → merge commit → minor release. - Schedule → pre-filters (`scripts/housekeeping.py`) → Claude only when a tool found something; audit, cleanup and fuzzing need no model. diff --git a/docs/MANUAL-STEPS.md b/docs/MANUAL-STEPS.md index bbe7178..f40634a 100644 --- a/docs/MANUAL-STEPS.md +++ b/docs/MANUAL-STEPS.md @@ -43,7 +43,7 @@ The official Claude GitHub App requests **Workflows: read and write**, so it is ## 6. Routines (Claude Code scheduled tasks) -- [ ] **Digest**: create a scheduled task from `prompts/digest.md`, daily 18:00 Europe/Berlin, small model, GitHub connector, push notifications on. +- [ ] **Digest**: create a scheduled task from `prompts/digest.md`, daily 18:00 Europe/Berlin, small model, GitHub connector, push notifications on. The routine holds a copy: paste the prompt again whenever `prompts/digest.md` changes (2026-11-24: stale `in-progress` issues). - [ ] Optional **immediate push on rollback**: create a routine with an API trigger and store its URL and token as secrets `ALERT_WEBHOOK_URL` / `ALERT_WEBHOOK_TOKEN`. `deploy.yml` posts `{"text": ...}` with a bearer token; verify the request format against the routine's trigger. ## 7. Hardening of this repository diff --git a/prompts/digest.md b/prompts/digest.md index 4131066..26518d7 100644 --- a/prompts/digest.md +++ b/prompts/digest.md @@ -11,6 +11,7 @@ Collect open items: 3. Fork PRs labeled po:review waiting for the owner. 4. PRs or issues labeled blocked, and issues labeled automation:rollback opened in the last 24 hours. 5. Failed governance audits (open issues titled "Governance audit failed"). +6. Issues labeled in-progress for more than 24 hours without an open PR that references them, and no PR merged into next that does (a roadmap run stopped early; removing the label lets the next nightly run retry). If there are no open items, end without a notification. Otherwise send one push notification: a short German summary (max 5 lines, counts per category) and the link to the owner's PO inbox project. Do not include issue text in the notification. diff --git a/scripts/housekeeping.py b/scripts/housekeeping.py index b0e52c8..f169cd4 100644 --- a/scripts/housekeeping.py +++ b/scripts/housekeeping.py @@ -5,6 +5,8 @@ housekeeping.py check run the pre-filter; outputs run, vars, agent, tier housekeeping.py audit-issue --report audit.json open/update the po:decision issue for a failed audit housekeeping.py cleanup delete merged branches, close stale bot PRs + housekeeping.py roadmap-finish --issue N --run-url URL after a roadmap run without a PR: release in-progress, + comment, and add blocked after the second attempt Claude is started only when `check` outputs run=true. Every check is cheap and token-free. """ @@ -329,6 +331,65 @@ def cleanup(repo: str, cfg: dict) -> int: return 0 +# --------------------------------------------------------------------------- roadmap finish (always runs after the model) + +ATTEMPT_MARKER = "" +ROADMAP_ATTEMPTS = 2 + + +def closing_pr(prs: list[dict], number: int) -> int | None: + """Open or merged PR for the issue: closing keyword in title or body, or the implementer's branch claude/-. + Merged counts because closing keywords do not close issues from PRs into next.""" + for pr in prs: + if pr.get("state") != "open" and not pr.get("merged_at"): + continue + refs = {int(n) for n in checks.CLOSES_RE.findall(f"{pr.get('title') or ''}\n{pr.get('body') or ''}")} + if number in refs or ((pr.get("head") or {}).get("ref") or "").startswith(f"claude/{number}-"): + return pr["number"] + return None + + +def failed_attempts(timeline: list[dict], bot: str) -> int: + """Attempt comments by the bot since `blocked` was last removed, so removing it allows new attempts.""" + count = 0 + for event in timeline: + if event.get("event") == "unlabeled" and (event.get("label") or {}).get("name") == "blocked": + count = 0 + elif event.get("event") == "commented" and (event.get("user") or event.get("actor") or {}).get("login") == bot and ATTEMPT_MARKER in (event.get("body") or ""): + count += 1 + return count + + +def roadmap_finish_plan(issue: dict, prs: list[dict], timeline: list[dict], bot: str) -> dict: + if issue.get("state") != "open" or "in-progress" not in labels_of(issue): + return {"release": False, "reason": "issue closed or not in progress"} + pr = closing_pr(prs, issue["number"]) + if pr: + return {"release": False, "reason": f"PR #{pr} exists"} + attempt = failed_attempts(timeline, bot) + 1 + return {"release": True, "attempt": attempt, "block": attempt >= ROADMAP_ATTEMPTS} + + +def roadmap_finish(repo: str, cfg: dict, number: int, run_url: str) -> int: + issue = govlib.gh_api(f"repos/{repo}/issues/{number}") + prs = govlib.gh_api(f"repos/{repo}/pulls?state=all&sort=updated&direction=desc&per_page=100") + timeline = govlib.gh_api(f"repos/{repo}/issues/{number}/timeline?per_page=100", paginate=True) + result = roadmap_finish_plan(issue, prs, timeline, f"{cfg['bot_app_slug']}[bot]") + if not result["release"]: + govlib.summary(f"roadmap #{number}: {result['reason']}; labels unchanged.") + return 0 + body = f"The roadmap run ended without a PR for this issue: {run_url}\n\n" + if result["block"]: + body += f"Attempt {result['attempt']} failed, so automation stops here (`blocked`). Remove `blocked` to allow {ROADMAP_ATTEMPTS} more attempts." + else: + body += "Removed `in-progress`; the next nightly run tries again." + govlib.gh("issue", "comment", str(number), "--repo", repo, "--body", f"{body}\n\n{ATTEMPT_MARKER}") + labels = ["--remove-label", "in-progress"] + (["--add-label", "blocked"] if result["block"] else []) + govlib.gh("issue", "edit", str(number), "--repo", repo, *labels) + govlib.summary(f"roadmap #{number}: no PR; in-progress removed{', blocked' if result['block'] else ''}.") + return 0 + + # --------------------------------------------------------------------------- CLI @@ -346,6 +407,9 @@ def main(argv: list[str] | None = None) -> int: a = sub.add_parser("audit-issue") a.add_argument("--report", required=True) sub.add_parser("cleanup") + f = sub.add_parser("roadmap-finish") + f.add_argument("--issue", required=True, type=int) + f.add_argument("--run-url", required=True) args = parser.parse_args(argv) cfg = govlib.load_config() @@ -374,6 +438,8 @@ def main(argv: list[str] | None = None) -> int: return audit_issue(repo, args.report) if args.cmd == "cleanup": return cleanup(repo, cfg) + if args.cmd == "roadmap-finish": + return roadmap_finish(repo, cfg, args.issue, args.run_url) return 1 diff --git a/tests/test_housekeeping.py b/tests/test_housekeeping.py new file mode 100644 index 0000000..6cdc503 --- /dev/null +++ b/tests/test_housekeeping.py @@ -0,0 +1,77 @@ +import unittest +from unittest import mock + +from helpers import ROOT # noqa: F401 +import housekeeping as hk + +BOT = "nullthrone-governance[bot]" +CFG = {"bot_app_slug": "nullthrone-governance"} + + +def issue(number=12, state="open", labels=("po:ready", "in-progress")): + return {"number": number, "state": state, "labels": [{"name": n} for n in labels]} + + +def attempt(user=BOT): + return {"event": "commented", "user": {"login": user}, "body": f"ended without a PR\n\n{hk.ATTEMPT_MARKER}"} + + +class RoadmapFinishTest(unittest.TestCase): + def test_closing_pr(self): + prs = [ + {"number": 1, "state": "open", "title": "fix: x", "body": "Closes #123", "head": {"ref": "claude/123-x"}}, + {"number": 2, "state": "closed", "merged_at": None, "title": "fix: y", "body": "Fixes #12", "head": {"ref": "y"}}, + ] + self.assertIsNone(hk.closing_pr(prs, 12)) + self.assertEqual(hk.closing_pr(prs + [{"number": 3, "state": "open", "title": "fix: z", "body": "What.\n\nResolves #12", "head": {"ref": "z"}}], 12), 3) + self.assertEqual(hk.closing_pr([{"number": 4, "state": "open", "title": "feat: a", "body": "", "head": {"ref": "claude/12-a"}}], 12), 4) + # A feat PR merged into next does not close the issue, but the work is done. + self.assertEqual(hk.closing_pr([{"number": 5, "state": "closed", "merged_at": "2026-11-24T01:00:00Z", "title": "feat: b", "body": "Closes #12", "head": {"ref": "b"}}], 12), 5) + + def test_failed_attempts(self): + self.assertEqual(hk.failed_attempts([], BOT), 0) + self.assertEqual(hk.failed_attempts([attempt(), attempt()], BOT), 2) + self.assertEqual(hk.failed_attempts([attempt(user="stranger")], BOT), 0) + removed = {"event": "unlabeled", "label": {"name": "blocked"}} + self.assertEqual(hk.failed_attempts([attempt(), attempt(), removed, attempt()], BOT), 1) + + def test_plan(self): + self.assertFalse(hk.roadmap_finish_plan(issue(state="closed"), [], [], BOT)["release"]) + self.assertFalse(hk.roadmap_finish_plan(issue(labels=("po:ready",)), [], [], BOT)["release"]) + pr = {"number": 7, "state": "open", "title": "fix: x", "body": "Closes #12", "head": {"ref": "x"}} + self.assertFalse(hk.roadmap_finish_plan(issue(), [pr], [], BOT)["release"]) + self.assertEqual(hk.roadmap_finish_plan(issue(), [], [], BOT), {"release": True, "attempt": 1, "block": False}) + self.assertEqual(hk.roadmap_finish_plan(issue(), [], [attempt()], BOT), {"release": True, "attempt": 2, "block": True}) + + def run_finish(self, timeline): + calls = [] + + def gh_api(path, **kwargs): + if "/timeline" in path: + return timeline + if "/pulls" in path: + return [] + return issue() + + with mock.patch.object(hk.govlib, "gh_api", gh_api), mock.patch.object(hk.govlib, "gh", lambda *a, **k: calls.append(a)), \ + mock.patch.object(hk.govlib, "summary"): + self.assertEqual(hk.roadmap_finish("o/r", CFG, 12, "https://run/1"), 0) + return calls + + def test_first_failure_releases_and_comments(self): + calls = self.run_finish([]) + comment = next(c for c in calls if c[:2] == ("issue", "comment")) + self.assertIn("https://run/1", comment[-1]) + self.assertIn(hk.ATTEMPT_MARKER, comment[-1]) + edit = next(c for c in calls if c[:2] == ("issue", "edit")) + self.assertIn("in-progress", edit) + self.assertNotIn("blocked", edit) + + def test_second_failure_blocks(self): + edit = next(c for c in self.run_finish([attempt()]) if c[:2] == ("issue", "edit")) + self.assertEqual(edit[edit.index("--remove-label") + 1], "in-progress") + self.assertEqual(edit[edit.index("--add-label") + 1], "blocked") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_repo_consistency.py b/tests/test_repo_consistency.py index 7137083..963ca2a 100644 --- a/tests/test_repo_consistency.py +++ b/tests/test_repo_consistency.py @@ -169,6 +169,20 @@ def test_candidate_counts_without_sync_merges(self): tag = next(s for s in steps if s.get("name") == "Tag release candidate") self.assertEqual(tag["if"], "steps.state.outputs.count != '0'") + def test_roadmap_run_always_releases_in_progress(self): + job = load(WF / "housekeeping.yml")["jobs"]["model-task"] + steps = job["steps"] + claude = next(s for s in steps if str(s.get("uses", "")).startswith("anthropics/claude-code-action")) + self.assertLess(claude["timeout-minutes"], job["timeout-minutes"]) + finish = next(s for s in steps if 'housekeeping.py" roadmap-finish' in s.get("run", "")) + token = next(s for s in steps if s.get("id") == "finish-app") + self.assertGreater(steps.index(finish), steps.index(claude)) + for step in (token, finish): + self.assertIn("always()", step["if"]) + self.assertIn("matrix.task == 'roadmap'", step["if"]) + self.assertEqual(finish["env"]["GH_TOKEN"], "${{ steps.finish-app.outputs.token }}") + self.assertIn("in-progress", (ROOT / "prompts/digest.md").read_text(encoding="utf-8")) + def test_third_party_actions_are_sha_pinned(self): # Scorecard Pinned-Dependencies; the comment keeps the version readable and lets Dependabot update it. for path in sorted(WF.glob("*.yml")) + sorted((ROOT / "callers").glob("*.yml")):