diff --git a/CHANGELOG.md b/CHANGELOG.md index a9d6fdd..fc33ac0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- **Project gate overrides.** `scripts/check-gate.py` reads `pipeline/gate-criteria.md` + from the project when present; a stage defined there replaces the plugin's criteria + for that stage, others fall back to `references/gate-criteria.md`. Output gains + `criteria_source` (and `source` per criterion). Project `script_returns_zero` + criteria resolve scripts in the project first, then the plugin. A missing script is + still inconclusive and promoted to blocker (REQ-GATESTUB-001). `scripts/why.py` + explains overridden criteria consistently. +- **`check_srs_acceptance.py` options** `--id-pattern`, `--acceptance-pattern` and + `--row-scoped`, so projects whose SRS uses other ID schemes or table-row requirements + (e.g. `| **REQ-F-001** | … | Given … when … then … |`) can reuse G1-003. Defaults + are unchanged. + ### Planned - Claude Code marketplace publication (pending marketplace availability) diff --git a/forge-opencode/scripts/check-gate.py b/forge-opencode/scripts/check-gate.py index eecff80..51b5102 100755 --- a/forge-opencode/scripts/check-gate.py +++ b/forge-opencode/scripts/check-gate.py @@ -34,12 +34,14 @@ def _state_readable(cwd: Path) -> bool: return False -def _load_stage_criteria(plugin_dir: Path, stage: int) -> list[dict]: - gate_file = plugin_dir / "references" / "gate-criteria.md" - if not gate_file.exists(): - print(f"error: gate-criteria.md not found at {gate_file}", file=sys.stderr) - sys.exit(1) +# Project-level override: a project may ship its own criteria for any stage in +# this file (same YAML-block format as references/gate-criteria.md). A stage it +# defines replaces the plugin's criteria for that stage wholesale; stages it +# does not define fall back to the plugin. +PROJECT_GATE_FILE = Path("pipeline") / "gate-criteria.md" + +def _find_stage_block(gate_file: Path, stage: int) -> list[dict] | None: text = gate_file.read_text() blocks = re.findall(r"```yaml\n(.*?)```", text, re.DOTALL) @@ -47,14 +49,45 @@ def _load_stage_criteria(plugin_dir: Path, stage: int) -> list[dict]: try: data = yaml.safe_load(block) if isinstance(data, dict) and data.get("stage") == stage: - return data.get("criteria", []) + return data.get("criteria", []) or [] except yaml.YAMLError: continue + return None + + +def _resolve_stage_criteria(plugin_dir: Path, stage: int, cwd: Path) -> tuple[list[dict], str]: + """Return (criteria, source) where source is "project" or "plugin".""" + project_file = cwd / PROJECT_GATE_FILE + if project_file.exists(): + criteria = _find_stage_block(project_file, stage) + if criteria is not None: + return criteria, "project" + return _load_stage_criteria(plugin_dir, stage), "plugin" + + +def _load_stage_criteria(plugin_dir: Path, stage: int) -> list[dict]: + gate_file = plugin_dir / "references" / "gate-criteria.md" + if not gate_file.exists(): + print(f"error: gate-criteria.md not found at {gate_file}", file=sys.stderr) + sys.exit(1) + + criteria = _find_stage_block(gate_file, stage) + if criteria is not None: + return criteria print(f"error: no gate criteria found for stage {stage}", file=sys.stderr) sys.exit(1) +def _resolve_script(script_rel: str, cwd: Path, plugin_dir: Path, source: str) -> Path: + """Project criteria may name a project-local script; plugin scripts are the fallback.""" + if source == "project": + local = cwd / script_rel + if local.exists(): + return local + return plugin_dir / script_rel + + def _check_file_exists(args: dict, cwd: Path) -> tuple[bool, str]: p = cwd / args["path"] if not p.exists(): @@ -80,11 +113,8 @@ def _check_file_contains(args: dict, cwd: Path) -> tuple[bool, str]: return False, f"invalid regex {pattern!r}: {exc}" -def _check_script_returns_zero( - args: dict, cwd: Path, plugin_dir: Path -) -> tuple[bool, str]: +def _check_script_returns_zero(args: dict, cwd: Path, script: Path) -> tuple[bool, str]: script_rel = args["script"] - script = plugin_dir / script_rel if not script.exists(): return False, f"check script not yet implemented: {script_rel}" argv = [sys.executable, str(script)] + [str(a) for a in args.get("argv", [])] @@ -108,7 +138,7 @@ def _check_all_tests_pass(args: dict, cwd: Path) -> tuple[bool, str]: return False, last[:300] -def _evaluate(criterion: dict, cwd: Path, plugin_dir: Path) -> dict: +def _evaluate(criterion: dict, cwd: Path, plugin_dir: Path, source: str = "plugin") -> dict: cid = criterion["id"] check = criterion["check"] args = criterion.get("args", {}) @@ -125,12 +155,13 @@ def _evaluate(criterion: dict, cwd: Path, plugin_dir: Path) -> dict: # pass. Report inconclusive and promote severity to blocker regardless # of the declared severity — a stub gate must not read as "warnings only". script_rel = args.get("script", "") - if not (plugin_dir / script_rel).exists(): + script = _resolve_script(script_rel, cwd, plugin_dir, source) + if not script.exists(): passed, msg = False, f"check script not implemented: {script_rel}" inconclusive = True severity = "blocker" else: - passed, msg = _check_script_returns_zero(args, cwd, plugin_dir) + passed, msg = _check_script_returns_zero(args, cwd, script) elif check == "all_tests_pass": passed, msg = _check_all_tests_pass(args, cwd) else: @@ -146,12 +177,13 @@ def _evaluate(criterion: dict, cwd: Path, plugin_dir: Path) -> dict: "severity": severity, "passed": passed, "message": msg, + "source": source, } def evaluate_stage(stage: int, cwd: Path, plugin_dir: Path) -> dict: - criteria = _load_stage_criteria(plugin_dir, stage) - details = [_evaluate(c, cwd, plugin_dir) for c in criteria] + criteria, source = _resolve_stage_criteria(plugin_dir, stage, cwd) + details = [_evaluate(c, cwd, plugin_dir, source) for c in criteria] # REQ-SILENTSTATE-001: if state.md exists but is unreadable, the whole gate is # inconclusive — it must not read as a clean pass against missing data. @@ -172,6 +204,7 @@ def evaluate_stage(stage: int, cwd: Path, plugin_dir: Path) -> dict: failed = len(details) - passed return { "stage": stage, + "criteria_source": source, "total": len(details), "passed": passed, "failed": failed, diff --git a/forge-opencode/scripts/check_srs_acceptance.py b/forge-opencode/scripts/check_srs_acceptance.py index 9f3e9b3..919c1d2 100755 --- a/forge-opencode/scripts/check_srs_acceptance.py +++ b/forge-opencode/scripts/check_srs_acceptance.py @@ -1,36 +1,70 @@ #!/usr/bin/env python3 """Gate G1-003: every requirement in the SRS has acceptance criteria. -Usage: check_srs_acceptance.py +Usage: check_srs_acceptance.py [--id-pattern RE] [--acceptance-pattern RE] + [--row-scoped] Exit 0 if every REQ-* block declares acceptance criteria; 1 otherwise. A requirement "has acceptance criteria" if its block (text from one REQ heading up to the next REQ/NFR heading) contains an `AC-*` token or the word "acceptance" (case-insensitive). + +Options let a project whose SRS uses a different layout reuse this check from a +project gate override (pipeline/gate-criteria.md): + + --id-pattern RE regex matching requirement definitions (MULTILINE). If it + has a capture group, group 1 is the reported ID. + --acceptance-pattern RE regex a block must match to count as having criteria. + --row-scoped when a match sits on a markdown table row (a line + starting with "|"), its block is that row alone. """ from __future__ import annotations +import argparse import re import sys from pathlib import Path -REQ_ID = re.compile(r"\bREQ-[A-Z0-9]+(?:-[A-Z0-9]+)*\b") -ACCEPTANCE = re.compile(r"\bAC-[A-Z0-9]|acceptance", re.IGNORECASE) +REQ_ID = r"\bREQ-[A-Z0-9]+(?:-[A-Z0-9]+)*\b" +ACCEPTANCE = r"(?i)\bAC-[A-Z0-9]|acceptance" + + +def _block_end(text: str, start: int, next_start: int, row_scoped: bool) -> int: + if row_scoped: + line_start = text.rfind("\n", 0, start) + 1 + if text[line_start:start].lstrip().startswith("|"): + line_end = text.find("\n", start) + return len(text) if line_end == -1 else min(line_end, next_start) + return next_start def main(argv: list[str]) -> int: - if len(argv) != 1: - print("usage: check_srs_acceptance.py ", file=sys.stderr) + parser = argparse.ArgumentParser(prog="check_srs_acceptance.py") + parser.add_argument("srs") + parser.add_argument("--id-pattern", default=REQ_ID) + parser.add_argument("--acceptance-pattern", default=ACCEPTANCE) + parser.add_argument("--row-scoped", action="store_true") + try: + args = parser.parse_args(argv) + except SystemExit: return 2 - path = Path(argv[0]) + + try: + req_id = re.compile(args.id_pattern, re.MULTILINE) + acceptance = re.compile(args.acceptance_pattern) + except re.error as exc: + print(f"invalid regex: {exc}", file=sys.stderr) + return 2 + + path = Path(args.srs) if not path.exists(): print(f"SRS not found: {path}", file=sys.stderr) return 1 text = path.read_text() # Split into blocks at each REQ id occurrence (keep order). - matches = list(REQ_ID.finditer(text)) + matches = list(req_id.finditer(text)) if not matches: print("no requirements (REQ-*) found in SRS", file=sys.stderr) return 1 @@ -38,10 +72,10 @@ def main(argv: list[str]) -> int: missing: list[str] = [] for i, m in enumerate(matches): start = m.start() - end = matches[i + 1].start() if i + 1 < len(matches) else len(text) - block = text[start:end] - if not ACCEPTANCE.search(block): - missing.append(m.group(0)) + next_start = matches[i + 1].start() if i + 1 < len(matches) else len(text) + block = text[start:_block_end(text, start, next_start, args.row_scoped)] + if not acceptance.search(block): + missing.append(m.group(1) if req_id.groups else m.group(0)) # de-dup while preserving order seen = set() diff --git a/forge-opencode/scripts/why.py b/forge-opencode/scripts/why.py index 2e22e36..73ff029 100644 --- a/forge-opencode/scripts/why.py +++ b/forge-opencode/scripts/why.py @@ -96,17 +96,13 @@ def _import_format_gate_result(plugin_dir: Path): return mod -def _load_all_criteria(plugin_dir: Path) -> dict[str, dict]: - """Return {criterion_id: criterion_dict} across all stages. - - Each value gets an added `_stage` field for cross-referencing. - """ - gate_file = plugin_dir / "references" / "gate-criteria.md" +def _load_stage_blocks(gate_file: Path) -> dict[int, list[dict]]: + """Return {stage: criteria} for every YAML block in a gate-criteria file.""" if not gate_file.exists(): return {} text = gate_file.read_text() blocks = re.findall(r"```yaml\n(.*?)```", text, re.DOTALL) - result: dict[str, dict] = {} + stages: dict[int, list[dict]] = {} for block in blocks: try: data = yaml.safe_load(block) @@ -114,8 +110,23 @@ def _load_all_criteria(plugin_dir: Path) -> dict[str, dict]: continue if not isinstance(data, dict): continue - stage = data.get("stage") - for c in data.get("criteria", []) or []: + stages[data.get("stage")] = data.get("criteria", []) or [] + return stages + + +def _load_all_criteria(plugin_dir: Path, cwd: Path | None = None) -> dict[str, dict]: + """Return {criterion_id: criterion_dict} across all stages. + + Each value gets an added `_stage` field for cross-referencing. A stage the + project defines in pipeline/gate-criteria.md replaces the plugin's criteria + for that stage, matching check-gate.py. + """ + stages = _load_stage_blocks(plugin_dir / "references" / "gate-criteria.md") + if cwd is not None: + stages.update(_load_stage_blocks(cwd / "pipeline" / "gate-criteria.md")) + result: dict[str, dict] = {} + for stage, criteria in stages.items(): + for c in criteria: cid = c.get("id") if cid: c2 = dict(c) @@ -141,9 +152,9 @@ def _load_lessons(cwd: Path) -> list[dict]: # ---------- explainers ---------- -def _explain_gate(target: str, plugin_dir: Path) -> dict | None: +def _explain_gate(target: str, plugin_dir: Path, cwd: Path | None = None) -> dict | None: """Look up a gate criterion across all stages.""" - all_criteria = _load_all_criteria(plugin_dir) + all_criteria = _load_all_criteria(plugin_dir, cwd) crit = all_criteria.get(target) if not crit: return None @@ -185,12 +196,12 @@ def _explain_lesson_tag(tag: str, cwd: Path, limit: int = 5) -> dict | None: } -def _explain_stage(stage: int, plugin_dir: Path) -> dict | None: +def _explain_stage(stage: int, plugin_dir: Path, cwd: Path | None = None) -> dict | None: """Explain a pipeline stage including its blocker gate count.""" if stage not in STAGE_NAMES: return None info = STAGE_NAMES[stage] - all_criteria = _load_all_criteria(plugin_dir) + all_criteria = _load_all_criteria(plugin_dir, cwd) stage_crits = [c for c in all_criteria.values() if c.get("_stage") == stage] blocker_count = sum(1 for c in stage_crits if c.get("severity") == "blocker") warning_count = sum(1 for c in stage_crits if c.get("severity") != "blocker") @@ -440,11 +451,11 @@ def main(argv: Optional[list[str]] = None) -> int: target = args.target.strip() kind = _classify(target) if kind == "gate": - answer = _explain_gate(target.upper(), plugin_dir) # REQ-WHYCI-001 + answer = _explain_gate(target.upper(), plugin_dir, cwd) # REQ-WHYCI-001 elif kind == "stage": m = _STAGE_PATTERN.match(target) stage_num = int(m.group(1)) if m else None - answer = _explain_stage(stage_num, plugin_dir) if stage_num else None + answer = _explain_stage(stage_num, plugin_dir, cwd) if stage_num else None else: answer = _explain_lesson_tag(target, cwd) diff --git a/references/gate-criteria.md b/references/gate-criteria.md index 150480a..dcc55f3 100644 --- a/references/gate-criteria.md +++ b/references/gate-criteria.md @@ -9,6 +9,15 @@ > - `check`: how to verify (file_exists | file_contains | script_returns_zero | all_tests_pass) > - `args`: parameters for the check > - `severity`: blocker | warning (only blockers prevent advancement) +> +> **Project overrides.** A project may add `pipeline/gate-criteria.md` in the same +> format. Any stage it defines **replaces** this file's criteria for that stage +> (stages it omits still use this file); `check-gate.py` reports +> `criteria_source: project | plugin`. In project criteria, `script_returns_zero` +> resolves `script` against the project root first, then the plugin — so a project +> can ship its own check or reuse a plugin script with its own `argv`. +> `scripts/check_srs_acceptance.py` accepts `--id-pattern`, `--acceptance-pattern` +> and `--row-scoped` for SRSs that keep requirements in markdown table rows. --- diff --git a/scripts/check-gate.py b/scripts/check-gate.py index eecff80..51b5102 100755 --- a/scripts/check-gate.py +++ b/scripts/check-gate.py @@ -34,12 +34,14 @@ def _state_readable(cwd: Path) -> bool: return False -def _load_stage_criteria(plugin_dir: Path, stage: int) -> list[dict]: - gate_file = plugin_dir / "references" / "gate-criteria.md" - if not gate_file.exists(): - print(f"error: gate-criteria.md not found at {gate_file}", file=sys.stderr) - sys.exit(1) +# Project-level override: a project may ship its own criteria for any stage in +# this file (same YAML-block format as references/gate-criteria.md). A stage it +# defines replaces the plugin's criteria for that stage wholesale; stages it +# does not define fall back to the plugin. +PROJECT_GATE_FILE = Path("pipeline") / "gate-criteria.md" + +def _find_stage_block(gate_file: Path, stage: int) -> list[dict] | None: text = gate_file.read_text() blocks = re.findall(r"```yaml\n(.*?)```", text, re.DOTALL) @@ -47,14 +49,45 @@ def _load_stage_criteria(plugin_dir: Path, stage: int) -> list[dict]: try: data = yaml.safe_load(block) if isinstance(data, dict) and data.get("stage") == stage: - return data.get("criteria", []) + return data.get("criteria", []) or [] except yaml.YAMLError: continue + return None + + +def _resolve_stage_criteria(plugin_dir: Path, stage: int, cwd: Path) -> tuple[list[dict], str]: + """Return (criteria, source) where source is "project" or "plugin".""" + project_file = cwd / PROJECT_GATE_FILE + if project_file.exists(): + criteria = _find_stage_block(project_file, stage) + if criteria is not None: + return criteria, "project" + return _load_stage_criteria(plugin_dir, stage), "plugin" + + +def _load_stage_criteria(plugin_dir: Path, stage: int) -> list[dict]: + gate_file = plugin_dir / "references" / "gate-criteria.md" + if not gate_file.exists(): + print(f"error: gate-criteria.md not found at {gate_file}", file=sys.stderr) + sys.exit(1) + + criteria = _find_stage_block(gate_file, stage) + if criteria is not None: + return criteria print(f"error: no gate criteria found for stage {stage}", file=sys.stderr) sys.exit(1) +def _resolve_script(script_rel: str, cwd: Path, plugin_dir: Path, source: str) -> Path: + """Project criteria may name a project-local script; plugin scripts are the fallback.""" + if source == "project": + local = cwd / script_rel + if local.exists(): + return local + return plugin_dir / script_rel + + def _check_file_exists(args: dict, cwd: Path) -> tuple[bool, str]: p = cwd / args["path"] if not p.exists(): @@ -80,11 +113,8 @@ def _check_file_contains(args: dict, cwd: Path) -> tuple[bool, str]: return False, f"invalid regex {pattern!r}: {exc}" -def _check_script_returns_zero( - args: dict, cwd: Path, plugin_dir: Path -) -> tuple[bool, str]: +def _check_script_returns_zero(args: dict, cwd: Path, script: Path) -> tuple[bool, str]: script_rel = args["script"] - script = plugin_dir / script_rel if not script.exists(): return False, f"check script not yet implemented: {script_rel}" argv = [sys.executable, str(script)] + [str(a) for a in args.get("argv", [])] @@ -108,7 +138,7 @@ def _check_all_tests_pass(args: dict, cwd: Path) -> tuple[bool, str]: return False, last[:300] -def _evaluate(criterion: dict, cwd: Path, plugin_dir: Path) -> dict: +def _evaluate(criterion: dict, cwd: Path, plugin_dir: Path, source: str = "plugin") -> dict: cid = criterion["id"] check = criterion["check"] args = criterion.get("args", {}) @@ -125,12 +155,13 @@ def _evaluate(criterion: dict, cwd: Path, plugin_dir: Path) -> dict: # pass. Report inconclusive and promote severity to blocker regardless # of the declared severity — a stub gate must not read as "warnings only". script_rel = args.get("script", "") - if not (plugin_dir / script_rel).exists(): + script = _resolve_script(script_rel, cwd, plugin_dir, source) + if not script.exists(): passed, msg = False, f"check script not implemented: {script_rel}" inconclusive = True severity = "blocker" else: - passed, msg = _check_script_returns_zero(args, cwd, plugin_dir) + passed, msg = _check_script_returns_zero(args, cwd, script) elif check == "all_tests_pass": passed, msg = _check_all_tests_pass(args, cwd) else: @@ -146,12 +177,13 @@ def _evaluate(criterion: dict, cwd: Path, plugin_dir: Path) -> dict: "severity": severity, "passed": passed, "message": msg, + "source": source, } def evaluate_stage(stage: int, cwd: Path, plugin_dir: Path) -> dict: - criteria = _load_stage_criteria(plugin_dir, stage) - details = [_evaluate(c, cwd, plugin_dir) for c in criteria] + criteria, source = _resolve_stage_criteria(plugin_dir, stage, cwd) + details = [_evaluate(c, cwd, plugin_dir, source) for c in criteria] # REQ-SILENTSTATE-001: if state.md exists but is unreadable, the whole gate is # inconclusive — it must not read as a clean pass against missing data. @@ -172,6 +204,7 @@ def evaluate_stage(stage: int, cwd: Path, plugin_dir: Path) -> dict: failed = len(details) - passed return { "stage": stage, + "criteria_source": source, "total": len(details), "passed": passed, "failed": failed, diff --git a/scripts/check_srs_acceptance.py b/scripts/check_srs_acceptance.py index 9f3e9b3..919c1d2 100755 --- a/scripts/check_srs_acceptance.py +++ b/scripts/check_srs_acceptance.py @@ -1,36 +1,70 @@ #!/usr/bin/env python3 """Gate G1-003: every requirement in the SRS has acceptance criteria. -Usage: check_srs_acceptance.py +Usage: check_srs_acceptance.py [--id-pattern RE] [--acceptance-pattern RE] + [--row-scoped] Exit 0 if every REQ-* block declares acceptance criteria; 1 otherwise. A requirement "has acceptance criteria" if its block (text from one REQ heading up to the next REQ/NFR heading) contains an `AC-*` token or the word "acceptance" (case-insensitive). + +Options let a project whose SRS uses a different layout reuse this check from a +project gate override (pipeline/gate-criteria.md): + + --id-pattern RE regex matching requirement definitions (MULTILINE). If it + has a capture group, group 1 is the reported ID. + --acceptance-pattern RE regex a block must match to count as having criteria. + --row-scoped when a match sits on a markdown table row (a line + starting with "|"), its block is that row alone. """ from __future__ import annotations +import argparse import re import sys from pathlib import Path -REQ_ID = re.compile(r"\bREQ-[A-Z0-9]+(?:-[A-Z0-9]+)*\b") -ACCEPTANCE = re.compile(r"\bAC-[A-Z0-9]|acceptance", re.IGNORECASE) +REQ_ID = r"\bREQ-[A-Z0-9]+(?:-[A-Z0-9]+)*\b" +ACCEPTANCE = r"(?i)\bAC-[A-Z0-9]|acceptance" + + +def _block_end(text: str, start: int, next_start: int, row_scoped: bool) -> int: + if row_scoped: + line_start = text.rfind("\n", 0, start) + 1 + if text[line_start:start].lstrip().startswith("|"): + line_end = text.find("\n", start) + return len(text) if line_end == -1 else min(line_end, next_start) + return next_start def main(argv: list[str]) -> int: - if len(argv) != 1: - print("usage: check_srs_acceptance.py ", file=sys.stderr) + parser = argparse.ArgumentParser(prog="check_srs_acceptance.py") + parser.add_argument("srs") + parser.add_argument("--id-pattern", default=REQ_ID) + parser.add_argument("--acceptance-pattern", default=ACCEPTANCE) + parser.add_argument("--row-scoped", action="store_true") + try: + args = parser.parse_args(argv) + except SystemExit: return 2 - path = Path(argv[0]) + + try: + req_id = re.compile(args.id_pattern, re.MULTILINE) + acceptance = re.compile(args.acceptance_pattern) + except re.error as exc: + print(f"invalid regex: {exc}", file=sys.stderr) + return 2 + + path = Path(args.srs) if not path.exists(): print(f"SRS not found: {path}", file=sys.stderr) return 1 text = path.read_text() # Split into blocks at each REQ id occurrence (keep order). - matches = list(REQ_ID.finditer(text)) + matches = list(req_id.finditer(text)) if not matches: print("no requirements (REQ-*) found in SRS", file=sys.stderr) return 1 @@ -38,10 +72,10 @@ def main(argv: list[str]) -> int: missing: list[str] = [] for i, m in enumerate(matches): start = m.start() - end = matches[i + 1].start() if i + 1 < len(matches) else len(text) - block = text[start:end] - if not ACCEPTANCE.search(block): - missing.append(m.group(0)) + next_start = matches[i + 1].start() if i + 1 < len(matches) else len(text) + block = text[start:_block_end(text, start, next_start, args.row_scoped)] + if not acceptance.search(block): + missing.append(m.group(1) if req_id.groups else m.group(0)) # de-dup while preserving order seen = set() diff --git a/scripts/why.py b/scripts/why.py index 2e22e36..73ff029 100644 --- a/scripts/why.py +++ b/scripts/why.py @@ -96,17 +96,13 @@ def _import_format_gate_result(plugin_dir: Path): return mod -def _load_all_criteria(plugin_dir: Path) -> dict[str, dict]: - """Return {criterion_id: criterion_dict} across all stages. - - Each value gets an added `_stage` field for cross-referencing. - """ - gate_file = plugin_dir / "references" / "gate-criteria.md" +def _load_stage_blocks(gate_file: Path) -> dict[int, list[dict]]: + """Return {stage: criteria} for every YAML block in a gate-criteria file.""" if not gate_file.exists(): return {} text = gate_file.read_text() blocks = re.findall(r"```yaml\n(.*?)```", text, re.DOTALL) - result: dict[str, dict] = {} + stages: dict[int, list[dict]] = {} for block in blocks: try: data = yaml.safe_load(block) @@ -114,8 +110,23 @@ def _load_all_criteria(plugin_dir: Path) -> dict[str, dict]: continue if not isinstance(data, dict): continue - stage = data.get("stage") - for c in data.get("criteria", []) or []: + stages[data.get("stage")] = data.get("criteria", []) or [] + return stages + + +def _load_all_criteria(plugin_dir: Path, cwd: Path | None = None) -> dict[str, dict]: + """Return {criterion_id: criterion_dict} across all stages. + + Each value gets an added `_stage` field for cross-referencing. A stage the + project defines in pipeline/gate-criteria.md replaces the plugin's criteria + for that stage, matching check-gate.py. + """ + stages = _load_stage_blocks(plugin_dir / "references" / "gate-criteria.md") + if cwd is not None: + stages.update(_load_stage_blocks(cwd / "pipeline" / "gate-criteria.md")) + result: dict[str, dict] = {} + for stage, criteria in stages.items(): + for c in criteria: cid = c.get("id") if cid: c2 = dict(c) @@ -141,9 +152,9 @@ def _load_lessons(cwd: Path) -> list[dict]: # ---------- explainers ---------- -def _explain_gate(target: str, plugin_dir: Path) -> dict | None: +def _explain_gate(target: str, plugin_dir: Path, cwd: Path | None = None) -> dict | None: """Look up a gate criterion across all stages.""" - all_criteria = _load_all_criteria(plugin_dir) + all_criteria = _load_all_criteria(plugin_dir, cwd) crit = all_criteria.get(target) if not crit: return None @@ -185,12 +196,12 @@ def _explain_lesson_tag(tag: str, cwd: Path, limit: int = 5) -> dict | None: } -def _explain_stage(stage: int, plugin_dir: Path) -> dict | None: +def _explain_stage(stage: int, plugin_dir: Path, cwd: Path | None = None) -> dict | None: """Explain a pipeline stage including its blocker gate count.""" if stage not in STAGE_NAMES: return None info = STAGE_NAMES[stage] - all_criteria = _load_all_criteria(plugin_dir) + all_criteria = _load_all_criteria(plugin_dir, cwd) stage_crits = [c for c in all_criteria.values() if c.get("_stage") == stage] blocker_count = sum(1 for c in stage_crits if c.get("severity") == "blocker") warning_count = sum(1 for c in stage_crits if c.get("severity") != "blocker") @@ -440,11 +451,11 @@ def main(argv: Optional[list[str]] = None) -> int: target = args.target.strip() kind = _classify(target) if kind == "gate": - answer = _explain_gate(target.upper(), plugin_dir) # REQ-WHYCI-001 + answer = _explain_gate(target.upper(), plugin_dir, cwd) # REQ-WHYCI-001 elif kind == "stage": m = _STAGE_PATTERN.match(target) stage_num = int(m.group(1)) if m else None - answer = _explain_stage(stage_num, plugin_dir) if stage_num else None + answer = _explain_stage(stage_num, plugin_dir, cwd) if stage_num else None else: answer = _explain_lesson_tag(target, cwd) diff --git a/tests/unit/test_check_gate.py b/tests/unit/test_check_gate.py index b551f99..889cbf5 100644 --- a/tests/unit/test_check_gate.py +++ b/tests/unit/test_check_gate.py @@ -210,3 +210,105 @@ def test_stage_6_has_build_criteria(self, tmp_path): assert data["stage"] == 6 ids = [d["id"] for d in data["details"]] assert any(i.startswith("G6-") for i in ids) + + +def _write_project_gates(root: Path, body: str) -> None: + (root / "pipeline").mkdir(parents=True, exist_ok=True) + (root / "pipeline" / "gate-criteria.md").write_text(body) + + +PROJECT_STAGE_1 = """# Project gates + +```yaml +stage: 1 +name: srs +criteria: + - id: G1-P01 + description: Project-format requirement present + check: file_contains + args: + path: "pipeline/01-srs/srs.md" + pattern: "\\\\*\\\\*REQ-F-\\\\d{3}\\\\*\\\\*" + severity: blocker +``` +""" + + +class TestProjectOverride: + def test_project_stage_replaces_plugin_criteria(self, tmp_path): + _write_srs(tmp_path / "pipeline", "| **REQ-F-001** | works |\n") + _write_project_gates(tmp_path, PROJECT_STAGE_1) + r = run(["--stage", "1", "--cwd", str(tmp_path), "--plugin-dir", PLUGIN_DIR]) + assert r.returncode == 0, r.stderr + data = json.loads(r.stdout) + assert data["criteria_source"] == "project" + assert [d["id"] for d in data["details"]] == ["G1-P01"] + assert data["details"][0]["passed"] is True + assert data["details"][0]["source"] == "project" + + def test_stage_not_in_project_file_falls_back_to_plugin(self, tmp_path): + _write_project_gates(tmp_path, PROJECT_STAGE_1) + r = run(["--stage", "6", "--cwd", str(tmp_path), "--plugin-dir", PLUGIN_DIR]) + data = json.loads(r.stdout) + assert data["criteria_source"] == "plugin" + assert any(d["id"].startswith("G6-") for d in data["details"]) + + def test_no_project_file_uses_plugin(self, tmp_path): + _write_srs(tmp_path / "pipeline", "REQ-001: works\n") + r = run(["--stage", "1", "--cwd", str(tmp_path), "--plugin-dir", PLUGIN_DIR]) + data = json.loads(r.stdout) + assert data["criteria_source"] == "plugin" + assert any(d["id"] == "G1-001" for d in data["details"]) + + def test_project_script_resolves_in_project_first(self, tmp_path): + (tmp_path / "gates").mkdir() + (tmp_path / "gates" / "ok.py").write_text("import sys\nsys.exit(0)\n") + _write_project_gates(tmp_path, """```yaml +stage: 1 +criteria: + - id: G1-P02 + description: project-local script + check: script_returns_zero + args: { script: "gates/ok.py" } + severity: blocker +``` +""") + r = run(["--stage", "1", "--cwd", str(tmp_path), "--plugin-dir", PLUGIN_DIR]) + assert r.returncode == 0, r.stdout + detail = json.loads(r.stdout)["details"][0] + assert detail["passed"] is True + + def test_project_criteria_can_reuse_plugin_script(self, tmp_path): + _write_srs(tmp_path / "pipeline", "## REQ-001\nShall X.\nAcceptance: X happens.\n") + _write_project_gates(tmp_path, """```yaml +stage: 1 +criteria: + - id: G1-P03 + description: plugin script with project argv + check: script_returns_zero + args: + script: "scripts/check_srs_acceptance.py" + argv: ["pipeline/01-srs/srs.md"] + severity: blocker +``` +""") + r = run(["--stage", "1", "--cwd", str(tmp_path), "--plugin-dir", PLUGIN_DIR]) + assert r.returncode == 0, r.stdout + assert json.loads(r.stdout)["details"][0]["passed"] is True + + def test_missing_project_script_is_inconclusive(self, tmp_path): + _write_project_gates(tmp_path, """```yaml +stage: 1 +criteria: + - id: G1-P04 + description: absent everywhere + check: script_returns_zero + args: { script: "gates/nope.py" } + severity: warning +``` +""") + r = run(["--stage", "1", "--cwd", str(tmp_path), "--plugin-dir", PLUGIN_DIR]) + assert r.returncode == 2 + detail = json.loads(r.stdout)["details"][0] + assert detail["inconclusive"] is True + assert detail["severity"] == "blocker" diff --git a/tests/unit/test_gate_scripts_req_spec.py b/tests/unit/test_gate_scripts_req_spec.py index 77e6e40..6753a47 100644 --- a/tests/unit/test_gate_scripts_req_spec.py +++ b/tests/unit/test_gate_scripts_req_spec.py @@ -53,6 +53,53 @@ def test_srs_acceptance_fail_no_reqs(tmp_path: Path) -> None: assert run("check_srs_acceptance.py", [str(srs)], tmp_path).returncode == 1 + +TABLE_SRS = ( + "| ID | Seed | Requirement | Acceptance conditions |\n" + "|---|---|---|---|\n" + "| **REQ-F-001** | `P1-FR-X-001` | Does X | Given A, when B, then C |\n" + "| **REQ-F-002** | `P1-FR-X-002` | Does Y | — |\n" + "| **REQ-NF-001** | `P1-NFR-PLAT-001` | Fast | Given load, when measured, then p95 < 1s |\n" + "\nREQ-F-002 is referenced in prose here: acceptance is discussed.\n" +) +TABLE_ARGS = [ + "--id-pattern", r"^\|\s*\*\*(REQ-(?:F|NF)-\d{3})\*\*", + "--acceptance-pattern", r"(?i)\bgiven\b.*\bwhen\b.*\bthen\b", + "--row-scoped", +] + + +def test_srs_acceptance_table_rows_flag_missing_row(tmp_path: Path) -> None: + srs = _mkfile(tmp_path, "srs.md", TABLE_SRS) + r = run("check_srs_acceptance.py", [str(srs)] + TABLE_ARGS, tmp_path) + assert r.returncode == 1 + assert "REQ-F-002" in r.stderr + assert "REQ-F-001" not in r.stderr + assert "REQ-NF-001" not in r.stderr + + +def test_srs_acceptance_table_rows_pass(tmp_path: Path) -> None: + srs = _mkfile(tmp_path, "srs.md", + TABLE_SRS.replace("| Does Y | — |", "| Does Y | Given D, when E, then F |")) + r = run("check_srs_acceptance.py", [str(srs)] + TABLE_ARGS, tmp_path) + assert r.returncode == 0, r.stderr + + +def test_srs_acceptance_row_scoped_ignores_prose_after_row(tmp_path: Path) -> None: + # Without --row-scoped the last row's block runs into the prose below it. + srs = _mkfile(tmp_path, "srs.md", + "| **REQ-F-001** | Does X | — |\n\nAcceptance is discussed later.\n") + base = [str(srs), "--id-pattern", r"\*\*(REQ-F-\d{3})\*\*"] + assert run("check_srs_acceptance.py", base, tmp_path).returncode == 0 + assert run("check_srs_acceptance.py", base + ["--row-scoped"], tmp_path).returncode == 1 + + +def test_srs_acceptance_bad_regex(tmp_path: Path) -> None: + srs = _mkfile(tmp_path, "srs.md", "REQ-001 acceptance\n") + r = run("check_srs_acceptance.py", [str(srs), "--id-pattern", "("], tmp_path) + assert r.returncode == 2 + + # ---------- traceability-check.py ---------- def test_traceability_pass(tmp_path: Path) -> None: diff --git a/tests/unit/test_why.py b/tests/unit/test_why.py index 0953b83..b75d718 100644 --- a/tests/unit/test_why.py +++ b/tests/unit/test_why.py @@ -143,6 +143,28 @@ def test_lookup_works_without_format_gate_result(self, tmp_path): assert answer["fix_hint"] == "" assert answer["description"] + def test_project_override_replaces_stage(self, tmp_path): + pd = _make_plugin_dir(tmp_path) + project = tmp_path / "project" + (project / "pipeline").mkdir(parents=True) + (project / "pipeline" / "gate-criteria.md").write_text( + "```yaml\n" + "stage: 1\n" + "criteria:\n" + " - id: G1-P01\n" + " description: Project-format requirement present\n" + " check: file_contains\n" + " severity: blocker\n" + "```\n" + ) + answer = why._explain_gate("G1-P01", pd, project) + assert answer is not None + assert answer["stage"] == 1 + # the overridden stage's plugin criteria no longer apply + assert why._explain_gate("G1-001", pd, project) is None + # other stages still come from the plugin + assert why._explain_gate("G3-001", pd, project) is not None + # ---------- stage explanation ----------