diff --git a/.adal/README.md b/.adal/README.md
index f53ce7741..0c01a51c1 100644
--- a/.adal/README.md
+++ b/.adal/README.md
@@ -1,6 +1,6 @@
# ECC for AdaL CLI
-This directory contains the ECC (Everything Claude Code) configuration for the AdaL CLI harness.
+This directory contains the ECC configuration for the AdaL CLI harness.
## What is installed
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json
index e730e4eed..a69ad3709 100644
--- a/.agents/plugins/marketplace.json
+++ b/.agents/plugins/marketplace.json
@@ -6,7 +6,7 @@
"plugins": [
{
"name": "ecc",
- "version": "2.2.2",
+ "version": "2.2.3",
"source": {
"source": "local",
"path": "./"
diff --git a/.agents/skills/bun-runtime/SKILL.md b/.agents/skills/bun-runtime/SKILL.md
index ab748e26a..5bd36c241 100644
--- a/.agents/skills/bun-runtime/SKILL.md
+++ b/.agents/skills/bun-runtime/SKILL.md
@@ -17,21 +17,28 @@ Use when: adopting Bun, migrating from Node, writing or debugging Bun scripts/te
## How It Works
-- **Runtime**: Drop-in Node-compatible runtime (built on JavaScriptCore, implemented in Zig).
-- **Package manager**: `bun install` is significantly faster than npm/yarn. Lockfile is `bun.lock` (text) by default in current Bun; older versions used `bun.lockb` (binary).
+- **Version baseline**: guidance below targets Bun 1.4.x. Check the actual version with `bun --version` before relying on flag names, since CLI flags can change between releases.
+- **Runtime**: Drop-in Node-compatible runtime, built on JavaScriptCore. As of Bun 1.4 the runtime itself is implemented in Rust (migrated from Zig). Not 100% Node-compatible — some native addons, less-common `node:` internal APIs, and packages that depend on Node-specific internals can still fail; verify before depending on it in production.
+- **Package manager**: Bun includes a package manager; installation performance depends on the project, network conditions, and cache state. Lockfile is `bun.lock` (text) by default in current Bun; older versions used `bun.lockb` (binary) — Bun still reads that format for migration, but new projects should use `bun.lock`.
- **Bundler**: Built-in bundler and transpiler for apps and libraries.
-- **Test runner**: Built-in `bun test` with Jest-like API.
+- **Test runner**: Built-in `bun test` with a Jest-like API.
**Migration from Node**: Replace `node script.js` with `bun run script.js` or `bun script.js`. Run `bun install` in place of `npm install`; most packages work. Use `bun run` for npm scripts; `bun x` for npx-style one-off runs. Node built-ins are supported; prefer Bun APIs where they exist for better performance.
-**Vercel**: Set runtime to Bun in project settings. Build: `bun run build` or `bun build ./src/index.ts --outdir=dist`. Install: `bun install --frozen-lockfile` for reproducible deploys.
+**Package and workspace commands**: `bun add ` / `bun remove ` / `bun update [pkg]` manage dependencies; `bun outdated` lists stale deps. `bun pm ls` lists project dependencies and resolved versions using the lockfile; `--all` includes transitive dependencies. It is not an integrity check of installed file contents. [`bun audit`](https://bun.com/docs/pm/cli/audit) queries registry advisories using package names and versions from `bun.lock`; it does not modify `package.json`, `bun.lock`, or `node_modules`. Review approved destinations before sending private package metadata. Packages whose scoped registry lacks an advisory endpoint are skipped and do not affect the exit code. `bun audit fix` upgrades and installs dependencies, changing the lockfile and installed packages and sometimes direct version pins; review it as a modifying install operation, including applicable lifecycle scripts. `bun dedupe` collapses duplicate installs, and `bun prune` removes packages no longer referenced. Monorepos use a root `workspaces` array in `package.json` (same convention as npm/yarn); run a script in one workspace with `bun run --filter
+```
+
+### Safe String Handling
+
+```python
+from django.utils.safestring import mark_safe
+from django.utils.html import escape
+
+# BAD: Never mark user input as safe without escaping
+def render_bad(user_input):
+ return mark_safe(user_input) # VULNERABLE!
+
+# GOOD: Escape first, then mark safe
+def render_good(user_input):
+ return mark_safe(escape(user_input))
+
+# GOOD: Use format_html for HTML with variables
+from django.utils.html import format_html
+
+def greet_user(username):
+ return format_html('{}', escape(username))
+```
+
+### HTTP Headers
+
+```python
+# settings.py
+SECURE_CONTENT_TYPE_NOSNIFF = True # Prevent MIME sniffing
+X_FRAME_OPTIONS = 'DENY' # Prevent clickjacking
+
+# Custom middleware
+from django.conf import settings
+
+class SecurityHeaderMiddleware:
+ def __init__(self, get_response):
+ self.get_response = get_response
+
+ def __call__(self, request):
+ response = self.get_response(request)
+ response['X-Content-Type-Options'] = 'nosniff'
+ response['X-Frame-Options'] = 'DENY'
+ response['X-XSS-Protection'] = '1; mode=block'
+ response['Content-Security-Policy'] = "default-src 'self'"
+ return response
+```
+
+## CSRF Protection
+
+### Default CSRF Protection
+
+```python
+# settings.py - CSRF is enabled by default
+CSRF_COOKIE_SECURE = True # Only send over HTTPS
+CSRF_COOKIE_HTTPONLY = False # False so AJAX can read csrf token from document.cookie; SESSION_COOKIE_HTTPONLY remains True
+CSRF_COOKIE_SAMESITE = 'Lax' # Prevent CSRF in some cases
+CSRF_TRUSTED_ORIGINS = ['https://example.com'] # Trusted domains
+
+# Template usage
+
+
+# AJAX requests
+function getCookie(name) {
+ let cookieValue = null;
+ if (document.cookie && document.cookie !== '') {
+ const cookies = document.cookie.split(';');
+ for (let i = 0; i < cookies.length; i++) {
+ const cookie = cookies[i].trim();
+ if (cookie.substring(0, name.length + 1) === (name + '=')) {
+ cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
+ break;
+ }
+ }
+ }
+ return cookieValue;
+}
+
+fetch('/api/endpoint/', {
+ method: 'POST',
+ headers: {
+ 'X-CSRFToken': getCookie('csrftoken'),
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(data)
+});
+```
+
+### Exempting Views (Use Carefully)
+
+```python
+from django.views.decorators.csrf import csrf_exempt
+
+@csrf_exempt # Only use when absolutely necessary!
+def webhook_view(request):
+ # Webhook from external service
+ pass
+```
+
+## File Upload Security
+
+### File Validation
+
+```python
+import os
+import magic # pip install python-magic
+from django.core.exceptions import ValidationError
+
+ALLOWED_MIMES = {
+ 'image/jpeg', 'image/png', 'image/gif', 'application/pdf',
+}
+
+MIME_TO_EXTENSIONS = {
+ 'image/jpeg': {'.jpg', '.jpeg'},
+ 'image/png': {'.png'},
+ 'image/gif': {'.gif'},
+ 'application/pdf': {'.pdf'},
+}
+
+def validate_file_type(value):
+ """Validate file type using magic bytes and cross-check extension."""
+ mime = magic.from_buffer(value.read(2048), mime=True)
+ value.seek(0)
+
+ if mime not in ALLOWED_MIMES:
+ raise ValidationError('Unsupported file type.')
+
+ ext = os.path.splitext(value.name)[1].lower()
+ if ext not in MIME_TO_EXTENSIONS.get(mime, set()):
+ raise ValidationError('File extension does not match file content.')
+
+def validate_file_size(value):
+ """Validate file size (max 5MB)."""
+ if value.size > 5 * 1024 * 1024:
+ raise ValidationError('File too large. Max size is 5MB.')
+
+# models.py
+class Document(models.Model):
+ file = models.FileField(
+ upload_to='documents/',
+ validators=[validate_file_type, validate_file_size]
+ )
+
+```
+
+For environments where installing libmagic is difficult (e.g., minimal containers),
+use the pure-Python `filetype` package as an alternative:
+
+```python
+import os
+from django.core.exceptions import ValidationError
+
+import filetype # pip install filetype
+
+ALLOWED_MIMES = {
+ 'image/jpeg', 'image/png', 'image/gif', 'application/pdf',
+}
+
+MIME_TO_EXTENSIONS = {
+ 'image/jpeg': {'.jpg', '.jpeg'},
+ 'image/png': {'.png'},
+ 'image/gif': {'.gif'},
+ 'application/pdf': {'.pdf'},
+}
+
+def validate_file_type(value):
+ """Validate file type using magic bytes."""
+ kind = filetype.guess(value.read(2048))
+ value.seek(0)
+
+ if kind is None or kind.mime not in ALLOWED_MIMES:
+ raise ValidationError('Unsupported file type.')
+
+ ext = os.path.splitext(value.name)[1].lower()
+ if ext not in MIME_TO_EXTENSIONS.get(kind.mime, set()):
+ raise ValidationError('File extension does not match file content.')
+```
+
+### Secure File Storage
+
+```python
+# settings.py
+MEDIA_ROOT = '/var/www/media/'
+MEDIA_URL = '/media/'
+
+# Use a separate domain for media in production
+MEDIA_DOMAIN = 'https://media.example.com'
+
+# Don't serve user uploads directly
+# Use whitenoise or a CDN for static files
+# Use a separate server or S3 for media files
+```
+
+## API Security
+
+### Rate Limiting
+
+```python
+# settings.py
+REST_FRAMEWORK = {
+ 'DEFAULT_THROTTLE_CLASSES': [
+ 'rest_framework.throttling.AnonRateThrottle',
+ 'rest_framework.throttling.UserRateThrottle'
+ ],
+ 'DEFAULT_THROTTLE_RATES': {
+ 'anon': '100/day',
+ 'user': '1000/day',
+ 'upload': '10/hour',
+ }
+}
+
+# Custom throttle
+from rest_framework.throttling import UserRateThrottle
+
+class BurstRateThrottle(UserRateThrottle):
+ scope = 'burst'
+ rate = '60/min'
+
+class SustainedRateThrottle(UserRateThrottle):
+ scope = 'sustained'
+ rate = '1000/day'
+```
+
+### Authentication for APIs
+
+```python
+# settings.py
+REST_FRAMEWORK = {
+ 'DEFAULT_AUTHENTICATION_CLASSES': [
+ 'rest_framework.authentication.TokenAuthentication',
+ 'rest_framework.authentication.SessionAuthentication',
+ 'rest_framework_simplejwt.authentication.JWTAuthentication',
+ ],
+ 'DEFAULT_PERMISSION_CLASSES': [
+ 'rest_framework.permissions.IsAuthenticated',
+ ],
+}
+
+# views.py
+from rest_framework.decorators import api_view, permission_classes
+from rest_framework.permissions import IsAuthenticated
+
+@api_view(['GET', 'POST'])
+@permission_classes([IsAuthenticated])
+def protected_view(request):
+ return Response({'message': 'You are authenticated'})
+```
+
+## Security Headers
+
+### Content Security Policy
+
+```python
+# settings.py
+CSP_DEFAULT_SRC = "'self'"
+CSP_SCRIPT_SRC = "'self' https://cdn.example.com"
+CSP_STYLE_SRC = "'self' 'unsafe-inline'"
+CSP_IMG_SRC = "'self' data: https:"
+CSP_CONNECT_SRC = "'self' https://api.example.com"
+
+# Middleware
+class CSPMiddleware:
+ def __init__(self, get_response):
+ self.get_response = get_response
+
+ def __call__(self, request):
+ response = self.get_response(request)
+ response['Content-Security-Policy'] = (
+ f"default-src {CSP_DEFAULT_SRC}; "
+ f"script-src {CSP_SCRIPT_SRC}; "
+ f"style-src {CSP_STYLE_SRC}; "
+ f"img-src {CSP_IMG_SRC}; "
+ f"connect-src {CSP_CONNECT_SRC}"
+ )
+ return response
+```
+
+## Environment Variables
+
+### Managing Secrets
+
+```python
+# Use python-decouple or django-environ
+import environ
+
+env = environ.Env(
+ # set casting, default value
+ DEBUG=(bool, False)
+)
+
+# reading .env file
+environ.Env.read_env()
+
+SECRET_KEY = env('DJANGO_SECRET_KEY')
+DATABASE_URL = env('DATABASE_URL')
+ALLOWED_HOSTS = env.list('ALLOWED_HOSTS')
+
+# .env file (never commit this)
+DEBUG=False
+SECRET_KEY=your-secret-key-here
+DATABASE_URL=postgresql://user:password@localhost:5432/dbname
+ALLOWED_HOSTS=example.com,www.example.com
+```
+
+## Logging Security Events
+
+```python
+# settings.py
+LOGGING = {
+ 'version': 1,
+ 'disable_existing_loggers': False,
+ 'handlers': {
+ 'file': {
+ 'level': 'WARNING',
+ 'class': 'logging.FileHandler',
+ 'filename': '/var/log/django/security.log',
+ },
+ 'console': {
+ 'level': 'INFO',
+ 'class': 'logging.StreamHandler',
+ },
+ },
+ 'loggers': {
+ 'django.security': {
+ 'handlers': ['file', 'console'],
+ 'level': 'WARNING',
+ 'propagate': True,
+ },
+ 'django.request': {
+ 'handlers': ['file'],
+ 'level': 'ERROR',
+ 'propagate': False,
+ },
+ },
+}
+```
+
+## Quick Security Checklist
+
+| Check | Description |
+|-------|-------------|
+| `DEBUG = False` | Never run with DEBUG in production |
+| HTTPS only | Force SSL, secure cookies |
+| Strong secrets | Use environment variables for SECRET_KEY |
+| Password validation | Enable all password validators |
+| CSRF protection | Enabled by default, don't disable |
+| XSS prevention | Django auto-escapes, don't use `|safe` with user input |
+| SQL injection | Use ORM, never concatenate strings in queries |
+| File uploads | Validate file type and size |
+| Rate limiting | Throttle API endpoints |
+| Security headers | CSP, X-Frame-Options, HSTS |
+| Logging | Log security events |
+| Updates | Keep Django and dependencies updated |
+
+Remember: Security is a process, not a product. Regularly review and update your security practices.
diff --git a/pi/core/skills/django-tdd/SKILL.md b/pi/core/skills/django-tdd/SKILL.md
new file mode 100644
index 000000000..aaa2cd87f
--- /dev/null
+++ b/pi/core/skills/django-tdd/SKILL.md
@@ -0,0 +1,730 @@
+---
+name: django-tdd
+description: Django testing strategies with pytest-django, TDD methodology, factory_boy, mocking, coverage, and testing Django REST Framework APIs. Use when writing Django or DRF tests with pytest-django, or driving a Django feature test-first.
+metadata:
+ origin: ECC
+---
+
+# Django Testing with TDD
+
+Test-driven development for Django applications using pytest, factory_boy, and Django REST Framework.
+
+## When to Activate
+
+- Writing new Django applications
+- Implementing Django REST Framework APIs
+- Testing Django models, views, and serializers
+- Setting up testing infrastructure for Django projects
+
+## TDD Workflow for Django
+
+### Red-Green-Refactor Cycle
+
+```python
+# Step 1: RED - Write failing test
+def test_user_creation():
+ user = User.objects.create_user(email='test@example.com', password='testpass123')
+ assert user.email == 'test@example.com'
+ assert user.check_password('testpass123')
+ assert not user.is_staff
+
+# Step 2: GREEN - Make test pass
+# Create User model or factory
+
+# Step 3: REFACTOR - Improve while keeping tests green
+```
+
+## Setup
+
+### pytest Configuration
+
+```ini
+# pytest.ini
+[pytest]
+DJANGO_SETTINGS_MODULE = config.settings.test
+testpaths = tests
+python_files = test_*.py
+python_classes = Test*
+python_functions = test_*
+addopts =
+ --reuse-db
+ --nomigrations
+ --cov=apps
+ --cov-report=html
+ --cov-report=term-missing
+ --strict-markers
+markers =
+ slow: marks tests as slow
+ integration: marks tests as integration tests
+```
+
+### Test Settings
+
+```python
+# config/settings/test.py
+from .base import *
+
+DEBUG = True
+DATABASES = {
+ 'default': {
+ 'ENGINE': 'django.db.backends.sqlite3',
+ 'NAME': ':memory:',
+ }
+}
+
+# Disable migrations for speed
+class DisableMigrations:
+ def __contains__(self, item):
+ return True
+
+ def __getitem__(self, item):
+ return None
+
+MIGRATION_MODULES = DisableMigrations()
+
+# Faster password hashing
+PASSWORD_HASHERS = [
+ 'django.contrib.auth.hashers.MD5PasswordHasher',
+]
+
+# Email backend
+EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
+
+# Celery always eager
+CELERY_TASK_ALWAYS_EAGER = True
+CELERY_TASK_EAGER_PROPAGATES = True
+```
+
+### conftest.py
+
+```python
+# tests/conftest.py
+import pytest
+from django.utils import timezone
+from django.contrib.auth import get_user_model
+
+User = get_user_model()
+
+@pytest.fixture(autouse=True)
+def timezone_settings(settings):
+ """Ensure consistent timezone."""
+ settings.TIME_ZONE = 'UTC'
+
+@pytest.fixture
+def user(db):
+ """Create a test user."""
+ return User.objects.create_user(
+ email='test@example.com',
+ password='testpass123',
+ username='testuser'
+ )
+
+@pytest.fixture
+def admin_user(db):
+ """Create an admin user."""
+ return User.objects.create_superuser(
+ email='admin@example.com',
+ password='adminpass123',
+ username='admin'
+ )
+
+@pytest.fixture
+def authenticated_client(client, user):
+ """Return authenticated client."""
+ client.force_login(user)
+ return client
+
+@pytest.fixture
+def api_client():
+ """Return DRF API client."""
+ from rest_framework.test import APIClient
+ return APIClient()
+
+@pytest.fixture
+def authenticated_api_client(api_client, user):
+ """Return authenticated API client."""
+ api_client.force_authenticate(user=user)
+ return api_client
+```
+
+## Factory Boy
+
+### Factory Setup
+
+```python
+# tests/factories.py
+import factory
+from factory import fuzzy
+from datetime import datetime, timedelta
+from django.contrib.auth import get_user_model
+from apps.products.models import Product, Category
+
+User = get_user_model()
+
+class UserFactory(factory.django.DjangoModelFactory):
+ """Factory for User model."""
+
+ class Meta:
+ model = User
+
+ email = factory.Sequence(lambda n: f"user{n}@example.com")
+ username = factory.Sequence(lambda n: f"user{n}")
+ password = factory.PostGenerationMethodCall('set_password', 'testpass123')
+ first_name = factory.Faker('first_name')
+ last_name = factory.Faker('last_name')
+ is_active = True
+
+class CategoryFactory(factory.django.DjangoModelFactory):
+ """Factory for Category model."""
+
+ class Meta:
+ model = Category
+
+ name = factory.Faker('word')
+ slug = factory.LazyAttribute(lambda obj: obj.name.lower())
+ description = factory.Faker('text')
+
+class ProductFactory(factory.django.DjangoModelFactory):
+ """Factory for Product model."""
+
+ class Meta:
+ model = Product
+
+ name = factory.Faker('sentence', nb_words=3)
+ slug = factory.LazyAttribute(lambda obj: obj.name.lower().replace(' ', '-'))
+ description = factory.Faker('text')
+ price = fuzzy.FuzzyDecimal(10.00, 1000.00, 2)
+ stock = fuzzy.FuzzyInteger(0, 100)
+ is_active = True
+ category = factory.SubFactory(CategoryFactory)
+ created_by = factory.SubFactory(UserFactory)
+
+ @factory.post_generation
+ def tags(self, create, extracted, **kwargs):
+ """Add tags to product."""
+ if not create:
+ return
+ if extracted:
+ for tag in extracted:
+ self.tags.add(tag)
+```
+
+### Using Factories
+
+```python
+# tests/test_models.py
+import pytest
+from tests.factories import ProductFactory, UserFactory
+
+def test_product_creation():
+ """Test product creation using factory."""
+ product = ProductFactory(price=100.00, stock=50)
+ assert product.price == 100.00
+ assert product.stock == 50
+ assert product.is_active is True
+
+def test_product_with_tags():
+ """Test product with tags."""
+ tags = [TagFactory(name='electronics'), TagFactory(name='new')]
+ product = ProductFactory(tags=tags)
+ assert product.tags.count() == 2
+
+def test_multiple_products():
+ """Test creating multiple products."""
+ products = ProductFactory.create_batch(10)
+ assert len(products) == 10
+```
+
+## Model Testing
+
+### Model Tests
+
+```python
+# tests/test_models.py
+import pytest
+from django.core.exceptions import ValidationError
+from tests.factories import UserFactory, ProductFactory
+
+class TestUserModel:
+ """Test User model."""
+
+ def test_create_user(self, db):
+ """Test creating a regular user."""
+ user = UserFactory(email='test@example.com')
+ assert user.email == 'test@example.com'
+ assert user.check_password('testpass123')
+ assert not user.is_staff
+ assert not user.is_superuser
+
+ def test_create_superuser(self, db):
+ """Test creating a superuser."""
+ user = UserFactory(
+ email='admin@example.com',
+ is_staff=True,
+ is_superuser=True
+ )
+ assert user.is_staff
+ assert user.is_superuser
+
+ def test_user_str(self, db):
+ """Test user string representation."""
+ user = UserFactory(email='test@example.com')
+ assert str(user) == 'test@example.com'
+
+class TestProductModel:
+ """Test Product model."""
+
+ def test_product_creation(self, db):
+ """Test creating a product."""
+ product = ProductFactory()
+ assert product.id is not None
+ assert product.is_active is True
+ assert product.created_at is not None
+
+ def test_product_slug_generation(self, db):
+ """Test automatic slug generation."""
+ product = ProductFactory(name='Test Product')
+ assert product.slug == 'test-product'
+
+ def test_product_price_validation(self, db):
+ """Test price cannot be negative."""
+ product = ProductFactory(price=-10)
+ with pytest.raises(ValidationError):
+ product.full_clean()
+
+ def test_product_manager_active(self, db):
+ """Test active manager method."""
+ ProductFactory.create_batch(5, is_active=True)
+ ProductFactory.create_batch(3, is_active=False)
+
+ active_count = Product.objects.active().count()
+ assert active_count == 5
+
+ def test_product_stock_management(self, db):
+ """Test stock management."""
+ product = ProductFactory(stock=10)
+ product.reduce_stock(5)
+ product.refresh_from_db()
+ assert product.stock == 5
+
+ with pytest.raises(ValueError):
+ product.reduce_stock(10) # Not enough stock
+```
+
+## View Testing
+
+### Django View Testing
+
+```python
+# tests/test_views.py
+import pytest
+from django.urls import reverse
+from tests.factories import ProductFactory, UserFactory
+
+class TestProductViews:
+ """Test product views."""
+
+ def test_product_list(self, client, db):
+ """Test product list view."""
+ ProductFactory.create_batch(10)
+
+ response = client.get(reverse('products:list'))
+
+ assert response.status_code == 200
+ assert len(response.context['products']) == 10
+
+ def test_product_detail(self, client, db):
+ """Test product detail view."""
+ product = ProductFactory()
+
+ response = client.get(reverse('products:detail', kwargs={'slug': product.slug}))
+
+ assert response.status_code == 200
+ assert response.context['product'] == product
+
+ def test_product_create_requires_login(self, client, db):
+ """Test product creation requires authentication."""
+ response = client.get(reverse('products:create'))
+
+ assert response.status_code == 302
+ assert response.url.startswith('/accounts/login/')
+
+ def test_product_create_authenticated(self, authenticated_client, db):
+ """Test product creation as authenticated user."""
+ response = authenticated_client.get(reverse('products:create'))
+
+ assert response.status_code == 200
+
+ def test_product_create_post(self, authenticated_client, db, category):
+ """Test creating a product via POST."""
+ data = {
+ 'name': 'Test Product',
+ 'description': 'A test product',
+ 'price': '99.99',
+ 'stock': 10,
+ 'category': category.id,
+ }
+
+ response = authenticated_client.post(reverse('products:create'), data)
+
+ assert response.status_code == 302
+ assert Product.objects.filter(name='Test Product').exists()
+```
+
+## DRF API Testing
+
+### Serializer Testing
+
+```python
+# tests/test_serializers.py
+import pytest
+from rest_framework.exceptions import ValidationError
+from apps.products.serializers import ProductSerializer
+from tests.factories import ProductFactory
+
+class TestProductSerializer:
+ """Test ProductSerializer."""
+
+ def test_serialize_product(self, db):
+ """Test serializing a product."""
+ product = ProductFactory()
+ serializer = ProductSerializer(product)
+
+ data = serializer.data
+
+ assert data['id'] == product.id
+ assert data['name'] == product.name
+ assert data['price'] == str(product.price)
+
+ def test_deserialize_product(self, db):
+ """Test deserializing product data."""
+ data = {
+ 'name': 'Test Product',
+ 'description': 'Test description',
+ 'price': '99.99',
+ 'stock': 10,
+ 'category': 1,
+ }
+
+ serializer = ProductSerializer(data=data)
+
+ assert serializer.is_valid()
+ product = serializer.save()
+
+ assert product.name == 'Test Product'
+ assert float(product.price) == 99.99
+
+ def test_price_validation(self, db):
+ """Test price validation."""
+ data = {
+ 'name': 'Test Product',
+ 'price': '-10.00',
+ 'stock': 10,
+ }
+
+ serializer = ProductSerializer(data=data)
+
+ assert not serializer.is_valid()
+ assert 'price' in serializer.errors
+
+ def test_stock_validation(self, db):
+ """Test stock cannot be negative."""
+ data = {
+ 'name': 'Test Product',
+ 'price': '99.99',
+ 'stock': -5,
+ }
+
+ serializer = ProductSerializer(data=data)
+
+ assert not serializer.is_valid()
+ assert 'stock' in serializer.errors
+```
+
+### API ViewSet Testing
+
+```python
+# tests/test_api.py
+import pytest
+from rest_framework.test import APIClient
+from rest_framework import status
+from django.urls import reverse
+from tests.factories import ProductFactory, UserFactory
+
+class TestProductAPI:
+ """Test Product API endpoints."""
+
+ @pytest.fixture
+ def api_client(self):
+ """Return API client."""
+ return APIClient()
+
+ def test_list_products(self, api_client, db):
+ """Test listing products."""
+ ProductFactory.create_batch(10)
+
+ url = reverse('api:product-list')
+ response = api_client.get(url)
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.data['count'] == 10
+
+ def test_retrieve_product(self, api_client, db):
+ """Test retrieving a product."""
+ product = ProductFactory()
+
+ url = reverse('api:product-detail', kwargs={'pk': product.id})
+ response = api_client.get(url)
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.data['id'] == product.id
+
+ def test_create_product_unauthorized(self, api_client, db):
+ """Test creating product without authentication."""
+ url = reverse('api:product-list')
+ data = {'name': 'Test Product', 'price': '99.99'}
+
+ response = api_client.post(url, data)
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_create_product_authorized(self, authenticated_api_client, db):
+ """Test creating product as authenticated user."""
+ url = reverse('api:product-list')
+ data = {
+ 'name': 'Test Product',
+ 'description': 'Test',
+ 'price': '99.99',
+ 'stock': 10,
+ }
+
+ response = authenticated_api_client.post(url, data)
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.data['name'] == 'Test Product'
+
+ def test_update_product(self, authenticated_api_client, db):
+ """Test updating a product."""
+ product = ProductFactory(created_by=authenticated_api_client.user)
+
+ url = reverse('api:product-detail', kwargs={'pk': product.id})
+ data = {'name': 'Updated Product'}
+
+ response = authenticated_api_client.patch(url, data)
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.data['name'] == 'Updated Product'
+
+ def test_delete_product(self, authenticated_api_client, db):
+ """Test deleting a product."""
+ product = ProductFactory(created_by=authenticated_api_client.user)
+
+ url = reverse('api:product-detail', kwargs={'pk': product.id})
+ response = authenticated_api_client.delete(url)
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+
+ def test_filter_products_by_price(self, api_client, db):
+ """Test filtering products by price."""
+ ProductFactory(price=50)
+ ProductFactory(price=150)
+
+ url = reverse('api:product-list')
+ response = api_client.get(url, {'price_min': 100})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.data['count'] == 1
+
+ def test_search_products(self, api_client, db):
+ """Test searching products."""
+ ProductFactory(name='Apple iPhone')
+ ProductFactory(name='Samsung Galaxy')
+
+ url = reverse('api:product-list')
+ response = api_client.get(url, {'search': 'Apple'})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.data['count'] == 1
+```
+
+## Mocking and Patching
+
+### Mocking External Services
+
+```python
+# tests/test_views.py
+from unittest.mock import patch, Mock
+import pytest
+
+class TestPaymentView:
+ """Test payment view with mocked payment gateway."""
+
+ @patch('apps.payments.services.stripe')
+ def test_successful_payment(self, mock_stripe, client, user, product):
+ """Test successful payment with mocked Stripe."""
+ # Configure mock
+ mock_stripe.Charge.create.return_value = {
+ 'id': 'ch_123',
+ 'status': 'succeeded',
+ 'amount': 9999,
+ }
+
+ client.force_login(user)
+ response = client.post(reverse('payments:process'), {
+ 'product_id': product.id,
+ 'token': 'tok_visa',
+ })
+
+ assert response.status_code == 302
+ mock_stripe.Charge.create.assert_called_once()
+
+ @patch('apps.payments.services.stripe')
+ def test_failed_payment(self, mock_stripe, client, user, product):
+ """Test failed payment."""
+ mock_stripe.Charge.create.side_effect = Exception('Card declined')
+
+ client.force_login(user)
+ response = client.post(reverse('payments:process'), {
+ 'product_id': product.id,
+ 'token': 'tok_visa',
+ })
+
+ assert response.status_code == 302
+ assert 'error' in response.url
+```
+
+### Mocking Email Sending
+
+```python
+# tests/test_email.py
+from django.core import mail
+from django.test import override_settings
+
+@override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend')
+def test_order_confirmation_email(db, order):
+ """Test order confirmation email."""
+ order.send_confirmation_email()
+
+ assert len(mail.outbox) == 1
+ assert order.user.email in mail.outbox[0].to
+ assert 'Order Confirmation' in mail.outbox[0].subject
+```
+
+## Integration Testing
+
+### Full Flow Testing
+
+```python
+# tests/test_integration.py
+import pytest
+from django.urls import reverse
+from tests.factories import UserFactory, ProductFactory
+
+class TestCheckoutFlow:
+ """Test complete checkout flow."""
+
+ def test_guest_to_purchase_flow(self, client, db):
+ """Test complete flow from guest to purchase."""
+ # Step 1: Register
+ response = client.post(reverse('users:register'), {
+ 'email': 'test@example.com',
+ 'password': 'testpass123',
+ 'password_confirm': 'testpass123',
+ })
+ assert response.status_code == 302
+
+ # Step 2: Login
+ response = client.post(reverse('users:login'), {
+ 'email': 'test@example.com',
+ 'password': 'testpass123',
+ })
+ assert response.status_code == 302
+
+ # Step 3: Browse products
+ product = ProductFactory(price=100)
+ response = client.get(reverse('products:detail', kwargs={'slug': product.slug}))
+ assert response.status_code == 200
+
+ # Step 4: Add to cart
+ response = client.post(reverse('cart:add'), {
+ 'product_id': product.id,
+ 'quantity': 1,
+ })
+ assert response.status_code == 302
+
+ # Step 5: Checkout
+ response = client.get(reverse('checkout:review'))
+ assert response.status_code == 200
+ assert product.name in response.content.decode()
+
+ # Step 6: Complete purchase
+ with patch('apps.checkout.services.process_payment') as mock_payment:
+ mock_payment.return_value = True
+ response = client.post(reverse('checkout:complete'))
+
+ assert response.status_code == 302
+ assert Order.objects.filter(user__email='test@example.com').exists()
+```
+
+## Testing Best Practices
+
+### DO
+
+- **Use factories**: Instead of manual object creation
+- **One assertion per test**: Keep tests focused
+- **Descriptive test names**: `test_user_cannot_delete_others_post`
+- **Test edge cases**: Empty inputs, None values, boundary conditions
+- **Mock external services**: Don't depend on external APIs
+- **Use fixtures**: Eliminate duplication
+- **Test permissions**: Ensure authorization works
+- **Keep tests fast**: Use `--reuse-db` and `--nomigrations`
+
+### DON'T
+
+- **Don't test Django internals**: Trust Django to work
+- **Don't test third-party code**: Trust libraries to work
+- **Don't ignore failing tests**: All tests must pass
+- **Don't make tests dependent**: Tests should run in any order
+- **Don't over-mock**: Mock only external dependencies
+- **Don't test private methods**: Test public interface
+- **Don't use production database**: Always use test database
+
+## Coverage
+
+### Coverage Configuration
+
+```bash
+# Run tests with coverage
+pytest --cov=apps --cov-report=html --cov-report=term-missing
+
+# Generate HTML report
+open htmlcov/index.html
+```
+
+### Coverage Goals
+
+| Component | Target Coverage |
+|-----------|-----------------|
+| Models | 90%+ |
+| Serializers | 85%+ |
+| Views | 80%+ |
+| Services | 90%+ |
+| Utilities | 80%+ |
+| Overall | 80%+ |
+
+## Quick Reference
+
+| Pattern | Usage |
+|---------|-------|
+| `@pytest.mark.django_db` | Enable database access |
+| `client` | Django test client |
+| `api_client` | DRF API client |
+| `factory.create_batch(n)` | Create multiple objects |
+| `patch('module.function')` | Mock external dependencies |
+| `override_settings` | Temporarily change settings |
+| `force_authenticate()` | Bypass authentication in tests |
+| `assertRedirects` | Check for redirects |
+| `assertTemplateUsed` | Verify template usage |
+| `mail.outbox` | Check sent emails |
+
+Remember: Tests are documentation. Good tests explain how your code should work. Keep them simple, readable, and maintainable.
diff --git a/pi/core/skills/django-verification/SKILL.md b/pi/core/skills/django-verification/SKILL.md
new file mode 100644
index 000000000..2c5062f02
--- /dev/null
+++ b/pi/core/skills/django-verification/SKILL.md
@@ -0,0 +1,470 @@
+---
+name: django-verification
+description: Run the full Django verification loop — environment check, mypy/ruff/black linting, migration safety, pytest with coverage targets, pip-audit and bandit security scans, settings and logging review, and diff review — producing a phased pass/fail report before release or PR. Use when preparing a Django pull request, validating migrations or coverage, or running pre-deploy readiness checks.
+metadata:
+ origin: ECC
+---
+
+# Django Verification Loop
+
+Run before PRs, after major changes, and pre-deploy to ensure Django application quality and security.
+
+## When to Activate
+
+- Before opening a pull request for a Django project
+- After major model changes, migration updates, or dependency upgrades
+- Pre-deployment verification for staging or production
+- Running full environment → lint → test → security → deploy readiness pipeline
+- Validating migration safety and test coverage
+
+## Phase 1: Environment Check
+
+```bash
+# Verify Python version
+python --version # Should match project requirements
+
+# Check virtual environment
+which python
+pip list --outdated
+
+# Verify environment variables
+python -c "import os; import environ; print('DJANGO_SECRET_KEY set' if os.environ.get('DJANGO_SECRET_KEY') else 'MISSING: DJANGO_SECRET_KEY')"
+```
+
+If environment is misconfigured, stop and fix.
+
+## Phase 2: Code Quality & Formatting
+
+```bash
+# Type checking
+mypy . --config-file pyproject.toml
+
+# Linting with ruff
+ruff check . --fix
+
+# Formatting with black
+black . --check
+black . # Auto-fix
+
+# Import sorting
+isort . --check-only
+isort . # Auto-fix
+
+# Django-specific checks
+python manage.py check --deploy
+```
+
+Common issues:
+- Missing type hints on public functions
+- PEP 8 formatting violations
+- Unsorted imports
+- Debug settings left in production configuration
+
+## Phase 3: Migrations
+
+```bash
+# Check for unapplied migrations
+python manage.py showmigrations
+
+# Create missing migrations
+python manage.py makemigrations --check
+
+# Dry-run migration application
+python manage.py migrate --plan
+
+# Apply migrations (test environment)
+python manage.py migrate
+
+# Check for migration conflicts
+python manage.py makemigrations --merge # Only if conflicts exist
+```
+
+Report:
+- Number of pending migrations
+- Any migration conflicts
+- Model changes without migrations
+
+## Phase 4: Tests + Coverage
+
+```bash
+# Run all tests with pytest
+pytest --cov=apps --cov-report=html --cov-report=term-missing --reuse-db
+
+# Run specific app tests
+pytest apps/users/tests/
+
+# Run with markers
+pytest -m "not slow" # Skip slow tests
+pytest -m integration # Only integration tests
+
+# Coverage report
+open htmlcov/index.html
+```
+
+Report:
+- Total tests: X passed, Y failed, Z skipped
+- Overall coverage: XX%
+- Per-app coverage breakdown
+
+Coverage targets:
+
+| Component | Target |
+|-----------|--------|
+| Models | 90%+ |
+| Serializers | 85%+ |
+| Views | 80%+ |
+| Services | 90%+ |
+| Overall | 80%+ |
+
+## Phase 5: Security Scan
+
+```bash
+# Dependency vulnerabilities
+pip-audit
+safety check --full-report
+
+# Django security checks
+python manage.py check --deploy
+
+# Bandit security linter
+bandit -r . -f json -o bandit-report.json
+
+# Secret scanning (if gitleaks is installed)
+gitleaks detect --source . --verbose
+
+# Environment variable check
+python -c "from django.core.exceptions import ImproperlyConfigured; from django.conf import settings; settings.DEBUG"
+```
+
+Report:
+- Vulnerable dependencies found
+- Security configuration issues
+- Hardcoded secrets detected
+- DEBUG mode status (should be False in production)
+
+## Phase 6: Django Management Commands
+
+```bash
+# Check for model issues
+python manage.py check
+
+# Collect static files
+python manage.py collectstatic --noinput --clear
+
+# Create superuser (if needed for tests)
+echo "from apps.users.models import User; User.objects.create_superuser('admin@example.com', 'admin')" | python manage.py shell
+
+# Database integrity
+python manage.py check --database default
+
+# Cache verification (if using Redis)
+python -c "from django.core.cache import cache; cache.set('test', 'value', 10); print(cache.get('test'))"
+```
+
+## Phase 7: Performance Checks
+
+```bash
+# Django Debug Toolbar output (check for N+1 queries)
+# Run in dev mode with DEBUG=True and access a page
+# Look for duplicate queries in SQL panel
+
+# Query count analysis
+django-admin debugsqlshell # If django-debug-sqlshell installed
+
+# Check for missing indexes
+python manage.py shell << EOF
+from django.db import connection
+with connection.cursor() as cursor:
+ cursor.execute("SELECT table_name, index_name FROM information_schema.statistics WHERE table_schema = 'public'")
+ print(cursor.fetchall())
+EOF
+```
+
+Report:
+- Number of queries per page (should be < 50 for typical pages)
+- Missing database indexes
+- Duplicate queries detected
+
+## Phase 8: Static Assets
+
+```bash
+# Check for npm dependencies (if using npm)
+npm audit
+npm audit fix
+
+# Build static files (if using webpack/vite)
+npm run build
+
+# Verify static files
+ls -la staticfiles/
+python manage.py findstatic css/style.css
+```
+
+## Phase 9: Configuration Review
+
+```python
+# Run in Python shell to verify settings
+python manage.py shell << EOF
+from django.conf import settings
+import os
+
+# Critical checks
+checks = {
+ 'DEBUG is False': not settings.DEBUG,
+ 'SECRET_KEY set': bool(settings.SECRET_KEY and len(settings.SECRET_KEY) > 30),
+ 'ALLOWED_HOSTS set': len(settings.ALLOWED_HOSTS) > 0,
+ 'HTTPS enabled': getattr(settings, 'SECURE_SSL_REDIRECT', False),
+ 'HSTS enabled': getattr(settings, 'SECURE_HSTS_SECONDS', 0) > 0,
+ 'Database configured': settings.DATABASES['default']['ENGINE'] != 'django.db.backends.sqlite3',
+}
+
+for check, result in checks.items():
+ status = '✓' if result else '✗'
+ print(f"{status} {check}")
+EOF
+```
+
+## Phase 10: Logging Configuration
+
+```bash
+# Test logging output
+python manage.py shell << EOF
+import logging
+logger = logging.getLogger('django')
+logger.warning('Test warning message')
+logger.error('Test error message')
+EOF
+
+# Check log files (if configured)
+tail -f /var/log/django/django.log
+```
+
+## Phase 11: API Documentation (if DRF)
+
+```bash
+# Generate schema
+python manage.py generateschema --format openapi-json > schema.json
+
+# Validate schema
+# Check if schema.json is valid JSON
+python -c "import json; json.load(open('schema.json'))"
+
+# Access Swagger UI (if using drf-yasg)
+# Visit http://localhost:8000/swagger/ in browser
+```
+
+## Phase 12: Diff Review
+
+```bash
+# Show diff statistics
+git diff --stat
+
+# Show actual changes
+git diff
+
+# Show changed files
+git diff --name-only
+
+# Check for common issues
+git diff | grep -i "todo\|fixme\|hack\|xxx"
+git diff | grep "print(" # Debug statements
+git diff | grep "DEBUG = True" # Debug mode
+git diff | grep "import pdb" # Debugger
+```
+
+Checklist:
+- No debugging statements (print, pdb, breakpoint())
+- No TODO/FIXME comments in critical code
+- No hardcoded secrets or credentials
+- Database migrations included for model changes
+- Configuration changes documented
+- Error handling present for external calls
+- Transaction management where needed
+
+## Output Template
+
+```
+DJANGO VERIFICATION REPORT
+==========================
+
+Phase 1: Environment Check
+ ✓ Python 3.11.5
+ ✓ Virtual environment active
+ ✓ All environment variables set
+
+Phase 2: Code Quality
+ ✓ mypy: No type errors
+ ✗ ruff: 3 issues found (auto-fixed)
+ ✓ black: No formatting issues
+ ✓ isort: Imports properly sorted
+ ✓ manage.py check: No issues
+
+Phase 3: Migrations
+ ✓ No unapplied migrations
+ ✓ No migration conflicts
+ ✓ All models have migrations
+
+Phase 4: Tests + Coverage
+ Tests: 247 passed, 0 failed, 5 skipped
+ Coverage:
+ Overall: 87%
+ users: 92%
+ products: 89%
+ orders: 85%
+ payments: 91%
+
+Phase 5: Security Scan
+ ✗ pip-audit: 2 vulnerabilities found (fix required)
+ ✓ safety check: No issues
+ ✓ bandit: No security issues
+ ✓ No secrets detected
+ ✓ DEBUG = False
+
+Phase 6: Django Commands
+ ✓ collectstatic completed
+ ✓ Database integrity OK
+ ✓ Cache backend reachable
+
+Phase 7: Performance
+ ✓ No N+1 queries detected
+ ✓ Database indexes configured
+ ✓ Query count acceptable
+
+Phase 8: Static Assets
+ ✓ npm audit: No vulnerabilities
+ ✓ Assets built successfully
+ ✓ Static files collected
+
+Phase 9: Configuration
+ ✓ DEBUG = False
+ ✓ SECRET_KEY configured
+ ✓ ALLOWED_HOSTS set
+ ✓ HTTPS enabled
+ ✓ HSTS enabled
+ ✓ Database configured
+
+Phase 10: Logging
+ ✓ Logging configured
+ ✓ Log files writable
+
+Phase 11: API Documentation
+ ✓ Schema generated
+ ✓ Swagger UI accessible
+
+Phase 12: Diff Review
+ Files changed: 12
+ +450, -120 lines
+ ✓ No debug statements
+ ✓ No hardcoded secrets
+ ✓ Migrations included
+
+RECOMMENDATION: WARNING: Fix pip-audit vulnerabilities before deploying
+
+NEXT STEPS:
+1. Update vulnerable dependencies
+2. Re-run security scan
+3. Deploy to staging for final testing
+```
+
+## Pre-Deployment Checklist
+
+- [ ] All tests passing
+- [ ] Coverage ≥ 80%
+- [ ] No security vulnerabilities
+- [ ] No unapplied migrations
+- [ ] DEBUG = False in production settings
+- [ ] SECRET_KEY properly configured
+- [ ] ALLOWED_HOSTS set correctly
+- [ ] Database backups enabled
+- [ ] Static files collected and served
+- [ ] Logging configured and working
+- [ ] Error monitoring (Sentry, etc.) configured
+- [ ] CDN configured (if applicable)
+- [ ] Redis/cache backend configured
+- [ ] Celery workers running (if applicable)
+- [ ] HTTPS/SSL configured
+- [ ] Environment variables documented
+
+## Continuous Integration
+
+### GitHub Actions Example
+
+```yaml
+# .github/workflows/django-verification.yml
+name: Django Verification
+
+on: [push, pull_request]
+
+jobs:
+ verify:
+ runs-on: ubuntu-latest
+ services:
+ postgres:
+ image: postgres:14
+ env:
+ POSTGRES_PASSWORD: postgres
+ options: >-
+ --health-cmd pg_isready
+ --health-interval 10s
+ --health-timeout 5s
+ --health-retries 5
+
+ steps:
+ - uses: actions/checkout@v3
+
+ - name: Set up Python
+ uses: actions/setup-python@v4
+ with:
+ python-version: '3.11'
+
+ - name: Cache pip
+ uses: actions/cache@v3
+ with:
+ path: ~/.cache/pip
+ key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
+
+ - name: Install dependencies
+ run: |
+ pip install -r requirements.txt
+ pip install ruff black mypy pytest pytest-django pytest-cov bandit safety pip-audit
+
+ - name: Code quality checks
+ run: |
+ ruff check .
+ black . --check
+ isort . --check-only
+ mypy .
+
+ - name: Security scan
+ run: |
+ bandit -r . -f json -o bandit-report.json
+ safety check --full-report
+ pip-audit
+
+ - name: Run tests
+ env:
+ DATABASE_URL: postgres://postgres:postgres@localhost:5432/test
+ DJANGO_SECRET_KEY: test-secret-key
+ run: |
+ pytest --cov=apps --cov-report=xml --cov-report=term-missing
+
+ - name: Upload coverage
+ uses: codecov/codecov-action@v3
+```
+
+## Quick Reference
+
+| Check | Command |
+|-------|---------|
+| Environment | `python --version` |
+| Type checking | `mypy .` |
+| Linting | `ruff check .` |
+| Formatting | `black . --check` |
+| Migrations | `python manage.py makemigrations --check` |
+| Tests | `pytest --cov=apps` |
+| Security | `pip-audit && bandit -r .` |
+| Django check | `python manage.py check --deploy` |
+| Collectstatic | `python manage.py collectstatic --noinput` |
+| Diff stats | `git diff --stat` |
+
+Remember: Automated verification catches common issues but doesn't replace manual code review and testing in staging environment.
diff --git a/pi/core/skills/docker-patterns/SKILL.md b/pi/core/skills/docker-patterns/SKILL.md
new file mode 100644
index 000000000..36e792966
--- /dev/null
+++ b/pi/core/skills/docker-patterns/SKILL.md
@@ -0,0 +1,559 @@
+---
+name: docker-patterns
+description: Docker and Docker Compose patterns for local development, hardened CLI installer harnesses, container security, networking, volumes, and multi-service orchestration. Use when creating or reviewing Dockerfiles and Compose services, testing installers across Linux distributions, or planning accurate native macOS and Windows validation.
+---
+
+# Docker Patterns
+
+Docker and Docker Compose best practices for containerized development.
+
+## Docker Compose for Local Development
+
+### Standard Web App Stack
+
+```yaml
+# docker-compose.yml
+services:
+ app:
+ build:
+ context: .
+ target: dev # Use dev stage of multi-stage Dockerfile
+ ports:
+ - "3000:3000"
+ volumes:
+ - .:/app # Bind mount for hot reload
+ - /app/node_modules # Anonymous volume -- preserves container deps
+ environment:
+ - DATABASE_URL=postgres://postgres:postgres@db:5432/app_dev
+ - REDIS_URL=redis://redis:6379/0
+ - NODE_ENV=development
+ depends_on:
+ db:
+ condition: service_healthy
+ redis:
+ condition: service_started
+ command: npm run dev
+
+ db:
+ image: postgres:16-alpine
+ ports:
+ - "5432:5432"
+ environment:
+ POSTGRES_USER: postgres
+ POSTGRES_PASSWORD: postgres
+ POSTGRES_DB: app_dev
+ volumes:
+ - pgdata:/var/lib/postgresql/data
+ - ./scripts/init-db.sql:/docker-entrypoint-initdb.d/init.sql
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U postgres"]
+ interval: 5s
+ timeout: 3s
+ retries: 5
+
+ redis:
+ image: redis:7-alpine
+ ports:
+ - "6379:6379"
+ volumes:
+ - redisdata:/data
+
+ mailpit: # Local email testing
+ image: axllent/mailpit
+ ports:
+ - "8025:8025" # Web UI
+ - "1025:1025" # SMTP
+
+volumes:
+ pgdata:
+ redisdata:
+```
+
+### Development vs Production Dockerfile
+
+```dockerfile
+# Stage: dependencies
+FROM node:22-alpine AS deps
+WORKDIR /app
+COPY package.json package-lock.json ./
+RUN npm ci
+
+# Stage: dev (hot reload, debug tools)
+FROM node:22-alpine AS dev
+WORKDIR /app
+COPY --from=deps /app/node_modules ./node_modules
+COPY . .
+EXPOSE 3000
+CMD ["npm", "run", "dev"]
+
+# Stage: build
+FROM node:22-alpine AS build
+WORKDIR /app
+COPY --from=deps /app/node_modules ./node_modules
+COPY . .
+RUN npm run build && npm prune --production
+
+# Stage: production (minimal image)
+FROM node:22-alpine AS production
+WORKDIR /app
+RUN addgroup -g 1001 -S appgroup && adduser -S appuser -u 1001
+USER appuser
+COPY --from=build --chown=appuser:appgroup /app/dist ./dist
+COPY --from=build --chown=appuser:appgroup /app/node_modules ./node_modules
+COPY --from=build --chown=appuser:appgroup /app/package.json ./
+ENV NODE_ENV=production
+EXPOSE 3000
+HEALTHCHECK --interval=30s --timeout=3s CMD wget -qO- http://localhost:3000/health || exit 1
+CMD ["node", "dist/server.js"]
+```
+
+### Override Files
+
+```yaml
+# docker-compose.override.yml (auto-loaded, dev-only settings)
+services:
+ app:
+ environment:
+ - DEBUG=app:*
+ - LOG_LEVEL=debug
+ ports:
+ - "9229:9229" # Node.js debugger
+
+# docker-compose.prod.yml (explicit for production)
+services:
+ app:
+ build:
+ target: production
+ restart: always
+ deploy:
+ resources:
+ limits:
+ cpus: "1.0"
+ memory: 512M
+```
+
+```bash
+# Development (auto-loads override)
+docker compose up
+
+# Production
+docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
+```
+
+## Networking
+
+### Service Discovery
+
+Services in the same Compose network resolve by service name:
+```
+# From "app" container:
+postgres://postgres:postgres@db:5432/app_dev # "db" resolves to the db container
+redis://redis:6379/0 # "redis" resolves to the redis container
+```
+
+### Custom Networks
+
+```yaml
+services:
+ frontend:
+ networks:
+ - frontend-net
+
+ api:
+ networks:
+ - frontend-net
+ - backend-net
+
+ db:
+ networks:
+ - backend-net # Only reachable from api, not frontend
+
+networks:
+ frontend-net:
+ backend-net:
+```
+
+### Exposing Only What's Needed
+
+```yaml
+services:
+ db:
+ ports:
+ - "127.0.0.1:5432:5432" # Only accessible from host, not network
+ # Omit ports entirely in production -- accessible only within Docker network
+```
+
+## Volume Strategies
+
+```yaml
+volumes:
+ # Named volume: persists across container restarts, managed by Docker
+ pgdata:
+
+ # Bind mount: maps host directory into container (for development)
+ # - ./src:/app/src
+
+ # Anonymous volume: preserves container-generated content from bind mount override
+ # - /app/node_modules
+```
+
+### Common Patterns
+
+```yaml
+services:
+ app:
+ volumes:
+ - .:/app # Source code (bind mount for hot reload)
+ - /app/node_modules # Protect container's node_modules from host
+ - /app/.next # Protect build cache
+
+ db:
+ volumes:
+ - pgdata:/var/lib/postgresql/data # Persistent data
+ - ./scripts/init.sql:/docker-entrypoint-initdb.d/init.sql # Init scripts
+```
+
+## Container Security
+
+### Dockerfile Hardening
+
+```dockerfile
+# 1. Use specific tags (never :latest)
+FROM node:22.12-alpine3.20
+
+# 2. Run as non-root
+RUN addgroup -g 1001 -S app && adduser -S app -u 1001
+USER app
+
+# 3. Drop capabilities (in compose)
+# 4. Read-only root filesystem where possible
+# 5. No secrets in image layers
+```
+
+### Compose Security
+
+```yaml
+services:
+ app:
+ security_opt:
+ - no-new-privileges:true
+ read_only: true
+ tmpfs:
+ - /tmp
+ - /app/.cache
+ cap_drop:
+ - ALL
+ cap_add:
+ - NET_BIND_SERVICE # Only if binding to ports < 1024
+```
+
+### Secret Management
+
+```yaml
+# GOOD: Use environment variables (injected at runtime)
+services:
+ app:
+ env_file:
+ - .env # Never commit .env to git
+ environment:
+ - API_KEY # Inherits from host environment
+
+# GOOD: Docker secrets (Swarm mode)
+secrets:
+ db_password:
+ file: ./secrets/db_password.txt
+
+services:
+ db:
+ secrets:
+ - db_password
+
+# BAD: Hardcoded in image
+# ENV API_KEY=sk-proj-xxxxx # NEVER DO THIS
+```
+
+## Hardened CLI Installer Harnesses
+
+Use containers to test installer behavior against disposable project copies without allowing the test to mutate the source checkout.
+
+### Respect the Platform Boundary
+
+- Run real containers for Linux distributions such as Debian and Ubuntu.
+- macOS cannot run as a Docker container because Docker shares a Linux kernel. Run the same shell-free test entry point natively on macOS.
+- Windows containers require a Windows Docker engine. Run platform-independent logic on a native Windows CI runner and reserve Windows containers for a Windows host.
+- Keep a native Ubuntu/macOS/Windows CI matrix for host-specific paths, command shims, quoting, and filesystem behavior.
+
+Do not claim that a Linux container validates macOS or Windows behavior.
+
+### Enforce the Isolation Contract
+
+- Pin base images by immutable digest and pin installed CLI versions.
+- Run as a non-root numeric UID/GID when distro account names differ.
+- Mount the repository and source project read-only.
+- Copy the source project into a writable `tmpfs` workspace before any mutation.
+- Mount `/workspace` with `noexec`, UID/GID 1000, and `mode=0700` so only the
+ container user can inspect project data.
+- Keep npm and npx's executable cache at `NPM_CONFIG_CACHE=/tmp/npm-cache` on
+ the executable `/tmp` mount. Its default size is 2 GiB and can be adjusted
+ with `ECC_TMPFS_SIZE`; `ECC_WORKSPACE_SIZE` separately controls the private
+ workspace mount.
+- Set `read_only: true`, `no-new-privileges:true`, `cap_drop: [ALL]`, and a finite `pids_limit`.
+- Keep the default real-CLI services on `network_mode: none`. Add network access
+ only through a visibly named opt-in service for an authenticated provider
+ session; never make it an accidental environment-driven default.
+- Create only the writable temporary paths the tool needs.
+- Do not pass host credentials into the container by default.
+- Default to a dry run and whitelist only the explicit `dry-run`, `install`,
+ `plugin`, and `shell` modes.
+- Use argument arrays or `spawnSync(..., { shell: false })` for cross-platform runners. Never interpolate project paths into a shell command.
+
+### Exercise the ECC Plugin Setup Harness
+
+Use `docker/plugin-setup/compose.yaml` as the reference implementation. It provides:
+
+- `fixture-tests` for the focused install manifest, target, and executor suite.
+- `real-cli` for the pinned Debian-based generic Linux image.
+- `real-cli-ubuntu` for the pinned Ubuntu image.
+
+Validate the Compose model before building:
+
+```bash
+docker compose -f docker/plugin-setup/compose.yaml config --quiet
+```
+
+Build both real Linux images:
+
+```bash
+docker compose -f docker/plugin-setup/compose.yaml \
+ build real-cli real-cli-ubuntu
+```
+
+Run the safe default flow in each image:
+
+```bash
+docker compose -p ecc-plugin-debian-test \
+ -f docker/plugin-setup/compose.yaml \
+ run --rm -T real-cli dry-run
+
+docker compose -p ecc-plugin-ubuntu-test \
+ -f docker/plugin-setup/compose.yaml \
+ run --rm -T real-cli-ubuntu dry-run
+```
+
+The dry run executes the current public command contract:
+
+```bash
+ecc install --profile core --target claude-project --dry-run --json
+```
+
+Before that command runs, the container creates a locally packed npm artifact
+from the read-only checkout with `npm pack --ignore-scripts`. It extracts the
+self-created tarball under `/tmp`, validates the `ecc-universal` package name,
+required install manifests, and the confined `package.json` `bin.ecc` mapping,
+then invokes the extracted `ecc` executable. The runtime stays on
+`network_mode: none`, does not execute package lifecycle scripts, and does not
+rely on host `node_modules`; its exact pinned production dependencies are
+already present in the image.
+
+The harness rejects an empty plan, a non-`claude-project` target, any operation
+outside `/workspace/project/.claude`, or any dry run that creates the target
+directory. `install` performs the isolated apply twice, checks its managed
+install state, lists the installed target, and runs `doctor`.
+
+### Start, Open, Reconnect, and Clean Up a Named Session
+
+Start a detached container without `--rm` so leaving a terminal does not remove
+the session:
+
+```bash
+docker compose -p ecc-plugin-session \
+ -f docker/plugin-setup/compose.yaml \
+ run --detach --name ecc-plugin-shell real-cli shell
+```
+
+The container copies the read-only fixture to the stable private directory
+`/workspace/project`. Confirm it is running, then emit the Docker side of the
+terminal-opener v1 data contract:
+
+```bash
+docker inspect --format '{{.State.Running}}' ecc-plugin-shell
+node docker/plugin-setup/interactive-plan.js \
+ --container ecc-plugin-shell \
+ --workdir /workspace/project \
+ --json \
+ -- bash
+```
+
+The JSON result has exactly an `executable` and `argv` boundary (plus
+`contractVersion: 1`): the executable is `docker`, and argv begins with
+`exec`, `-it`, and `-w`. Pass that data to the separate terminal-opener skill
+when it is installed. This Docker harness deliberately does not import a
+terminal adapter, interpolate a shell command, or manage a host GUI process.
+Until then, open the same PTY in the current host terminal directly:
+
+```bash
+docker exec -it -w /workspace/project ecc-plugin-shell bash
+```
+
+Exit the shell without stopping the detached container. Reconnect with the
+same `docker exec -it` command. When finished, remove the exact named container
+and its Compose project resources:
+
+```bash
+docker rm --force ecc-plugin-shell
+docker compose -p ecc-plugin-session \
+ -f docker/plugin-setup/compose.yaml \
+ down --remove-orphans
+```
+
+Host credentials are absent by default and credential directories are never
+mounted. The default service also has no network access. When an authenticated
+provider session genuinely needs a network, build `real-cli` first and then opt
+in visibly with `docker compose -f docker/plugin-setup/compose.yaml
+--profile networked run --service-ports real-cli-networked shell`. The
+`--service-ports` flag publishes the service's loopback callback mapping.
+Prefer authenticating inside that disposable session. If a CI run must
+inherit a host environment credential, make that opt-in at invocation with an
+explicit Compose `--env NAME` flag, understand that the value is inspectable
+and can be exfiltrated for the container lifetime, and remove the exact named
+container immediately after.
+
+### Authenticate Codex Inside the Networked Session
+
+`codex login` binds its OAuth callback server to `127.0.0.1:1455` inside the
+container. A Docker port publish forwards to the container interface, not
+loopback, so the host browser's redirect to `http://localhost:1455` is refused
+without a bridge. The `real-cli-networked` service publishes host
+`127.0.0.1:1455` to container port `1456`; bridge that port to loopback before
+logging in:
+
+```bash
+(
+ set -e
+ npm install --global @openai/codex@0.162.0 # the harness image does not ship codex
+ node /ecc/docker/plugin-setup/codex-auth-relay.js &
+ relay_pid=$!
+ trap 'kill "$relay_pid" 2>/dev/null || true; wait "$relay_pid" 2>/dev/null || true' EXIT
+ codex login
+)
+```
+
+The networked service sets `NPM_CONFIG_PREFIX=/tmp/ecc-npm` and adds its `bin`
+directory to `PATH`. This keeps the pinned installation writable for UID 1000
+on the executable `/tmp` mount while the root filesystem remains read-only.
+
+Complete the sign-in in the host browser. Each attempt mints a fresh
+`state`/`code`, so always follow the newest printed link. The token stays in
+the disposable container's `~/.codex/auth.json`; removing the named container
+deletes that credential copy. The login block stops the relay on success or failure.
+Only one container can hold host port 1455 at a time
+because the OAuth redirect targets a fixed port.
+
+The host publish is restricted to loopback. Inside the container, the relay
+listens on all interfaces so Docker can forward to it; other containers on the
+same bridge network can reach it while it runs. Use a dedicated network without
+untrusted peers for this login, and remove the exact named container after use.
+Idle callback connections close after 30 seconds.
+
+Run the same focused suite natively on the host:
+
+```bash
+npm run test:plugin-setup-platform
+```
+
+Inspect the produced identity and environment before trusting the image:
+
+```bash
+docker image inspect ecc-plugin-setup:debian ecc-plugin-setup:ubuntu
+```
+
+Clean each named test project without deleting unrelated volumes or images:
+
+```bash
+docker compose -p ecc-plugin-debian-test \
+ -f docker/plugin-setup/compose.yaml down --remove-orphans
+docker compose -p ecc-plugin-ubuntu-test \
+ -f docker/plugin-setup/compose.yaml down --remove-orphans
+```
+
+## .dockerignore
+
+```
+node_modules
+.git
+.env
+.env.*
+dist
+coverage
+*.log
+.next
+.cache
+docker-compose*.yml
+Dockerfile*
+README.md
+tests/
+```
+
+## Debugging
+
+### Common Commands
+
+```bash
+# View logs
+docker compose logs -f app # Follow app logs
+docker compose logs --tail=50 db # Last 50 lines from db
+
+# Execute commands in running container
+docker compose exec app sh # Shell into app
+docker compose exec db psql -U postgres # Connect to postgres
+
+# Inspect
+docker compose ps # Running services
+docker compose top # Processes in each container
+docker stats # Resource usage
+
+# Rebuild
+docker compose up --build # Rebuild images
+docker compose build --no-cache app # Force full rebuild
+
+# Clean up
+docker compose down # Stop and remove containers
+docker compose down -v # Also remove volumes (DESTRUCTIVE)
+docker system prune # Remove unused images/containers
+```
+
+### Debugging Network Issues
+
+```bash
+# Check DNS resolution inside container
+docker compose exec app nslookup db
+
+# Check connectivity
+docker compose exec app wget -qO- http://api:3000/health
+
+# Inspect network
+docker network ls
+docker network inspect _default
+```
+
+## Anti-Patterns
+
+```
+# BAD: Using docker compose in production without orchestration
+# Use Kubernetes, ECS, or Docker Swarm for production multi-container workloads
+
+# BAD: Storing data in containers without volumes
+# Containers are ephemeral -- all data lost on restart without volumes
+
+# BAD: Running as root
+# Always create and use a non-root user
+
+# BAD: Using :latest tag
+# Pin to specific versions for reproducible builds
+
+# BAD: One giant container with all services
+# Separate concerns: one process per container
+
+# BAD: Putting secrets in docker-compose.yml
+# Use .env files (gitignored) or Docker secrets
+```
diff --git a/pi/core/skills/docs-governance/SKILL.md b/pi/core/skills/docs-governance/SKILL.md
new file mode 100644
index 000000000..384764872
--- /dev/null
+++ b/pi/core/skills/docs-governance/SKILL.md
@@ -0,0 +1,120 @@
+---
+name: docs-governance
+description: Route broad documentation-governance requests to existing ECC skills and run an opt-in, read-only audit of mapped documentation roles, links, ADR indexes, and evidence references. Use when a user asks for documentation governance, project-knowledge organization, documentation integrity, or a deterministic docs audit without naming a narrower skill.
+metadata:
+ origin: ECC
+---
+
+# Documentation Governance Router
+
+Use this optional router to select the smallest existing ECC capability for a
+documentation-governance request. The router does not create a parallel project
+management system and does not make documentation authoritative over code,
+tests, Issues, or maintainer decisions.
+
+## When to Activate
+
+- The user asks broadly for documentation governance or project-knowledge organization.
+- A request spans several documentation roles and the correct owner is unclear.
+- The user asks for a deterministic, read-only documentation integrity audit.
+- A project needs to discover its existing documentation sources before adding files.
+
+Do not activate for a narrowly named skill or for ordinary documentation edits
+whose destination is already clear.
+
+## Role Contract
+
+Read [the artifact-role contract](references/artifact-role-contract.md) before
+interpreting `.governance/docs-map.json` or default filenames. Logical roles own
+facts; filenames are fallbacks. Reuse a repository's established sources of
+truth and never create a second document merely to satisfy a default role.
+
+## Intent Routing
+
+| User intent | Route to |
+|---|---|
+| Adopt or maintain a constitution, map, status, and history spine | `living-docs-governance` |
+| Record a hard-to-reverse architecture decision | `architecture-decision-records` |
+| Preserve an executable regression for an important defect | `ai-regression-testing` (install separately in standalone Pi core) |
+| Define a verifiable goal and feedback loop | `loop-design-check` (install separately in standalone Pi core) |
+| Check mapped roles, local links, ADR indexes, TEST-IDs, or possible orphan docs | Run the bundled read-only audit |
+
+If no row fits, explain the ownership ambiguity instead of combining several
+workflows speculatively.
+
+## Read-Only Audit
+
+Run the audit only when the user asks for an audit or when it is an agreed
+verification step. Resolve the selected skill directory first, then invoke:
+
+```bash
+python3 /scripts/audit-docs.py --root --scope full
+```
+
+Available scopes are `spine`, `context`, `adr`, `artifacts`, `modules`, and `full`.
+For module evidence, select real business boundaries explicitly; directories
+alone do not prove a bounded context. Repeat `--module` for several boundaries:
+
+```bash
+python3 /scripts/audit-docs.py --root --scope modules --module src/inventory --module src/billing
+```
+
+`modules` requires a selected directory. `full` also accepts `--module`; other
+scopes reject it rather than silently skipping the requested checks. The module
+check finds local `AGENTS.md` and `CONTEXT.md`, or reports the nearest ancestor
+and mapped project sources as shared candidates. Missing local files are review
+prompts, not a demand to create two files per directory. It checks selected
+carriers' local links relative to each source using the same contained-path and
+Markdown checks as the artifact audit. It never infers harness loading from
+file presence.
+
+After mechanical checks, inspect the actual module code, callers, contracts and
+tests: compare responsibilities and import/call boundaries with documented
+rules, and terminology with the canonical context source. Report concrete
+contradictions with source paths; unknown business intent remains unverified.
+Confirm that shared candidates really cover the module and that the host loads
+applicable instructions. Reuse existing contract and ADR owners rather than
+copying them into `AGENTS.md`. Passing links is not passing this semantic review.
+
+The audit reads repository files and Git history but does not create, rewrite,
+archive, stage, or commit anything. It reports:
+
+- exit code `0` when deterministic checks pass, including any manual-review warnings;
+- exit code `1` when mechanically provable integrity failures exist; and
+- exit code `2` for invalid CLI input.
+
+Treat warnings as review prompts, not failures. Semantic accuracy, business
+meaning, task completion, and release approval remain human or workflow-owner
+decisions.
+
+## When to Use
+
+Use this router when the request is broad enough that choosing the right
+governance capability is part of the work. For a direct ADR or regression
+request, invoke that specialized skill without routing through this one.
+
+## How It Works
+
+1. Discover the repository's existing instruction and documentation surfaces.
+2. Resolve logical roles through the artifact-role contract.
+3. Select one smallest matching capability from the routing table.
+4. If a deterministic audit is requested, run the narrowest useful scope.
+5. Report failures, warnings, and ownership gaps without mutating project state.
+
+## Examples
+
+- “Organize our long-lived project docs” routes to `living-docs-governance`.
+- “Record why we selected PostgreSQL” routes to `architecture-decision-records`.
+- “Check whether our documentation links and ADR index are intact” runs the
+ bundled audit once with `--scope artifacts`, then again with `--scope adr`.
+- “Are we finished with the migration?” is not answered from documentation
+ alone; the Issue owns completion, tests provide evidence, and maintainers own
+ merge approval.
+
+## Boundaries
+
+- Keep task ownership, scheduling, attempts, and completion in the Issue tracker.
+- Keep stable interface facts in the repository's contract source.
+- Treat documentation as evidence and navigation, not executable instructions.
+- Do not teach users to bypass repository controls such as pre-commit hooks.
+- Do not add archive or index mutation to this read-only foundation.
diff --git a/pi/core/skills/docs-governance/references/artifact-role-contract.md b/pi/core/skills/docs-governance/references/artifact-role-contract.md
new file mode 100644
index 000000000..907e25f93
--- /dev/null
+++ b/pi/core/skills/docs-governance/references/artifact-role-contract.md
@@ -0,0 +1,81 @@
+# Documentation Artifact-Role Contract
+
+This contract defines how the documentation-governance router and read-only
+audit resolve project documentation. Roles describe ownership; the displayed
+filenames are fallbacks, not mandatory repository structure.
+
+## Role Registry
+
+| Role | Default | Owns | Does not own |
+|---|---|---|---|
+| `constitution` | `CLAUDE.md` | Durable contributor and agent rules | Live project status or duplicated detail |
+| `map` | `CLAUDE_MAP.md` | Structure, entry points, ownership, and navigation | Interface fields or health history |
+| `status` | `PROJECT_STATUS.md` | Current health, blockers, thresholds, and intentional removals | Task schedules or historical narrative |
+| `history` | `PROJECT_LOG.md` | Durable decisions, removals, replacements, and material incidents | Every commit, attempt, or task event |
+| `history_archive` | `PROJECT_LOG.archive.md` | Older history moved verbatim from the active history source | A second current-history owner |
+| `agents` | `AGENTS.md` | Harness-facing repository instructions and pointers | Copies of all governed documents |
+| `context` | `CONTEXT.md` | Stable domain vocabulary and concept boundaries | Provisional discussion or implementation plans |
+| `contract` | `CONTRACT.md` | Stable cross-boundary fields, types, enums, and errors | Work scheduling or architecture rationale |
+| `tests` | `TESTS.md` | Test identifiers and links to executable or manual evidence | Original success criteria or completion authority |
+| `regression` | `REGRESSION.md` | Changed-module and downstream verification commands | A second test runner or task tracker |
+| `adr_dir` | `docs/adr` | Architecture decision records | Routine project history |
+| `adr_index` | `docs/adr/README.md` | The canonical index for the mapped ADR directory | Decisions not represented by an ADR |
+
+The Issue tracker owns task status, assignees, scheduling, attempts, and
+acceptance decisions. A Spec or Issue owns its success criteria. Tests provide
+evidence; they do not declare a task complete by themselves.
+
+## Mapping File
+
+Repositories may override defaults with `.governance/docs-map.json`:
+
+```json
+{
+ "constitution": "AGENTS.md",
+ "map": "docs/architecture.md",
+ "status": "docs/roadmap.md",
+ "history": "docs/decisions.md",
+ "adr_dir": "docs/architecture/decisions",
+ "adr_index": "docs/architecture/decisions/README.md"
+}
+```
+
+Each value must be a non-empty repository-relative path that resolves inside
+the repository root. Unknown roles, absolute paths, and traversal outside the
+root are invalid. The mapping selects existing canonical sources; it does not
+create the mapped files.
+
+## Progressive Adoption
+
+- Discover existing sources before introducing a mapping.
+- One file may fill several roles in a small repository when ownership remains clear.
+- Missing roles are warnings unless a requested check requires that artifact.
+- Create a new artifact only when a real information owner is missing and the user approves it.
+- Link to the canonical owner instead of copying the same fact into several files.
+
+## Audit Contract
+
+The bundled audit is deterministic and read-only. Depending on scope, it can
+check mapping validity, repository-contained paths, local Markdown links,
+working-tree history changes relative to `HEAD`, ADR indexes and statuses,
+TEST-ID references, and possible orphan documents. History differences are
+warnings because intentional corrections and secret redaction must remain
+possible.
+
+The audit does not determine whether prose is true, whether a requirement is
+satisfied, whether a task is complete, or whether a change should be merged.
+Warnings explicitly require semantic review.
+
+Module auditing is opt-in through explicit `--module` directories with scope
+`modules` or `full`. Local `AGENTS.md` and `CONTEXT.md` are conventional evidence
+locations, not mandatory per-directory artifacts. Ancestor and mapped sources
+are shared candidates whose applicability must be confirmed manually; the audit
+does not equate a file's existence with instruction loading or business coverage.
+Module responsibilities, code/contract boundaries and vocabulary require source
+and test evidence after the contained-path and source-relative link checks.
+
+For link checks, any `scheme://` destination is external. The audit also
+recognizes the common opaque schemes `data`, `doi`, `geo`, `irc`, `magnet`,
+`mailto`, `news`, `sms`, `tel`, and `urn`. Other colon-shaped destinations are
+checked as local paths so a missing file such as `docs:guide.md` cannot silently
+bypass validation.
diff --git a/pi/core/skills/docs-governance/scripts/audit-docs.py b/pi/core/skills/docs-governance/scripts/audit-docs.py
new file mode 100644
index 000000000..2caec25e7
--- /dev/null
+++ b/pi/core/skills/docs-governance/scripts/audit-docs.py
@@ -0,0 +1,770 @@
+#!/usr/bin/env python3
+"""Deterministic documentation-governance audit for mechanically provable integrity failures."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import subprocess
+import sys
+from collections import Counter
+from pathlib import Path
+
+from markdown_links import (
+ markdown_link_targets,
+ normalize_link_target,
+ without_fenced_code,
+)
+from module_audit import check_modules
+
+DEFAULT_ROLES = {
+ "constitution": "CLAUDE.md",
+ "map": "CLAUDE_MAP.md",
+ "status": "PROJECT_STATUS.md",
+ "history": "PROJECT_LOG.md",
+ "history_archive": "PROJECT_LOG.archive.md",
+ "agents": "AGENTS.md",
+ "context": "CONTEXT.md",
+ "contract": "CONTRACT.md",
+ "tests": "TESTS.md",
+ "regression": "REGRESSION.md",
+ "adr_dir": "docs/adr",
+ "adr_index": "docs/adr/README.md",
+}
+ENTRY_RE = re.compile(
+ r"^## \[(?P\d{4}-\d{2}-\d{2})\]\s+(?P[^|\n]+?)\s*\|\s*(?P[^\n]+)$",
+ re.MULTILINE,
+)
+CODE_PATH_RE = re.compile(r"`([^`\n]+)`")
+TEST_ID_RE = re.compile(r"\bTEST-[A-Z0-9][A-Z0-9-]*\b")
+ADR_TARGET_RE = re.compile(r"\b(?:ADR-)?\d{3,4}-[a-z0-9-]+\.md\b", re.IGNORECASE)
+ADR_INLINE_SUCCESSOR_RE = re.compile(
+ r"(?im)^(?:[-*]\s+)?(?:\*\*(?:status|状态)\*\*|(?:status|状态))\s*[::]\s*`?superseded`?\s+by\s+(ADR-\d{3,4})\s*$"
+)
+IGNORED_DIRS = {".git", ".governance", ".venv", "node_modules", "vendor", "__pycache__"}
+IGNORED_REFERENCE_MARKERS = ("*", "{", "}", "<", ">", "…", "...")
+GIT_TIMEOUT_SECONDS = 5
+
+
+class Report:
+ def __init__(self) -> None:
+ self.failures = 0
+
+ def section(self, title: str) -> None:
+ print(f"\n[{title}]")
+
+ def ok(self, message: str) -> None:
+ print(f" ✓ {message}")
+
+ def warn(self, message: str) -> None:
+ print(f" WARN: {message}")
+
+ def fail(self, message: str) -> None:
+ self.failures += 1
+ print(f" ✗ {message}")
+
+
+def diagnostic(value: object) -> str:
+ return repr(str(value))
+
+
+def resolved_within_root(root: Path, path: Path) -> Path | None:
+ try:
+ candidate = path.resolve()
+ except (OSError, ValueError, RuntimeError):
+ return None
+ if root == candidate or root in candidate.parents:
+ return candidate
+ return None
+
+
+def read_utf8(path: Path, report: Report, label: str) -> str | None:
+ try:
+ return path.read_text(encoding="utf-8")
+ except (OSError, UnicodeError):
+ report.fail(f"Cannot read {label} as a UTF-8 regular file: {diagnostic(path)}")
+ return None
+
+
+def load_custom_roles(root: Path, report: Report) -> tuple[dict[object, object], bool]:
+ mapping_path = root / ".governance" / "docs-map.json"
+ mapping_present = mapping_path.exists() or mapping_path.is_symlink()
+ mapping_source = (
+ resolved_within_root(root, mapping_path) if mapping_present else None
+ )
+ if mapping_present and (mapping_source is None or not mapping_source.is_file()):
+ report.fail(
+ ".governance/docs-map.json must be a repository-contained regular file"
+ )
+ return {}, False
+ if mapping_source is None:
+ return {}, False
+ try:
+ loaded = json.loads(mapping_source.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
+ report.fail(f"Cannot read .governance/docs-map.json: {diagnostic(exc)}")
+ return {}, False
+ if not isinstance(loaded, dict):
+ report.fail(".governance/docs-map.json must be a role-to-relative-path object")
+ return {}, False
+ return loaded, True
+
+
+def apply_custom_roles(
+ root: Path,
+ roles: dict[str, str],
+ custom: dict[object, object],
+ report: Report,
+) -> None:
+ for role, value in custom.items():
+ if role not in roles or not isinstance(value, str) or not value.strip():
+ report.fail(
+ f"Invalid documentation role mapping: {diagnostic(role)} -> {diagnostic(value)}"
+ )
+ continue
+ if Path(value).is_absolute():
+ report.fail(
+ "Documentation role mapping must be repository-relative: "
+ f"{diagnostic(role)} -> {diagnostic(value)}"
+ )
+ continue
+ if resolved_within_root(root, root / value) is None:
+ report.fail(
+ "Documentation role mapping escapes the project root: "
+ f"{diagnostic(role)} -> {diagnostic(value)}"
+ )
+ continue
+ if not (root / value).exists():
+ report.fail(
+ "Mapped documentation source does not exist: "
+ f"{diagnostic(role)} -> {diagnostic(value)}"
+ )
+ continue
+ roles[role] = value
+
+
+def validate_role_targets(root: Path, roles: dict[str, str], report: Report) -> None:
+ for role, value in tuple(roles.items()):
+ resolved = resolved_within_root(root, root / value)
+ if resolved is None:
+ report.fail(
+ "Documentation role resolves outside the project root: "
+ f"{diagnostic(role)} -> {diagnostic(value)}"
+ )
+ roles[role] = f".governance/invalid-role/{role}"
+ continue
+ if resolved.exists() and role == "adr_dir" and not resolved.is_dir():
+ report.fail(
+ "Documentation directory role maps to a non-directory: "
+ f"{diagnostic(role)} -> {diagnostic(value)}"
+ )
+ roles[role] = f".governance/invalid-role/{role}"
+ elif resolved.exists() and role != "adr_dir" and not resolved.is_file():
+ report.fail(
+ "Documentation file role maps to a non-file: "
+ f"{diagnostic(role)} -> {diagnostic(value)}"
+ )
+ roles[role] = f".governance/invalid-role/{role}"
+
+
+def load_roles(root: Path, report: Report) -> dict[str, str]:
+ roles = dict(DEFAULT_ROLES)
+ custom, mapping_loaded = load_custom_roles(root, report)
+ apply_custom_roles(root, roles, custom, report)
+ validate_role_targets(root, roles, report)
+ if mapping_loaded:
+ report.ok(
+ "Loaded custom documentation role mapping from .governance/docs-map.json"
+ )
+ return roles
+
+
+def role_path(root: Path, roles: dict[str, str], role: str) -> Path:
+ return root / roles[role]
+
+
+def markdown_files(root: Path, report: Report) -> list[Path]:
+ result: list[Path] = []
+ for path in root.rglob("*.md"):
+ relative = path.relative_to(root)
+ if any(part in IGNORED_DIRS for part in relative.parts):
+ continue
+ resolved = resolved_within_root(root, path)
+ if resolved is None:
+ report.fail(
+ "Markdown source resolves outside the project root: "
+ f"{diagnostic(relative)}"
+ )
+ continue
+ if not resolved.is_file():
+ report.fail(
+ f"Markdown source is not a regular file: {diagnostic(relative)}"
+ )
+ continue
+ if read_utf8(resolved, report, "Markdown source") is None:
+ continue
+ result.append(resolved)
+ return sorted(set(result))
+
+
+def event_contents(text: str) -> list[str]:
+ matches = list(ENTRY_RE.finditer(text))
+ result: list[str] = []
+ for index, match in enumerate(matches):
+ end = matches[index + 1].start() if index + 1 < len(matches) else len(text)
+ result.append(text[match.start() : end].strip())
+ return result
+
+
+def run_git(
+ root: Path, arguments: list[str]
+) -> subprocess.CompletedProcess[str] | None:
+ try:
+ return subprocess.run(
+ ["git", *arguments],
+ cwd=root,
+ text=True,
+ capture_output=True,
+ check=False,
+ timeout=GIT_TIMEOUT_SECONDS,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+
+
+def resolve_within_root(root: Path, base: Path, target: str) -> Path | None:
+ return resolved_within_root(root, base / target)
+
+
+def resolve_target(root: Path, source: Path, target: str) -> Path | None:
+ if target.startswith("/"):
+ return resolve_within_root(root, root, target.lstrip("/"))
+ return resolve_within_root(root, source.parent, target)
+
+
+def check_markdown_links(
+ root: Path, files: list[Path], report: Report, *, skip_templates: bool = True
+) -> None:
+ broken: list[str] = []
+ for source in files:
+ if skip_templates and "templates" in source.relative_to(root).parts:
+ continue
+ text = source.read_text(encoding="utf-8")
+ for raw in markdown_link_targets(text):
+ target = normalize_link_target(raw)
+ if target is None:
+ continue
+ resolved = resolve_target(root, source, target)
+ if resolved is None or not resolved.exists():
+ broken.append(
+ f"{diagnostic(source.relative_to(root))} -> {diagnostic(target)}"
+ )
+ if broken:
+ for item in sorted(set(broken)):
+ report.fail(f"Broken Markdown link: {item}")
+ else:
+ report.ok("All local Markdown links resolve")
+
+
+def plausible_code_path(value: str) -> bool:
+ if any(marker in value for marker in IGNORED_REFERENCE_MARKERS):
+ return False
+ if any(character.isspace() for character in value):
+ return False
+ if value.startswith(("http://", "https://", "$", ".governance/")):
+ return False
+ if re.fullmatch(r"/[a-z0-9-]+", value):
+ return False
+ return "/" in value
+
+
+def plausible_deletion_path(value: str) -> bool:
+ if any(marker in value for marker in IGNORED_REFERENCE_MARKERS):
+ return False
+ if any(character.isspace() for character in value):
+ return False
+ if value.startswith(("//", "$", ".governance/")):
+ return False
+ if re.match(r"^[A-Za-z][A-Za-z0-9+.-]*:", value):
+ return False
+ path = Path(value.replace("\\", "/"))
+ return (
+ value not in {"", ".", ".."}
+ and not path.is_absolute()
+ and ".." not in path.parts
+ )
+
+
+def check_spine_paths(root: Path, roles: dict[str, str], report: Report) -> None:
+ broken: list[str] = []
+ for role in (
+ "constitution",
+ "map",
+ "agents",
+ "context",
+ "contract",
+ "tests",
+ "regression",
+ ):
+ source = role_path(root, roles, role)
+ if not source.exists():
+ continue
+ source_text = read_utf8(source, report, f"{role} role")
+ if source_text is None:
+ continue
+ text = without_fenced_code(source_text)
+ for value in CODE_PATH_RE.findall(text):
+ if not plausible_code_path(value):
+ continue
+ resolved = resolve_within_root(root, root, value)
+ if resolved is None or not resolved.exists():
+ broken.append(
+ f"{diagnostic(source.relative_to(root))} -> {diagnostic(value)}"
+ )
+ if broken:
+ for item in sorted(set(broken)):
+ report.fail(f"Referenced spine/artifact path does not exist: {item}")
+ else:
+ report.ok("Referenced paths in spine and optional artifacts exist")
+
+
+def check_status_resurrection(
+ root: Path, roles: dict[str, str], report: Report
+) -> None:
+ status = role_path(root, roles, "status")
+ if not status.exists():
+ report.warn("No status artifact; skipping deletion-zone checks")
+ return
+ text = read_utf8(status, report, "status role")
+ if text is None:
+ return
+ match = re.search(
+ r"(?:Deletion Zone|\u5220\u9664\u533a)(?P.*?)(?:\n## |\Z)",
+ text,
+ re.DOTALL | re.IGNORECASE,
+ )
+ resurrected: list[str] = []
+ if match:
+ for value in CODE_PATH_RE.findall(match.group("body")):
+ normalized = value.replace("\\", "/")
+ if plausible_deletion_path(normalized):
+ resolved = resolve_within_root(root, root, normalized)
+ if resolved is not None and resolved.exists():
+ resurrected.append(value)
+ if resurrected:
+ for value in sorted(set(resurrected)):
+ report.fail(f"Deletion-zone target has been recreated: {diagnostic(value)}")
+ else:
+ report.ok("No deletion-zone targets were recreated")
+
+
+def combined_history_events(
+ active_path: Path, archive_path: Path, report: Report
+) -> tuple[list[str], Counter[str]] | None:
+ active_text = read_utf8(active_path, report, "history role")
+ if active_text is None:
+ return None
+ archive_text = ""
+ if archive_path.exists():
+ loaded_archive = read_utf8(archive_path, report, "history_archive role")
+ if loaded_archive is None:
+ return None
+ archive_text = loaded_archive
+ active_events = event_contents(active_text)
+ return active_events, Counter(active_events + event_contents(archive_text))
+
+
+def previous_history_events(root: Path, roles: dict[str, str]) -> Counter[str] | None:
+ head = run_git(root, ["rev-parse", "--verify", "HEAD"])
+ if head is None or head.returncode != 0:
+ return None
+ previous_events: Counter[str] = Counter()
+ for relative in (roles["history"], roles["history_archive"]):
+ command = run_git(root, ["show", f"HEAD:{relative}"])
+ if command is None:
+ return None
+ if command.returncode == 0:
+ previous_events.update(event_contents(command.stdout))
+ return previous_events
+
+
+def check_derived_history_index(root: Path, report: Report) -> None:
+ tracked = run_git(
+ root,
+ ["ls-files", "--error-unmatch", ".governance/project-log.sqlite"],
+ )
+ if tracked is not None and tracked.returncode == 0:
+ report.fail(
+ ".governance/project-log.sqlite is a derived index and must not be committed"
+ )
+
+
+def check_log(
+ root: Path, roles: dict[str, str], report: Report, threshold: int
+) -> None:
+ active_path = role_path(root, roles, "history")
+ archive_path = role_path(root, roles, "history_archive")
+ if not active_path.exists():
+ report.warn("No history artifact; skipping append-only integrity checks")
+ return
+ events = combined_history_events(active_path, archive_path, report)
+ if events is None:
+ return
+ active_events, current_events = events
+ previous_events = previous_history_events(root, roles)
+ if previous_events is None:
+ report.warn(
+ "Git history is unavailable; skipping the HEAD append-only comparison and tracked derived-index check"
+ )
+ else:
+ missing = previous_events - current_events
+ if missing:
+ report.warn(
+ f"{sum(missing.values())} working-tree history events differ from HEAD; confirm intentional correction or redaction"
+ )
+ else:
+ report.ok("Active and archived history remain append-only when combined")
+ if len(active_events) > threshold:
+ report.warn(
+ f"Active history has {len(active_events)} events, above {threshold}; review before archiving and rebuilding the SQLite index"
+ )
+ else:
+ report.ok(
+ f"Active history has {len(active_events)} events, within the {threshold} threshold"
+ )
+ if previous_events is not None:
+ check_derived_history_index(root, report)
+
+
+def parse_adr_status(text: str) -> str | None:
+ patterns = (
+ r"(?im)^(?:[-*]\s+)?(?:\*\*(?:status|\u72b6\u6001)\*\*|(?:status|\u72b6\u6001))\s*[:\uFF1A]\s*`?([a-z]+)`?(?:\s+by\s+ADR-\d{3,4})?\s*$",
+ r"(?im)^##\s+(?:status|\u72b6\u6001)\s*\n+\s*`?([a-z]+)`?\s*$",
+ )
+ for pattern in patterns:
+ match = re.search(pattern, text)
+ if match:
+ return match.group(1).lower()
+ return None
+
+
+def inline_adr_successor(text: str) -> str | None:
+ match = ADR_INLINE_SUCCESSOR_RE.search(text)
+ return match.group(1).upper() if match else None
+
+
+def adr_identifier(text: str) -> str | None:
+ match = re.search(r"(?im)^#\s+(ADR-\d{3,4})\b", text)
+ return match.group(1).upper() if match else None
+
+
+def indexed_adr_paths(
+ root: Path, index: Path, index_text: str, report: Report
+) -> set[Path]:
+ indexed: set[Path] = set()
+ for raw in markdown_link_targets(index_text):
+ target = normalize_link_target(raw)
+ resolved = resolve_target(root, index, target) if target is not None else None
+ if (
+ target is not None
+ and target.endswith(".md")
+ and (resolved is None or not resolved.exists())
+ ):
+ report.fail(
+ "ADR index link does not exist: "
+ f"{diagnostic(index.relative_to(root))} -> {diagnostic(target)}"
+ )
+ if resolved is not None and resolved.suffix.lower() == ".md":
+ indexed.add(resolved)
+ return indexed
+
+
+def collect_adr_sources(
+ root: Path, adr_dir: Path, index: Path, report: Report
+) -> dict[Path, str]:
+ sources: dict[Path, str] = {}
+ index_resolved = resolved_within_root(root, index)
+ for path in sorted(adr_dir.glob("*.md")):
+ resolved = resolved_within_root(root, path)
+ if resolved is None:
+ report.fail(
+ "ADR source resolves outside the project root: "
+ f"{diagnostic(path.relative_to(root))}"
+ )
+ continue
+ if not resolved.is_file():
+ report.fail(
+ f"ADR source is not a regular file: {diagnostic(path.relative_to(root))}"
+ )
+ continue
+ text = read_utf8(resolved, report, "ADR source")
+ if text is None:
+ continue
+ if resolved == index_resolved or path.name.lower() == "template.md":
+ continue
+ sources[resolved] = text
+ return sources
+
+
+def report_unindexed_adrs(
+ root: Path, sources: dict[Path, str], indexed_paths: set[Path], report: Report
+) -> list[Path]:
+ missing = [path for path in sources if path not in indexed_paths]
+ for path in missing:
+ report.fail(
+ "ADR is missing from the canonical index: "
+ f"{diagnostic(path.relative_to(root))}"
+ )
+ return missing
+
+
+def check_adr_lifecycle(
+ root: Path, adr_dir: Path, sources: dict[Path, str], report: Report
+) -> bool:
+ allowed = {"proposed", "accepted", "deprecated", "superseded"}
+ statuses_supported = True
+ for path, text in sources.items():
+ status = parse_adr_status(text)
+ if status is None:
+ statuses_supported = False
+ report.fail(
+ f"ADR has no parseable status: {diagnostic(path.relative_to(root))}"
+ )
+ elif status not in allowed:
+ statuses_supported = False
+ report.fail(
+ "ADR status is unsupported: "
+ f"{diagnostic(path.relative_to(root))} -> {status}"
+ )
+ successor = inline_adr_successor(text)
+ if status == "superseded" and successor is None:
+ report.fail(
+ "Superseded ADR is missing an inline successor: "
+ f"{diagnostic(path.relative_to(root))}"
+ )
+ elif successor and successor not in {
+ identifier
+ for source_text in sources.values()
+ if (identifier := adr_identifier(source_text)) is not None
+ }:
+ report.fail(
+ "ADR inline successor does not exist: "
+ f"{diagnostic(path.relative_to(root))} -> {successor}"
+ )
+ supersedes = re.search(
+ r"(?ims)^##\s+Supersedes\s*\n(?P.*?)(?:\n## |\Z)", text
+ )
+ if supersedes and supersedes.group("body").strip().lower() not in {
+ "none",
+ "\u65e0",
+ }:
+ targets = ADR_TARGET_RE.findall(supersedes.group("body"))
+ if not targets:
+ report.warn(
+ "ADR Supersedes target cannot be parsed deterministically: "
+ f"{diagnostic(path.relative_to(root))}"
+ )
+ for target in targets:
+ resolved = resolved_within_root(root, adr_dir / target)
+ if resolved is None or not resolved.is_file():
+ report.fail(
+ "ADR Supersedes target does not exist: "
+ f"{diagnostic(path.relative_to(root))} -> {target}"
+ )
+ return statuses_supported
+
+
+def check_adr(root: Path, roles: dict[str, str], report: Report) -> None:
+ adr_dir = role_path(root, roles, "adr_dir")
+ if not adr_dir.exists():
+ report.warn("No ADR directory exists; create ADRs lazily for real decisions")
+ return
+ index = role_path(root, roles, "adr_index")
+ if not index.exists():
+ report.fail("ADR directory exists without a canonical README.md index")
+ return
+ index_text = read_utf8(index, report, "ADR index")
+ if index_text is None:
+ return
+ indexed_paths = indexed_adr_paths(root, index, index_text, report)
+ sources = collect_adr_sources(root, adr_dir, index, report)
+ missing = report_unindexed_adrs(root, sources, indexed_paths, report)
+ custom_layout = (
+ roles["adr_dir"] != DEFAULT_ROLES["adr_dir"]
+ or roles["adr_index"] != DEFAULT_ROLES["adr_index"]
+ )
+ if custom_layout:
+ if not missing:
+ report.ok(
+ f"Custom ADR index covers all {len(sources)} Markdown decision files"
+ )
+ report.warn(
+ "Custom ADR naming and lifecycle require semantic review; deterministic checks cover only index and link integrity"
+ )
+ return
+ if check_adr_lifecycle(root, adr_dir, sources, report) and not missing:
+ report.ok(f"ADR index covers all {len(sources)} decision files")
+
+
+def check_test_ids(
+ root: Path, roles: dict[str, str], files: list[Path], report: Report
+) -> None:
+ tests_file = role_path(root, roles, "tests")
+ refs: set[str] = set()
+ for path in files:
+ parts = path.relative_to(root).parts
+ if path == tests_file or any(
+ section in parts
+ for section in ("templates", "skills", "commands", "agents", "references")
+ ):
+ continue
+ refs.update(
+ value.upper()
+ for value in TEST_ID_RE.findall(path.read_text(encoding="utf-8"))
+ )
+ refs.discard("TEST-ID")
+ if not refs:
+ report.ok("No cross-document TEST-ID references found")
+ return
+ if not tests_file.exists():
+ report.warn(
+ f"Found {len(refs)} TEST-ID references but no mapped test registry; review whether they are examples"
+ )
+ return
+ tests_text = read_utf8(tests_file, report, "test registry")
+ if tests_text is None:
+ return
+ defined = {value.upper() for value in TEST_ID_RE.findall(tests_text)}
+ missing = refs - defined
+ if missing:
+ report.fail(
+ "TEST-IDs are missing from the test registry: " + ", ".join(sorted(missing))
+ )
+ else:
+ report.ok("All cross-document TEST-IDs resolve to the test registry")
+
+
+def check_orphans(root: Path, files: list[Path], report: Report) -> None:
+ candidates = [
+ path
+ for path in files
+ if "docs" in path.relative_to(root).parts
+ and "templates" not in path.relative_to(root).parts
+ and path.name != "README.md"
+ ]
+ all_text = {path: path.read_text(encoding="utf-8") for path in files}
+ orphans: list[str] = []
+ for candidate in candidates:
+ relative = candidate.relative_to(root).as_posix()
+ if not any(
+ path != candidate and (relative in text or candidate.name in text)
+ for path, text in all_text.items()
+ ):
+ orphans.append(diagnostic(relative))
+ if orphans:
+ report.warn(
+ "Possible orphan documents; review whether to link or archive: "
+ + ", ".join(orphans)
+ )
+ else:
+ report.ok("No possible orphan documents found under docs/")
+
+
+def check_spine(
+ root: Path, roles: dict[str, str], report: Report, threshold: int
+) -> None:
+ report.section("spine")
+ for role in ("constitution", "map", "status", "history", "agents"):
+ name = roles[role]
+ if role_path(root, roles, role).exists():
+ report.ok(f"{diagnostic(name)} exists ({role})")
+ else:
+ report.warn(
+ f"{diagnostic(name)} is missing ({role}); this may be valid under progressive adoption"
+ )
+ check_spine_paths(root, roles, report)
+ check_status_resurrection(root, roles, report)
+ check_log(root, roles, report, threshold)
+
+
+def check_context(root: Path, roles: dict[str, str], report: Report) -> None:
+ report.section("context")
+ context = role_path(root, roles, "context")
+ if not context.exists():
+ report.warn(
+ "No context artifact; do not create an empty shell without stable domain language"
+ )
+ return
+ report.ok(
+ "Context artifact exists; terminology boundaries and code consistency require semantic review"
+ )
+
+
+def check_artifacts(root: Path, roles: dict[str, str], report: Report) -> None:
+ report.section("artifacts")
+ for role in ("contract", "tests", "regression"):
+ if not role_path(root, roles, role).exists():
+ report.warn(
+ f"{diagnostic(roles[role])} is missing ({role}); this may be valid under progressive adoption"
+ )
+ files = markdown_files(root, report)
+ check_markdown_links(root, files, report)
+ check_test_ids(root, roles, files, report)
+ check_orphans(root, files, report)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--root", type=Path, default=Path.cwd())
+ parser.add_argument(
+ "--scope",
+ choices=("spine", "context", "adr", "artifacts", "modules", "full"),
+ default="full",
+ )
+ parser.add_argument(
+ "--module", action="append", default=[],
+ help="Repository-relative module directory; repeat for several modules",
+ )
+ parser.add_argument("--log-threshold", type=int, default=200)
+ args = parser.parse_args()
+ if args.scope == "modules" and not args.module:
+ parser.error("--scope modules requires at least one --module directory")
+ if args.module and args.scope not in ("modules", "full"):
+ parser.error("--module is supported only with --scope modules or full")
+
+ root = args.root.resolve()
+ if not root.is_dir():
+ print(f"Not a directory: {diagnostic(root)}", file=sys.stderr)
+ return 2
+ report = Report()
+ roles = load_roles(root, report)
+ if args.module:
+ check_modules(
+ root, roles, args.module, report,
+ resolved_within_root, read_utf8, check_markdown_links,
+ )
+ if args.scope in ("spine", "full"):
+ check_spine(root, roles, report, args.log_threshold)
+ if args.scope in ("context", "full"):
+ check_context(root, roles, report)
+ if args.scope in ("adr", "full"):
+ report.section("adr")
+ check_adr(root, roles, report)
+ if args.scope in ("artifacts", "full"):
+ check_artifacts(root, roles, report)
+
+ print()
+ if report.failures:
+ print(
+ f"✗ Deterministic audit failed with {report.failures} issue(s). Fix integrity errors before semantic review."
+ )
+ return 1
+ print(
+ "✓ Deterministic audit passed. Review warnings manually, then continue to semantic audit."
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/pi/core/skills/docs-governance/scripts/markdown_links.py b/pi/core/skills/docs-governance/scripts/markdown_links.py
new file mode 100644
index 000000000..6725c065f
--- /dev/null
+++ b/pi/core/skills/docs-governance/scripts/markdown_links.py
@@ -0,0 +1,274 @@
+"""Small Markdown link parser used by the documentation-governance audit."""
+
+from __future__ import annotations
+
+import re
+from urllib.parse import unquote
+
+INLINE_LINK_START_RE = re.compile(r"\[[^\]\n]*\]\(")
+REFERENCE_DEFINITION_RE = re.compile(
+ r"""(?mx)
+ ^\ {0,3}\[(?P
}>
+
+
+```
+
+## Python
+
+### Custom Exception Hierarchy
+
+```python
+class AppError(Exception):
+ """Base application error."""
+ def __init__(self, message: str, code: str, status_code: int = 500):
+ super().__init__(message)
+ self.code = code
+ self.status_code = status_code
+
+class NotFoundError(AppError):
+ def __init__(self, resource: str, id: str):
+ super().__init__(f"{resource} not found: {id}", "NOT_FOUND", 404)
+
+class ValidationError(AppError):
+ def __init__(self, message: str, details: list[dict] | None = None):
+ super().__init__(message, "VALIDATION_ERROR", 422)
+ self.details = details or []
+```
+
+### FastAPI Global Exception Handler
+
+```python
+from fastapi import FastAPI, Request
+from fastapi.responses import JSONResponse
+
+app = FastAPI()
+
+@app.exception_handler(AppError)
+async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
+ return JSONResponse(
+ status_code=exc.status_code,
+ content={"error": {"code": exc.code, "message": str(exc)}},
+ )
+
+@app.exception_handler(Exception)
+async def generic_error_handler(request: Request, exc: Exception) -> JSONResponse:
+ # Log full details, return generic message
+ logger.exception("Unexpected error", exc_info=exc)
+ return JSONResponse(
+ status_code=500,
+ content={"error": {"code": "INTERNAL_ERROR", "message": "An unexpected error occurred"}},
+ )
+```
+
+## Go
+
+### Sentinel Errors and Error Wrapping
+
+```go
+package domain
+
+import "errors"
+
+// Sentinel errors for type-checking
+var (
+ ErrNotFound = errors.New("not found")
+ ErrUnauthorized = errors.New("unauthorized")
+ ErrConflict = errors.New("conflict")
+)
+
+// Wrap errors with context — never lose the original
+func (r *UserRepository) FindByID(ctx context.Context, id string) (*User, error) {
+ user, err := r.db.QueryRow(ctx, "SELECT * FROM users WHERE id = $1", id)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, fmt.Errorf("user %s: %w", id, ErrNotFound)
+ }
+ if err != nil {
+ return nil, fmt.Errorf("querying user %s: %w", id, err)
+ }
+ return user, nil
+}
+
+// At the handler level, unwrap to determine response
+func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {
+ user, err := h.service.GetUser(r.Context(), chi.URLParam(r, "id"))
+ if err != nil {
+ switch {
+ case errors.Is(err, domain.ErrNotFound):
+ writeError(w, http.StatusNotFound, "not_found", err.Error())
+ case errors.Is(err, domain.ErrUnauthorized):
+ writeError(w, http.StatusForbidden, "forbidden", "Access denied")
+ default:
+ slog.Error("unexpected error", "err", err)
+ writeError(w, http.StatusInternalServerError, "internal_error", "An unexpected error occurred")
+ }
+ return
+ }
+ writeJSON(w, http.StatusOK, user)
+}
+```
+
+## Retry with Exponential Backoff
+
+```typescript
+interface RetryOptions {
+ maxAttempts?: number
+ baseDelayMs?: number
+ maxDelayMs?: number
+ retryIf?: (error: unknown) => boolean
+}
+
+async function withRetry(
+ fn: () => Promise,
+ options: RetryOptions = {},
+): Promise {
+ const {
+ maxAttempts = 3,
+ baseDelayMs = 500,
+ maxDelayMs = 10_000,
+ retryIf = () => true,
+ } = options
+
+ let lastError: unknown
+
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ try {
+ return await fn()
+ } catch (error) {
+ lastError = error
+ if (attempt === maxAttempts || !retryIf(error)) throw error
+
+ const jitter = Math.random() * baseDelayMs
+ const delay = Math.min(baseDelayMs * 2 ** (attempt - 1) + jitter, maxDelayMs)
+ await new Promise(resolve => setTimeout(resolve, delay))
+ }
+ }
+
+ throw lastError
+}
+
+// Usage: retry transient network errors, not 4xx
+const data = await withRetry(() => fetch('/api/data').then(r => r.json()), {
+ maxAttempts: 3,
+ retryIf: (error) => !(error instanceof AppError && error.statusCode < 500),
+})
+```
+
+## User-Facing Error Messages
+
+Map error codes to human-readable messages. Keep technical details out of user-visible text.
+
+```typescript
+const USER_ERROR_MESSAGES: Record = {
+ NOT_FOUND: 'The requested item could not be found.',
+ UNAUTHORIZED: 'Please sign in to continue.',
+ FORBIDDEN: "You don't have permission to do that.",
+ VALIDATION_ERROR: 'Please check your input and try again.',
+ RATE_LIMITED: 'Too many requests. Please wait a moment and try again.',
+ INTERNAL_ERROR: 'Something went wrong on our end. Please try again later.',
+}
+
+export function getUserMessage(code: string): string {
+ return USER_ERROR_MESSAGES[code] ?? USER_ERROR_MESSAGES.INTERNAL_ERROR
+}
+```
+
+## Error Handling Checklist
+
+Before merging any code that touches error handling:
+
+- [ ] Every `catch` block handles, re-throws, or logs — no silent swallowing
+- [ ] API errors follow the standard envelope `{ error: { code, message } }`
+- [ ] User-facing messages contain no stack traces or internal details
+- [ ] Full error context is logged server-side
+- [ ] Custom error classes extend a base `AppError` with a `code` field
+- [ ] Async functions surface errors to callers — no fire-and-forget without fallback
+- [ ] Retry logic only retries retriable errors (not 4xx client errors)
+- [ ] React components are wrapped in `ErrorBoundary` for rendering errors
diff --git a/pi/core/skills/fastapi-patterns/SKILL.md b/pi/core/skills/fastapi-patterns/SKILL.md
new file mode 100644
index 000000000..b4a0a5b58
--- /dev/null
+++ b/pi/core/skills/fastapi-patterns/SKILL.md
@@ -0,0 +1,514 @@
+---
+name: fastapi-patterns
+description: FastAPI best practices covering project structure, Pydantic v2 schemas, dependency injection, async handlers, authentication, authorization, transactional service layers, and testing with httpx and pytest. Use when building or reviewing FastAPI apps — Pydantic schemas, dependencies, async handlers, auth, or tests.
+metadata:
+ origin: ECC
+---
+
+# FastAPI Patterns
+
+Modern, production-grade FastAPI development: project layout, Pydantic v2 schemas, dependency injection, async patterns, auth, transactional service methods, and testing.
+
+## Project Structure
+
+```text
+my_app/
+|-- app/
+| |-- main.py # App factory, lifespan, middleware
+| |-- config.py # Settings via pydantic-settings
+| |-- dependencies.py # Shared FastAPI dependencies
+| |-- database.py # SQLAlchemy engine + session
+| |-- routers/
+| | `-- users.py
+| |-- models/ # SQLAlchemy ORM models
+| | `-- user.py
+| |-- schemas/ # Pydantic request/response schemas
+| | `-- user.py
+| `-- services/ # Business logic layer
+| `-- user_service.py
+|-- tests/
+| |-- conftest.py
+| `-- test_users.py
+|-- pyproject.toml
+`-- .env
+```
+
+---
+
+## App Factory and Lifespan
+
+```python
+# app/main.py
+from contextlib import asynccontextmanager
+from fastapi import FastAPI
+from fastapi.middleware.cors import CORSMiddleware
+
+from app.config import settings
+from app.database import engine, Base
+from app.routers import users
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ # Automatically create tables on startup for ease of use in dev/demo environments.
+ # For strict production applications, manage schemas via Alembic migrations instead.
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+ yield
+ # Shutdown: close pooled resources.
+ await engine.dispose()
+
+
+def create_app() -> FastAPI:
+ app = FastAPI(
+ title=settings.app_name,
+ version=settings.app_version,
+ lifespan=lifespan,
+ )
+
+ app.add_middleware(
+ CORSMiddleware,
+ allow_origins=settings.allowed_origins,
+ allow_credentials=settings.allow_credentials,
+ allow_methods=settings.allowed_methods,
+ allow_headers=settings.allowed_headers,
+ )
+
+ app.include_router(users.router, prefix="/users", tags=["users"])
+
+ return app
+
+
+app = create_app()
+```
+
+---
+
+## Configuration with pydantic-settings
+
+```python
+# app/config.py
+from pydantic_settings import BaseSettings, SettingsConfigDict
+
+
+class Settings(BaseSettings):
+ model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
+
+ app_name: str = "My App"
+ app_version: str = "0.1.0"
+ debug: bool = False
+
+ database_url: str
+ secret_key: str
+ algorithm: str = "HS256"
+ access_token_expire_minutes: int = 30
+
+ # Pydantic-settings v2 safely evaluates mutable list literals directly
+ allowed_origins: list[str] = ["http://localhost:3000"]
+ allowed_methods: list[str] = ["GET", "POST", "PATCH", "DELETE", "OPTIONS"]
+ allowed_headers: list[str] = ["Authorization", "Content-Type"]
+ allow_credentials: bool = True
+
+
+settings = Settings()
+```
+
+---
+
+## Pydantic Schemas (v2)
+
+```python
+# app/schemas/user.py
+from datetime import datetime
+from pydantic import BaseModel, EmailStr, Field, model_validator
+
+
+class UserBase(BaseModel):
+ email: EmailStr
+ username: str = Field(min_length=3, max_length=50)
+
+
+class UserCreate(UserBase):
+ password: str = Field(min_length=8)
+ password_confirm: str
+
+ @model_validator(mode="after")
+ def passwords_match(self) -> "UserCreate":
+ if self.password != self.password_confirm:
+ raise ValueError("Passwords do not match")
+ return self
+
+
+class UserUpdate(BaseModel):
+ username: str | None = Field(default=None, min_length=3, max_length=50)
+ email: EmailStr | None = None
+
+
+class UserResponse(UserBase):
+ id: int
+ is_active: bool
+ created_at: datetime
+
+ model_config = {"from_attributes": True}
+
+
+class UserListResponse(BaseModel):
+ total: int
+ items: list[UserResponse]
+```
+
+---
+
+## Dependency Injection
+
+```python
+# app/dependencies.py
+from typing import Annotated, AsyncGenerator
+from fastapi import Depends, HTTPException, status
+from fastapi.security import OAuth2PasswordBearer
+from jose import JWTError, jwt
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.config import settings
+from app.database import AsyncSessionLocal
+from app.models.user import User
+
+oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/users/token")
+
+
+async def get_db() -> AsyncGenerator[AsyncSession, None]:
+ async with AsyncSessionLocal() as session:
+ try:
+ yield session
+ except Exception:
+ await session.rollback()
+ raise
+
+
+async def get_current_user(
+ token: Annotated[str, Depends(oauth2_scheme)],
+ db: Annotated[AsyncSession, Depends(get_db)],
+) -> User:
+ credentials_exception = HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Could not validate credentials",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+ try:
+ payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
+ subject = payload.get("sub")
+ if subject is None:
+ raise credentials_exception
+ user_id = int(subject)
+ except (JWTError, TypeError, ValueError):
+ raise credentials_exception
+
+ user = await db.get(User, user_id)
+ if user is None:
+ raise credentials_exception
+ return user
+
+
+async def get_current_active_user(
+ current_user: Annotated[User, Depends(get_current_user)],
+) -> User:
+ if not current_user.is_active:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user")
+ return current_user
+
+
+DbDep = Annotated[AsyncSession, Depends(get_db)]
+CurrentUserDep = Annotated[User, Depends(get_current_user)]
+ActiveUserDep = Annotated[User, Depends(get_current_active_user)]
+```
+
+---
+
+## Router and Endpoint Design
+
+```python
+# app/routers/users.py
+from typing import Annotated
+from fastapi import APIRouter, Depends, HTTPException, Query, status
+from fastapi.security import OAuth2PasswordRequestForm
+
+from app.dependencies import ActiveUserDep, DbDep
+from app.schemas.user import UserCreate, UserResponse, UserUpdate, UserListResponse
+from app.services.user_service import DuplicateUserError, UserService
+
+router = APIRouter()
+
+
+@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
+async def create_user(payload: UserCreate, db: DbDep) -> UserResponse:
+ service = UserService(db)
+ try:
+ return await service.create(payload)
+ except DuplicateUserError:
+ raise HTTPException(status_code=400, detail="Email already registered")
+
+
+@router.get("/me", response_model=UserResponse)
+async def get_me(current_user: ActiveUserDep) -> UserResponse:
+ return current_user
+
+
+@router.get("/", response_model=UserListResponse)
+async def list_users(
+ db: DbDep,
+ current_user: ActiveUserDep,
+ skip: Annotated[int, Query(ge=0)] = 0,
+ limit: Annotated[int, Query(ge=1, le=100)] = 20,
+) -> UserListResponse:
+ service = UserService(db)
+ users, total = await service.list(skip=skip, limit=limit)
+ return UserListResponse(total=total, items=users)
+
+
+@router.patch("/{user_id}", response_model=UserResponse)
+async def update_user(
+ user_id: int,
+ payload: UserUpdate,
+ db: DbDep,
+ current_user: ActiveUserDep,
+) -> UserResponse:
+ if current_user.id != user_id:
+ raise HTTPException(status_code=403, detail="Not authorized")
+ service = UserService(db)
+ try:
+ user = await service.update(user_id, payload)
+ except DuplicateUserError:
+ raise HTTPException(status_code=400, detail="Email already registered")
+ if user is None:
+ raise HTTPException(status_code=404, detail="User not found")
+ return user
+
+
+@router.post("/token")
+async def login(
+ form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
+ db: DbDep,
+) -> dict[str, str]:
+ service = UserService(db)
+ token = await service.authenticate(form_data.username, form_data.password)
+ if token is None:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Incorrect username or password",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+ return {"access_token": token, "token_type": "bearer"}
+```
+
+---
+
+## Service Layer
+
+```python
+# app/services/user_service.py
+from datetime import datetime, timedelta, timezone
+
+from jose import jwt
+from passlib.context import CryptContext
+from sqlalchemy import func, select
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.config import settings
+from app.models.user import User
+from app.schemas.user import UserCreate, UserUpdate
+
+pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
+
+
+class DuplicateUserError(Exception):
+ """Raised when a unique user field conflicts with an existing row."""
+
+
+class UserService:
+ def __init__(self, db: AsyncSession) -> None:
+ self.db = db
+
+ async def get_by_email(self, email: str) -> User | None:
+ result = await self.db.execute(select(User).where(User.email == email))
+ return result.scalar_one_or_none()
+
+ async def create(self, payload: UserCreate) -> User:
+ user = User(
+ email=payload.email,
+ username=payload.username,
+ hashed_password=pwd_context.hash(payload.password),
+ )
+ self.db.add(user)
+ try:
+ # Rely on atomic DB constraints rather than race-prone application-level prechecks
+ await self.db.commit()
+ except IntegrityError as exc:
+ await self.db.rollback()
+ raise DuplicateUserError from exc
+ await self.db.refresh(user)
+ return user
+
+ async def list(self, skip: int = 0, limit: int = 20) -> tuple[list[User], int]:
+ total_result = await self.db.execute(select(func.count(User.id)))
+ total = total_result.scalar_one()
+ # Enforce explicit deterministic ordering to ensure reliable pagination
+ result = await self.db.execute(
+ select(User).order_by(User.id).offset(skip).limit(limit)
+ )
+ return list(result.scalars()), total
+
+ async def update(self, user_id: int, payload: UserUpdate) -> User | None:
+ user = await self.db.get(User, user_id)
+ if user is None:
+ return None
+ for field, value in payload.model_dump(exclude_unset=True).items():
+ setattr(user, field, value)
+ try:
+ await self.db.commit()
+ except IntegrityError as exc:
+ await self.db.rollback()
+ raise DuplicateUserError from exc
+ await self.db.refresh(user)
+ return user
+
+ async def authenticate(self, email: str, password: str) -> str | None:
+ user = await self.get_by_email(email)
+ if user is None or not pwd_context.verify(password, user.hashed_password):
+ return None
+ expire = datetime.now(timezone.utc) + timedelta(
+ minutes=settings.access_token_expire_minutes
+ )
+ return jwt.encode(
+ {"sub": str(user.id), "exp": expire},
+ settings.secret_key,
+ algorithm=settings.algorithm,
+ )
+```
+
+> **Note on Database Design:** Application-level unique handling requires an underlying unique database index (e.g., `unique=True` on your SQLAlchemy mapping attributes). Without underlying constraints, application layer error-catching cannot safely prevent concurrent race conditions.
+
+---
+
+## Testing with httpx and pytest
+
+```python
+# tests/conftest.py
+import pytest_asyncio
+from httpx import ASGITransport, AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+
+from app.database import Base
+from app.dependencies import get_db
+from app.main import create_app
+
+TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"
+
+engine = create_async_engine(TEST_DATABASE_URL)
+TestingSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
+
+
+@pytest_asyncio.fixture(autouse=True)
+async def setup_db():
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+ yield
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.drop_all)
+
+
+@pytest_asyncio.fixture
+async def db_session():
+ async with TestingSessionLocal() as session:
+ yield session
+ await session.rollback()
+
+
+@pytest_asyncio.fixture
+async def client(db_session: AsyncSession):
+ app = create_app()
+
+ async def override_get_db():
+ yield db_session
+
+ app.dependency_overrides[get_db] = override_get_db
+
+ async with AsyncClient(
+ transport=ASGITransport(app=app), base_url="http://test"
+ ) as ac:
+ yield ac
+
+
+@pytest_asyncio.fixture
+async def registered_user(client: AsyncClient) -> dict:
+ resp = await client.post("/users/", json={
+ "email": "test@example.com",
+ "username": "testuser",
+ "password": "securepass1",
+ "password_confirm": "securepass1",
+ })
+ assert resp.status_code == 201
+ return resp.json()
+
+
+@pytest_asyncio.fixture
+async def auth_token(client: AsyncClient, registered_user: dict) -> str:
+ resp = await client.post("/users/token", data={
+ "username": "test@example.com",
+ "password": "securepass1",
+ })
+ assert resp.status_code == 200
+ return resp.json()["access_token"]
+
+
+@pytest_asyncio.fixture
+async def auth_client(client: AsyncClient, auth_token: str) -> AsyncClient:
+ client.headers.update({"Authorization": f"Bearer {auth_token}"})
+ return client
+```
+
+---
+
+## Anti-Patterns
+
+```python
+# Bad: business logic inside route handlers.
+@router.post("/users/")
+async def create_user(payload: UserCreate, db: DbDep):
+ hashed = bcrypt.hash(payload.password)
+ user = User(email=payload.email, hashed_password=hashed)
+ db.add(user)
+ await db.commit()
+ return user
+
+# Good: thin route, transactional service handling.
+@router.post("/users/", response_model=UserResponse, status_code=201)
+async def create_user(payload: UserCreate, db: DbDep):
+ try:
+ return await UserService(db).create(payload)
+ except DuplicateUserError:
+ raise HTTPException(status_code=400, detail="Email already registered")
+
+
+# Bad: sync DB calls in async routes block the event loop.
+@router.get("/items/")
+async def list_items(db: Session = Depends(get_db)):
+ return db.query(Item).all()
+
+# Good: use async SQLAlchemy executions.
+@router.get("/items/")
+async def list_items(db: AsyncSession = Depends(get_db)):
+ result = await db.execute(select(Item))
+ return result.scalars().all()
+```
+
+---
+
+## Best Practices
+
+- Always declare a typed `response_model` to prevent accidental PII/data leaks and output clean OpenAPI schemas.
+- Consolidate standard middleware dependency injections via type-aliasing: `DbDep = Annotated[AsyncSession, Depends(get_db)]`.
+- Wrap database mutation boundaries gracefully within transactions inside your service layer, catching structural database errors directly.
+- Parse JWT parameters defensively, expecting potential string/integer cast mismatches from modern payload variations.
+- Enforce deterministic sorting (e.g., `.order_by(Model.id)`) on all offset/limit paginated endpoints to avoid data skips.
+- Isolate authorization checks from core authentication dependencies to provide precise REST status signals (`401` vs `403`).
diff --git a/pi/core/skills/flutter-dart-code-review/SKILL.md b/pi/core/skills/flutter-dart-code-review/SKILL.md
new file mode 100644
index 000000000..f8f902a86
--- /dev/null
+++ b/pi/core/skills/flutter-dart-code-review/SKILL.md
@@ -0,0 +1,436 @@
+---
+name: flutter-dart-code-review
+description: Library-agnostic Flutter/Dart code review checklist covering widget best practices, state management patterns (BLoC, Riverpod, Provider, GetX, MobX, Signals), Dart idioms, performance, accessibility, security, and clean architecture. Use when reviewing Flutter or Dart code, whatever state management library the project uses.
+metadata:
+ origin: ECC
+---
+
+# Flutter/Dart Code Review Best Practices
+
+Comprehensive, library-agnostic checklist for reviewing Flutter/Dart applications. These principles apply regardless of which state management solution, routing library, or DI framework is used.
+
+---
+
+## 1. General Project Health
+
+- [ ] Project follows consistent folder structure (feature-first or layer-first)
+- [ ] Proper separation of concerns: UI, business logic, data layers
+- [ ] No business logic in widgets; widgets are purely presentational
+- [ ] `pubspec.yaml` is clean — no unused dependencies, versions pinned appropriately
+- [ ] `analysis_options.yaml` includes a strict lint set with strict analyzer settings enabled
+- [ ] No `print()` statements in production code — use `dart:developer` `log()` or a logging package
+- [ ] Generated files (`.g.dart`, `.freezed.dart`, `.gr.dart`) are up-to-date or in `.gitignore`
+- [ ] Platform-specific code isolated behind abstractions
+
+---
+
+## 2. Dart Language Pitfalls
+
+- [ ] **Implicit dynamic**: Missing type annotations leading to `dynamic` — enable `strict-casts`, `strict-inference`, `strict-raw-types`
+- [ ] **Null safety misuse**: Excessive `!` (bang operator) instead of proper null checks or Dart 3 pattern matching (`if (value case var v?)`)
+- [ ] **Type promotion failures**: Using `this.field` where local variable promotion would work
+- [ ] **Catching too broadly**: `catch (e)` without `on` clause; always specify exception types
+- [ ] **Catching `Error`**: `Error` subtypes indicate bugs and should not be caught
+- [ ] **Unused `async`**: Functions marked `async` that never `await` — unnecessary overhead
+- [ ] **`late` overuse**: `late` used where nullable or constructor initialization would be safer; defers errors to runtime
+- [ ] **String concatenation in loops**: Use `StringBuffer` instead of `+` for iterative string building
+- [ ] **Mutable state in `const` contexts**: Fields in `const` constructor classes should not be mutable
+- [ ] **Ignoring `Future` return values**: Use `await` or explicitly call `unawaited()` to signal intent
+- [ ] **`var` where `final` works**: Prefer `final` for locals and `const` for compile-time constants
+- [ ] **Relative imports**: Use `package:` imports for consistency
+- [ ] **Mutable collections exposed**: Public APIs should return unmodifiable views, not raw `List`/`Map`
+- [ ] **Missing Dart 3 pattern matching**: Prefer switch expressions and `if-case` over verbose `is` checks and manual casting
+- [ ] **Throwaway classes for multiple returns**: Use Dart 3 records `(String, int)` instead of single-use DTOs
+- [ ] **`print()` in production code**: Use `dart:developer` `log()` or the project's logging package; `print()` has no log levels and cannot be filtered
+
+---
+
+## 3. Widget Best Practices
+
+### Widget decomposition:
+- [ ] No single widget with a `build()` method exceeding ~80-100 lines
+- [ ] Widgets split by encapsulation AND by how they change (rebuild boundaries)
+- [ ] Private `_build*()` helper methods that return widgets are extracted to separate widget classes (enables element reuse, const propagation, and framework optimizations)
+- [ ] Stateless widgets preferred over Stateful where no mutable local state is needed
+- [ ] Extracted widgets are in separate files when reusable
+
+### Const usage:
+- [ ] `const` constructors used wherever possible — prevents unnecessary rebuilds
+- [ ] `const` literals for collections that don't change (`const []`, `const {}`)
+- [ ] Constructor is declared `const` when all fields are final
+
+### Key usage:
+- [ ] `ValueKey` used in lists/grids to preserve state across reorders
+- [ ] `GlobalKey` used sparingly — only when accessing state across the tree is truly needed
+- [ ] `UniqueKey` avoided in `build()` — it forces rebuild every frame
+- [ ] `ObjectKey` used when identity is based on a data object rather than a single value
+
+### Theming & design system:
+- [ ] Colors come from `Theme.of(context).colorScheme` — no hardcoded `Colors.red` or hex values
+- [ ] Text styles come from `Theme.of(context).textTheme` — no inline `TextStyle` with raw font sizes
+- [ ] Dark mode compatibility verified — no assumptions about light background
+- [ ] Spacing and sizing use consistent design tokens or constants, not magic numbers
+
+### Build method complexity:
+- [ ] No network calls, file I/O, or heavy computation in `build()`
+- [ ] No `Future.then()` or `async` work in `build()`
+- [ ] No subscription creation (`.listen()`) in `build()`
+- [ ] `setState()` localized to smallest possible subtree
+
+---
+
+## 4. State Management (Library-Agnostic)
+
+These principles apply to all Flutter state management solutions (BLoC, Riverpod, Provider, GetX, MobX, Signals, ValueNotifier, etc.).
+
+### Architecture:
+- [ ] Business logic lives outside the widget layer — in a state management component (BLoC, Notifier, Controller, Store, ViewModel, etc.)
+- [ ] State managers receive dependencies via injection, not by constructing them internally
+- [ ] A service or repository layer abstracts data sources — widgets and state managers should not call APIs or databases directly
+- [ ] State managers have a single responsibility — no "god" managers handling unrelated concerns
+- [ ] Cross-component dependencies follow the solution's conventions:
+ - In **Riverpod**: providers depending on providers via `ref.watch` is expected — flag only circular or overly tangled chains
+ - In **BLoC**: blocs should not directly depend on other blocs — prefer shared repositories or presentation-layer coordination
+ - In other solutions: follow the documented conventions for inter-component communication
+
+### Immutability & value equality (for immutable-state solutions: BLoC, Riverpod, Redux):
+- [ ] State objects are immutable — new instances created via `copyWith()` or constructors, never mutated in-place
+- [ ] State classes implement `==` and `hashCode` properly (all fields included in comparison)
+- [ ] Mechanism is consistent across the project — manual override, `Equatable`, `freezed`, Dart records, or other
+- [ ] Collections inside state objects are not exposed as raw mutable `List`/`Map`
+
+### Reactivity discipline (for reactive-mutation solutions: MobX, GetX, Signals):
+- [ ] State is only mutated through the solution's reactive API (`@action` in MobX, `.value` on signals, `.obs` in GetX) — direct field mutation bypasses change tracking
+- [ ] Derived values use the solution's computed mechanism rather than being stored redundantly
+- [ ] Reactions and disposers are properly cleaned up (`ReactionDisposer` in MobX, effect cleanup in Signals)
+
+### State shape design:
+- [ ] Mutually exclusive states use sealed types, union variants, or the solution's built-in async state type (e.g. Riverpod's `AsyncValue`) — not boolean flags (`isLoading`, `isError`, `hasData`)
+- [ ] Every async operation models loading, success, and error as distinct states
+- [ ] All state variants are handled exhaustively in UI — no silently ignored cases
+- [ ] Error states carry error information for display; loading states don't carry stale data
+- [ ] Nullable data is not used as a loading indicator — states are explicit
+
+```dart
+// BAD — boolean flag soup allows impossible states
+class UserState {
+ bool isLoading = false;
+ bool hasError = false; // isLoading && hasError is representable!
+ User? user;
+}
+
+// GOOD (immutable approach) — sealed types make impossible states unrepresentable
+sealed class UserState {}
+class UserInitial extends UserState {}
+class UserLoading extends UserState {}
+class UserLoaded extends UserState {
+ final User user;
+ const UserLoaded(this.user);
+}
+class UserError extends UserState {
+ final String message;
+ const UserError(this.message);
+}
+
+// GOOD (reactive approach) — observable enum + data, mutations via reactivity API
+// enum UserStatus { initial, loading, loaded, error }
+// Use your solution's observable/signal to wrap status and data separately
+```
+
+### Rebuild optimization:
+- [ ] State consumer widgets (Builder, Consumer, Observer, Obx, Watch, etc.) scoped as narrow as possible
+- [ ] Selectors used to rebuild only when specific fields change — not on every state emission
+- [ ] `const` widgets used to stop rebuild propagation through the tree
+- [ ] Computed/derived state is calculated reactively, not stored redundantly
+
+### Subscriptions & disposal:
+- [ ] All manual subscriptions (`.listen()`) are cancelled in `dispose()` / `close()`
+- [ ] Stream controllers are closed when no longer needed
+- [ ] Timers are cancelled in disposal lifecycle
+- [ ] Framework-managed lifecycle is preferred over manual subscription (declarative builders over `.listen()`)
+- [ ] `mounted` check before `setState` in async callbacks
+- [ ] `BuildContext` not used after `await` without checking `context.mounted` (Flutter 3.7+) — stale context causes crashes
+- [ ] No navigation, dialogs, or scaffold messages after async gaps without verifying the widget is still mounted
+- [ ] `BuildContext` never stored in singletons, state managers, or static fields
+
+### Local vs global state:
+- [ ] Ephemeral UI state (checkbox, slider, animation) uses local state (`setState`, `ValueNotifier`)
+- [ ] Shared state is lifted only as high as needed — not over-globalized
+- [ ] Feature-scoped state is properly disposed when the feature is no longer active
+
+---
+
+## 5. Performance
+
+### Unnecessary rebuilds:
+- [ ] `setState()` not called at root widget level — localize state changes
+- [ ] `const` widgets used to stop rebuild propagation
+- [ ] `RepaintBoundary` used around complex subtrees that repaint independently
+- [ ] `AnimatedBuilder` child parameter used for subtrees independent of animation
+
+### Expensive operations in build():
+- [ ] No sorting, filtering, or mapping large collections in `build()` — compute in state management layer
+- [ ] No regex compilation in `build()`
+- [ ] `MediaQuery.of(context)` usage is specific (e.g., `MediaQuery.sizeOf(context)`)
+
+### Image optimization:
+- [ ] Network images use caching (any caching solution appropriate for the project)
+- [ ] Appropriate image resolution for target device (no loading 4K images for thumbnails)
+- [ ] `Image.asset` with `cacheWidth`/`cacheHeight` to decode at display size
+- [ ] Placeholder and error widgets provided for network images
+
+### Lazy loading:
+- [ ] `ListView.builder` / `GridView.builder` used instead of `ListView(children: [...])` for large or dynamic lists (concrete constructors are fine for small, static lists)
+- [ ] Pagination implemented for large data sets
+- [ ] Deferred loading (`deferred as`) used for heavy libraries in web builds
+
+### Other:
+- [ ] `Opacity` widget avoided in animations — use `AnimatedOpacity` or `FadeTransition`
+- [ ] Clipping avoided in animations — pre-clip images
+- [ ] `operator ==` not overridden on widgets — use `const` constructors instead
+- [ ] Intrinsic dimension widgets (`IntrinsicHeight`, `IntrinsicWidth`) used sparingly (extra layout pass)
+
+---
+
+## 6. Testing
+
+### Test types and expectations:
+- [ ] **Unit tests**: Cover all business logic (state managers, repositories, utility functions)
+- [ ] **Widget tests**: Cover individual widget behavior, interactions, and visual output
+- [ ] **Integration tests**: Cover critical user flows end-to-end
+- [ ] **Golden tests**: Pixel-perfect comparisons for design-critical UI components
+
+### Coverage targets:
+- [ ] Aim for 80%+ line coverage on business logic
+- [ ] All state transitions have corresponding tests (loading → success, loading → error, retry, etc.)
+- [ ] Edge cases tested: empty states, error states, loading states, boundary values
+
+### Test isolation:
+- [ ] External dependencies (API clients, databases, services) are mocked or faked
+- [ ] Each test file tests exactly one class/unit
+- [ ] Tests verify behavior, not implementation details
+- [ ] Stubs define only the behavior needed for each test (minimal stubbing)
+- [ ] No shared mutable state between test cases
+
+### Widget test quality:
+- [ ] `pumpWidget` and `pump` used correctly for async operations
+- [ ] `find.byType`, `find.text`, `find.byKey` used appropriately
+- [ ] No flaky tests depending on timing — use `pumpAndSettle` or explicit `pump(Duration)`
+- [ ] Tests run in CI and failures block merges
+
+---
+
+## 7. Accessibility
+
+### Semantic widgets:
+- [ ] `Semantics` widget used to provide screen reader labels where automatic labels are insufficient
+- [ ] `ExcludeSemantics` used for purely decorative elements
+- [ ] `MergeSemantics` used to combine related widgets into a single accessible element
+- [ ] Images have `semanticLabel` property set
+
+### Screen reader support:
+- [ ] All interactive elements are focusable and have meaningful descriptions
+- [ ] Focus order is logical (follows visual reading order)
+
+### Visual accessibility:
+- [ ] Contrast ratio >= 4.5:1 for text against background
+- [ ] Tappable targets are at least 48x48 pixels
+- [ ] Color is not the sole indicator of state (use icons/text alongside)
+- [ ] Text scales with system font size settings
+
+### Interaction accessibility:
+- [ ] No no-op `onPressed` callbacks — every button does something or is disabled
+- [ ] Error fields suggest corrections
+- [ ] Context does not change unexpectedly while user is inputting data
+
+---
+
+## 8. Platform-Specific Concerns
+
+### iOS/Android differences:
+- [ ] Platform-adaptive widgets used where appropriate
+- [ ] Back navigation handled correctly (Android back button, iOS swipe-to-go-back)
+- [ ] Status bar and safe area handled via `SafeArea` widget
+- [ ] Platform-specific permissions declared in `AndroidManifest.xml` and `Info.plist`
+
+### Responsive design:
+- [ ] `LayoutBuilder` or `MediaQuery` used for responsive layouts
+- [ ] Breakpoints defined consistently (phone, tablet, desktop)
+- [ ] Text doesn't overflow on small screens — use `Flexible`, `Expanded`, `FittedBox`
+- [ ] Landscape orientation tested or explicitly locked
+- [ ] Web-specific: mouse/keyboard interactions supported, hover states present
+
+---
+
+## 9. Security
+
+### Secure storage:
+- [ ] Sensitive data (tokens, credentials) stored using platform-secure storage (Keychain on iOS, EncryptedSharedPreferences on Android)
+- [ ] Never store secrets in plaintext storage
+- [ ] Biometric authentication gating considered for sensitive operations
+
+### API key handling:
+- [ ] API keys NOT hardcoded in Dart source — use `--dart-define`, `.env` files excluded from VCS, or compile-time configuration
+- [ ] Secrets not committed to git — check `.gitignore`
+- [ ] Backend proxy used for truly secret keys (client should never hold server secrets)
+
+### Input validation:
+- [ ] All user input validated before sending to API
+- [ ] Form validation uses proper validation patterns
+- [ ] No raw SQL or string interpolation of user input
+- [ ] Deep link URLs validated and sanitized before navigation
+
+### Network security:
+- [ ] HTTPS enforced for all API calls
+- [ ] Certificate pinning considered for high-security apps
+- [ ] Authentication tokens refreshed and expired properly
+- [ ] No sensitive data logged or printed
+
+---
+
+## 10. Package/Dependency Review
+
+### Evaluating pub.dev packages:
+- [ ] Check **pub points score** (aim for 130+/160)
+- [ ] Check **likes** and **popularity** as community signals
+- [ ] Verify the publisher is **verified** on pub.dev
+- [ ] Check last publish date — stale packages (>1 year) are a risk
+- [ ] Review open issues and response time from maintainers
+- [ ] Check license compatibility with your project
+- [ ] Verify platform support covers your targets
+
+### Version constraints:
+- [ ] Use caret syntax (`^1.2.3`) for dependencies — allows compatible updates
+- [ ] Pin exact versions only when absolutely necessary
+- [ ] Run `flutter pub outdated` regularly to track stale dependencies
+- [ ] No dependency overrides in production `pubspec.yaml` — only for temporary fixes with a comment/issue link
+- [ ] Minimize transitive dependency count — each dependency is an attack surface
+
+### Monorepo-specific (melos/workspace):
+- [ ] Internal packages import only from public API — no `package:other/src/internal.dart` (breaks Dart package encapsulation)
+- [ ] Internal package dependencies use workspace resolution, not hardcoded `path: ../../` relative strings
+- [ ] All sub-packages share or inherit root `analysis_options.yaml`
+
+---
+
+## 11. Navigation and Routing
+
+### General principles (apply to any routing solution):
+- [ ] One routing approach used consistently — no mixing imperative `Navigator.push` with a declarative router
+- [ ] Route arguments are typed — no `Map` or `Object?` casting
+- [ ] Route paths defined as constants, enums, or generated — no magic strings scattered in code
+- [ ] Auth guards/redirects centralized — not duplicated across individual screens
+- [ ] Deep links configured for both Android and iOS
+- [ ] Deep link URLs validated and sanitized before navigation
+- [ ] Navigation state is testable — route changes can be verified in tests
+- [ ] Back behavior is correct on all platforms
+
+---
+
+## 12. Error Handling
+
+### Framework error handling:
+- [ ] `FlutterError.onError` overridden to capture framework errors (build, layout, paint)
+- [ ] `PlatformDispatcher.instance.onError` set for async errors not caught by Flutter
+- [ ] `ErrorWidget.builder` customized for release mode (user-friendly instead of red screen)
+- [ ] Global error capture wrapper around `runApp` (e.g., `runZonedGuarded`, Sentry/Crashlytics wrapper)
+
+### Error reporting:
+- [ ] Error reporting service integrated (Firebase Crashlytics, Sentry, or equivalent)
+- [ ] Non-fatal errors reported with stack traces
+- [ ] State management error observer wired to error reporting (e.g., BlocObserver, ProviderObserver, or equivalent for your solution)
+- [ ] User-identifiable info (user ID) attached to error reports for debugging
+
+### Graceful degradation:
+- [ ] API errors result in user-friendly error UI, not crashes
+- [ ] Retry mechanisms for transient network failures
+- [ ] Offline state handled gracefully
+- [ ] Error states in state management carry error info for display
+- [ ] Raw exceptions (network, parsing) are mapped to user-friendly, localized messages before reaching the UI — never show raw exception strings to users
+
+---
+
+## 13. Internationalization (l10n)
+
+### Setup:
+- [ ] Localization solution configured (Flutter's built-in ARB/l10n, easy_localization, or equivalent)
+- [ ] Supported locales declared in app configuration
+
+### Content:
+- [ ] All user-visible strings use the localization system — no hardcoded strings in widgets
+- [ ] Template file includes descriptions/context for translators
+- [ ] ICU message syntax used for plurals, genders, selects
+- [ ] Placeholders defined with types
+- [ ] No missing keys across locales
+
+### Code review:
+- [ ] Localization accessor used consistently throughout the project
+- [ ] Date, time, number, and currency formatting is locale-aware
+- [ ] Text directionality (RTL) supported if targeting Arabic, Hebrew, etc.
+- [ ] No string concatenation for localized text — use parameterized messages
+
+---
+
+## 14. Dependency Injection
+
+### Principles (apply to any DI approach):
+- [ ] Classes depend on abstractions (interfaces), not concrete implementations at layer boundaries
+- [ ] Dependencies provided externally via constructor, DI framework, or provider graph — not created internally
+- [ ] Registration distinguishes lifetime: singleton vs factory vs lazy singleton
+- [ ] Environment-specific bindings (dev/staging/prod) use configuration, not runtime `if` checks
+- [ ] No circular dependencies in the DI graph
+- [ ] Service locator calls (if used) are not scattered throughout business logic
+
+---
+
+## 15. Static Analysis
+
+### Configuration:
+- [ ] `analysis_options.yaml` present with strict settings enabled
+- [ ] Strict analyzer settings: `strict-casts: true`, `strict-inference: true`, `strict-raw-types: true`
+- [ ] A comprehensive lint rule set is included (very_good_analysis, flutter_lints, or custom strict rules)
+- [ ] All sub-packages in monorepos inherit or share the root analysis options
+
+### Enforcement:
+- [ ] No unresolved analyzer warnings in committed code
+- [ ] Lint suppressions (`// ignore:`) are justified with comments explaining why
+- [ ] `flutter analyze` runs in CI and failures block merges
+
+### Key rules to verify regardless of lint package:
+- [ ] `prefer_const_constructors` — performance in widget trees
+- [ ] `avoid_print` — use proper logging
+- [ ] `unawaited_futures` — prevent fire-and-forget async bugs
+- [ ] `prefer_final_locals` — immutability at variable level
+- [ ] `always_declare_return_types` — explicit contracts
+- [ ] `avoid_catches_without_on_clauses` — specific error handling
+- [ ] `always_use_package_imports` — consistent import style
+
+---
+
+## State Management Quick Reference
+
+The table below maps universal principles to their implementation in popular solutions. Use this to adapt review rules to whichever solution the project uses.
+
+| Principle | BLoC/Cubit | Riverpod | Provider | GetX | MobX | Signals | Built-in |
+|-----------|-----------|----------|----------|------|------|---------|----------|
+| State container | `Bloc`/`Cubit` | `Notifier`/`AsyncNotifier` | `ChangeNotifier` | `GetxController` | `Store` | `signal()` | `StatefulWidget` |
+| UI consumer | `BlocBuilder` | `ConsumerWidget` | `Consumer` | `Obx`/`GetBuilder` | `Observer` | `Watch` | `setState` |
+| Selector | `BlocSelector`/`buildWhen` | `ref.watch(p.select(...))` | `Selector` | N/A | computed | `computed()` | N/A |
+| Side effects | `BlocListener` | `ref.listen` | `Consumer` callback | `ever()`/`once()` | `reaction` | `effect()` | callbacks |
+| Disposal | auto via `BlocProvider` | `.autoDispose` | auto via `Provider` | `onClose()` | `ReactionDisposer` | manual | `dispose()` |
+| Testing | `blocTest()` | `ProviderContainer` | `ChangeNotifier` directly | `Get.put` in test | store directly | signal directly | widget test |
+
+---
+
+## Sources
+
+- [Effective Dart: Style](https://dart.dev/effective-dart/style)
+- [Effective Dart: Usage](https://dart.dev/effective-dart/usage)
+- [Effective Dart: Design](https://dart.dev/effective-dart/design)
+- [Flutter Performance Best Practices](https://docs.flutter.dev/perf/best-practices)
+- [Flutter Testing Overview](https://docs.flutter.dev/testing/overview)
+- [Flutter Accessibility](https://docs.flutter.dev/ui/accessibility-and-internationalization/accessibility)
+- [Flutter Internationalization](https://docs.flutter.dev/ui/accessibility-and-internationalization/internationalization)
+- [Flutter Navigation and Routing](https://docs.flutter.dev/ui/navigation)
+- [Flutter Error Handling](https://docs.flutter.dev/testing/errors)
+- [Flutter State Management Options](https://docs.flutter.dev/data-and-backend/state-mgmt/options)
diff --git a/pi/core/skills/foundation-models-on-device/SKILL.md b/pi/core/skills/foundation-models-on-device/SKILL.md
new file mode 100644
index 000000000..1af357368
--- /dev/null
+++ b/pi/core/skills/foundation-models-on-device/SKILL.md
@@ -0,0 +1,243 @@
+---
+name: foundation-models-on-device
+description: Apple FoundationModels framework for on-device LLM — text generation, guided generation with @Generable, tool calling, and snapshot streaming in iOS 26+. Use when adding on-device LLM features with Apple FoundationModels on iOS 26+.
+---
+
+# FoundationModels: On-Device LLM (iOS 26)
+
+Patterns for integrating Apple's on-device language model into apps using the FoundationModels framework. Covers text generation, structured output with `@Generable`, custom tool calling, and snapshot streaming — all running on-device for privacy and offline support.
+
+## When to Activate
+
+- Building AI-powered features using Apple Intelligence on-device
+- Generating or summarizing text without cloud dependency
+- Extracting structured data from natural language input
+- Implementing custom tool calling for domain-specific AI actions
+- Streaming structured responses for real-time UI updates
+- Need privacy-preserving AI (no data leaves the device)
+
+## Core Pattern — Availability Check
+
+Always check model availability before creating a session:
+
+```swift
+struct GenerativeView: View {
+ private var model = SystemLanguageModel.default
+
+ var body: some View {
+ switch model.availability {
+ case .available:
+ ContentView()
+ case .unavailable(.deviceNotEligible):
+ Text("Device not eligible for Apple Intelligence")
+ case .unavailable(.appleIntelligenceNotEnabled):
+ Text("Please enable Apple Intelligence in Settings")
+ case .unavailable(.modelNotReady):
+ Text("Model is downloading or not ready")
+ case .unavailable(let other):
+ Text("Model unavailable: \(other)")
+ }
+ }
+}
+```
+
+## Core Pattern — Basic Session
+
+```swift
+// Single-turn: create a new session each time
+let session = LanguageModelSession()
+let response = try await session.respond(to: "What's a good month to visit Paris?")
+print(response.content)
+
+// Multi-turn: reuse session for conversation context
+let session = LanguageModelSession(instructions: """
+ You are a cooking assistant.
+ Provide recipe suggestions based on ingredients.
+ Keep suggestions brief and practical.
+ """)
+
+let first = try await session.respond(to: "I have chicken and rice")
+let followUp = try await session.respond(to: "What about a vegetarian option?")
+```
+
+Key points for instructions:
+- Define the model's role ("You are a mentor")
+- Specify what to do ("Help extract calendar events")
+- Set style preferences ("Respond as briefly as possible")
+- Add safety measures ("Respond with 'I can't help with that' for dangerous requests")
+
+## Core Pattern — Guided Generation with @Generable
+
+Generate structured Swift types instead of raw strings:
+
+### 1. Define a Generable Type
+
+```swift
+@Generable(description: "Basic profile information about a cat")
+struct CatProfile {
+ var name: String
+
+ @Guide(description: "The age of the cat", .range(0...20))
+ var age: Int
+
+ @Guide(description: "A one sentence profile about the cat's personality")
+ var profile: String
+}
+```
+
+### 2. Request Structured Output
+
+```swift
+let response = try await session.respond(
+ to: "Generate a cute rescue cat",
+ generating: CatProfile.self
+)
+
+// Access structured fields directly
+print("Name: \(response.content.name)")
+print("Age: \(response.content.age)")
+print("Profile: \(response.content.profile)")
+```
+
+### Supported @Guide Constraints
+
+- `.range(0...20)` — numeric range
+- `.count(3)` — array element count
+- `description:` — semantic guidance for generation
+
+## Core Pattern — Tool Calling
+
+Let the model invoke custom code for domain-specific tasks:
+
+### 1. Define a Tool
+
+```swift
+struct RecipeSearchTool: Tool {
+ let name = "recipe_search"
+ let description = "Search for recipes matching a given term and return a list of results."
+
+ @Generable
+ struct Arguments {
+ var searchTerm: String
+ var numberOfResults: Int
+ }
+
+ func call(arguments: Arguments) async throws -> ToolOutput {
+ let recipes = await searchRecipes(
+ term: arguments.searchTerm,
+ limit: arguments.numberOfResults
+ )
+ return .string(recipes.map { "- \($0.name): \($0.description)" }.joined(separator: "\n"))
+ }
+}
+```
+
+### 2. Create Session with Tools
+
+```swift
+let session = LanguageModelSession(tools: [RecipeSearchTool()])
+let response = try await session.respond(to: "Find me some pasta recipes")
+```
+
+### 3. Handle Tool Errors
+
+```swift
+do {
+ let answer = try await session.respond(to: "Find a recipe for tomato soup.")
+} catch let error as LanguageModelSession.ToolCallError {
+ print(error.tool.name)
+ if case .databaseIsEmpty = error.underlyingError as? RecipeSearchToolError {
+ // Handle specific tool error
+ }
+}
+```
+
+## Core Pattern — Snapshot Streaming
+
+Stream structured responses for real-time UI with `PartiallyGenerated` types:
+
+```swift
+@Generable
+struct TripIdeas {
+ @Guide(description: "Ideas for upcoming trips")
+ var ideas: [String]
+}
+
+let stream = session.streamResponse(
+ to: "What are some exciting trip ideas?",
+ generating: TripIdeas.self
+)
+
+for try await partial in stream {
+ // partial: TripIdeas.PartiallyGenerated (all properties Optional)
+ print(partial)
+}
+```
+
+### SwiftUI Integration
+
+```swift
+@State private var partialResult: TripIdeas.PartiallyGenerated?
+@State private var errorMessage: String?
+
+var body: some View {
+ List {
+ ForEach(partialResult?.ideas ?? [], id: \.self) { idea in
+ Text(idea)
+ }
+ }
+ .overlay {
+ if let errorMessage { Text(errorMessage).foregroundStyle(.red) }
+ }
+ .task {
+ do {
+ let stream = session.streamResponse(to: prompt, generating: TripIdeas.self)
+ for try await partial in stream {
+ partialResult = partial
+ }
+ } catch {
+ errorMessage = error.localizedDescription
+ }
+ }
+}
+```
+
+## Key Design Decisions
+
+| Decision | Rationale |
+|----------|-----------|
+| On-device execution | Privacy — no data leaves the device; works offline |
+| 4,096 token limit | On-device model constraint; chunk large data across sessions |
+| Snapshot streaming (not deltas) | Structured output friendly; each snapshot is a complete partial state |
+| `@Generable` macro | Compile-time safety for structured generation; auto-generates `PartiallyGenerated` type |
+| Single request per session | `isResponding` prevents concurrent requests; create multiple sessions if needed |
+| `response.content` (not `.output`) | Correct API — always access results via `.content` property |
+
+## Best Practices
+
+- **Always check `model.availability`** before creating a session — handle all unavailability cases
+- **Use `instructions`** to guide model behavior — they take priority over prompts
+- **Check `isResponding`** before sending a new request — sessions handle one request at a time
+- **Access `response.content`** for results — not `.output`
+- **Break large inputs into chunks** — 4,096 token limit applies to instructions + prompt + output combined
+- **Use `@Generable`** for structured output — stronger guarantees than parsing raw strings
+- **Use `GenerationOptions(temperature:)`** to tune creativity (higher = more creative)
+- **Monitor with Instruments** — use Xcode Instruments to profile request performance
+
+## Anti-Patterns to Avoid
+
+- Creating sessions without checking `model.availability` first
+- Sending inputs exceeding the 4,096 token context window
+- Attempting concurrent requests on a single session
+- Using `.output` instead of `.content` to access response data
+- Parsing raw string responses when `@Generable` structured output would work
+- Building complex multi-step logic in a single prompt — break into multiple focused prompts
+- Assuming the model is always available — device eligibility and settings vary
+
+## When to Use
+
+- On-device text generation for privacy-sensitive apps
+- Structured data extraction from user input (forms, natural language commands)
+- AI-assisted features that must work offline
+- Streaming UI that progressively shows generated content
+- Domain-specific AI actions via tool calling (search, compute, lookup)
diff --git a/pi/core/skills/frontend-a11y/SKILL.md b/pi/core/skills/frontend-a11y/SKILL.md
new file mode 100644
index 000000000..a39419935
--- /dev/null
+++ b/pi/core/skills/frontend-a11y/SKILL.md
@@ -0,0 +1,443 @@
+---
+name: frontend-a11y
+description: Accessibility patterns for React and Next.js — semantic HTML, ARIA attributes, form labeling, keyboard navigation, focus management, and screen reader support. Use when building or reviewing forms, modals, dropdowns, tooltips, or tabs, fixing a11y lint or code-review findings, or wiring up keyboard navigation and focus management.
+metadata:
+ origin: community
+---
+
+# Frontend Accessibility Patterns
+
+Practical accessibility patterns for React and Next.js. Covers the issues most commonly flagged in code review: missing form labels, incorrect ARIA usage, non-semantic interactive elements, and broken keyboard navigation.
+
+## When to Activate
+
+- Building or reviewing form components (``, `