From 3f673431e2c58332167917830243cd9aebc3149a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 03:50:57 +0000 Subject: [PATCH 01/10] fix(build_tools): check_plan_refs --issues reads issues over REST `gh issue view` is GraphQL, which cloud sessions refuse with HTTP 403, so every `--issues` lookup there came back ERROR and the report never showed a closed issue. The lookup is now `gh api -X GET repos/antonsynd/sharpy/issues/N`; the REST state and state_reason are upper-cased to the values render() already filters on (CLOSED, COMPLETED). /implement-plan step 2 runs this report on every light plan, and check_plan_ready.py (next commit) runs it in-process. Measured: plan-460cbf.md --issues went from 4 lookup errors to "4 referenced; 2 CLOSED; 0 lookup errors". Mutation record (test_issue_lookup_uses_rest; break, restore with cp, checked with cmp): - argv back to `gh issue view N --json state,title,stateReason`: broken -> 1 failed / 3 passed; restored -> 0 failed / 4 passed - state not upper-cased: broken -> 1 failed / 3 passed; restored -> 0 failed / 4 passed Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- build_tools/check_plan_refs.py | 17 ++++++---------- build_tools/tests/test_check_plan_refs.py | 24 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/build_tools/check_plan_refs.py b/build_tools/check_plan_refs.py index c516a9f48f..f9b5570b9a 100755 --- a/build_tools/check_plan_refs.py +++ b/build_tools/check_plan_refs.py @@ -13,7 +13,7 @@ * ``SPYnnnn`` diagnostic codes — checked against ``DiagnosticCodes.cs`` (warning: a plan may propose one); * PascalCase **symbols** in backticks, prose only (fenced code is skipped) — checked against the identifier set of ``src/**/*.cs`` (warning: a plan may introduce one); -* ``#NNNN`` **issue** numbers — with ``--issues``, ``gh issue view`` reports state (needs the network). +* ``#NNNN`` **issue** numbers — with ``--issues``, ``gh api -X GET repos/…/issues/N`` reports state (needs the network). Usage:: @@ -57,6 +57,7 @@ r"^[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)+$" ) # ≥2 humps: TypeChecker, MergeFrom FENCE_RE = re.compile(r"```.*?```", re.S) +GH_REPO = "antonsynd/sharpy" SKIP_DIRS = {".git", "bin", "obj", "node_modules", "__pycache__", ".claude"} @@ -183,23 +184,17 @@ def check(plan_text: str, repo: Path, *, with_issues: bool = False) -> dict: if with_issues: for n in numbers: try: + # REST, not `gh issue view`: that is GraphQL, which cloud sessions refuse (HTTP 403) out = subprocess.run( - [ - "gh", - "issue", - "view", - str(n), - "--json", - "state,title,stateReason", - ], + ["gh", "api", "-X", "GET", f"repos/{GH_REPO}/issues/{n}"], capture_output=True, text=True, check=True, ).stdout d = json.loads(out) result["issues"][str(n)] = { - "state": d.get("state"), - "reason": d.get("stateReason"), + "state": (d.get("state") or "").upper() or None, + "reason": (d.get("state_reason") or "").upper() or None, "title": d.get("title"), } except (OSError, subprocess.CalledProcessError, json.JSONDecodeError) as e: diff --git a/build_tools/tests/test_check_plan_refs.py b/build_tools/tests/test_check_plan_refs.py index 3305b5c107..b07ff5b5a5 100644 --- a/build_tools/tests/test_check_plan_refs.py +++ b/build_tools/tests/test_check_plan_refs.py @@ -73,3 +73,27 @@ def test_mutation_control(tmp_path): (repo / "src/missing.cs").write_text("x\n") r = cpr.check(PLAN, repo) assert r["paths"]["missing"] == [] + + +def test_issue_lookup_uses_rest(tmp_path, monkeypatch): + # `gh issue view` is GraphQL, which cloud sessions refuse with HTTP 403: the lookup is REST + import json + import subprocess + + calls = [] + + def fake_run(argv, **kw): + calls.append(argv) + if argv[0] != "gh": # list_files: fall back to the directory walk + raise subprocess.CalledProcessError(1, argv) + body = {"state": "closed", "state_reason": "completed", "title": "t"} + return subprocess.CompletedProcess(argv, 0, stdout=json.dumps(body), stderr="") + + monkeypatch.setattr(cpr.subprocess, "run", fake_run) + r = cpr.check("Issue #1234.", _repo(tmp_path), with_issues=True) + assert r["issues"] == { + "1234": {"state": "CLOSED", "reason": "COMPLETED", "title": "t"} + } + assert ["gh", "api", "-X", "GET", "repos/antonsynd/sharpy/issues/1234"] in calls + text, _ = cpr.render(r, strict=False) + assert "#1234 CLOSED (COMPLETED)" in text From 2e8ef0fa9c73e3bdbf540271e505f0b0a6fe379f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 03:51:19 +0000 Subject: [PATCH 02/10] feat(build_tools): check_plan_ready decides /implement-plan step 2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owner's ruling of 2026-11-20 ("let's go with your recs") moves "a plan is implemented only when its stamps allow it" from prose into a checker. `check_plan_ready.py ` reads the stamp block, the DRAFT marker, the `## Scope` Tier line, the `## Issues to Close` inputs and the override records, and prints READY (exit 0), REFUSE (1), ASK (3) or UNVERIFIED (4) with step 2's messages; 2 stays argparse's usage error. - Tier: light needs an Adequacy-only (or full) stamp, PASS or CONVERGED; absent -> REFUSE; then check_plan_refs --issues runs in-process and a red report (its exit 1) refuses. Full: absent or DRAFT -> ASK. - NEEDS REVISION -> REFUSE at both tiers. - Adequacy CELL on a bug-fix plan: ASK (step 2's cell question, or the converged question with the `### Deferred findings` rows). A bug-fix plan is one whose `## Issues to Close` inputs (minus "stay open" items) carry `bug` or a `lane:*` label, or say ICE/regression in the title, read with `gh api`. - No Adequacy line: before 2026-08-26 (on that day, by whether the stamp's sha contains be99a0c4f) N/A for a feature plan, CELL for a bug-fix plan without a Defect Class section; later -> REFUSE. - Scope: MULTI-GROUP or Generator: MISSING -> ASK; no Scope line before 2026-09-27 (95a734eea) -> ASK to derive it from the groups; later -> REFUSE. - Overrides answer a gate only as `Override (cell|scope): owner YYYY-MM-DD "" — `. The comment is read with `gh api -X GET`: author_association must be OWNER, it must be on the cited issue or PR, and the quoted words must be in its body; otherwise REFUSE. Unreadable -> UNVERIFIED, and under CI=true/1 UNVERIFIED reports as REFUSE. Uncited override prose is listed and answers nothing. `--all` prints one row per docs/process/plans/*.md; `--offline` reads nothing from GitHub. Mutation record (build_tools/tests/test_check_plan_ready.py, 101 tests; each broken, then restored with cp and checked with cmp; every restore -> 0 failed / 101 passed): M01 Tier `light` not read: 11 failed M02 no Tier line read as light: 14 failed M03 full unverified -> READY: 5 failed M04 DRAFT marker ignored: 2 failed M05 light without adequacy pass -> ASK: 2 failed M06 NEEDS REVISION not matched: 4 failed M07 unreadable result line accepted: 1 failed M08 refs exit 1 not red: 1 failed M09 refs not run passes: 1 failed M10 refs run on full plans: 1 failed M11 no label makes a bug-fix plan: 24 failed M12 title ICE/regression ignored: 2 failed M13 "stay open" items counted as inputs: 1 failed M14 no Issues to Close read as no input: 1 failed M15 unreadable labels -> ASK: 3 failed M16 CONVERGED+CELL asked as PASS: 2 failed M17 only the first Adequacy token read: 1 failed M18 Adequacy line without a verdict accepted: 1 failed M19 cutoff comparison reversed: 8 failed M20 cutoff-day sha test reversed: 2 failed M21 Defect Class branch dropped: 1 failed M22 missing Adequacy line after cutoff accepted: 2 failed M23 MULTI-GROUP not matched: 2 failed M24 Generator MISSING not matched: 2 failed M25 pre-Scope-line derivation -> READY: 2 failed M26 missing Scope line after cutoff accepted: 1 failed M27 unreadable Scope line accepted: 1 failed M28 OWNER association not checked: 5 failed M29 cited words not checked: 2 failed M30 comment's issue/PR not checked: 2 failed M31 unreadable override -> READY: 1 failed M32 repository not checked: 1 failed M33 citation not required: 1 failed M34 fenced override text read as a record: 1 failed M35 legacy override text not listed: 1 failed M36 CI does not turn UNVERIFIED into REFUSE: 2 failed M37 CI=1 not read as CI: 1 failed M38 ASK outranks REFUSE: 1 failed M39 full plan with Adequacy-only stamp not noted: 1 failed Absence checks carry positive controls: refs never run on a full plan (test_full_plan_never_runs_refs) beside the light test that asserts the call; overrides not read for an unhit gate (test_overrides_are_read_only_for_a_gate_the_plan_hits) beside the verified-override tests that read them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- build_tools/check_plan_ready.py | 966 +++++++++++++++++++++ build_tools/tests/test_check_plan_ready.py | 744 ++++++++++++++++ 2 files changed, 1710 insertions(+) create mode 100644 build_tools/check_plan_ready.py create mode 100644 build_tools/tests/test_check_plan_ready.py diff --git a/build_tools/check_plan_ready.py b/build_tools/check_plan_ready.py new file mode 100644 index 0000000000..1c9647b93b --- /dev/null +++ b/build_tools/check_plan_ready.py @@ -0,0 +1,966 @@ +#!/usr/bin/env python3 +"""Check: may `/implement-plan` start on this plan? (`/implement-plan` Pre-Implementation step 2.) + +Reads the plan's stamp lines (the leading HTML-comment block `/verify-plan` writes, or the DRAFT +marker `/create-plan` writes), its `## Scope` block's Tier line, its `## Issues to Close` inputs and +its override records, and prints one verdict: + + READY the stamps allow implementation; print the Implementation Summary header values. + REFUSE stop; the message is step 2's. Also: a malformed stamp, a red `check_plan_refs.py` + report on a light plan, or an override record that does not verify. + ASK the owner's word is needed; the printed question is the one to ask, once. + UNVERIFIED a fact the verdict needs lives on GitHub and could not be read (no `gh`, no network): + an override's comment, or an input issue's labels. Never READY. Under `CI=true` (or + `1`, any case) it is reported as REFUSE: on CI an unverifiable override fails. + +Exit codes: READY 0, REFUSE 1, ASK 3, UNVERIFIED 4 (2 is a usage error or an unreadable plan). + +The decision, in step 2's order (every branch has a test in build_tools/tests/test_check_plan_ready.py): + +* Tier: the first `Tier:` in the plan's `## Scope` block (`- **Tier:** light — …`, `**Tier:** full (c)`, + `` `tier: light (…)` ``); no Tier line means `full` (plans created before 2026-10-28). +* light: the stamp must be `Verified by /verify-plan --adequacy (Adequacy-only …)` (a full + nine-dimension stamp is accepted: it grades Dimensions 6 and 7 too). No stamp, or the DRAFT marker, + → REFUSE "This light plan has no adequacy pass. …". NEEDS REVISION → REFUSE. Then + `check_plan_refs.py --issues` runs in-process; a red report (its exit 1: a missing path, a + line past end of file, an R-LW cap) → REFUSE. Lookup errors are a NOTE: they never made that + report red. +* full: no stamp, or the DRAFT marker → ASK "This plan has not been verified. …" (proceed or stop). + NEEDS REVISION → REFUSE. +* Adequacy (both tiers): CLASS or N/A proceed. CELL proceeds unless a plan input is a bug, ICE or + regression issue; then PASS / PASS WITH CORRECTIONS asks step 2's cell question and CONVERGED asks + "converged with CELL …" with the `### Deferred findings` rows. A cited `Override (cell)` record + that verifies answers either. A stamp without an Adequacy line, verified before 2026-08-26 (on + that day: when its sha does not contain ADEQUACY_LINE_COMMIT), is N/A for a feature plan and CELL + for a bug-fix plan unless the plan has a `## Defect Class` section; a later stamp without one is + malformed. +* Scope (both tiers): `MULTI-GROUP`, or `Generator: MISSING`, asks step 2's scope question unless a + cited `Override (scope)` record verifies. A stamp before 2026-09-27 (on that day: SCOPE_LINE_COMMIT) + has no Scope line: the scope is derived from the plan's groups, which is a reading, so it is ASK + with the group ids the title names as evidence. A later stamp without one is malformed. + +Which inputs make a bug-fix plan: the issue numbers on the `## Issues to Close` list items, except +an item that says "stay open". An input is a bug, ICE or regression issue when GitHub gives it the +`bug` label or any `lane:*` label (contract §10: every lane names a defect), or its title says `ICE` +or "regression". No `## Issues to Close` section → ASK (which issues are the inputs?); a section with +no issue number → no bug input. + +Override records. An override answers a gate only when it cites where the owner said it: + + - Override (cell): owner 2026-11-06 "override" — https://github.com/antonsynd/sharpy/issues/2433#issuecomment-1234567890 + - **Override (scope):** owner 2026-09-28 "" — #2423 comment 7050154806 + +one line, outside fenced code, anywhere in the plan (`## Scope` › Override, `## Revision log`, the +`## Implementation Checklist`). The citation is an issue or pull request comment URL +(`#issuecomment-`), a review comment URL (`#discussion_r`), a review URL +(`#pullrequestreview-`), or `# comment `; the repository is REPO. The checker reads +the comment with `gh api -X GET` (or REST with GH_TOKEN / GITHUB_TOKEN) and accepts it only when +its `author_association` is `OWNER`, it belongs to the cited issue or pull request, and the quoted +words appear in its body (compared case-folded, with blockquote markers, emphasis marks, curly +quotes and runs of whitespace normalised). A record that fails either test → REFUSE (a record the +owner did not make must be corrected or deleted). Override text without a citation is listed as a +legacy record and answers nothing. Only the gates the plan hits are verified. + +What this does NOT judge: whether an `OWNER` comment was typed by the owner or posted by an agent +with the owner's token (both read `OWNER`: a relayed comment that quotes the owner verifies the same +way); a tier override or the charter row behind a Tier line; a light plan whose group should have +been full; an output or layout change sharing a gate beyond what the stamp's Scope line (Dimension 9) +records; promotion in flight; the Implementation Summary header itself. + +Usage:: + + python3 build_tools/check_plan_ready.py [--repo ] [--offline] [--json] + + python3 build_tools/check_plan_ready.py --all [--repo ] [--offline] + +`--offline` reads nothing from GitHub (overrides and labels are UNVERIFIED; the light tier's +`check_plan_refs.py` runs without `--issues`). `--all` prints one row per `docs/process/plans/*.md` +and exits 0. Never edits anything. +""" + +from __future__ import annotations + +import argparse +import contextlib +import io +import json +import os +import re +import shutil +import subprocess +import sys +import urllib.error +import urllib.request +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable, Dict, List, Optional, Sequence, Set, Tuple + +try: # imported as build_tools.check_plan_ready (tests) or run as a script + from build_tools import check_plan_refs as cpr +except ImportError: # pragma: no cover - script mode + import check_plan_refs as cpr # type: ignore + +REPO = "antonsynd/sharpy" +REPO_ROOT = Path(__file__).resolve().parent.parent +PLANS_GLOB = "docs/process/plans/*.md" + +READY, REFUSE, ASK, UNVERIFIED = "READY", "REFUSE", "ASK", "UNVERIFIED" +EXIT = {READY: 0, REFUSE: 1, ASK: 3, UNVERIFIED: 4} +PRECEDENCE = (REFUSE, UNVERIFIED, ASK, READY) + +# Dates from step 2's prose; the commits that added each stamp line to /verify-plan decide a stamp +# written on the cutoff day itself (its sha contains the commit → it should carry the line). +ADEQUACY_CUTOFF, ADEQUACY_LINE_COMMIT = "2026-08-26", "be99a0c4f" +SCOPE_CUTOFF, SCOPE_LINE_COMMIT = "2026-09-27", "95a734eea" + +# Step 2's messages, verbatim. +MSG_UNVERIFIED = ( + "This plan has not been verified. Consider running `/verify-plan` first. " + "Ask the owner whether to proceed or stop." +) +MSG_NEEDS_REVISION = ( + "This plan was flagged as needing revision. Please address the issues in the Verification " + "Summary before implementing." +) +MSG_LIGHT_ABSENT = ( + "This light plan has no adequacy pass. Run `/verify-plan {path}` (it runs `--adequacy` for a " + "light plan) first." +) +MSG_CELL = ( + "This plan patches a cell, not its class (see the plan's Adequacy verdict). Add a Defect Class " + "section — contract, matrix, standard cure — and re-run `/verify-plan`, or say `override` to " + "implement it as a cell fix knowingly." +) +MSG_CONVERGED_CELL = ( + "converged with CELL — say `override` to implement, or revise. Show the owner the " + "`### Deferred findings` rows:" +) +MSG_SCOPE = ( + "This plan bundles more than one group (or skips its generator). Split it per the charter, or " + "say `override` to implement it knowingly." +) +MSG_REFS_RED = ( + "`check_plan_refs.py {path} --issues` is red; fix the references until it is clean (the light " + "pass corrects nothing inline, so references may have drifted since)." +) +MSG_RECORD = ( + '\n Record the answer as `Override ({gate}): owner YYYY-MM-DD "" — ` once the ' + "owner has said it on GitHub (the checker verifies the comment)." +) + +STAMP_RE = re.compile(r"^|$)") +ADEQUACY_TOKEN_RE = re.compile(r"(?|$)") +SCOPE_TOKEN_RE = re.compile(r"^\s*(ONE-GROUP|MULTI-GROUP|N/A)\b") +GENERATOR_RE = re.compile(r"\bGenerator:\s*([A-Za-z-]+)") +TIER_RE = re.compile( + r"\btier:[*_]*\s*`?(?:tier:\s*)?(light|full|band)\b", re.IGNORECASE +) +ISSUE_RE = re.compile(r"(? bool: + return environ.get("CI", "").lower() in ("true", "1") + + +# ── Parsing ────────────────────────────────────────────────────────────────────────────────────── + + +@dataclass +class Stamp: + line: int + adequacy_only: bool + date: Optional[str] + sha: Optional[str] + result: Optional[str] # None: no or unreadable result line + result_line: bool + adequacy: Optional[Set[str]] # None: no Adequacy line; empty set: unreadable + scope: Optional[str] # None: no Scope line; "" unreadable + generator: Optional[str] + + +@dataclass +class Override: + line: int + gate: str + date: str + words: str + cite: Optional[Tuple[str, str, int, int]] # (kind, repo, issue/pr number, id) + text: str + + +@dataclass +class Plan: + path: str + text: str + draft: bool + stamp: Optional[Stamp] + tier: str + tier_text: Optional[str] + defect_class: bool + inputs: Optional[List[int]] # None: no `## Issues to Close` section + deferred: List[str] + overrides: List[Override] + legacy_overrides: List[Tuple[int, str]] + title: str + + +def _outside_fences(text: str) -> List[Tuple[int, str]]: + """(1-based line number, line) for each line outside fenced code.""" + out, fence = [], None + for i, line in enumerate(text.split("\n"), 1): + m = cpr.FENCE_LINE_RE.match(line) + if fence is None: + if m and not (m.group(1)[0] == "`" and "`" in m.group(2)): + fence = (m.group(1)[0], len(m.group(1))) + continue + out.append((i, line)) + elif ( + m + and m.group(1)[0] == fence[0] + and len(m.group(1)) >= fence[1] + and not m.group(2).strip() + ): + fence = None + return out + + +def _section(text: str, name: str) -> Optional[str]: + """The text of the first `## ` section (heading suffixes allowed), or None.""" + for heading, sec in cpr.sections(text): + if cpr.heading_name(heading) == name.casefold(): + return sec + return None + + +def _section_start_line(text: str, name: str) -> Optional[int]: + for pos, level, heading in cpr.scan_headings(text)[0]: + if level == 2 and cpr.heading_name(heading) == name.casefold(): + return text.count("\n", 0, pos) + 1 + return None + + +def parse_stamp(header: List[str]) -> Optional[Stamp]: + for i, line in enumerate(header): + m = STAMP_RE.match(line.strip()) + if not m: + continue + date = STAMP_DATE_RE.search(line) + sha = STAMP_SHA_RE.search(line) + result, result_line, adequacy, scope, generator = None, False, None, None, None + for other in header: + s = other.strip() + if RESULT_LINE_RE.match(s): + result_line = True + r = RESULT_RE.match(s) + result = r.group(1) if r else None + a = ADEQUACY_LINE_RE.match(s) + if a and adequacy is None: + adequacy = set(ADEQUACY_TOKEN_RE.findall(a.group(1))) + sc = SCOPE_LINE_RE.match(s) + if sc and scope is None: + t = SCOPE_TOKEN_RE.match(sc.group(1)) + scope = t.group(1) if t else "" + g = GENERATOR_RE.search(sc.group(1)) + generator = g.group(1) if g else None + return Stamp( + line=i + 1, + adequacy_only=bool(m.group("adequacy")), + date=date.group(1) if date else None, + sha=sha.group(1) if sha else None, + result=result, + result_line=result_line, + adequacy=adequacy, + scope=scope, + generator=generator, + ) + return None + + +def parse_inputs(text: str) -> Optional[List[int]]: + sec = _section(text, "Issues to Close") + if sec is None: + return None + nums: List[int] = [] + items: List[str] = [] + for line in sec.split("\n")[1:]: + if LIST_ITEM_RE.match(line) or line.lstrip().startswith("|"): + items.append(line) + elif items and line.strip() and line.startswith((" ", "\t")): + items[-1] += " " + line.strip() # a list item's continuation line + for item in items: + if re.search(r"\bstay(?:s)? open\b", item, re.IGNORECASE): + continue + for n in ISSUE_RE.findall(item): + if int(n) not in nums: + nums.append(int(n)) + return nums + + +def parse_cite(rest: str) -> Optional[Tuple[str, str, int, int]]: + for kind, rx in CITE_PATTERNS: + m = rx.search(rest) + if m: + return kind, m.group(1), int(m.group(2)), int(m.group(3)) + m = CITE_SHORT_RE.search(rest) + if m: + return "issue-comment", REPO, int(m.group(1)), int(m.group(2)) + return None + + +def parse_overrides( + text: str, header_len: int +) -> Tuple[List[Override], List[Tuple[int, str]]]: + cited, legacy = [], [] + record_sections = [] + for name in ("Scope", "Revision log", "Implementation Checklist"): + start = _section_start_line(text, name) + sec = _section(text, name) + if start and sec: + record_sections.append((start, start + sec.count("\n"))) + for n, line in _outside_fences(text): + if n <= header_len: + continue + m = OVERRIDE_RE.match(line) + if m: + cited.append( + Override( + line=n, + gate=m.group(1).lower(), + date=m.group(2), + words=m.group(3), + cite=parse_cite(m.group(4)), + text=line.strip(), + ) + ) + elif ( + LEGACY_OVERRIDE_RE.search(line) + and not NO_OVERRIDE_RE.search(line) + and re.search(r"\bowner\b", line, re.IGNORECASE) + and any(a <= n <= b for a, b in record_sections) + ): + legacy.append((n, line.strip())) + return cited, legacy + + +def parse_deferred(text: str) -> List[str]: + rows, inside = [], False + for _, line in _outside_fences(text): + if re.match(r"^#{2,3}\s", line): + inside = bool(re.match(r"^###\s+Deferred findings\b", line, re.IGNORECASE)) + continue + if inside and LIST_ITEM_RE.match(line): + rows.append(line.strip()) + return rows + + +def parse_plan(path: str, text: str) -> Plan: + lines = text.split("\n") + header: List[str] = [] + for line in lines: + if not cpr.is_stamp_line(line): + break + header.append(line) + scope = _section(text, "Scope") + tier, tier_text = "full", None + if scope is not None: + for _, line in _outside_fences(scope): + m = TIER_RE.search(line) + if m: + tier, tier_text = m.group(1).lower(), line.strip() + break + title = next((l[2:].strip() for l in lines if l.startswith("# ")), "") + overrides, legacy = parse_overrides(text, len(header)) + return Plan( + path=path, + text=text, + draft=bool(lines and DRAFT_RE.match(lines[0].strip())), + stamp=parse_stamp(header), + tier=tier, + tier_text=tier_text, + defect_class=_section(text, "Defect Class") is not None, + inputs=parse_inputs(text), + deferred=parse_deferred(text), + overrides=overrides, + legacy_overrides=legacy, + title=title, + ) + + +# ── Deciding ───────────────────────────────────────────────────────────────────────────────────── + + +@dataclass +class Finding: + verdict: str + message: str + + +@dataclass +class Report: + plan: str + tier: str + stamp: str + findings: List[Finding] = field(default_factory=list) + notes: List[str] = field(default_factory=list) + header: Dict[str, str] = field(default_factory=dict) + refs_output: str = "" + + @property + def verdict(self) -> str: + got = {f.verdict for f in self.findings} + return next((v for v in PRECEDENCE if v in got), READY) + + def add(self, verdict: str, message: str) -> None: + self.findings.append(Finding(verdict, message)) + + +def normalise(s: str) -> str: + s = s.replace("“", '"').replace("”", '"').replace("‘", "'").replace("’", "'") + s = re.sub(r"(?m)^\s*(?:>\s?)+", "", s) # blockquote markers + s = re.sub(r"[*_`]", "", s) + return re.sub(r"\s+", " ", s).strip().casefold() + + +def comment_path(cite: Tuple[str, str, int, int]) -> str: + kind, repo, number, cid = cite + if kind == "issue-comment": + return f"repos/{repo}/issues/comments/{cid}" + if kind == "review-comment": + return f"repos/{repo}/pulls/comments/{cid}" + return f"repos/{repo}/pulls/{number}/reviews/{cid}" + + +def verify_override(o: Override, fetch: Callable) -> Tuple[str, str]: + """(READY | REFUSE | UNVERIFIED, reason) for one cited override record.""" + where = f"line {o.line}" + if o.cite is None: + return ( + REFUSE, + f"{where}: the override cites no owner comment (a comment URL or `#N comment `)", + ) + kind, repo, number, cid = o.cite + if repo.casefold() != REPO.casefold(): + return REFUSE, f"{where}: the cited comment is in {repo}, not {REPO}" + try: + c = fetch(comment_path(o.cite)) + except FetchError as e: + return UNVERIFIED, f"{where}: could not read comment {cid} ({e})" + if not c: + return REFUSE, f"{where}: comment {cid} does not exist" + owner_url = c.get("issue_url") or c.get("pull_request_url") or "" + if kind != "review" and not re.search(rf"/(?:issues|pulls)/{number}$", owner_url): + return ( + REFUSE, + f"{where}: comment {cid} is not on #{number} ({owner_url or 'no parent'})", + ) + assoc = c.get("author_association") + if assoc != "OWNER": + login = (c.get("user") or {}).get("login", "?") + return ( + REFUSE, + f"{where}: comment {cid} is by {login} ({assoc}), not the repository OWNER", + ) + if normalise(o.words) not in normalise(c.get("body") or ""): + return REFUSE, f'{where}: the quoted words "{o.words}" are not in comment {cid}' + return READY, f'{where}: owner comment {cid} holds "{o.words}"' + + +def check_gate( + plan: Plan, + report: Report, + gate: str, + question: str, + fetch: Callable, + extra: Sequence[str] = (), +) -> None: + """The gate needs the owner's word: a verified cited override answers it, else ASK.""" + records = [o for o in plan.overrides if o.gate == gate] + outcomes = [verify_override(o, fetch) for o in records] + for v, reason in outcomes: + if v == READY: + report.notes.append(f"override ({gate}) verified — {reason}") + else: + report.add(v, f"override ({gate}) — {reason}") + if records: + return # every record verified, or each one that did not is its own finding + msg = question + "".join("\n " + e for e in extra) + MSG_RECORD.format(gate=gate) + for n, line in plan.legacy_overrides: + msg += f"\n legacy override text at line {n} (no `Override ({gate}):` record with a citation): {line[:160]}" + report.add(ASK, msg) + + +def is_bug_fix(plan: Plan, fetch: Callable) -> Tuple[Optional[bool], str, str]: + """(True | False | None = undecided, why, the verdict an undecided answer takes).""" + if plan.inputs is None: + return ( + None, + "no `## Issues to Close` section: which issues are this plan's inputs?", + ASK, + ) + if not plan.inputs: + return False, "`## Issues to Close` names no input issue", READY + for n in plan.inputs: + try: + d = fetch(f"repos/{REPO}/issues/{n}") + except FetchError as e: + return None, f"could not read #{n}'s labels ({e})", UNVERIFIED + if d is None: + return None, f"#{n} does not exist: which issues are this plan's inputs?", ASK + labels = [l.get("name", "") for l in d.get("labels", [])] + hit = [l for l in labels if l == "bug" or l.startswith("lane:")] + if hit or DEFECT_TITLE_RE.search(d.get("title") or ""): + why = ", ".join(hit) if hit else "its title" + return True, f"#{n} is a bug/ICE/regression issue ({why})", READY + return ( + False, + "no input carries `bug` or a `lane:*` label: " + + ", ".join(f"#{n}" for n in plan.inputs), + READY, + ) + + +def stamp_predates( + stamp: Stamp, cutoff: str, commit: str, contains: Callable +) -> Optional[bool]: + """Was the stamp written before /verify-plan wrote this line? None: undecidable.""" + if not stamp.date: + return None + if stamp.date != cutoff: + return stamp.date < cutoff + if not stamp.sha: + return None + has_line = contains(commit, stamp.sha) + return None if has_line is None else not has_line + + +def git_contains(repo: Path) -> Callable[[str, str], Optional[bool]]: + def contains(ancestor: str, sha: str) -> Optional[bool]: + try: + r = subprocess.run( + ["git", "-C", str(repo), "merge-base", "--is-ancestor", ancestor, sha], + capture_output=True, + check=False, + ) + except OSError: + return None + return {0: True, 1: False}.get(r.returncode) + + return contains + + +def run_refs(path: str, repo: Path, with_issues: bool) -> Tuple[int, str]: + """`check_plan_refs.py --issues`, in-process: (exit code, its report).""" + argv = [path, "--repo", str(repo)] + (["--issues"] if with_issues else []) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = cpr.main(argv) + return code, buf.getvalue() + + +def describe(stamp: Optional[Stamp], draft: bool) -> str: + if stamp is None: + return "DRAFT marker, no stamp" if draft else "no stamp" + kind = "--adequacy" if stamp.adequacy_only else "full" + adq = ( + "/".join(sorted(stamp.adequacy)) + if stamp.adequacy + else ("none" if stamp.adequacy is None else "?") + ) + return ( + f"{kind} on {stamp.date or '?'} @ {stamp.sha or '?'}: {stamp.result or '?'} · Adequacy {adq}" + f" · Scope {stamp.scope if stamp.scope is not None else 'none'}" + + (f" · Generator {stamp.generator}" if stamp.generator else "") + + (" (and a DRAFT marker)" if draft else "") + ) + + +def decide( + plan: Plan, + *, + fetch: Callable = api_get, + refs: Optional[Callable[[str], Tuple[int, str]]] = None, + contains: Callable[[str, str], Optional[bool]] = lambda a, b: None, + ci: bool = False, +) -> Report: + st = plan.stamp + report = Report(plan=plan.path, tier=plan.tier, stamp=describe(st, plan.draft)) + tier_src = f"`{plan.tier_text[:100]}`" if plan.tier_text else "no Tier line" + report.header["Tier"] = plan.tier + if plan.tier not in ("light", "full"): + report.add( + ASK, + f"tier `{plan.tier}` ({tier_src}) has no /implement-plan path: a band group has no plan", + ) + return _finish(report, ci) + + unverified = st is None or plan.draft + if plan.tier == "light": + if unverified: + report.add(REFUSE, MSG_LIGHT_ABSENT.format(path=plan.path)) + return _finish(report, ci) + elif unverified: + report.add(ASK, MSG_UNVERIFIED) + return _finish(report, ci) + + assert st is not None + if not st.result_line or st.result is None: + report.add( + REFUSE, + f"the stamp (line {st.line}) has no readable `Verification result:` line; re-run `/verify-plan`", + ) + return _finish(report, ci) + if st.result == "NEEDS REVISION": + report.add(REFUSE, MSG_NEEDS_REVISION) + return _finish(report, ci) + if plan.tier == "full" and st.adequacy_only: + if not (plan.tier_text and "promoted at /implement-plan" in plan.tier_text): + report.notes.append( + "a full plan carries an Adequacy-only stamp without a promotion in flight on its Tier line; " + "step 2 accepts any `/verify-plan` stamp at the full tier" + ) + if plan.tier == "light" and not st.adequacy_only: + report.notes.append( + "a light plan with a full /verify-plan stamp: accepted (the full pass grades Dimensions 6 and 7 too)" + ) + + if plan.tier == "light": + if refs is None: + code, out = -1, "" + report.add(UNVERIFIED, "check_plan_refs.py was not run on this light plan") + else: + code, out = refs(plan.path) + report.refs_output = out + if code > 0: + report.add(REFUSE, MSG_REFS_RED.format(path=plan.path)) + errors = re.search(r"; (\d+) lookup errors;", out) + if errors and int(errors.group(1)): + report.notes.append( + f"check_plan_refs: {errors.group(1)} issue lookups failed (issue states unchecked; not red)" + ) + if "unchecked (use --issues)" in out and re.search( + r"; [1-9]\d* unchecked", out + ): + report.notes.append( + "check_plan_refs ran without --issues (offline): issue states unchecked" + ) + + # Adequacy + adequacy = st.adequacy + derived = "" + if adequacy is None: + pre = stamp_predates(st, ADEQUACY_CUTOFF, ADEQUACY_LINE_COMMIT, contains) + if pre is None: + report.add( + ASK, + f"the stamp has no Adequacy line and its date/sha cannot place it against {ADEQUACY_CUTOFF}: was it verified before the Adequacy line existed?", + ) + return _finish(report, ci) + if not pre: + report.add( + REFUSE, + f"the stamp (on {st.date}) has no Adequacy line, which /verify-plan writes since {ADEQUACY_CUTOFF}; re-run `/verify-plan`", + ) + return _finish(report, ci) + bug, why, undecided = is_bug_fix(plan, fetch) + if bug is None: + report.add( + undecided, + f"no Adequacy line (stamped before /verify-plan wrote one, {ADEQUACY_CUTOFF}): " + f"feature plan (N/A) or bug-fix plan (CELL unless it has a Defect Class section)? {why}", + ) + elif not bug: + adequacy, derived = ( + {"N/A"}, + f"N/A (stamped before /verify-plan wrote an Adequacy line, {ADEQUACY_CUTOFF}; feature plan: {why})", + ) + elif plan.defect_class: + adequacy, derived = ( + {"N/A"}, + f"proceed (no Adequacy line; bug-fix plan with a Defect Class section: {why})", + ) + else: + adequacy, derived = ( + {"CELL"}, + f"CELL (no Adequacy line; bug-fix plan without a Defect Class section: {why})", + ) + elif not adequacy: + report.add( + REFUSE, + "the stamp's Adequacy line names none of CLASS, CELL, N/A; re-run `/verify-plan`", + ) + return _finish(report, ci) + if derived: + report.notes.append("Adequacy: " + derived) + + if adequacy is not None: + label = "CELL" if "CELL" in adequacy else "/".join(sorted(adequacy)) + if derived: + label = f"none (stamp before {ADEQUACY_CUTOFF}; read as {label})" + report.header["Adequacy"] = label + ( + " (converged)" if st.result == "CONVERGED" else "" + ) + if "CELL" in adequacy: + bug, why, undecided = ( + (True, derived, READY) + if derived.startswith("CELL") + else is_bug_fix(plan, fetch) + ) + if bug is None: + report.add( + undecided, + f"Adequacy CELL: is any plan input a bug/ICE/regression issue? {why}", + ) + elif bug: + if st.result == "CONVERGED": + rows = plan.deferred or ["(no `### Deferred findings` rows found)"] + check_gate(plan, report, "cell", MSG_CONVERGED_CELL, fetch, rows) + else: + check_gate(plan, report, "cell", MSG_CELL, fetch) + report.header["Adequacy"] = "CELL (override)" + ( + " (converged)" if st.result == "CONVERGED" else "" + ) + else: + report.notes.append( + f"Adequacy CELL on a plan with no bug input: proceeds ({why})" + ) + + # Scope + if st.scope is None: + pre = stamp_predates(st, SCOPE_CUTOFF, SCOPE_LINE_COMMIT, contains) + if pre is None: + report.add( + ASK, + f"the stamp has no Scope line and its date/sha cannot place it against {SCOPE_CUTOFF}: was it stamped before the Scope line existed?", + ) + elif not pre: + report.add( + REFUSE, + f"the stamp (on {st.date}) has no Scope line, which /verify-plan writes since {SCOPE_CUTOFF}; re-run `/verify-plan`", + ) + else: + groups = sorted(set(GROUP_ID_RE.findall(plan.title))) + chores = "chore" in plan.title.casefold() + evidence = ( + f"title names {', '.join(groups) if groups else 'no P-group id'}" + + (" and chores" if chores else "") + ) + if any(o.gate == "scope" for o in plan.overrides): + check_gate(plan, report, "scope", MSG_SCOPE, fetch) + else: + report.add( + ASK, + f"no Scope line (stamped before {SCOPE_CUTOFF}): derive the scope from the plan's groups " + f"({evidence}). One non-chore group on one gate, no output/layout phase sharing a gate and " + f"no generator-required group without its generator → proceed; otherwise: {MSG_SCOPE}", + ) + elif st.scope == "": + report.add( + REFUSE, + "the stamp's Scope line names none of ONE-GROUP, MULTI-GROUP, N/A; re-run `/verify-plan`", + ) + else: + problems = [] + if st.scope == "MULTI-GROUP": + problems.append("Scope: MULTI-GROUP") + if (st.generator or "").upper() == "MISSING": + problems.append("Generator: MISSING") + if problems: + check_gate( + plan, + report, + "scope", + MSG_SCOPE + " (" + "; ".join(problems) + ")", + fetch, + ) + return _finish(report, ci) + + +def _finish(report: Report, ci: bool) -> Report: + if ci: + for f in report.findings: + if f.verdict == UNVERIFIED: + f.verdict = REFUSE + f.message += " — on CI a fact that cannot be verified fails" + return report + + +# ── Output ─────────────────────────────────────────────────────────────────────────────────────── + + +def render(report: Report) -> str: + lines = [f"plan: {report.plan}", f"tier: {report.tier}", f"stamp: {report.stamp}"] + for f in report.findings: + lines.append(f"{f.verdict}: {f.message}") + for n in report.notes: + lines.append(f"NOTE: {n}") + if report.refs_output: + lines.append("check_plan_refs:") + lines += [" " + l for l in report.refs_output.rstrip().split("\n")] + if report.verdict == READY and report.header: + lines.append( + "Implementation Summary header: " + + " · ".join(f"{k}: {v}" for k, v in report.header.items()) + ) + lines.append(f"VERDICT: {report.verdict}") + return "\n".join(lines) + + +def check_path(path: Path, repo: Path, *, offline: bool, ci: bool) -> Report: + text = path.read_text(encoding="utf-8") + try: + shown = str(path.resolve().relative_to(repo)) + except ValueError: + shown = str(path) + plan = parse_plan(shown, text) + return decide( + plan, + fetch=offline_fetch if offline else api_get, + refs=lambda p: run_refs(str(path), repo, with_issues=not offline), + contains=git_contains(repo), + ci=ci, + ) + + +def main(argv: Optional[Sequence[str]] = None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("plan", type=Path, nargs="?") + ap.add_argument( + "--all", action="store_true", help=f"one row per {PLANS_GLOB}; exit 0" + ) + ap.add_argument("--repo", type=Path, default=REPO_ROOT) + ap.add_argument("--offline", action="store_true", help="read nothing from GitHub") + ap.add_argument("--json", action="store_true") + a = ap.parse_args(argv) + repo = a.repo.resolve() + ci = on_ci() + if a.all: + for p in sorted(repo.glob(PLANS_GLOB)): + r = check_path(p, repo, offline=a.offline, ci=ci) + first = r.findings[0].message.split("\n")[0][:110] if r.findings else "" + print(f"{p.name}\t{r.verdict}\t{r.tier}\t{r.stamp}\t{first}") + return 0 + if a.plan is None: + ap.error("a plan path is required unless --all is given") + try: + report = check_path(a.plan, repo, offline=a.offline, ci=ci) + except OSError as e: + print(f"check_plan_ready: cannot read {a.plan}: {e}", file=sys.stderr) + return 2 + if a.json: + print( + json.dumps( + { + "plan": report.plan, + "verdict": report.verdict, + "tier": report.tier, + "stamp": report.stamp, + "findings": [ + {"verdict": f.verdict, "message": f.message} + for f in report.findings + ], + "notes": report.notes, + "header": report.header, + }, + indent=2, + ) + ) + else: + print(render(report)) + return EXIT[report.verdict] + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/build_tools/tests/test_check_plan_ready.py b/build_tools/tests/test_check_plan_ready.py new file mode 100644 index 0000000000..2a705af57d --- /dev/null +++ b/build_tools/tests/test_check_plan_ready.py @@ -0,0 +1,744 @@ +"""check_plan_ready: `/implement-plan` step 2's decision, one test (or more) per branch. + +Every GitHub read goes through a fake `fetch`; `check_plan_refs` through a fake `refs`. +""" + +from pathlib import Path + +import pytest + +from build_tools import check_plan_ready as cpr + +REPO_ROOT = Path(__file__).resolve().parents[2] + +FULL = "" +ADEQ = "" +DRAFT = "" + + +def plan_text( + stamp=FULL, + *, + date="2026-11-01", + result="PASS WITH CORRECTIONS", + adequacy="CLASS", + scope="ONE-GROUP · Generator: existing", + tier=None, + issues="- #100 — the input issue; **close criterion:** A1", + defect_class=True, + extra="", + pre="", +): + head = [pre] if pre else [] + if stamp: + head.append(stamp.format(date=date)) + if result is not None: + head.append(f"") + if adequacy is not None: + head.append(f"") + if scope is not None: + head.append(f"") + body = ["", "# P99 — a plan", "", "## Scope", "", "- **Group:** P99 (chores: none)"] + if tier: + body.append(f"- **Tier:** {tier}") + body += ["- **Override:** none", ""] + if defect_class: + body += ["## Defect Class", "", "- **Violated contract:** x", ""] + if issues is not None: + body += ["## Issues to Close", "", issues, ""] + body += [extra] + return "\n".join(head + body) + "\n" + + +def issue(labels=(), title="an issue"): + return {"title": title, "labels": [{"name": l} for l in labels]} + + +class Fetch: + """path -> response; a FetchError instance is raised; unknown paths raise FetchError.""" + + def __init__(self, table=None): + self.table = dict(table or {}) + self.calls = [] + + def __call__(self, path): + self.calls.append(path) + v = self.table.get(path, cpr.FetchError(f"no fixture for {path}")) + if isinstance(v, Exception): + raise v + return v + + +FEATURE = Fetch({"repos/antonsynd/sharpy/issues/100": issue(["enhancement"])}) +BUG = Fetch({"repos/antonsynd/sharpy/issues/100": issue(["bug"])}) +CLEAN_REFS = lambda p: (0, "RESULT: OK\n") + + +def run(text, fetch=FEATURE, refs=CLEAN_REFS, contains=lambda a, b: None, ci=False): + return cpr.decide( + cpr.parse_plan("docs/process/plans/plan-x.md", text), + fetch=fetch, + refs=refs, + contains=contains, + ci=ci, + ) + + +def verdicts(report): + return [f.verdict for f in report.findings] + + +# ── tier ───────────────────────────────────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize( + "tier, want", + [ + (None, "full"), + ("light — from charter §3.8", "light"), + ("full (c: the seam is under `Semantic/`) — from charter §3.20l", "full"), + ("`tier: light (derived, no §12 letter)`: doors ruled", "light"), + ("full (a, promoted at /implement-plan: D9), from light", "full"), + ], +) +def test_tier_line(tier, want): + assert cpr.parse_plan("p", plan_text(tier=tier)).tier == want + + +def test_tier_inline_after_group_and_outside_scope_ignored(): + text = plan_text().replace( + "- **Group:** P99 (chores: none)", + "- **Group:** P82; no chores. **Tier:** light. **Alone:** no.", + ) + assert cpr.parse_plan("p", text).tier == "light" + later = plan_text( + extra="## Implementation Verification Record\n\n**Tier:** light — Agents 2, 3, 4\n" + ) + assert ( + cpr.parse_plan("p", later).tier == "full" + ) # a Tier outside `## Scope` is not the plan's + + +# ── unverified / DRAFT ─────────────────────────────────────────────────────────────────────────── + + +def test_full_without_stamp_asks(): + r = run(plan_text(stamp=None)) + assert r.verdict == cpr.ASK and cpr.MSG_UNVERIFIED in r.findings[0].message + + +def test_full_draft_marker_asks(): + r = run(plan_text(stamp=None, pre=DRAFT)) + assert r.verdict == cpr.ASK and r.stamp == "DRAFT marker, no stamp" + + +def test_draft_marker_beside_a_stamp_is_still_unverified(): + r = run(plan_text(pre=DRAFT)) + assert r.verdict == cpr.ASK and cpr.MSG_UNVERIFIED in r.findings[0].message + + +@pytest.mark.parametrize("pre", ["", DRAFT]) +def test_light_without_adequacy_pass_refuses(pre): + r = run(plan_text(stamp=None, tier="light", pre=pre)) + assert r.verdict == cpr.REFUSE + assert "This light plan has no adequacy pass" in r.findings[0].message + + +# ── NEEDS REVISION ─────────────────────────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize("stamp, tier", [(FULL, None), (ADEQ, "light")]) +def test_needs_revision_refuses(stamp, tier): + r = run(plan_text(stamp=stamp, tier=tier, result="NEEDS REVISION", adequacy="CELL")) + assert ( + verdicts(r) == [cpr.REFUSE] and r.findings[0].message == cpr.MSG_NEEDS_REVISION + ) + + +def test_unreadable_result_refuses(): + r = run(plan_text(result="MAYBE")) + assert r.verdict == cpr.REFUSE and "Verification result" in r.findings[0].message + assert run(plan_text(result=None)).verdict == cpr.REFUSE + + +# ── PASS / PASS WITH CORRECTIONS × Adequacy ────────────────────────────────────────────────────── + + +@pytest.mark.parametrize("result", ["PASS", "PASS WITH CORRECTIONS"]) +@pytest.mark.parametrize( + "adequacy", ["CLASS", "N/A", "CLASS (Batches 0–6); N/A for Batch 7"] +) +def test_pass_class_or_na_is_ready(result, adequacy): + r = run(plan_text(result=result, adequacy=adequacy), fetch=Fetch()) + assert r.verdict == cpr.READY, r.findings + assert r.header["Tier"] == "full" + + +@pytest.mark.parametrize( + "labels, title", + [ + (["bug"], "x"), + (["lane:ice", "reach:program"], "x"), + (["lane:tooling"], "x"), + ([], "ICE: crash"), + ([], "a regression in emit"), + ], +) +def test_cell_on_bug_fix_plan_asks(labels, title): + fetch = Fetch({"repos/antonsynd/sharpy/issues/100": issue(labels, title)}) + r = run(plan_text(adequacy="CELL"), fetch=fetch) + assert verdicts(r) == [cpr.ASK] + assert cpr.MSG_CELL in r.findings[0].message + assert "Override (cell)" in r.findings[0].message # how to record the answer + + +def test_cell_on_feature_plan_is_ready(): + r = run(plan_text(adequacy="CELL"), fetch=FEATURE) + assert r.verdict == cpr.READY and any("no bug input" in n for n in r.notes) + + +def test_cell_any_token_counts(): + # a mixed Adequacy line holding CELL anywhere is read as CELL (fail-safe) + r = run(plan_text(adequacy="CLASS for D1; CELL for D2"), fetch=BUG) + assert r.verdict == cpr.ASK + + +def test_adequacy_line_without_a_verdict_refuses(): + assert run(plan_text(adequacy="see summary")).verdict == cpr.REFUSE + + +# ── CONVERGED ──────────────────────────────────────────────────────────────────────────────────── + + +def test_converged_class_is_ready_and_header_says_converged(): + r = run(plan_text(result="CONVERGED")) + assert r.verdict == cpr.READY and r.header["Adequacy"] == "CLASS (converged)" + + +def test_converged_cell_on_bug_fix_asks_with_deferred_rows(): + extra = ( + "## Verification Summary\n\n### Deferred findings\n\n" + "1. axis 1 roster ← enumeration — fix: map — proved by roster test\n" + "2. axis 2 ← enumeration — fix: entry — proved by mutation\n\n### Unchecked Claims\n\n- none\n" + ) + r = run(plan_text(result="CONVERGED", adequacy="CELL", extra=extra), fetch=BUG) + assert verdicts(r) == [cpr.ASK] + msg = r.findings[0].message + assert msg.startswith(cpr.MSG_CONVERGED_CELL) + assert "1. axis 1 roster" in msg and "2. axis 2" in msg and "- none" not in msg + + +def test_converged_cell_on_feature_plan_is_ready(): + assert run(plan_text(result="CONVERGED", adequacy="CELL")).verdict == cpr.READY + + +# ── a stamp without an Adequacy line ───────────────────────────────────────────────────────────── + + +def test_pre_adequacy_feature_plan_reads_na(): + r = run(plan_text(date="2026-08-24", adequacy=None, scope=None), fetch=FEATURE) + assert cpr.ASK in verdicts(r) # the Scope derivation; Adequacy itself proceeds + assert all("Adequacy" not in f.message for f in r.findings) + assert any(n.startswith("Adequacy: N/A") for n in r.notes) + + +def test_pre_adequacy_bug_fix_plan_without_defect_class_reads_cell(): + r = run(plan_text(date="2026-08-24", adequacy=None, defect_class=False), fetch=BUG) + assert any(cpr.MSG_CELL in f.message for f in r.findings) + + +def test_pre_adequacy_bug_fix_plan_with_defect_class_proceeds(): + r = run(plan_text(date="2026-08-24", adequacy=None, defect_class=True), fetch=BUG) + assert r.verdict == cpr.READY, r.findings + + +def test_no_input_issue_is_a_feature_plan(): + r = run( + plan_text( + date="2026-08-24", + adequacy=None, + defect_class=False, + issues="None pre-existing.", + ), + fetch=Fetch(), + ) + assert r.verdict == cpr.READY + + +def test_no_issues_section_asks_which_inputs(): + r = run(plan_text(date="2026-08-24", adequacy=None, issues=None), fetch=Fetch()) + assert verdicts(r) == [cpr.ASK] and "which issues" in r.findings[0].message + + +def test_stay_open_items_are_not_inputs(): + issues = ( + "- #100 — closes; criterion A1\n- **Stay open:** #200 (closes with P78), #201" + ) + plan = cpr.parse_plan("p", plan_text(issues=issues)) + assert plan.inputs == [100] + issues2 = "- #300, #301 — **stay open**; each gains a comment\n- #100 — closes" + assert cpr.parse_plan("p", plan_text(issues=issues2)).inputs == [100] + + +def test_adequacy_line_missing_after_cutoff_refuses(): + r = run(plan_text(date="2026-09-01", adequacy=None)) + assert r.verdict == cpr.REFUSE and "no Adequacy line" in r.findings[0].message + + +@pytest.mark.parametrize( + "has_line, want", + [(False, cpr.READY), (True, cpr.REFUSE), (None, cpr.ASK)], +) +def test_adequacy_cutoff_day_is_decided_by_the_stamp_sha(has_line, want): + seen = [] + + def contains(a, b): + seen.append((a, b)) + return has_line + + r = run( + plan_text(date="2026-08-26", adequacy=None, issues="None."), + fetch=Fetch(), + contains=contains, + ) + assert r.verdict == want + assert seen == [(cpr.ADEQUACY_LINE_COMMIT, "abcdef123")] + + +# ── Scope ──────────────────────────────────────────────────────────────────────────────────────── + + +def test_multi_group_asks(): + r = run(plan_text(scope="MULTI-GROUP (override) · Generator: existing")) + assert verdicts(r) == [cpr.ASK] and cpr.MSG_SCOPE in r.findings[0].message + assert "Scope: MULTI-GROUP" in r.findings[0].message + + +def test_generator_missing_asks(): + r = run(plan_text(scope="ONE-GROUP · Generator: MISSING")) + assert verdicts(r) == [cpr.ASK] and "Generator: MISSING" in r.findings[0].message + + +@pytest.mark.parametrize( + "scope", + [ + "ONE-GROUP · Generator: built-first", + "N/A · Generator: not-required", + "ONE-GROUP (ordering override recorded) · Generator: existing", + ], +) +def test_one_group_is_ready(scope): + assert run(plan_text(scope=scope)).verdict == cpr.READY + + +def test_no_scope_line_before_cutoff_asks_for_the_derivation(): + r = run(plan_text(date="2026-09-20", scope=None)) + assert verdicts(r) == [cpr.ASK] and "derive the scope" in r.findings[0].message + assert "P99" in r.findings[0].message # the title's group ids are the evidence + + +def test_no_scope_line_after_cutoff_refuses(): + r = run(plan_text(date="2026-10-01", scope=None)) + assert r.verdict == cpr.REFUSE and "no Scope line" in r.findings[0].message + + +def test_unreadable_scope_line_refuses(): + assert run(plan_text(scope="maybe")).verdict == cpr.REFUSE + + +# ── light tier: the Adequacy-only stamp and check_plan_refs ────────────────────────────────────── + + +@pytest.mark.parametrize("result", ["PASS", "CONVERGED"]) +def test_light_adequacy_stamp_with_clean_refs_is_ready(result): + called = [] + + def refs(path): + called.append(path) + return ( + 0, + "issues: 1 referenced; 0 CLOSED; 0 lookup errors; 0 unchecked (use --issues)\nRESULT: OK\n", + ) + + r = run(plan_text(stamp=ADEQ, tier="light", result=result), refs=refs) + assert r.verdict == cpr.READY and called == ["docs/process/plans/plan-x.md"] + assert r.header["Tier"] == "light" + + +def test_light_red_refs_refuses(): + r = run(plan_text(stamp=ADEQ, tier="light"), refs=lambda p: (1, "RESULT: FAIL\n")) + assert verdicts(r) == [cpr.REFUSE] and "check_plan_refs.py" in r.findings[0].message + + +def test_light_refs_not_run_is_never_ready(): + r = run(plan_text(stamp=ADEQ, tier="light"), refs=None) + assert r.verdict == cpr.UNVERIFIED + + +def test_light_refs_lookup_errors_are_a_note_not_red(): + out = "issues: 2 referenced; 0 CLOSED; 2 lookup errors; 0 unchecked (use --issues)\nRESULT: OK\n" + r = run(plan_text(stamp=ADEQ, tier="light"), refs=lambda p: (0, out)) + assert r.verdict == cpr.READY and any( + "2 issue lookups failed" in n for n in r.notes + ) + + +def test_full_plan_never_runs_refs(): + def refs(path): + raise AssertionError("refs run on a full plan") + + assert run(plan_text(), refs=refs).verdict == cpr.READY + + +def test_light_cell_and_scope_rules_are_the_full_tiers(): + r = run( + plan_text(stamp=ADEQ, tier="light", result="CONVERGED", adequacy="CELL"), + fetch=BUG, + ) + assert r.verdict == cpr.ASK and r.findings[0].message.startswith( + cpr.MSG_CONVERGED_CELL + ) + r = run( + plan_text(stamp=ADEQ, tier="light", scope="MULTI-GROUP · Generator: existing") + ) + assert r.verdict == cpr.ASK and cpr.MSG_SCOPE in r.findings[0].message + + +def test_light_plan_with_full_stamp_is_accepted_with_a_note(): + r = run(plan_text(tier="light")) + assert r.verdict == cpr.READY and any( + "full /verify-plan stamp" in n for n in r.notes + ) + + +def test_full_plan_with_adequacy_only_stamp_notes_it_unless_promoted(): + r = run(plan_text(stamp=ADEQ)) + assert r.verdict == cpr.READY and any("Adequacy-only stamp" in n for n in r.notes) + r = run( + plan_text( + stamp=ADEQ, tier="full (a, promoted at /implement-plan: D9), from light" + ) + ) + assert not any("Adequacy-only stamp" in n for n in r.notes) + + +# ── overrides ──────────────────────────────────────────────────────────────────────────────────── + +CITE = "https://github.com/antonsynd/sharpy/issues/2423#issuecomment-7050154806" +COMMENT_PATH = "repos/antonsynd/sharpy/issues/comments/7050154806" + + +def owner_comment(body, assoc="OWNER", issue=2423): + return { + "author_association": assoc, + "body": body, + "user": {"login": "someone"}, + "issue_url": f"https://api.github.com/repos/antonsynd/sharpy/issues/{issue}", + } + + +def cell_plan(record, result="PASS WITH CORRECTIONS"): + return plan_text( + adequacy="CELL", result=result, extra=f"## Revision log\n\n{record}\n" + ) + + +def fetch_with(comment): + return Fetch( + {"repos/antonsynd/sharpy/issues/100": issue(["bug"]), COMMENT_PATH: comment} + ) + + +GOOD = f'- Override (cell): owner 2026-11-06 "implement it as a cell fix" — {CITE}' + + +def test_verified_owner_override_answers_the_cell_gate(): + r = run( + cell_plan(GOOD), + fetch=fetch_with(owner_comment("> Implement it as a **cell fix**, please")), + ) + assert r.verdict == cpr.READY, r.findings + assert r.header["Adequacy"] == "CELL (override)" + assert any("verified" in n for n in r.notes) + + +def test_verified_override_answers_converged_cell_too(): + r = run( + cell_plan(GOOD, result="CONVERGED"), + fetch=fetch_with(owner_comment("implement it as a cell fix")), + ) + assert ( + r.verdict == cpr.READY and r.header["Adequacy"] == "CELL (override) (converged)" + ) + + +@pytest.mark.parametrize( + "assoc", ["COLLABORATOR", "MEMBER", "CONTRIBUTOR", "NONE", None] +) +def test_override_by_non_owner_refuses(assoc): + r = run( + cell_plan(GOOD), + fetch=fetch_with(owner_comment("implement it as a cell fix", assoc=assoc)), + ) + assert ( + verdicts(r) == [cpr.REFUSE] + and "not the repository OWNER" in r.findings[0].message + ) + + +def test_override_words_absent_from_the_comment_refuses(): + r = run( + cell_plan(GOOD), fetch=fetch_with(owner_comment("revise it, do not override")) + ) + assert verdicts(r) == [cpr.REFUSE] and "not in comment" in r.findings[0].message + + +def test_override_comment_on_another_issue_refuses(): + r = run( + cell_plan(GOOD), + fetch=fetch_with(owner_comment("implement it as a cell fix", issue=9)), + ) + assert verdicts(r) == [cpr.REFUSE] and "is not on #2423" in r.findings[0].message + + +def test_override_comment_missing_refuses(): + r = run(cell_plan(GOOD), fetch=fetch_with(None)) + assert verdicts(r) == [cpr.REFUSE] and "does not exist" in r.findings[0].message + + +def test_override_in_another_repo_refuses(): + rec = '- Override (cell): owner 2026-11-06 "x" — https://github.com/evil/sharpy/issues/1#issuecomment-5' + r = run(cell_plan(rec), fetch=BUG) + assert ( + verdicts(r) == [cpr.REFUSE] and "not antonsynd/sharpy" in r.findings[0].message + ) + + +def test_override_without_citation_refuses(): + r = run(cell_plan('- Override (cell): owner 2026-11-06 "override"'), fetch=BUG) + assert ( + verdicts(r) == [cpr.REFUSE] + and "cites no owner comment" in r.findings[0].message + ) + + +def test_unreadable_override_is_unverified_and_fails_on_ci(): + fetch = Fetch( + { + "repos/antonsynd/sharpy/issues/100": issue(["bug"]), + COMMENT_PATH: cpr.FetchError("offline"), + } + ) + assert run(cell_plan(GOOD), fetch=fetch).verdict == cpr.UNVERIFIED + r = run(cell_plan(GOOD), fetch=fetch, ci=True) + assert r.verdict == cpr.REFUSE and "on CI" in r.findings[0].message + + +def test_legacy_override_prose_is_listed_and_answers_nothing(): + legacy = '- 2026-11-06 @ ee9a007a1 — `/implement-plan` owner override of the `Adequacy: CELL` gate, owner\'s word: "override"' + r = run(cell_plan(legacy), fetch=BUG) + assert verdicts(r) == [cpr.ASK] + assert "legacy override text at line" in r.findings[0].message + + +def test_override_for_the_other_gate_does_not_answer(): + scope_only = GOOD.replace("(cell)", "(scope)") + r = run( + cell_plan(scope_only), + fetch=fetch_with(owner_comment("implement it as a cell fix")), + ) + assert verdicts(r) == [cpr.ASK] + + +def test_scope_override_answers_multi_group(): + rec = f'- **Override (scope):** owner 2026-09-28 "go ahead with both groups" — #2423 comment 7050154806' + text = plan_text(scope="MULTI-GROUP (override) · Generator: existing", extra=rec) + r = run(text, fetch=fetch_with(owner_comment("ok — go ahead with both groups"))) + assert r.verdict == cpr.READY, r.findings + + +def test_override_inside_a_fence_is_not_a_record(): + text = cell_plan(f"```\n{GOOD}\n```") + assert cpr.parse_plan("p", text).overrides == [] + + +def test_overrides_are_read_only_for_a_gate_the_plan_hits(): + fetch = Fetch() # any read would raise + r = run(plan_text(extra=GOOD), fetch=fetch) + assert r.verdict == cpr.READY and fetch.calls == [] + + +@pytest.mark.parametrize( + "text, want", + [ + ( + "https://github.com/antonsynd/sharpy/issues/12#issuecomment-34", + ("issue-comment", "antonsynd/sharpy", 12, 34), + ), + ( + "https://github.com/antonsynd/sharpy/pull/12#issuecomment-34", + ("issue-comment", "antonsynd/sharpy", 12, 34), + ), + ( + "https://github.com/antonsynd/sharpy/pull/12/files#discussion_r34", + ("review-comment", "antonsynd/sharpy", 12, 34), + ), + ( + "https://github.com/antonsynd/sharpy/pull/12#pullrequestreview-34", + ("review", "antonsynd/sharpy", 12, 34), + ), + ( + "(#2423 comment 7050154806)", + ("issue-comment", "antonsynd/sharpy", 2423, 7050154806), + ), + ("no citation", None), + ], +) +def test_citation_forms(text, want): + assert cpr.parse_cite(text) == want + + +def test_comment_paths(): + assert ( + cpr.comment_path(("issue-comment", "a/b", 1, 2)) + == "repos/a/b/issues/comments/2" + ) + assert ( + cpr.comment_path(("review-comment", "a/b", 1, 2)) + == "repos/a/b/pulls/comments/2" + ) + assert cpr.comment_path(("review", "a/b", 1, 2)) == "repos/a/b/pulls/1/reviews/2" + + +def test_review_comment_parent_is_checked(): + rec = '- Override (cell): owner 2026-11-06 "yes" — https://github.com/antonsynd/sharpy/pull/12#discussion_r34' + c = { + "author_association": "OWNER", + "body": "yes", + "pull_request_url": "https://api.github.com/repos/antonsynd/sharpy/pulls/12", + } + fetch = Fetch( + { + "repos/antonsynd/sharpy/issues/100": issue(["bug"]), + "repos/antonsynd/sharpy/pulls/comments/34": c, + } + ) + assert run(cell_plan(rec), fetch=fetch).verdict == cpr.READY + c["pull_request_url"] = c["pull_request_url"].replace("/12", "/13") + assert run(cell_plan(rec), fetch=fetch).verdict == cpr.REFUSE + + +def test_normalise(): + assert ( + cpr.normalise("> nix that\n>\n> **Recommendation:** no fifth pass.") + == "nix that recommendation: no fifth pass." + ) + assert cpr.normalise("“Keep light”") == '"keep light"' + + +# ── labels unreadable ──────────────────────────────────────────────────────────────────────────── + + +def test_unreadable_labels_are_unverified(): + r = run(plan_text(adequacy="CELL"), fetch=Fetch()) + assert ( + r.verdict == cpr.UNVERIFIED and "could not read #100" in r.findings[0].message + ) + assert run(plan_text(adequacy="CELL"), fetch=Fetch(), ci=True).verdict == cpr.REFUSE + + +# ── precedence, CI, exit codes ─────────────────────────────────────────────────────────────────── + + +def test_refuse_outranks_ask(): + r = run( + plan_text(adequacy="CELL", scope="ONE-GROUP · Generator: MISSING", extra=GOOD), + fetch=fetch_with(owner_comment("other")), + ) + assert set(verdicts(r)) == {cpr.REFUSE, cpr.ASK} and r.verdict == cpr.REFUSE + + +@pytest.mark.parametrize( + "value, want", + [ + ("true", True), + ("1", True), + ("TRUE", True), + ("false", False), + ("0", False), + ("", False), + ("yes", False), + ], +) +def test_on_ci(value, want): + assert cpr.on_ci({"CI": value}) is want + + +def test_exit_codes_are_distinct(): + assert sorted(cpr.EXIT.values()) == [0, 1, 3, 4] + assert 2 not in cpr.EXIT.values() # argparse's usage error + + +@pytest.mark.parametrize( + "text, code", + [ + (plan_text(issues="None."), 0), + (plan_text(result="NEEDS REVISION"), 1), + (plan_text(stamp=None), 3), + (plan_text(adequacy="CELL"), 4), # --offline: the input's labels cannot be read + ], +) +def test_main_exit_code(tmp_path, monkeypatch, capsys, text, code): + monkeypatch.delenv("CI", raising=False) + p = tmp_path / "plan-x.md" + p.write_text(text) + assert cpr.main([str(p), "--repo", str(tmp_path), "--offline"]) == code + assert ( + capsys.readouterr() + .out.rstrip() + .endswith( + "VERDICT: " + {0: "READY", 1: "REFUSE", 3: "ASK", 4: "UNVERIFIED"}[code] + ) + ) + + +def test_main_unreadable_plan(tmp_path, capsys): + assert cpr.main([str(tmp_path / "missing.md"), "--offline"]) == 2 + + +# ── the corpus (a control on real plans; offline, no refs) ─────────────────────────────────────── + + +def corpus(): + return sorted((REPO_ROOT / "docs/process/plans").glob("*.md")) + + +def test_corpus_parses_and_known_rows_hold(): + plans = { + p.name: cpr.parse_plan(p.name, p.read_text(encoding="utf-8")) for p in corpus() + } + assert plans, "the corpus is empty: the glob is wrong" + got = { + name: cpr.decide( + plan, + fetch=cpr.offline_fetch, + refs=lambda p: (0, ""), + contains=lambda a, b: None, + ).verdict + for name, plan in plans.items() + } + # one row per verdict the corpus holds, each read by hand against step 2 + if "plan-777361.md" in got: + assert ( + got["plan-777361.md"] == cpr.ASK + ) # DRAFT by the owner's ruling (#2423 comment 7050154806) + if "plan-ed89b6.md" in got: + assert got["plan-ed89b6.md"] == cpr.REFUSE # light, NEEDS REVISION + if "plan-05dd79.md" in got: + assert ( + got["plan-05dd79.md"] == cpr.READY + ) # full, PASS WITH CORRECTIONS, CLASS, ONE-GROUP + if "plan-3eba57.md" in got: + assert ( + got["plan-3eba57.md"] == cpr.UNVERIFIED + ) # CONVERGED + CELL: the inputs' labels are on GitHub From 31ee14c5ad25586b93dc94cdafc40fa8268d692b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 03:52:45 +0000 Subject: [PATCH 03/10] process(skills): implement-plan step 2 runs check_plan_ready Step 2's decision prose (tier, stamp result, Adequacy, Scope, the light tier's check_plan_refs run, the pre-2026-08-26 and pre-2026-09-27 readings) is replaced by one pointer: run `build_tools/check_plan_ready.py ` and act on READY / REFUSE / ASK / UNVERIFIED. What the checker cannot do stays as text: promotion in flight, the CONVERGED deferred rows as Phase 1's first task, the light auditor set, and a new Override bullet that names the record format the checker verifies (an OWNER comment holding the words). The Implementation Summary header is copied from the checker's `Implementation Summary header:` line. Procedure bytes 145065 -> 142472 (-2593); baseline lowered with `scorecard_metrics.py --lower`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- .claude/skills/implement-plan/SKILL.md | 13 +++---------- build_tools/scorecard-baseline.json | 2 +- 2 files changed, 4 insertions(+), 11 deletions(-) diff --git a/.claude/skills/implement-plan/SKILL.md b/.claude/skills/implement-plan/SKILL.md index 4f0a7b460f..2d611b7cd7 100644 --- a/.claude/skills/implement-plan/SKILL.md +++ b/.claude/skills/implement-plan/SKILL.md @@ -27,17 +27,10 @@ Before spawning any agents, perform these checks yourself. Note its **Defect Class** and **Adversarial Review** sections (if any), its **Issues to Close** rows with their close criteria, the **blast-radius** line, the **generated artifacts touched** line, and any spec examples it promises. Record the plan's **base sha** — the commit it was verified against (the `@ ` in the stamp) or the commit before its first implementation commit. Every scope check below uses `..HEAD`, never the branch-vs-`mainline` range (on `dev` that spans every batch since the last release). ### 2. Check the tier and the verification stamp -- Read the `## Scope` block's **Tier** line (contract §12). `tier: light` → the stamp must read `Verified by /verify-plan --adequacy (Adequacy-only …)` with result `PASS` or `CONVERGED` (contract §12 Convergence: the Verification Summary's `### Deferred findings` rows are the first commit, resolved in code; `Adequacy: CELL` on a bug-fix plan still asks the owner once, as below); absent → "This light plan has no adequacy pass. Run `/verify-plan ` (it runs `--adequacy` for a light plan) first." `NEEDS REVISION` → stop, as for a full plan. Then run `python3 build_tools/check_plan_refs.py --issues` (outside the sandbox, `gh`) yourself and **refuse on a red report** until it is clean — the light pass corrects nothing inline, so references may have drifted since. Record the tier in the Implementation Summary header; the final `/verify-implementation` runs its light auditor set. No `Tier` line (plans created before 2026-10-28) → `full`. +- Run `python3 build_tools/check_plan_ready.py ` (outside the sandbox: `gh api`) and act on its verdict; its docstring holds the rules (contract §11, §12). **READY** → go on, and copy the `Implementation Summary header:` line it prints; a light plan's final `/verify-implementation` runs its light auditor set. **REFUSE** → stop with its message. **ASK** → ask the owner its question, once (an unverified plan: proceed or stop). **UNVERIFIED** → re-run where `gh` reaches GitHub; never proceed on it. +- **Override.** When the owner answers ASK with `override`, record it in the plan as `Override (cell|scope): owner YYYY-MM-DD "" — ` and re-run the checker until it reads READY: it accepts the line only when that comment's author is the repository `OWNER` and holds the words. - **Promotion in flight** (§12): if an implementer hits a decision the charter and plan did not rule, or the fix moves into `Semantic/`, `Lowering/` or `CodeGen/` on a light plan — STOP that lane, write the question with lettered options and the door type under `## Implementation Checklist` (added for this when the harness keeps a task board; never into `## Design Decisions`), ask the owner, record the answer there, and replace the `## Scope` Tier line with `tier: full (, promoted at /implement-plan: )`, the one design-section edit allowed after a stamp (contract §12). Never demote. -- For a `full` plan, look for `` line: - - `CLASS` or `N/A` → proceed - - `CELL` and any plan input is a bug/ICE/regression issue → **refuse**: "This plan patches a cell, not its class (see the plan's Adequacy verdict). Add a Defect Class section — contract, matrix, standard cure — and re-run `/verify-plan`, or say `override` to implement it as a cell fix knowingly." Proceed only on an explicit override, and record the override in the plan file. A `CONVERGED` stamp does not replace the override — it only changes what the owner is asked (the deferred rows, above). - - Stamp without an Adequacy line (verified before 2026-08-26) → treat as `N/A` for feature plans, and as `CELL` for bug-fix plans unless the plan already has a Defect Class section. -- Read the `` spans, and whether a comment is still open after it.""" + kept, pos = [], 0 + while pos <= len(line): + if in_comment: + end = line.find("-->", pos) + if end < 0: + return "".join(kept), True + pos, in_comment = end + 3, False + else: + start = line.find("`, one line or several) removed: a record inside a comment is not rendered, so it + is not read. The stamp lines are HTML comments too; parse_stamp reads them from the header.""" + out, fence, in_comment = [], None, False for i, line in enumerate(text.split("\n"), 1): m = cpr.FENCE_LINE_RE.match(line) if fence is None: - if m and not (m.group(1)[0] == "`" and "`" in m.group(2)): + if not in_comment and m and not (m.group(1)[0] == "`" and "`" in m.group(2)): fence = (m.group(1)[0], len(m.group(1))) continue - out.append((i, line)) + visible, in_comment = _strip_comments(line, in_comment) + if visible.strip() or not line.strip(): + out.append((i, visible)) elif ( m and m.group(1)[0] == fence[0] @@ -466,11 +507,16 @@ def parse_plan(path: str, text: str) -> Plan: scope = _section(text, "Scope") tier, tier_text = "full", None if scope is not None: - for _, line in _outside_fences(scope): + scope_lines = _outside_fences(scope) + for _, line in scope_lines: m = TIER_RE.search(line) if m: tier, tier_text = m.group(1).lower(), line.strip() break + else: + mention = next((l for _, l in scope_lines if TIER_WORD_RE.search(l)), None) + if mention is not None: # a Tier the parser cannot read is never taken as `full` + tier, tier_text = "unreadable", mention.strip() title = next((l[2:].strip() for l in lines if l.startswith("# ")), "") overrides, legacy = parse_overrides(text, len(header)) return Plan( @@ -533,28 +579,72 @@ def comment_path(cite: Tuple[str, str, int, int]) -> str: return f"repos/{repo}/pulls/{number}/reviews/{cid}" -def verify_override(o: Override, fetch: Callable) -> Tuple[str, str]: - """(READY | REFUSE | UNVERIFIED, reason) for one cited override record.""" +def plan_id(path: str) -> Optional[str]: + m = PLAN_ID_RE.match(Path(path).name) + return m.group(1) if m else None + + +def linked_to_plan( + plan: Plan, number: int, body: str, fetch: Callable +) -> Tuple[Optional[bool], str]: + """Is the cited issue or pull request this plan's? (True | False | None = unreadable, how).""" + if plan.inputs and number in plan.inputs: + return True, f"#{number} is a plan input" + pid = plan_id(plan.path) + if pid and re.search(rf"(? Tuple[str, str, str]: + """(READY | REFUSE | UNVERIFIED, reason, how the comment was posted) for one cited record. + + The checks are textual: a comment whose words say the opposite ("do not implement it + knowingly" holds "implement it knowingly") verifies. The checker does not judge meaning. + """ where = f"line {o.line}" + words = normalise(o.words) + if len(WORD_RE.findall(words)) < MIN_WORDS or len(words) < MIN_CHARS: + return ( + REFUSE, + f'{where}: malformed record: the quoted words "{o.words}" are under {MIN_WORDS} words or ' + f"{MIN_CHARS} characters; quote the owner's sentence", + "", + ) if o.cite is None: return ( REFUSE, f"{where}: the override cites no owner comment (a comment URL or `#N comment `)", + "", ) kind, repo, number, cid = o.cite if repo.casefold() != REPO.casefold(): - return REFUSE, f"{where}: the cited comment is in {repo}, not {REPO}" + return REFUSE, f"{where}: the cited comment is in {repo}, not {REPO}", "" try: c = fetch(comment_path(o.cite)) except FetchError as e: - return UNVERIFIED, f"{where}: could not read comment {cid} ({e})" + return UNVERIFIED, f"{where}: could not read comment {cid} ({e})", "" if not c: - return REFUSE, f"{where}: comment {cid} does not exist" + return REFUSE, f"{where}: comment {cid} does not exist", "" owner_url = c.get("issue_url") or c.get("pull_request_url") or "" if kind != "review" and not re.search(rf"/(?:issues|pulls)/{number}$", owner_url): return ( REFUSE, f"{where}: comment {cid} is not on #{number} ({owner_url or 'no parent'})", + "", ) assoc = c.get("author_association") if assoc != "OWNER": @@ -562,10 +652,39 @@ def verify_override(o: Override, fetch: Callable) -> Tuple[str, str]: return ( REFUSE, f"{where}: comment {cid} is by {login} ({assoc}), not the repository OWNER", + "", ) - if normalise(o.words) not in normalise(c.get("body") or ""): - return REFUSE, f'{where}: the quoted words "{o.words}" are not in comment {cid}' - return READY, f'{where}: owner comment {cid} holds "{o.words}"' + body = c.get("body") or "" + if words not in normalise(body): + return REFUSE, f'{where}: the quoted words "{o.words}" are not in comment {cid}', "" + posted_at = c.get("created_at") or c.get("submitted_at") or "" + try: + posted, recorded = date.fromisoformat(posted_at[:10]), date.fromisoformat(o.date) + except ValueError: + return REFUSE, f"{where}: comment {cid} or the record has no readable date", "" + if abs((posted - recorded).days) > 1: + return ( + REFUSE, + f"{where}: comment {cid} was posted {posted} (UTC), not within a day of the record's {o.date}", + "", + ) + if plan is not None: + linked, how = linked_to_plan(plan, number, body, fetch) + if linked is None: + return UNVERIFIED, f"{where}: {how}", "" + if not linked: + return ( + REFUSE, + f"{where}: comment {cid} is on #{number}, which is not one of the plan's inputs, " + f"does not name {plan_id(plan.path) or 'the plan'}, and is not the pull request that " + "holds the plan file", + "", + ) + else: + how = "no plan to link" + app = (c.get("performed_via_github_app") or {}).get("slug") + via = f"relayed via app {app}" if app else "no app" + return READY, f'{where}: owner comment {cid} ({via}; {how}) holds "{o.words}"', via def check_gate( @@ -578,10 +697,15 @@ def check_gate( ) -> None: """The gate needs the owner's word: a verified cited override answers it, else ASK.""" records = [o for o in plan.overrides if o.gate == gate] - outcomes = [verify_override(o, fetch) for o in records] - for v, reason in outcomes: + for o in records: + v, reason, via = verify_override(o, fetch, plan) if v == READY: report.notes.append(f"override ({gate}) verified — {reason}") + cid = o.cite[3] if o.cite else "?" + report.header.setdefault("Override", "") + report.header["Override"] += ( + ("; " if report.header["Override"] else "") + f"{gate} @ comment {cid}, {via}" + ) else: report.add(v, f"override ({gate}) — {reason}") if records: @@ -693,6 +817,13 @@ def decide( report = Report(plan=plan.path, tier=plan.tier, stamp=describe(st, plan.draft)) tier_src = f"`{plan.tier_text[:100]}`" if plan.tier_text else "no Tier line" report.header["Tier"] = plan.tier + if plan.tier == "unreadable": + report.add( + REFUSE, + f"the `## Scope` block mentions a tier ({tier_src}) but no `Tier: light|full` parses; " + "write the Tier line as `- **Tier:** — …`", + ) + return _finish(report, ci) if plan.tier not in ("light", "full"): report.add( ASK, @@ -700,6 +831,9 @@ def decide( ) return _finish(report, ci) + if st is not None and st.result == "NEEDS REVISION": + report.add(REFUSE, MSG_NEEDS_REVISION) # wins over a DRAFT marker beside it + return _finish(report, ci) unverified = st is None or plan.draft if plan.tier == "light": if unverified: @@ -725,6 +859,14 @@ def decide( "a full plan carries an Adequacy-only stamp without a promotion in flight on its Tier line; " "step 2 accepts any `/verify-plan` stamp at the full tier" ) + if plan.tier == "light" and st.result not in ("PASS", "CONVERGED"): + report.add( + REFUSE, + f"a light plan's stamp must read PASS or CONVERGED (`/verify-plan --adequacy` writes only " + f"PASS, NEEDS REVISION or CONVERGED); this one reads {st.result}: a malformed stamp, re-run " + "`/verify-plan`", + ) + return _finish(report, ci) if plan.tier == "light" and not st.adequacy_only: report.notes.append( "a light plan with a full /verify-plan stamp: accepted (the full pass grades Dimensions 6 and 7 too)" @@ -856,9 +998,9 @@ def decide( else: report.add( ASK, - f"no Scope line (stamped before {SCOPE_CUTOFF}): derive the scope from the plan's groups " - f"({evidence}). One non-chore group on one gate, no output/layout phase sharing a gate and " - f"no generator-required group without its generator → proceed; otherwise: {MSG_SCOPE}", + f"no Scope line (stamped before {SCOPE_CUTOFF}): the LEAD answers this, not the owner — " + f"derive the scope from the plan's groups ({evidence}). One non-chore group → proceed; " + f"more than one → ask the owner: {MSG_SCOPE}", ) elif st.scope == "": report.add( @@ -967,6 +1109,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int: ], "notes": report.notes, "header": report.header, + "refs_output": report.refs_output, }, indent=2, ) diff --git a/build_tools/tests/test_check_plan_ready.py b/build_tools/tests/test_check_plan_ready.py index c351e09f1e..0ef7d205dd 100644 --- a/build_tools/tests/test_check_plan_ready.py +++ b/build_tools/tests/test_check_plan_ready.py @@ -20,7 +20,7 @@ def plan_text( stamp=FULL, *, date="2026-11-01", - result="PASS WITH CORRECTIONS", + result=None, adequacy="CLASS", scope="ONE-GROUP · Generator: existing", tier=None, @@ -30,9 +30,11 @@ def plan_text( pre="", ): head = [pre] if pre else [] + if result is None: # the result each stamp kind writes by default + result = "PASS" if stamp == ADEQ else "PASS WITH CORRECTIONS" if stamp: head.append(stamp.format(date=date)) - if result is not None: + if result != "-": # "-": no result line head.append(f"") if adequacy is not None: head.append(f"") @@ -158,7 +160,7 @@ def test_needs_revision_refuses(stamp, tier): def test_unreadable_result_refuses(): r = run(plan_text(result="MAYBE")) assert r.verdict == cpr.REFUSE and "Verification result" in r.findings[0].message - assert run(plan_text(result=None)).verdict == cpr.REFUSE + assert run(plan_text(result="-")).verdict == cpr.REFUSE # ── PASS / PASS WITH CORRECTIONS × Adequacy ────────────────────────────────────────────────────── @@ -405,7 +407,7 @@ def test_light_cell_and_scope_rules_are_the_full_tiers(): def test_light_plan_with_full_stamp_is_accepted_with_a_note(): - r = run(plan_text(tier="light")) + r = run(plan_text(tier="light", result="PASS")) assert r.verdict == cpr.READY and any( "full /verify-plan stamp" in n for n in r.notes ) @@ -424,16 +426,20 @@ def test_full_plan_with_adequacy_only_stamp_notes_it_unless_promoted(): # ── overrides ──────────────────────────────────────────────────────────────────────────────────── -CITE = "https://github.com/antonsynd/sharpy/issues/2423#issuecomment-7050154806" +CITE = "https://github.com/antonsynd/sharpy/issues/100#issuecomment-7050154806" COMMENT_PATH = "repos/antonsynd/sharpy/issues/comments/7050154806" -def owner_comment(body, assoc="OWNER", issue=2423): +def owner_comment( + body, assoc="OWNER", issue=100, created="2026-11-06T15:00:00Z", app=None +): return { "author_association": assoc, "body": body, "user": {"login": "someone"}, "issue_url": f"https://api.github.com/repos/antonsynd/sharpy/issues/{issue}", + "created_at": created, + "performed_via_github_app": {"slug": app} if app else None, } @@ -498,7 +504,7 @@ def test_override_comment_on_another_issue_refuses(): cell_plan(GOOD), fetch=fetch_with(owner_comment("implement it as a cell fix", issue=9)), ) - assert verdicts(r) == [cpr.REFUSE] and "is not on #2423" in r.findings[0].message + assert verdicts(r) == [cpr.REFUSE] and "is not on #100" in r.findings[0].message def test_override_comment_missing_refuses(): @@ -507,7 +513,7 @@ def test_override_comment_missing_refuses(): def test_override_in_another_repo_refuses(): - rec = '- Override (cell): owner 2026-11-06 "x" — https://github.com/evil/sharpy/issues/1#issuecomment-5' + rec = '- Override (cell): owner 2026-11-06 "implement it knowingly" — https://github.com/evil/sharpy/issues/1#issuecomment-5' r = run(cell_plan(rec), fetch=BUG) assert ( verdicts(r) == [cpr.REFUSE] and "not antonsynd/sharpy" in r.findings[0].message @@ -515,7 +521,9 @@ def test_override_in_another_repo_refuses(): def test_override_without_citation_refuses(): - r = run(cell_plan('- Override (cell): owner 2026-11-06 "override"'), fetch=BUG) + r = run( + cell_plan('- Override (cell): owner 2026-11-06 "implement it knowingly"'), fetch=BUG + ) assert ( verdicts(r) == [cpr.REFUSE] and "cites no owner comment" in r.findings[0].message @@ -551,9 +559,10 @@ def test_override_for_the_other_gate_does_not_answer(): def test_scope_override_answers_multi_group(): - rec = f'- **Override (scope):** owner 2026-09-28 "go ahead with both groups" — #2423 comment 7050154806' + rec = f'- **Override (scope):** owner 2026-09-28 "go ahead with both groups" — #100 comment 7050154806' text = plan_text(scope="MULTI-GROUP (override) · Generator: existing", extra=rec) - r = run(text, fetch=fetch_with(owner_comment("ok — go ahead with both groups"))) + comment = owner_comment("ok — go ahead with both groups", created="2026-09-28T23:59:00Z") + r = run(text, fetch=fetch_with(comment)) assert r.verdict == cpr.READY, r.findings @@ -611,16 +620,22 @@ def test_comment_paths(): def test_review_comment_parent_is_checked(): - rec = '- Override (cell): owner 2026-11-06 "yes" — https://github.com/antonsynd/sharpy/pull/12#discussion_r34' + rec = '- Override (cell): owner 2026-11-06 "yes, implement it knowingly" — https://github.com/antonsynd/sharpy/pull/12#discussion_r34' c = { "author_association": "OWNER", - "body": "yes", + "body": "yes, implement it knowingly", + "created_at": "2026-11-06T10:00:00Z", "pull_request_url": "https://api.github.com/repos/antonsynd/sharpy/pulls/12", } fetch = Fetch( { "repos/antonsynd/sharpy/issues/100": issue(["bug"]), "repos/antonsynd/sharpy/pulls/comments/34": c, + # #12 is the pull request that holds the plan file (not an input, not named in the body) + "repos/antonsynd/sharpy/pulls/12/files?per_page=100&page=1": [ + {"filename": "src/x.cs"}, + {"filename": "docs/process/plans/plan-x.md"}, + ], } ) assert run(cell_plan(rec), fetch=fetch).verdict == cpr.READY @@ -776,3 +791,176 @@ def test_script_runs_the_sibling_check_plan_refs(tmp_path): assert "decoy" not in proc.stdout + proc.stderr assert "check_plan_refs:" in proc.stdout # the sibling ran and printed its report assert proc.returncode in (0, 1), proc.stdout + proc.stderr + + +# ── fix round 1: trivial words, date, link, app, malformed light stamp, comments, tiers ───────── + + +@pytest.mark.parametrize("words", ["**", "`", " ", "o", "ok", "override", "go ahead", "a b c"]) +def test_trivial_override_words_are_a_malformed_record(words): + fetch = fetch_with(owner_comment(f"{words} anything at all, a long comment")) + rec = f'- Override (cell): owner 2026-11-06 "{words}" — {CITE}' + r = run(cell_plan(rec), fetch=fetch) + assert verdicts(r) == [cpr.REFUSE] and "malformed record" in r.findings[0].message + assert COMMENT_PATH not in fetch.calls # refused before any read + + +def test_single_negated_word_fails_and_a_negated_phrase_is_not_judged(): + # "override" inside "do not override" fails on length alone + rec = f'- Override (cell): owner 2026-11-06 "override" — {CITE}' + r = run(cell_plan(rec), fetch=fetch_with(owner_comment("do not override"))) + assert r.verdict == cpr.REFUSE + # a 3-word phrase inside its negation verifies: the checker does not judge meaning (documented) + rec = f'- Override (cell): owner 2026-11-06 "implement it knowingly" — {CITE}' + r = run(cell_plan(rec), fetch=fetch_with(owner_comment("do not implement it knowingly"))) + assert r.verdict == cpr.READY + assert "does not judge meaning" in cpr.verify_override.__doc__ + assert "does not judge meaning" in cpr.__doc__ + + +@pytest.mark.parametrize( + "created, want", + [ + ("2026-11-05T00:00:01Z", cpr.READY), + ("2026-11-06T23:59:59Z", cpr.READY), + ("2026-11-07T23:59:59Z", cpr.READY), + ("2026-11-04T23:59:59Z", cpr.REFUSE), + ("2026-11-08T00:00:00Z", cpr.REFUSE), + ("", cpr.REFUSE), + ], +) +def test_override_comment_date_is_the_record_date_within_a_day(created, want): + comment = owner_comment("implement it as a cell fix", created=created) + r = run(cell_plan(GOOD), fetch=fetch_with(comment)) + assert r.verdict == want, r.findings + + +def _unlinked(body, files): + rec = '- Override (cell): owner 2026-11-06 "implement it as a cell fix" — #2487 comment 7055038414' + comment = owner_comment(body, issue=2487) + table = { + "repos/antonsynd/sharpy/issues/100": issue(["bug"]), + "repos/antonsynd/sharpy/issues/comments/7055038414": comment, + "repos/antonsynd/sharpy/pulls/2487/files?per_page=100&page=1": files, + } + return run(cell_plan(rec), fetch=Fetch(table)) + + +def test_override_on_an_issue_unrelated_to_the_plan_refuses(): + r = _unlinked("implement it as a cell fix", None) # #2487: no input, no plan id, no PR + assert verdicts(r) == [cpr.REFUSE] and "not one of the plan's inputs" in r.findings[0].message + + +def test_override_comment_naming_the_plan_id_is_linked(): + r = _unlinked("plan-x: implement it as a cell fix", None) + assert r.verdict == cpr.READY, r.findings + assert _unlinked("plan-xy: implement it as a cell fix", None).verdict == cpr.REFUSE + + +def test_override_on_the_pull_request_holding_the_plan_is_linked(): + r = _unlinked("implement it as a cell fix", [{"filename": "docs/process/plans/plan-x.md"}]) + assert r.verdict == cpr.READY, r.findings + r = _unlinked("implement it as a cell fix", [{"filename": "docs/process/plans/plan-y.md"}]) + assert r.verdict == cpr.REFUSE + + +def test_override_link_unreadable_is_unverified(): + r = _unlinked("implement it as a cell fix", cpr.FetchError("offline")) + assert r.verdict == cpr.UNVERIFIED + + +def test_reviewer_repro_drift_guard_note_no_longer_verifies(): + # the review's live repro: Adequacy CELL, input #2765, `"**"` citing an unrelated note on #2487 + text = plan_text(adequacy="CELL", issues="- #2765 — the input") + text += '\n## Revision log\n\n- Override (cell): owner 2026-11-21 "**" — #2487 comment 7055038414\n' + fetch = Fetch( + { + "repos/antonsynd/sharpy/issues/2765": issue(["bug"]), + "repos/antonsynd/sharpy/issues/comments/7055038414": owner_comment( + "**Drift guard** note", issue=2487, created="2026-11-21T09:00:00Z" + ), + } + ) + assert run(text, fetch=fetch).verdict == cpr.REFUSE + + +@pytest.mark.parametrize("app, want", [("claude", "relayed via app claude"), (None, "no app")]) +def test_override_app_is_printed_not_judged(app, want): + r = run(cell_plan(GOOD), fetch=fetch_with(owner_comment("implement it as a cell fix", app=app))) + assert r.verdict == cpr.READY + assert any(want in n for n in r.notes) + assert want in r.header["Override"] + assert want in cpr.render(r) + + +@pytest.mark.parametrize("stamp, tier", [(ADEQ, "light"), (FULL, "light")]) +def test_light_plan_stamped_pass_with_corrections_is_malformed(stamp, tier): + r = run(plan_text(stamp=stamp, tier=tier, result="PASS WITH CORRECTIONS")) + assert verdicts(r) == [cpr.REFUSE] and "must read PASS or CONVERGED" in r.findings[0].message + + +def test_full_plan_stamped_pass_with_corrections_is_ready(): + assert run(plan_text(result="PASS WITH CORRECTIONS")).verdict == cpr.READY + + +def test_scope_derivation_is_addressed_to_the_lead(): + r = run(plan_text(date="2026-09-20", scope=None)) + assert verdicts(r) == [cpr.ASK] + msg = r.findings[0].message + assert "the LEAD answers this" in msg and "One non-chore group → proceed" in msg + + +def test_override_inside_an_html_comment_is_not_a_record(): + text = cell_plan(f"") + assert cpr.parse_plan("p", text).overrides == [] + one_line = cell_plan(f"") + assert cpr.parse_plan("p", one_line).overrides == [] + # positive control: the same record outside the comment is read, and the stamps still are + plan = cpr.parse_plan("p", cell_plan(f"\n{GOOD}")) + assert [o.line for o in plan.overrides] and plan.stamp is not None + assert plan.stamp.adequacy == {"CELL"} and plan.stamp.result == "PASS WITH CORRECTIONS" + + +def test_tier_after_an_open_comment_is_not_read(): + text = plan_text(tier="full (c)").replace("- **Tier:** full (c)", "\n- **Tier:** full (c)") + assert cpr.parse_plan("p", text).tier == "full" + + +@pytest.mark.parametrize( + "line, want", + [ + ("- **Tier:** **light** — from charter §3.8", "light"), + ("- Tier — light", "light"), + ("- Tier: _light_", "light"), + ("- **Tier:** `light`", "light"), + ("- **Tier**: light", "light"), + ], +) +def test_tier_spellings(line, want): + text = plan_text().replace("- **Override:** none", line + "\n- **Override:** none") + assert cpr.parse_plan("p", text).tier == want + + +def test_scope_mentioning_an_unparsed_tier_refuses(): + text = plan_text().replace("- **Override:** none", "- **Tier:** lite\n- **Override:** none") + assert cpr.parse_plan("p", text).tier == "unreadable" + r = run(text) + assert verdicts(r) == [cpr.REFUSE] and "mentions a tier" in r.findings[0].message + assert cpr.parse_plan("p", plan_text()).tier == "full" # control: no mention, no Tier → full + + +def test_draft_marker_with_needs_revision_refuses(): + for tier in (None, "light"): + r = run(plan_text(pre=DRAFT, tier=tier, result="NEEDS REVISION")) + assert verdicts(r) == [cpr.REFUSE] and r.findings[0].message == cpr.MSG_NEEDS_REVISION + + +def test_json_includes_the_refs_output(tmp_path, monkeypatch, capsys): + import json + + monkeypatch.delenv("CI", raising=False) + p = tmp_path / "plan-x.md" + p.write_text(plan_text(stamp=ADEQ, tier="light")) + cpr.main([str(p), "--repo", str(tmp_path), "--offline", "--json"]) + out = json.loads(capsys.readouterr().out) + assert "RESULT:" in out["refs_output"] From af93aed250bf92605f234ad931711b189884ad58 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:29:29 +0000 Subject: [PATCH 06/10] process(skills): step 2 says who answers each verdict; scope record MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 1, findings 4–6. /implement-plan step 2 now says: - a REFUSE on an override record means correct or delete the record; - "proceed or stop" and "which inputs?" are answered in chat with no plan record (the inputs go in the Implementation Summary); - with no Scope line the lead derives the scope and proceeds on one group; only more than one needs the owner; - the owner posts the override words on the plan's pull request or an input issue, and a chat `override` counts only once posted; - the two §11 clauses the checker does not check (a layout-changing phase sharing a gate; a generator-required group without stage 0 or its generator first) are the lead's, and are the scope question. /verify-plan's One-group row and Scope stamp line, and /create-plan's scope-exception sentence and `## Scope` template, name the `Override (scope)` record instead of `override: `. Procedure bytes 142472 -> 142675 (+203, after trimming this change's own wording). The baseline is NOT raised: scorecard_metrics.py --check and test_repository_matches_its_baseline are red by 203 until the lead trims elsewhere or the owner rules a raise. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- .claude/skills/create-plan/SKILL.md | 4 ++-- .claude/skills/implement-plan/SKILL.md | 5 +++-- .claude/skills/verify-plan/SKILL.md | 4 ++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/.claude/skills/create-plan/SKILL.md b/.claude/skills/create-plan/SKILL.md index 7a8c9f5f08..32f8dd08d1 100644 --- a/.claude/skills/create-plan/SKILL.md +++ b/.claude/skills/create-plan/SKILL.md @@ -47,7 +47,7 @@ A revision is plan-author work on an existing file of record. It runs in a **fre ## Scope check (before any research) -A plan implements **one non-chore group** of the round charter and lands on **one gate** (contract §11). If the issue list spans more than one group, or bundles a group that changes printed output or emitted layout with anything else, **stop and ask** which group to plan — never bundle. Chores ride along only when they touch no seam the group touches. Record the answer in the plan's `## Scope` block; a deliberate exception is written there as `override: `. +A plan implements **one non-chore group** of the round charter and lands on **one gate** (contract §11). If the issue list spans more than one group, or bundles a group that changes printed output or emitted layout with anything else, **stop and ask** which group to plan — never bundle. Chores ride along only when they touch no seam the group touches. Record the answer in the plan's `## Scope` block; a deliberate exception is an `Override (scope)` record there. ## Tier check (contract §12, before any research) @@ -161,7 +161,7 @@ The plan must follow this structure. `## Defect Class` and `## Adversarial Revie - **Alone:** - **Gates:** 1 - **Filing:** cells outside the contract go to the findings ledger; the lead files by class (contract §10); trackers named at the end of this plan -- **Override:** +- **Override (scope):** " — > ## Defect Class diff --git a/.claude/skills/implement-plan/SKILL.md b/.claude/skills/implement-plan/SKILL.md index 2d611b7cd7..ef3e24eab8 100644 --- a/.claude/skills/implement-plan/SKILL.md +++ b/.claude/skills/implement-plan/SKILL.md @@ -27,8 +27,9 @@ Before spawning any agents, perform these checks yourself. Note its **Defect Class** and **Adversarial Review** sections (if any), its **Issues to Close** rows with their close criteria, the **blast-radius** line, the **generated artifacts touched** line, and any spec examples it promises. Record the plan's **base sha** — the commit it was verified against (the `@ ` in the stamp) or the commit before its first implementation commit. Every scope check below uses `..HEAD`, never the branch-vs-`mainline` range (on `dev` that spans every batch since the last release). ### 2. Check the tier and the verification stamp -- Run `python3 build_tools/check_plan_ready.py ` (outside the sandbox: `gh api`) and act on its verdict; its docstring holds the rules (contract §11, §12). **READY** → go on, and copy the `Implementation Summary header:` line it prints; a light plan's final `/verify-implementation` runs its light auditor set. **REFUSE** → stop with its message. **ASK** → ask the owner its question, once (an unverified plan: proceed or stop). **UNVERIFIED** → re-run where `gh` reaches GitHub; never proceed on it. -- **Override.** When the owner answers ASK with `override`, record it in the plan as `Override (cell|scope): owner YYYY-MM-DD "" — ` and re-run the checker until it reads READY: it accepts the line only when that comment's author is the repository `OWNER` and holds the words. +- Run `python3 build_tools/check_plan_ready.py ` (unsandboxed: `gh`) and act on its verdict; its docstring holds the rules (§11, §12). **READY** → go on, and copy the `Implementation Summary header:` line it prints; a light plan's final `/verify-implementation` runs its light auditor set. **REFUSE** → stop with its message (a bad override record: correct or delete it). **ASK** → ask its question once; "proceed or stop" and "which inputs?" are answered in chat, unrecorded (inputs go in the Implementation Summary); with no Scope line the lead derives it and proceeds on one group. **UNVERIFIED** → re-run where `gh` reaches GitHub. +- **Override.** The owner posts it on the plan's pull request or an input issue (chat counts once posted); record `Override (cell|scope): owner YYYY-MM-DD "" — `, re-run until READY. +- The lead checks (§11): a layout-changing phase sharing a gate, or a generator-required group without stage 0 or its generator first, is the scope question. - **Promotion in flight** (§12): if an implementer hits a decision the charter and plan did not rule, or the fix moves into `Semantic/`, `Lowering/` or `CodeGen/` on a light plan — STOP that lane, write the question with lettered options and the door type under `## Implementation Checklist` (added for this when the harness keeps a task board; never into `## Design Decisions`), ask the owner, record the answer there, and replace the `## Scope` Tier line with `tier: full (, promoted at /implement-plan: )`, the one design-section edit allowed after a stamp (contract §12). Never demote. - **CONVERGED** (contract §12 Convergence): the `### Deferred findings` rows are Phase 1's first task (a light plan's first commit): each is resolved in code — a map or exclusion entry, an assertion's source expression, a test's census constant — with the assertion or mutation the row names, and the commit body names the row it closes; the design sections contract §12 Convergence names are not edited beyond one `## Revision log` line, `deferred findings resolved in code @ `. diff --git a/.claude/skills/verify-plan/SKILL.md b/.claude/skills/verify-plan/SKILL.md index 2e55e698cc..769745f759 100644 --- a/.claude/skills/verify-plan/SKILL.md +++ b/.claude/skills/verify-plan/SKILL.md @@ -148,7 +148,7 @@ Flag as warning: any missing item; add it as a Missing Step. `verification-contract.md` §10–§11: -- **One group** — the plan's `## Scope` block names one non-chore group; chores riding along touch no seam the group touches (grep the chores' files against the group's). A second group, or an output/layout-changing phase sharing a gate with anything, is an error unless `override: ` is recorded. +- **One group** — the plan's `## Scope` block names one non-chore group; chores riding along touch no seam the group touches (grep the chores' files against the group's). A second group, or an output/layout-changing phase sharing a gate with anything, is an error without an `Override (scope)` record. - **Generator first** — if the Defect Class matrix has ≥2 axes × ≥3 values, or the group is a residue (second suffix), stage 0 holds the generator (or the first task does, with the product hook it needs; contract §11), and the hand matrix covers only the axis the generator cannot reach (the plan says which). Missing = error. - **Filing rule** — the plan names the class trackers it posts cells to and instructs no implementer to `gh issue create`; cells go to the findings ledger and the lead files by class. A Phase 0 that says "file the siblings" one per cell is a warning; correct it inline. - **Fidelity scope** — every Python-parity cell names its row in `python-fidelity-scope.md`; a DEVIATION-by-default surface without a promotion ruling is an error (the plan is fixing a non-bug). @@ -166,7 +166,7 @@ After verification, edit the plan file directly. - + ``` In `--adequacy` mode all four stamp lines are written: the first reads ``; the result is `PASS`, `NEEDS REVISION` or `CONVERGED`; `Adequacy:` is Dimension 6's verdict; `Scope:` is copied from the plan's `## Scope` block and `Generator:` row without grading Dimension 9 (a light plan that reads `MULTI-GROUP` or needs a generator is `NEEDS REVISION: promote to full`, §12). The Verification Summary carries only `### Paraphrase`, `### Adequacy`, `### Falsifiability`, `### Design decisions checked` and `### Unchecked Claims`, plus `### Deferred findings` on `CONVERGED`; downstream skills read the stamp as a full one. From a491a0b13bda3ebab635205518567c736ba2c346 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:35:45 +0000 Subject: [PATCH 07/10] build(scorecard): lower procedure bytes to the PR's final size Net against dev: procedure_bytes 145065 -> 142675 (-2390). The branch's intermediate baseline of 142472 (the --lower in 31ee14c5a) was never a dev value: review round 1's step-2 sentences (af93aed25) added 203 bytes on top of it, which is still a net lowering against dev. The baseline file was reset to dev's copy (cp of `git show origin/dev:build_tools/scorecard-baseline.json`) and `scorecard_metrics.py --lower` wrote 142675; no other row changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- build_tools/scorecard-baseline.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build_tools/scorecard-baseline.json b/build_tools/scorecard-baseline.json index d99ed880de..d3c3f17dc1 100644 --- a/build_tools/scorecard-baseline.json +++ b/build_tools/scorecard-baseline.json @@ -1,5 +1,5 @@ { - "procedure_bytes": 142472, + "procedure_bytes": 142675, "claude_md_bytes": 9205, "allowlist_rows_outside_seed": 2184, "allowlist_rows_seed": 2368 From 02fa77f13d6b58d4ded77dbff2d3179d5d052946 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:41:15 +0000 Subject: [PATCH 08/10] fix(build_tools): check_plan_ready refuses a full plan's light stamp The owner ruled on D1-D4 in chat on 2026-11-21: "2) accept and label" (D1) and "yes to all thtree" (D2 refuse, D3 as built, D4 no record as built). - D2: a full-tier plan whose stamp is Adequacy-only is REFUSE as a malformed stamp ("a full plan needs a full /verify-plan pass; re-run /verify-plan"), unless its Tier line says `promoted at /implement-plan` (the 3eba57 case, unchanged). This replaces the NOTE that accepted it. - D1, D3, D4: no code change. The docstring now states them as ruled: relayed comments are accepted and labelled (the app is printed, not judged); `lane:tooling` and `lane:message` make a bug-fix plan; an unverified plan's "proceed or stop" is answered in chat with no record. Corpus (75 files, GitHub reachable): 33 READY / 2 REFUSE / 40 ASK, no row changed (3eba57 stays ASK on its CONVERGED + CELL gate). Mutation record (test_check_plan_ready.py, 138 tests; broken, restored with cp, checked with cmp; each restore -> 0 failed / 138 passed): - D2a the full-plan Adequacy-only refusal dropped: 1 failed / 137 passed - D2b the promotion exemption dropped: 2 failed / 136 passed Positive control: the promoted, CONVERGED shape reads READY with header `CLASS (converged)` in the same test that pins the refusal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- build_tools/check_plan_ready.py | 22 +++++++++++++++------- build_tools/tests/test_check_plan_ready.py | 20 +++++++++++--------- 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/build_tools/check_plan_ready.py b/build_tools/check_plan_ready.py index cdea8fc49f..103c2d231b 100644 --- a/build_tools/check_plan_ready.py +++ b/build_tools/check_plan_ready.py @@ -29,8 +29,10 @@ `check_plan_refs.py --issues` runs in-process; a red report (its exit 1: a missing path, a line past end of file, an R-LW cap) → REFUSE. Lookup errors are a NOTE: they never made that report red. -* full: no stamp, or the DRAFT marker → ASK "This plan has not been verified. …" (proceed or stop). - NEEDS REVISION → REFUSE. +* full: no stamp, or the DRAFT marker → ASK "This plan has not been verified. …" (proceed or stop; + answered in chat, no plan record: owner, 2026-11-21). NEEDS REVISION → REFUSE. An Adequacy-only + stamp → REFUSE as malformed (a full plan needs a full pass), unless the Tier line says + `promoted at /implement-plan` (owner, 2026-11-21). * Adequacy (both tiers): CLASS or N/A proceed. CELL proceeds unless a plan input is a bug, ICE or regression issue; then PASS / PASS WITH CORRECTIONS asks step 2's cell question and CONVERGED asks "converged with CELL …" with the `### Deferred findings` rows. A cited `Override (cell)` record @@ -46,7 +48,8 @@ Which inputs make a bug-fix plan: the issue numbers on the `## Issues to Close` list items, except an item that says "stay open". An input is a bug, ICE or regression issue when GitHub gives it the -`bug` label or any `lane:*` label (contract §10: every lane names a defect), or its title says `ICE` +`bug` label or any `lane:*` label (contract §10: every lane names a defect; `lane:tooling` and +`lane:message` count, owner 2026-11-21), or its title says `ICE` or "regression". No `## Issues to Close` section → ASK (which issues are the inputs?); a section with no issue number → no bug input. @@ -73,7 +76,8 @@ legacy record and answers nothing. Only the gates the plan hits are verified. What this does NOT judge: whether an `OWNER` comment was typed by the owner or posted by an agent -with the owner's token (both read `OWNER`; the app is printed, not judged); a tier override or the charter row behind a Tier line; a light plan whose group should have +with the owner's token (both read `OWNER`; relayed comments are accepted and labelled, owner +2026-11-21: the app is printed, not judged); a tier override or the charter row behind a Tier line; a light plan whose group should have been full; an output or layout change sharing a gate beyond what the stamp's Scope line (Dimension 9) records; promotion in flight; the Implementation Summary header itself. @@ -854,11 +858,15 @@ def decide( report.add(REFUSE, MSG_NEEDS_REVISION) return _finish(report, ci) if plan.tier == "full" and st.adequacy_only: + # owner, 2026-11-21 (D2): only a promotion in flight keeps a light pass on a full plan if not (plan.tier_text and "promoted at /implement-plan" in plan.tier_text): - report.notes.append( - "a full plan carries an Adequacy-only stamp without a promotion in flight on its Tier line; " - "step 2 accepts any `/verify-plan` stamp at the full tier" + report.add( + REFUSE, + "a malformed stamp: a full plan needs a full /verify-plan pass, and this one carries an " + "Adequacy-only stamp with no `promoted at /implement-plan` on its Tier line; re-run " + "/verify-plan", ) + return _finish(report, ci) if plan.tier == "light" and st.result not in ("PASS", "CONVERGED"): report.add( REFUSE, diff --git a/build_tools/tests/test_check_plan_ready.py b/build_tools/tests/test_check_plan_ready.py index 0ef7d205dd..7390d1eed8 100644 --- a/build_tools/tests/test_check_plan_ready.py +++ b/build_tools/tests/test_check_plan_ready.py @@ -413,15 +413,17 @@ def test_light_plan_with_full_stamp_is_accepted_with_a_note(): ) -def test_full_plan_with_adequacy_only_stamp_notes_it_unless_promoted(): - r = run(plan_text(stamp=ADEQ)) - assert r.verdict == cpr.READY and any("Adequacy-only stamp" in n for n in r.notes) - r = run( - plan_text( - stamp=ADEQ, tier="full (a, promoted at /implement-plan: D9), from light" - ) - ) - assert not any("Adequacy-only stamp" in n for n in r.notes) +def test_full_plan_with_adequacy_only_stamp_refuses_unless_promoted(): + # owner, 2026-11-21 (D2): a full plan needs a full pass + for tier in (None, "full (c: the seam is under `Semantic/`)"): + r = run(plan_text(stamp=ADEQ, tier=tier)) + assert verdicts(r) == [cpr.REFUSE] + assert "a full plan needs a full /verify-plan pass" in r.findings[0].message + # the 3eba57 shape: promoted in flight, CONVERGED, its Adequacy-only stamp still stands + promoted = "full (a, promoted at /implement-plan: D9), from light" + r = run(plan_text(stamp=ADEQ, tier=promoted, result="CONVERGED")) + assert r.verdict == cpr.READY, r.findings + assert r.header["Adequacy"] == "CLASS (converged)" # ── overrides ──────────────────────────────────────────────────────────────────────────────────── From 8652b0fd978ca5ce955bfb71bf759c7876ab16f5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:56:17 +0000 Subject: [PATCH 09/10] =?UTF-8?q?fix(build=5Ftools):=20check=5Fplan=5Fread?= =?UTF-8?q?y=20review=20round=202=20=E2=80=94=20override=20words?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 2 on the plan-readiness checker: 1. The quoted words of an override record, and the owner comment they come from, must hold the whole word `override` (case-folded), on top of the 3-word / 12-character rule. The docstring states the limit: this is evidence, not authentication (D1: relayed comments are accepted and labelled), and meaning is not judged. 2. MSG_CELL, MSG_SCOPE and MSG_CONVERGED_CELL ask the owner to post `override` and a one-line reason on the plan's PR or an input issue. The docstring examples and the create-plan template example pass. 3. The light result rule (PASS or CONVERGED only) applies to an Adequacy-only stamp. A light plan with a full stamp keeps PASS WITH CORRECTIONS, its default. 4. The NOTE spells out "no app (web or a local gh/API client; who typed it cannot be told)"; the header keeps `no app`. 5. A Tier REFUSE fires only on label-shaped mentions (`Tier:`, `Tier —`). Prose such as "Two-tier rollout" or "the tier is the owner's call" is not a label. A label with no readable value still refuses. 6. Inline-code spans are blanked before scanning for `` spans, and whether a comment is still open after it.""" + """The line without its `` spans, and whether a comment is still open after it. + A ``, one line or several) removed: a record inside a comment is not rendered, so it is not read. The stamp lines are HTML comments too; parse_stamp reads them from the header.""" - out, fence, in_comment = [], None, False + return _scan(text)[0] + + +def unclosed_comment(text: str) -> Optional[int]: + """The line where an HTML comment opens and never closes, or None.""" + return _scan(text)[1] + + +def _scan(text: str) -> Tuple[List[Tuple[int, str]], Optional[int]]: + out, fence, in_comment, opened = [], None, False, None for i, line in enumerate(text.split("\n"), 1): m = cpr.FENCE_LINE_RE.match(line) if fence is None: if not in_comment and m and not (m.group(1)[0] == "`" and "`" in m.group(2)): fence = (m.group(1)[0], len(m.group(1))) continue + was_open = in_comment visible, in_comment = _strip_comments(line, in_comment) + if in_comment and not was_open: + opened = i if visible.strip() or not line.strip(): out.append((i, visible)) elif ( @@ -369,7 +397,7 @@ def _outside_fences(text: str) -> List[Tuple[int, str]]: and not m.group(2).strip() ): fence = None - return out + return out, (opened if in_comment else None) def _section(text: str, name: str) -> Optional[str]: @@ -536,6 +564,7 @@ def parse_plan(path: str, text: str) -> Plan: overrides=overrides, legacy_overrides=legacy, title=title, + open_comment=unclosed_comment(text), ) @@ -608,6 +637,8 @@ def linked_to_plan( return True, f"#{number} is the pull request that holds {plan.path}" if len(files) < 100: break + else: + return None, f"#{number} has more than {PR_FILES_PAGES * 100} files: cannot tell" return False, "" @@ -628,6 +659,13 @@ def verify_override( f"{MIN_CHARS} characters; quote the owner's sentence", "", ) + if not OVERRIDE_WORD_RE.search(words): + return ( + REFUSE, + f'{where}: malformed record: the quoted words "{o.words}" do not say `override`; quote ' + "the owner's override and its reason", + "", + ) if o.cite is None: return ( REFUSE, @@ -688,7 +726,8 @@ def verify_override( how = "no plan to link" app = (c.get("performed_via_github_app") or {}).get("slug") via = f"relayed via app {app}" if app else "no app" - return READY, f'{where}: owner comment {cid} ({via}; {how}) holds "{o.words}"', via + told = via if app else "no app (web or a local gh/API client; who typed it cannot be told)" + return READY, f'{where}: owner comment {cid} ({told}; {how}) holds "{o.words}"', via def check_gate( @@ -725,7 +764,8 @@ def is_bug_fix(plan: Plan, fetch: Callable) -> Tuple[Optional[bool], str, str]: if plan.inputs is None: return ( None, - "no `## Issues to Close` section: which issues are this plan's inputs?", + "no `## Issues to Close` section: which issues are this plan's inputs? (the lead " + "answers, listing them in the Implementation Summary)", ASK, ) if not plan.inputs: @@ -821,6 +861,13 @@ def decide( report = Report(plan=plan.path, tier=plan.tier, stamp=describe(st, plan.draft)) tier_src = f"`{plan.tier_text[:100]}`" if plan.tier_text else "no Tier line" report.header["Tier"] = plan.tier + if plan.open_comment is not None: + report.add( + REFUSE, + f"an HTML comment opened at line {plan.open_comment} never closes: everything after it is " + "hidden; close it with `-->`", + ) + return _finish(report, ci) if plan.tier == "unreadable": report.add( REFUSE, @@ -867,7 +914,7 @@ def decide( "/verify-plan", ) return _finish(report, ci) - if plan.tier == "light" and st.result not in ("PASS", "CONVERGED"): + if plan.tier == "light" and st.adequacy_only and st.result not in ("PASS", "CONVERGED"): report.add( REFUSE, f"a light plan's stamp must read PASS or CONVERGED (`/verify-plan --adequacy` writes only " diff --git a/build_tools/scorecard-baseline.json b/build_tools/scorecard-baseline.json index d3c3f17dc1..00d2f034a1 100644 --- a/build_tools/scorecard-baseline.json +++ b/build_tools/scorecard-baseline.json @@ -1,5 +1,5 @@ { - "procedure_bytes": 142675, + "procedure_bytes": 142673, "claude_md_bytes": 9205, "allowlist_rows_outside_seed": 2184, "allowlist_rows_seed": 2368 diff --git a/build_tools/tests/test_check_plan_ready.py b/build_tools/tests/test_check_plan_ready.py index 7390d1eed8..7b938c707a 100644 --- a/build_tools/tests/test_check_plan_ready.py +++ b/build_tools/tests/test_check_plan_ready.py @@ -407,7 +407,7 @@ def test_light_cell_and_scope_rules_are_the_full_tiers(): def test_light_plan_with_full_stamp_is_accepted_with_a_note(): - r = run(plan_text(tier="light", result="PASS")) + r = run(plan_text(tier="light")) assert r.verdict == cpr.READY and any( "full /verify-plan stamp" in n for n in r.notes ) @@ -457,13 +457,13 @@ def fetch_with(comment): ) -GOOD = f'- Override (cell): owner 2026-11-06 "implement it as a cell fix" — {CITE}' +GOOD = f'- Override (cell): owner 2026-11-06 "override, implement it as a cell fix" — {CITE}' def test_verified_owner_override_answers_the_cell_gate(): r = run( cell_plan(GOOD), - fetch=fetch_with(owner_comment("> Implement it as a **cell fix**, please")), + fetch=fetch_with(owner_comment("> Override, implement it as a **cell fix**, please")), ) assert r.verdict == cpr.READY, r.findings assert r.header["Adequacy"] == "CELL (override)" @@ -473,7 +473,7 @@ def test_verified_owner_override_answers_the_cell_gate(): def test_verified_override_answers_converged_cell_too(): r = run( cell_plan(GOOD, result="CONVERGED"), - fetch=fetch_with(owner_comment("implement it as a cell fix")), + fetch=fetch_with(owner_comment("override, implement it as a cell fix")), ) assert ( r.verdict == cpr.READY and r.header["Adequacy"] == "CELL (override) (converged)" @@ -486,7 +486,7 @@ def test_verified_override_answers_converged_cell_too(): def test_override_by_non_owner_refuses(assoc): r = run( cell_plan(GOOD), - fetch=fetch_with(owner_comment("implement it as a cell fix", assoc=assoc)), + fetch=fetch_with(owner_comment("override, implement it as a cell fix", assoc=assoc)), ) assert ( verdicts(r) == [cpr.REFUSE] @@ -504,7 +504,7 @@ def test_override_words_absent_from_the_comment_refuses(): def test_override_comment_on_another_issue_refuses(): r = run( cell_plan(GOOD), - fetch=fetch_with(owner_comment("implement it as a cell fix", issue=9)), + fetch=fetch_with(owner_comment("override, implement it as a cell fix", issue=9)), ) assert verdicts(r) == [cpr.REFUSE] and "is not on #100" in r.findings[0].message @@ -515,7 +515,7 @@ def test_override_comment_missing_refuses(): def test_override_in_another_repo_refuses(): - rec = '- Override (cell): owner 2026-11-06 "implement it knowingly" — https://github.com/evil/sharpy/issues/1#issuecomment-5' + rec = '- Override (cell): owner 2026-11-06 "override: implement it knowingly" — https://github.com/evil/sharpy/issues/1#issuecomment-5' r = run(cell_plan(rec), fetch=BUG) assert ( verdicts(r) == [cpr.REFUSE] and "not antonsynd/sharpy" in r.findings[0].message @@ -524,7 +524,7 @@ def test_override_in_another_repo_refuses(): def test_override_without_citation_refuses(): r = run( - cell_plan('- Override (cell): owner 2026-11-06 "implement it knowingly"'), fetch=BUG + cell_plan('- Override (cell): owner 2026-11-06 "override: implement it knowingly"'), fetch=BUG ) assert ( verdicts(r) == [cpr.REFUSE] @@ -555,15 +555,15 @@ def test_override_for_the_other_gate_does_not_answer(): scope_only = GOOD.replace("(cell)", "(scope)") r = run( cell_plan(scope_only), - fetch=fetch_with(owner_comment("implement it as a cell fix")), + fetch=fetch_with(owner_comment("override, implement it as a cell fix")), ) assert verdicts(r) == [cpr.ASK] def test_scope_override_answers_multi_group(): - rec = f'- **Override (scope):** owner 2026-09-28 "go ahead with both groups" — #100 comment 7050154806' + rec = f'- **Override (scope):** owner 2026-09-28 "override, go ahead with both groups" — #100 comment 7050154806' text = plan_text(scope="MULTI-GROUP (override) · Generator: existing", extra=rec) - comment = owner_comment("ok — go ahead with both groups", created="2026-09-28T23:59:00Z") + comment = owner_comment("ok — override, go ahead with both groups", created="2026-09-28T23:59:00Z") r = run(text, fetch=fetch_with(comment)) assert r.verdict == cpr.READY, r.findings @@ -622,10 +622,10 @@ def test_comment_paths(): def test_review_comment_parent_is_checked(): - rec = '- Override (cell): owner 2026-11-06 "yes, implement it knowingly" — https://github.com/antonsynd/sharpy/pull/12#discussion_r34' + rec = '- Override (cell): owner 2026-11-06 "override: yes, implement it knowingly" — https://github.com/antonsynd/sharpy/pull/12#discussion_r34' c = { "author_association": "OWNER", - "body": "yes, implement it knowingly", + "body": "override: yes, implement it knowingly", "created_at": "2026-11-06T10:00:00Z", "pull_request_url": "https://api.github.com/repos/antonsynd/sharpy/pulls/12", } @@ -813,11 +813,11 @@ def test_single_negated_word_fails_and_a_negated_phrase_is_not_judged(): r = run(cell_plan(rec), fetch=fetch_with(owner_comment("do not override"))) assert r.verdict == cpr.REFUSE # a 3-word phrase inside its negation verifies: the checker does not judge meaning (documented) - rec = f'- Override (cell): owner 2026-11-06 "implement it knowingly" — {CITE}' - r = run(cell_plan(rec), fetch=fetch_with(owner_comment("do not implement it knowingly"))) + rec = f'- Override (cell): owner 2026-11-06 "override this cell fix" — {CITE}' + r = run(cell_plan(rec), fetch=fetch_with(owner_comment("do not override this cell fix"))) assert r.verdict == cpr.READY assert "does not judge meaning" in cpr.verify_override.__doc__ - assert "does not judge meaning" in cpr.__doc__ + assert "is not judged" in cpr.__doc__ and "evidence, not authentication" in cpr.__doc__ @pytest.mark.parametrize( @@ -832,13 +832,13 @@ def test_single_negated_word_fails_and_a_negated_phrase_is_not_judged(): ], ) def test_override_comment_date_is_the_record_date_within_a_day(created, want): - comment = owner_comment("implement it as a cell fix", created=created) + comment = owner_comment("override, implement it as a cell fix", created=created) r = run(cell_plan(GOOD), fetch=fetch_with(comment)) assert r.verdict == want, r.findings def _unlinked(body, files): - rec = '- Override (cell): owner 2026-11-06 "implement it as a cell fix" — #2487 comment 7055038414' + rec = '- Override (cell): owner 2026-11-06 "override, implement it as a cell fix" — #2487 comment 7055038414' comment = owner_comment(body, issue=2487) table = { "repos/antonsynd/sharpy/issues/100": issue(["bug"]), @@ -849,25 +849,25 @@ def _unlinked(body, files): def test_override_on_an_issue_unrelated_to_the_plan_refuses(): - r = _unlinked("implement it as a cell fix", None) # #2487: no input, no plan id, no PR + r = _unlinked("override, implement it as a cell fix", None) # #2487: no input, no plan id, no PR assert verdicts(r) == [cpr.REFUSE] and "not one of the plan's inputs" in r.findings[0].message def test_override_comment_naming_the_plan_id_is_linked(): - r = _unlinked("plan-x: implement it as a cell fix", None) + r = _unlinked("plan-x: override, implement it as a cell fix", None) assert r.verdict == cpr.READY, r.findings - assert _unlinked("plan-xy: implement it as a cell fix", None).verdict == cpr.REFUSE + assert _unlinked("plan-xy: override, implement it as a cell fix", None).verdict == cpr.REFUSE def test_override_on_the_pull_request_holding_the_plan_is_linked(): - r = _unlinked("implement it as a cell fix", [{"filename": "docs/process/plans/plan-x.md"}]) + r = _unlinked("override, implement it as a cell fix", [{"filename": "docs/process/plans/plan-x.md"}]) assert r.verdict == cpr.READY, r.findings - r = _unlinked("implement it as a cell fix", [{"filename": "docs/process/plans/plan-y.md"}]) + r = _unlinked("override, implement it as a cell fix", [{"filename": "docs/process/plans/plan-y.md"}]) assert r.verdict == cpr.REFUSE def test_override_link_unreadable_is_unverified(): - r = _unlinked("implement it as a cell fix", cpr.FetchError("offline")) + r = _unlinked("override, implement it as a cell fix", cpr.FetchError("offline")) assert r.verdict == cpr.UNVERIFIED @@ -886,18 +886,23 @@ def test_reviewer_repro_drift_guard_note_no_longer_verifies(): assert run(text, fetch=fetch).verdict == cpr.REFUSE -@pytest.mark.parametrize("app, want", [("claude", "relayed via app claude"), (None, "no app")]) -def test_override_app_is_printed_not_judged(app, want): - r = run(cell_plan(GOOD), fetch=fetch_with(owner_comment("implement it as a cell fix", app=app))) +@pytest.mark.parametrize( + "app, want, note", + [ + ("claude", "relayed via app claude", "relayed via app claude"), + (None, "no app", "no app (web or a local gh/API client; who typed it cannot be told)"), + ], +) +def test_override_app_is_printed_not_judged(app, want, note): + r = run(cell_plan(GOOD), fetch=fetch_with(owner_comment("override, implement it as a cell fix", app=app))) assert r.verdict == cpr.READY - assert any(want in n for n in r.notes) - assert want in r.header["Override"] + assert any(note in n for n in r.notes) + assert r.header["Override"].endswith(want) assert want in cpr.render(r) -@pytest.mark.parametrize("stamp, tier", [(ADEQ, "light"), (FULL, "light")]) -def test_light_plan_stamped_pass_with_corrections_is_malformed(stamp, tier): - r = run(plan_text(stamp=stamp, tier=tier, result="PASS WITH CORRECTIONS")) +def test_light_plan_adequacy_stamp_with_corrections_is_malformed(): + r = run(plan_text(stamp=ADEQ, tier="light", result="PASS WITH CORRECTIONS")) assert verdicts(r) == [cpr.REFUSE] and "must read PASS or CONVERGED" in r.findings[0].message @@ -966,3 +971,98 @@ def test_json_includes_the_refs_output(tmp_path, monkeypatch, capsys): cpr.main([str(p), "--repo", str(tmp_path), "--offline", "--json"]) out = json.loads(capsys.readouterr().out) assert "RESULT:" in out["refs_output"] + + +# ── fix round 2 ───────────────────────────────────────────────────────────────────────────────── + + +def test_override_words_must_say_override(): + # the review's live repro: an unrelated OWNER note on an input, words that are in it + rec = f'- Override (cell): owner 2026-11-05 "Two additions from the same round" — {CITE}' + fetch = fetch_with(owner_comment("Two additions from the same round @ fd925ddca", created="2026-11-05T20:30:02Z")) + r = run(cell_plan(rec), fetch=fetch) + assert verdicts(r) == [cpr.REFUSE] and "do not say `override`" in r.findings[0].message + assert COMMENT_PATH not in fetch.calls + for words in ("overrides the cell gate", "the override-free path"): # not the whole word + r = run(cell_plan(f'- Override (cell): owner 2026-11-06 "{words}" — {CITE}'), fetch=fetch) + assert "do not say `override`" in r.findings[0].message + # positive control: the word in any case verifies + rec = f'- Override (cell): owner 2026-11-06 "OVERRIDE, implement it as a cell fix" — {CITE}' + assert run(cell_plan(rec), fetch=fetch_with(owner_comment("override, implement it as a cell fix"))).verdict == cpr.READY + + +@pytest.mark.parametrize("msg", [cpr.MSG_CELL, cpr.MSG_SCOPE, cpr.MSG_CONVERGED_CELL]) +def test_questions_ask_for_a_posted_override_with_a_reason(msg): + assert "say `override`" not in msg + assert "post `override` and a one-line reason on the plan's PR or an input issue" in msg + + +def test_documented_examples_pass_the_word_rules(): + import re + + examples = re.findall(r'owner \d{4}-\d{2}-\d{2} "([^"]+)"', cpr.__doc__) + assert len(examples) == 2 + for words in examples: + n = cpr.normalise(words) + assert cpr.OVERRIDE_WORD_RE.search(n) and len(cpr.WORD_RE.findall(n)) >= 3 and len(n) >= 12 + template = (REPO_ROOT / ".claude/skills/create-plan/SKILL.md").read_text() + assert '"override: "' in template + + +def test_light_plan_full_stamp_result_rule_is_the_adequacy_stamps(): + assert "a full\n nine-dimension stamp is accepted" in cpr.__doc__ + r = run(plan_text(tier="light", result="PASS WITH CORRECTIONS")) + assert r.verdict == cpr.READY + + +@pytest.mark.parametrize( + "line", ["- Two-tier rollout", "- the tier-1 seam stays", "The tier is the owner's call."] +) +def test_tier_prose_is_not_a_label(line): + text = plan_text().replace("- **Override:** none", line + "\n- **Override:** none") + assert cpr.parse_plan("p", text).tier == "full" + + +@pytest.mark.parametrize("line", ["- Tier: n/a", "- **Tier:** banana", "- Tier — tbd"]) +def test_tier_label_without_a_value_refuses(line): + text = plan_text().replace("- **Override:** none", line + "\n- **Override:** none") + assert cpr.parse_plan("p", text).tier == "unreadable" + assert run(text).verdict == cpr.REFUSE + + +def test_comment_opener_inside_inline_code_is_text(): + line = "- The stamp opens with `")).open_comment is None # control + + +def test_pr_with_more_files_than_the_pages_read_is_unverified(): + full = [{"filename": f"src/f{i}.cs"} for i in range(100)] + rec = '- Override (cell): owner 2026-11-06 "override, implement it as a cell fix" — #2487 comment 7055038414' + table = { + "repos/antonsynd/sharpy/issues/100": issue(["bug"]), + "repos/antonsynd/sharpy/issues/comments/7055038414": owner_comment("override, implement it as a cell fix", issue=2487), + } + for page in range(1, cpr.PR_FILES_PAGES + 1): + table[f"repos/antonsynd/sharpy/pulls/2487/files?per_page=100&page={page}"] = full + r = run(cell_plan(rec), fetch=Fetch(table)) + assert r.verdict == cpr.UNVERIFIED and "more than 300 files" in r.findings[0].message + # control: a short last page that misses the plan file is "not linked" + table[f"repos/antonsynd/sharpy/pulls/2487/files?per_page=100&page={cpr.PR_FILES_PAGES}"] = full[:5] + assert run(cell_plan(rec), fetch=Fetch(table)).verdict == cpr.REFUSE + + +def test_inputs_question_is_the_leads(): + r = run(plan_text(date="2026-08-24", adequacy=None, issues=None), fetch=Fetch()) + assert "the lead answers" in r.findings[0].message and "Implementation Summary" in r.findings[0].message + assert "the lead records the inputs in the Implementation Summary" in cpr.__doc__ From f7c227b73432c60d0fbabc30b7d3531e72f53026 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 05:11:05 +0000 Subject: [PATCH 10/10] fix(build_tools): check_plan_ready reads a Tier list item as a mention MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Narrow check of 8652b0fd9: the label-shaped TIER_WORD_RE stopped catching lines such as `- Tier = light`, `- **Tier (contract §12):** light`, `- Tier is light` and `- **Tier** light — charter`. Each read `tier: full` with no message, so a light plan with a full stamp and a red refs report read READY: the refs check was skipped. A list item that starts with the label (TIER_ITEM_RE, `^\s{0,3}[-*+]\s+[*_]*tier(?![\w-])`) now also counts as a mention. Such a line is REFUSE as unreadable unless TIER_RE reads it. Prose still reads full: "- Two-tier rollout", "- the tier-1 seam stays", "- tier-1 seams stay", "The tier is the owner's call.". `Tier: n/a` still refuses, and `- **Tier:** light`, `- Tier — light` and `* Tier: light (…)` read light. Corpus (75 plans): 33 READY / 2 REFUSE / 40 ASK, no changed rows. Mutation records: each guard broken -> red, restored with cp, checked with cmp (identical) -> green, over build_tools/tests/test_check_plan_ready.py (164 tests): R12 a list item starting with the label is a mention 4 failed / 160 -> 0 / 164 R13 `tier-1` at an item's start is prose 1 failed / 163 -> 0 / 164 Guards: pytest build_tools/tests 2448 passed / 0 failed / 1 skipped; scorecard --check OK; check_skill_refs OK (0 broken of 1021). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- build_tools/check_plan_ready.py | 4 ++- build_tools/tests/test_check_plan_ready.py | 30 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/build_tools/check_plan_ready.py b/build_tools/check_plan_ready.py index ceae2d3a42..49cdf9d238 100644 --- a/build_tools/check_plan_ready.py +++ b/build_tools/check_plan_ready.py @@ -200,6 +200,8 @@ def _load_sibling(name: str): ) # A label-shaped mention (`Tier:`, `**Tier:**`, `Tier —`), not prose ("two-tier", "the tier-1 seam"). TIER_WORD_RE = re.compile(r"\btier\b[*_]*(?:\s*:|\s+[—–-])", re.IGNORECASE) +# A list item that starts with the label (`- Tier = light`, `- **Tier (contract §12):** light`). +TIER_ITEM_RE = re.compile(r"^\s{0,3}[-*+]\s+[*_]*tier(?![\w-])", re.IGNORECASE | re.MULTILINE) ISSUE_RE = re.compile(r"(? Plan: tier, tier_text = m.group(1).lower(), line.strip() break else: - mention = next((l for _, l in scope_lines if TIER_WORD_RE.search(l)), None) + mention = next((l for _, l in scope_lines if TIER_WORD_RE.search(l) or TIER_ITEM_RE.search(l)), None) if mention is not None: # a Tier the parser cannot read is never taken as `full` tier, tier_text = "unreadable", mention.strip() title = next((l[2:].strip() for l in lines if l.startswith("# ")), "") diff --git a/build_tools/tests/test_check_plan_ready.py b/build_tools/tests/test_check_plan_ready.py index 7b938c707a..4766d78915 100644 --- a/build_tools/tests/test_check_plan_ready.py +++ b/build_tools/tests/test_check_plan_ready.py @@ -1066,3 +1066,33 @@ def test_inputs_question_is_the_leads(): r = run(plan_text(date="2026-08-24", adequacy=None, issues=None), fetch=Fetch()) assert "the lead answers" in r.findings[0].message and "Implementation Summary" in r.findings[0].message assert "the lead records the inputs in the Implementation Summary" in cpr.__doc__ + + +# ── narrow check of 8652b0fd9: list items that start with the Tier label ──────────────────────── + + +@pytest.mark.parametrize( + "line", + ["- Tier = light", "- **Tier (contract §12):** light", "- Tier is light", "- **Tier** light — charter"], +) +def test_tier_list_item_the_parser_cannot_read_refuses(line): + text = plan_text().replace("- **Override:** none", line + "\n- **Override:** none") + plan = cpr.parse_plan("p", text) + assert plan.tier == "unreadable" and plan.tier_text == line + # the reviewer's case: a full stamp and a red refs report must not read READY + r = run(text, refs=lambda p: (1, "RESULT: FAIL\n")) + assert verdicts(r) == [cpr.REFUSE] + + +@pytest.mark.parametrize( + "line", ["- Two-tier rollout", "- the tier-1 seam stays", "- tier-1 seams stay", "The tier is the owner's call."] +) +def test_tier_prose_list_items_still_read_full(line): + text = plan_text().replace("- **Override:** none", line + "\n- **Override:** none") + assert cpr.parse_plan("p", text).tier == "full" + + +@pytest.mark.parametrize("line", ["- **Tier:** light", "- Tier — light", "* Tier: light (no seam)"]) +def test_tier_list_item_with_a_readable_value_reads_it(line): + text = plan_text().replace("- **Override:** none", line + "\n- **Override:** none") + assert cpr.parse_plan("p", text).tier == "light"