diff --git a/.claude/skills/create-plan/SKILL.md b/.claude/skills/create-plan/SKILL.md index 7a8c9f5f0..604fa1cc4 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 4f0a7b460..2e19d9abe 100644 --- a/.claude/skills/implement-plan/SKILL.md +++ b/.claude/skills/implement-plan/SKILL.md @@ -27,17 +27,11 @@ 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 ` (unsandboxed: `gh`) and act on its verdict; its docstring holds the rules (§11, §12). **READY** → go on; copy its `Implementation Summary header:` line; a light plan's final `/verify-implementation` runs its light auditor set. **REFUSE** → stop with its message (a bad override record: fix or delete it). **ASK** → ask its question once; "proceed or stop" is answered in chat, unrecorded; the lead answers "which inputs?" in the Implementation Summary; with no Scope line the lead derives it and proceeds on one group. **UNVERIFIED** → re-run with GitHub reachable. +- **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 "override: " — `, 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. -- 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 ` - + ``` 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. diff --git a/build_tools/check_plan_ready.py b/build_tools/check_plan_ready.py new file mode 100644 index 000000000..49cdf9d23 --- /dev/null +++ b/build_tools/check_plan_ready.py @@ -0,0 +1,1180 @@ +#!/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 a word is needed; the printed question is the one to ask, once. Most are the owner's; + the pre-2026-09-27 Scope derivation and "which issues are the inputs?" are the lead's + (the lead records the inputs in the Implementation Summary). + 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 (…)` ``, `- **Tier:** **light**`, `- Tier — light`); no Tier line means `full` + (plans created before 2026-10-28); a Scope block that mentions a tier no pattern reads → REFUSE. +* 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 (also beside a DRAFT + marker, at both tiers). An Adequacy-only stamp with any result but PASS or CONVERGED (PASS WITH + CORRECTIONS) → REFUSE as a malformed stamp. 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; + 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 + 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 lead derives the scope from the plan's groups (a reading), so it is ASK, + addressed to the lead, with the group ids the title names as evidence; one group proceeds, more + ask the owner. 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; `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. + +Override records. An override answers a gate only when it cites where the owner said it: + + - Override (cell): owner 2026-11-06 "override: the class is P77b's next group" — https://github.com/antonsynd/sharpy/issues/2433#issuecomment-1234567890 + - **Override (scope):** owner 2026-09-28 "override, both groups share the one seam" — #2423 comment 7050154806 + +one line, outside fenced code and HTML comments (a `|$)") +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\b[*_]*\s*(?::|[—–-])[*_]*\s*[*_`]*\s*(?:tier:\s*)?(light|full|band)(?![A-Za-z0-9])", + re.IGNORECASE, +) +# 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"(? 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 + open_comment: Optional[int] = None # the line of an HTML comment that never closes + + +CODE_SPAN_RE = re.compile(r"(`+)(.+?)\1") + + +def _strip_comments(line: str, in_comment: bool) -> Tuple[str, bool]: + """The line without its `` spans, and whether a comment is still open after it. + A `", pos) + if end < 0: + return "".join(kept), True + pos, in_comment = end + 3, False + else: + start = masked.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.""" + 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 ( + 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, (opened if in_comment else None) + + +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: + 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) 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("# ")), "") + 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, + open_comment=unclosed_comment(text), + ) + + +# ── 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 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 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, + 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", + "", + ) + 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" + 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( + 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] + 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: + 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? (the lead " + "answers, listing them in the Implementation Summary)", + 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.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, + 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, + f"tier `{plan.tier}` ({tier_src}) has no /implement-plan path: a band group has no plan", + ) + 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: + 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: + # 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.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.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 " + 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)" + ) + + 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}): 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( + 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, + "refs_output": report.refs_output, + }, + indent=2, + ) + ) + else: + print(render(report)) + return EXIT[report.verdict] + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/build_tools/check_plan_refs.py b/build_tools/check_plan_refs.py index c516a9f48..f9b5570b9 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/scorecard-baseline.json b/build_tools/scorecard-baseline.json index 02759411a..00d2f034a 100644 --- a/build_tools/scorecard-baseline.json +++ b/build_tools/scorecard-baseline.json @@ -1,5 +1,5 @@ { - "procedure_bytes": 145065, + "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 new file mode 100644 index 000000000..4766d7891 --- /dev/null +++ b/build_tools/tests/test_check_plan_ready.py @@ -0,0 +1,1098 @@ +"""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=None, + 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 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 != "-": # "-": no result line + 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="-")).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_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 ──────────────────────────────────────────────────────────────────────────────────── + +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=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, + } + + +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 "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("> Override, 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("override, 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("override, 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("override, implement it as a cell fix", issue=9)), + ) + assert verdicts(r) == [cpr.REFUSE] and "is not on #100" 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 "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 + ) + + +def test_override_without_citation_refuses(): + r = run( + cell_plan('- Override (cell): owner 2026-11-06 "override: implement it knowingly"'), 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("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 "override, go ahead with both groups" — #100 comment 7050154806' + text = plan_text(scope="MULTI-GROUP (override) · Generator: existing", extra=rec) + 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 + + +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 "override: yes, implement it knowingly" — https://github.com/antonsynd/sharpy/pull/12#discussion_r34' + c = { + "author_association": "OWNER", + "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", + } + 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 + 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 + + +def test_script_runs_the_sibling_check_plan_refs(tmp_path): + # `build_tools` is a namespace package: with another checkout on PYTHONPATH, an import by + # package name would run that checkout's check_plan_refs. A decoy proves which one runs. + import os + import subprocess + import sys + + decoy = tmp_path / "decoy" / "build_tools" + decoy.mkdir(parents=True) + (decoy / "check_plan_refs.py").write_text( + 'raise SystemExit("decoy check_plan_refs")\n' + ) + plan = tmp_path / "plan-x.md" + plan.write_text(plan_text(stamp=ADEQ, tier="light")) + env = dict(os.environ, PYTHONPATH=str(tmp_path / "decoy")) + env.pop("CI", None) + proc = subprocess.run( + [ + sys.executable, + str(REPO_ROOT / "build_tools/check_plan_ready.py"), + str(plan), + "--repo", + str(tmp_path), + "--offline", + ], + capture_output=True, + text=True, + env=env, + ) + 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 "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 "is not judged" in cpr.__doc__ and "evidence, not authentication" 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("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 "override, 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("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: override, implement it as a cell fix", None) + assert r.verdict == cpr.READY, r.findings + 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("override, implement it as a cell fix", [{"filename": "docs/process/plans/plan-x.md"}]) + assert r.verdict == cpr.READY, r.findings + 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("override, 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, 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(note in n for n in r.notes) + assert r.header["Override"].endswith(want) + assert want in cpr.render(r) + + +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 + + +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"] + + +# ── 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__ + + +# ── 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" diff --git a/build_tools/tests/test_check_plan_refs.py b/build_tools/tests/test_check_plan_refs.py index 3305b5c10..b07ff5b5a 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