/verify-patterns

Quality L3 Production medium usage

/verify-patterns

Overview

/verify-patterns is a production command in the Quality category of the Prismatic Platform. It performs comprehensive pattern matching audits across files, modules, or the entire codebase, verifying that code patterns conform to platform standards, detecting anti-patterns, validating pattern completeness in case/cond expressions, and ensuring consistent pattern usage across the 90+ umbrella applications. The command leverages Elixir's AST (Abstract Syntax Tree) analysis to identify pattern-related issues that conventional static analysis tools miss.

This command operates under the L3 authority level and is executed by the pattern-matching-auditor agent. It is part of the platform's 216-command slash command registry, built on the AIAD (Autonomous Intelligence Agent Design) standard. The L3 authority level grants the auditor deep AST access across the entire codebase, enabling cross-module pattern consistency checks that require visibility into both producer and consumer modules.

Pattern matching is fundamental to Elixir and is the primary mechanism for control flow, data extraction, and error handling on the Prismatic Platform. Incorrect patterns cause subtle bugs: incomplete case clauses lead to CaseClauseError, overly broad matches swallow errors silently, and inconsistent patterns across modules create maintenance burden. /verify-patterns systematically identifies these issues through six audit categories: completeness, specificity, consistency, anti-patterns, performance, and idiom compliance.

Architecture

The pattern verification system operates as a multi-pass AST analysis pipeline.

Verification Architecture

             /verify-patterns
                    |
            Pattern Orchestrator
                    |
          +--------+--------+--------+
          |        |        |        |
       Complete  Specific  Consist  Anti
       Audit     Audit     Audit    Pattern
          |        |        |        |
    +-----+--+ +--+--+ +--+--+ +---+---+
    |    |   | |  |  | |  |  | |   |   |
   Case  With Match Guard Cross Unsafe Broad
   Check Check Check Check Check Match  Match
    |    |   | |  |  | |  |  | |   |   |
    +----+---+-+--+--+-+--+--+-+---+---+
                    |
            Finding Aggregator
                    |
          +--------+--------+
          |        |        |
       Critical  Warning  Info
       Patterns  Patterns Patterns
                    |
            Pattern Report

Audit Categories

CategoryFocusExample Issues
CompletenessAll pattern branches coveredMissing clause in case, unhandled {:error, _}
SpecificityPatterns are precise, not overly broadCatch-all _ that swallows errors
ConsistencyPatterns match across modulesProducer returns {:ok, data}, consumer matches {:ok, result}
Anti-PatternsKnown problematic patternslength(list) > 0 instead of list != []
PerformancePattern efficiencyNested pattern matches that could be simplified
Idiom ComplianceElixir convention adherenceUsing if/else where pattern matching is idiomatic

Anti-Pattern Library

Anti-PatternProblemCorrect PatternSeverity
length(list) > 0O(n) for empty checklist != [] or pattern matchMedium
Bare rescue _Swallows all exceptionsrescue e in [SpecificError]High
Map.get(m, k) without nil handlingSilent nil propagationPattern match or Map.fetch/2Medium
String.to_atom/1 on user inputAtom table exhaustionString.to_existing_atom/1Critical
Enum.count(list) == 0O(n) for empty checklist == [] or match?([], list)Low
Nested case without withDeep nestingwith clause chainMedium
Process.sleep in production codeBlocking processTimer/GenServer schedulingHigh

Usage

# Verify patterns in specific file
/verify-patterns apps/prismatic_web/lib/prismatic_web/live/perimeter_live.ex

# Verify patterns in specific module
/verify-patterns --module PrismaticPerimeter.SecurityRating

# Full codebase pattern audit
/verify-patterns --all

# Focus on specific audit category
/verify-patterns --category completeness --all

# Show only anti-patterns
/verify-patterns --anti-patterns --all

# Verify patterns in specific application
/verify-patterns --app prismatic_perimeter

# Export findings as JSON
/verify-patterns --all --format json --export ./pattern-report.json

# Show verbose findings with code context
/verify-patterns --verbose --all

# Verify recently changed files only
/verify-patterns --changed

# Dry run showing audit plan
/verify-patterns --dry-run --all

Practical Examples

# Pre-commit pattern verification
/verify-patterns --changed --verbose

# Focus on critical anti-patterns across codebase
/verify-patterns --anti-patterns --min-severity high --all

# Cross-module consistency check for Perimeter module
/verify-patterns --category consistency --app prismatic_perimeter --verbose

# Verify case clause completeness in all LiveView modules
/verify-patterns --category completeness --app prismatic_web --module-pattern "*Live*"

# Generate fix suggestions for all anti-patterns
/verify-patterns --anti-patterns --all --suggest-fixes --format markdown --export ./pattern-fixes.md

Options

OptionTypeDefaultDescription
--modulestringnoneSpecific module to verify
--appstringnoneSpecific application to verify
--allflagfalseVerify entire codebase
--changedflagfalseVerify only recently changed files
--categoryenumallAudit category: completeness, specificity, consistency, anti-patterns, performance, idiom, all
--anti-patternsflagfalseShow only anti-patterns
--min-severityenuminfoMinimum severity: info, low, medium, high, critical
--verboseflagfalseDetailed findings with code context
--formatenumtextOutput format: text, json, markdown
--exportpathnoneExport report to file
--suggest-fixesflagfalseInclude fix suggestions for each finding
--module-patternstringallGlob pattern for module name filtering
--dry-runflagfalseShow audit plan without executing
--auto-fixflagfalseAutomatically fix safe anti-patterns

Execution Flow

Phase 1: Source Enumeration

Target source files are enumerated using Git Trees for performance. For --changed, Git diff identifies modified Elixir files. For --app, all .ex files within the application are selected. For --all, all 6,652 .ex files are included.

Phase 2: AST Parsing

Each source file is parsed into an AST using Code.string_to_quoted/2. The AST is traversed to identify all pattern-bearing constructs: case, cond, with, function heads with pattern matching, receive, try/rescue, and = assignments.

Phase 3: Pattern Analysis

Each pattern construct is analyzed through the configured audit categories. Completeness checks verify all branches are covered. Specificity checks flag overly broad matches. Consistency checks compare patterns across module boundaries. Anti-pattern checks match against the 25+ item anti-pattern library.

Phase 4: Cross-Reference Validation

For consistency audits, the analyzer correlates function return types (from @spec and actual returns) with calling code patterns. Mismatches between what a function returns and how its callers pattern-match the result are flagged as consistency violations.

Phase 5: Report Generation

Findings are aggregated, deduplicated, and severity-scored. The report groups findings by category and severity, includes code context for each finding (surrounding lines), and optionally includes suggested fixes. Fix suggestions show the problematic pattern and the recommended replacement.

Integration Points

ComponentIntegration TypeDescription
/quality-gatesEnforcementPattern findings affect gate passage
/quality-evolveConsumerPattern findings drive quality evolution
/scan-myceliumUpstreamMycelium scanner feeds pattern data
/regression-checkPeerRegression checks include pattern verification
/refactorDownstreamPattern fixes are refactoring operations
/tech-debtPeerAnti-patterns are a form of technical debt
Quality DNAStatePattern health metrics persisted
TelemetryMonitoringPattern audit execution metrics

Best Practices

Pre-Commit Verification

Run /verify-patterns --changed as part of the pre-commit workflow. Catching anti-patterns and incomplete patterns before commit prevents them from entering the codebase and accumulating as pattern debt.

Anti-Pattern Zero Tolerance

Maintain zero anti-patterns across the codebase. The platform's current perfect quality score of 100/100 was achieved partly through systematic anti-pattern elimination. Use /verify-patterns --anti-patterns --all periodically to verify this standard is maintained.

Cross-Module Consistency Focus

Pattern consistency across module boundaries is the highest-value audit category because inconsistencies cause runtime errors that unit tests in individual modules do not catch. Prioritize --category consistency in regular verification cycles.

Safe Auto-Fix

Use --auto-fix only for anti-patterns with known safe transformations (like replacing length(list) > 0 with list != []). Never auto-fix patterns that involve business logic or control flow changes.

Error Handling

Error CodeDescriptionResolution
AST_PARSE_ERRORCannot parse source fileCheck file for syntax errors
MODULE_NOT_FOUNDSpecified module does not existVerify module name and path
CROSS_REF_UNAVAILABLECannot resolve cross-module referencesEnsure all apps are compiled
FIX_CONFLICTAuto-fix would change behaviorManual review required
SCAN_TIMEOUTPattern analysis exceeded time limitNarrow scope with --app or --module
PATTERN_LIBRARY_STALEAnti-pattern library outdatedUpdate pattern library

Advanced Usage

Custom Anti-Pattern Rules

Add project-specific anti-patterns:

/verify-patterns --custom-patterns ./patterns/prismatic-anti-patterns.yaml --all

Pattern Coverage Metrics

Generate pattern coverage metrics per module:

/verify-patterns --coverage --app prismatic_perimeter --format json --export ./pattern-coverage.json

Pattern Evolution Tracking

Track pattern health over time:

/verify-patterns --trends --since 30d --format markdown --export ./pattern-trends.md

Doctrine Compliance

All commands operate under the NO MERCY, NO DOUBTS doctrine:

  • NO MERCY: Zero tolerance for incomplete execution or quality violations. Every anti-pattern is flagged, every incomplete case clause is reported, every inconsistency is identified.
  • NO DOUBTS: Full investigation before action, evidence-based results. Every finding includes the source location, the problematic pattern, the reason it is problematic, and a suggested alternative.
  • /quality-gates - Enforce quality gate checkpoints with zero-warning compilation validation
  • /quality-evolve - Quality-focused evolution targeting specific quality domains
  • /regression-check - Execute 25 custom Credo regression checks preventing 700+ violations
  • /refactor - Safe refactoring with zero-regression guarantee
  • /scan-mycelium - Mycelial pattern scanning across documentation and code
  • /tech-debt - Technical debt analysis and elimination planning
  • /code - Core coding implementation and feature development

Connect & Contribute

Created by Tomáš Korcak (korczis) | Open Source under GHL