Skip to content

Snoozer10/synthesize-skills / .claude/skills/repo-blast-radius-sync

repo-blast-radius-sync

Verified

Use when checking code changes for orphaned callers, outdated tests, or stale documentation, discovering change blast radius, or verifying git staged parity against the dependency registry

scripts/verify_parity.py.bak-20260909-094445

View on GitHub
#!/usr/bin/env python3
"""
Pre-commit Verification Gate for repo-blast-radius-sync.
Analyzes current dirty git status against compiled blast radius definitions.
Enforces strict synchronization to prevent orphaned edits.
"""

import json
import os
import sys
import subprocess
import argparse
from pathlib import Path
from typing import Set, Dict, List, Any
try:
    from blast_radius import BlastRadiusResolver
except ImportError:
    from scripts.blast_radius import BlastRadiusResolver

class ParityVerifier:
    def __init__(self, root_dir: Path, strict_mode: bool = False, staged_only: bool = False):
        self.root_dir = root_dir
        self.resolver = BlastRadiusResolver(root_dir)
        self.strict_mode = strict_mode
        self.staged_only = staged_only

    def get_dirty_git_files(self) -> Set[str]:
        """Obtains changed files in git repo using porcelain command."""
        dirty_files: Set[str] = set()
        try:
            output = subprocess.check_output(
                ["git", "status", "--porcelain"], 
                cwd=str(self.root_dir), 
                stderr=subprocess.DEVNULL
            ).decode("utf-8")
            
            for line in output.splitlines():
                if not line.strip():
                    continue
                
                # Git status porcelain: first two columns represent staged/unstaged state
                staged_indicator = line[0]
                unstaged_indicator = line[1]
                file_path_str = line[3:].strip()
                
                # Handle renamed files 'R old_file -> new_file'
                if " -> " in file_path_str:
                    file_path_str = file_path_str.split(" -> ")[1]

                # Filter staging vs untracked/modified
                if self.staged_only:
                    if staged_indicator in ("M", "A", "D", "R", "C", "T"):
                        dirty_files.add(file_path_str)
                else:
                    if staged_indicator in ("M", "A", "D", "R", "C", "T", "?") or unstaged_indicator in ("M", "A", "D", "R", "C", "T"):
                        dirty_files.add(file_path_str)
        except Exception as e:
            print(f"Warning: Failed to parse git workspace state: {e}", file=sys.stderr)
        return dirty_files

    def verify(self) -> int:
        """Audits dirty files vs their target blast-radius constraints."""
        dirty_files = self.get_dirty_git_files()
        if not dirty_files:
            print("Parity Verification PASSED: Git workspace is fully clean.")
            return 0

        failures: Dict[str, List[Dict[str, str]]] = {}

        for file in dirty_files:
            # Only audit code files (source code edits)
            if not file.endswith((".py", ".js", ".ts", ".go", ".cpp", ".java")):
                continue
                
            radius = self.resolver.resolve(file)
            docs_radius = set(radius["GOVERNING DOCS"])
            tests_radius = set(radius["TEST SUITES"])
            configs_radius = set(radius["CONFIGS/SCHEMAS"])
            callers_radius = set(radius["CODE CALLERS"])

            missing_docs = docs_radius - dirty_files
            missing_tests = tests_radius - dirty_files
            missing_configs = configs_radius - dirty_files
            missing_callers = callers_radius - dirty_files

            file_failures = []
            
            # Non-strict mode enforcement: coupled files defined in annotations must be touched
            if missing_docs:
                for doc in missing_docs:
                    file_failures.append({"file": doc, "type": "GOVERNING DOC", "reason": "Explicit coupling annotation"})
            if missing_tests:
                for test in missing_tests:
                    file_failures.append({"file": test, "type": "TEST SUITE", "reason": "Explicit coupling annotation"})

            # Strict mode enforcement: Caller updates and adjacent config synchronization required
            if self.strict_mode:
                if missing_configs:
                    for cfg in missing_configs:
                        file_failures.append({"file": cfg, "type": "CONFIG/SCHEMA", "reason": "Strict dependency synchronization"})
                if missing_callers:
                    for caller in missing_callers:
                        file_failures.append({"file": caller, "type": "CODE CALLER", "reason": "Strict upstream interface synchronization"})

            # Fallback heuristic: If no tests or docs are explicitly linked, enforce generic directory mappings
            if not docs_radius:
                doc_stem_found = any(f.endswith(".md") and Path(file).stem in f for f in dirty_files)
                if not doc_stem_found and not any(f.startswith("docs/") for f in dirty_files):
                    file_failures.append({"file": f"docs/ or .md matching {Path(file).stem}", "type": "GOVERNING DOC", "reason": "Generic directory mapping"})
            
            if not tests_radius:
                test_stem_found = any(f.startswith("tests/") and Path(file).stem in f for f in dirty_files)
                if not test_stem_found:
                    file_failures.append({"file": f"tests/ matching {Path(file).stem}", "type": "TEST SUITE", "reason": "Generic directory mapping"})

            if file_failures:
                failures[file] = file_failures

        if failures:
            # Construct a structured, machine-readable validation failure block to stderr
            structured_error = {
                "status": "gate_failed",
                "error_code": "ERR_ORPHAN_EDIT_VIOLATION",
                "summary": "Orphaned edits detected in repository! Changes to source code files require synchronized docs/tests.",
                "payload": {
                    "dirty_files": sorted(list(dirty_files)),
                    "failures": {
                        src: [{ "file": f["file"], "type": f["type"], "coupled_via": f["reason"] } for f in flist]
                        for src, flist in failures.items()
                    }
                }
            }
            
            print("=================================================================", file=sys.stderr)
            print("CRITICAL VERIFICATION ERROR: SYSTEMIC ORPHANED EDITS", file=sys.stderr)
            print("=================================================================", file=sys.stderr)
            print(json.dumps(structured_error, indent=2), file=sys.stderr)
            print("=================================================================", file=sys.stderr)
            print("Action Required: Modify or add the missing test/documentation files listed above before completing your task.", file=sys.stderr)
            return 1

        print("Parity Verification PASSED: All blast-radius couplings are fully synchronized.")
        return 0

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Enforce synchronous repository edits across tests and documentation")
    parser.add_argument("--strict", action="store_true", help="Enforce verification across configs and upstream callers")
    parser.add_argument("--staged-only", action="store_true", help="Verify only files staged in git index")
    args = parser.parse_args()

    verifier = ParityVerifier(
        Path(os.getcwd()), 
        strict_mode=args.strict, 
        staged_only=args.staged_only
    )
    sys.exit(verifier.verify())
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 323kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 323kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 323kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 198kUpdated Claude CodeCodexVerifiedInstall