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.
This commit is contained in:
kiskaadee committed 2026-10-08 19:03:50 -05:00
1 parent ca759704f3
commit fc620c7cdc
6 files changed
+134 -50

No files matched your search

@@ -80,7 +80,13 @@ def get_target_text(target_path: Path) -> str:
except (subprocess.SubprocessError, FileNotFoundError): except (subprocess.SubprocessError, FileNotFoundError):
# Fallback to nix-shell pdftotext if needed # Fallback to nix-shell pdftotext if needed
res = subprocess.run( 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, capture_output=True,
text=True, text=True,
check=True, check=True,
@@ -123,7 +129,9 @@ def check_integrity(source_path: Path, target_path: Path) -> tuple[bool, list[st
def main(): 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("source_md", type=Path, help="Path to source Markdown file")
parser.add_argument("target", type=Path, help="Path to target .typ or .pdf file") parser.add_argument("target", type=Path, help="Path to target .typ or .pdf file")
args = parser.parse_args() args = parser.parse_args()
@@ -139,10 +147,15 @@ def main():
passed, missing = check_integrity(args.source_md, args.target) passed, missing = check_integrity(args.source_md, args.target)
if passed: 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) sys.exit(0)
else: 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): for i, m in enumerate(missing, 1):
sample = m[:120] + "..." if len(m) > 120 else m sample = m[:120] + "..." if len(m) > 120 else m
print(f" [{i}] {sample}", file=sys.stderr) print(f" [{i}] {sample}", file=sys.stderr)
+49
View File
@@ -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 <archivos>' 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
+13 -8
View File
@@ -118,11 +118,16 @@ Do not invent missing information.
--- ---
## Coding and Automation Standards ## Coding and Automation Standards
- All scripts must pass the project's configured linting and static-analysis checks. - Si se crea o modifica cualquier archivo Python (`.py`), es obligatorio ejecutar y verificar:
- Changes must not introduce linting or static-analysis violations. 1. Formateo de código: `ruff format <archivos o tools/>`
- Non-trivial behavior should have tests. 2. Linter y análisis estático: `ruff check <archivos o tools/> --fix`
- Use inline documentation when intent is not obvious from the code. 3. Tipado estático: `pyright tools/`
- Document non-obvious workflows, prerequisites, and usage in Markdown. 4. Suite de pruebas: ejecutar los tests correspondientes (e.g. `PYTHONPATH=. python3 <script_de_prueba>`).
- Keep scripts focused and avoid unnecessary abstractions or dependencies. - 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.
- Handle expected errors explicitly. - 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.
- Keep CLI behavior predictable and documented. - 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.
+1 -2
View File
@@ -75,8 +75,7 @@ class IndependentEvidenceAuditor:
if kind == "negative_observation": if kind == "negative_observation":
if identity_status != "not_applicable": if identity_status != "not_applicable":
reasons.append( reasons.append(
"Observación negativa debe tener identity_status: " "Observación negativa debe tener identity_status: 'not_applicable'."
"'not_applicable'."
) )
if candidate.get("matched_anchors"): if candidate.get("matched_anchors"):
reasons.append( reasons.append(
+50 -27
View File
@@ -6,17 +6,22 @@ Tests behavioral robustness and epistemic enforcement across 12 adversarial fixt
2. Correct NIT + different legal name -> hold / ambiguous 2. Correct NIT + different legal name -> hold / ambiguous
3. Historical address -> admit presence + proposed anchor (historical period) 3. Historical address -> admit presence + proposed anchor (historical period)
4. New legal representative -> admit presence + proposed anchor 4. New legal representative -> admit presence + proposed anchor
5. Search snippet vs. underlying page discrepancy -> page governs observation, snippet discarded 5. Search snippet vs. underlying page discrepancy -> page governs observation,
6. Unsupported promotional claim -> source_claims only, rejected if in direct_observations snippet discarded
6. Unsupported promotional claim -> source_claims only,
rejected if in direct_observations
7. Ambiguous local listing -> hold (missing tax_id / domain) 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 9. Negative observation on map platform -> negative_observation, not_applicable identity
10. Contradictory addresses -> contradiction preserved in open_questions 10. Contradictory addresses -> contradiction preserved in open_questions
11. Conflicting proposed anchor -> rejected by orchestrator, not promoted to active 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, 12. Temporal Exploit & Re-entry -> auditor catches 2023 source claimed as 2026,
worker corrects temporal scope, re-enters pending, auditor passes candidate. demotes to hold, worker corrects temporal scope, re-enters pending,
13. Metadata claim without observation -> auditor catches discard claiming tax_id conflict auditor passes candidate.
without empirical NIT in direct_observations, worker remediates to verified anchors. 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 from typing import Any
@@ -81,7 +86,9 @@ class EvidenceAuditor:
): ):
return ( return (
False, 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" return True, "Discard verified by conflicting anchors"
@@ -96,7 +103,8 @@ class EvidenceAuditor:
if candidate.get("matched_anchors"): if candidate.get("matched_anchors"):
return ( return (
False, 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": if candidate.get("confidence") != "negative_scoped":
return ( return (
@@ -112,14 +120,15 @@ class EvidenceAuditor:
if len(matched) < 2: if len(matched) < 2:
return ( return (
False, 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": elif identity_status == "ambiguous":
if disposition != "hold": if disposition != "hold":
return False, "Ambiguous identity must have disposition: hold" return False, "Ambiguous identity must have disposition: hold"
return True, "Ambiguous candidate correctly retained in 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 obs in candidate.get("direct_observations", []):
for promotional_word in [ for promotional_word in [
"líder", "líder",
@@ -130,18 +139,20 @@ class EvidenceAuditor:
if promotional_word in obs.lower(): if promotional_word in obs.lower():
return ( return (
False, 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", "") source_date = raw_source.get("publication_date", "")
relevant_period = candidate.get("relevant_period", "").lower() relevant_period = candidate.get("relevant_period", "").lower()
if source_date and "2023" in source_date: if source_date and "2023" in source_date:
if "2026" in relevant_period or "actual" in relevant_period: 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 ( return (
False, 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) # Check Observation vs Underlying Page (snippet conflict)
@@ -155,7 +166,8 @@ class EvidenceAuditor:
): ):
return ( return (
False, 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" return True, "Admissibility verified"
@@ -246,7 +258,8 @@ def run_all_adversarial_tests():
"PASS (retained in hold, not attributed)" "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 = { c3 = {
"id": "ADV-003", "id": "ADV-003",
"candidate_kind": "presence", "candidate_kind": "presence",
@@ -291,7 +304,8 @@ def run_all_adversarial_tests():
"matched_anchors": ["ANC-002", "ANC-003"], "matched_anchors": ["ANC-002", "ANC-003"],
"proposed_anchors": ["ANC-007"], "proposed_anchors": ["ANC-007"],
"direct_observations": [ "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"} raw4 = {"publication_date": "2023-12-31"}
@@ -339,7 +353,8 @@ def run_all_adversarial_tests():
"audit_status": "pending", "audit_status": "pending",
"conflicting_anchors": ["legal_name"], "conflicting_anchors": ["legal_name"],
"direct_observations": [ "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) passed_good, _ = auditor.audit_candidate(corrected_c5, raw5)
@@ -420,7 +435,8 @@ def run_all_adversarial_tests():
"confidence": "negative_scoped", "confidence": "negative_scoped",
"matched_anchors": [], "matched_anchors": [],
"direct_observations": [ "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, {}) passed, _ = auditor.audit_candidate(c9, {})
@@ -459,11 +475,13 @@ def run_all_adversarial_tests():
"status": "proposed", "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( registry.reconcile_proposed(
"ANC-099", "ANC-099",
accept=False, 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 assert "ANC-099" in registry.rejected and "ANC-099" not in registry.active
results["11. Conflicting proposed anchor"] = ( results["11. Conflicting proposed anchor"] = (
@@ -471,7 +489,8 @@ def run_all_adversarial_tests():
) )
# Fixture 12: THE TEMPORAL EXPLOIT & RE-ENTRY # 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 = { exploit_c12 = {
"id": "ADV-012", "id": "ADV-012",
"candidate_kind": "presence", "candidate_kind": "presence",
@@ -513,7 +532,8 @@ def run_all_adversarial_tests():
) )
assert eligible assert eligible
results["12. Temporal exploit & re-entry"] = ( 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) # 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, {}) passed_bad, reason_bad = auditor.audit_candidate(bad_c13, {})
assert not passed_bad and "metadata claim without observation" in reason_bad.lower() 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 = { remediated_c13 = {
"id": "ADV-013", "id": "ADV-013",
"candidate_kind": "discard", "candidate_kind": "discard",
@@ -540,13 +561,15 @@ def run_all_adversarial_tests():
"audit_status": "pending", "audit_status": "pending",
"conflicting_anchors": ["city", "industry_sector"], "conflicting_anchors": ["city", "industry_sector"],
"direct_observations": [ "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, {}) passed_good, reason_good = auditor.audit_candidate(remediated_c13, {})
assert passed_good and remediated_c13["disposition"] == "discard" assert passed_good and remediated_c13["disposition"] == "discard"
results["13. Metadata claim without observation"] = ( 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 return results
+4 -9
View File
@@ -26,12 +26,10 @@ candidates = [
"Ficha mercantil en Portafolio/eInforma lista a Amc Solutions " "Ficha mercantil en Portafolio/eInforma lista a Amc Solutions "
"Colombia S A S con NIT 9013807700 en Valledupar, Cesar.", "Colombia S A S con NIT 9013807700 en Valledupar, Cesar.",
"Registra número telefónico 3144138478 coincidente con semilla.", "Registra número telefónico 3144138478 coincidente con semilla.",
"Registra dirección física Carrera 14 # 13 C 60, Edificio Ágora, " "Registra dirección física Carrera 14 # 13 C 60, Edificio Ágora, Of. 308.",
"Of. 308.",
], ],
"source_claims": [ "source_claims": [
"Clasifica actividad bajo CIIU 4663 (comercio al por mayor de " "Clasifica actividad bajo CIIU 4663 (comercio al por mayor de materiales).",
"materiales).",
"Estima rango de ventas entre 1.000M y 2.000M COP.", "Estima rango de ventas entre 1.000M y 2.000M COP.",
], ],
}, },
@@ -74,9 +72,7 @@ candidates = [
"id": "SRC-003", "id": "SRC-003",
"candidate_kind": "presence", "candidate_kind": "presence",
"source_class": 1, "source_class": 1,
"source_name": ( "source_name": ("Departamento Administrativo de la Función Pública (SIGEP)"),
"Departamento Administrativo de la Función Pública (SIGEP)"
),
"url": ( "url": (
"https://www.funcionpublica.gov.co/dafpIndexerBHV/hvSigep/" "https://www.funcionpublica.gov.co/dafpIndexerBHV/hvSigep/"
"detallarHV/S2360517-8062-5" "detallarHV/S2360517-8062-5"
@@ -96,8 +92,7 @@ candidates = [
"Hoja de vida pública en SIGEP del Ingeniero de Minas Jose Jorge " "Hoja de vida pública en SIGEP del Ingeniero de Minas Jose Jorge "
"Brochero Herrera (Valledupar) registra experiencia laboral en " "Brochero Herrera (Valledupar) registra experiencia laboral en "
"AMC SOLUTIONS COLOMBIA S.A.S.", "AMC SOLUTIONS COLOMBIA S.A.S.",
"Cargo registrado: INGENIERO DE MINAS, periodo 28/04/2020 a " "Cargo registrado: INGENIERO DE MINAS, periodo 28/04/2020 a 28/04/2021.",
"28/04/2021.",
], ],
"source_claims": [ "source_claims": [
"Declaración juramentada institucional del servidor público en " "Declaración juramentada institucional del servidor público en "