pumuki-ast-hooks
v5.3.20
Published
Enterprise-grade AST Intelligence System with multi-platform support (iOS, Android, Backend, Frontend) and Feature-First + DDD + Clean Architecture enforcement. Includes dynamic violations API for intelligent querying.
Maintainers
Readme
Visual Overview
🧠 The Vision: Solving AI Context Loss in Software Development
The Fundamental Problem
In modern AI-assisted development, a critical limitation emerges: AI assistants lose context. Whether due to token limits, session resets, or conversation boundaries, AI agents repeatedly forget:
- Project architecture: "What's the structure here? Clean Architecture? DDD? Feature-First?"
- Active rules: "Which validation rules apply? What are the coding standards?"
- Current work: "What branch am I on? What files were recently changed? What patterns exist?"
- Quality gates: "Are there blocking violations? What needs to be fixed?"
This forces developers into a repetitive, inefficient cycle of re-explaining context, re-loading rules, and re-establishing project understanding—defeating the purpose of AI assistance.
The Solution: Permanent Context Persistence
This library was conceived to solve this fundamental problem by creating a permanent, always-on context system for AI assistants. It transforms AI from a "stateless helper" into a context-aware collaborator that maintains deep, persistent understanding of your project.
🔄 How It Works: The Complete Flow
Phase 1: Context Initialization (ai_start Protocol)
When: Before any code editing begins, or when context becomes stale (>3 minutes)
What Happens:
Developer runs
ai-start(or it auto-executes via MCP):ai-start feature/user-authentication # or automatically via MCP: auto_execute_ai_startThe system answers three critical questions:
- Q1: What file types am I working with?
- Analyzes staged/modified files
- Detects platforms (iOS, Android, Backend, Frontend)
- Identifies target Clean Architecture layers (Domain, Application, Infrastructure, Presentation)
- Example:
"Code task on branch 'feature/auth'. Modifying typescript, kotlin in: auth, users. Target layer: Domain."
- Q2: Does similar code already exist?
- Analyzes recent Git commits
- Identifies affected modules
- Suggests existing patterns to follow
- Example:
"Modules affected: auth, users. Recent commits: abc123 feat: Add JWT validation. Check for existing patterns before adding new code."
- Q3: How does this fit in Clean Architecture?
- Validates layer dependencies
- Ensures dependencies point inward (Domain ← Application ← Infrastructure)
- Example:
"Code changes in Domain layer affecting auth, users. Ensure dependencies point inward."
- Q1: What file types am I working with?
Rules are automatically loaded:
DynamicRulesLoaderscans agentic IDE rules directories (.cursor/rules/,.ast-intelligence/skills/,.windsurf/rules/,.vscode/rules/,.kilo/rules/,.cline/rules/) for platform-specific rules- Always loads
rulesgold.mdcfirst (generic rules that apply to all projects) - Then loads platform-specific rules:
rulesbackend.mdc,rulesios.mdc,rulesandroid.mdc,rulesfront.mdc - Aggregates all 798+ validation rules into a single context
- Creates
auto-context.mdcwith all active rules
.AI_EVIDENCE.jsonis created/updated:{ "timestamp": "2025-12-13T23:07:19.632Z", "session_id": "feature/user-authentication", "protocol_3_questions": { "answered": true, "question_1_file_type": "Code task on branch 'feature/auth'. Modifying typescript, kotlin in: auth, users. Target layer: Domain.", "question_2_similar_exists": "Modules affected: auth, users. Recent commits: abc123 feat: Add JWT validation. Check for existing patterns before adding new code.", "question_3_clean_architecture": "Code changes in Domain layer affecting auth, users. Ensure dependencies point inward." }, "rules_read": [ { "file": "rulesgold.mdc", "verified": true, "summary": "IDE Rules: ### ANTES de implementar CUALQUIER cosa (aplicables en todas las tecnologías):;### Reglas de Arquitectura:;### Seguridad y Validación:;### Performance y Escalabilidad:;### Testing y Calidad:;### Observabilidad y Debugging:;### Arquitectura y Diseño:;### Control de Versiones y Colaboración:;### i18n y Accesibilidad:;### Error Handling:; | AST: Files: 96, Rules: types.any,debug.console,security.secret,security.sql.raw,performance.pagination,performance.nplus1,architecture.layering,ios.force_unwrapping" }, { "file": "rulesbackend.mdc", "verified": true, "summary": "IDE Rules: ### NestJS Architecture:;### Repository Pattern:;### Use Cases Pattern:;### DTOs y Validación:;### Database y ORM:;### Autenticación y Autorización:;### Event-Driven Architecture:;### Caché (Redis):;### Logging y Observabilidad:;### Testing Backend:;### Error Handling:;### Seguridad:;### Performance:;### API Design:;### Configuración:;### Documentación:; | AST: Files: 16, Rules: backend.error_handling.untyped_catch,backend.security.pii_in_logs,backend.performance.nplus1" }, { "file": "rulesios.mdc", "verified": true, "summary": "IDE Rules: ### Swift Moderno:;### SwiftUI (Preferido):;### UIKit (Legacy/Necesario):;### Protocol-Oriented Programming:;### Value Types:;### Memory Management:;### Optionals:;### Clean Architecture en iOS:;### Dependency Injection:;### Networking:;### Persistence:;### Combine (Reactive):;### Concurrency:;### Testing:;### Security:;### Accessibility:;### Localization:; | AST: Files: 24, Rules: ios.force_unwrapping,ios.singleton,ios.massive_view_controller" } ], "current_context": { "branch": "feature/user-authentication", "last_commits": "abc123 feat: Add JWT validation" }, "platforms": ["backend", "ios"], "ai_gate": { "status": "BLOCKED", "last_check": "2025-12-13T23:16:39.736Z", "violations": [ { "file": "/path/to/project/src/auth/user.service.ts", "line": 45, "severity": "HIGH", "rule": "backend.error_handling.untyped_catch", "message": "Catch parameter MUST be typed as ': unknown' - use type guards (error instanceof HttpException/Error)", "category": "Error Handling", "intelligent_evaluation": false, "severity_score": 50 }, { "file": "/path/to/project/src/auth/auth.controller.ts", "line": 12, "severity": "CRITICAL", "rule": "backend.security.pii_in_logs", "message": "🚨 CRITICAL: Potential PII in logs. Never log: passwords, tokens, SSN, credit cards. Sanitize: logger.info({ userId, action }) - don't include sensitive fields. GDPR violation risk.", "category": "Security", "intelligent_evaluation": true, "severity_score": 100 } ], "instruction": "🚨 AI MUST call mcp_ast-intelligence-automation_ai_gate_check BEFORE any action. If BLOCKED, fix violations first!", "mandatory": true }, "severity_metrics": { "last_updated": "2025-12-13T23:16:39.726Z", "total_violations": 2, "by_severity": { "CRITICAL": 1, "HIGH": 1, "MEDIUM": 0, "LOW": 0 }, "average_severity_score": 75, "gate_status": "FAILED", "blocked_by": "CRITICAL" } }
Phase 2: Continuous Context Maintenance
When: Throughout the development session
What Happens:
Pre-Tool-Use Validation (
pre-tool-use-evidence-validator.ts):- Before every AI edit operation, validates
.AI_EVIDENCE.json:- ✅ File exists
- ✅ Valid JSON structure
- ✅ Timestamp is fresh (<180 seconds old)
- ✅ Rules were read
- ✅ Protocol 3 questions answered
- ✅ AI gate is not BLOCKED
- If stale or missing: Blocks the edit and prompts to run
ai-start - If BLOCKED: Shows violations and requires fixing before proceeding
- Before every AI edit operation, validates
Real-Time Monitoring (
RealtimeGuardService):- Polls
.AI_EVIDENCE.jsonevery 30 seconds - Detects staleness (>180 seconds)
- Auto-refreshes evidence if stale (
HOOK_GUARD_AUTO_REFRESH=trueby default) - Auto-executes ai-start when code files detected (
HOOK_GUARD_AI_START=trueby default) - Monitors Git tree state with differentiated thresholds:
- Staged files: Warning at >10 files (configurable via
HOOK_GUARD_DIRTY_TREE_STAGED_LIMIT) - Unstaged files: Warning at >15 files (configurable via
HOOK_GUARD_DIRTY_TREE_UNSTAGED_LIMIT) - Total files: Warning at >20 files (configurable via
HOOK_GUARD_DIRTY_TREE_TOTAL_LIMIT)
- Staged files: Warning at >10 files (configurable via
- Sends macOS notifications for critical events
- Polls
Automatic Rule Updates:
- When new rules are added to any agentic IDE rules directory, they're automatically detected
DynamicRulesLoaderreloads rules on nextai-startauto-context.mdcis regenerated with latest rules
Phase 3: Code Quality Enforcement
When: Before commits, during development, via MCP tools
What Happens:
Pre-Commit Analysis (Git Hook):
- Analyzes staged files using AST (Abstract Syntax Tree)
- Applies 798+ validation rules
- Checks Clean Architecture violations
- Validates SOLID principles
- Detects security issues, performance problems, maintainability issues
- Blocks commit if CRITICAL/HIGH violations found
AI Gate Check (
ai_gate_checkMCP tool):- Called at the start of every AI response (enforced by Cursor rules)
- Reads
.AI_EVIDENCE.json→ai_gate.status - Returns
BLOCKEDorALLOWED - If
BLOCKED: Shows violations, requires fixing before proceeding - If
ALLOWED: AI can proceed with user's task
Violation Detection:
- AST analyzers scan code for:
- Architecture violations (wrong layer dependencies)
- SOLID violations (God classes, tight coupling)
- Security issues (PII in logs, SQL injection risks)
- Performance issues (N+1 queries, missing pagination)
- Code quality (comments, magic numbers, force unwrapping)
- Findings are aggregated into
AuditResult - Severity-based blocking (CRITICAL/HIGH block, MEDIUM/LOW warn)
- AST analyzers scan code for:
Phase 4: Evidence Update Before Commits
When: Before every Git commit
What Happens:
ai-commit.shis executed (via Git alias or directly):git commit -m "feat: Add user authentication" # Internally calls: ai-commit.shEvidence is refreshed:
- Updates
.AI_EVIDENCE.jsontimestamp - Re-analyzes current context (branch, files, commits)
- Updates violation status
- Ensures evidence is fresh for next AI interaction
- Updates
Commit proceeds with fresh evidence
🛠️ Tools & Technologies
Core Components
Git Hooks:
pre-commit: AST analysis before commitspre-push: Additional validation before pushingpost-commit: Evidence update after commits
MCP (Model Context Protocol) Server:
ast-intelligence-automation: Provides AI tools via MCP- Tools:
ai_gate_check,auto_execute_ai_start,auto_complete_gitflow,sync_branches,cleanup_stale_branches,validate_and_fix - Enables Cursor, Claude Desktop, and other MCP-compatible IDEs to interact with the system
AST Analysis Engine:
ts-morph: TypeScript AST parsing- Custom analyzers for each platform:
BackendArchitectureDetector: Detects NestJS patterns, Clean ArchitectureFrontendArchitectureDetector: Detects React/Next.js patterns, Feature-FirstiOSArchitectureDetector: Detects multiple iOS architecture patterns (MVVM, MVVM-C, MVP, VIPER, TCA, Clean Swift, Feature-First + Clean + DDD, MVC Legacy)AndroidClassAnalyzer: Detects Kotlin/Jetpack Compose patterns
MaintainabilityAnalyzer,PerformanceAnalyzer,SecurityAnalyzer,StabilityAnalyzer
Context Management:
DynamicRulesLoader: Loads and aggregates rules from any agentic IDE rules directory (Cursor, Claude, Windsurf, VS Code, Kilo, Cline, etc.)ContextDetectionEngine: Detects project structure and patternsPlatformDetectionService: Identifies platforms (iOS, Android, Backend, Frontend)AutonomousOrchestrator: Coordinates context detection and rule loading
Real-Time Services:
RealtimeGuardService: Monitors evidence freshness, Git tree stateIntelligentGitTreeMonitor: Tracks Git changes and suggests actionsEvidenceMonitorService: Watches for evidence staleness
Use Cases (Clean Architecture):
AnalyzeCodebaseUseCase: Full codebase analysisAnalyzeStagedFilesUseCase: Staged files onlyBlockCommitUseCase: Determines if commit should be blockedAutoExecuteAIStartUseCase: Auto-executesai-startbased on confidenceGenerateAuditReportUseCase: Creates audit reports (console, JSON, HTML)
📊 What, How, and When: The Developer's Perspective
What Does This Library Provide?
- Permanent AI Context:
.AI_EVIDENCE.jsonthat never gets lost - 798+ Validation Rules: Platform-specific code quality rules
- Automatic Architecture Detection: Identifies multiple patterns per platform (iOS: MVVM, MVVM-C, MVP, VIPER, TCA, Clean Swift, Feature-First + Clean + DDD; Backend: Clean Architecture, DDD, CQRS; Frontend: Feature-First, Component-Based, Atomic Design; Android: MVVM, MVI, MVP, Clean Architecture)
- Quality Gates: Blocks commits with CRITICAL/HIGH violations
- Git Flow Automation: Complete workflow automation (commit → push → PR → merge)
- MCP Integration: Standard protocol for any agentic IDE
How Does It Work?
- Installation:
npm install --save-dev pumuki-ast-hooks && npm run install-hooks - Initialization: Run
ai-startbefore coding (or it auto-executes) - Development: System monitors and validates automatically
- Commits: Pre-commit hooks analyze and block if needed
- AI Interaction: AI always has fresh context via
.AI_EVIDENCE.json
When Does It Activate?
- On Installation: Sets up Git hooks, MCP server, rules
- Before Coding:
ai-startinitializes context (manual or auto) - During Editing: Pre-tool-use hooks validate evidence freshness
- Before Commits: Pre-commit hooks analyze staged files
- On AI Requests:
ai_gate_checkvalidates before AI actions - Continuously:
RealtimeGuardServicemonitors and auto-refreshes
Why Does It Matter?
- Efficiency: AI never asks "What's the architecture?" again
- Quality: Catches violations before they reach production
- Consistency: Enforces standards across entire team
- Automation: Reduces manual Git Flow tasks
- Context Persistence: Survives token limits, session resets, conversation boundaries
Complete Architecture and Workflow
The library operates through a multi-phase process that integrates with Git and development workflows to ensure code quality and context persistence. Below is a high-level overview of the architecture and key components:
Architectural Diagram
graph LR
A[Developer] -->|Runs `ai-start`| B(AI Evidence Initialization)
B --> C[.AI_EVIDENCE.json]
C --> D[Pre-Tool-Use Validator]
D --> E[AI Gate Check]
E --> F[Allow/Block Actions]
F --> G[Code Editing]
G --> H[Pre-Commit Analysis]
H --> I[Block Commit if Violations]
I --> J[Update Evidence]
J --> K[Commit]Key Components
AI Evidence Initialization (
ai-start)- Generates
.AI_EVIDENCE.jsonwith project context and rules. - Answers three critical questions about the task.
- Example:
ai-start feature/user-authentication
- Generates
Pre-Tool-Use Validator
- Validates
.AI_EVIDENCE.jsonbefore every AI edit operation. - Ensures context is fresh and rules are loaded.
- Validates
AI Gate Check
- Checks for blocking violations before allowing actions.
- Enforces quality gates.
Pre-Commit Analysis
- Runs AST analysis on staged files.
- Blocks commits with critical violations.
Evidence Update
- Updates
.AI_EVIDENCE.jsonbefore commits to maintain context.
- Updates
Example Workflow
- Developer runs
ai-startto initialize context. - AI uses context to perform edits.
- Pre-commit hook analyzes code and blocks if violations exist.
- Developer fixes violations and commits.
For a detailed architecture, see ARCHITECTURE.md.
📖 Table of Contents
- The Vision: Solving AI Context Loss
- How It Works: The Complete Flow
- Tools & Technologies
- What, How, and When: The Developer's Perspective
- Complete Architecture and Workflow
- What is it?
- What problems does it solve?
- Features
- Use Cases
- Installation
- Quick Start
- 📚 Documentation Guide - Step by Step
- Architecture
- MCP Servers
- API Reference
- Configuration
- Best Practices
- FAQ
- Contributing
- License
What is it?
ast-intelligence-hooks is an intelligent static analysis system that automatically validates that your code complies with Clean Architecture, Domain-Driven Design (DDD), and Feature-First Architecture principles.
But more importantly, it's a context persistence system that ensures AI assistants maintain permanent understanding of your project through the ai_start protocol, automatic rule loading, and continuously updated .AI_EVIDENCE.json.
Key Features
🧠 Context Persistence (Core Purpose)
- ✅
ai_startProtocol: Automatically answers the three critical questions for AI context - ✅
.AI_EVIDENCE.json: Permanent context file that never goes stale - ✅ Automatic rule loading: All 798+ rules loaded automatically for AI awareness
- ✅ Context detection: Real-time understanding of what you're working on
🔍 Code Validation
- ✅ 798+ validation rules across all platforms with severity-based quality gates
- ✅ Multi-platform support: iOS (Swift/SwiftUI), Android (Kotlin/Jetpack Compose), Backend (TypeScript/NestJS), Frontend (React/Next.js)
- ✅ Automatic architecture detection: Identifies multiple patterns per platform (iOS: MVVM, MVVM-C, MVP, VIPER, TCA, Clean Swift, Feature-First + Clean + DDD; Backend: Clean Architecture, DDD, CQRS; Frontend: Feature-First, Component-Based, Atomic Design; Android: MVVM, MVI, MVP, Clean Architecture)
- ✅ BDD→TDD workflow enforcement: CRITICAL priority - ensures feature files exist before implementation and tests before code
- ✅ Pre-commit Git hooks: Automatic validation blocks commits with CRITICAL/HIGH violations
- ✅ AST analysis engine: Deep static code analysis using Abstract Syntax Trees
- ✅ Clean Architecture enforcement: Strict SOLID principles validation and dependency rules
🤖 Automation & Integration
- ✅ Git Flow automation: Complete workflow automation via MCP (commit → push → PR → merge)
- ✅ MCP integration: Standard Model Context Protocol (MCP) support for any agentic IDE or AI client (Cursor, Claude Desktop, etc.)
- ✅ Version checking: Automatic detection of library updates
- ✅ CI/CD ready: Seamless integration with GitHub Actions and other CI systems
What problems does it solve?
❌ Common Problems
Clean Architecture Violations
- Domain layer importing frameworks
- Infrastructure coupled to Presentation
- Circular dependencies
Undetected Code Smells
- Magic numbers without constants
- Functions that are too long
- Classes with too many responsibilities
Lack of Architectural Consistency
- Incorrect folder structure
- Forbidden imports between layers
- Missing separation of concerns
Production-time Errors
- Security violations (passwords without hash)
- Performance issues
- Untestable code
✅ Solutions
- Automatic validation before each commit
- 798+ rules specific to each platform
- Detailed reports with correction suggestions
- CI/CD integration for continuous validation
Features
🎯 Platform-specific Analysis
Backend (TypeScript/NestJS)
- 150+ Clean Architecture rules
- Automatic architecture detection: Clean Architecture, Onion, Layered, Feature-First + Clean + DDD, CQRS
- DDD pattern validation
- Circular dependency detection
- Decorator and module analysis
Frontend (React/Next.js)
- 200+ architecture rules
- Automatic architecture detection: Component-Based, Atomic Design, Feature-First + Clean + DDD, State Management patterns
- Server/Client Components validation
- Hooks and state management analysis
- Prop drilling detection
iOS (Swift/SwiftUI)
- 150+ iOS-specific rules
- Automatic architecture detection: MVVM-C, MVVM, MVP, VIPER, TCA, Clean Swift, Feature-First + Clean + DDD
- SwiftUI best practices analysis
- Potential memory leak detection
Android (Kotlin/Jetpack Compose)
- 200+ Android-specific rules
- Automatic architecture detection: MVVM, MVI, MVP, Clean Architecture, Feature-First + Clean + DDD
- Compose pattern analysis
- Common anti-pattern detection
🏗️ Automatic Architecture Detection
All platforms now support automatic architecture pattern detection:
- No configuration needed - works out of the box
- Detects patterns by analyzing project structure, imports, and code
- Supports manual override via
.ast-architecture.json(optional) - Works for iOS, Android, Backend, and Frontend
See HOW_IT_WORKS.md for details on detected patterns per platform.
🤖 MCP Integration
- evidence-watcher: Automatic monitoring of
.AI_EVIDENCE.json - ast-intelligence-automation: Complete Git Flow automation and context detection
- Standard MCP protocol: Works with any MCP-compatible agentic IDE (Cursor, Claude Desktop, and others)
🔒 Quality Gates
- CRITICAL/HIGH: Automatically block commits
- MEDIUM/LOW: Generate warnings in reports
- Configurable: Adjust levels according to your project
Use Cases
1. Automatic Validation on Pre-commit
# Runs automatically on each git commit
git commit -m "feat: add new feature"
# → Analyzes only staged files
# → Blocks commit if CRITICAL/HIGH violations found
# → Generates violation report2. Full Project Analysis
# Analyzes entire codebase
npm run audit
# Or using CLI
ast-hooks analyze3. CI/CD Integration
# .github/workflows/ci.yml
- name: Run AST Analysis
run: npm run audit4. Programmatic Usage
const { runASTIntelligence } = require('@pumuki/ast-intelligence-hooks');
const result = await runASTIntelligence({
files: ['src/**/*.ts'],
platforms: ['backend'],
strict: true
});
if (result.hasCriticalViolations()) {
console.error('❌ Critical violations found!');
process.exit(1);
}5. Continuous Monitoring
# Watch mode for development
hook-watch
# System status
hook-statusInstallation
Prerequisites
- Node.js ≥18.0.0
- npm ≥9.0.0
- Git (for hooks)
Option 1: Installation via npm (Recommended)
npm install --save-dev pumuki-ast-hooks
npm run install-hooksOption 2: Installation via Git
npm install --save-dev git+https://github.com/carlos/ast-intelligence-hooks.git
npm run install-hooksOption 3: Manual Installation
git clone https://github.com/carlos/ast-intelligence-hooks.git
cd ast-intelligence-hooks
npm install
npm link
npm run install-hooksConfigure Git Hooks
# Install hooks automatically
npm run install-hooks
# Or manually
ast-installFor more details, see INSTALLATION.md.
Quick Start
1. Install the library
npm install --save-dev @pumuki/ast-intelligence-hooks2. Configure hooks
npm run install-hooks3. Make a test commit
git add .
git commit -m "test: verify hooks"The hooks will run automatically and validate your code.
4. View full report
npm run audit5. Check violations
# List all violations
npm run violations:list
# View summary
npm run violations:summary
# Top violations
npm run violations:top📚 Documentation Guide - Step by Step
This section provides a recommended reading order to fully understand the library and its capabilities.
For New Users (Start Here)
HOW_IT_WORKS.md ⭐ START HERE
- Complete step-by-step explanation of what the library does
- Installation process breakdown
- How each component works (Git hooks, MCP servers, AST analysis)
- Execution flows and real-world examples
- Read this first to understand the system!
INSTALLATION.md - Start here! Complete installation guide with platform-specific instructions
- Prerequisites and requirements
- Installation methods (npm, Git, manual)
- Initial configuration
- Verification steps
USAGE.md - Learn how to use the library
- Minimal example (5 minutes)
- Basic commands
- Git hooks integration
- Programmatic usage
- Advanced examples
- CI/CD integration
Quick Start (this README) - Get up and running quickly
- Fast setup in 5 steps
- First test commit
For Understanding the System
ARCHITECTURE.md - High-level architecture overview
- System layers
- Data flow
- Key components
- Quality gates
ARCHITECTURE_DETAILED.md - Deep dive into architecture
- Detailed layer architecture
- Module dependencies
- Extension points
- Key files mapping
For Integration and Advanced Usage
MCP_SERVERS.md - MCP integration for agentic IDEs
- evidence-watcher setup
- ast-intelligence-automation setup
- Usage examples
- Troubleshooting
API_REFERENCE.md - Complete API documentation
- Core services
- Use Cases
- Domain entities
- Entry points
For Configuration and Customization
CODE_STANDARDS.md - Code style and conventions
- ESLint configuration
- TypeScript conventions
- Clean code principles
- Git commit format
DEPENDENCIES.md - Dependencies analysis
- Runtime dependencies
- Development dependencies
- Optional tools
- Platform compatibility
For Development and Testing
- TESTING.md - Testing guide
- Test structure
- Running tests
- Writing new tests
- Best practices
Quick Reference
- Need to install? → INSTALLATION.md
- Need examples? → USAGE.md or
examples/folder - Need API docs? → API_REFERENCE.md
- Need to configure? → USAGE.md
- Need to understand architecture? → ARCHITECTURE.md
Architecture
The project follows strict Clean Architecture with 4 well-defined layers:
┌─────────────────────────────────────────┐
│ PRESENTATION LAYER │
│ - CLI Interface │
│ - Git Hooks │
│ - MCP Servers │
└──────────────┬──────────────────────────┘
│
┌──────────────▼──────────────────────────┐
│ APPLICATION LAYER │
│ - Use Cases │
│ - Services │
└──────────────┬──────────────────────────┘
│
┌──────────────▼──────────────────────────┐
│ DOMAIN LAYER │
│ - Entities │
│ - Business Rules │
│ - Repository Interfaces │
└──────────────┬──────────────────────────┘
▲
┌──────────────┴──────────────────────────┐
│ INFRASTRUCTURE LAYER │
│ - AST Analyzers │
│ - Repository Implementations │
│ - External Tools │
└─────────────────────────────────────────┘Principles:
- Dependencies inward: Presentation → Application → Domain
- Domain without dependencies: Zero external dependencies
- Dependency Inversion: Interfaces in Domain, implementations in Infrastructure
For more details, see ARCHITECTURE.md and ARCHITECTURE_DETAILED.md.
MCP Servers
The project includes MCP (Model Context Protocol) servers for integration with any agentic IDE or AI client:
evidence-watcher
Monitors the status of .AI_EVIDENCE.json and allows AI to verify if it's up to date.
Resources:
evidence://status: Evidence status (fresh/stale/missing)
Tools:
check_evidence_status: Checks if the evidence is stale
ast-intelligence-automation
Automates the complete Git Flow cycle: commit → push → PR → merge, plus context detection and AI gate checks.
Resources:
evidence://status: Evidence statusgitflow://state: Git Flow workflow statecontext://active: Active project context
Tools:
auto_complete_gitflow: Automatically completes Git Flow cyclesync_branches: Syncs develop/main branchescleanup_stale_branches: Cleans up merged branchesauto_execute_ai_start: Automatically executes ai-startvalidate_and_fix: Validates and fixes common issuesai_gate_check: Gate check before tasks
For more details, see MCP_SERVERS.md.
API Reference
Main Functions
runASTIntelligence(options)
Analyzes code using AST Intelligence.
const { runASTIntelligence } = require('@pumuki/ast-intelligence-hooks');
const result = await runASTIntelligence({
files: ['src/**/*.ts'],
platforms: ['backend', 'frontend'],
strict: false
});Options:
files(string[]): File patterns to analyzeplatforms(string[]): Platforms to analyze (ios,android,backend,frontend)strict(boolean): If true, blocks on any violation
Returns: AuditResult
AnalyzeCodebaseUseCase
Use Case for full codebase analysis.
const { AnalyzeCodebaseUseCase } = require('@pumuki/ast-intelligence-hooks');
const useCase = new AnalyzeCodebaseUseCase(/* dependencies */);
const result = await useCase.execute('/path/to/codebase');AnalyzeStagedFilesUseCase
Use Case for analyzing only staged files.
const { AnalyzeStagedFilesUseCase } = require('@pumuki/ast-intelligence-hooks');
const useCase = new AnalyzeStagedFilesUseCase(/* dependencies */);
const result = await useCase.execute();Domain Entities
AuditResult
Aggregated result of an analysis.
const { AuditResult } = require('@pumuki/ast-intelligence-hooks');
result.getFindings(); // All violations
result.getCriticalFindings(); // Only CRITICAL
result.hasCriticalViolations(); // Boolean
result.getTechnicalDebtHours(); // Estimated hoursFinding
Individual violation found.
const { Finding } = require('@pumuki/ast-intelligence-hooks');
finding.getSeverity(); // 'critical' | 'high' | 'medium' | 'low'
finding.getRule(); // Rule ID
finding.getMessage(); // Descriptive message
finding.getFile(); // File where it was foundFor more details, see API_REFERENCE.md.
Configuration
Environment Variables
# Repository root
export REPO_ROOT=/path/to/project
# Evidence stale threshold (milliseconds, default: 180000 = 3 minutes)
export HOOK_GUARD_EVIDENCE_STALE_THRESHOLD=180000
# Auto ai-start execution (enabled by default)
export HOOK_GUARD_AI_START=true
export HOOK_GUARD_AI_START_COOLDOWN=60000
# Auto-refresh evidence when stale (enabled by default)
export HOOK_GUARD_AUTO_REFRESH=true
# Auto-commit in Git Flow
export AUTO_COMMIT_ENABLED=true
export AUTO_PUSH_ENABLED=true
export AUTO_PR_ENABLED=falseConfiguration Files
config/ast-exclusions.json: Exclude files from analysisconfig/language-guard.json: Language-specific guard configurationconfig/doc-standards.json: Documentation standards.cursor/mcp.jsonor client-specific config: MCP Servers configuration (see MCP_SERVERS.md)
Customize Rules
Rules are in skills/ by platform:
skills/backend-guidelines/skills/frontend-guidelines/skills/ios-guidelines/skills/android-guidelines/
For more details, see USAGE.md.
Best Practices
1. Install Hooks in All Projects
# on each new project
npm install --save-dev pumuki-ast-hooks
npm run install-hooks2. Use in CI/CD
# .github/workflows/ci.yml
- name: AST Analysis
run: npm run audit3. Review Violations Regularly
# Weekly
npm run violations:summary4. Configure Appropriate Exclusions
// config/ast-exclusions.json
{
"patterns": [
"node_modules/**",
"dist/**",
"build/**"
]
}5. Use MCP Servers with Agentic IDEs
Configure MCP Servers in your IDE's MCP configuration file (e.g., .cursor/mcp.json for Cursor, or client-specific location) for complete automation.
FAQ
Can I use this in existing projects?
Yes, it's backward compatible. Hooks only validate new code you commit.
How to temporarily disable hooks?
# For a specific commit
GIT_BYPASS_HOOK=1 git commit -m "emergency fix"Does it work with monorepos?
Yes, automatically detects monorepo structure and analyzes each module.
Can I add custom rules?
Yes, you can extend rules in skills/ or create your own analyzers.
Does it work on Windows?
Works with WSL2 or Git Bash. Not tested on native Windows.
What if I have many violations?
Start by fixing CRITICAL and HIGH. MEDIUM and LOW are warnings and don't block commits.
How to update evidence?
# Automatically via MCP
# Or manually
bash scripts/hooks-system/infrastructure/shell/orchestrators/audit-orchestrator.shFor more questions, check the issues on GitHub.
Available Commands
CLI Commands
# Analysis
ast-hooks analyze # Full analysis
ast-hooks analyze --staged # Only staged files
# Violations
ast-violations list # List all
ast-violations summary # Summary
ast-violations top # Top violations
ast-violations show <id> # Show specific violation
# Hooks
hook-status # System status
hook-watch # Watch mode
hook-predict # Violation prediction
hook-playbook # Execute playbook
# Git Flow
gitflow check # Verify Git Flow
gitflow status # Current status
gitflow workflow # View full workflownpm Scripts
npm run audit # Full analysis
npm run install-hooks # Install hooks
npm test # Run tests
npm run lint # Linter
npm run typecheck # Type checkingContributing
Contributions are welcome. Please:
- Fork the repository
- Create a branch for your feature (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Contribution Guidelines
- Follow the code of conduct
- Ensure tests pass (
npm test) - Add tests for new features
- Update documentation if necessary
For coding standards, see CODE_STANDARDS.md.
License
This project is licensed under the MIT License - see LICENSE for more details.
Credits
Developed by Pumuki Team®
- Author: Juan Carlos Merlos Albarracín (Senior Software Architect - AI-Driven Development)
- Contact: [email protected]
- Version: 5.3.9
- Repository: GitHub
Useful Links
- 📚 Complete Documentation
- 🏗️ Detailed Architecture | Architecture Detailed
- 🔌 MCP Servers
- 📖 API Reference
- 📦 Installation Guide
- 💡 Usage Guide
- 🔍 Dependencies Analysis
- 🧪 Testing Guide
- 📋 Code Standards
⭐ If this project is useful to you, please consider giving it a star on GitHub.
Run the Audit
To start the interactive audit menu, run:
bash scripts/hooks-system/infrastructure/shell/orchestrators/audit-orchestrator.shThis will present a menu with options for different audit modes.
For non-interactive use, specify the mode directly:
bash scripts/hooks-system/infrastructure/shell/orchestrators/audit-orchestrator.sh analyze # Full repository analysis
bash scripts/hooks-system/infrastructure/shell/orchestrators/audit-orchestrator.sh staged # Analyze only staged files (pre-commit mode)