From 743f1213e27c2257b78acb46e7753197bfc8a313 Mon Sep 17 00:00:00 2001 From: "repo-worker-code (lane code-j)" Date: Tue, 10 Nov 2026 19:06:24 -0600 Subject: [PATCH 1/2] =?UTF-8?q?feat(program-tending):=20slice=202=20?= =?UTF-8?q?=E2=80=94=20real=20epics=20+=20roadmaps=20sections=20(#1352)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Epics: child progress from body refs verified live, body-vs-reality mismatches, 7-day silence check-ins, completion proposals, hard-stop + PR guards, 7-day re-tend suppression. Roadmaps: certain drift (forward item, all refs closed) fixed by PR removing the item; ambiguous drift flagged on #1352 with meta/roadmap-drift; Done rows never edited. Dry-run by default; --live posts via the token; 12-action run cap. Workflow: live mode, write permissions, 30m timeout. 22 unit tests pass; live dry-run on developing-today/code planned 9 epic comments + 1 roadmap flag, certain drift verified clean. --- .github/workflows/program-tending.yml | 14 +- scripts/program_tending.py | 609 ++++++++++++++++++++++++-- scripts/tests/test_program_tending.py | 275 +++++++++++- 3 files changed, 848 insertions(+), 50 deletions(-) diff --git a/.github/workflows/program-tending.yml b/.github/workflows/program-tending.yml index 176575b166..35e9fadb66 100644 --- a/.github/workflows/program-tending.yml +++ b/.github/workflows/program-tending.yml @@ -1,6 +1,6 @@ name: program-tending -# program-tending (issue #1352, slice 1/3 scaffold). +# program-tending (issue #1352, slices 1+2 of 3). # # Daily scheduled care for the planning layer across the four fleet # repos (code, opencode, openchamber, nix): epics, roadmaps, projects, @@ -31,13 +31,15 @@ concurrency: cancel-in-progress: true permissions: - contents: read + contents: write + issues: write + pull-requests: write jobs: tend: - name: program-tending scaffold run + name: program-tending run (slices 1+2) runs-on: ubuntu-latest - timeout-minutes: 15 + timeout-minutes: 30 steps: - uses: actions/checkout@v7 - uses: actions/setup-python@v7 @@ -47,7 +49,7 @@ jobs: run: | test -f scripts/tests/test_program_tending.py python3 -m unittest discover -s scripts/tests -p 'test_program_tending.py' -v - - name: Run program-tending scaffold (slice 1 stubs) + - name: Run program-tending (slice 2 sections live) env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: python3 -I scripts/program_tending.py --run + run: python3 -I scripts/program_tending.py --run --live diff --git a/scripts/program_tending.py b/scripts/program_tending.py index ab28b1f4eb..9f505c1ab7 100755 --- a/scripts/program_tending.py +++ b/scripts/program_tending.py @@ -1,14 +1,31 @@ #!/usr/bin/env python3 -"""program-tending scaffold (issue #1352, slice 1/3). +"""program-tending (issue #1352, slices 1+2 of 3). Daily scheduled care for the planning layer across the four fleet repos -(code, opencode, openchamber, nix). This slice is the scaffold only: the -runner entrypoint, per-section stubs that verify and report no-actions, -and the structured run log. Full section implementations (epics + -roadmaps in slice 2, projects + stalled-PRs + loose-ends in slice 3) -land after this scaffold does — see the triage decomposition on #1352. +(code, opencode, openchamber, nix). Slice 1 landed the scaffold: the +runner entrypoint, per-section stubs, and the structured run log. +Slice 2 (this version) implements two sections for real: -Ownership rules (from #1352; enforced by every section stub): +- epics: open `epic` issues get child progress (from the issue refs in + the body, verified against live issue state), body-vs-reality + mismatch counts, a status comment when the epic has been silent 7+ + days (last movement, next step, blockers), and a completion comment + proposing closure when every child is closed. One comment per epic + per run, and an epic already tended within 7 days is skipped. +- roadmaps: ROADMAP.md + planning/roadmaps/*.md in the checked-out + home repo are compared against landed work. Certain drift — a + forward-looking (Now/Next/Later) list item whose referenced issues + are ALL closed — is fixed by PR (the item is removed; per ROADMAP.md + itself, completed work is recorded in GitHub, not in a Done row). + Done rows are never edited. Ambiguous drift (mixed open/closed refs + on a forward item, or a Done-section item whose issue is still open) + is reported on the tracking issue with the `meta/roadmap-drift` + label instead of a guess — the precedent set by the 2026-11-01 run + and tracked in #4412. + +Projects, stalled-PRs and loose-ends remain slice 3 stubs. + +Ownership rules (from #1352; enforced by every section): - never touch held / do-not-merge / user-owned PRs (hold labels only: `held`, `user/owned`, `do-not-merge`, `do-not-auto-edit`); - PRs labeled `user/owned` get a check-in comment at 7 days, never a packet @@ -16,7 +33,13 @@ hold label is workable like any other — Drew ruling 2026-11-07, code#7077); - user/review is reported, never re-decided. -Usage: python3 -I scripts/program_tending.py --run [--repo owner/name ...] +Actions are capped at MAX_ACTIONS_PER_RUN per run (#1352: ~12). The +runner is dry-run by default: it reports the actions it WOULD take. +--live performs them (comments, the drift label, the drift PR) and is +what the scheduled workflow runs. Without a token in the environment +--live degrades to dry-run reporting, because every write would fail. + +Usage: python3 -I scripts/program_tending.py --run [--live] [--repo owner/name ...] """ from __future__ import annotations @@ -25,8 +48,11 @@ import datetime as dt import json import os +import re +import subprocess import sys import urllib.request +from pathlib import Path SECTIONS = ("epics", "roadmaps", "projects", "stalled-prs", "loose-ends") @@ -37,22 +63,48 @@ "developing-today/nix", ) -# Labels the stubs must never act on (read-only signals). +# The repo this runner is checked out in when the workflow runs; the +# roadmap files and the tracking issue live here. +HOME_REPO = "developing-today/code" +TENDING_ISSUE = 1352 +ROADMAP_DRIFT_LABEL = "meta/roadmap-drift" + +# Labels the sections must never act on (read-only signals). HARD_STOPS = ("held", "user/owned", "do-not-merge", "do-not-auto-edit") # The fleet monitor tends issues and queue state; this job reports the # planning layer and never changes monitor or stewardship-cycle behavior. OUT_OF_SCOPE = ("fleet monitor behavior", "stewardship-cycle behavior") +MAX_ACTIONS_PER_RUN = 12 +EPIC_SILENCE_DAYS = 7 +EPIC_MARKER = "" +ROADMAP_MARKER = "" + +_REF_RE = re.compile(r"(? str: return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") -def _gh_api(path: str) -> list: - """GET a GitHub REST collection, following pagination. Read-only.""" - items: list = [] - url = f"https://api.github.com{path}" +def _utcnow_dt() -> dt.datetime: + return dt.datetime.now(dt.timezone.utc) + + +def _parse_ts(value: str) -> dt.datetime | None: + try: + return dt.datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace( + tzinfo=dt.timezone.utc + ) + except (TypeError, ValueError): + return None + + +def _gh_headers() -> dict: headers = {"Accept": "application/vnd.github+json"} # The workflow hands this job a token (#6860): send it when present # so the reads are authenticated; without one, behave exactly as @@ -61,11 +113,28 @@ def _gh_api(path: str) -> list: token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") if token: headers["Authorization"] = f"Bearer {token}" + return headers + + +def _gh_api(path: str) -> list: + """GET a GitHub REST path, following pagination. + + Collection endpoints return their items; a single-object endpoint + returns a one-item list holding the object, so callers have one + shape to handle. + """ + items: list = [] + url = f"https://api.github.com{path}" + headers = _gh_headers() while url: req = urllib.request.Request(url, headers=headers) with urllib.request.urlopen(req, timeout=30) as resp: - items.extend(json.loads(resp.read().decode("utf-8"))) + data = json.loads(resp.read().decode("utf-8")) nxt = resp.headers.get("Link", "") + if isinstance(data, list): + items.extend(data) + else: + items.append(data) url = "" for part in nxt.split(","): if 'rel="next"' in part: @@ -73,33 +142,464 @@ def _gh_api(path: str) -> list: return items +def _gh_write(path: str, payload: dict) -> dict: + """POST a GitHub REST path with a JSON body (comments, labels).""" + req = urllib.request.Request( + f"https://api.github.com{path}", + data=json.dumps(payload).encode("utf-8"), + headers={**_gh_headers(), "Content-Type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(req, timeout=30) as resp: + return json.loads(resp.read().decode("utf-8")) + + def _labels(item: dict) -> set[str]: return {label["name"] for label in item.get("labels", [])} -def stub_epics(repos: list[str]) -> dict: - """Slice 2 owns this section. Slice 1 verifies reachability only.""" - checked = [{"repo": repo, "open_epics": "unverified (slice 2)"} for repo in repos] +def _refs_in(text: str, default_repo: str) -> list[tuple[str, int]]: + """Issue/PR references in a body of text, as (repo, number) pairs.""" + refs: list[tuple[str, int]] = [] + seen: set[tuple[str, int]] = set() + for match in _URL_REF_RE.finditer(text): + key = (match.group(1), int(match.group(2))) + if key not in seen: + seen.add(key) + refs.append(key) + for match in _REF_RE.finditer(text): + key = (default_repo, int(match.group(1))) + if key not in seen: + seen.add(key) + refs.append(key) + return refs + + +def _issue_state(repo: str, number: int, cache: dict) -> dict | None: + """Live issue state via the API, memoised per run. None = unverified.""" + key = (repo, number) + if key not in cache: + try: + found = _gh_api(f"/repos/{repo}/issues/{number}") + cache[key] = found[0] if found else None + except Exception: # noqa: BLE001 - a section reports, never fails + cache[key] = None + return cache[key] + + +# ---------------------------------------------------------------- epics + + +def _epic_children(epic: dict, repo: str, cache: dict) -> list[dict]: + """Child progress for one epic from the refs in its body.""" + body = epic.get("body") or "" + checked_in_body: dict[tuple[str, int], bool] = {} + for line in body.splitlines(): + match = _CHECKBOX_RE.match(line) + if match: + for ref in _refs_in(match.group(2), repo): + checked_in_body[ref] = match.group(1).lower() == "x" + children = [] + for ref_repo, number in _refs_in(body, repo): + if ref_repo == repo and number == epic.get("number"): + continue + state = _issue_state(ref_repo, number, cache) + children.append( + { + "repo": ref_repo, + "number": number, + "state": state.get("state") if state else "unverified", + "title": state.get("title", "") if state else "", + "labels": sorted(_labels(state)) if state else [], + "body_checked": checked_in_body.get((ref_repo, number)), + } + ) + return children + + +def _epic_comment(kind: str, epic: dict, children: list[dict]) -> str: + total = len(children) + closed = [c for c in children if c["state"] == "closed"] + open_children = [c for c in children if c["state"] == "open"] + blocked = [ + c for c in open_children if "status/blocked" in c.get("labels", []) + ] + lines = [ + f"**Program tending — epic {'completion' if kind == 'completion' else 'check-in'}**" + f" (tracking: #{TENDING_ISSUE})", + f"- Child progress: {len(closed)} of {total} children closed" + f" ({len(open_children)} open).", + f"- Last movement: {epic.get('updated_at', 'unknown')}.", + ] + if kind == "completion": + lines.append( + "- All recorded children are closed. Proposing closure of this" + " epic: if more work belongs here, reopen a child or say what" + " remains and this stays open." + ) + else: + if open_children: + nxt = open_children[0] + lines.append( + f"- Next step: #{nxt['number']} — {nxt['title'] or 'untitled'}" + " is the first open child recorded in the body." + ) + else: + lines.append( + "- Next step: no open children are recorded in the body;" + " add the next child or propose closure." + ) + if blocked: + names = ", ".join(f"#{c['number']}" for c in blocked) + lines.append(f"- Blockers: {names} carry `status/blocked`.") + else: + lines.append("- Blockers: none recorded (`status/blocked` on a child).") + lines.append(EPIC_MARKER) + return "\n".join(lines) + + +def section_epics( + repos: list[str], live: bool, now: dt.datetime, budget: int +) -> dict: + checked: list[dict] = [] + actions: list[dict] = [] + cache: dict = {} + for repo in repos: + try: + epics = _gh_api( + f"/repos/{repo}/issues?state=open&labels=epic&per_page=100" + ) + except Exception as exc: # noqa: BLE001 - report, never fail + checked.append({"repo": repo, "open_epics": "unverified", "error": str(exc)}) + continue + for epic in epics: + entry: dict = {"repo": repo, "epic": epic.get("number")} + if "pull_request" in epic: + # The issues endpoint also returns PRs; an epic is an + # issue by definition, never a PR. + entry["disposition"] = "skipped: pull request, not an epic" + checked.append(entry) + continue + if _labels(epic) & set(HARD_STOPS): + entry["disposition"] = "skipped: hard-stop label" + checked.append(entry) + continue + children = _epic_children(epic, repo, cache) + verified = [c for c in children if c["state"] in ("open", "closed")] + entry["children"] = { + "total": len(children), + "open": sum(1 for c in verified if c["state"] == "open"), + "closed": sum(1 for c in verified if c["state"] == "closed"), + "unverified": len(children) - len(verified), + } + entry["body_vs_reality_mismatches"] = sum( + 1 + for c in verified + if c["body_checked"] is not None + and c["body_checked"] != (c["state"] == "closed") + ) + updated = _parse_ts(epic.get("updated_at", "")) + silent_days = (now - updated).days if updated else 0 + entry["silent_days"] = silent_days + kind = None + if verified and all(c["state"] == "closed" for c in verified) \ + and entry["children"]["unverified"] == 0: + kind = "completion" + elif silent_days >= EPIC_SILENCE_DAYS: + kind = "status" + if kind is None: + entry["disposition"] = "verified: no action due" + checked.append(entry) + continue + if kind == "status": + try: + comments = _gh_api( + f"/repos/{repo}/issues/{epic.get('number')}/comments" + "?per_page=100" + ) + except Exception: # noqa: BLE001 - treat as not tended + comments = [] + recently_tended = any( + EPIC_MARKER in (c.get("body") or "") + and (_parse_ts(c.get("created_at", "")) or now) + >= now - dt.timedelta(days=EPIC_SILENCE_DAYS) + for c in comments + ) + if recently_tended: + entry["disposition"] = "verified: tended within 7 days" + checked.append(entry) + continue + if len(actions) >= budget: + entry["disposition"] = "deferred: run action cap reached" + checked.append(entry) + continue + action = { + "kind": f"epic-{kind}-comment", + "repo": repo, + "issue": epic.get("number"), + "live": False, + } + if live: + posted = _gh_write( + f"/repos/{repo}/issues/{epic.get('number')}/comments", + {"body": _epic_comment(kind, epic, children)}, + ) + action["live"] = True + action["comment_id"] = posted.get("id") + actions.append(action) + entry["disposition"] = f"{kind} comment {'posted' if live else 'planned'}" + checked.append(entry) return { "section": "epics", - "status": "no-action", - "detail": "scaffold only: per-epic child-progress checks land in slice 2", + "status": "action" if actions else "no-action", + "detail": ( + "per-epic child progress verified against live issue state; " + f"{EPIC_SILENCE_DAYS}-day silence check-ins and completion " + "proposals, one comment per epic per run" + ), "checked": checked, + "actions": actions, } -def stub_roadmaps(repos: list[str]) -> dict: - """Slice 2 owns this section. Slice 1 verifies reachability only.""" +# ------------------------------------------------------------- roadmaps + + +def _roadmap_files(root: Path) -> list[Path]: + files = [] + top = root / "ROADMAP.md" + if top.is_file(): + files.append(top) + planning = root / "planning" / "roadmaps" + if planning.is_dir(): + files.extend(sorted(planning.glob("*.md"))) + return files + + +def _section_kind(heading: str) -> str: + text = heading.lstrip("#").strip().lower() + if text.startswith("done"): + return "done" + if text.startswith(("now", "next", "later")): + return "forward" + return "neutral" + + +def _roadmap_drift(root: Path) -> tuple[list[dict], list[dict]]: + """Certain and ambiguous drift entries across the roadmap files. + + Certain: a forward-section list item whose refs are all verified + closed. Ambiguous: a forward item with mixed open/closed refs, or + a Done-section item with a verified-open ref. Refs whose state + cannot be verified are neither — the run reports them unverified. + """ + states: dict[tuple[str, int], str] = {} + try: + issues = _gh_api(f"/repos/{HOME_REPO}/issues?state=all&per_page=100") + for issue in issues: + if isinstance(issue, dict) and issue.get("number"): + states[(HOME_REPO, int(issue["number"]))] = issue.get( + "state", "unverified" + ) + except Exception: # noqa: BLE001 - all refs stay unverified + pass + certain: list[dict] = [] + ambiguous: list[dict] = [] + for path in _roadmap_files(root): + kind = "neutral" + for lineno, line in enumerate( + path.read_text().splitlines(), start=1 + ): + if line.startswith("##"): + kind = _section_kind(line) + continue + if kind == "neutral" or not _LIST_ITEM_RE.match(line): + continue + refs = _refs_in(line, HOME_REPO) + if not refs: + continue + resolved = [ + (ref, states.get(ref, "unverified")) for ref in refs + ] + verified = [s for _, s in resolved if s in ("open", "closed")] + if not verified: + continue + entry = { + "file": str(path.relative_to(root)), + "line": lineno, + "text": line.strip()[:200], + "refs": [f"{r[0]}#{r[1]}:{s}" for r, s in resolved], + } + if kind == "forward" and all( + s == "closed" for _, s in resolved + ): + certain.append(entry) + elif kind == "forward" and "closed" in verified \ + and "open" in verified: + entry["reason"] = "forward item mixes closed and open refs" + ambiguous.append(entry) + elif kind == "done" and "open" in verified: + entry["reason"] = "Done-section item references an open issue" + ambiguous.append(entry) + return certain, ambiguous + + +def _remove_lines(path: Path, linenos: set[int]) -> None: + lines = path.read_text().splitlines() + kept = [l for i, l in enumerate(lines, start=1) if i not in linenos] + path.write_text("\n".join(kept) + "\n") + + +def _run_cmd(argv: list[str], cwd: Path) -> None: + subprocess.run(argv, cwd=str(cwd), check=True, capture_output=True, text=True) + + +def _open_drift_pr(root: Path, certain: list[dict], today: str) -> dict: + """Apply the certain-drift removals and open the fix PR via git+gh.""" + by_file: dict[str, set[int]] = {} + for entry in certain: + by_file.setdefault(entry["file"], set()).add(entry["line"]) + for rel, linenos in by_file.items(): + _remove_lines(root / rel, linenos) + branch = f"program-tending/roadmap-drift-{today}" + removed = "\n".join( + f"- `{e['file']}` line {e['line']}: {e['text']} " + f"(refs: {', '.join(e['refs'])})" + for e in certain + ) + body = ( + "Program-tending roadmap drift fix (tracking: " + f"#{TENDING_ISSUE}). Each removed item is a forward-looking " + "roadmap entry whose referenced issues are all closed; per " + "ROADMAP.md, completed work is recorded in GitHub, not in a " + "Done row. No Done rows were edited.\n\n" + removed + "\n" + ) + _run_cmd(["git", "checkout", "-b", branch], root) + _run_cmd(["git", "add", *sorted(by_file)], root) + _run_cmd( + ["git", "commit", "-m", "docs(roadmap): program-tending drift fix — remove landed forward items"], + root, + ) + _run_cmd(["git", "push", "-u", "origin", branch], root) + proc = subprocess.run( + [ + "gh", "pr", "create", "--repo", HOME_REPO, "--base", "main", + "--head", branch, "--title", + "docs(roadmap): program-tending drift fix (landed forward items)", + "--body", body, + ], + cwd=str(root), capture_output=True, text=True, check=True, + ) + return {"kind": "roadmap-drift-pr", "branch": branch, + "pr": proc.stdout.strip().splitlines()[-1] if proc.stdout else "", + "items_removed": len(certain), "live": True} + + +def section_roadmaps( + repos: list[str], live: bool, now: dt.datetime, budget: int, root: Path +) -> dict: + checked: list[dict] = [] + actions: list[dict] = [] + for repo in repos: + if repo != HOME_REPO: + checked.append( + {"repo": repo, + "drift": "not evaluated: roadmap files live in the checked-out home repo"} + ) + if HOME_REPO not in repos: + return { + "section": "roadmaps", "status": "no-action", + "detail": "home repo not in this run's repo set", + "checked": checked, "actions": actions, + } + files = _roadmap_files(root) + if not files: + checked.append({"repo": HOME_REPO, "drift": "no roadmap files found"}) + return { + "section": "roadmaps", "status": "no-action", + "detail": "ROADMAP.md + planning/roadmaps vs landed work", + "checked": checked, "actions": actions, + } + certain, ambiguous = _roadmap_drift(root) + checked.append( + { + "repo": HOME_REPO, + "files": [str(p.relative_to(root)) for p in files], + "certain_drift": certain, + "ambiguous_drift": ambiguous, + } + ) + if certain and len(actions) < budget: + if live: + try: + actions.append( + _open_drift_pr(root, certain, now.strftime("%Y-%m-%d")) + ) + except Exception as exc: # noqa: BLE001 - report, never fail + checked.append( + {"repo": HOME_REPO, "drift_pr_error": str(exc)[:300]} + ) + else: + actions.append( + { + "kind": "roadmap-drift-pr", + "items_removed": len(certain), + "files": sorted({e["file"] for e in certain}), + "live": False, + } + ) + if ambiguous and len(actions) < budget: + action = { + "kind": "roadmap-drift-flag", + "repo": HOME_REPO, + "issue": TENDING_ISSUE, + "items": len(ambiguous), + "live": False, + } + if live: + body = "\n".join( + [ + "**Program tending — ambiguous roadmap drift** " + f"(tracking: #{TENDING_ISSUE}). Not fixed by guess; " + f"`{ROADMAP_DRIFT_LABEL}` applied here per the " + "2026-11-01 precedent:", + ] + + [ + f"- `{e['file']}` line {e['line']}: {e['text']} — " + f"{e['reason']} (refs: {', '.join(e['refs'])})" + for e in ambiguous + ] + + [ROADMAP_MARKER], + ) + posted = _gh_write( + f"/repos/{HOME_REPO}/issues/{TENDING_ISSUE}/comments", + {"body": body}, + ) + _gh_write( + f"/repos/{HOME_REPO}/issues/{TENDING_ISSUE}/labels", + {"labels": [ROADMAP_DRIFT_LABEL]}, + ) + action["live"] = True + action["comment_id"] = posted.get("id") + actions.append(action) return { "section": "roadmaps", - "status": "no-action", - "detail": "scaffold only: ROADMAP.md vs landed-work drift checks land in slice 2", - "checked": [{"repo": repo, "drift": "unverified (slice 2)"} for repo in repos], + "status": "action" if actions else "no-action", + "detail": ( + "ROADMAP.md + planning/roadmaps vs landed work: certain drift " + "fixed by PR (forward rows only, never Done rows); ambiguous " + f"drift flagged on #{TENDING_ISSUE} with `{ROADMAP_DRIFT_LABEL}`" + ), + "checked": checked, + "actions": actions, } +# ------------------------------------------------------- slice 3 stubs + + def stub_projects(repos: list[str]) -> dict: - """Slice 3 owns this section. Slice 1 verifies reachability only.""" + """Slice 3 owns this section. Slice 2 verifies reachability only.""" return { "section": "projects", "status": "no-action", @@ -111,7 +611,7 @@ def stub_projects(repos: list[str]) -> dict: def stub_stalled_prs(repos: list[str]) -> dict: - """Slice 3 owns this section. Slice 1 counts, but never comments.""" + """Slice 3 owns this section. Slice 2 counts, but never comments.""" counts = [] for repo in repos: try: @@ -134,7 +634,7 @@ def stub_stalled_prs(repos: list[str]) -> dict: def stub_loose_ends(repos: list[str]) -> dict: - """Slice 3 owns this section. Slice 1 verifies reachability only.""" + """Slice 3 owns this section. Slice 2 verifies reachability only.""" return { "section": "loose-ends", "status": "no-action", @@ -145,33 +645,62 @@ def stub_loose_ends(repos: list[str]) -> dict: } -def run(repos: list[str]) -> dict: +# ------------------------------------------------------------------ run + + +def _default_roadmap_root() -> Path: + return Path(__file__).resolve().parents[1] + + +def run( + repos: list[str], + live: bool = False, + now: dt.datetime | None = None, + roadmap_root: Path | None = None, +) -> dict: + now = now or _utcnow_dt() + root = roadmap_root or _default_roadmap_root() + # Writes need a token; without one, --live degrades to dry-run + # reporting rather than a run of failed writes. + if live and not (os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")): + live = False + epics = section_epics(repos, live, now, MAX_ACTIONS_PER_RUN) + remaining = MAX_ACTIONS_PER_RUN - len(epics["actions"]) + roadmaps = section_roadmaps(repos, live, now, remaining, root) + sections = [ + epics, + roadmaps, + stub_projects(repos), + stub_stalled_prs(repos), + stub_loose_ends(repos), + ] log = { "job": "program-tending", - "slice": 1, + "slice": 2, "issue": "developing-today/code#1352", "run_at": _utcnow(), + "mode": "live" if live else "dry-run", "repos": repos, "hard_stops": list(HARD_STOPS), "out_of_scope": list(OUT_OF_SCOPE), - "sections": [ - stub_epics(repos), - stub_roadmaps(repos), - stub_projects(repos), - stub_stalled_prs(repos), - stub_loose_ends(repos), - ], + "sections": sections, } - log["actions_taken"] = sum(1 for s in log["sections"] if s["status"] != "no-action") + log["actions_taken"] = sum(len(s.get("actions", [])) for s in sections) return log def main(argv: list[str]) -> int: parser = argparse.ArgumentParser( - description="program-tending scaffold runner (slice 1/3)" + description="program-tending runner (slices 1+2 of 3)" + ) + parser.add_argument( + "--run", action="store_true", help="execute one run and print the log" ) parser.add_argument( - "--run", action="store_true", help="execute one scaffold run and print the log" + "--live", + action="store_true", + help="perform the actions (comments, drift label, drift PR); " + "default is dry-run reporting", ) parser.add_argument( "--repo", action="append", default=[], help="limit to owner/name (repeatable)" @@ -181,7 +710,7 @@ def main(argv: list[str]) -> int: parser.print_help() return 2 repos = args.repo or list(FLEET_REPOS) - print(json.dumps(run(repos), indent=2)) + print(json.dumps(run(repos, live=args.live), indent=2)) return 0 diff --git a/scripts/tests/test_program_tending.py b/scripts/tests/test_program_tending.py index d091ca5520..f7ef503139 100644 --- a/scripts/tests/test_program_tending.py +++ b/scripts/tests/test_program_tending.py @@ -1,8 +1,10 @@ -"""Contract tests for the program-tending scaffold (issue #1352, slice 1/3). +"""Contract tests for program-tending (issue #1352, slices 1+2 of 3). -The scaffold is read-only by design: every section reports a verified -no-action, the runner never fails on a per-repo fetch error, and the -run log always covers all five sections with the hard-stop labels named. +Slice 1 contracts: the scaffold sections report verified no-actions, +the runner never fails on a per-repo fetch error, and the run log +always covers all five sections with the hard-stop labels named. +Slice 2 contracts: epics/roadmaps compute real actions in dry-run +without writing anything, and live mode posts through _gh_write only. """ import io @@ -150,5 +152,270 @@ def test_no_authorization_without_token(self): + +class Slice2EpicsTest(unittest.TestCase): + """Slice 2 epics: child progress, silence check-ins, completion.""" + + NOW = None # set in setUp + + def setUp(self): + import datetime as dt + + self.now = dt.datetime(2026, 11, 11, tzinfo=dt.timezone.utc) + + def fake_api(self, epic, children, comments=None): + def api(path): + if "labels=epic" in path: + return [epic] + if "/comments" in path: + return comments or [] + for number, child in children.items(): + if path.endswith(f"/issues/{number}"): + return [child] + return [] + + return api + + def test_silent_epic_gets_planned_status_comment(self): + epic = { + "number": 100, + "title": "Epic A", + "updated_at": "2026-10-20T00:00:00Z", + "labels": [], + "body": "- [ ] #101 first child\n- [x] #102 done child", + } + children = { + 101: {"number": 101, "state": "open", "title": "First", "labels": []}, + 102: {"number": 102, "state": "closed", "title": "Done", "labels": []}, + } + with mock.patch.object(pt, "_gh_api", self.fake_api(epic, children)): + section = pt.section_epics( + ["developing-today/code"], False, self.now, 12 + ) + self.assertEqual(len(section["actions"]), 1) + self.assertEqual(section["actions"][0]["kind"], "epic-status-comment") + self.assertFalse(section["actions"][0]["live"]) + entry = section["checked"][0] + self.assertEqual(entry["children"], {"total": 2, "open": 1, "closed": 1, "unverified": 0}) + self.assertEqual(entry["body_vs_reality_mismatches"], 0) + self.assertGreaterEqual(entry["silent_days"], 7) + + def test_body_vs_reality_mismatch_counted(self): + epic = { + "number": 100, + "title": "Epic A", + "updated_at": "2026-11-10T00:00:00Z", + "labels": [], + "body": "- [x] #101 claimed done but open", + } + children = { + 101: {"number": 101, "state": "open", "title": "First", "labels": []}, + } + with mock.patch.object(pt, "_gh_api", self.fake_api(epic, children)): + section = pt.section_epics( + ["developing-today/code"], False, self.now, 12 + ) + self.assertEqual(section["checked"][0]["body_vs_reality_mismatches"], 1) + self.assertEqual(section["actions"], []) + + def test_all_children_closed_proposes_completion(self): + epic = { + "number": 100, + "title": "Epic A", + "updated_at": "2026-11-10T00:00:00Z", + "labels": [], + "body": "- [x] #102 done child", + } + children = { + 102: {"number": 102, "state": "closed", "title": "Done", "labels": []}, + } + with mock.patch.object(pt, "_gh_api", self.fake_api(epic, children)): + section = pt.section_epics( + ["developing-today/code"], False, self.now, 12 + ) + self.assertEqual(len(section["actions"]), 1) + self.assertEqual(section["actions"][0]["kind"], "epic-completion-comment") + + def test_hard_stop_epic_skipped(self): + epic = { + "number": 100, + "title": "Epic A", + "updated_at": "2026-10-01T00:00:00Z", + "labels": [{"name": "held"}], + "body": "- [ ] #101 first child", + } + with mock.patch.object(pt, "_gh_api", self.fake_api(epic, {})): + section = pt.section_epics( + ["developing-today/code"], False, self.now, 12 + ) + self.assertEqual(section["actions"], []) + self.assertIn("hard-stop", section["checked"][0]["disposition"]) + + def test_recently_tended_epic_skipped(self): + epic = { + "number": 100, + "title": "Epic A", + "updated_at": "2026-10-20T00:00:00Z", + "labels": [], + "body": "- [ ] #101 first child", + } + children = { + 101: {"number": 101, "state": "open", "title": "First", "labels": []}, + } + comments = [ + { + "body": "check-in ", + "created_at": "2026-11-10T00:00:00Z", + } + ] + with mock.patch.object( + pt, "_gh_api", self.fake_api(epic, children, comments) + ): + section = pt.section_epics( + ["developing-today/code"], False, self.now, 12 + ) + self.assertEqual(section["actions"], []) + self.assertIn("tended within 7 days", section["checked"][0]["disposition"]) + + def test_live_epic_comment_posts(self): + epic = { + "number": 100, + "title": "Epic A", + "updated_at": "2026-10-20T00:00:00Z", + "labels": [], + "body": "- [ ] #101 first child", + } + children = { + 101: {"number": 101, "state": "open", "title": "First", "labels": []}, + } + with mock.patch.object(pt, "_gh_api", self.fake_api(epic, children)): + with mock.patch.object( + pt, "_gh_write", return_value={"id": 555} + ) as write: + section = pt.section_epics( + ["developing-today/code"], True, self.now, 12 + ) + self.assertTrue(section["actions"][0]["live"]) + self.assertEqual(section["actions"][0]["comment_id"], 555) + self.assertIn("/issues/100/comments", write.call_args[0][0]) + + +class Slice2RoadmapsTest(unittest.TestCase): + """Slice 2 roadmaps: certain drift by PR, ambiguous drift flagged.""" + + ROADMAP = ( + "# Roadmap\n" + "## Now\n" + "1. Landed thing (#201).\n" + "2. Mixed thing (#202, #203).\n" + "3. Open thing (#203).\n" + "## Done\n" + "- Finished (#204).\n" + "- Wrongly done (#203).\n" + ) + + def setUp(self): + import datetime as dt + import tempfile + + self.now = dt.datetime(2026, 11, 11, tzinfo=dt.timezone.utc) + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + (self.root / "ROADMAP.md").write_text(self.ROADMAP) + + def tearDown(self): + self.tmp.cleanup() + + def fake_api(self, path): + if "state=all" in path: + return [ + {"number": 201, "state": "closed"}, + {"number": 202, "state": "closed"}, + {"number": 203, "state": "open"}, + {"number": 204, "state": "closed"}, + ] + return [] + + def test_drift_classification(self): + with mock.patch.object(pt, "_gh_api", self.fake_api): + certain, ambiguous = pt._roadmap_drift(self.root) + self.assertEqual(len(certain), 1) + self.assertIn("Landed thing", certain[0]["text"]) + reasons = sorted(e["reason"] for e in ambiguous) + self.assertEqual(len(ambiguous), 2) + self.assertIn("forward item mixes closed and open refs", reasons) + self.assertIn("Done-section item references an open issue", reasons) + + def test_dry_run_plans_without_touching_files(self): + with mock.patch.object(pt, "_gh_api", self.fake_api): + section = pt.section_roadmaps( + ["developing-today/code"], False, self.now, 12, self.root + ) + kinds = sorted(a["kind"] for a in section["actions"]) + self.assertEqual(kinds, ["roadmap-drift-flag", "roadmap-drift-pr"]) + pr_action = next( + a for a in section["actions"] if a["kind"] == "roadmap-drift-pr" + ) + self.assertEqual(pr_action["items_removed"], 1) + self.assertFalse(pr_action["live"]) + self.assertEqual((self.root / "ROADMAP.md").read_text(), self.ROADMAP) + + def test_live_flag_posts_comment_and_label(self): + calls = [] + + def fake_write(path, payload): + calls.append(path) + return {"id": 777} + + with mock.patch.object(pt, "_gh_api", self.fake_api): + with mock.patch.object(pt, "_gh_write", fake_write): + with mock.patch.object( + pt, + "_open_drift_pr", + return_value={"kind": "roadmap-drift-pr", "live": True}, + ): + section = pt.section_roadmaps( + ["developing-today/code"], True, self.now, 12, self.root + ) + flag = next( + a for a in section["actions"] if a["kind"] == "roadmap-drift-flag" + ) + self.assertTrue(flag["live"]) + self.assertEqual(flag["comment_id"], 777) + self.assertTrue(any("/comments" in c for c in calls)) + self.assertTrue(any("/labels" in c for c in calls)) + + def test_remove_lines(self): + target = self.root / "ROADMAP.md" + pt._remove_lines(target, {3}) + self.assertNotIn("Landed thing", target.read_text()) + self.assertIn("Open thing", target.read_text()) + + +class GhApiSingleObjectTest(unittest.TestCase): + """_gh_api returns a one-item list for single-object endpoints.""" + + def test_dict_response_wrapped(self): + class FakeResp: + headers = {} + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def read(self): + return b'{"number": 7, "state": "open"}' + + with mock.patch.object( + pt.urllib.request, "urlopen", return_value=FakeResp() + ): + self.assertEqual( + pt._gh_api("/repos/x/y/issues/7"), + [{"number": 7, "state": "open"}], + ) + + if __name__ == "__main__": unittest.main() From 6f6efa0014a1e8c43d53af17215f9f75968a097e Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 20:18:47 -0600 Subject: [PATCH 2/2] =?UTF-8?q?fix(program-tending):=20disposition=20Codex?= =?UTF-8?q?=20findings=20on=20slice=202=20=E2=80=94=20cross-repo=20token?= =?UTF-8?q?=20+=20write=20isolation,=20completion=20suppression,=20table-r?= =?UTF-8?q?ow=20roadmaps,=20git=20identity,=20link-label=20refs=20(#1352)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/program-tending.yml | 7 +- scripts/program_tending.py | 56 ++++++++-- scripts/tests/test_program_tending.py | 142 ++++++++++++++++++++++++++ 3 files changed, 196 insertions(+), 9 deletions(-) diff --git a/.github/workflows/program-tending.yml b/.github/workflows/program-tending.yml index 35e9fadb66..2caf18bb28 100644 --- a/.github/workflows/program-tending.yml +++ b/.github/workflows/program-tending.yml @@ -51,5 +51,10 @@ jobs: python3 -m unittest discover -s scripts/tests -p 'test_program_tending.py' -v - name: Run program-tending (slice 2 sections live) env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Live writes span all four fleet repos; this repo's + # GITHUB_TOKEN cannot write issues elsewhere (Codex, + # PR #8377). REPO_AUTOMATION_TOKEN is the fleet credential + # other cross-repo workflows here already use; fall back to + # the workflow token when it is not configured. + GH_TOKEN: ${{ secrets.REPO_AUTOMATION_TOKEN || github.token }} run: python3 -I scripts/program_tending.py --run --live diff --git a/scripts/program_tending.py b/scripts/program_tending.py index 9f505c1ab7..6242b0c974 100755 --- a/scripts/program_tending.py +++ b/scripts/program_tending.py @@ -83,8 +83,23 @@ _REF_RE = re.compile(r"(? bool: + """A roadmap entry line: a list item, or a Markdown table row. + + The project roadmaps under planning/roadmaps/ express their + Now/Next/Later entries as table rows, not bullets (Codex, + PR #8377); separator rows (|---|---|) are not entries. + """ + if _LIST_ITEM_RE.match(line): + return True + return bool(_TABLE_ROW_RE.match(line)) and not _TABLE_SEP_RE.match(line) def _utcnow() -> str: @@ -167,7 +182,12 @@ def _refs_in(text: str, default_repo: str) -> list[tuple[str, int]]: if key not in seen: seen.add(key) refs.append(key) - for match in _REF_RE.finditer(text): + # Bare refs are read from the text with Markdown links masked out: + # a link's label ("[#42](https://github.com/other/repo/issues/42)") + # is not a local reference -- the URL pass above already recorded + # the cross-repo ref, and counting the label too would invent a + # phantom local child (Codex, PR #8377). + for match in _REF_RE.finditer(_MD_LINK_RE.sub(" ", text)): key = (default_repo, int(match.group(1))) if key not in seen: seen.add(key) @@ -311,7 +331,10 @@ def section_epics( entry["disposition"] = "verified: no action due" checked.append(entry) continue - if kind == "status": + # The recent-tending suppression applies to both kinds: a + # completion proposal reposted daily would spam the epic + # and burn the shared action budget (Codex, PR #8377). + if kind in ("status", "completion"): try: comments = _gh_api( f"/repos/{repo}/issues/{epic.get('number')}/comments" @@ -340,10 +363,21 @@ def section_epics( "live": False, } if live: - posted = _gh_write( - f"/repos/{repo}/issues/{epic.get('number')}/comments", - {"body": _epic_comment(kind, epic, children)}, - ) + try: + posted = _gh_write( + f"/repos/{repo}/issues/{epic.get('number')}/comments", + {"body": _epic_comment(kind, epic, children)}, + ) + except Exception as exc: # noqa: BLE001 - isolate the failure + # One repo's write failure (e.g. a token without + # access there) must not abort the run before the + # remaining repos and sections are processed + # (Codex, PR #8377). + action["error"] = f"write failed: {exc}" + actions.append(action) + entry["disposition"] = f"{kind} comment failed: {exc}" + checked.append(entry) + continue action["live"] = True action["comment_id"] = posted.get("id") actions.append(action) @@ -413,7 +447,7 @@ def _roadmap_drift(root: Path) -> tuple[list[dict], list[dict]]: if line.startswith("##"): kind = _section_kind(line) continue - if kind == "neutral" or not _LIST_ITEM_RE.match(line): + if kind == "neutral" or not _is_roadmap_item(line): continue refs = _refs_in(line, HOME_REPO) if not refs: @@ -477,7 +511,13 @@ def _open_drift_pr(root: Path, certain: list[dict], today: str) -> dict: _run_cmd(["git", "checkout", "-b", branch], root) _run_cmd(["git", "add", *sorted(by_file)], root) _run_cmd( - ["git", "commit", "-m", "docs(roadmap): program-tending drift fix — remove landed forward items"], + [ + "git", + "-c", "user.name=github-actions[bot]", + "-c", "user.email=41898282+github-actions[bot]@users.noreply.github.com", + "commit", "-m", + "docs(roadmap): program-tending drift fix — remove landed forward items", + ], root, ) _run_cmd(["git", "push", "-u", "origin", branch], root) diff --git a/scripts/tests/test_program_tending.py b/scripts/tests/test_program_tending.py index f7ef503139..0958522bd4 100644 --- a/scripts/tests/test_program_tending.py +++ b/scripts/tests/test_program_tending.py @@ -277,6 +277,78 @@ def test_recently_tended_epic_skipped(self): self.assertEqual(section["actions"], []) self.assertIn("tended within 7 days", section["checked"][0]["disposition"]) + def test_completion_proposal_suppressed_when_recently_tended(self): + epic = { + "number": 100, + "title": "Epic A", + "updated_at": "2026-11-10T00:00:00Z", + "labels": [], + "body": "- [x] #102 done child", + } + children = { + 102: {"number": 102, "state": "closed", "title": "Done", "labels": []}, + } + comments = [ + { + "body": "completion ", + "created_at": "2026-11-10T00:00:00Z", + } + ] + with mock.patch.object( + pt, "_gh_api", self.fake_api(epic, children, comments) + ): + section = pt.section_epics( + ["developing-today/code"], False, self.now, 12 + ) + self.assertEqual(section["actions"], []) + self.assertIn("tended within 7 days", section["checked"][0]["disposition"]) + + def test_write_failure_isolated_per_repo(self): + epics = { + "aaa/one": { + "number": 100, "title": "Epic A", + "updated_at": "2026-10-20T00:00:00Z", "labels": [], + "body": "- [ ] #101 first child", + }, + "bbb/two": { + "number": 200, "title": "Epic B", + "updated_at": "2026-10-20T00:00:00Z", "labels": [], + "body": "- [ ] #201 first child", + }, + } + kids = { + ("aaa/one", 101): {"number": 101, "state": "open", "title": "First", "labels": []}, + ("bbb/two", 201): {"number": 201, "state": "open", "title": "First", "labels": []}, + } + + def api(path): + for repo, epic in epics.items(): + if path.startswith(f"/repos/{repo}/issues?"): + return [epic] + if "/comments" in path: + return [] + for (repo, number), child in kids.items(): + if path == f"/repos/{repo}/issues/{number}": + return [child] + return [] + + def write(path, payload): + if path.startswith("/repos/aaa/one/"): + raise RuntimeError("403 forbidden") + return {"id": 999} + + with mock.patch.object(pt, "_gh_api", api): + with mock.patch.object(pt, "_gh_write", write): + section = pt.section_epics( + ["aaa/one", "bbb/two"], True, self.now, 12 + ) + by_repo = {a["repo"]: a for a in section["actions"]} + self.assertIn("write failed", by_repo["aaa/one"]["error"]) + self.assertEqual(by_repo["bbb/two"]["comment_id"], 999) + dispositions = {c["repo"]: c["disposition"] for c in section["checked"]} + self.assertIn("comment failed", dispositions["aaa/one"]) + self.assertIn("posted", dispositions["bbb/two"]) + def test_live_epic_comment_posts(self): epic = { "number": 100, @@ -385,6 +457,24 @@ def fake_write(path, payload): self.assertTrue(any("/comments" in c for c in calls)) self.assertTrue(any("/labels" in c for c in calls)) + def test_table_row_drift_detected(self): + planning = self.root / "planning" / "roadmaps" + planning.mkdir(parents=True) + (planning / "proj.md").write_text( + "# Project roadmap\n" + "## Now\n" + "| Item | Issue |\n" + "| --- | --- |\n" + "| Table landed thing | #201 |\n" + "| Table open thing | #203 |\n" + ) + with mock.patch.object(pt, "_gh_api", self.fake_api): + certain, _ambiguous = pt._roadmap_drift(self.root) + texts = [e["text"] for e in certain] + self.assertTrue(any("Table landed thing" in x for x in texts), texts) + self.assertFalse(any("Table open thing" in x for x in texts), texts) + self.assertFalse(any(x.strip().startswith("| ---") for x in texts), texts) + def test_remove_lines(self): target = self.root / "ROADMAP.md" pt._remove_lines(target, {3}) @@ -417,5 +507,57 @@ def read(self): ) +class RefsInTest(unittest.TestCase): + """Reference extraction (Codex regression, PR #8377).""" + + def test_markdown_link_label_is_not_a_local_ref(self): + refs = pt._refs_in( + "[#42](https://github.com/other/repo/issues/42) and #43", + "developing-today/code", + ) + self.assertEqual( + refs, [("other/repo", 42), ("developing-today/code", 43)] + ) + + def test_bare_and_url_refs_still_found(self): + refs = pt._refs_in( + "see #7 and https://github.com/a/b/pull/9", + "developing-today/code", + ) + self.assertEqual(refs, [("a/b", 9), ("developing-today/code", 7)]) + + +class DriftPrGitIdentityTest(unittest.TestCase): + """The drift-PR commit carries an explicit git identity (PR #8377).""" + + def test_commit_configures_identity(self): + import tempfile + + calls = [] + + def fake_run_cmd(argv, cwd): + calls.append(argv) + + proc = mock.MagicMock() + proc.stdout = "https://example.invalid/pr/1\n" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "ROADMAP.md").write_text("# Roadmap\nold line\n") + certain = [{ + "file": "ROADMAP.md", "line": 2, "text": "old line", + "refs": ["developing-today/code#1:closed"], + }] + with mock.patch.object(pt, "_run_cmd", fake_run_cmd): + with mock.patch.object( + pt.subprocess, "run", return_value=proc + ): + pt._open_drift_pr(root, certain, "2026-11-11") + commit = next(a for a in calls if "commit" in a) + self.assertIn("user.name=github-actions[bot]", commit) + self.assertTrue( + any(x.startswith("user.email=") for x in commit), commit + ) + + if __name__ == "__main__": unittest.main()