318 lines
15 KiB
Python
Executable File
318 lines
15 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.
|
|
|
|
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]
|
|
python3 scripts/verify_traceability_gates.py --all
|
|
"""
|
|
|
|
import argparse
|
|
import os
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
# 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, f"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 run_gate_14_1(self, target_iteration: str = None) -> bool:
|
|
"""Gate 14.1: Iteration Definition of Done & Delivery Surface Completeness."""
|
|
print(f"\n{BOLD}{CYAN}=== Executing Gate 14.1: Iteration Definition of Done ==={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"
|
|
|
|
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")
|
|
|
|
# Check Manual QA Deliverables (Dual QA requirement)
|
|
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", "Major",
|
|
f"Generate MANUAL_TESTING_GUIDE.md under 07_test_design/manual_qa/{it_name}/")
|
|
else:
|
|
print(f" {GREEN}✓{RESET} MANUAL_TESTING_GUIDE.md present")
|
|
|
|
# Check Excel workbook directory
|
|
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:
|
|
self.add_finding("G14-006", f"workbooks/*{it_name}*.xlsx", "21-sheet Excel QA Workbook (.xlsx) missing", "Major",
|
|
f"Compile workbook via scripts/generate_manual_qa_workbook.py.")
|
|
else:
|
|
print(f" {GREEN}✓{RESET} Excel QA Workbook present: {workbooks[0].name}")
|
|
|
|
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':<24} | {'Severity':<9} | {'Issue & Action'}{RESET}")
|
|
print("-" * 80)
|
|
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']:<24} | {color}{f['severity']:<9}{RESET} | {f['issue']}")
|
|
print(f"{'':<10} | {'':<24} | {'':<9} | -> Action: {f['action']}")
|
|
print("-" * 80)
|
|
|
|
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 main():
|
|
parser = argparse.ArgumentParser(description="Deterministic Quality Gate Validator (UP-AI v1.2)")
|
|
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("--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 Path(__file__).resolve().parent.parent
|
|
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)
|
|
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)
|
|
|
|
sys.exit(0 if overall_pass else 1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|