Pattern Library
Reusable code patterns extracted from real projects.
Swift Patterns
Core Architecture
- Observable State - @Observable and @Published patterns
- Navigation Patterns - NavigationStack approaches
- Persistence Patterns - CoreData and UserDefaults
- MVVM with @MainActor ObservableObject - Main actor view model pattern
- MVVM with @MainActor ViewModels - View model architecture
- NavigationStack Route Enum - Enum-based navigation routing
- FullScreenCover Modal Navigation - Modal presentation
- Environment Injection for Services - SwiftUI environment DI
- EnvironmentKey for Layout Metrics - Custom environment keys
- Lazy-Loaded Service Instances - Per-viewmodel service loading
- Protocol-Based Service Abstraction - Service protocol pattern
- Protocol-Based PredictionContent Providers - ML prediction protocols
State & Data
- AppStorage with Enum RawValue Bridge - Enum-backed AppStorage
- CustomTemplateStorage with Observable - Observable storage
- UserPreferences Singleton with AppStorage - Preferences persistence
- Singleton Streak Tracking - Streak tracking manager
- History with Deduplication and Limit - Bounded history
- Enum-Based Content Collections - Static content via enums
- StorySegment Enum - Text/blank segment modeling
- Word Pool Combinatorial Generation - Word combination generator
UI & Theming
- AudioService Singleton - Audio playback service singleton
- AppTheme ThemeManager - Theme management
- ThemeManager EnvironmentObject Injection - Theme via environment
- Semantic Color Aliases - Theme-prefixed color naming
- Color(hex:) Extension - Hex color initialization
- AloysiusTheme Enum with Static Colors - Static color definitions
- AmbientBackground - Ambient background view
- MesmerizingButtonStyle - Custom button styling
- MesmerizingCard - Card component
- MesmerizingTextField - Custom text field
- PressableButtonStyle - Press-responsive button
- ScaleButtonStyle - Scale animation button
- ParticleEmitterView via UIViewRepresentable - UIKit particle bridge
- View ID Modifier for Scene Transitions - Scene transition control
- AnimationPresets Extension - Reusable animation presets
- HapticService with Named Patterns - Haptic feedback service
Audio & System
- SystemSoundID Constants Enum - System sound constants
- Achievement System with Unlock Conditions - Gamification
- as const Object Union Type - Const union pattern
- Silent Error Fallbacks with Nil Coalescing - Graceful error handling
TypeScript Patterns
State & Architecture
- Factory + DI - Factory functions with dependency injection
- Context + Reducer - React state management
- Conversation State Machine - Chat/conversation state management
- TContext Generic - Generic context typing
- Board Management - Board data management
- Immutable Progress Tracker - Immutable state tracking
- Fire-and-Forget Persistence - Async persistence
- Recursive Tree Manipulation - Tree data structure ops
- Dashboard Aggregation - Multi-source dashboard data
- Direct Store Integration Testing - Integration testing stores directly
Audio & Media
- Web Audio - Web Audio API patterns
- SoundGenerator with Presets - Audio generation with presets
- ADSR Synthesis - Attack-decay-sustain-release audio
- Audio Context Autoplay Handling - Browser autoplay workarounds
- Audio Stream Processing - Real-time audio streams
- RecordingService Singleton - Audio recording service
React Hooks
- Vitest Setup with react-ga4 Mocking - Test setup for analytics SDK mocking (source: djg)
- useAudio Hook - React hook for audio
- useKeyboard Hook - React hook for keyboard events
- useCallback for Move Handler - Memoized move handling
- useLongPress Hook - Long press detection
- usePeer Hook - WebRTC peer connection hook
Data & Conversion
- Bidirectional Conversion Pattern - Two-way data conversion pattern
- Graph Health Reporting - Graph health metrics and reporting
- Mode-Based UI Switching - UI mode toggling pattern
Networking & Security
- fetchWithRetry Utility - Retry logic for fetch
- CryptoBackend Interface - Crypto abstraction
- KeyStorage Interface - Key storage abstraction
- WebSocket Broadcast - Cross-device synchronization
- MIME Fallback Chain - Content type fallbacks
- MIME Type Fallback - MIME type resolution
Code Organization
- Stack-Based Scope Tracking - Stack-based variable scope management
- Multi-Pane Productivity Workflow - Terminal pane layout for parallel development tasks
- tmux Session Launcher - Reproducible tmux session configuration
- TypeScript Project References - Vite standard for faster type checking (source: djg)
- CSS Co-location - Keeping styles with components
- ESM Module Separation - Module organization patterns
- Fetch Scripts - Data fetching patterns
- LocalStorage Validation - Storage with validation
- Minimal Interface Types - Lean type definitions
- PascalCase Components, camelCase Services - Naming conventions
- Path Alias src - Import path aliasing
- ReactFC with Explicit Props Types - Component typing
- SliderControl Component - Slider UI component
AI & NLP
- Proposer-Solver-Evaluator - Self-evolving knowledge building loop
- Global Type Augmentation - Extending Window, Document, and module types
- Multi-Stage NL-to-Code Pipeline - Natural language to code generation
- Safe Reflection - Runtime type introspection with safety
- User Persona Simulation - Simulating user behaviors for testing
- Weighted Rule Matching - Priority-based rule evaluation
- Pattern Matcher - Regex with capture groups
- REPL Interface - Interactive command interfaces
- Topic Memory - Context retention patterns
- Eliza Pattern Matching Engine - Classic AI pattern matching
- Eliza Rule Matching - Rule-based response generation
- Response Variety Cycling - Varied response selection
Python Patterns
- Release Readiness Workflow - Pre-release validation workflow
- Environment-Aware Scripts - Scripts that adapt to local vs CI
- Threshold-Based Alerting - 50%/80% warning/critical thresholds
- Contacts Array Preservation - Maintaining array integrity during transforms
- Dry Run Mode - Preview changes before applying
- External ID Deduplication - Dedup via external identifiers
- Headless Rendering with Data Injection - Server-side rendering with dynamic data
- Hunk-Based Diff Workflow - Granular diff processing
- Manual-First Automation Discovery - Manual process before automating
- Natural Language Structure Parsing - Extracting structure from free text
- Polished Mode - Draft vs production output separation
- Security Gate Before Deploy - Pre-deployment security checks
- Single-Block ALP Pseudocode - Atomic pseudocode block format
- Thin Command Wrappers - Rich workflow delegation
- Variables API for Data-Driven Rendering - Dynamic rendering via variable APIs
- Workflow Graph Navigation - Graph-based workflow traversal
- YAML for Structured Data - YAML as structured data format
- FOUC Prevention for Dynamic Theme Properties - Prevent flash of unstyled content during theme load
- Git Branch as Coordination Primitive - Using branch creation as an atomic coordination lock
General Patterns
Architecture & APIs
- BDD-to-Code Pipeline - Gherkin to Robot Framework to code generation
- Centralized Utility API Architecture - Shared org-wide API services
- Data Deduplication Patterns - Dedup strategies and algorithms
- Data Deduplication Architecture - Dedup system design
- Neural Gateway Architecture - Model-agnostic AI inference routing
- Software Dependency Management - Supply chain and dependency patterns
- Graph Builder Helpers - Graph construction utility functions
- Graph Diagnostics - Graph health and diagnostic tooling
- Immutable Graph Editing Helpers - Immutable graph edit operations
- AppwriteService Abstraction - Backend service abstraction
- Centralized Constants File - Constants organization
- Dynamic Source Registry - Pluggable source registration
- EncryptedPayload Type - Encrypted data type definition
- Integration Interface - Connect/GetProjects/CreateTask contract
- IntegrationService Facade - Facade pattern for integrations
- Module Export Services - Functional service exports
- Optional Interface Methods - Variant behavior via optional methods
- Source Adapter ABC - Abstract base class for data adapters
- Unified Directed Graph - Graph data structure
Infrastructure & DevOps
- CI Pipeline - CI/CD pipeline configuration
- CI QA Gate with Representative Graphs - QA gates using graph coverage
- QA Gate Helper - Helper utilities for QA gates
- Reference Repos as Read-Only Archives - Keep upstream URLs documented (source: aloysius-references)
- x64 Platform Awareness - Cross-architecture compatibility
- Circuit Breaker - Fault tolerance for external calls
- Circuit Breaker 3-States - Open/half-open/closed states
- Circuit Breaker Status - Status monitoring for circuit breakers
- Credential Permission Verification - Validating access credentials
- Environment Variable Hygiene - Clean env var management
- Git for Change Tracking - Using git as an audit trail
- Mirror-Based Backup - Mirrored backup strategy
- Pre-commit Format Enforcement - Auto-format on commit
- READMEs in Empty Directories - Preserving directory structure in git
- SecretStr for Credentials - Pydantic secret string handling
- Submodule References - Git submodule organization
- Token Bucket Rate Limiting - Rate limiter implementation
- Token Bucket Rate Limiter - Rate limiter variant
- TruffleHog Exclude-Paths - Exclude staging/research dirs from secret scanning
- TruffleHog Self-Hosted Runner - Install without sudo
- Sequential Dependabot Merge with Rebase Cycle - Safe merge ordering for batch dependency updates
- Docker Template Field Validation - Docker config validation
- Hardware Capacity Documentation - Documenting hardware specs
- Infrastructure Separation - Isolating infra concerns
- Infrastructure Sync Discipline - Keeping infra in sync
- Monorepo Folder Cleanup - Monorepo maintenance
- Sea Captain Port Management - Port registry management
- SSH Fleet Management - Managing SSH across hosts
- Terminal Workflow Optimization - Efficient terminal usage
- Homelab File Management Principles - Home server file org
Security
- 3-Scanner Security Architecture - Multi-scanner security pipeline
- Code Supply Chain Risk - Dependency supply chain risks
- Cryptographic Key Exchange - Key exchange protocols
- Path Traversal Protection - Preventing directory traversal
- Pre-commit Secret Scanning - Scanning for secrets before commit
- Zero Trust External Access - Zero trust security model
- Peer-to-Peer Messaging - P2P communication
Knowledge Vault Patterns
- Cross-Cutting Theme Clusters - Organizing content by themes
- Frontmatter Draft Handling - Managing draft states in frontmatter
- Minimum 2 Wikilinks Per Doc - Connectivity requirement
- Orphan Page Detection - Finding unlinked pages
- Research Integration Pipeline - Staging to vault workflow
- Template File Exclusion - Excluding templates from processing
- Standard Link Parse - Link format parsing
- Domain READMEs with YAML Examples - Structured domain docs
- evaluation.md as Standard POC Deliverable - POC evaluation format
- GAS manifest.json for Critical File Tracking - File manifest tracking
- GAS Planning - Planning methodology patterns
- Graduation Criteria - Promotion criteria for projects
- POC Directory Structure - Proof of concept project layout
- protocol.md as Experimental Process Doc - Process documentation format
- Reference Material in Library - Library organization
- Stub-First Shared Resources - Stub-first development approach
- verification.md Per Phase - Phase verification documents
Data & Validation
- IndexedDB Migration Protocol - IndexedDB schema migration strategy
- Metadata Schema Validation - Runtime metadata schema validation
- createTables() Must Mirror Migrations - DDL must match migration columns (source: haven)
- localStorage Mock in Test Environment - Browser API mocking for Vitest/jsdom (source: djg)
- Category-to-Type Mapping - Mapping categories to types
- Form Component Pattern - Reusable form components
- LocalStorage Persistence - Browser storage persistence
- LocalStorage Persistence with Zod Validation - Validated browser storage
- Perceptual Hash Similarity - Image similarity via perceptual hashing
- Slot Subtraction Algorithm - Availability slot calculation
- Source Adapter Interface - Pluggable data source adapters
- from_dict Serialization - Dictionary serialization pattern
- Zod Schema Validation - Runtime schema validation
- Segment-Based Template Parsing - Template segment extraction
- Session Serialization - Session state persistence
- Tab Persistence via LocalStorage - Tab state persistence
- Template Interpolation with Caching - Cached template rendering
- Template Interpolation Caching - Template interpolation with caching variant
Agentic Patterns
- Agent Scratchpad Workspace - Isolated, agent-owned workspace with three-part structure
- AI Agent Execution Constraints - Loop budgets, spec-first, context boundaries
- Boundary Guard Hooks - Pre-execution file access enforcement
- Context Refresh Session State - Three-mode session state management
- Human-in-the-Loop Approval Gates - Four-category approval taxonomy
- Polyglot Monorepo Architecture - Multi-language monorepo with daemon-client layers
- Multi-Pane Agent Parallelism - Parallel AI agent coordination across terminal panes
- Self-Contained Generated Files - Generated files that work across AI tools without external references
Automation & AI
- AI Context Injection - Injecting context into AI prompts
- Async Session Context Manager - Async context management
- Custom CodeMirror Language - Custom language definition for CodeMirror
- Feature-Based Store Pattern - Feature-scoped state management
- Lazy Directory Loading - On-demand directory traversal
- Monaco Model Registry - Editor model management
- Optional Dependency Import - Graceful optional imports
- Quiz Variation Transforms - Generating quiz variations
- Simulation Service - Service layer for simulations
- SikuliX Visual Automation - Visual UI automation
- Organize Flow - Data capture pipeline
- AI Summarization Pipeline - Multi-stage AI pipeline for summarizing research corpora
- Drift Prediction Visualization - Prediction drift monitoring
- Intelligent Response Generation - Smart response creation
- Monte Carlo Goal Forecasting - Probabilistic goal modeling
- NarrativeEngine Wrapper - Narrative engine abstraction
- Persona System with Rule Precedence - Rule-based persona management
- QuizEngine State Machine - Quiz state management
- Synthetic Data Generation - Generating synthetic datasets
- Procedural Generation Workflows - Procedural content creation
Desktop Automation
- AutoKey Linux Automation - Linux keyboard automation
- GIMP Headless Automation - Headless image processing
- Hammerspoon macOS Automation - macOS window/keyboard automation
- PyAutoGUI Cross-Platform Automation - Cross-platform GUI automation
UI & Components
- GA Event Tracking via Functional Component - Analytics separated from UI (source: djg)
- Tailwind-First Component Styling - Utility-class-only styling convention (source: djg)
- CSS Custom Properties + @theme inline - Runtime theming via CSS custom properties
- Three-Layer Accessibility Enforcement - Audit, automation, and CI-based a11y enforcement
- WCAG Contrast Validation Engine - Automated WCAG contrast ratio checking
- AloysiusTheme Enum with Static Colors - Theme color definitions
- Color(init:hex) Extension - Hex color initialization
- Compliance Verification UI - Compliance check interface
- ErrorBoundary Component - Error boundary pattern
- ErrorBoundary Wrapper Component - Error boundary HOC
- ErrorToast Component - Error notification toast
- MainTabView with AppMode Enum - Tab-based navigation
- Single App Component with useState - Simple app state
React Hooks & State
- Context useReducer Action Types - Typed reducer actions
- Custom Hook useInbox - Inbox context wrapper
- useConnectionStatus Hook - Connection monitoring
- useMemo for Board Layout Parsing - Memoized layout
- useNewMessageNotification Hook - Message notifications
- useRoom Hook - Room context management
- Zustand Persist for Client State - Persistent client state
- Zustand Slice Composition - Modular Zustand store slices
- Write-through Dexie Sync Middleware - Dexie IndexedDB write-through sync
Game & Domain Patterns
- DiceCollection as ObservableObject - Observable dice collection
- DiceType CaseIterable Enum - Dice type enumeration
- Static Factory Method on DiceRoll - Factory method pattern
Process & Methodology
- Consumer Integration Smoke Test - Integration smoke test pattern
- Property-Based Tests - Property-based testing methodology
- Scale Testing - Performance and scale testing patterns
- Telemetry Hooks - Observability via telemetry hook points
- Temporal Middleware Wrapper - Async middleware wrapper pattern
- Atomic File Write - Safe file writing
- Exported Pure Helpers for Testability - Testable pure functions
- handleEventName for Event Handlers - Event handler naming convention
- Idempotent Auto-Creation - Safe repeated creation
- Immutable Effect Processing - Side-effect-free processing
- Market Analysis Before POC - Pre-POC market research
- Phase-Based Incremental Delivery - Phased delivery strategy
- Project with Embedded Tasks - Task embedding in projects
- Safe-First Merge Ordering - Merge conflict prevention
- Snooze) - Reversible user actions
About This Section
Each pattern includes:
- Problem - What challenge it solves
- Solution - The pattern implementation
- Usage - Code examples
- Trade-offs - When to use (and when not to)
- Source - Which project it came from