Auditeur de contrats API (L3)

VérifiéSûr

Audite les contrats API, les signatures de méthodes, les fuites de couches et la cohérence des contrats d'erreur.

Spar Skills Guide Bot
DeveloppementAvancé
23/07/2026
Claude Code
#api-contracts#architecture-audit#dto#layer-boundaries#code-review

Recommandé pour

Synthèse automatique

Ce worker L3 audite les contrats d'API aux frontières de service : fuites de couches, DTO manquants, entités exposées et incohérences de contrats d'erreur, avec un rapport de scores structuré.

Points forts

  • Six règles de détection explicites (fuite de couche, DTO manquant, fuite d'entité, contrats d'erreur, surcharges redondantes, honnêteté architecturale) avec niveaux de sévérité gradués
  • Détection à deux couches : scan de candidats par Grep, puis vérification contextuelle pour limiter les faux positifs
  • Découverte automatique des frontières API/service/domaine et cartographie des appels endpoint vers service
  • Fonctionne en mode global ou domain-aware, et signale explicitement le repli sur Read/Grep/Glob si les MCP hex-graph/hex-line sont indisponibles

Limites

  • Ne couvre que les frontières d'architecture : la duplication de code est explicitement hors périmètre
  • Dépend de références externes (detection_patterns.md, two_layer_detection.md) propres au dépôt du skill
  • Les patterns de détection sont spécifiques à un langage donné dans les références, ce qui peut laisser des angles morts sur d'autres stacks
  • Produit une analyse et des scores, pas de correctifs automatiques
Quand l'utiliser

À utiliser lors d'une revue d'architecture pour vérifier qu'une couche API respecte ses frontières et n'expose pas ses entités internes.

Quand l'éviter

À éviter si vous cherchez à détecter de la duplication de code ou à obtenir des corrections appliquées automatiquement.

Analyse de sécurité

Sûr
Score qualité78/100

The skill is a read-only static-analysis auditor for API contract boundaries. It enumerates Glob/Grep/symbol-lookup steps and writes a JSON/markdown report to a run-scoped artifact directory. Bash is permitted but never tied to a destructive or outbound operation, and there is no instruction to run downloaded code, touch secrets, or bypass guardrails. Risk is limited to ordinary codebase reading.

Points d'attention
  • •Bash is in allowed-tools but the workflow only describes read-only discovery (Glob/Grep/Read) and report writing; no destructive commands specified
  • •No network calls, credential access, or exfiltration behavior
  • •No obfuscation, encoded payloads, or instructions to disable safety checks
  • •Reads reference files from the skill's own references/ directory — expected and benign
Comment cette analyse est faite

Exemples

Audit API layer boundaries
Audit the API contracts in src/api and src/services: check for layer leakage, missing DTOs, and ORM entities returned without a response DTO. Report findings with severity levels.
Domain-scoped contract check
Run the API contract auditor in domain-aware mode on src/users/ and flag any inconsistent error contracts (mixing raise and return None) in the user services.
Check entity leakage before release
Before we ship, scan the controllers layer for ORM entities exposed directly in API responses and tell me which endpoints need a response DTO.

name: ln-643-api-contract-auditor description: "Checks layer leakage in method signatures, missing DTOs, entity leakage to API, inconsistent error contracts. Use when auditing API contracts." allowed-tools: Read, Grep, Glob, Bash, mcp__hex-graph__find_references, mcp__hex-graph__find_symbols, mcp__hex-line__read_file, mcp__hex-line__grep_search, mcp__hex-line__outline license: MIT

Paths: File paths (references/, ../ln-*) are relative to this skill directory.

API Contract Auditor (L3 Worker)

Type: L3 Worker

Specialized worker auditing API contracts, method signatures at service boundaries, and DTO usage patterns.

Purpose & Scope

  • Audit API contracts at architecture level (service boundaries, layer separation)
  • Check layer leakage, DTO patterns, error contract consistency
  • Return structured analysis with 4 scores (compliance, completeness, quality, implementation)

Out of Scope:

  • Code duplication (same DTO shape repeated, same mapping logic, same validation)
  • Report only ARCHITECTURE BOUNDARY findings (wrong layer, missing contract)

Inputs

- pattern: "API Contracts"     # Pattern name
- locations: string[]          # Service/API directories
- adr_reference: string        # Path to related ADR
- bestPractices: object        # Best practices from MCP Ref/Context7
- output_dir: string           # e.g., ".hex-skills/runtime-artifacts/runs/{run_id}/audit-report"

# Domain-aware (optional)
- domain_mode: "global" | "domain-aware"   # Default: "global"
- current_domain: string                   # e.g., "users", "billing" (only if domain-aware)
- scan_path: string                        # e.g., "src/users/" (only if domain-aware)

Workflow

Phase 0: Load References

Load references/detection_patterns.md -- language-specific Grep patterns for all 5 rules. Detection policy: use two-layer detection (candidate scan, then context verification); load references/two_layer_detection.md only when the verification method is ambiguous. Tool policy: follow host AGENTS.md MCP preferences; load references/mcp_tool_preferences.md and references/mcp_integration_patterns.md only when host policy is absent or MCP behavior is unclear.

Use hex-graph first when symbol or reference analysis materially improves contract findings. Use hex-line first for local code reads when available. If MCP is unavailable, unsupported, or not indexed, continue with built-in Read/Grep/Glob/Bash and state the fallback in the report.

Phase 1: Discover Service Boundaries

scan_root = scan_path IF domain_mode == "domain-aware" ELSE codebase_root

1. Find API layer: Glob("**/api/**/*.py", "**/routes/**/*.ts", "**/controllers/**/*.ts", root=scan_root)
2. Find service layer: Glob("**/services/**/*.py", "**/services/**/*.ts", root=scan_root)
3. Find domain layer: Glob("**/domain/**/*.py", "**/models/**/*.py", root=scan_root)
4. Map: which services are called by which API endpoints

Phase 2: Analyze Contracts (5 Rules)

MANDATORY READ: Load references/detection_patterns.md for language-specific Grep patterns per rule.

| # | Rule | Severity | What to Check | |---|------|----------|---------------| | 1 | Layer Leakage | HIGH/MEDIUM | Service/domain accepts HTTP types (Request, parsed_body, headers) | | 2 | Missing DTO | MEDIUM/LOW | 4+ params repeated in 2+ methods without grouping DTO | | 3 | Entity Leakage | HIGH/MEDIUM | ORM entity returned from API without response DTO. Downgrade when: internal API with no external consumers -> LOW | | 4 | Error Contracts | MEDIUM/LOW | Mixed error patterns (raise + return None) in same service | | 5 | Redundant Overloads | LOW/MEDIUM | Method pairs with _with_/_and_ suffix differing by 1-2 params | | 6 | Architectural Honesty | HIGH/MEDIUM | Read-named function (get_/find_/check_/validate_/is_/has_) body contains write side-effects. Exclusions per references/ai_ready_architecture.md |

Scope boundary: SKIP duplication findings. REPORT only ARCHITECTURE BOUNDARY findings.

Phase 3: Calculate 4 Scores

Compliance Score (0-100):

| Criterion | Points | |-----------|--------| | No layer leakage (HTTP types in service) | +35 | | Consistent error handling pattern | +25 | | Follows project naming conventions | +10 | | No hidden side-effects in read-named functions | +10 | | No entity leakage to API | +20 |

Completeness Score (0-100):

| Criterion | Points | |-----------|--------| | All service methods have typed params | +30 | | All service methods have typed returns | +30 | | DTOs defined for complex data | +20 | | Error types documented/typed | +20 |

Quality Score (0-100):

| Criterion | Points | |-----------|--------| | No boolean flag params in service methods | +15 | | No opaque return types hiding write actions | +10 | | No methods with >5 params without DTO | +25 | | Consistent naming across module | +25 | | No redundant overloads | +25 |

Implementation Score (0-100):

| Criterion | Points | |-----------|--------| | DTOs/schemas exist and are used | +30 | | Type annotations present | +25 | | Validation at boundaries (Pydantic, Zod) | +25 | | API response DTOs separate from domain | +20 |

Phase 3.5: Calculate Score

MANDATORY READ: Load references/audit_worker_core_contract.md and references/audit_scoring.md.

Primary score uses penalty formula (same as all workers):

penalty = (critical x 2.0) + (high x 1.0) + (medium x 0.5) + (low x 0.2)
score = max(0, 10 - penalty)

Diagnostic sub-scores (0-100 each) are calculated separately and reported in AUDIT-META for diagnostic purposes only.

Phase 4: Write Report

MANDATORY READ: Load references/templates/audit_worker_report_template.md.

Write JSON summary per references/audit_summary_contract.md. In managed mode the caller passes both runId and summaryArtifactPath; in standalone mode the worker generates its own run-scoped artifact path per shared contract.

# Build markdown report in memory with:
# - AUDIT-META (extended: score [penalty-based] + diagnostic score_compliance/completeness/quality/implementation)
# - Checks table (layer_leakage, missing_dto, entity_leakage, error_contracts, redundant_overloads)
# - Findings table (issues sorted by severity)
# - DATA-EXTENDED: issues array with principle + domain fields (for cross-domain aggregation)

IF domain_mode == "domain-aware":
  Write to {output_dir}/643-api-contract-{current_domain}.md
ELSE:
  Write to {output_dir}/643-api-contract.md

Phase 5: Return Summary

Report written: .hex-skills/runtime-artifacts/runs/{run_id}/audit-report/643-api-contract-users.md
Score: 6.75/10 (C:65 K:70 Q:55 I:80) | Issues: 4 (H:2 M:1 L:1)

Critical Rules

Apply the already-loaded references/audit_worker_core_contract.md.

  • Architecture-level only: Focus on service boundaries, not internal implementation
  • Read before score: Never score without reading actual service code
  • Scope boundary: SKIP duplication findings
  • Detection patterns: Use language-specific Grep from detection_patterns.md
  • Domain-aware: When domain_mode="domain-aware", scan only scan_path, tag findings with domain
  • Unique angle: Audit service/API boundary contracts only. Do not audit code duplication, package health, dependency topology, or runtime operations.
  • Action required: Every finding uses ADD_DTO, STOP_ENTITY_LEAK, or STANDARDIZE_ERROR_CONTRACT.

Definition of Done

Apply the already-loaded references/audit_worker_core_contract.md.

  • [ ] Service boundaries discovered (API, service, domain layers)
  • [ ] Method signatures extracted and analyzed
  • [ ] All 5 rules checked using detection_patterns.md
  • [ ] Scope boundary applied (no duplication findings)
  • [ ] 4 scores calculated with justification
  • [ ] Issues identified with severity, location, suggestion, effort
  • [ ] If domain-aware: findings tagged with domain field
  • [ ] Report written to {output_dir}/643-api-contract[-{domain}].md (atomic single Write call)
  • [ ] Summary written per contract

Reference Files

  • Detection patterns: references/detection_patterns.md
  • Scoring rules: references/audit_scoring.md

Version: 2.0.0 Last Updated: 2026-02-08

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/api-contract-auditor-l3-mrx3xxt5/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/api-contract-auditor-l3-mrx3xxt5' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/api-contract-auditor-l3-mrx3xxt5/download' --output '.skill-downloads/api-contract-auditor-l3-mrx3xxt5/SKILL.md.part' && mv '.skill-downloads/api-contract-auditor-l3-mrx3xxt5/SKILL.md.part' '.skill-downloads/api-contract-auditor-l3-mrx3xxt5/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Outils déclarés par l’auteur (à vérifier dans votre agent) : Read, Grep, Glob, Bash, mcp__hex-graph__find_references, mcp__hex-graph__find_symbols, mcp__hex-line__read_file, mcp__hex-line__grep_search, mcp__hex-line__outline

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/api-contract-auditor-l3-mrx3xxt5/SKILL.md' && test -s '.skill-downloads/api-contract-auditor-l3-mrx3xxt5/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/ln-643-api-contract-auditor' && cp -R '.skill-downloads/api-contract-auditor-l3-mrx3xxt5' '.claude/skills/ln-643-api-contract-auditor'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/api-contract-auditor-l3-mrx3xxt5'

openskills read 'api-contract-auditor-l3-mrx3xxt5'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/api-contract-auditor-l3-mrx3xxt5/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires