Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
63 changes: 48 additions & 15 deletions forge-opencode/scripts/check-gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,27 +34,60 @@ 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)

for block in blocks:
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():
Expand All @@ -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", [])]
Expand All @@ -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", {})
Expand All @@ -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:
Expand All @@ -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.
Expand All @@ -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,
Expand Down
56 changes: 45 additions & 11 deletions forge-opencode/scripts/check_srs_acceptance.py
Original file line number Diff line number Diff line change
@@ -1,47 +1,81 @@
#!/usr/bin/env python3
"""Gate G1-003: every requirement in the SRS has acceptance criteria.

Usage: check_srs_acceptance.py <srs.md>
Usage: check_srs_acceptance.py <srs.md> [--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 <srs.md>", 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

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()
Expand Down
41 changes: 26 additions & 15 deletions forge-opencode/scripts/why.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,26 +96,37 @@ 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)
except yaml.YAMLError:
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)
Expand All @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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)

Expand Down
9 changes: 9 additions & 0 deletions references/gate-criteria.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

---

Expand Down
Loading
Loading