From fc620c7cdca3c6fc30bb3eb36592bbb7dc1d2633 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Thu, 8 Oct 2026 19:03:50 -0500 Subject: [PATCH] ci(compliance): enforce ruff, pyright, and test execution via pre-commit hook and AGENTS protocol - Add tracked Git pre-commit hook (.githooks/pre-commit) executing ruff format, ruff check, pyright, and test suites. - Update AGENTS.md Coding and Automation Standards with mandatory imperative verification steps for Python files. - Wrap long lines and format test_adversarial_contract.py, resolving 70 E501 line-length violations. - Format tools/audit_external_evidence.py, tools/test_audit_candidates.py, and verify_content_integrity.py to ensure full ruff compliance. --- .../scripts/verify_content_integrity.py | 21 ++++- .githooks/pre-commit | 49 ++++++++++++ AGENTS.md | 21 +++-- tools/audit_external_evidence.py | 3 +- tools/test/test_adversarial_contract.py | 77 ++++++++++++------- tools/test_audit_candidates.py | 13 +--- 6 files changed, 134 insertions(+), 50 deletions(-) create mode 100755 .githooks/pre-commit diff --git a/.agents/skills/publish_document/scripts/verify_content_integrity.py b/.agents/skills/publish_document/scripts/verify_content_integrity.py index e646dc7..b439150 100755 --- a/.agents/skills/publish_document/scripts/verify_content_integrity.py +++ b/.agents/skills/publish_document/scripts/verify_content_integrity.py @@ -80,7 +80,13 @@ def get_target_text(target_path: Path) -> str: except (subprocess.SubprocessError, FileNotFoundError): # Fallback to nix-shell pdftotext if needed res = subprocess.run( - ["nix-shell", "-p", "poppler-utils", "--run", f"pdftotext '{target_path}' -"], + [ + "nix-shell", + "-p", + "poppler-utils", + "--run", + f"pdftotext '{target_path}' -", + ], capture_output=True, text=True, check=True, @@ -123,7 +129,9 @@ def check_integrity(source_path: Path, target_path: Path) -> tuple[bool, list[st def main(): - parser = argparse.ArgumentParser(description="Verify content integrity between Markdown source and document target.") + parser = argparse.ArgumentParser( + description="Verify content integrity between Markdown source and document target." + ) parser.add_argument("source_md", type=Path, help="Path to source Markdown file") parser.add_argument("target", type=Path, help="Path to target .typ or .pdf file") args = parser.parse_args() @@ -139,10 +147,15 @@ def main(): passed, missing = check_integrity(args.source_md, args.target) if passed: - print(f"PASS: All content blocks from '{args.source_md.name}' verified in '{args.target.name}'.") + print( + f"PASS: All content blocks from '{args.source_md.name}' verified in '{args.target.name}'." + ) sys.exit(0) else: - print(f"FAIL: {len(missing)} content blocks from '{args.source_md.name}' were not found in '{args.target.name}':", file=sys.stderr) + print( + f"FAIL: {len(missing)} content blocks from '{args.source_md.name}' were not found in '{args.target.name}':", + file=sys.stderr, + ) for i, m in enumerate(missing, 1): sample = m[:120] + "..." if len(m) > 120 else m print(f" [{i}] {sample}", file=sys.stderr) diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..a7d799f --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +set -eo pipefail + +echo "=== [PRE-COMMIT] Verificando calidad de código, análisis estático y pruebas ===" + +# Identificar archivos Python en staged (Added, Copied, Modified) +STAGED_PY=$(git diff --cached --name-only --diff-filter=ACM | grep '\.py$' || true) + +if [ -z "$STAGED_PY" ]; then + echo "[PRE-COMMIT] No hay archivos Python en staged. Procediendo." + exit 0 +fi + +echo "[PRE-COMMIT] Archivos Python en staged:" +echo "$STAGED_PY" + +# 1. Verificación de formato con ruff +echo "[PRE-COMMIT] 1/4 Comprobando formato con ruff..." +if ! ruff format --check $STAGED_PY; then + echo "ERROR: Falló el formato de código. Ejecuta 'ruff format ' antes de commitear." >&2 + exit 1 +fi + +# 2. Verificación de reglas de linting con ruff +echo "[PRE-COMMIT] 2/4 Comprobando reglas de linting con ruff..." +if ! ruff check $STAGED_PY; then + echo "ERROR: Violaciones de linting detectadas con ruff. Corrige los errores o ejecuta 'ruff check --fix'." >&2 + exit 1 +fi + +# 3. Comprobación de tipos con pyright +echo "[PRE-COMMIT] 3/4 Comprobando tipos estáticos con pyright..." +if ! pyright tools/; then + echo "ERROR: Se encontraron errores de tipado con pyright." >&2 + exit 1 +fi + +# 4. Ejecución de pruebas automatizadas +echo "[PRE-COMMIT] 4/4 Ejecutando suite de pruebas..." +if [ -f "tools/test_audit_candidates.py" ]; then + PYTHONPATH=. python3 tools/test_audit_candidates.py +fi + +if [ -f "tools/test/test_adversarial_contract.py" ]; then + PYTHONPATH=. python3 tools/test/test_adversarial_contract.py +fi + +echo "=== [PRE-COMMIT] Todos los checks de linting, tipos y pruebas pasaron correctamente ===" +exit 0 diff --git a/AGENTS.md b/AGENTS.md index ec98a63..2b896e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -118,11 +118,16 @@ Do not invent missing information. --- ## Coding and Automation Standards -- All scripts must pass the project's configured linting and static-analysis checks. -- Changes must not introduce linting or static-analysis violations. -- Non-trivial behavior should have tests. -- Use inline documentation when intent is not obvious from the code. -- Document non-obvious workflows, prerequisites, and usage in Markdown. -- Keep scripts focused and avoid unnecessary abstractions or dependencies. -- Handle expected errors explicitly. -- Keep CLI behavior predictable and documented. +- Si se crea o modifica cualquier archivo Python (`.py`), es obligatorio ejecutar y verificar: + 1. Formateo de código: `ruff format ` + 2. Linter y análisis estático: `ruff check --fix` + 3. Tipado estático: `pyright tools/` + 4. Suite de pruebas: ejecutar los tests correspondientes (e.g. `PYTHONPATH=. python3 `). +- Todo script o modificación debe finalizar con código de salida 0 (sin advertencias ni errores) antes de dar por concluida la tarea o realizar commits. +- El repositorio cuenta con un hook de pre-commit (`.githooks/pre-commit`) que bloquea automáticamente los commits si fallan el formateo, linting, análisis estático o las pruebas. +- El comportamiento no trivial debe contar con pruebas (`tests`). +- Usar documentación en línea cuando la intención no resulte obvia a partir del código. +- Documentar flujos no obvios, prerrequisitos y uso en Markdown. +- Mantener los scripts enfocados y evitar abstracciones o dependencias innecesarias. +- Manejar errores esperados de forma explícita. +- Mantener el comportamiento de la CLI predecible y documentado. diff --git a/tools/audit_external_evidence.py b/tools/audit_external_evidence.py index 2f94044..d121d76 100644 --- a/tools/audit_external_evidence.py +++ b/tools/audit_external_evidence.py @@ -75,8 +75,7 @@ class IndependentEvidenceAuditor: if kind == "negative_observation": if identity_status != "not_applicable": reasons.append( - "Observación negativa debe tener identity_status: " - "'not_applicable'." + "Observación negativa debe tener identity_status: 'not_applicable'." ) if candidate.get("matched_anchors"): reasons.append( diff --git a/tools/test/test_adversarial_contract.py b/tools/test/test_adversarial_contract.py index 745d02f..ea818d2 100644 --- a/tools/test/test_adversarial_contract.py +++ b/tools/test/test_adversarial_contract.py @@ -6,17 +6,22 @@ Tests behavioral robustness and epistemic enforcement across 12 adversarial fixt 2. Correct NIT + different legal name -> hold / ambiguous 3. Historical address -> admit presence + proposed anchor (historical period) 4. New legal representative -> admit presence + proposed anchor -5. Search snippet vs. underlying page discrepancy -> page governs observation, snippet discarded -6. Unsupported promotional claim -> source_claims only, rejected if in direct_observations +5. Search snippet vs. underlying page discrepancy -> page governs observation, + snippet discarded +6. Unsupported promotional claim -> source_claims only, + rejected if in direct_observations 7. Ambiguous local listing -> hold (missing tax_id / domain) -8. Historical government contract -> admit with strict temporal validity, no present-tense leap +8. Historical government contract -> admit with strict temporal validity, + no present-tense leap 9. Negative observation on map platform -> negative_observation, not_applicable identity 10. Contradictory addresses -> contradiction preserved in open_questions 11. Conflicting proposed anchor -> rejected by orchestrator, not promoted to active -12. Temporal Exploit & Re-entry -> auditor catches 2023 source claimed as 2026, demotes to hold, - worker corrects temporal scope, re-enters pending, auditor passes candidate. -13. Metadata claim without observation -> auditor catches discard claiming tax_id conflict - without empirical NIT in direct_observations, worker remediates to verified anchors. +12. Temporal Exploit & Re-entry -> auditor catches 2023 source claimed as 2026, + demotes to hold, worker corrects temporal scope, re-enters pending, + auditor passes candidate. +13. Metadata claim without observation -> auditor catches discard claiming + tax_id conflict without empirical NIT in direct_observations, + worker remediates to verified anchors. """ from typing import Any @@ -81,7 +86,9 @@ class EvidenceAuditor: ): return ( False, - "Metadata claim without observation: 'tax_id' declared in conflicting_anchors but no NIT recorded in direct_observations", + "Metadata claim without observation: 'tax_id' declared in " + "conflicting_anchors but no NIT recorded in " + "direct_observations", ) return True, "Discard verified by conflicting anchors" @@ -96,7 +103,8 @@ class EvidenceAuditor: if candidate.get("matched_anchors"): return ( False, - "Negative observation cannot have matched anchors for an unobserved profile", + "Negative observation cannot have matched anchors for an " + "unobserved profile", ) if candidate.get("confidence") != "negative_scoped": return ( @@ -112,14 +120,15 @@ class EvidenceAuditor: if len(matched) < 2: return ( False, - f"Attribution requires at least 2 anchors, found {len(matched)}", + "Attribution requires at least 2 anchors, " + f"found {len(matched)}", ) elif identity_status == "ambiguous": if disposition != "hold": return False, "Ambiguous identity must have disposition: hold" return True, "Ambiguous candidate correctly retained in hold" - # Check Epistemic Separation: Promotional or third-party claims in direct_observations + # Check Epistemic Separation: Promotional claims in direct_observations for obs in candidate.get("direct_observations", []): for promotional_word in [ "líder", @@ -130,18 +139,20 @@ class EvidenceAuditor: if promotional_word in obs.lower(): return ( False, - f"Unevidenced promotional claim '{promotional_word}' found in direct_observations", + f"Unevidenced promotional claim '{promotional_word}' " + "found in direct_observations", ) - # Check Temporal Validity: Extrapolation of past records to current present state + # Check Temporal Validity: Extrapolation of past records source_date = raw_source.get("publication_date", "") relevant_period = candidate.get("relevant_period", "").lower() if source_date and "2023" in source_date: if "2026" in relevant_period or "actual" in relevant_period: - # Source from 2023 cannot assert current 2026 operational truth without fresh evidence + # 2023 source cannot assert 2026 truth without fresh evidence return ( False, - f"Temporal validity violation: Source dated {source_date} extrapolated to {relevant_period}", + f"Temporal validity violation: Source dated {source_date} " + f"extrapolated to {relevant_period}", ) # Check Observation vs Underlying Page (snippet conflict) @@ -155,7 +166,8 @@ class EvidenceAuditor: ): return ( False, - "Direct observation adopted search snippet rather than underlying page reality", + "Direct observation adopted search snippet rather " + "than underlying page reality", ) return True, "Admissibility verified" @@ -246,7 +258,8 @@ def run_all_adversarial_tests(): "PASS (retained in hold, not attributed)" ) - # Fixture 3: Historical address -> admit presence + proposed anchor with historical period + # Fixture 3: Historical address -> admit presence + proposed anchor + # with historical period c3 = { "id": "ADV-003", "candidate_kind": "presence", @@ -291,7 +304,8 @@ def run_all_adversarial_tests(): "matched_anchors": ["ANC-002", "ANC-003"], "proposed_anchors": ["ANC-007"], "direct_observations": [ - "Acta municipal registra a Ledys del Rosario Martínez Lara como representante legal" + "Acta municipal registra a Ledys del Rosario Martínez Lara " + "como representante legal" ], } raw4 = {"publication_date": "2023-12-31"} @@ -339,7 +353,8 @@ def run_all_adversarial_tests(): "audit_status": "pending", "conflicting_anchors": ["legal_name"], "direct_observations": [ - "La página de destino corresponde a Servicios Mineros de Colombia S.A., no a AMC Solutions" + "La página de destino corresponde a Servicios Mineros de Colombia S.A., " + "no a AMC Solutions" ], } passed_good, _ = auditor.audit_candidate(corrected_c5, raw5) @@ -420,7 +435,8 @@ def run_all_adversarial_tests(): "confidence": "negative_scoped", "matched_anchors": [], "direct_observations": [ - "En la muestra de búsqueda en Google Maps no se observó perfil comercial verificado" + "En la muestra de búsqueda en Google Maps no se observó perfil " + "comercial verificado" ], } passed, _ = auditor.audit_candidate(c9, {}) @@ -459,11 +475,13 @@ def run_all_adversarial_tests(): "status": "proposed", } ) - # Orchestrator detects conflicting area code (+57 4 is Medellín, competitor conflict) + # Orchestrator detects conflicting area code (+57 4 is Medellín conflict) registry.reconcile_proposed( "ANC-099", accept=False, - rejection_reason="Conflicto de jurisdicción y homonimia con competidor en Medellín", + rejection_reason=( + "Conflicto de jurisdicción y homonimia con competidor en Medellín" + ), ) assert "ANC-099" in registry.rejected and "ANC-099" not in registry.active results["11. Conflicting proposed anchor"] = ( @@ -471,7 +489,8 @@ def run_all_adversarial_tests(): ) # Fixture 12: THE TEMPORAL EXPLOIT & RE-ENTRY - # Worker correctly attributes entity, but fraudulently or carelessly sets relevant_period to 'actual 2026' on a 2023 source! + # Worker attributes entity, but carelessly sets relevant_period + # to 'actual 2026' on a 2023 source! exploit_c12 = { "id": "ADV-012", "candidate_kind": "presence", @@ -513,7 +532,8 @@ def run_all_adversarial_tests(): ) assert eligible results["12. Temporal exploit & re-entry"] = ( - "PASS (auditor caught 2026 leap, demoted to hold; worker repaired, re-entered, passed audit)" + "PASS (auditor caught 2026 leap, demoted to hold; " + "worker repaired, re-entered, passed audit)" ) # Fixture 13: Metadata claim without observation (DISC-001 regression fixture) @@ -531,7 +551,8 @@ def run_all_adversarial_tests(): passed_bad, reason_bad = auditor.audit_candidate(bad_c13, {}) assert not passed_bad and "metadata claim without observation" in reason_bad.lower() - # Re-entry: Worker remediates by grounding discard strictly on verifiable conflicting anchors (city, sector) + # Re-entry: Worker remediates by grounding discard strictly on + # verifiable conflicting anchors (city, sector) remediated_c13 = { "id": "ADV-013", "candidate_kind": "discard", @@ -540,13 +561,15 @@ def run_all_adversarial_tests(): "audit_status": "pending", "conflicting_anchors": ["city", "industry_sector"], "direct_observations": [ - "Ficha mercantil en Bogotá (Calle 74) con actividad CIIU 7730 (alquiler de maquinaria)" + "Ficha mercantil en Bogotá (Calle 74) con actividad " + "CIIU 7730 (alquiler de maquinaria)" ], } passed_good, reason_good = auditor.audit_candidate(remediated_c13, {}) assert passed_good and remediated_c13["disposition"] == "discard" results["13. Metadata claim without observation"] = ( - "PASS (auditor caught unsupported tax_id assertion; remediated to verified anchors)" + "PASS (auditor caught unsupported tax_id assertion; " + "remediated to verified anchors)" ) return results diff --git a/tools/test_audit_candidates.py b/tools/test_audit_candidates.py index 7c69aec..3c8acd2 100644 --- a/tools/test_audit_candidates.py +++ b/tools/test_audit_candidates.py @@ -26,12 +26,10 @@ candidates = [ "Ficha mercantil en Portafolio/eInforma lista a Amc Solutions " "Colombia S A S con NIT 9013807700 en Valledupar, Cesar.", "Registra número telefónico 3144138478 coincidente con semilla.", - "Registra dirección física Carrera 14 # 13 C 60, Edificio Ágora, " - "Of. 308.", + "Registra dirección física Carrera 14 # 13 C 60, Edificio Ágora, Of. 308.", ], "source_claims": [ - "Clasifica actividad bajo CIIU 4663 (comercio al por mayor de " - "materiales).", + "Clasifica actividad bajo CIIU 4663 (comercio al por mayor de materiales).", "Estima rango de ventas entre 1.000M y 2.000M COP.", ], }, @@ -74,9 +72,7 @@ candidates = [ "id": "SRC-003", "candidate_kind": "presence", "source_class": 1, - "source_name": ( - "Departamento Administrativo de la Función Pública (SIGEP)" - ), + "source_name": ("Departamento Administrativo de la Función Pública (SIGEP)"), "url": ( "https://www.funcionpublica.gov.co/dafpIndexerBHV/hvSigep/" "detallarHV/S2360517-8062-5" @@ -96,8 +92,7 @@ candidates = [ "Hoja de vida pública en SIGEP del Ingeniero de Minas Jose Jorge " "Brochero Herrera (Valledupar) registra experiencia laboral en " "AMC SOLUTIONS COLOMBIA S.A.S.", - "Cargo registrado: INGENIERO DE MINAS, periodo 28/04/2020 a " - "28/04/2021.", + "Cargo registrado: INGENIERO DE MINAS, periodo 28/04/2020 a 28/04/2021.", ], "source_claims": [ "Declaración juramentada institucional del servidor público en "