
Define and implement Service Level Indicators (SLIs) and Service Level Objectives (SLOs) with error budgets and alerting. Use when establishing reliability targets, implementing SRE practices, or measuring service performance.
Master advanced prompt engineering techniques to maximize LLM performance, reliability, and controllability in production. Use when optimizing prompts, improving LLM outputs, or designing production prompt templates.
Master ShellCheck static analysis configuration and usage for shell script quality. Use when setting up linting infrastructure, fixing code issues, or ensuring script portability.
Implement distributed tracing with Jaeger and Tempo to track requests across microservices and identify performance bottlenecks. Use when debugging microservices, analyzing request flows, or implementing observability for distributed systems.
Set up Prometheus for comprehensive metric collection, storage, and monitoring of infrastructure and applications. Use when implementing metrics collection, setting up monitoring infrastructure, or configuring alerting systems.
Build automated billing systems for recurring payments, invoicing, subscription lifecycle, and dunning management. Use when implementing subscription billing, automating invoicing, or managing recurring payment systems.
Master error handling patterns across languages including exceptions, Result types, error propagation, and graceful degradation to build resilient applications. Use when implementing error handling, designing APIs, or improving application reliability.
Migrate from AngularJS to Angular using hybrid mode, incremental component rewriting, and dependency injection updates. Use when upgrading AngularJS applications, planning framework migrations, or modernizing legacy Angular code.
Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers. Use when designing new APIs, reviewing API specifications, or establishing API design standards.
# Archetypal Combinations: Alchemy Engine ## Overview The Archetypal Alchemy system combines **Jungian Archetypes** (behavioral/structural patterns) with **Major Arcana** (color/mood modifiers) to generate cohesive, meaningful UI/UX designs. **Formula**: `ARCHETYPE + CARD = Complete Design System` --- ## The Alchemy Process ### Step 1: Parse the Formula ``` Input: "Hero+Sun" Parse: Archetype = Hero, Card = Sun ``` ### Step 2: Extract Archetype Patterns From jungian-archetypes skill: - UI
Master Python asyncio, concurrent programming, and async/await patterns for high-performance applications. Use when building async APIs, concurrent systems, or I/O-bound applications requiring non-blocking operations.
Master authentication and authorization patterns including JWT, OAuth2, session management, and RBAC to build secure, scalable access control systems. Use when implementing auth systems, securing APIs, or debugging security issues.
Master defensive Bash programming techniques for production-grade scripts. Use when writing robust shell scripts, CI/CD pipelines, or system utilities requiring fault tolerance and safety.
Integrating Chrome DevTools and browser automation via MCP for live UI inspection, screenshot-to-code workflows, and visual debugging. Bridges the gap between design and implementation.
Master effective code review practices to provide constructive feedback, catch bugs early, and foster knowledge sharing while maintaining team morale. Use when reviewing pull requests, establishing review standards, or mentoring developers.
Master systematic debugging techniques, profiling tools, and root cause analysis to efficiently track down bugs across any codebase or technology stack. Use when investigating bugs, performance issues, or unexpected behavior.
Implement DeFi protocols with production-ready templates for staking, AMMs, governance, and lending systems. Use when building decentralized finance applications or smart contract protocols.
Manage major dependency version upgrades with compatibility analysis, staged rollout, and comprehensive testing. Use when upgrading framework versions, updating major dependencies, or managing breaking changes in libraries.
Deep knowledge of legendary designers and their enduring contributions. Learn from Saul Bass, Massimo Vignelli, Dieter Rams, Paula Scher, and others whose work defines excellence. Use when seeking inspiration, understanding design history, or applying proven approaches.
Core visual design principles that underpin all great design. Master gestalt psychology, visual hierarchy, composition, color theory, and typography fundamentals. Use when making design decisions or evaluating designs against proven principles.
Managing design tokens and system context for LLM-driven UI development. Covers loading, persisting, and optimizing design decisions within context windows.
Master end-to-end testing with Playwright and Cypress to build reliable test suites that catch bugs, improve confidence, and enable fast deployment. Use when implementing E2E tests, debugging flaky tests, or establishing testing standards.
Implement NFT standards (ERC-721, ERC-1155) with proper metadata handling, minting strategies, and marketplace integration. Use when creating NFT contracts, building NFT marketplaces, or implementing digital asset systems.
Build production-ready Node.js backend services with Express/Fastify, implementing middleware patterns, error handling, authentication, database integration, and API design best practices. Use when creating Node.js servers, REST APIs, GraphQL backends, or microservices architectures.
Integrate PayPal payment processing with support for express checkout, subscriptions, and refund management. Use when implementing PayPal payments, processing online transactions, or building e-commerce checkout flows.
Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.
Create production-ready GitHub Actions workflows for automated testing, building, and deploying applications. Use when setting up CI/CD with GitHub Actions, automating development workflows, or creating reusable workflow templates.
Implement GitOps workflows with ArgoCD and Flux for automated, declarative Kubernetes deployments with continuous reconciliation. Use when implementing GitOps practices, automating Kubernetes deployments, or setting up declarative infrastructure management.
Create and manage production Grafana dashboards for real-time visualization of system and application metrics. Use when building monitoring dashboards, visualizing metrics, or creating operational observability interfaces.
Configure secure, high-performance connectivity between on-premises infrastructure and cloud platforms using VPN and dedicated connections. Use when building hybrid cloud architectures, connecting data centers to cloud, or implementing secure cross-premises networking.
Implement Kubernetes security policies including NetworkPolicy, PodSecurityPolicy, and RBAC for production-grade security. Use when securing Kubernetes clusters, implementing network isolation, or enforcing pod security standards.
Design LLM applications using the LangChain framework with agents, memory, and tool integration patterns. Use when building LangChain applications, implementing AI agents, or creating complex LLM workflows.
# Major Arcana → Color Palettes & Moods ## Overview The 22 Major Arcana cards of the Tarot represent archetypal life stages and cosmic forces. Each card carries distinct energetic signatures that translate into color palettes, lighting moods, and visual atmospheres for UI/UX design. --- ## The Major Arcana Palette System ### 0. THE FOOL **Energy**: Innocence, spontaneity, new beginnings **Color Palette**: - Primary: Sky Blue (#38bdf8) → Boundless possibility - Secondary: Cloud White (#f0f9f
Design microservices architectures with service boundaries, event-driven communication, and resilience patterns. Use when building distributed systems, decomposing monoliths, or implementing microservices.
Master ES6+ features including async/await, destructuring, spread operators, arrow functions, promises, modules, iterators, generators, and functional programming patterns for writing clean, efficient JavaScript code. Use when refactoring legacy code, implementing modern patterns, or optimizing JavaScript applications.
Master monorepo management with Turborepo, Nx, and pnpm workspaces to build efficient, scalable multi-package repositories with optimized builds and dependency management. Use when setting up monorepos, optimizing builds, or managing shared dependencies.
Prompt patterns for consistent UI generation. Covers precise design intent communication, component specification formats, and iterative refinement patterns for LLM-driven UI development.
Implement PCI DSS compliance requirements for secure handling of payment card data and payment systems. Use when securing payment processing, achieving PCI compliance, or implementing payment card security measures.
Design a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features
Create distributable Python packages with proper project structure, setup.py/pyproject.toml, and publishing to PyPI. Use when packaging Python libraries, creating CLI tools, or distributing Python code.
Implement comprehensive testing strategies with pytest, fixtures, mocking, and test-driven development. Use when writing Python tests, setting up test suites, or implementing testing best practices.
Build Retrieval-Augmented Generation (RAG) systems for LLM applications with vector databases and semantic search. Use when implementing knowledge-grounded AI, building document Q&A systems, or integrating LLMs with external knowledge bases.
Embrace vibe coding for rapid UI exploration. Covers when to iterate vs refine, ephemeral app patterns, and the art of fast, disposable prototyping with AI-assisted development.
Implement secure secrets management for CI/CD pipelines using Vault, AWS Secrets Manager, or native platform solutions. Use when handling sensitive credentials, rotating secrets, or securing CI/CD environments.
Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application performance.
Implement Stripe payment processing for robust, PCI-compliant payment flows including checkout, subscriptions, and webhooks. Use when integrating Stripe payments, building subscription systems, or implementing secure checkout flows.
Build reusable Terraform modules for AWS, Azure, and GCP infrastructure following infrastructure-as-code best practices. Use when creating infrastructure modules, standardizing cloud provisioning, or implementing reusable IaC components.
Master the uv package manager for fast Python dependency management, virtual environments, and modern Python project workflows. Use when setting up Python projects, managing dependencies, or optimizing Python development workflows with uv.
Test smart contracts comprehensively using Hardhat and Foundry with unit tests, integration tests, and mainnet forking. Use when testing Solidity contracts, setting up blockchain test suites, or validating DeFi protocols.
Profile and optimize Python code using cProfile, memory profilers, and performance best practices. Use when debugging slow Python code, optimizing bottlenecks, or improving application performance.
Configure Static Application Security Testing (SAST) tools for automated vulnerability detection in application code. Use when setting up security scanning, implementing DevSecOps practices, or automating code vulnerability detection.
Master Bash Automated Testing System (Bats) for comprehensive shell script testing. Use when writing tests for shell scripts, CI/CD pipelines, or requiring test-driven development of shell utilities.
Patterns for delegating UI work to specialized agents. Covers synthesis-master vs specialized agents, multi-agent UI generation workflows, and orchestration strategies for complex UI tasks.
Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use when architecting complex backend systems or refactoring existing applications for better maintainability.
Design durable workflows with Temporal for distributed systems. Covers workflow vs activity separation, saga patterns, state management, and determinism constraints. Use when building long-running processes, distributed transactions, or microservice orchestration.
Design multi-stage CI/CD pipelines with approval gates, security checks, and deployment orchestration. Use when architecting deployment workflows, setting up continuous delivery, or implementing GitOps practices.
Build GitLab CI/CD pipelines with multi-stage workflows, caching, and distributed runners for scalable automation. Use when implementing GitLab CI/CD, optimizing pipeline performance, or setting up automated testing and deployment.
Design multi-cloud architectures using a decision framework to select and integrate services across AWS, Azure, and GCP. Use when building multi-cloud systems, avoiding vendor lock-in, or leveraging best-of-breed services from multiple providers.
Building comprehensive brand identity systems from strategy to implementation. Covers logo design, color palettes, typography pairing, voice guidelines, and system documentation. Use when creating new brands, rebranding, or systematizing existing identities.
Master advanced Git workflows including rebasing, cherry-picking, bisect, worktrees, and reflog to maintain clean history and recover from any situation. Use when managing complex Git histories, collaborating on feature branches, or troubleshooting repository issues.
Upgrade React applications to latest versions, migrate from class components to hooks, and adopt concurrent features. Use when modernizing React codebases, migrating to React Hooks, or upgrading to latest React versions.
Implement comprehensive testing strategies using Jest, Vitest, and Testing Library for unit tests, integration tests, and end-to-end testing with mocking, fixtures, and test-driven development. Use when writing JavaScript/TypeScript tests, setting up test infrastructure, or implementing TDD/BDD workflows.
Design, organize, and manage Helm charts for templating and packaging Kubernetes applications with reusable configurations. Use when creating Helm charts, packaging Kubernetes applications, or implementing templated deployments.
Build end-to-end MLOps pipelines from data preparation through model training, validation, and production deployment. Use when creating ML pipelines, implementing MLOps practices, or automating model training and deployment workflows.
Execute database migrations across ORMs and platforms with zero-downtime strategies, data transformation, and rollback procedures. Use when migrating databases, changing schemas, performing data transformations, or implementing zero-downtime deployment strategies.
# Jungian Archetypes → UI/UX Aesthetics ## Overview The 12 Jungian archetypes represent universal patterns of human behavior and motivation. Each archetype carries distinct visual languages, interaction patterns, and design philosophies that can be translated into UI/UX systems. --- ## The 12 Archetypes ### 1. THE HERO **Core Drive**: Mastery, courage, achievement **Visual Language**: Bold, angular, dynamic **UI Characteristics**: - Strong geometric shapes (triangles, sharp edges) - High co
Test Temporal workflows with pytest, time-skipping, and mocking strategies. Covers unit testing, integration testing, replay testing, and local development setup. Use when implementing Temporal workflow tests or debugging test failures.
Master smart contract security best practices to prevent common vulnerabilities and implement secure Solidity patterns. Use when writing smart contracts, auditing existing contracts, or implementing security measures for blockchain applications.
Optimize cloud costs through resource rightsizing, tagging strategies, reserved instances, and spending analysis. Use when reducing cloud expenses, analyzing infrastructure costs, or implementing cost governance policies.
Historical design movements and their enduring influence. Understand Bauhaus, Swiss International Style, Art Deco, Memphis, and more. Use when choosing an aesthetic direction, understanding cultural context, or predicting trend cycles.
Professional framework for building premium $5k+ SaaS websites with AI - the Define, Build, Review, Refine loop used by real product teams
Master TypeScript's advanced type system including generics, conditional types, mapped types, template literals, and utility types for building type-safe applications. Use when implementing complex type logic, creating reusable type utilities, or ensuring compile-time type safety in TypeScript projects.
Implement comprehensive evaluation strategies for LLM applications using automated metrics, human feedback, and benchmarking. Use when testing LLM performance, measuring AI application quality, or establishing evaluation frameworks.
# Tutorial Patterns ## Tutorial vs. How-to Guide: The Critical Distinction Before writing, identify which document is actually needed: | Tutorial | How-to Guide | |----------|-------------| | "Build a REST API in Node.js" | "Add JWT authentication to your Express API" | | For someone new to this | For someone who knows the domain | | Explains why each step is done | Steps are efficient, minimal explanation | | Has checkpoints, explores | Numbered steps, no detours | | Learner reaches a comple
# Tech Blogging Patterns ## The Developer Reading Pattern Developers do not read technical posts linearly. They scan in this order: 1. Headline (is this relevant to me?) 2. Code blocks (is this real code I can use?) 3. Headers (what does this cover?) 4. First paragraph (what's the point?) 5. Key takeaways / conclusion (is it worth reading fully?) Design for scanning first, reading second. Put real code within the first 25% of the post. ## The Before/After Pattern The contrast between a pain
# LLM Tuning Patterns Expert patterns for LoRA, QLoRA, instruction dataset preparation, DPO, and evaluation. ## Pattern 1: QLoRA Fine-Tuning with SFTTrainer Complete QLoRA setup for instruction fine-tuning a 7B model on 24 GB VRAM. ```python from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training from trl import SFTTrainer from datasets import load_dataset import torch # 1. Load model in 4-
# GPU Optimization Patterns Expert patterns for memory management, torch.compile, profiling, quantization, and kernel optimization. ## Pattern 1: GPU Memory Profiling and Budgeting Profile and track GPU memory usage with explicit memory math. ```python import torch def memory_report(label: str = ""): allocated = torch.cuda.memory_allocated() / 1e9 reserved = torch.cuda.memory_reserved() / 1e9 print(f"[{label}] Allocated: {allocated:.2f} GB | Reserved: {reserved:.2f} GB") def es
# Changelog Patterns > Standards, conventions, and best practices for maintaining project changelogs. ## Knowledge Base ### Keep a Changelog Principles 1. Changelogs are for **humans**, not machines. 2. There should be an entry for every **single version**. 3. The same types of changes should be **grouped**. 4. Versions and sections should be **linkable**. 5. The latest version comes **first**. 6. The **release date** of each version is displayed (ISO 8601: YYYY-MM-DD). 7. State whether you
# Docstring Patterns > Language-specific documentation comment syntax, conventions, and best practices. ## Knowledge Base ### The Documentation Comment Spectrum | Level | What to Document | Example | |-------|-----------------|---------| | Module/Package | Purpose, exports, usage overview | File header comment | | Class/Interface | Responsibility, lifecycle, usage | Class docstring | | Function/Method | Contract (inputs, outputs, errors) | Function docstring | | Parameter | Semantic meaning
# Developer Guide Patterns ## Diátaxis in Practice ### Tutorial characteristics - The user is in a **learning** state, not trying to accomplish a real task - Provide a safe sandbox environment (don't operate on real data) - Every step must succeed - no choices, no optional paths - Show expected output after every step - The goal is the learning experience, not the artifact built ```markdown # Tutorial: Build Your First Webhook Handler In this tutorial, you will build a simple webhook receive
# Proposal Writing Patterns ## Problem-First Structure The most common proposal mistake: opening with the solution. Reviewers who disagree with the framing of the problem will block everything that follows. ```markdown # Bad: starts with solution ## Proposed Solution We should replace our current session-based auth with JWTs. Benefit: JWTs are stateless, which means... # Good: starts with problem ## Problem Statement Our auth service maintains a session store that is shared across all API i
# Knowledge Base Patterns ## Article Title Patterns The title is the single most important field for findability. Users search with the same words they would type in a title. ``` # Good: question format How do I cancel my subscription? How do I export my data to CSV? What's the difference between API keys and OAuth tokens? # Good: task format Cancel your subscription Export data to CSV Reset two-factor authentication # Bad: topic format (too vague, no search intent) Subscription management
# Blog Structures > Structural patterns and frameworks for different types of technical blog posts. ## Knowledge Base ### The Technical Blog Post Anatomy Every technical blog post has these layers: ``` Hook --> Why should I care? (2-3 sentences) Context --> What problem exists? (1-2 paragraphs) Solution --> How do we solve it? (bulk of the post) Evidence --> Does it work? (benchmarks, examples, results) Takeaways --> What did we learn? (3-5 bullet points) Call t
# User Doc Patterns > Patterns for writing clear, accessible end-user documentation. ## Knowledge Base ### User Documentation vs Developer Documentation | User Docs | Developer Docs | |-----------|---------------| | Task-oriented ("How do I...") | Concept-oriented ("How does it work...") | | Plain language | Technical language | | Screenshots and visual aids | Code examples | | Step-by-step procedures | API references | | Feature names and UI labels | Function signatures and parameters | | A
# Labeling Patterns Expert patterns for annotation pipeline design, quality assurance, and scalable labeling systems. ## Pattern 1: Annotation Guideline Design Good guidelines are the highest-leverage investment in label quality. Bad guidelines produce high IAA on wrong labels. ### Structure 1. **Task definition**: What exactly is being labeled, and why 2. **Label taxonomy**: Exhaustive list with definitions and examples 3. **Decision tree for edge cases**: Binary yes/no questions leading to
# MLflow Patterns Expert patterns for MLflow tracking server, model registry, custom flavors, and deployment. ## Pattern 1: Production MLflow Server Setup PostgreSQL backend + S3 artifact store for team deployment. ```bash # Infrastructure # PostgreSQL for run metadata (reliable, concurrent, queryable) # S3 for artifacts (scalable, durable, cheap) # 1. Create PostgreSQL database psql -c "CREATE DATABASE mlflow; CREATE USER mlflow_user WITH PASSWORD 'secure_password'; GRANT ALL PRIVILEGES ON
# ML Testing Patterns Expert patterns for data quality tests, model unit tests, behavioral tests, and performance regression gates. ## Pattern 1: pytest Fixtures for ML Shared fixtures that load model and data once per test session. ```python # conftest.py import pytest import pandas as pd import numpy as np import joblib import torch from transformers import AutoModelForSequenceClassification, AutoTokenizer @pytest.fixture(scope="session") def model(): """Load model once for entire tes
# Model Evaluation Patterns Expert patterns for classification metrics, calibration, sliced evaluation, fairness, and LLM evaluation. ## Pattern 1: Complete Classification Evaluation Report All key metrics in one evaluation pass. ```python import numpy as np import pandas as pd from sklearn.metrics import ( f1_score, accuracy_score, roc_auc_score, average_precision_score, matthews_corrcoef, confusion_matrix, classification_report, brier_score_loss, calibration_curve ) from scipy
# Model Deployment Patterns Expert patterns for model serving, ONNX export, Triton configuration, and traffic splitting. ## Pattern 1: FastAPI Production Serving Production-ready FastAPI service with model loaded at startup, health checks, and Prometheus metrics. ```python # app/main.py from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException from pydantic import BaseModel import joblib import numpy as np import time import logging from prometheus_fastapi_instrum
# README Templates > Structural patterns and content frameworks for different project types. ## Knowledge Base ### The README Pyramid Every README serves multiple audiences simultaneously. Structure content as a pyramid: ``` [Title + One-liner] <-- 2 seconds: "What is this?" [Badges + Visual] <-- 5 seconds: "Is it healthy?" [Install + Quick Start] <-- 30 seconds: "Can I use it?" [Features / API Overview] <-- 2 minutes: "What ca
# ADR Templates > Architecture Decision Record formats, status lifecycles, and architectural documentation patterns. ## Knowledge Base ### What is an ADR? An Architecture Decision Record captures a single architectural decision along with its context and consequences. ADRs are: - **Immutable**: Once accepted, an ADR is not modified. If a decision changes, a new ADR supersedes the old one. - **Sequential**: Numbered in the order they are created. - **Lightweight**: One page, one decision. No
# API Documentation Patterns ## Operation Documentation ### summary vs description `summary` is the one-line entry in navigation and index tables. `description` is the full explanation. Both matter. ```yaml # Bad: summary that restates the method and path summary: GET user by ID # Good: summary that describes intent summary: Retrieve a user # description adds what summary cannot: description: | Returns a single active user. Suspended users still return 200 with `status: suspended`. Dele
# Architecture Documentation Patterns ## C4 Model Patterns ### Level selection guide | Audience | Level | Format | |----------|-------|--------| | Executive sponsor, non-technical stakeholders | L1 Context | One diagram, one page | | Product managers, frontend developers, DevOps | L2 Container | 1-2 diagrams with tech annotations | | Backend developers maintaining a service | L3 Component | Per-service, updated when structure changes | | Code reviewers | L4 Code | Auto-generate from IDE; rare
# CLI Help Text Patterns ## POSIX Usage Line Conventions The usage line is the most compact expression of a command's interface. Know the notation: | Notation | Meaning | Example | |----------|---------|---------| | `[item]` | Optional | `[--verbose]` | | `<item>` | Required placeholder | `<source>` | | `item...` | Repeatable | `FILE...` | | `a\|b` | Mutually exclusive | `--json\|--yaml` | | `{a,b,c}` | One of these required | `{start,stop,status}` | ``` # Simple command USAGE: compress [OPT
# Code Comment Patterns ## The Core Rule: Why, Not What Code already shows what is happening. Comments should explain why a choice was made, or what non-obvious constraint applies. ```typescript // Bad: describes what the code says // Convert kilometers to miles const miles = km * 0.621371; // Bad: states the obvious // Increment counter by 1 count++; // Good: explains non-obvious choice // Using 0.621371 (exact IEEE 754 value) rather than 0.62 to match // the precision required by the vehi
# Content Strategy Patterns ## Diátaxis Framework The four content types serve fundamentally different user needs. Mixing types in a single article creates confusion. | Type | User Need | User State | Analogy | |------|-----------|-----------|---------| | Tutorial | Learning | Studying | Teaching a child to cook | | How-To | Accomplishing a task | Working | Recipe for experienced cook | | Reference | Looking up information | Working | Ingredient reference card | | Explanation | Understanding
# Data Versioning Patterns Expert patterns for reproducible data management with DVC, Delta Lake, and data lineage tracking. ## Pattern 1: Git + DVC Workflow The core pattern: code in Git, data pointers in Git, data bytes in remote storage. ```bash # Initialize DVC in existing Git repo git init dvc init git add .dvc/ git commit -m "chore: initialize DVC" # Configure remote storage (S3 example) dvc remote add -d s3remote s3://my-ml-bucket/dvc-cache dvc remote modify s3remote region us-east-1
# Developer Guide Patterns > Patterns for writing developer onboarding documentation, contributing guides, and integration docs. ## Knowledge Base ### The Developer Journey Developers interact with a project through distinct phases, each needing different documentation: ``` Discover --> Evaluate --> Adopt --> Build --> Contribute --> Maintain | | | | | | README Quick Start Install Guides CONTRIBUTING Architecture + Exa
# Distributed Training Patterns Expert patterns for DDP, FSDP, DeepSpeed, and mixed precision training across multiple GPUs. ## Pattern 1: PyTorch DDP Training Loop Standard DDP setup with torchrun launcher, DistributedSampler, and proper cleanup. ```python # train_ddp.py import os import torch import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data import DataLoader, DistributedSampler def setup(rank: int, world_size: int): os
# Documentation Testing Patterns ## The Documentation Testing Pyramid Analogous to the software testing pyramid, documentation testing should be layered: ``` E2E (manual, periodic) / Can a real user follow the guide? \ / \ Integration (automated, weekly) / Cross-file links, external URLs \ / \ Unit (automated, every PR) Prose style, code execution, internal anchors, markdown formatting
# Experiment Tracking Patterns Expert patterns for MLflow, W&B, Optuna hyperparameter search, and experiment organization at scale. ## Pattern 1: MLflow Manual Logging Complete MLflow run with params, metrics, artifacts, and model signature. ```python import mlflow import mlflow.pytorch from mlflow.models import infer_signature import torch import numpy as np # Set tracking URI (local or server) mlflow.set_tracking_uri("http://mlflow-server:5000") # or "mlite:///mlflow.db" for local SQLite
# Feature Engineering Patterns Expert patterns for feature stores, sklearn pipelines, time-series features, and drift detection. ## Pattern 1: Feast Feature Store Setup Define entity, feature view, and feature service; retrieve point-in-time correct training data. ```python from feast import FeatureStore, Entity, FeatureView, Field, FileSource from feast.types import Float32, Int64, String from datetime import timedelta # feature_repo/feature_store.yaml # project: my_ml_project # registry:
# ML Pipeline Patterns Expert patterns for building batch and streaming ML data pipelines with Apache Beam, Spark, dbt, and orchestrators. ## Pattern 1: Apache Beam DoFn Pattern The `DoFn` is Beam's per-element processing unit. Structure it to handle setup, processing, and teardown correctly. ```python import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions class NormalizeFeaturesFn(beam.DoFn): """Normalize numerical features using precomputed statist
# Model Monitoring Patterns Expert patterns for data drift detection, concept drift, performance estimation without labels, and alert engineering. ## Pattern 1: PSI Feature Drift Monitor Population Stability Index for continuous and categorical features. ```python import numpy as np import pandas as pd from scipy.stats import ks_2samp, wasserstein_distance def compute_psi(reference: np.ndarray, current: np.ndarray, n_bins: int = 10, epsilon: float = 1e-6) -> float: """
# Model Registry Patterns Expert patterns for model registration, versioning, champion/challenger promotion, model cards, and webhook-driven CI/CD. ## Pattern 1: MLflow Registration with Signature and Lineage Register a model with full metadata: signature, metrics, dataset reference. ```python import mlflow import mlflow.sklearn from mlflow.models import infer_signature import pandas as pd mlflow.set_tracking_uri("http://mlflow-server:5000") with mlflow.start_run(run_name="churn-model-v2.1
# Onboarding Documentation Patterns ## Time-to-First-Success Optimization The single most important metric for onboarding documentation is time-to-first-success (TTFS): the time from a user arriving at your documentation to completing their first meaningful action. ### TTFS benchmarks by product type | Product Type | Target TTFS | |--------------|-------------| | CLI tool | < 5 minutes | | SDK/library | < 10 minutes | | API | < 15 minutes | | Platform/SaaS | < 30 minutes | ### Measuring TTFS
# OpenAPI Patterns > Comprehensive knowledge base for writing correct, consistent, and developer-friendly OpenAPI 3.x specifications. ## Knowledge Base ### OpenAPI 3.1 vs 3.0 OpenAPI 3.1 aligns with JSON Schema 2020-12. Key differences from 3.0: | Feature | 3.0 | 3.1 | |---------|-----|-----| | JSON Schema | Draft 4 (modified) | 2020-12 (full) | | Nullable | `nullable: true` | `type: ['string', 'null']` | | Exclusive min/max | `exclusiveMinimum: true` + `minimum: 0` | `exclusiveMinimum: 0`
# Prompt Engineering Patterns Expert patterns for chain-of-thought, few-shot design, structured output, ReAct agents, DSPy optimization, and prompt injection defense. ## Pattern 1: Chain-of-Thought with Few-Shot Examples Force step-by-step reasoning before final answer. ```python from anthropic import Anthropic client = Anthropic() COT_SYSTEM = """You are a medical coding assistant. You classify clinical notes into ICD-10 codes. Always reason through the clinical evidence before stating th
# PyTorch Patterns Expert patterns for custom Dataset/DataLoader, nn.Module design, model surgery, custom autograd, and profiling. ## Pattern 1: Custom Dataset with Transforms Production Dataset with augmentation pipeline and weighted sampling. ```python import torch from torch.utils.data import Dataset, DataLoader, WeightedRandomSampler import pandas as pd import numpy as np from pathlib import Path from PIL import Image import albumentations as A from albumentations.pytorch import ToTensor
# RAG Patterns Expert patterns for document chunking, embedding pipelines, hybrid search, cross-encoder re-ranking, and RAGAS evaluation. ## Pattern 1: Document Ingestion with Recursive Chunking Parse and chunk documents with metadata preservation. ```python from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.document_loaders import PyPDFLoader, TextLoader from langchain.schema import Document import hashlib from pathlib import Path def ingest_documents(file_pa
# README Patterns ## The 5-Second Test A developer landing on a README has 5 seconds before they decide to stay or leave. The test: - Close the README - Ask: "What does this project do?" - If you cannot answer in one sentence, the README failed The one-liner must complete this template: "[Name] is a [category] that [value proposition]." ```markdown # Bad: feature list as description A comprehensive toolkit with logging, caching, retry logic, and more. # Good: one-liner that passes the 5-sec
# Release Note Formats > Release note structures for different audiences, channels, and release types. ## Knowledge Base ### Release Note vs Changelog | Changelog | Release Notes | |-----------|--------------| | Technical record of changes | Communication to users | | Every version, every change | Curated highlights | | Developer audience | Multiple audiences | | Keep a Changelog format | Flexible format | | Lives in CHANGELOG.md | Lives in GitHub Releases, blog, email | A changelog is the
# Release Note Patterns ## Audience-First Writing The most common release note mistake: writing for the audience who built the feature, not the audience who uses it. Before writing, answer: "Who reads this, and what question are they trying to answer?" | Audience | Their Question | Write This | |----------|---------------|-----------| | End user | "Can I do something new?" | "You can now export reports as PDF" | | API developer | "Does this break my code?" | "Added `format` parameter to `expo
# Runbook Patterns ## The 3AM Test A runbook passes the 3AM test if a competent on-call engineer can: 1. Find the runbook from the alert within 30 seconds (alert must link directly to runbook) 2. Understand the scope within 60 seconds (overview section) 3. Start diagnosing within 2 minutes (first command is on screen without scrolling) If any of these fail, the runbook will be abandoned during an incident. ## Structure Pattern: Symptom → Cause → Remedy The fundamental runbook pattern. Every
# Spec Writing Patterns ## The Testability Test Every requirement must answer: "How would you verify this in a test case?" If you cannot write a test case from the requirement, it is not a requirement -- it is a wish. ``` # Wish (untestable) The checkout flow should be fast and intuitive. # Requirement (testable) The checkout flow shall complete in ≤ 3 user interactions from cart to order confirmation. The payment step shall respond to submission in ≤ 3s at p99 under normal load (≤ 500 concu
# Style Guide Frameworks > Frameworks and reference patterns for building effective writing style guides. ## Knowledge Base ### Industry Style Guide Comparison | Style Guide | Best For | Key Stance | |------------|----------|------------| | Google Developer Style Guide | Developer documentation | Present tense, active voice, second person | | Microsoft Writing Style Guide | Product documentation | Conversational, task-oriented, accessible | | Apple Style Guide | Consumer-facing docs | Minima
# Style Guide Patterns ## The 10-Rule Principle A style guide with 100 rules is a style guide no one reads. A style guide with 10 high-impact rules, automated by Vale, will actually be followed. Before writing any rule, answer: "Is this in the base guide already (Google, Microsoft)?" If yes, do not duplicate it. Link to it. Write only the rules where you differ or extend. The 10 most impactful rules for most technical teams: 1. Person (second vs. third) 2. Tense (present vs. future) 3. Voice
# TensorFlow Patterns Expert patterns for Keras functional API, tf.data pipeline ordering, custom layers, SavedModel export, and TFLite quantization. ## Pattern 1: Keras Functional API Model Multi-input model with proper BatchNorm and Dropout usage. ```python import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers def build_classifier( numeric_dim: int, cat_vocab_sizes: dict, # {"country": 50, "device": 10} embedding_dim: int = 16, hidden_u
# Training Patterns Expert patterns for PyTorch Lightning modules, HuggingFace Trainer, LR scheduling, gradient monitoring, checkpoint resume, and early stopping. ## Pattern 1: PyTorch Lightning LightningModule Complete LightningModule structure with validation, logging, and optimizer config. ```python import torch import torch.nn as nn import pytorch_lightning as pl from torch.optim import AdamW from torch.optim.lr_scheduler import CosineAnnealingLR from torchmetrics import AUROC, F1Score
# Error Message Patterns ## The Three-Part Error Message Every error message should answer three questions: 1. What happened? (context - what operation failed on what resource) 2. Why? (cause - the specific condition that prevented success) 3. Now what? (remedy - the concrete action to take) ``` # Bad: answers none of the three questions "An error occurred" "Error 422" "Invalid input" # Bad: answers what but not why or how "Validation failed" # Good: answers all three "Unable to create the
# Tutorial Structures > Pedagogical patterns and frameworks for creating effective technical tutorials. ## Knowledge Base ### The Tutorial Spectrum Tutorials exist on a spectrum between two extremes: | Recipe | Concept Guide | |--------|--------------| | "Do exactly this" | "Understand this idea" | | Step-by-step | Explanation-heavy | | Fast to complete | Deep understanding | | Low retention | High retention | The best tutorials blend both: steps for doing, explanations for understanding.
# VectorDB Patterns Expert patterns for HNSW index tuning, pgvector setup, Pinecone/Qdrant upsert, metadata filtering, multi-tenancy, and embedding drift management. ## Pattern 1: pgvector Setup with HNSW Index PostgreSQL vector search with proper index configuration. ```sql -- Install extension (requires PostgreSQL 15+ with pgvector) CREATE EXTENSION IF NOT EXISTS vector; -- Table with embedding column CREATE TABLE documents ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(),