c_agri_trade/process/scripts/verify_traceability_gates.py

518 lines
27 KiB
Python
Executable File

#!/usr/bin/env python3
"""Deterministic Quality Gate & Traceability Validator for AI-Native Unified Process.
Enforces SEI-CMMI Level 3 quality gate criteria (Gates 5.1, 9.1, 14.1) deterministically
without relying on probabilistic LLM self-evaluation. Hardened per UP-AI v1.4 against
superficial completions (Goodhart's Law): enforces semantic density, workbook row counts (>=20),
Bruno API collection completeness, and 4-dimension functional test models.
Usage:
python3 scripts/verify_traceability_gates.py --gate 5.1
python3 scripts/verify_traceability_gates.py --gate 9.1
python3 scripts/verify_traceability_gates.py --gate 14.1 [--iteration iteration-01] [--run-tests]
python3 scripts/verify_traceability_gates.py --all [--run-tests]
"""
import argparse
import os
import re
import subprocess
import sys
import xml.etree.ElementTree as ET
import zipfile
from pathlib import Path
try:
import openpyxl
HAS_OPENPYXL = True
except ImportError:
HAS_OPENPYXL = False
# ANSI colors
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
CYAN = "\033[96m"
BOLD = "\033[1m"
RESET = "\033[0m"
class QualityGateValidator:
def __init__(self, repo_root: Path):
self.repo_root = repo_root
self.doc_root = repo_root / "04_generated_documentation"
self.requirements_dir = self.doc_root / "03_requirements"
self.architecture_dir = self.doc_root / "04_architecture_design"
self.planning_dir = self.doc_root / "05_iteration_planning"
self.test_design_dir = self.doc_root / "07_test_design"
self.process_control_dir = self.doc_root / "00_process_control"
self.traceability_graph = self.process_control_dir / "traceability_graph.md"
self.findings = [] # list of dicts: {"check_id", "target", "issue", "severity", "action"}
def add_finding(self, check_id: str, target: str, issue: str, severity: str, action: str):
self.findings.append({
"check_id": check_id,
"target": target,
"issue": issue,
"severity": severity, # Critical, Major, Minor
"action": action,
})
def collect_use_cases_and_frs(self):
"""Scans 03_requirements/use_cases/ and discovers all UC-xxx and child FR-xxx."""
uc_dict = {} # {uc_id: {"name": ..., "dir": ..., "frs": []}}
fr_dict = {} # {fr_id: {"parent_uc": ..., "source_brd": ..., "file": ...}}
uc_dir = self.requirements_dir / "use_cases"
if not uc_dir.exists():
return uc_dict, fr_dict
for entry in sorted(uc_dir.iterdir()):
if entry.is_dir():
uc_match = re.match(r"(uc-\d{3})", entry.name, re.IGNORECASE)
uc_id = uc_match.group(1).upper() if uc_match else entry.name.upper()
# Parse use-case.md if present
uc_file = entry / "use-case.md"
uc_name = entry.name
if uc_file.exists():
text = uc_file.read_text(encoding="utf-8")
title_m = re.search(r"#\s+(UC-\d{3}:\s*[^#\n]+)", text)
if title_m:
uc_name = title_m.group(1).strip()
id_m = re.search(r"\*\*Use Case ID\*\*\s*\|\s*`?(UC-\d{3})`?", text, re.IGNORECASE)
if id_m:
uc_id = id_m.group(1).upper()
uc_dict[uc_id] = {
"name": uc_name,
"path": entry,
"frs": []
}
# Parse functional-reqs.md
fr_file = entry / "functional-reqs.md"
if fr_file.exists():
fr_text = fr_file.read_text(encoding="utf-8")
fr_blocks = re.split(r"\n(?=##\s+FR-)", fr_text)
for block in fr_blocks:
fr_id_m = re.search(r"##\s+(FR-[A-Z0-9_\-]+)", block)
if not fr_id_m:
fr_id_m = re.search(r"\*\*Requirement ID:\*\*\s*`?(FR-[A-Z0-9_\-]+)`?", block)
if fr_id_m:
fr_id = fr_id_m.group(1).strip().upper()
parent_uc_m = re.search(r"\*\*Parent Use Case:\*\*\s*\[?`?(UC-\d{3})`?", block, re.IGNORECASE)
parent_uc = parent_uc_m.group(1).upper() if parent_uc_m else uc_id
source_brd_m = re.search(r"\*\*Source Feature:\*\*\s*`?([A-Z0-9_\-]+)`?", block)
source_brd = source_brd_m.group(1) if source_brd_m else None
fr_dict[fr_id] = {
"parent_uc": parent_uc,
"source_brd": source_brd,
"file": fr_file
}
uc_dict[uc_id]["frs"].append(fr_id)
return uc_dict, fr_dict
def run_gate_5_1(self) -> bool:
"""Gate 5.1: UC <-> FR Completeness & Orphan Check."""
print(f"\n{BOLD}{CYAN}=== Executing Gate 5.1: UC ↔ FR Completeness & Integrity ==={RESET}")
uc_dict, fr_dict = self.collect_use_cases_and_frs()
if not uc_dict:
self.add_finding("G51-000", "03_requirements/use_cases", "No use case directories found", "Critical",
"Author at least one use case via up-use-case-author before exiting Stage 5.")
return False
# Rule 1: Every UC must have at least one FR
for uc_id, uc_data in uc_dict.items():
if not uc_data["frs"]:
self.add_finding("G51-001", uc_id, "Use case has 0 functional requirement (FR) children", "Critical",
f"Add at least one FR-xxx under {uc_data['path']}/functional-reqs.md")
else:
print(f" {GREEN}✓{RESET} {BOLD}{uc_id}{RESET} has {len(uc_data['frs'])} children: {', '.join(uc_data['frs'])}")
# Rule 2: Every FR's parent_uc must resolve to an existing UC
for fr_id, fr_data in fr_dict.items():
parent_uc = fr_data["parent_uc"]
if parent_uc not in uc_dict:
self.add_finding("G51-002", fr_id, f"Parent use case '{parent_uc}' does not exist", "Critical",
f"Update {fr_data['file']} to point parent_uc to a valid existing UC-xxx.")
# Rule 3: Check source BRD traceability
if not fr_data["source_brd"]:
self.add_finding("G51-003", fr_id, "Missing Source Feature (BRD-FR reference)", "Major",
f"Declare source BRD feature or provide 'new — not in BRD' justification in {fr_data['file']}.")
return self.evaluate_findings("Gate 5.1")
def run_gate_9_1(self) -> bool:
"""Gate 9.1: FR <-> SRS <-> HLD <-> LLD Completeness."""
print(f"\n{BOLD}{CYAN}=== Executing Gate 9.1: FR ↔ SRS ↔ HLD ↔ LLD Architecture Completeness ==={RESET}")
uc_dict, fr_dict = self.collect_use_cases_and_frs()
if not fr_dict:
self.add_finding("G91-000", "Requirements", "No functional requirements found to check against architecture", "Critical",
"Complete Stage 5 (use cases and functional requirements) first.")
return False
# Parse LLD directory for FR mappings
lld_dir = self.architecture_dir / "lld"
lld_fr_coverage = set()
lld_components = set()
if lld_dir.exists():
for lld_file in lld_dir.glob("*.md"):
text = lld_file.read_text(encoding="utf-8")
found_frs = re.findall(r"FR-[A-Z0-9_\-]+", text)
for f in found_frs:
lld_fr_coverage.add(f.upper())
comp_m = re.search(r"\*\*Component\*\*\s*\|\s*`?([A-Z0-9_\-]+)`?", text)
if comp_m:
lld_components.add(comp_m.group(1))
# Parse traceability graph for SRS, HLD, LLD links
graph_text = ""
if self.traceability_graph.exists():
graph_text = self.traceability_graph.read_text(encoding="utf-8")
for fr_id in fr_dict.keys():
has_srs = bool(re.search(rf"{fr_id}.*?SRS-[A-Z0-9_\-]+", graph_text) or
re.search(rf"SRS-[A-Z0-9_\-]+.*?{fr_id}", graph_text) or
f"SRS-{fr_id.replace('FR-', '')}" in graph_text)
has_lld = (fr_id in lld_fr_coverage) or bool(re.search(rf"{fr_id}.*?LLD-[A-Z0-9_\-]+", graph_text))
has_hld = bool(re.search(rf"{fr_id}.*?HLD-[A-Z0-9_\-]+", graph_text) or
re.search(r"HLD-[A-Z0-9_\-]+", graph_text))
if not has_srs:
self.add_finding("G91-001", fr_id, "FR does not resolve to any SRS/NFR specification", "Critical",
f"Derive system requirement (SRS-xxx) for {fr_id} in Stage 8 before Gate 9.1.")
if not has_hld:
self.add_finding("G91-002", fr_id, "FR does not resolve to an owning HLD component", "Critical",
f"Map {fr_id} to an HLD service in 04_architecture_design/hld.md.")
if not has_lld:
self.add_finding("G91-003", fr_id, "FR does not resolve to an LLD contract (API/Table/Event)", "Critical",
f"Include {fr_id} in Parent FRs of an LLD document under 04_architecture_design/lld/.")
if has_srs and has_hld and has_lld:
print(f" {GREEN}✓{RESET} {BOLD}{fr_id}{RESET} resolved to SRS + HLD + LLD contracts.")
return self.evaluate_findings("Gate 9.1")
def inspect_workbook_density(self, wb_path: Path) -> int:
"""Inspects Excel workbook density and returns total number of populated test cases."""
if HAS_OPENPYXL:
try:
wb = openpyxl.load_workbook(wb_path, data_only=True, read_only=True)
if "Execution Summary" in wb.sheetnames:
ws = wb["Execution Summary"]
for row in ws.iter_rows(values_only=True):
if row and str(row[0]).strip().upper() == "TOTAL":
try:
return int(row[1])
except (ValueError, TypeError):
pass
total_cases = 0
for sheet_name in wb.sheetnames:
if sheet_name.endswith("_Testcase"):
ws = wb[sheet_name]
rows = list(ws.iter_rows(values_only=True))
if len(rows) > 1:
total_cases += len([r for r in rows[1:] if any(r[:5]) and str(r[0]).strip() not in ("", "Test Case ID")])
return total_cases
except Exception:
pass
# Zero-dependency zipfile + XML fallback
try:
with zipfile.ZipFile(wb_path, "r") as zf:
wb_xml = zf.read("xl/workbook.xml")
root = ET.fromstring(wb_xml)
ns = {"ns": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"}
sheets = root.findall(".//ns:sheet", ns)
sheet_map = {s.attrib.get("name"): s.attrib.get("sheetId") for s in sheets}
if "Execution Summary" in sheet_map:
sheet_id = sheet_map["Execution Summary"]
sheet_file = f"xl/worksheets/sheet{sheet_id}.xml"
if sheet_file in zf.namelist():
sh_root = ET.fromstring(zf.read(sheet_file))
for row in sh_root.findall(".//ns:row", ns):
cells = [c.find(".//ns:t", ns).text for c in row.findall("ns:c", ns) if c.find(".//ns:t", ns) is not None]
if cells and cells[0].strip().upper() == "TOTAL":
try:
return int(cells[1])
except (ValueError, TypeError):
pass
total_cases = 0
for sh_name, sh_id in sheet_map.items():
if sh_name.endswith("_Testcase"):
sh_file = f"xl/worksheets/sheet{sh_id}.xml"
if sh_file in zf.namelist():
sh_root = ET.fromstring(zf.read(sh_file))
rows = sh_root.findall(".//ns:row", ns)
if len(rows) > 1:
total_cases += (len(rows) - 1)
return total_cases
except Exception:
return 0
def run_gate_14_1(self, target_iteration: str = None, run_tests: bool = False) -> bool:
"""Gate 14.1: Iteration Definition of Done, Delivery Surface & Semantic Density Verification."""
print(f"\n{BOLD}{CYAN}=== Executing Gate 14.1: Iteration Definition of Done & Density Validation ==={RESET}")
iter_dir = self.planning_dir / "iterations"
if not iter_dir.exists():
self.add_finding("G14-000", "05_iteration_planning", "No iterations found", "Critical",
"Plan the iteration via up-iteration-plan before running Gate 14.1.")
return False
iterations = [d for d in iter_dir.iterdir() if d.is_dir() and d.name.startswith("iteration-")]
if target_iteration:
iterations = [d for d in iterations if d.name == target_iteration]
if not iterations:
self.add_finding("G14-001", target_iteration, f"Target iteration '{target_iteration}' directory not found", "Critical",
f"Ensure 05_iteration_planning/iterations/{target_iteration} exists.")
return False
for it in sorted(iterations):
it_name = it.name
print(f"\n Checking {BOLD}{it_name}{RESET}:")
plan_file = it / "iteration_plan.md"
backlog_file = it / "iteration_backlog.md"
surface_file = it / "iteration_surface_matrix.md"
# 1. Structural Files Check
if not plan_file.exists():
self.add_finding("G14-002", f"{it_name}/iteration_plan.md", "Iteration plan missing", "Critical", "Run up-iteration-plan.")
else:
print(f" {GREEN}✓{RESET} iteration_plan.md present")
if not backlog_file.exists():
self.add_finding("G14-003", f"{it_name}/iteration_backlog.md", "Iteration backlog missing", "Critical", "Run up-iteration-plan.")
else:
print(f" {GREEN}✓{RESET} iteration_backlog.md present")
if not surface_file.exists():
self.add_finding("G14-004", f"{it_name}/iteration_surface_matrix.md", "Delivery surface matrix missing", "Critical", "Generate surface matrix.")
else:
print(f" {GREEN}✓{RESET} iteration_surface_matrix.md present")
# 2. Check Manual QA Guide (Mandatory Deliverable)
manual_guide = self.test_design_dir / "manual_qa" / it_name / "MANUAL_TESTING_GUIDE.md"
if not manual_guide.exists():
self.add_finding("G14-005", f"manual_qa/{it_name}/MANUAL_TESTING_GUIDE.md", "Manual Testing Guide missing", "Critical",
f"Generate MANUAL_TESTING_GUIDE.md under 07_test_design/manual_qa/{it_name}/")
else:
print(f" {GREEN}✓{RESET} MANUAL_TESTING_GUIDE.md present")
# 3. Check Excel QA Workbook Presence & Semantic Density (>=20 test cases)
workbooks_dir = self.test_design_dir / "manual_qa" / "workbooks"
workbooks = list(workbooks_dir.glob(f"*{it_name}*.xlsx")) if workbooks_dir.exists() else []
if not workbooks:
# Also check with normalized iteration tag, e.g. Iteration01
it_clean = re.sub(r"[^0-9]", "", it_name)
workbooks = list(workbooks_dir.glob(f"*Iteration{it_clean}*.xlsx")) if workbooks_dir.exists() else []
if not workbooks:
self.add_finding("G14-006", f"workbooks/*{it_name}*.xlsx", "21-sheet Excel QA Workbook (.xlsx) missing", "Critical",
f"Compile workbook via scripts/generate_manual_qa_workbook.py --iteration {it_name}.")
else:
wb_file = workbooks[0]
total_cases = self.inspect_workbook_density(wb_file)
if total_cases < 20:
self.add_finding("G14-007", wb_file.name,
f"Excel QA Workbook has insufficient test density: {total_cases} test cases found (< 20 required threshold). Zero-row or stub workbooks violate UP-AI anti-placeholder rules.",
"Critical",
f"Recompile {wb_file.name} with >=20 test cases via scripts/generate_manual_qa_workbook.py.")
else:
print(f" {GREEN}✓{RESET} Excel QA Workbook present: {wb_file.name} (Dense: {total_cases} test cases >= 20 threshold)")
# 4. Bruno API Collections Check
declared_endpoints = []
if surface_file.exists():
surface_text = surface_file.read_text(encoding="utf-8")
# Look for lines with API Endpoint column (HTTP method or path)
for line in surface_text.splitlines():
parts = [p.strip() for p in line.split("|")]
if len(parts) >= 6:
api_col = parts[5]
if any(api_col.startswith(m) for m in ["GET", "POST", "PUT", "DELETE", "PATCH"]) or "/api/" in api_col:
declared_endpoints.append(api_col)
if declared_endpoints:
bruno_dirs = [
self.repo_root / "docs" / "api" / "bruno",
self.repo_root / "05_implementation_workspace" / "docs" / "api" / "bruno",
self.repo_root / "docs" / "bruno",
]
found_bru_files = []
for b_dir in bruno_dirs:
if b_dir.exists():
found_bru_files.extend(list(b_dir.rglob("*.bru")))
if not found_bru_files:
self.add_finding("G14-008", f"{it_name} Bruno Collections",
f"API endpoints declared in surface matrix ({len(declared_endpoints)} endpoints) but zero .bru files found under docs/api/bruno/.",
"Critical",
"Create git-versioned Bruno collections (.bru) in docs/api/bruno/ for declared API surfaces.")
else:
print(f" {GREEN}✓{RESET} Bruno API Collections verified ({len(found_bru_files)} .bru files for {len(declared_endpoints)} declared endpoints)")
# 5. Functional Test Model & 4-Dimension Coverage Check
in_scope_ucs = set()
if backlog_file.exists():
bl_text = backlog_file.read_text(encoding="utf-8")
in_scope_ucs.update(re.findall(r"UC-\d{3}", bl_text, re.IGNORECASE))
if surface_file.exists():
sf_text = surface_file.read_text(encoding="utf-8")
in_scope_ucs.update(re.findall(r"UC-\d{3}", sf_text, re.IGNORECASE))
if plan_file.exists():
pl_text = plan_file.read_text(encoding="utf-8")
in_scope_ucs.update(re.findall(r"UC-\d{3}", pl_text, re.IGNORECASE))
for uc_id in sorted(in_scope_ucs):
uc_clean = uc_id.upper()
uc_num = re.sub(r"[^0-9]", "", uc_clean)
tc_candidates = list((self.test_design_dir / "functional_test_cases").glob(f"TC-*{uc_num}*.md"))
if not tc_candidates:
self.add_finding("G14-009", f"functional_test_cases/TC-*{uc_num}*.md",
f"Missing functional test model TC-xxx file for in-scope use case {uc_clean}.",
"Critical",
f"Author TC-xxx test model under 07_test_design/functional_test_cases/ for {uc_clean}.")
else:
tc_file = tc_candidates[0]
tc_content = tc_file.read_text(encoding="utf-8").lower()
# Assert all 4 dimensions: Happy, Boundary, Negative, FSM Invariant
has_happy = bool(re.search(r"happy|functional", tc_content))
has_boundary = bool(re.search(r"boundary|edge", tc_content))
has_negative = bool(re.search(r"negative|security|rejection|fail", tc_content))
has_invariant = bool(re.search(r"invariant|fsm|lifecycle|concurrency", tc_content))
missing_dims = []
if not has_happy: missing_dims.append("Happy Path")
if not has_boundary: missing_dims.append("Boundary/Edge")
if not has_negative: missing_dims.append("Negative/Security")
if not has_invariant: missing_dims.append("FSM Invariant")
if missing_dims:
self.add_finding("G14-010", tc_file.name,
f"Functional test model lacks required test dimensions: missing {', '.join(missing_dims)}. All 4 dimensions are mandatory.",
"Critical",
f"Flesh out missing test dimensions in {tc_file.name}.")
else:
print(f" {GREEN}✓{RESET} Functional Test Model {tc_file.name} verified (all 4 dimensions present)")
# 6. Automated Test Runner Execution (if requested or enabled)
if run_tests:
test_script = self.repo_root / "scripts" / "run_tests.sh"
if test_script.exists():
print(f" Running automated test suite: scripts/run_tests.sh --scope {it_name} ...")
try:
res = subprocess.run(["bash", str(test_script), "--scope", it_name],
cwd=self.repo_root, capture_output=True, text=True)
if res.returncode != 0:
self.add_finding("G14-011", f"{it_name} Automated Tests",
f"scripts/run_tests.sh --scope {it_name} failed with exit code {res.returncode}.",
"Critical",
"Fix failing automated tests before closing Gate 14.1.")
else:
print(f" {GREEN}✓{RESET} Automated tests executed and passed cleanly.")
except Exception as e:
self.add_finding("G14-011", f"{it_name} Automated Tests",
f"Failed to execute scripts/run_tests.sh: {str(e)}",
"Critical", "Ensure scripts/run_tests.sh is executable and tests pass.")
# 7. Traceability Status Progression Check
if self.traceability_graph.exists():
tg_text = self.traceability_graph.read_text(encoding="utf-8")
# Detect premature status inflation (e.g. plain 'Delivered' without E2E verification)
premature_delivered = re.findall(r"\| `(FR-[A-Z0-9_\-]+)` \|.*?\| Delivered \|", tg_text)
if premature_delivered:
self.add_finding("G14-012", "traceability_graph.md",
f"Found premature 'Delivered' status without granular verification state: {', '.join(premature_delivered)}. Must use 'Implemented (Domain/Schema)' or 'Delivered (E2E Verified)'.",
"Major",
"Update traceability_graph.md to use granular requirement lifecycle states.")
return self.evaluate_findings("Gate 14.1")
def evaluate_findings(self, gate_name: str) -> bool:
"""Summarizes findings and returns True if zero Critical issues."""
criticals = [f for f in self.findings if f["severity"] == "Critical"]
majors = [f for f in self.findings if f["severity"] == "Major"]
minors = [f for f in self.findings if f["severity"] == "Minor"]
print(f"\n{BOLD}Gate Assessment Summary for {gate_name}:{RESET}")
print(f" Critical Issues (Blocking): {RED}{len(criticals)}{RESET}")
print(f" Major Issues: {YELLOW}{len(majors)}{RESET}")
print(f" Minor Issues: {len(minors)}")
if self.findings:
print(f"\n{BOLD}{'Check-ID':<10} | {'Target':<30} | {'Severity':<9} | {'Issue & Action'}{RESET}")
print("-" * 88)
for f in self.findings:
color = RED if f["severity"] == "Critical" else (YELLOW if f["severity"] == "Major" else RESET)
print(f"{f['check_id']:<10} | {f['target']:<30} | {color}{f['severity']:<9}{RESET} | {f['issue']}")
print(f"{'':<10} | {'':<30} | {'':<9} | -> Action: {f['action']}")
print("-" * 88)
if criticals:
print(f"\n{RED}{BOLD}❌ {gate_name} FAILED: Critical issues must be resolved before proceeding.{RESET}\n")
return False
elif majors:
print(f"\n{YELLOW}{BOLD}⚠️ {gate_name} PASSED WITH WARNINGS: Zero critical issues, but major issues should be reviewed.{RESET}\n")
return True
else:
print(f"\n{GREEN}{BOLD}✅ {gate_name} PASSED: All referential integrity criteria met.{RESET}\n")
return True
def find_repo_root(start_file: Path) -> Path:
curr = start_file.resolve().parent
for p in [curr] + list(curr.parents):
if (p / "04_generated_documentation").exists() or (p / "tech-profile.yaml").exists():
return p
return start_file.resolve().parent.parent
def main():
parser = argparse.ArgumentParser(description="Deterministic Quality Gate Validator (UP-AI v1.5)")
parser.add_argument("--gate", choices=["5.1", "9.1", "14.1"], help="Specific gate to validate")
parser.add_argument("--iteration", default=None, help="Target iteration for Gate 14.1 (e.g. iteration-01)")
parser.add_argument("--run-tests", action="store_true", help="Execute automated test runner during Gate 14.1 validation")
parser.add_argument("--all", action="store_true", help="Run all available quality gates")
parser.add_argument("--repo-root", default=None, help="Path to repository root")
args = parser.parse_args()
repo_root = Path(args.repo_root) if args.repo_root else find_repo_root(Path(__file__))
validator = QualityGateValidator(repo_root)
overall_pass = True
if args.all or not args.gate:
g5_pass = validator.run_gate_5_1()
validator.findings = []
g9_pass = validator.run_gate_9_1()
validator.findings = []
g14_pass = validator.run_gate_14_1(args.iteration, run_tests=args.run_tests)
overall_pass = g5_pass and g9_pass and g14_pass
elif args.gate == "5.1":
overall_pass = validator.run_gate_5_1()
elif args.gate == "9.1":
overall_pass = validator.run_gate_9_1()
elif args.gate == "14.1":
overall_pass = validator.run_gate_14_1(args.iteration, run_tests=args.run_tests)
sys.exit(0 if overall_pass else 1)
if __name__ == "__main__":
main()