πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore: upgrde claude code (#10140)
Max Deichmann0ef38fdc0eb7
diff --git a/.claude/hooks/CONFIG.md b/.claude/hooks/CONFIG.mdnew file mode 100644index 0000000000..c110b7c0a3--- /dev/null+++ b/.claude/hooks/CONFIG.md@@ -0,0 +1,436 @@+# Hooks Configuration Guide++This guide explains how to configure and customize the hooks system for your project.++## Quick Start Configuration++### 1. Register Hooks in .claude/settings.json++Create or update `.claude/settings.json` in your project root:++```json+{+ "hooks": {+ "UserPromptSubmit": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/skill-activation-prompt.sh"+ }+ ]+ }+ ],+ "Stop": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/error-handling-reminder.sh"+ }+ ]+ }+ ]+ }+}+```++### 2. Install Dependencies++```bash+cd .claude/hooks+npm install+```++### 3. Set Execute Permissions++```bash+chmod +x .claude/hooks/*.sh+```++## Customization Options++### Project Structure Detection++By default, hooks detect these directory patterns:++**Frontend:** `frontend/`, `client/`, `web/`, `app/`, `ui/`+**Backend:** `backend/`, `server/`, `api/`, `src/`, `services/`+**Database:** `database/`, `prisma/`, `migrations/`+**Monorepo:** `packages/*`, `examples/*`++#### Adding Custom Directory Patterns++Edit `.claude/hooks/post-tool-use-tracker.sh`, function `detect_repo()`:++```bash+case "$repo" in+ # Add your custom directories here+ my-custom-service)+ echo "$repo"+ ;;+ admin-panel)+ echo "$repo"+ ;;+ # ... existing patterns+esac+```++### Build Command Detection++The hooks auto-detect build commands based on:++1. Presence of `package.json` with "build" script+2. Package manager (pnpm > npm > yarn)+3. Special cases (Prisma schemas)++#### Customizing Build Commands++Edit `.claude/hooks/post-tool-use-tracker.sh`, function `get_build_command()`:++```bash+# Add custom build logic+if [[ "$repo" == "my-service" ]]; then+ echo "cd $repo_path && make build"+ return+fi+```++### TypeScript Configuration++Hooks automatically detect:++- `tsconfig.json` for standard TypeScript projects+- `tsconfig.app.json` for Vite/React projects++#### Custom TypeScript Configs++Edit `.claude/hooks/post-tool-use-tracker.sh`, function `get_tsc_command()`:++```bash+if [[ "$repo" == "my-service" ]]; then+ echo "cd $repo_path && npx tsc --project tsconfig.build.json --noEmit"+ return+fi+```++### Prettier Configuration++The prettier hook searches for configs in this order:++1. Current file directory (walking upward)+2. Project root+3. Falls back to Prettier defaults++#### Custom Prettier Config Search++Edit `.claude/hooks/stop-prettier-formatter.sh`, function `get_prettier_config()`:++```bash+# Add custom config locations+if [[ -f "$project_root/config/.prettierrc" ]]; then+ echo "$project_root/config/.prettierrc"+ return+fi+```++### Error Handling Reminders++Configure file category detection in `.claude/hooks/error-handling-reminder.ts`:++```typescript+function getFileCategory(+ filePath: string,+): "backend" | "frontend" | "database" | "other" {+ // Add custom patterns+ if (filePath.includes("/my-custom-dir/")) return "backend";+ // ... existing patterns+}+```++### Error Threshold Configuration++Change when to recommend the auto-error-resolver agent.++Edit `.claude/hooks/stop-build-check-enhanced.sh`:++```bash+# Default is 5 errors - change to your preference+if [[ $total_errors -ge 10 ]]; then # Now requires 10+ errors+ # Recommend agent+fi+```++## Environment Variables++### Global Environment Variables++Set in your shell profile (`.bashrc`, `.zshrc`, etc.):++```bash+# Disable error handling reminders+export SKIP_ERROR_REMINDER=1++# Custom project directory (if not using default)+export CLAUDE_PROJECT_DIR=/path/to/your/project+```++### Per-Session Environment Variables++Set before starting Claude Code:++```bash+SKIP_ERROR_REMINDER=1 claude-code+```++## Hook Execution Order++Stop hooks run in the order specified in `settings.json`:++```json+"Stop": [+ {+ "hooks": [+ { "command": "...formatter.sh" }, // Runs FIRST+ { "command": "...build-check.sh" }, // Runs SECOND+ { "command": "...reminder.sh" } // Runs THIRD+ ]+ }+]+```++**Why this order matters:**++1. Format files first (clean code)+2. Then check for errors+3. Finally show reminders++## Selective Hook Enabling++You don't need all hooks. Choose what works for your project:++### Minimal Setup (Skill Activation Only)++```json+{+ "hooks": {+ "UserPromptSubmit": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/skill-activation-prompt.sh"+ }+ ]+ }+ ]+ }+}+```++### Build Checking Only (No Formatting)++```json+{+ "hooks": {+ "PostToolUse": [+ {+ "matcher": "Edit|MultiEdit|Write",+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/post-tool-use-tracker.sh"+ }+ ]+ }+ ],+ "Stop": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/stop-build-check-enhanced.sh"+ }+ ]+ }+ ]+ }+}+```++### Formatting Only (No Build Checking)++```json+{+ "hooks": {+ "PostToolUse": [+ {+ "matcher": "Edit|MultiEdit|Write",+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/post-tool-use-tracker.sh"+ }+ ]+ }+ ],+ "Stop": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/stop-prettier-formatter.sh"+ }+ ]+ }+ ]+ }+}+```++## Cache Management++### Cache Location++```+$CLAUDE_PROJECT_DIR/.claude/tsc-cache/[session_id]/+```++### Manual Cache Cleanup++```bash+# Remove all cached data+rm -rf $CLAUDE_PROJECT_DIR/.claude/tsc-cache/*++# Remove specific session+rm -rf $CLAUDE_PROJECT_DIR/.claude/tsc-cache/[session-id]+```++### Automatic Cleanup++The build-check hook automatically cleans up session cache on successful builds.++## Troubleshooting Configuration++### Hook Not Executing++1. **Check registration:** Verify hook is in `.claude/settings.json`+2. **Check permissions:** Run `chmod +x .claude/hooks/*.sh`+3. **Check path:** Ensure `$CLAUDE_PROJECT_DIR` is set correctly+4. **Check TypeScript:** Run `cd .claude/hooks && npx tsc` to check for errors++### False Positive Detections++**Issue:** Hook triggers for files it shouldn't++**Solution:** Add skip conditions in the relevant hook:++```bash+# In post-tool-use-tracker.sh+if [[ "$file_path" =~ /generated/ ]]; then+ exit 0 # Skip generated files+fi+```++### Performance Issues++**Issue:** Hooks are slow++**Solutions:**++1. Limit TypeScript checks to changed files only+2. Use faster package managers (pnpm > npm)+3. Add more skip conditions+4. Disable Prettier for large files++```bash+# Skip large files in stop-prettier-formatter.sh+file_size=$(wc -c < "$file" 2>/dev/null || echo 0)+if [[ $file_size -gt 100000 ]]; then # Skip files > 100KB+ continue+fi+```++### Debugging Hooks++Add debug output to any hook:++```bash+# At the top of the hook script+set -x # Enable debug mode++# Or add specific debug lines+echo "DEBUG: file_path=$file_path" >&2+echo "DEBUG: repo=$repo" >&2+```++View hook execution in Claude Code's logs.++## Advanced Configuration++### Custom Hook Event Handlers++You can create your own hooks for other events:++```json+{+ "hooks": {+ "PreToolUse": [+ {+ "matcher": "Bash",+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/my-custom-bash-guard.sh"+ }+ ]+ }+ ]+ }+}+```++### Monorepo Configuration++For monorepos with multiple packages:++```bash+# In post-tool-use-tracker.sh, detect_repo()+case "$repo" in+ packages)+ # Get the package name+ local package=$(echo "$relative_path" | cut -d'/' -f2)+ if [[ -n "$package" ]]; then+ echo "packages/$package"+ else+ echo "$repo"+ fi+ ;;+esac+```++### Docker/Container Projects++If your build commands need to run in containers:++```bash+# In post-tool-use-tracker.sh, get_build_command()+if [[ "$repo" == "api" ]]; then+ echo "docker-compose exec api npm run build"+ return+fi+```++## Best Practices++1. **Start minimal** - Enable hooks one at a time+2. **Test thoroughly** - Make changes and verify hooks work+3. **Document customizations** - Add comments to explain custom logic+4. **Version control** - Commit `.claude/` directory to git+5. **Team consistency** - Share configuration across team++## See Also++- [README.md](./README.md) - Hooks overview+- [../../docs/HOOKS_SYSTEM.md](../../docs/HOOKS_SYSTEM.md) - Complete hooks reference+- [../../docs/SKILLS_SYSTEM.md](../../docs/SKILLS_SYSTEM.md) - Skills integrationdiff --git a/.claude/hooks/README.md b/.claude/hooks/README.mdnew file mode 100644index 0000000000..0ee9b6dd99--- /dev/null+++ b/.claude/hooks/README.md@@ -0,0 +1,116 @@+# Hooks++Claude Code hooks that enable skill auto-activation, file tracking, and validation.++---++## What Are Hooks?++Hooks are scripts that run at specific points in Claude's workflow:++- **UserPromptSubmit**: When user submits a prompt+- **PreToolUse**: Before a tool executes+- **PostToolUse**: After a tool completes+- **Stop**: When user requests to stop++**Key insight:** Hooks can modify prompts, block actions, and track state - enabling features Claude can't do alone.++---++## Essential Hooks (Start Here)++### skill-activation-prompt (UserPromptSubmit)++**Purpose:** Automatically suggests relevant skills based on user prompts and file context++**How it works:**++1. Reads `skill-rules.json`+2. Matches user prompt against trigger patterns+3. Checks which files user is working with+4. Injects skill suggestions into Claude's context++**Why it's essential:** This is THE hook that makes skills auto-activate.++**Integration:**++```bash+# Copy both files+cp skill-activation-prompt.sh your-project/.claude/hooks/+cp skill-activation-prompt.ts your-project/.claude/hooks/++# Make executable+chmod +x your-project/.claude/hooks/skill-activation-prompt.sh++# Install dependencies+cd your-project/.claude/hooks+npm install+```++**Add to settings.json:**++```json+{+ "hooks": {+ "UserPromptSubmit": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/skill-activation-prompt.sh"+ }+ ]+ }+ ]+ }+}+```++**Customization:** β None needed - reads skill-rules.json automatically++---++### post-tool-use-tracker (PostToolUse)++**Purpose:** Tracks file changes to maintain context across sessions++**How it works:**++1. Monitors Edit/Write/MultiEdit tool calls+2. Records which files were modified+3. Creates cache for context management+4. Auto-detects project structure (frontend, backend, packages, etc.)++**Why it's essential:** Helps Claude understand what parts of your codebase are active.++**Integration:**++```bash+# Copy file+cp post-tool-use-tracker.sh your-project/.claude/hooks/++# Make executable+chmod +x your-project/.claude/hooks/post-tool-use-tracker.sh+```++**Add to settings.json:**++```json+{+ "hooks": {+ "PostToolUse": [+ {+ "matcher": "Edit|MultiEdit|Write",+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/post-tool-use-tracker.sh"+ }+ ]+ }+ ]+ }+}+```++**Customization:** β None needed - auto-detects structurediff --git a/.claude/hooks/error-handling-reminder.sh b/.claude/hooks/error-handling-reminder.shnew file mode 100644index 0000000000..de28a794be--- /dev/null+++ b/.claude/hooks/error-handling-reminder.sh@@ -0,0 +1,12 @@+#!/bin/bash++# Skip if environment variable is set+if [ -n "$SKIP_ERROR_REMINDER" ]; then+ exit 0+fi++# Get the directory of this script+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+cd "$SCRIPT_DIR"++cat | npx tsx error-handling-reminder.tsdiff --git a/.claude/hooks/error-handling-reminder.ts b/.claude/hooks/error-handling-reminder.tsnew file mode 100644index 0000000000..3a72461138--- /dev/null+++ b/.claude/hooks/error-handling-reminder.ts@@ -0,0 +1,256 @@+#!/usr/bin/env node+import { readFileSync, existsSync } from "fs";+import { join } from "path";++interface HookInput {+ session_id: string;+ transcript_path: string;+ cwd: string;+ permission_mode: string;+ hook_event_name: string;+}++interface EditedFile {+ path: string;+ tool: string;+ timestamp: string;+}++interface SessionTracking {+ edited_files: EditedFile[];+}++function getFileCategory(+ filePath: string,+): "backend" | "frontend" | "database" | "other" {+ // Frontend detection+ if (+ filePath.includes("/frontend/") ||+ filePath.includes("/client/") ||+ filePath.includes("/src/components/") ||+ filePath.includes("/src/features/")+ )+ return "frontend";++ // Backend detection (common service directories)+ if (+ filePath.includes("/src/controllers/") ||+ filePath.includes("/src/services/") ||+ filePath.includes("/src/routes/") ||+ filePath.includes("/src/api/") ||+ filePath.includes("/server/")+ )+ return "backend";++ // Database detection+ if (+ filePath.includes("/database/") ||+ filePath.includes("/prisma/") ||+ filePath.includes("/migrations/")+ )+ return "database";++ return "other";+}++function shouldCheckErrorHandling(filePath: string): boolean {+ // Skip test files, config files, and type definitions+ if (filePath.match(/\.(test|spec)\.(ts|tsx)$/)) return false;+ if (filePath.match(/\.(config|d)\.(ts|tsx)$/)) return false;+ if (filePath.includes("types/")) return false;+ if (filePath.includes(".styles.ts")) return false;++ // Check for code files+ return filePath.match(/\.(ts|tsx|js|jsx)$/) !== null;+}++function analyzeFileContent(filePath: string): {+ hasTryCatch: boolean;+ hasAsync: boolean;+ hasPrisma: boolean;+ hasController: boolean;+ hasApiCall: boolean;+} {+ if (!existsSync(filePath)) {+ return {+ hasTryCatch: false,+ hasAsync: false,+ hasPrisma: false,+ hasController: false,+ hasApiCall: false,+ };+ }++ const content = readFileSync(filePath, "utf-8");++ return {+ hasTryCatch: /try\s*\{/.test(content),+ hasAsync: /async\s+/.test(content),+ hasPrisma:+ /prisma\.|PrismaService|findMany|findUnique|create\(|update\(|delete\(/i.test(+ content,+ ),+ hasController:+ /export class.*Controller|router\.|app\.(get|post|put|delete|patch)/.test(+ content,+ ),+ hasApiCall: /fetch\(|axios\.|apiClient\./i.test(content),+ };+}++async function main() {+ try {+ // Read input from stdin+ const input = readFileSync(0, "utf-8");+ const data: HookInput = JSON.parse(input);++ const { session_id } = data;+ const projectDir = process.env.CLAUDE_PROJECT_DIR || process.cwd();++ // Check for edited files tracking+ const cacheDir = join(+ process.env.HOME || "/root",+ ".claude",+ "tsc-cache",+ session_id,+ );+ const trackingFile = join(cacheDir, "edited-files.log");++ if (!existsSync(trackingFile)) {+ // No files edited this session, no reminder needed+ process.exit(0);+ }++ // Read tracking data+ const trackingContent = readFileSync(trackingFile, "utf-8");+ const editedFiles = trackingContent+ .trim()+ .split("\n")+ .filter((line) => line.length > 0)+ .map((line) => {+ const [timestamp, tool, path] = line.split("\t");+ return { timestamp, tool, path };+ });++ if (editedFiles.length === 0) {+ process.exit(0);+ }++ // Categorize files+ const categories = {+ backend: [] as string[],+ frontend: [] as string[],+ database: [] as string[],+ other: [] as string[],+ };++ const analysisResults: Array<{+ path: string;+ category: string;+ analysis: ReturnType<typeof analyzeFileContent>;+ }> = [];++ for (const file of editedFiles) {+ if (!shouldCheckErrorHandling(file.path)) continue;++ const category = getFileCategory(file.path);+ categories[category].push(file.path);++ const analysis = analyzeFileContent(file.path);+ analysisResults.push({ path: file.path, category, analysis });+ }++ // Check if any code that needs error handling was written+ const needsAttention = analysisResults.some(+ ({ analysis }) =>+ analysis.hasTryCatch ||+ analysis.hasAsync ||+ analysis.hasPrisma ||+ analysis.hasController ||+ analysis.hasApiCall,+ );++ if (!needsAttention) {+ // No risky code patterns detected, skip reminder+ process.exit(0);+ }++ // Display reminder+ console.log("\nβββββββββββββββββββββββββββββββββββββββ");+ console.log("π ERROR HANDLING SELF-CHECK");+ console.log("βββββββββββββββββββββββββββββββββββββββ\n");++ // Backend reminders+ if (categories.backend.length > 0) {+ const backendFiles = analysisResults.filter(+ (f) => f.category === "backend",+ );+ const hasTryCatch = backendFiles.some((f) => f.analysis.hasTryCatch);+ const hasPrisma = backendFiles.some((f) => f.analysis.hasPrisma);+ const hasController = backendFiles.some((f) => f.analysis.hasController);++ console.log("β οΈ Backend Changes Detected");+ console.log(` ${categories.backend.length} file(s) edited\n`);++ if (hasTryCatch) {+ console.log(+ " β Did you add Sentry.captureException() in catch blocks?",+ );+ }+ if (hasPrisma) {+ console.log(" β Are Prisma operations wrapped in error handling?");+ }+ if (hasController) {+ console.log(" β Do controllers use BaseController.handleError()?");+ }++ console.log("\n π‘ Backend Best Practice:");+ console.log(" - All errors should be captured to Sentry");+ console.log(" - Use appropriate error helpers for context");+ console.log(" - Controllers should extend BaseController\n");+ }++ // Frontend reminders+ if (categories.frontend.length > 0) {+ const frontendFiles = analysisResults.filter(+ (f) => f.category === "frontend",+ );+ const hasApiCall = frontendFiles.some((f) => f.analysis.hasApiCall);+ const hasTryCatch = frontendFiles.some((f) => f.analysis.hasTryCatch);++ console.log("π‘ Frontend Changes Detected");+ console.log(` ${categories.frontend.length} file(s) edited\n`);++ if (hasApiCall) {+ console.log(" β Do API calls show user-friendly error messages?");+ }+ if (hasTryCatch) {+ console.log(" β Are errors displayed to the user?");+ }++ console.log("\n π‘ Frontend Best Practice:");+ console.log(" - Use your notification system for user feedback");+ console.log(" - Error boundaries for component errors");+ console.log(" - Display user-friendly error messages\n");+ }++ // Database reminders+ if (categories.database.length > 0) {+ console.log("ποΈ Database Changes Detected");+ console.log(` ${categories.database.length} file(s) edited\n`);+ console.log(" β Did you verify column names against schema?");+ console.log(" β Are migrations tested?\n");+ }++ console.log("βββββββββββββββββββββββββββββββββββββββ");+ console.log("π‘ TIP: Disable with SKIP_ERROR_REMINDER=1");+ console.log("βββββββββββββββββββββββββββββββββββββββ\n");++ process.exit(0);+ } catch (err) {+ // Silently fail - this is just a reminder, not critical+ process.exit(0);+ }+}++main().catch(() => process.exit(0));diff --git a/.claude/hooks/package-lock.json b/.claude/hooks/package-lock.jsonnew file mode 100644index 0000000000..b90b38532e--- /dev/null+++ b/.claude/hooks/package-lock.json@@ -0,0 +1,556 @@+{+ "name": "claude-hooks",+ "version": "1.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "claude-hooks",+ "version": "1.0.0",+ "dependencies": {+ "@types/node": "^20.11.0",+ "tsx": "^4.7.0",+ "typescript": "^5.3.3"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.11.tgz",+ "integrity": "sha512-Xt1dOL13m8u0WE8iplx9Ibbm+hFAO0GsU2P34UNoDGvZYkY8ifSiy6Zuc1lYxfG7svWE2fzqCUmFp5HCn51gJg==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.11.tgz",+ "integrity": "sha512-uoa7dU+Dt3HYsethkJ1k6Z9YdcHjTrSb5NUy66ZfZaSV8hEYGD5ZHbEMXnqLFlbBflLsl89Zke7CAdDJ4JI+Gg==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.11.tgz",+ "integrity": "sha512-9slpyFBc4FPPz48+f6jyiXOx/Y4v34TUeDDXJpZqAWQn/08lKGeD8aDp9TMn9jDz2CiEuHwfhRmGBvpnd/PWIQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.11.tgz",+ "integrity": "sha512-Sgiab4xBjPU1QoPEIqS3Xx+R2lezu0LKIEcYe6pftr56PqPygbB7+szVnzoShbx64MUupqoE0KyRlN7gezbl8g==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.11.tgz",+ "integrity": "sha512-VekY0PBCukppoQrycFxUqkCojnTQhdec0vevUL/EDOCnXd9LKWqD/bHwMPzigIJXPhC59Vd1WFIL57SKs2mg4w==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.11.tgz",+ "integrity": "sha512-+hfp3yfBalNEpTGp9loYgbknjR695HkqtY3d3/JjSRUyPg/xd6q+mQqIb5qdywnDxRZykIHs3axEqU6l1+oWEQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.11.tgz",+ "integrity": "sha512-CmKjrnayyTJF2eVuO//uSjl/K3KsMIeYeyN7FyDBjsR3lnSJHaXlVoAK8DZa7lXWChbuOk7NjAc7ygAwrnPBhA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.11.tgz",+ "integrity": "sha512-Dyq+5oscTJvMaYPvW3x3FLpi2+gSZTCE/1ffdwuM6G1ARang/mb3jvjxs0mw6n3Lsw84ocfo9CrNMqc5lTfGOw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.11.tgz",+ "integrity": "sha512-TBMv6B4kCfrGJ8cUPo7vd6NECZH/8hPpBHHlYI3qzoYFvWu2AdTvZNuU/7hsbKWqu/COU7NIK12dHAAqBLLXgw==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.11.tgz",+ "integrity": "sha512-Qr8AzcplUhGvdyUF08A1kHU3Vr2O88xxP0Tm8GcdVOUm25XYcMPp2YqSVHbLuXzYQMf9Bh/iKx7YPqECs6ffLA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.11.tgz",+ "integrity": "sha512-TmnJg8BMGPehs5JKrCLqyWTVAvielc615jbkOirATQvWWB1NMXY77oLMzsUjRLa0+ngecEmDGqt5jiDC6bfvOw==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.11.tgz",+ "integrity": "sha512-DIGXL2+gvDaXlaq8xruNXUJdT5tF+SBbJQKbWy/0J7OhU8gOHOzKmGIlfTTl6nHaCOoipxQbuJi7O++ldrxgMw==",+ "cpu": [+ "loong64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.11.tgz",+ "integrity": "sha512-Osx1nALUJu4pU43o9OyjSCXokFkFbyzjXb6VhGIJZQ5JZi8ylCQ9/LFagolPsHtgw6himDSyb5ETSfmp4rpiKQ==",+ "cpu": [+ "mips64el"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.11.tgz",+ "integrity": "sha512-nbLFgsQQEsBa8XSgSTSlrnBSrpoWh7ioFDUmwo158gIm5NNP+17IYmNWzaIzWmgCxq56vfr34xGkOcZ7jX6CPw==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.11.tgz",+ "integrity": "sha512-HfyAmqZi9uBAbgKYP1yGuI7tSREXwIb438q0nqvlpxAOs3XnZ8RsisRfmVsgV486NdjD7Mw2UrFSw51lzUk1ww==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.11.tgz",+ "integrity": "sha512-HjLqVgSSYnVXRisyfmzsH6mXqyvj0SA7pG5g+9W7ESgwA70AXYNpfKBqh1KbTxmQVaYxpzA/SvlB9oclGPbApw==",+ "cpu": [+ "s390x"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.11.tgz",+ "integrity": "sha512-HSFAT4+WYjIhrHxKBwGmOOSpphjYkcswF449j6EjsjbinTZbp8PJtjsVK1XFJStdzXdy/jaddAep2FGY+wyFAQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.11.tgz",+ "integrity": "sha512-hr9Oxj1Fa4r04dNpWr3P8QKVVsjQhqrMSUzZzf+LZcYjZNqhA3IAfPQdEh1FLVUJSiu6sgAwp3OmwBfbFgG2Xg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.11.tgz",+ "integrity": "sha512-u7tKA+qbzBydyj0vgpu+5h5AeudxOAGncb8N6C9Kh1N4n7wU1Xw1JDApsRjpShRpXRQlJLb9wY28ELpwdPcZ7A==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.11.tgz",+ "integrity": "sha512-Qq6YHhayieor3DxFOoYM1q0q1uMFYb7cSpLD2qzDSvK1NAvqFi8Xgivv0cFC6J+hWVw2teCYltyy9/m/14ryHg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.11.tgz",+ "integrity": "sha512-CN+7c++kkbrckTOz5hrehxWN7uIhFFlmS/hqziSFVWpAzpWrQoAG4chH+nN3Be+Kzv/uuo7zhX716x3Sn2Jduw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.11.tgz",+ "integrity": "sha512-rOREuNIQgaiR+9QuNkbkxubbp8MSO9rONmwP5nKncnWJ9v5jQ4JxFnLu4zDSRPf3x4u+2VN4pM4RdyIzDty/wQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.11.tgz",+ "integrity": "sha512-nq2xdYaWxyg9DcIyXkZhcYulC6pQ2FuCgem3LI92IwMgIZ69KHeY8T4Y88pcwoLIjbed8n36CyKoYRDygNSGhA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.11.tgz",+ "integrity": "sha512-3XxECOWJq1qMZ3MN8srCJ/QfoLpL+VaxD/WfNRm1O3B4+AZ/BnLVgFbUV3eiRYDMXetciH16dwPbbHqwe1uU0Q==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.11.tgz",+ "integrity": "sha512-3ukss6gb9XZ8TlRyJlgLn17ecsK4NSQTmdIXRASVsiS2sQ6zPPZklNJT5GR5tE/MUarymmy8kCEf5xPCNCqVOA==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.11.tgz",+ "integrity": "sha512-D7Hpz6A2L4hzsRpPaCYkQnGOotdUpDzSGRIv9I+1ITdHROSFUWW95ZPZWQmGka1Fg7W3zFJowyn9WGwMJ0+KPA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@types/node": {+ "version": "20.19.24",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.24.tgz",+ "integrity": "sha512-FE5u0ezmi6y9OZEzlJfg37mqqf6ZDSF2V/NLjUyGrR9uTZ7Sb9F7bLNZ03S4XVUNRWGA7Ck4c1kK+YnuWjl+DA==",+ "license": "MIT",+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "node_modules/esbuild": {+ "version": "0.25.11",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.11.tgz",+ "integrity": "sha512-KohQwyzrKTQmhXDW1PjCv3Tyspn9n5GcY2RTDqeORIdIJY8yKIF7sTSopFmn/wpMPW4rdPXI0UE5LJLuq3bx0Q==",+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.25.11",+ "@esbuild/android-arm": "0.25.11",+ "@esbuild/android-arm64": "0.25.11",+ "@esbuild/android-x64": "0.25.11",+ "@esbuild/darwin-arm64": "0.25.11",+ "@esbuild/darwin-x64": "0.25.11",+ "@esbuild/freebsd-arm64": "0.25.11",+ "@esbuild/freebsd-x64": "0.25.11",+ "@esbuild/linux-arm": "0.25.11",+ "@esbuild/linux-arm64": "0.25.11",+ "@esbuild/linux-ia32": "0.25.11",+ "@esbuild/linux-loong64": "0.25.11",+ "@esbuild/linux-mips64el": "0.25.11",+ "@esbuild/linux-ppc64": "0.25.11",+ "@esbuild/linux-riscv64": "0.25.11",+ "@esbuild/linux-s390x": "0.25.11",+ "@esbuild/linux-x64": "0.25.11",+ "@esbuild/netbsd-arm64": "0.25.11",+ "@esbuild/netbsd-x64": "0.25.11",+ "@esbuild/openbsd-arm64": "0.25.11",+ "@esbuild/openbsd-x64": "0.25.11",+ "@esbuild/openharmony-arm64": "0.25.11",+ "@esbuild/sunos-x64": "0.25.11",+ "@esbuild/win32-arm64": "0.25.11",+ "@esbuild/win32-ia32": "0.25.11",+ "@esbuild/win32-x64": "0.25.11"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/get-tsconfig": {+ "version": "4.13.0",+ "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.0.tgz",+ "integrity": "sha512-1VKTZJCwBrvbd+Wn3AOgQP/2Av+TfTCOlE4AcRJE72W1ksZXbAx8PPBR9RzgTeSPzlPMHrbANMH3LbltH73wxQ==",+ "license": "MIT",+ "dependencies": {+ "resolve-pkg-maps": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"+ }+ },+ "node_modules/resolve-pkg-maps": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",+ "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"+ }+ },+ "node_modules/tsx": {+ "version": "4.20.6",+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.20.6.tgz",+ "integrity": "sha512-ytQKuwgmrrkDTFP4LjR0ToE2nqgy886GpvRSpU0JAnrdBYppuY5rLkRUYPU1yCryb24SsKBTL/hlDQAEFVwtZg==",+ "license": "MIT",+ "dependencies": {+ "esbuild": "~0.25.0",+ "get-tsconfig": "^4.7.5"+ },+ "bin": {+ "tsx": "dist/cli.mjs"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "license": "MIT"+ }+ }+}diff --git a/.claude/hooks/package.json b/.claude/hooks/package.jsonnew file mode 100644index 0000000000..c462606b76--- /dev/null+++ b/.claude/hooks/package.json@@ -0,0 +1,16 @@+{+ "name": "claude-hooks",+ "version": "1.0.0",+ "description": "TypeScript hooks for Claude Code skill auto-activation",+ "private": true,+ "type": "module",+ "scripts": {+ "check": "tsc --noEmit",+ "test": "tsx skill-activation-prompt.ts < test-input.json"+ },+ "dependencies": {+ "@types/node": "^20.11.0",+ "tsx": "^4.7.0",+ "typescript": "^5.3.3"+ }+}diff --git a/.claude/hooks/post-tool-use-tracker.sh b/.claude/hooks/post-tool-use-tracker.shnew file mode 100755index 0000000000..8ff5c7e76e--- /dev/null+++ b/.claude/hooks/post-tool-use-tracker.sh@@ -0,0 +1,169 @@+#!/bin/bash+set -e++# Post-tool-use hook that tracks edited files and their repos+# This runs after Edit, MultiEdit, or Write tools complete successfully+++# Read tool information from stdin+tool_info=$(cat)+++# Extract relevant data+tool_name=$(echo "$tool_info" | jq -r '.tool_name // empty')+file_path=$(echo "$tool_info" | jq -r '.tool_input.file_path // empty')+session_id=$(echo "$tool_info" | jq -r '.session_id // empty')+++# Skip if not an edit tool or no file path+if [[ ! "$tool_name" =~ ^(Edit|MultiEdit|Write)$ ]] || [[ -z "$file_path" ]]; then+ exit 0 # Exit 0 for skip conditions+fi++# Skip markdown files+if [[ "$file_path" =~ \.(md|markdown)$ ]]; then+ exit 0 # Exit 0 for skip conditions+fi++# Create cache directory in project+cache_dir="$CLAUDE_PROJECT_DIR/.claude/tsc-cache/${session_id:-default}"+mkdir -p "$cache_dir"++# Function to detect repo from file path+detect_repo() {+ local file="$1"+ local project_root="$CLAUDE_PROJECT_DIR"++ # Remove project root from path+ local relative_path="${file#$project_root/}"++ # Extract first directory component+ local repo=$(echo "$relative_path" | cut -d'/' -f1)++ # Common project directory patterns+ case "$repo" in+ # Frontend variations+ frontend|client|web|app|ui)+ echo "$repo"+ ;;+ # Backend variations+ backend|server|api|src|services|worker)+ echo "$repo"+ ;;+ # Database+ database|prisma|migrations)+ echo "$repo"+ ;;+ # Package/monorepo structure+ packages)+ # For monorepos, get the package name+ local package=$(echo "$relative_path" | cut -d'/' -f2)+ if [[ -n "$package" ]]; then+ echo "packages/$package"+ else+ echo "$repo"+ fi+ ;;+ # Examples directory+ # Check if it's a source file in root+ if [[ ! "$relative_path" =~ / ]]; then+ echo "root"+ else+ echo "unknown"+ fi+ ;;+ esac+}++# Function to get build command for repo+get_build_command() {+ local repo="$1"+ local project_root="$CLAUDE_PROJECT_DIR"+ local repo_path="$project_root/$repo"++ # Check if package.json exists and has a build script+ if [[ -f "$repo_path/package.json" ]]; then+ if grep -q '"build"' "$repo_path/package.json" 2>/dev/null; then+ # Detect package manager (prefer pnpm, then npm, then yarn)+ if [[ -f "$repo_path/pnpm-lock.yaml" ]]; then+ echo "cd $repo_path && pnpm build"+ elif [[ -f "$repo_path/package-lock.json" ]]; then+ echo "cd $repo_path && npm run build"+ elif [[ -f "$repo_path/yarn.lock" ]]; then+ echo "cd $repo_path && yarn build"+ else+ echo "cd $repo_path && npm run build"+ fi+ return+ fi+ fi++ # Special case for database with Prisma+ if [[ "$repo" == "database" ]] || [[ "$repo" =~ prisma ]]; then+ if [[ -f "$repo_path/schema.prisma" ]] || [[ -f "$repo_path/prisma/schema.prisma" ]]; then+ echo "cd $repo_path && npx prisma generate"+ return+ fi+ fi++ # No build command found+ echo ""+}++# Function to get TSC command for repo+get_tsc_command() {+ local repo="$1"+ local project_root="$CLAUDE_PROJECT_DIR"+ local repo_path="$project_root/$repo"++ # Check if tsconfig.json exists+ if [[ -f "$repo_path/tsconfig.json" ]]; then+ # Check for Vite/React-specific tsconfig+ if [[ -f "$repo_path/tsconfig.app.json" ]]; then+ echo "cd $repo_path && npx tsc --project tsconfig.app.json --noEmit"+ else+ echo "cd $repo_path && npx tsc --noEmit"+ fi+ return+ fi++ # No TypeScript config found+ echo ""+}++# Detect repo+repo=$(detect_repo "$file_path")++# Skip if unknown repo+if [[ "$repo" == "unknown" ]] || [[ -z "$repo" ]]; then+ exit 0 # Exit 0 for skip conditions+fi++# Log edited file+echo "$(date +%s):$file_path:$repo" >> "$cache_dir/edited-files.log"++# Update affected repos list+if ! grep -q "^$repo$" "$cache_dir/affected-repos.txt" 2>/dev/null; then+ echo "$repo" >> "$cache_dir/affected-repos.txt"+fi++# Store build commands+build_cmd=$(get_build_command "$repo")+tsc_cmd=$(get_tsc_command "$repo")++if [[ -n "$build_cmd" ]]; then+ echo "$repo:build:$build_cmd" >> "$cache_dir/commands.txt.tmp"+fi++if [[ -n "$tsc_cmd" ]]; then+ echo "$repo:tsc:$tsc_cmd" >> "$cache_dir/commands.txt.tmp"+fi++# Remove duplicates from commands+if [[ -f "$cache_dir/commands.txt.tmp" ]]; then+ sort -u "$cache_dir/commands.txt.tmp" > "$cache_dir/commands.txt"+ rm -f "$cache_dir/commands.txt.tmp"+fi++# Exit cleanly+exit 0\ No newline at end of filediff --git a/.claude/hooks/skill-activation-prompt.sh b/.claude/hooks/skill-activation-prompt.shnew file mode 100755index 0000000000..fe594c9e60--- /dev/null+++ b/.claude/hooks/skill-activation-prompt.sh@@ -0,0 +1,5 @@+#!/bin/bash+set -e++cd "$CLAUDE_PROJECT_DIR/.claude/hooks"+cat | npx tsx skill-activation-prompt.tsdiff --git a/.claude/hooks/skill-activation-prompt.ts b/.claude/hooks/skill-activation-prompt.tsnew file mode 100644index 0000000000..3eb045555e--- /dev/null+++ b/.claude/hooks/skill-activation-prompt.ts@@ -0,0 +1,136 @@+#!/usr/bin/env node+import { readFileSync } from "fs";+import { join } from "path";++interface HookInput {+ session_id: string;+ transcript_path: string;+ cwd: string;+ permission_mode: string;+ prompt: string;+}++interface PromptTriggers {+ keywords?: string[];+ intentPatterns?: string[];+}++interface SkillRule {+ type: "guardrail" | "domain";+ enforcement: "block" | "suggest" | "warn";+ priority: "critical" | "high" | "medium" | "low";+ promptTriggers?: PromptTriggers;+}++interface SkillRules {+ version: string;+ skills: Record<string, SkillRule>;+}++interface MatchedSkill {+ name: string;+ matchType: "keyword" | "intent";+ config: SkillRule;+}++async function main() {+ try {+ // Read input from stdin+ const input = readFileSync(0, "utf-8");+ const data: HookInput = JSON.parse(input);+ const prompt = data.prompt.toLowerCase();++ // Load skill rules+ const projectDir = process.env.CLAUDE_PROJECT_DIR || "$HOME/project";+ const rulesPath = join(projectDir, ".claude", "skills", "skill-rules.json");+ const rules: SkillRules = JSON.parse(readFileSync(rulesPath, "utf-8"));++ const matchedSkills: MatchedSkill[] = [];++ // Check each skill for matches+ for (const [skillName, config] of Object.entries(rules.skills)) {+ const triggers = config.promptTriggers;+ if (!triggers) {+ continue;+ }++ // Keyword matching+ if (triggers.keywords) {+ const keywordMatch = triggers.keywords.some((kw) =>+ prompt.includes(kw.toLowerCase()),+ );+ if (keywordMatch) {+ matchedSkills.push({ name: skillName, matchType: "keyword", config });+ continue;+ }+ }++ // Intent pattern matching+ if (triggers.intentPatterns) {+ const intentMatch = triggers.intentPatterns.some((pattern) => {+ const regex = new RegExp(pattern, "i");+ return regex.test(prompt);+ });+ if (intentMatch) {+ matchedSkills.push({ name: skillName, matchType: "intent", config });+ }+ }+ }++ // Generate output if matches found+ if (matchedSkills.length > 0) {+ let output = "βββββββββββββββββββββββββββββββββββββββ\n";+ output += "π― SKILL ACTIVATION CHECK\n";+ output += "βββββββββββββββββββββββββββββββββββββββ\n\n";++ // Group by priority+ const critical = matchedSkills.filter(+ (s) => s.config.priority === "critical",+ );+ const high = matchedSkills.filter((s) => s.config.priority === "high");+ const medium = matchedSkills.filter(+ (s) => s.config.priority === "medium",+ );+ const low = matchedSkills.filter((s) => s.config.priority === "low");++ if (critical.length > 0) {+ output += "β οΈ CRITICAL SKILLS (REQUIRED):\n";+ critical.forEach((s) => (output += ` β ${s.name}\n`));+ output += "\n";+ }++ if (high.length > 0) {+ output += "π RECOMMENDED SKILLS:\n";+ high.forEach((s) => (output += ` β ${s.name}\n`));+ output += "\n";+ }++ if (medium.length > 0) {+ output += "π‘ SUGGESTED SKILLS:\n";+ medium.forEach((s) => (output += ` β ${s.name}\n`));+ output += "\n";+ }++ if (low.length > 0) {+ output += "π OPTIONAL SKILLS:\n";+ low.forEach((s) => (output += ` β ${s.name}\n`));+ output += "\n";+ }++ output += "ACTION: Use Skill tool BEFORE responding\n";+ output += "βββββββββββββββββββββββββββββββββββββββ\n";++ console.log(output);+ }++ process.exit(0);+ } catch (err) {+ console.error("Error in skill-activation-prompt hook:", err);+ process.exit(1);+ }+}++main().catch((err) => {+ console.error("Uncaught error:", err);+ process.exit(1);+});diff --git a/.claude/hooks/tsconfig.json b/.claude/hooks/tsconfig.jsonnew file mode 100644index 0000000000..b9df89f1e7--- /dev/null+++ b/.claude/hooks/tsconfig.json@@ -0,0 +1,19 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "lib": ["ES2022"],+ "outDir": "./dist",+ "rootDir": ".",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true,+ "allowSyntheticDefaultImports": true,+ "types": ["node"]+ },+ "include": ["*.ts"],+ "exclude": ["node_modules", "dist"]+}diff --git a/.claude/settings.json b/.claude/settings.jsonindex 0a0824fab7..989ad28b95 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -10,5 +10,30 @@"Bash(tail:*)"],"deny": []+ },+ "enableAllProjectMcpServers": true,+ "enabledMcpjsonServers": ["sequential-thinking"],+ "hooks": {+ "UserPromptSubmit": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/skill-activation-prompt.sh"+ }+ ]+ }+ ],+ "PostToolUse": [+ {+ "matcher": "Edit|MultiEdit|Write",+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/post-tool-use-tracker.sh"+ }+ ]+ }+ ]}}diff --git a/.claude/skills/README.md b/.claude/skills/README.mdnew file mode 100644index 0000000000..ac992ab483--- /dev/null+++ b/.claude/skills/README.md@@ -0,0 +1,304 @@+# Skills++Production-tested skills for Claude Code that auto-activate based on context.++---++## What Are Skills?++Skills are modular knowledge bases that Claude loads when needed. They provide:++- Domain-specific guidelines+- Best practices+- Code examples+- Anti-patterns to avoid++**Problem:** Skills don't activate automatically by default.++**Solution:** This showcase includes the hooks + configuration to make them activate.++---++## Available Skills++### skill-developer (Meta-Skill)++**Purpose:** Creating and managing Claude Code skills++**Files:** 7 resource files (426 lines total)++**Use when:**++- Creating new skills+- Understanding skill structure+- Working with skill-rules.json+- Debugging skill activation++**Customization:** β None - copy as-is++**[View Skill β](skill-developer/)**++---++### backend-dev-guidelines++**Purpose:** Node.js/Express/TypeScript development patterns++**Files:** 12 resource files (304 lines main + resources)++**Covers:**++- Layered architecture (Routes β Controllers β Services β Repositories)+- BaseController pattern+- Prisma database access+- Sentry error tracking+- Zod validation+- UnifiedConfig pattern+- Dependency injection+- Testing strategies++**Use when:**++- Creating/modifying API routes+- Building controllers or services+- Database operations with Prisma+- Setting up error tracking++**Customization:** β οΈ Update `pathPatterns` in skill-rules.json to match your backend directories++**Example pathPatterns:**++```json+{+ "pathPatterns": [+ "src/api/**/*.ts", // Single app with src/api+ "backend/**/*.ts", // Backend directory+ "services/*/src/**/*.ts" // Multi-service monorepo+ ]+}+```++**[View Skill β](backend-dev-guidelines/)**++---++## How to Add a Skill to Your Project++### Quick Integration++**For Claude Code:**++```+User: "Add the backend-dev-guidelines skill to my project"++Claude should:+1. Ask about project structure+2. Copy skill directory+3. Update skill-rules.json with their paths+4. Verify integration+```++See [CLAUDE_INTEGRATION_GUIDE.md](../../CLAUDE_INTEGRATION_GUIDE.md) for complete instructions.++### Manual Integration++**Step 1: Copy the skill directory**++```bash+cp -r claude-code-infrastructure-showcase/.claude/skills/backend-dev-guidelines \\+ your-project/.claude/skills/+```++**Step 2: Update skill-rules.json**++If you don't have one, create it:++```bash+cp claude-code-infrastructure-showcase/.claude/skills/skill-rules.json \\+ your-project/.claude/skills/+```++Then customize the `pathPatterns` for your project:++```json+{+ "skills": {+ "backend-dev-guidelines": {+ "fileTriggers": {+ "pathPatterns": [+ "YOUR_BACKEND_PATH/**/*.ts" // β Update this!+ ]+ }+ }+ }+}+```++**Step 3: Test**++- Edit a file in your backend directory+- The skill should activate automatically++---++## skill-rules.json Configuration++### What It Does++Defines when skills should activate based on:++- **Keywords** in user prompts ("backend", "API", "route")+- **Intent patterns** (regex matching user intent)+- **File path patterns** (editing backend files)+- **Content patterns** (code contains Prisma queries)++### Configuration Format++```json+{+ "skill-name": {+ "type": "domain" | "guardrail",+ "enforcement": "suggest" | "block",+ "priority": "high" | "medium" | "low",+ "promptTriggers": {+ "keywords": ["list", "of", "keywords"],+ "intentPatterns": ["regex patterns"]+ },+ "fileTriggers": {+ "pathPatterns": ["path/to/files/**/*.ts"],+ "contentPatterns": ["import.*Prisma"]+ }+ }+}+```++### Enforcement Levels++- **suggest**: Skill appears as suggestion, doesn't block+- **block**: Must use skill before proceeding (guardrail)++**Use "block" for:**++- Preventing breaking changes (MUI v6βv7)+- Critical database operations+- Security-sensitive code++**Use "suggest" for:**++- General best practices+- Domain guidance+- Code organization++---++## Creating Your Own Skills++See the **skill-developer** skill for complete guide on:++- Skill YAML frontmatter structure+- Resource file organization+- Trigger pattern design+- Testing skill activation++**Quick template:**++```markdown+---+name: my-skill+description: What this skill does+---++# My Skill Title++## Purpose++[Why this skill exists]++## When to Use This Skill++[Auto-activation scenarios]++## Quick Reference++[Key patterns and examples]++## Resource Files++- [topic-1.md](resources/topic-1.md)+- [topic-2.md](resources/topic-2.md)+```++---++## Troubleshooting++### Skill isn't activating++**Check:**++1. Is skill directory in `.claude/skills/`?+2. Is skill listed in `skill-rules.json`?+3. Do `pathPatterns` match your files?+4. Are hooks installed and working?+5. Is settings.json configured correctly?++**Debug:**++```bash+# Check skill exists+ls -la .claude/skills/++# Validate skill-rules.json+cat .claude/skills/skill-rules.json | jq .++# Check hooks are executable+ls -la .claude/hooks/*.sh++# Test hook manually+./.claude/hooks/skill-activation-prompt.sh+```++### Skill activates too often++Update skill-rules.json:++- Make keywords more specific+- Narrow `pathPatterns`+- Increase specificity of `intentPatterns`++### Skill never activates++Update skill-rules.json:++- Add more keywords+- Broaden `pathPatterns`+- Add more `intentPatterns`++---++## For Claude Code++**When integrating a skill for a user:**++1. **Read [CLAUDE_INTEGRATION_GUIDE.md](../../CLAUDE_INTEGRATION_GUIDE.md)** first+2. Ask about their project structure+3. Customize `pathPatterns` in skill-rules.json+4. Verify the skill file has no hardcoded paths+5. Test activation after integration++**Common mistakes:**++- Keeping example paths (blog-api/, frontend/)+- Not asking about monorepo vs single-app+- Copying skill-rules.json without customization++---++## Next Steps++1. **Start simple:** Add one skill that matches your work+2. **Verify activation:** Edit a relevant file, skill should suggest+3. **Add more:** Once first skill works, add others+4. **Customize:** Adjust triggers based on your workflow++**Questions?** See [CLAUDE_INTEGRATION_GUIDE.md](../../CLAUDE_INTEGRATION_GUIDE.md) for comprehensive integration instructions.diff --git a/.claude/skills/backend-dev-guidelines/SKILL.md b/.claude/skills/backend-dev-guidelines/SKILL.mdnew file mode 100644index 0000000000..0d8037fb68--- /dev/null+++ b/.claude/skills/backend-dev-guidelines/SKILL.md@@ -0,0 +1,507 @@+---+name: backend-dev-guidelines+description: Comprehensive backend development guide for Langfuse's Next.js 14/tRPC/Express/TypeScript monorepo. Use when creating tRPC routers, public API endpoints, BullMQ queue processors, services, or working with tRPC procedures, Next.js API routes, Prisma database access, ClickHouse analytics queries, Redis queues, OpenTelemetry instrumentation, Zod v4 validation, env.mjs configuration, or async patterns. Covers layered architecture (tRPC procedures β services, queue processors β services), traceException error handling, observability patterns, and testing strategies.+---++# Backend Development Guidelines++## Purpose++Establish consistency and best practices across Langfuse's backend packages (web, worker, packages/shared) using Next.js 14, tRPC, BullMQ, and TypeScript patterns.++## When to Use This Skill++Automatically activates when working on:++- Creating or modifying tRPC routers and procedures+- Creating or modifying public API endpoints (REST)+- Creating or modifying BullMQ queue consumers and producers+- Building services with business logic+- Authenticating API requests+- Accessing resources based on entitlements+- Implementing middleware (tRPC, NextAuth, public API)+- Database operations with Prisma (PostgreSQL) or ClickHouse+- Error tracking with traceException and OpenTelemetry instrumentation+- Input validation with Zod v4+- Environment configuration from env variables+- Backend testing and refactoring++---++## Quick Start++### UI: New tRPC Feature Checklist (Web)++- [ ] **Router**: Define in `features/[feature]/server/*Router.ts`+- [ ] **Procedures**: Use appropriate procedure type (protected, public)+- [ ] **Authentication**: Use JWT authorization via middlewares.+- [ ] **Entitlement check**: Access resources based on resource and role+- [ ] **Validation**: Zod v4 schema for input+- [ ] **Service**: Business logic in service file+- [ ] **Error handling**: Use traceException wrapper+- [ ] **Tests**: Unit + integration tests in `__tests__/`+- [ ] **Config**: Access via env.mjs++### SDKs: New Public API Endpoint Checklist (Web)++- [ ] **Route file**: Create in `pages/api/public/`+- [ ] **Wrapper**: Use `withMiddlewares` + `createAuthedProjectAPIRoute`+- [ ] **Types**: Define in `features/public-api/types/`+- [ ] **Authentication**: Authorization via basic auth+- [ ] **Validation**: Zod schemas for query/body/response+- [ ] **Versioning**: Versioning in API path and Zod schemas for query/body/response+- [ ] **Tests**: Add end-to-end test in `__tests__/async/`++### New Queue Processor Checklist (Worker)++- [ ] **Processor**: Create in `worker/src/queues/`+- [ ] **Queue types**: Create queue types in `packages/shared/src/server/queues`+- [ ] **Service**: Business logic in `features/` or `worker/src/features/`+- [ ] **Error handling**: Distinguish between errors which should fail queue processing and errors which should result in a succeeded event.+- [ ] **Queue registration**: Add to WorkerManager in app.ts+- [ ] **Tests**: Add vitest tests in worker++---++## Architecture Overview++### Layered Architecture++```+# Web Package (Next.js 14)++ββ tRPC API βββββββββββββββββββ βββ Public REST API βββββββββββ+β β β β+β HTTP Request β β HTTP Request β+β β β β β β+β tRPC Procedure β β withMiddlewares + β+β (protectedProjectProcedure)β β createAuthedProjectAPIRouteβ+β β β β β β+β Service (business logic) β β Service (business logic) β+β β β β β β+β Prisma / ClickHouse β β Prisma / ClickHouse β+β β β β+βββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββ+ β+ [optional]: Publish to Redis BullMQ queue+ β+ββ Worker Package (Express) βββββββββββββββββββββββββββββββββββ+β β+β BullMQ Queue Job β+β β β+β Queue Processor (handles job) β+β β β+β Service (business logic) β+β β β+β Prisma / ClickHouse β+β β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++**Key Principles:**++- **Web**: tRPC procedures for UI OR public API routes for SDKs β Services β Database+- **Worker**: Queue processors β Services β Database+- **packages/shared**: Shared code for Web and Worker++See [architecture-overview.md](architecture-overview.md) for complete details.++---++## Directory Structure++### Web Package (`/web/`)++```+web/src/+βββ features/ # Feature-organized code+β βββ [feature-name]/+β β βββ server/ # Backend logic+β β β βββ *Router.ts # tRPC router+β β β βββ service.ts # Business logic+β β βββ components/ # React components+β β βββ types/ # Feature types+βββ server/+β βββ api/+β β βββ routers/ # tRPC routers+β β βββ trpc.ts # tRPC setup & middleware+β β βββ root.ts # Main router+β βββ auth.ts # NextAuth.js config+β βββ db.ts # Database client+βββ pages/+β βββ api/+β β βββ public/ # Public REST APIs+β β βββ trpc/ # tRPC endpoint+β βββ [routes].tsx # Next.js pages+βββ __tests__/ # Jest tests+β βββ async/ # Integration tests+βββ instrumentation.ts # OpenTelemetry (FIRST IMPORT)+βββ env.mjs # Environment config+```++### Worker Package (`/worker/`)++```+worker/src/+βββ queues/ # BullMQ processors+β βββ evalQueue.ts+β βββ ingestionQueue.ts+β βββ workerManager.ts+βββ features/ # Business logic+β βββ [feature]/+β βββ service.ts+βββ instrumentation.ts # OpenTelemetry (FIRST IMPORT)+βββ app.ts # Express setup + queue registration+βββ env.ts # Environment config+βββ index.ts # Server start+```++### Shared Package (`/packages/shared/`)++```+shared/src/+βββ server/ # Server utilities+β βββ auth/ # Authentication helpers+β βββ clickhouse/ # ClickHouse client & schema+β βββ instrumentation/ # OpenTelemetry helpers+β βββ llm/ # LLM integration utilities+β βββ redis/ # Redis queues & cache+β βββ repositories/ # Data repositories+β βββ services/ # Shared services+β βββ utils/ # Server utilities+β βββ logger.ts+β βββ queues.ts+βββ encryption/ # Encryption utilities+βββ features/ # Feature-specific code+βββ tableDefinitions/ # Table schemas+βββ utils/ # Shared utilities+βββ constants.ts+βββ db.ts # Prisma client+βββ env.ts # Environment config+βββ index.ts # Main exports+```++**Import Paths (package.json exports):**++The shared package exposes specific import paths for different use cases:++| Import Path | Maps To | Use For |+| ------------------------------------------ | --------------------------------- | --------------------------------------------------------------- |+| `@langfuse/shared` | `dist/src/index.js` | General types, schemas, utilities, constants |+| `@langfuse/shared/src/db` | `dist/src/db.js` | Prisma client and database types |+| `@langfuse/shared/src/server` | `dist/src/server/index.js` | Server-side utilities (queues, auth, services, instrumentation) |+| `@langfuse/shared/src/server/auth/apiKeys` | `dist/src/server/auth/apiKeys.js` | API key management utilities |+| `@langfuse/shared/encryption` | `dist/src/encryption/index.js` | Encryption and signature utilities |++**Usage Examples:**++```typescript+// General imports - types, schemas, constants, interfaces+import {+ CloudConfigSchema,+ StringNoHTML,+ AnnotationQueueObjectType,+ type APIScoreV2,+ type ColumnDefinition,+ Role,+} from "@langfuse/shared";++// Database - Prisma client and types+import { prisma, Prisma, JobExecutionStatus } from "@langfuse/shared/src/db";+import { type DB as Database } from "@langfuse/shared";++// Server utilities - queues, services, auth, instrumentation+import {+ logger,+ instrumentAsync,+ traceException,+ redis,+ getTracesTable,+ StorageService,+ sendMembershipInvitationEmail,+ invalidateApiKeysForProject,+ recordIncrement,+ recordHistogram,+} from "@langfuse/shared/src/server";++// API key management (specific path)+import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";++// Encryption utilities+import { encrypt, decrypt, sign, verify } from "@langfuse/shared/encryption";+```++**What Goes Where:**++The shared package provides types, utilities, and server code used by both web and worker packages. It has **5 export paths** that control frontend vs backend access:++| Import Path | Usage | What's Included |+| ------------------------------------------ | --------------------- | ---------------------------------------------------------------------------------- |+| `@langfuse/shared` | β Frontend + Backend | Prisma types, Zod schemas, constants, table definitions, domain models, utilities |+| `@langfuse/shared/src/db` | π Backend only | Prisma client instance |+| `@langfuse/shared/src/server` | π Backend only | Services, repositories, queues, auth, ClickHouse, LLM integration, instrumentation |+| `@langfuse/shared/src/server/auth/apiKeys` | π Backend only | API key management (separated to avoid circular deps) |+| `@langfuse/shared/encryption` | π Backend only | Database field encryption/decryption |++**Naming Conventions:**++- tRPC Routers: `camelCaseRouter.ts` - `datasetRouter.ts`+- Services: `service.ts` in feature directory+- Queue Processors: `camelCaseQueue.ts` - `evalQueue.ts`+- Public APIs: `kebab-case.ts` - `dataset-items.ts`++---++## Core Principles++### 1. tRPC Procedures Delegate to Services++```typescript+// β NEVER: Business logic in procedures+export const traceRouter = createTRPCRouter({+ byId: protectedProjectProcedure+ .input(z.object({ traceId: z.string() }))+ .query(async ({ input, ctx }) => {+ // 200 lines of logic here+ }),+});++// β ALWAYS: Delegate to service+export const traceRouter = createTRPCRouter({+ byId: protectedProjectProcedure+ .input(z.object({ traceId: z.string() }))+ .query(async ({ input, ctx }) => {+ return await getTraceById(input.traceId);+ }),+});+```++### 2. Access Config via env.mjs, NEVER process.env++```typescript+// β NEVER (except in env.mjs itself)+const dbUrl = process.env.DATABASE_URL;++// β ALWAYS+import { env } from "@/src/env.mjs";+const dbUrl = env.DATABASE_URL;+```++### 3. Validate ALL Input with Zod v4++```typescript+import { z } from "zod/v4";++const schema = z.object({+ email: z.string().email(),+ projectId: z.string(),+});+const validated = schema.parse(input);+```++### 4. Direct Prisma Usage from @langfuse/shared from within services++```typescript+// Services use Prisma directly+import { prisma } from "@langfuse/shared/src/db";++const dataset = await prisma.dataset.findUnique({+ where: { id: datasetId },+});+```++### 6. Instrument Critical Operations (all API routes are auto-instrumented by a wrapper span)++```typescript+import { instrumentAsync } from "@langfuse/shared/src/server";++const result = await instrumentAsync(+ { name: "dataset.create" },+ async (span) => {+ // Operation here+ return dataset;+ },+);+```++### 7. Comprehensive Testing Required++Write tests for all new features and bug fixes. See [testing-guide.md](resources/testing-guide.md) for detailed examples.++**Test Types:**++| Type | Framework | Location | Purpose |+| ----------- | --------- | --------------------------------------- | ---------------------------- |+| Integration | Jest | `web/src/__tests__/async/` | Full API endpoint testing |+| tRPC | Jest | `web/src/__tests__/async/` | tRPC procedures with auth |+| Service | Jest | `web/src/__tests__/async/repositories/` | Repository/service functions |+| Worker | Vitest | `worker/src/__tests__/` | Queue processors & streams |++**Quick Examples:**++```typescript+// Integration Test (Public API)+const res = await makeZodVerifiedAPICall(+ PostDatasetsV1Response, "POST", "/api/public/datasets",+ { name: "test-dataset" }, auth+);+expect(res.status).toBe(200);++// tRPC Test+const { caller } = await prepare(); // Creates session + caller+const response = await caller.automations.getAutomations({ projectId });+expect(response).toHaveLength(1);++// Service Test+const result = await getObservationsWithModelDataFromEventsTable({+ projectId, filter: [...], limit: 1000, offset: 0+});+expect(result.length).toBeGreaterThan(0);++// Worker Test (vitest)+const stream = await getObservationStream({ projectId, filter: [] });+const rows = [];+for await (const chunk of stream) rows.push(chunk);+expect(rows).toHaveLength(2);+```++**Key Principles:**++- Use unique IDs (`randomUUID()`) to avoid test interference+- Clean up test data or use unique project IDs+- Tests must be independent and runnable in any order+- Never use `pruneDatabase` in tests++---++## Common Imports++```typescript+// tRPC (Web)+import { z } from "zod/v4";+import {+ createTRPCRouter,+ protectedProjectProcedure,+} from "@/src/server/api/trpc";+import { TRPCError } from "@trpc/server";++// Database+import { prisma } from "@langfuse/shared/src/db";+import type { Prisma } from "@prisma/client";++// ClickHouse+import { getTracesTable } from "@langfuse/shared/src/server";++// Error tracking & instrumentation+import {+ traceException,+ instrumentAsync,+ logger,+} from "@langfuse/shared/src/server";++// Config+import { env } from "@/src/env.mjs"; // web+// or+import { env } from "./env"; // worker++// Public API (Web)+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";++// Queue Processing (Worker)+import { Job } from "bullmq";+import { QueueName, TQueueJobTypes } from "@langfuse/shared/src/server";+```++---++## Quick Reference++### HTTP Status Codes++| Code | Use Case |+| ---- | ------------ |+| 200 | Success |+| 201 | Created |+| 400 | Bad Request |+| 401 | Unauthorized |+| 403 | Forbidden |+| 404 | Not Found |+| 500 | Server Error |++### Service Templates++**Blog API** (β Mature) - Use as template for REST APIs+**Auth Service** (β Mature) - Use as template for authentication patterns++---++## Anti-Patterns to Avoid++β Business logic in routes+β Direct process.env usage+β Missing error handling+β No input validation+β Direct Prisma everywhere+β console.log instead of Sentry++---++## Navigation Guide++| Need to... | Read this |+| ------------------------- | ------------------------------------------------------------ |+| Understand architecture | [architecture-overview.md](architecture-overview.md) |+| Create routes/controllers | [routing-and-controllers.md](routing-and-controllers.md) |+| Organize business logic | [services-and-repositories.md](services-and-repositories.md) |+| Create middleware | [middleware-guide.md](middleware-guide.md) |+| Database access | [database-patterns.md](database-patterns.md) |+| Manage config | [configuration.md](configuration.md) |+| Write tests | [testing-guide.md](testing-guide.md) |+| See examples | [complete-examples.md](complete-examples.md) |++---++## Resource Files++### [architecture-overview.md](architecture-overview.md)++Layered architecture, request lifecycle, separation of concerns++### [routing-and-controllers.md](routing-and-controllers.md)++Route definitions, BaseController, error handling, examples++### [services-and-repositories.md](services-and-repositories.md)++Service patterns, DI, repository pattern, caching++### [middleware-guide.md](middleware-guide.md)++Auth, audit, error boundaries, AsyncLocalStorage++### [database-patterns.md](database-patterns.md)++PrismaService, repositories, transactions, optimization++### [configuration.md](configuration.md)++UnifiedConfig, environment configs, secrets++### [testing-guide.md](testing-guide.md)++Unit/integration tests, mocking, coverage++---++## Related Skills++- **database-verification** - Verify column names and schema consistency+- **error-tracking** - Sentry integration patterns+- **skill-developer** - Meta-skill for creating and managing skills++---++**Skill Status**: COMPLETE β+**Line Count**: < 500 β+**Progressive Disclosure**: 11 resource files βdiff --git a/.claude/skills/backend-dev-guidelines/resources/architecture-overview.md b/.claude/skills/backend-dev-guidelines/resources/architecture-overview.mdnew file mode 100644index 0000000000..7c78db5d6b--- /dev/null+++ b/.claude/skills/backend-dev-guidelines/resources/architecture-overview.md@@ -0,0 +1,845 @@+# Architecture Overview - Langfuse Backend++Complete guide to the layered architecture pattern used in Langfuse's Next.js 14/tRPC/Express monorepo.++## Table of Contents++- [Layered Architecture Pattern](#layered-architecture-pattern)+- [Request Lifecycle](#request-lifecycle)+- [Directory Structure](#directory-structure)+- [Module Organization](#module-organization)+- [Separation of Concerns](#separation-of-concerns)+- [Database Architecture](#database-architecture)++---++## Layered Architecture Pattern++Langfuse uses a **three-layer architecture** with two primary entry points (tRPC and Public API) plus async processing via Worker.++### The Three Layers++```+# Web Package (Next.js 14)++ββ tRPC API βββββββββββββββββββ βββ Public REST API βββββββββββ+β β β β+β HTTP Request β β HTTP Request β+β β β β β β+β tRPC Procedure β β withMiddlewares + β+β (protectedProjectProcedure)β β createAuthedProjectAPIRouteβ+β β β β β β+β Service (business logic) β β Service (business logic) β+β β β β β β+β Prisma / ClickHouse β β Prisma / ClickHouse β+β β β β+βββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββ+ β+ [optional]: Publish to Redis BullMQ queue+ β+ββ Worker Package (Express) βββββββββββββββββββββββββββββββββββ+β β+β BullMQ Queue Job β+β β β+β Queue Processor (handles job) β+β β β+β Service (business logic) β+β β β+β Prisma / ClickHouse β+β β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++### Layer Breakdown++**Layer 1: API Entry Points**++Two types of entry points:++- **tRPC Procedures** - Type-safe RPC for UI+ - Located in `features/[feature]/server/*Router.ts`+ - Uses middleware for auth/validation+ - Types shared between client/server++- **Public REST APIs** - REST endpoints for SDKs+ - Located in `pages/api/public/`+ - Uses `withMiddlewares` + `createAuthedProjectAPIRoute`+ - Versioned with Zod schemas++**Layer 2: Services**++- Business logic and orchestration+- Shared between tRPC, Public API, and Worker+- Located in `features/[feature]/server/service.ts`+- No HTTP/Request/Response knowledge+- Use repositories for complex queries or Prisma directly for simple CRUD++**Layer 3: Data Access**++- **Repositories** for complex data access patterns (traces, observations, scores, events)+- **Direct Prisma** for simple CRUD operations in services+- PostgreSQL for transactional data+- ClickHouse for analytics/traces (accessed via repositories)+- Redis for caching/queues++**Async Processing Layer: Worker**++- BullMQ queue processors+- Same service layer as Web+- Handles long-running operations++### Why This Architecture?++**Testability:**++- tRPC procedures easily testable with type-safe callers+- Services tested independently with mocked DB+- Queue processors tested with vitest+- Clear test boundaries++**Maintainability:**++- Business logic isolated in services+- tRPC provides type safety end-to-end+- Changes to API don't affect service layer+- Easy to locate and fix bugs++**Reusability:**++- Services used by tRPC, Public API, Worker, and scripts+- Business logic not tied to HTTP or tRPC+- Consistent patterns across packages++**Scalability:**++- Worker handles async operations separately+- Easy to add new tRPC procedures+- Clear patterns to follow+- Shared code in packages/shared++---++## Request Lifecycle++### tRPC Request Flow (UI)++```typescript+1. HTTP POST /api/trpc/datasets.create+ β+2. Next.js API route catches request (pages/api/trpc/[trpc].ts)+ β+3. tRPC router resolves procedure:+ - Match route to procedure in datasetRouter.ts+ β+4. tRPC middleware chain executes:+ - protectedProjectProcedure (authentication)+ - hasEntitlement checks+ - Input validation with Zod v4+ β+5. Procedure handler calls service:+ export const datasetRouter = createTRPCRouter({+ create: protectedProjectProcedure+ .input(createDatasetSchema)+ .mutation(async ({ input, ctx }) => {+ return await createDataset(input, ctx.session);+ }),+ })+ β+6. Service executes business logic:+ - Validate business rules+ - Use repositories for complex queries or Prisma directly+ - ClickHouse queries via repositories if needed+ β+7. Database operations:+ - prisma.dataset.create({ data })+ - clickhouse queries via getTracesTable()+ β+8. Response flows back:+ Database β Service β Procedure β tRPC β Client+```++### Public API Request Flow (SDKs)++```typescript+1. HTTP POST /api/public/datasets+ β+2. Next.js API route handler (pages/api/public/datasets.ts)+ β+3. withMiddlewares wrapper executes:+ - Basic auth verification+ - Rate limiting+ - CORS handling+ β+4. createAuthedProjectAPIRoute handler:+ - Parse and validate request with Zod v4+ - Extract auth context (project, user)+ β+5. Handler calls service function:+ const dataset = await createDataset({+ name: req.body.name,+ projectId: req.auth.projectId,+ });+ β+6. Service executes (same as tRPC path)+ β+7. Response formatted and returned:+ res.status(201).json(dataset);+```++### Worker/Queue Processing Flow++```typescript+1. Job added to Redis BullMQ queue:+ await evalQueue.add("eval-job", {+ evalId, projectId+ });+ β+2. Worker picks up job from Redis+ β+3. Queue processor handles job:+ // worker/src/queues/evalQueue.ts+ async process(job: Job<EvalJobType>) {+ await processEvaluation(job.data);+ }+ β+4. Processor calls service:+ - Same service layer as Web+ - Business logic execution+ β+5. Service performs operations:+ - Prisma transactions+ - ClickHouse queries+ - External API calls (LLMs)+ β+6. Job completes or fails:+ - Success: job.updateProgress(100)+ - Failure: throw error for retry+```++---++## Directory Structure++### Web Package (`/web/src/`)++```+web/src/+βββ features/ # Feature-organized code+β βββ datasets/+β β βββ server/ # Backend logic+β β β βββ datasetRouter.ts # tRPC router+β β β βββ datasetService.ts # Business logic+β β βββ components/ # React components+β β βββ types/ # Feature types+β β+β βββ public-api/+β β βββ server/+β β β βββ withMiddlewares.ts+β β β βββ createAuthedProjectAPIRoute.ts+β β βββ types/ # API schemas+β β+β βββ [feature-name]/+β βββ server/+β β βββ *Router.ts # tRPC router+β β βββ service.ts # Business logic+β βββ components/+β βββ types/+β+βββ server/+β βββ api/+β β βββ routers/ # tRPC routers+β β βββ trpc.ts # tRPC setup & middleware+β β βββ root.ts # Main router combining all+β βββ auth.ts # NextAuth.js config+β βββ db.ts # Database utilities+β+βββ pages/+β βββ api/+β β βββ public/ # Public REST APIs+β β β βββ datasets.ts+β β β βββ traces.ts+β β βββ trpc/+β β βββ [trpc].ts # tRPC endpoint+β βββ [routes].tsx # Next.js pages+β+βββ __tests__/ # Jest tests+β βββ async/ # Integration tests+β βββ sync/ # Unit tests+β+βββ instrumentation.ts # OpenTelemetry (FIRST IMPORT)+βββ env.mjs # Environment config+```++### Worker Package (`/worker/src/`)++```+worker/src/+βββ queues/ # BullMQ processors+β βββ evalQueue.ts # Evaluation jobs+β βββ ingestionQueue.ts # Data ingestion+β βββ batchExportQueue.ts # Batch exports+β βββ workerManager.ts # Queue registration+β+βββ features/ # Business logic+β βββ [feature]/+β βββ service.ts+β+βββ __tests__/ # Vitest tests+β+βββ instrumentation.ts # OpenTelemetry (FIRST IMPORT)+βββ app.ts # Express setup + queue registration+βββ env.ts # Environment config+βββ index.ts # Server start+```++### Shared Package (`/packages/shared/`)++The shared package provides types, utilities, and server code used by both web and worker packages. It has **5 export paths** that control frontend vs backend access:++| Import Path | Usage | What's Included |+| ------------------------------------------ | --------------------- | ---------------------------------------------------------------------------------- |+| `@langfuse/shared` | β Frontend + Backend | Prisma types, Zod schemas, constants, table definitions, domain models, utilities |+| `@langfuse/shared/src/db` | π Backend only | Prisma client instance |+| `@langfuse/shared/src/server` | π Backend only | Services, repositories, queues, auth, ClickHouse, LLM integration, instrumentation |+| `@langfuse/shared/src/server/auth/apiKeys` | π Backend only | API key management (separated to avoid circular deps) |+| `@langfuse/shared/encryption` | π Backend only | Database field encryption/decryption |++**Key Structure:**++```+packages/shared/src/+βββ server/ # π All server-only code+β βββ auth/ # Authentication & authorization+β βββ clickhouse/ # ClickHouse client & queries+β βββ redis/ # Redis client & 30+ queue types+β βββ repositories/ # Data access (traces, observations, scores, events)+β βββ services/ # Business services (Storage, Email, Slack, etc.)+β βββ llm/ # LLM integration+β βββ instrumentation/ # OpenTelemetry+β βββ queues.ts, logger.ts, filterToPrisma.ts, etc.+β+βββ features/ # β Feature types (evals, scores, prompts, datasets)+βββ domain/ # β Domain models (automations, webhooks, etc.)+βββ tableDefinitions/ # β Table schemas+βββ interfaces/ # β Shared interfaces (filters, orderBy)+βββ utils/ # β Utilities (JSON, Zod, string checks)+βββ encryption/ # π Encryption utilities+βββ db.ts, constants.ts, types.ts, etc.+```++**Common Import Patterns:**++```typescript+// β Main export - Safe for frontend + backend+import {+ Prisma,+ Role,+ type Dataset,+ CloudConfigSchema,+} from "@langfuse/shared";++// π Database - Backend only+import { prisma } from "@langfuse/shared/src/db";++// π Server utilities - Backend only+import {+ logger,+ instrumentAsync,+ traceException,+ redis,+ clickhouseClient,+ StorageService,+ fetchLLMCompletion,+ filterToPrisma,+} from "@langfuse/shared/src/server";++// π API keys - Backend only+import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";++// π Encryption - Backend only+import { encrypt, decrypt } from "@langfuse/shared/encryption";+```++---++## Module Organization++### Feature-Based Organization (Recommended)++For most features, organize by domain within `features/`:++```+src/features/datasets/+βββ server/ # Backend code+β βββ datasetRouter.ts # tRPC procedures+β βββ service.ts # Business logic+βββ components/ # React components+β βββ DatasetTable.tsx+β βββ DatasetForm.tsx+βββ types/ # Feature types+β βββ index.ts+βββ utils/ # Feature utilities+```++**When to use:**++- Any feature with UI + API+- Clear domain boundary+- Multiple related procedures++### Subdomain Organization++For complex features with multiple subdomains:++```+src/features/evaluations/+βββ server/+β βββ evalRouter.ts # Main router+β βββ evalService.ts # Core service+β βββ templates/ # Template subdomain+β β βββ templateRouter.ts+β β βββ templateService.ts+β βββ configs/ # Config subdomain+β βββ configRouter.ts+β βββ configService.ts+βββ components/+β βββ templates/+β βββ configs/+βββ types/+```++**When to use:**++- Feature has 10+ files+- Clear subdomains exist+- Logical grouping improves clarity++### Flat Organization (Rare)++For small, standalone features:++```+src/server/api/routers/+βββ healthRouter.ts # Simple health check+βββ versionRouter.ts # Version info+```++**When to use:**++- Simple features (1-2 procedures)+- No UI components+- Standalone utilities++---++## Separation of Concerns++### What Goes Where++**tRPC Procedures (Entry Layer):**++- β Procedure definitions (query/mutation)+- β Middleware application (auth, validation)+- β Input schemas (Zod v4)+- β Service delegation+- β Error transformation (TRPCError)+- β Business logic (belongs in services)+- β Database operations (belongs in services)+- β Complex validation (belongs in services)++**Public API Routes (Entry Layer):**++- β Route registration+- β Middleware wrapper application+- β Input validation (Zod v4)+- β Service delegation+- β Response formatting+- β HTTP status codes+- β Business logic (belongs in services)+- β Database operations (belongs in services)++**Services Layer:**++- β Business logic+- β Business rules enforcement+- β Transaction orchestration+- β Repository calls for complex queries+- β Direct Prisma operations for simple CRUD+- β ClickHouse queries (via repositories)+- β Redis cache access+- β External API calls (LLMs, etc.)+- β HTTP concerns (Request/Response)+- β tRPC-specific types (TRPCError in entry layer)+- β NextAuth session handling (passed as parameter)++**Queue Processors (Worker):**++- β Job registration and configuration+- β Job data extraction+- β Service delegation+- β Progress updates+- β Error handling (retry logic)+- β Business logic (belongs in services)+- β Database operations (belongs in services)++### Example: Dataset Creation++**tRPC Procedure (Entry Point):**++```typescript+// web/src/features/datasets/server/datasetRouter.ts+import { z } from "zod/v4";+import {+ createTRPCRouter,+ protectedProjectProcedure,+} from "@/src/server/api/trpc";+import { TRPCError } from "@trpc/server";+import { createDataset } from "./service";++export const datasetRouter = createTRPCRouter({+ create: protectedProjectProcedure+ .input(+ z.object({+ name: z.string(),+ description: z.string().optional(),+ projectId: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ try {+ return await createDataset({+ ...input,+ userId: ctx.session.user.id,+ });+ } catch (error) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Failed to create dataset",+ cause: error,+ });+ }+ }),+});+```++**Service (Business Logic):**++```typescript+// web/src/features/datasets/server/service.ts+import { prisma } from "@langfuse/shared/src/db";+import { instrumentAsync, traceException } from "@langfuse/shared/src/server";++export async function createDataset(data: {+ name: string;+ description?: string;+ projectId: string;+ userId: string;+}) {+ return await instrumentAsync({ name: "dataset.create" }, async (span) => {+ // Business rule: Check for duplicate names in project+ const existing = await prisma.dataset.findFirst({+ where: {+ name: data.name,+ projectId: data.projectId,+ },+ });++ if (existing) {+ throw new Error(`Dataset with name "${data.name}" already exists`);+ }++ // Create dataset+ const dataset = await prisma.dataset.create({+ data: {+ name: data.name,+ description: data.description,+ projectId: data.projectId,+ createdById: data.userId,+ },+ });++ span.setAttributes({+ datasetId: dataset.id,+ projectId: dataset.projectId,+ });++ return dataset;+ });+}+```++**Public API (Alternative Entry Point):**++```typescript+// web/src/pages/api/public/datasets.ts+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";+import { createDataset } from "@/src/features/datasets/server/service";+import { z } from "zod/v4";++const createDatasetSchema = z.object({+ name: z.string(),+ description: z.string().optional(),+});++export default withMiddlewares({+ POST: createAuthedProjectAPIRoute({+ name: "Create Dataset",+ bodySchema: createDatasetSchema,+ fn: async ({ body, auth, res }) => {+ const dataset = await createDataset({+ name: body.name,+ description: body.description,+ projectId: auth.scope.projectId,+ userId: auth.scope.userId,+ });++ return res.status(201).json(dataset);+ },+ }),+});+```++**Queue Processor (Async Processing):**++```typescript+// worker/src/queues/datasetExportQueue.ts+import { Job } from "bullmq";+import { exportDataset } from "../features/datasets/exportService";++export async function processDatasetExport(+ job: Job<{ datasetId: string; projectId: string; format: string }>,+) {+ const { datasetId, projectId, format } = job.data;++ await job.updateProgress(10);++ // Delegate to service+ const exportUrl = await exportDataset({+ datasetId,+ projectId,+ format,+ onProgress: (percent) => job.updateProgress(percent),+ });++ await job.updateProgress(100);++ return { exportUrl };+}+```++**Notice:** Each layer has clear, distinct responsibilities!++- **Entry layers** (tRPC/Public API/Queue) handle protocol concerns+- **Service layer** contains all business logic+- **Data layer** accessed via repositories (complex queries) or Prisma directly (simple CRUD)++---++## Database Architecture++### Dual Database System++Langfuse uses two databases with different purposes:++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β Application β+β β+β ββββββββββββββββ ββββββββββββββββ β+β β PostgreSQL β β ClickHouse β β+β β β β β β+β β Transactionalβ β Analytics β β+β β Data β β Data β β+β ββββββββββββββββ ββββββββββββββββ β+β β β β+β β β β+β Prisma ORM Direct SQL β+β (schema migrations) (via client) β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++**PostgreSQL (Primary Database):**++- Accessed via Prisma ORM+- Transactional data (users, projects, datasets, etc.)+- ACID guarantees+- Schema managed via `prisma migrate`+- Located in `packages/shared/prisma/`++**ClickHouse (Analytics Database):**++- Accessed via direct SQL queries+- High-volume trace/observation data+- Columnar storage for analytics+- Optimized for aggregations+- Schema in `packages/shared/src/server/clickhouse/`+- Schema managed via `golang-migrate`++**Redis (Cache & Queues):**++- BullMQ job queues+- Caching layer+- Session storage+- Rate limiting++### Data Access Pattern++**Services access databases directly:**++```typescript+// PostgreSQL via Prisma+import { prisma } from "@langfuse/shared/src/db";++const dataset = await prisma.dataset.create({ data });++// ClickHouse via helper functions+import { getTracesTable } from "@langfuse/shared/src/server";++const traces = await getTracesTable({+ projectId,+ filter: [...],+ limit: 1000,+});++// Redis via queue/cache utilities+import { redis } from "@langfuse/shared/src/server";++await redis.set(`cache:${key}`, value, "EX", 3600);+```++**Repository Pattern:**++Langfuse uses repositories in `packages/shared/src/server/repositories/` for complex data access patterns. Repositories provide:+- Abstraction over complex queries (traces, observations, scores, events)+- Data converters for transforming database models to application models+- ClickHouse query builders and stream processing+- Reusable query logic across services++Services can use repositories for complex operations OR Prisma directly for simple CRUD operations.++---++## Best Practices++### 1. Keep Procedures Thin++tRPC procedures should only handle protocol concerns:++```typescript+// β BAD: Business logic in procedure+export const datasetRouter = createTRPCRouter({+ create: protectedProjectProcedure+ .input(createSchema)+ .mutation(async ({ input, ctx }) => {+ // 200 lines of business logic here+ const existing = await prisma.dataset.findFirst(...);+ if (existing) throw new Error(...);+ const dataset = await prisma.dataset.create(...);+ await sendNotification(...);+ return dataset;+ }),+});++// β GOOD: Delegate to service+export const datasetRouter = createTRPCRouter({+ create: protectedProjectProcedure+ .input(createSchema)+ .mutation(async ({ input, ctx }) => {+ return await createDataset(input, ctx.session);+ }),+});+```++### 2. Services Should Be Protocol-Agnostic++Services should work regardless of entry point:++```typescript+// β GOOD: No HTTP/tRPC knowledge+export async function createDataset(data: CreateDatasetInput) {+ // Pure business logic+ return await prisma.dataset.create({ data });+}++// β BAD: tRPC-specific+export async function createDataset(ctx: TRPCContext) {+ // Coupled to tRPC+}+```++### 3. Instrument Critical Operations++Use OpenTelemetry for observability:++```typescript+import { instrumentAsync } from "@langfuse/shared/src/server";++export async function processEvaluation(evalId: string) {+ return await instrumentAsync(+ { name: "evaluation.process", attributes: { evalId } },+ async (span) => {+ // Operation here+ span.setAttributes({ score: result.score });+ return result;+ },+ );+}+```++### 4. Use Proper Error Handling++Transform errors at entry points:++```typescript+// tRPC procedure+try {+ return await service();+} catch (error) {+ traceException(error); // Log to Sentry+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "User-friendly message",+ cause: error,+ });+}++// Public API+try {+ return await service();+} catch (error) {+ traceException(error);+ return res.status(500).json({+ error: "User-friendly message",+ });+}+```++### 5. Validate at Entry Points++Use Zod v4 for all input validation:++```typescript+import { z } from "zod/v4";++// tRPC+.input(z.object({+ name: z.string().min(1).max(255),+ projectId: z.string(),+}))++// Public API+const bodySchema = z.object({+ name: z.string().min(1).max(255),+});+const validated = bodySchema.parse(req.body);+```++---++**Related Files:**++- [SKILL.md](../SKILL.md) - Main guide+- [routing-and-controllers.md](routing-and-controllers.md) - tRPC and Public API details+- [services-and-repositories.md](services-and-repositories.md) - Service patterns+- [testing-guide.md](testing-guide.md) - Testing strategiesdiff --git a/.claude/skills/backend-dev-guidelines/resources/configuration.md b/.claude/skills/backend-dev-guidelines/resources/configuration.mdnew file mode 100644index 0000000000..d62db03482--- /dev/null+++ b/.claude/skills/backend-dev-guidelines/resources/configuration.md@@ -0,0 +1,535 @@+# Configuration Management - Environment Variables++Complete guide to managing configuration across Langfuse's monorepo packages.++## Table of Contents++- [Environment Variable Pattern](#environment-variable-pattern)+- [Package-Specific Configuration](#package-specific-configuration)+- [Special Environment Variables](#special-environment-variables)+- [Best Practices](#best-practices)++---++## Environment Variable Pattern++### Why Zod-Validated Environment Variables?++**Problems with raw process.env:**++- β No type safety+- β No validation+- β Hard to test+- β Runtime errors for typos+- β No default values++**Benefits of Zod validation:**++- β Type-safe configuration+- β Validated at startup+- β Clear error messages+- β Default values+- β Environment-specific transformation++---++## Package-Specific Configuration++Each package has its own `env.ts` or `env.mjs` file that validates and exports environment variables:++```+langfuse/+βββ web/src/env.mjs # Next.js app (t3-env pattern)+βββ worker/src/env.ts # Worker service (Zod schema)+βββ packages/shared/src/env.ts # Shared config (Zod schema)+βββ ee/src/env.ts # Enterprise Edition (Zod schema)+```++### Web Package (`web/src/env.mjs`)++Uses **t3-oss/env-nextjs** for Next.js-specific validation with server/client separation.++**Key Features:**+- Separates server-side and client-side environment variables+- Client variables must be prefixed with `NEXT_PUBLIC_`+- Validates at build time (unless `DOCKER_BUILD=1`)+- `runtimeEnv` section manually maps all variables++**Structure:**++```typescript+import { createEnv } from "@t3-oss/env-nextjs";+import { z } from "zod";++export const env = createEnv({+ // Server-side only variables (never exposed to client)+ server: {+ DATABASE_URL: z.string().url(),+ NEXTAUTH_SECRET: z.string().min(1),+ SALT: z.string(),+ CLICKHOUSE_URL: z.string().url(),+ // ... 100+ server variables+ },++ // Client-side variables (exposed to browser)+ client: {+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: z+ .enum(["US", "EU", "STAGING", "DEV", "HIPAA"])+ .optional(),+ NEXT_PUBLIC_SIGN_UP_DISABLED: z.enum(["true", "false"]).default("false"),+ NEXT_PUBLIC_TURNSTILE_SITE_KEY: z.string().optional(),+ // ... client variables+ },++ // Runtime mapping (required for Next.js edge runtime)+ runtimeEnv: {+ DATABASE_URL: process.env.DATABASE_URL,+ NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET,+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,+ // ... must map ALL variables+ },++ // Skip validation in Docker builds+ skipValidation: process.env.DOCKER_BUILD === "1",+ emptyStringAsUndefined: true,+});+```++**Usage:**++```typescript+// In server-side code (tRPC, API routes)+import { env } from "@/src/env.mjs";++const dbUrl = env.DATABASE_URL;+const salt = env.SALT;++// In client-side code (React components)+import { env } from "@/src/env.mjs";++const region = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+```++### Worker Package (`worker/src/env.ts`)++Uses **plain Zod schema** for Express.js worker service.++**Structure:**++```typescript+import { z } from "zod/v4";+import { removeEmptyEnvVariables } from "@langfuse/shared";++const EnvSchema = z.object({+ BUILD_ID: z.string().optional(),+ NODE_ENV: z.enum(["development", "test", "production"]).default("development"),+ DATABASE_URL: z.string(),+ PORT: z.coerce.number().positive().max(65536).default(3030),++ // ClickHouse+ CLICKHOUSE_URL: z.string().url(),+ CLICKHOUSE_USER: z.string(),+ CLICKHOUSE_PASSWORD: z.string(),++ // S3 Event Upload (required)+ LANGFUSE_S3_EVENT_UPLOAD_BUCKET: z.string({+ error: "Langfuse requires a bucket name for S3 Event Uploads.",+ }),++ // Queue concurrency settings+ LANGFUSE_INGESTION_QUEUE_PROCESSING_CONCURRENCY: z.coerce.number().positive().default(20),+ LANGFUSE_EVAL_EXECUTION_WORKER_CONCURRENCY: z.coerce.number().positive().default(5),++ // Queue consumer toggles+ QUEUE_CONSUMER_INGESTION_QUEUE_IS_ENABLED: z.enum(["true", "false"]).default("true"),+ QUEUE_CONSUMER_BATCH_EXPORT_QUEUE_IS_ENABLED: z.enum(["true", "false"]).default("true"),++ // ... 150+ worker-specific variables+});++export const env: z.infer<typeof EnvSchema> =+ process.env.DOCKER_BUILD === "1"+ ? (process.env as any)+ : EnvSchema.parse(removeEmptyEnvVariables(process.env));+```++**Usage:**++```typescript+import { env } from "./env";++const concurrency = env.LANGFUSE_INGESTION_QUEUE_PROCESSING_CONCURRENCY;+const s3Bucket = env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET;+```++### Shared Package (`packages/shared/src/env.ts`)++Uses **plain Zod schema** for configuration shared between web and worker.++**Structure:**++```typescript+import { z } from "zod/v4";+import { removeEmptyEnvVariables } from "./utils/environment";++const EnvSchema = z.object({+ NODE_ENV: z.enum(["development", "test", "production"]).default("development"),++ // Redis configuration+ REDIS_HOST: z.string().nullish(),+ REDIS_PORT: z.coerce.number().positive().max(65536).default(6379).nullable(),+ REDIS_AUTH: z.string().nullish(),+ REDIS_CONNECTION_STRING: z.string().nullish(),+ REDIS_CLUSTER_ENABLED: z.enum(["true", "false"]).default("false"),++ // ClickHouse+ CLICKHOUSE_URL: z.string().url(),+ CLICKHOUSE_USER: z.string(),+ CLICKHOUSE_PASSWORD: z.string(),+ CLICKHOUSE_MAX_OPEN_CONNECTIONS: z.coerce.number().int().default(25),++ // S3 Event Upload+ LANGFUSE_S3_EVENT_UPLOAD_BUCKET: z.string(),+ LANGFUSE_S3_EVENT_UPLOAD_REGION: z.string().optional(),++ // Logging+ LANGFUSE_LOG_LEVEL: z.enum(["trace", "debug", "info", "warn", "error", "fatal"]).optional(),+ LANGFUSE_LOG_FORMAT: z.enum(["text", "json"]).default("text"),++ // Encryption+ ENCRYPTION_KEY: z.string().length(64, "ENCRYPTION_KEY must be 256 bits, 64 string characters in hex format, generate via: openssl rand -hex 32").optional(),++ // ... 80+ shared variables+});++export const env: z.infer<typeof EnvSchema> =+ process.env.DOCKER_BUILD === "1"+ ? (process.env as any)+ : EnvSchema.parse(removeEmptyEnvVariables(process.env));+```++**Usage:**++```typescript+import { env } from "@langfuse/shared/src/env";++const redisHost = env.REDIS_HOST;+const clickhouseUrl = env.CLICKHOUSE_URL;+```++### Enterprise Edition Package (`ee/src/env.ts`)++Minimal Zod schema for EE-specific variables.++**Structure:**++```typescript+import { z } from "zod/v4";+import { removeEmptyEnvVariables } from "@langfuse/shared";++const EnvSchema = z.object({+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: z.string().optional(),+ LANGFUSE_EE_LICENSE_KEY: z.string().optional(),+});++export const env = EnvSchema.parse(removeEmptyEnvVariables(process.env));+```++**Usage:**++```typescript+import { env } from "@langfuse/ee/src/env";++const licenseKey = env.LANGFUSE_EE_LICENSE_KEY;+```++---++## Special Environment Variables++### NEXT_PUBLIC_LANGFUSE_CLOUD_REGION++**Purpose:** Identifies the cloud deployment region for Langfuse Cloud.++**Type:** `"US" | "EU" | "STAGING" | "DEV" | "HIPAA" | undefined`++**Where Used:**+- **web/src/env.mjs** - Client-side accessible (prefixed with `NEXT_PUBLIC_`)+- **ee/src/env.ts** - Enterprise features+- **packages/shared/src/env.ts** - Shared logic+- **worker/src/env.ts** - Worker processing++**When Set:**++| Environment | Value | Purpose |+|-------------|-------|---------|+| **Developer Laptop** | `"DEV"` or `"STAGING"` | Local development against cloud infrastructure |+| **Langfuse Cloud US** | `"US"` | Production US region |+| **Langfuse Cloud EU** | `"EU"` | Production EU region |+| **Langfuse Cloud HIPAA** | `"HIPAA"` | HIPAA-compliant region |+| **OSS Self-Hosted** | `undefined` (not set) | Self-hosted deployments don't have region |++**Use Cases:**++```typescript+// Check if running in cloud+if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {+ // Enable cloud-specific features+ - Usage metering and billing+ - Cloud spend alerts+ - Free tier enforcement+ - Stripe integration+ - PostHog analytics+}++// Region-specific behavior+if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "HIPAA") {+ // HIPAA compliance features+}++// Development/staging checks+if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "DEV") {+ // Enable debug features+}+```++**Example Configuration:**++```bash+# .env file on developer laptop+NEXT_PUBLIC_LANGFUSE_CLOUD_REGION=DEV++# Cloud US deployment+NEXT_PUBLIC_LANGFUSE_CLOUD_REGION=US++# Self-hosted OSS deployment+# (variable not set)+```++### LANGFUSE_EE_LICENSE_KEY++**Purpose:** Enables Enterprise Edition features in self-hosted deployments.++**Type:** `string | undefined`++**Where Used:**+- **web/src/env.mjs** - Web app EE features+- **ee/src/env.ts** - EE package++**When Set:**++| Deployment | Value | Features Enabled |+|------------|-------|------------------|+| **Langfuse Cloud** | Not set | Cloud features controlled by `NEXT_PUBLIC_LANGFUSE_CLOUD_REGION` |+| **OSS Self-Hosted** | Not set | Core open-source features only |+| **EE Self-Hosted** | License key string | Enterprise features enabled |++**Enterprise Features Controlled:**++When `LANGFUSE_EE_LICENSE_KEY` is set and valid:+- SSO integrations (custom OIDC, SAML)+- Advanced RBAC+- Audit logging+- Custom branding+- SLA support+- Advanced security features++**Usage Pattern:**++```typescript+import { env } from "@/src/env.mjs";++// Check if EE license is present+if (env.LANGFUSE_EE_LICENSE_KEY) {+ // Validate license+ const isValidLicense = await validateEELicense(env.LANGFUSE_EE_LICENSE_KEY);++ if (isValidLicense) {+ // Enable EE features+ enableCustomSSO();+ enableAdvancedRBAC();+ }+}+```++**Example Configuration:**++```bash+# OSS self-hosted (no license)+# LANGFUSE_EE_LICENSE_KEY not set++# EE self-hosted+LANGFUSE_EE_LICENSE_KEY=ee_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx++# Langfuse Cloud (uses region instead)+NEXT_PUBLIC_LANGFUSE_CLOUD_REGION=US+# LANGFUSE_EE_LICENSE_KEY not used+```++### Other Important Variables++**DOCKER_BUILD**++```typescript+// Skip validation during Docker builds+skipValidation: process.env.DOCKER_BUILD === "1"+```++**Purpose:** Docker builds happen before runtime env vars are available, so validation must be skipped.++**SALT**++```typescript+SALT: z.string({+ required_error: "A strong Salt is required to encrypt API keys securely.",+})+```++**Purpose:** Required for encrypting API keys in database. Must be set in production.++**ENCRYPTION_KEY**++```typescript+ENCRYPTION_KEY: z.string().length(64, "Must be 256 bits, 64 hex characters")+```++**Purpose:** Optional 256-bit key for encrypting sensitive database fields.++**Generate:** `openssl rand -hex 32`++---++## Best Practices++### 1. Always Import from env.mjs/env.ts++```typescript+// β NEVER DO THIS+const dbUrl = process.env.DATABASE_URL;++// β ALWAYS DO THIS+import { env } from "@/src/env.mjs";+const dbUrl = env.DATABASE_URL; // Type-safe, validated+```++### 2. Use Appropriate Import Path++```typescript+// In web package+import { env } from "@/src/env.mjs";++// In worker package+import { env } from "./env";++// In shared package+import { env } from "@langfuse/shared/src/env";+```++### 3. Client Variables Must Start with NEXT_PUBLIC_++```typescript+// β Won't work in browser+API_KEY: z.string() // in server config++// β Accessible in browser+NEXT_PUBLIC_API_KEY: z.string() // in client config+```++### 4. Provide Sensible Defaults for Development++```typescript+PORT: z.coerce.number().positive().default(3030),+NODE_ENV: z.enum(["development", "test", "production"]).default("development"),+REDIS_PORT: z.coerce.number().positive().default(6379),+```++### 5. Use Coercion for Numbers++```typescript+// .env files are always strings+PORT: z.coerce.number() // Converts "3000" to 3000+```++### 6. Transform Complex Values++```typescript+// Split comma-separated values+LANGFUSE_LOG_PROPAGATED_HEADERS: z.string().optional().transform((s) =>+ s ? s.split(",").map((s) => s.toLowerCase().trim()) : []+),++// Parse project:rate pairs+LANGFUSE_INGESTION_PROCESSING_SAMPLED_PROJECTS: z.string().optional().transform((val) => {+ const map = new Map<string, number>();+ val?.split(",").forEach(part => {+ const [projectId, rate] = part.split(":");+ map.set(projectId, parseFloat(rate));+ });+ return map;+}),+```++### 7. Validation at Startup++All environment variables are validated when the application starts. Invalid configuration will cause immediate failure with clear error messages:++```bash+β Validation error:+ - SALT: Required+ - CLICKHOUSE_URL: Invalid url+ - PORT: Number must be less than or equal to 65536+```++### 8. Skip Validation in Docker Builds++Always include the Docker build escape hatch:++```typescript+export const env =+ process.env.DOCKER_BUILD === "1"+ ? (process.env as any)+ : EnvSchema.parse(removeEmptyEnvVariables(process.env));+```++### 9. Use removeEmptyEnvVariables Helper++Treats empty strings as undefined:++```typescript+import { removeEmptyEnvVariables } from "@langfuse/shared";++EnvSchema.parse(removeEmptyEnvVariables(process.env));+```++This prevents errors from `.env` files with empty values:++```bash+# .env+OPTIONAL_VAR= # Treated as undefined, not empty string+```++---++## Configuration File Locations++```+langfuse/+βββ .env # Local development overrides+βββ .env.dev.example # Example dev configuration+βββ web/src/env.mjs # Web app env validation+βββ worker/src/env.ts # Worker env validation+βββ packages/shared/src/env.ts # Shared env validation+βββ ee/src/env.ts # EE env validation+```++**DO NOT commit:**+- `.env`+- `.env.local`+- `.env.production`++---++**Related Files:**++- [SKILL.md](../SKILL.md) - Main guide+- [architecture-overview.md](architecture-overview.md) - Architecture patternsdiff --git a/.claude/skills/backend-dev-guidelines/resources/database-patterns.md b/.claude/skills/backend-dev-guidelines/resources/database-patterns.mdnew file mode 100644index 0000000000..b2500012a7--- /dev/null+++ b/.claude/skills/backend-dev-guidelines/resources/database-patterns.md@@ -0,0 +1,580 @@+# Database Patterns - PostgreSQL & ClickHouse++Complete guide to database access patterns in Langfuse using PostgreSQL (Prisma ORM) and ClickHouse (direct client).++## Table of Contents++- [Database Architecture Overview](#database-architecture-overview)+- [PostgreSQL with Prisma](#postgresql-with-prisma)+- [ClickHouse with Direct Client](#clickhouse-with-direct-client)+- [Repository Pattern](#repository-pattern)+- [When to Use Which Database](#when-to-use-which-database)+- [Error Handling](#error-handling)++---++## Database Architecture Overview++Langfuse uses a **dual database architecture**:++| Database | Technology | Purpose | Access Pattern |+| -------------- | ----------------- | ------------------------------------------------------------- | -------------------------------------- |+| **PostgreSQL** | Prisma ORM | Transactional data, relational data, CRUD operations | Type-safe ORM with migrations |+| **ClickHouse** | Direct SQL client | Analytics data, high-volume traces/observations, aggregations | Raw SQL queries with streaming support |+| **Redis** | ioredis | Queues (BullMQ), caching, rate limiting | Direct client access |++**Key Principle**: Use PostgreSQL for transactional data and relationships. Use ClickHouse for high-volume analytics and time-series data.++---++## PostgreSQL with Prisma++### Import Pattern++```typescript+import { prisma } from "@langfuse/shared/src/db";++// Direct access to Prisma client+const user = await prisma.user.findUnique({ where: { id } });+```++**Important**: Always import from `@langfuse/shared/src/db`, not `@prisma/client` directly.++### Common CRUD Operations++```typescript+// Create+const project = await prisma.project.create({+ data: {+ name: "My Project",+ orgId: organizationId,+ },+});++// Read with relations+const trace = await prisma.trace.findUnique({+ where: { id: traceId, projectId },+ include: {+ scores: true,+ project: { select: { id: true, name: true } },+ },+});++// Update+await prisma.user.update({+ where: { id: userId },+ data: { lastLogin: new Date() },+});++// Delete+await prisma.apiKey.delete({+ where: { id: apiKeyId, projectId },+});++// Count+const traceCount = await prisma.trace.count({+ where: { projectId, userId },+});+```++### Transactions++Use Prisma interactive transactions for operations that must be atomic:++```typescript+const result = await prisma.$transaction(async (tx) => {+ const user = await tx.user.create({ data: userData });++ const project = await tx.project.create({+ data: {+ name: "Default Project",+ orgId: user.id,+ },+ });++ await tx.projectMembership.create({+ data: {+ userId: user.id,+ projectId: project.id,+ role: "OWNER",+ },+ });++ return { user, project };+});+```++**Transaction options:**++```typescript+await prisma.$transaction(+ async (tx) => {+ // Transaction logic+ },+ {+ maxWait: 5000, // Max time to wait for transaction to start (ms)+ timeout: 10000, // Max time transaction can run (ms)+ },+);+```++### Query Optimization++**Use `select` to limit fields:**++```typescript+// β Fetches all fields (including large JSON columns)+const traces = await prisma.trace.findMany({ where: { projectId } });++// β Only fetch needed fields+const traces = await prisma.trace.findMany({+ where: { projectId },+ select: {+ id: true,+ name: true,+ timestamp: true,+ userId: true,+ },+});+```++**Prevent N+1 queries with `include`:**++```typescript+// β N+1 Query Problem+const projects = await prisma.project.findMany();+for (const project of projects) {+ // N additional queries+ const memberCount = await prisma.projectMembership.count({+ where: { projectId: project.id },+ });+}++// β Use include or aggregation+const projects = await prisma.project.findMany({+ include: {+ members: { select: { userId: true, role: true } },+ },+});+```++**Pagination:**++```typescript+const PAGE_SIZE = 50;++const traces = await prisma.trace.findMany({+ where: { projectId },+ orderBy: { timestamp: "desc" },+ take: PAGE_SIZE,+ skip: page * PAGE_SIZE,+});+```++## ClickHouse with Direct Client++### Import Pattern++```typescript+import { queryClickhouse } from "@langfuse/shared/src/server/repositories/clickhouse";+import { clickhouseClient } from "@langfuse/shared/src/server/clickhouse/client";+```++### ClickHouse Client Singleton++ClickHouse uses a singleton client manager that reuses connections:++```typescript+import { clickhouseClient } from "@langfuse/shared/src/server/clickhouse/client";++// Get client (automatically reuses existing connection)+const client = clickhouseClient();++// For read-only queries (uses read replica if configured)+const client = clickhouseClient(undefined, "ReadOnly");+```++### Query Patterns++ClickHouse queries use **raw SQL** with parameterized queries. Parameters use `{paramName: Type}` syntax:++**Simple query:**++```typescript+import { queryClickhouse } from "@langfuse/shared/src/server/repositories/clickhouse";++const rows = await queryClickhouse<{ id: string; name: string }>({+ query: `+ SELECT id, name, timestamp+ FROM traces+ WHERE project_id = {projectId: String}+ AND timestamp >= {startTime: DateTime64(3)}+ ORDER BY timestamp DESC+ LIMIT {limit: UInt32}+ `,+ params: {+ projectId,+ startTime: convertDateToClickhouseDateTime(startDate),+ limit: 100,+ },+ tags: { feature: "tracing", type: "trace" },+});+```++**Streaming query (for large result sets):**++```typescript+import { queryClickhouseStream } from "@langfuse/shared/src/server/repositories/clickhouse";++// Stream results to avoid loading all rows in memory+for await (const row of queryClickhouseStream<ObservationRecordReadType>({+ query: `+ SELECT *+ FROM observations+ WHERE project_id = {projectId: String}+ AND start_time >= {startTime: DateTime64(3)}+ `,+ params: { projectId, startTime },+})) {+ // Process row by row+ await processObservation(row);+}+```++**Upsert (insert) operation:**++```typescript+import { upsertClickhouse } from "@langfuse/shared/src/server/repositories/clickhouse";++await upsertClickhouse({+ table: "traces",+ records: [+ {+ id: traceId,+ project_id: projectId,+ timestamp: new Date(),+ name: "API Call",+ user_id: userId,+ // ... other fields+ },+ ],+ eventBodyMapper: (record) => ({+ // Transform record for event log+ id: record.id,+ name: record.name,+ // ... other fields+ }),+ tags: { feature: "ingestion", type: "trace" },+});+```++**DDL/Administrative commands:**++```typescript+import { commandClickhouse } from "@langfuse/shared/src/server/repositories/clickhouse";++// Create table, alter schema, etc.+await commandClickhouse({+ query: `+ ALTER TABLE traces+ ADD COLUMN IF NOT EXISTS new_field String+ `,+ tags: { feature: "migration" },+});+```++### ClickHouse Type Mapping++| JavaScript Type | ClickHouse Param Type |+| --------------- | --------------------------------------------------------- |+| `string` | `String` |+| `number` | `UInt32`, `Int64`, `Float64` |+| `Date` | `DateTime64(3)` (use `convertDateToClickhouseDateTime()`) |+| `boolean` | `UInt8` (0 or 1) |+| `string[]` | `Array(String)` |++**Date handling:**++```typescript+import { convertDateToClickhouseDateTime } from "@langfuse/shared/src/server/clickhouse/client";++const params = {+ startTime: convertDateToClickhouseDateTime(new Date()),+};+```++### ClickHouse Query Best Practices++**Use LIMIT BY for deduplication:**++```typescript+// Get latest version of each trace+const query = `+ SELECT *+ FROM traces+ WHERE project_id = {projectId: String}+ ORDER BY event_ts DESC+ LIMIT 1 BY id, project_id+`;+```++**Use time-based filtering:**++```typescript+// Always filter by timestamp for performance+const query = `+ SELECT *+ FROM observations+ WHERE project_id = {projectId: String}+ AND start_time >= {startTime: DateTime64(3)}+ AND start_time < {endTime: DateTime64(3)}+`;+```++**Use CTEs for complex queries:**++```typescript+const query = `+ WITH observations_agg AS (+ SELECT+ trace_id,+ count() as observation_count,+ sum(total_cost) as total_cost+ FROM observations+ WHERE project_id = {projectId: String}+ GROUP BY trace_id+ )+ SELECT+ t.id,+ t.name,+ o.observation_count,+ o.total_cost+ FROM traces t+ LEFT JOIN observations_agg o ON t.id = o.trace_id+ WHERE t.project_id = {projectId: String}+`;+```++**Error handling with retries:**++ClickHouse queries automatically retry on network errors (socket hang up). Custom error handling for resource limits:++```typescript+import {+ queryClickhouse,+ ClickHouseResourceError,+} from "@langfuse/shared/src/server/repositories/clickhouse";++try {+ const rows = await queryClickhouse({ query, params });+} catch (error) {+ if (error instanceof ClickHouseResourceError) {+ // Memory limit, timeout, or overcommit error+ throw new Error(ClickHouseResourceError.ERROR_ADVICE_MESSAGE);+ }+ throw error;+}+```++---++## Repository Pattern++Langfuse uses repositories in `packages/shared/src/server/repositories/` for complex data access patterns.++### When to Use Repositories++β **Use repositories when:**++- Complex ClickHouse queries with CTEs, aggregations, or joins+- Query used in multiple places (DRY principle)+- Need data transformation/converters (DB β domain models)+- Building reusable query logic with filters++β **Use direct Prisma/ClickHouse for:**++- Simple CRUD operations+- One-off queries+- Prototyping (refactor to repository later)++### Repository Examples++**Trace repository (ClickHouse):**++```typescript+// packages/shared/src/server/repositories/traces.ts+export const getTracesByIds = async (+ projectId: string,+ traceIds: string[],+): Promise<TraceRecordReadType[]> => {+ const rows = await queryClickhouse<TraceRecordReadType>({+ query: `+ SELECT *+ FROM traces+ WHERE project_id = {projectId: String}+ AND id IN ({traceIds: Array(String)})+ ORDER BY event_ts DESC+ LIMIT 1 BY id, project_id+ `,+ params: { projectId, traceIds },+ tags: { feature: "tracing", type: "trace" },+ });++ return rows.map(convertClickhouseToDomain);+};+```++**Score repository (PostgreSQL + ClickHouse):**++```typescript+// Repositories can query both databases+export const getScoresByTraceId = async (+ projectId: string,+ traceId: string,+) => {+ // Use ClickHouse for analytics+ const clickhouseScores = await queryClickhouse<ScoreRecordReadType>({+ query: `+ SELECT *+ FROM scores+ WHERE project_id = {projectId: String}+ AND trace_id = {traceId: String}+ `,+ params: { projectId, traceId },+ });++ // Use Prisma for config data+ const scoreConfigs = await prisma.scoreConfig.findMany({+ where: { projectId },+ });++ return enrichScoresWithConfigs(clickhouseScores, scoreConfigs);+};+```++---++## When to Use Which Database++| Use Case | Database | Reasoning |+| -------------------------------------- | ---------- | ------------------------------------------ |+| User accounts, projects, API keys | PostgreSQL | Transactional data with strong consistency |+| Prompt management, dataset definitions | PostgreSQL | Configuration data with relations |+| Project settings, RBAC permissions | PostgreSQL | Small, frequently updated data |+| Traces, observations, events | ClickHouse | High-volume time-series data |+| Score aggregations, analytics queries | ClickHouse | Fast aggregations over millions of rows |+| Usage metrics, cost calculations | ClickHouse | Analytical queries with GROUP BY |+| Exports, large dataset queries | ClickHouse | Streaming support for large result sets |++**Decision flow:**++1. Is it high-volume time-series data? β **ClickHouse**+2. Does it need aggregation over millions of rows? β **ClickHouse**+3. Is it transactional data with relationships? β **PostgreSQL**+4. Is it configuration or user data? β **PostgreSQL**+5. Is it frequently updated? β **PostgreSQL**+6. Is it append-only analytics data? β **ClickHouse**++---++## Error Handling++### PostgreSQL (Prisma) Errors++```typescript+import { Prisma } from "@prisma/client";+import { prisma } from "@langfuse/shared/src/db";++try {+ await prisma.user.create({ data: userData });+} catch (error) {+ if (error instanceof Prisma.PrismaClientKnownRequestError) {+ // Unique constraint violation+ if (error.code === "P2002") {+ const target = error.meta?.target as string[];+ throw new ConflictError(`${target?.join(", ")} already exists`);+ }++ // Foreign key constraint+ if (error.code === "P2003") {+ throw new ValidationError("Invalid reference");+ }++ // Record not found+ if (error.code === "P2025") {+ throw new NotFoundError("Record not found");+ }++ // Record required to connect not found+ if (error.code === "P2018") {+ throw new ValidationError("Related record not found");+ }+ }++ // Unknown error+ logger.error("Prisma error", { error });+ throw error;+}+```++**Common Prisma error codes:**++| Code | Meaning | Typical Cause |+| -------- | ---------------------------- | ------------------------------------- |+| `P2002` | Unique constraint violation | Duplicate email, API key, etc. |+| `P2003` | Foreign key constraint | Referenced record doesn't exist |+| `P2025` | Record not found | Update/delete of non-existent record |+| `P2018` | Required relation not found | Connect to non-existent related record |++### ClickHouse Errors++```typescript+import {+ queryClickhouse,+ ClickHouseResourceError,+} from "@langfuse/shared/src/server/repositories/clickhouse";++try {+ const rows = await queryClickhouse({ query, params });+} catch (error) {+ // ClickHouse resource errors (memory limit, timeout, overcommit)+ if (error instanceof ClickHouseResourceError) {+ logger.warn("ClickHouse resource error", {+ errorType: error.errorType, // "MEMORY_LIMIT" | "OVERCOMMIT" | "TIMEOUT"+ message: error.message,+ });++ // User-friendly error message+ throw new BadRequestError(ClickHouseResourceError.ERROR_ADVICE_MESSAGE);+ }++ // Network/connection errors are automatically retried+ logger.error("ClickHouse error", { error });+ throw error;+}+```++**ClickHouse error types:**++| Error Type | Discriminator | Meaning | Solution |+| --------------- | ----------------------- | ---------------------------- | -------------------------------------------------- |+| `MEMORY_LIMIT` | "memory limit exceeded" | Query used too much memory | Use more specific filters or shorter time range |+| `OVERCOMMIT` | "OvercommitTracker" | Memory overcommit limit hit | Reduce query complexity or result set size |+| `TIMEOUT` | "Timeout", "timed out" | Query took too long | Add filters, reduce time range, or optimize query |++**ClickHouse retries:**++ClickHouse queries automatically retry network errors (socket hang up) with exponential backoff. Configure retry behavior:++```typescript+// In packages/shared/src/env.ts+LANGFUSE_CLICKHOUSE_QUERY_MAX_ATTEMPTS: z.coerce.number().positive().default(3)+```++---++**Related Files:**++- [SKILL.md](../SKILL.md) - Main backend development guidelines+- [architecture-overview.md](architecture-overview.md) - System architecture+- [configuration.md](configuration.md) - Environment variable configurationdiff --git a/.claude/skills/backend-dev-guidelines/resources/middleware-guide.md b/.claude/skills/backend-dev-guidelines/resources/middleware-guide.mdnew file mode 100644index 0000000000..cebfc57984--- /dev/null+++ b/.claude/skills/backend-dev-guidelines/resources/middleware-guide.md@@ -0,0 +1,765 @@+# Middleware Guide - tRPC & Public API Patterns++Complete guide to middleware patterns in Langfuse's Next.js + tRPC architecture.++## Table of Contents++- [tRPC Middleware](#trpc-middleware)+- [Public API Middleware](#public-api-middleware)+- [Authentication Patterns](#authentication-patterns)+- [Error Handling Middleware](#error-handling-middleware)+- [OpenTelemetry Instrumentation](#opentelemetry-instrumentation)+- [Composable Procedures](#composable-procedures)++---++## tRPC Middleware++**File:** `web/src/server/api/trpc.ts`++tRPC middleware in Langfuse is composable and type-safe. Each middleware enriches the context and provides guarantees to subsequent middleware.++### Core tRPC Middlewares++**1. Error Handling Middleware (`withErrorHandling`)**++Intercepts all errors and transforms them into user-friendly tRPC errors:++```typescript+const withErrorHandling = t.middleware(async ({ ctx, next }) => {+ const res = await next({ ctx });++ if (!res.ok) {+ if (res.error.cause instanceof ClickHouseResourceError) {+ // Surface ClickHouse resource errors with advice message+ res.error = new TRPCError({+ code: "SERVICE_UNAVAILABLE",+ message: ClickHouseResourceError.ERROR_ADVICE_MESSAGE,+ });+ } else {+ // Transform 5xx errors to not expose internals+ const { code, httpStatus } = resolveError(res.error);+ const isSafeToExpose = httpStatus >= 400 && httpStatus < 500;++ res.error = new TRPCError({+ code,+ cause: null, // do not expose stack traces+ message: isSafeToExpose+ ? res.error.message+ : "Internal error. We have been notified and are working on it.",+ });+ }+ }++ return res;+});+```++**2. OpenTelemetry Instrumentation (`withOtelInstrumentation`)**++Propagates OpenTelemetry context with Langfuse-specific baggage:++```typescript+const withOtelInstrumentation = t.middleware(async (opts) => {+ const actualInput = await opts.getRawInput();++ const baggageCtx = contextWithLangfuseProps({+ headers: opts.ctx.headers,+ userId: opts.ctx.session?.user?.id,+ projectId: (actualInput as Record<string, string>)?.projectId,+ });++ return opentelemetry.context.with(baggageCtx, () => opts.next());+});+```++**3. Authentication Middleware (`enforceUserIsAuthed`)**++Ensures user is logged in via NextAuth session:++```typescript+const enforceUserIsAuthed = t.middleware(({ ctx, next }) => {+ if (!ctx.session || !ctx.session.user) {+ throw new TRPCError({ code: "UNAUTHORIZED" });+ }++ return next({+ ctx: {+ // infers the `session` as non-nullable+ session: { ...ctx.session, user: ctx.session.user },+ },+ });+});+```++**4. Project Membership Middleware (`enforceUserIsAuthedAndProjectMember`)**++Validates that the user is a member of the project specified in input:++```typescript+const enforceUserIsAuthedAndProjectMember = t.middleware(async (opts) => {+ const { ctx, next } = opts;++ if (!ctx.session || !ctx.session.user) {+ throw new TRPCError({ code: "UNAUTHORIZED" });+ }++ const actualInput = await opts.getRawInput();+ const parsedInput = inputProjectSchema.safeParse(actualInput);++ if (!parsedInput.success) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Invalid input, projectId is required",+ });+ }++ const projectId = parsedInput.data.projectId;+ const sessionProject = ctx.session.user.organizations+ .flatMap((org) => org.projects.map((project) => ({ ...project, organization: org })))+ .find((project) => project.id === projectId);++ if (!sessionProject) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "User is not a member of this project",+ });+ }++ return next({+ ctx: {+ session: {+ ...ctx.session,+ user: ctx.session.user,+ orgId: sessionProject.organization.id,+ orgRole: sessionProject.organization.role,+ projectId: projectId,+ projectRole: sessionProject.role,+ },+ },+ });+});+```++**5. Organization Membership Middleware (`enforceIsAuthedAndOrgMember`)**++Validates organization membership:++```typescript+const enforceIsAuthedAndOrgMember = t.middleware(async (opts) => {+ const { ctx, next } = opts;++ if (!ctx.session || !ctx.session.user) {+ throw new TRPCError({ code: "UNAUTHORIZED" });+ }++ const actualInput = await opts.getRawInput();+ const result = inputOrganizationSchema.safeParse(actualInput);++ if (!result.success) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Invalid input, orgId is required",+ });+ }++ const orgId = result.data.orgId;+ const sessionOrg = ctx.session.user.organizations.find((org) => org.id === orgId);++ if (!sessionOrg && ctx.session.user.admin !== true) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "User is not a member of this organization",+ });+ }++ return next({+ ctx: {+ session: {+ ...ctx.session,+ user: ctx.session.user,+ orgId: orgId,+ orgRole: ctx.session.user.admin === true ? Role.OWNER : sessionOrg!.role,+ },+ },+ });+});+```++**6. Trace Access Middleware (`enforceTraceAccess`)**++Special middleware for trace-level routes that supports public traces:++```typescript+const enforceTraceAccess = t.middleware(async (opts) => {+ const { ctx, next } = opts;+ const actualInput = await opts.getRawInput();+ const result = inputTraceSchema.safeParse(actualInput);++ if (!result.success) {+ throw new TRPCError({ code: "BAD_REQUEST", message: "Invalid input" });+ }++ const trace = await getTraceById({+ traceId: result.data.traceId,+ projectId: result.data.projectId,+ timestamp: result.data.timestamp ?? undefined,+ });++ if (!trace) {+ throw new TRPCError({ code: "NOT_FOUND", message: "Trace not found" });+ }++ const sessionProject = ctx.session?.user?.organizations+ .flatMap((org) => org.projects)+ .find(({ id }) => id === result.data.projectId);++ // Allow access if:+ // 1. User is a project member+ // 2. Trace is public+ // 3. User is admin+ if (!trace.public && !sessionProject && ctx.session?.user?.admin !== true) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "User is not a member of this project and this trace is not public",+ });+ }++ return next({+ ctx: {+ session: { ...ctx.session, projectRole: sessionProject?.role },+ trace: trace, // pass the trace to avoid refetching+ },+ });+});+```++### tRPC Procedure Types++Langfuse exports composed procedures with middleware chains:++```typescript+// 1. Public procedure (no auth required)+export const publicProcedure = withOtelTracingProcedure.use(withErrorHandling);++// 2. Authenticated procedure (NextAuth session required)+export const authenticatedProcedure = withOtelTracingProcedure+ .use(withErrorHandling)+ .use(enforceUserIsAuthed);++// 3. Project-scoped procedure (project membership required)+export const protectedProjectProcedure = withOtelTracingProcedure+ .use(withErrorHandling)+ .use(enforceUserIsAuthedAndProjectMember);++// 4. Organization-scoped procedure+export const protectedOrganizationProcedure = withOtelTracingProcedure+ .use(withErrorHandling)+ .use(enforceIsAuthedAndOrgMember);++// 5. Trace access procedure (public traces supported)+export const protectedGetTraceProcedure = withOtelTracingProcedure+ .use(withErrorHandling)+ .use(enforceTraceAccess);++// 6. Session access procedure+export const protectedGetSessionProcedure = withOtelTracingProcedure+ .use(withErrorHandling)+ .use(enforceSessionAccess);++// 7. Admin API key procedure (for admin operations)+export const adminProcedure = withOtelTracingProcedure+ .use(withErrorHandling)+ .use(enforceAdminAuth);+```++---++## Public API Middleware++**Files:** `web/src/features/public-api/server/`++### withMiddlewares Pattern++Wraps all public API routes with CORS, error handling, and OpenTelemetry:++```typescript+export function withMiddlewares(handlers: Handlers) {+ return async (req: NextApiRequest, res: NextApiResponse) => {+ const ctx = contextWithLangfuseProps({ headers: req.headers });++ return opentelemetry.context.with(ctx, async () => {+ try {+ // 1. CORS middleware+ await runMiddleware(req, res, cors);++ // 2. HTTP method routing+ const method = req.method as HttpMethod;+ if (!handlers[method]) throw new MethodNotAllowedError();++ // 3. Execute handler+ return await handlers[method](req, res);+ } catch (error) {+ // 4. Error handling+ if (error instanceof BaseError) {+ if (error.httpCode >= 500) traceException(error);++ return res.status(error.httpCode).json({+ message: error.message,+ error: error.name,+ });+ }++ if (error instanceof ClickHouseResourceError) {+ return res.status(524).json({+ message: ClickHouseResourceError.ERROR_ADVICE_MESSAGE,+ error: "Request is taking too long to process.",+ });+ }++ if (isZodError(error)) {+ return res.status(400).json({+ message: "Invalid request data",+ error: error.issues,+ });+ }++ traceException(error);+ return res.status(500).json({+ message: "Internal Server Error",+ error: error instanceof Error ? error.message : "Unknown error",+ });+ }+ });+ };+}+```++**Usage:**++```typescript+// web/src/pages/api/public/datasets/[datasetName]/items.ts+export default withMiddlewares({+ GET: getDatasetItemsHandler,+ POST: createDatasetItemHandler,+});+```++### createAuthedProjectAPIRoute Pattern++Factory function for authenticated public API routes with:+- Authentication (Basic auth or Admin API key)+- Rate limiting+- Input/output validation (Zod)+- OpenTelemetry context++```typescript+export const createAuthedProjectAPIRoute = <TQuery, TBody, TResponse>(+ routeConfig: RouteConfig<TQuery, TBody, TResponse>+) => {+ return async (req: NextApiRequest, res: NextApiResponse) => {+ // 1. Authentication (verifyAuth)+ const auth = await verifyAuth(req, routeConfig.isAdminApiKeyAuthAllowed || false);++ // 2. Rate limiting+ const rateLimitResponse = await RateLimitService.getInstance().rateLimitRequest(+ auth.scope,+ routeConfig.rateLimitResource || "public-api"+ );++ if (rateLimitResponse?.isRateLimited()) {+ return rateLimitResponse.sendRestResponseIfLimited(res);+ }++ // 3. Input validation+ const query = routeConfig.querySchema+ ? routeConfig.querySchema.parse(req.query)+ : {};+ const body = routeConfig.bodySchema+ ? routeConfig.bodySchema.parse(req.body)+ : {};++ // 4. Execute with OpenTelemetry context+ const ctx = contextWithLangfuseProps({+ headers: req.headers,+ projectId: auth.scope.projectId,+ });++ return opentelemetry.context.with(ctx, async () => {+ const response = await routeConfig.fn({ query, body, req, res, auth });++ // 5. Response validation (dev only)+ if (env.NODE_ENV === "development" && routeConfig.responseSchema) {+ const parsingResult = routeConfig.responseSchema.safeParse(response);+ if (!parsingResult.success) {+ logger.error("Response validation failed:", parsingResult.error);+ }+ }++ res.status(routeConfig.successStatusCode || 200).json(response);+ });+ };+};+```++**Usage:**++```typescript+// web/src/pages/api/public/traces/[traceId].ts+export default createAuthedProjectAPIRoute({+ name: "Get Trace",+ querySchema: GetTraceV1Query,+ responseSchema: GetTraceV1Response,+ fn: async ({ query, auth }) => {+ const trace = await getTraceById({+ traceId: query.traceId,+ projectId: auth.scope.projectId,+ });++ return transformTraceToApiResponse(trace);+ },+});+```++---++## Authentication Patterns++### tRPC Authentication (NextAuth)++tRPC uses NextAuth sessions stored in JWT cookies:++```typescript+// Context creation with session+export const createTRPCContext = async (opts: CreateNextContextOptions) => {+ const { req, res } = opts;+ const session = await getServerAuthSession({ req, res });++ addUserToSpan({+ userId: session?.user?.id,+ email: session?.user?.email ?? undefined,+ });++ return {+ session,+ headers: req.headers,+ prisma,+ DB,+ };+};+```++**Session types:**++```typescript+// Base authenticated context+export type AuthedContext = {+ session: { user: NonNullable<Session["user"]> };+};++// Project-scoped context+export type ProjectAuthedContext = {+ session: AuthedContext["session"] & {+ orgId: string;+ orgRole: Role;+ projectId: string;+ projectRole: Role;+ };+};+```++### Public API Authentication++Public APIs use **Basic Auth** with API keys:++```typescript+async function verifyBasicAuth(authHeader: string | undefined) {+ const regularAuth = await new ApiAuthService(prisma, redis)+ .verifyAuthHeaderAndReturnScope(authHeader);++ if (!regularAuth.validKey) {+ throw { status: 401, message: regularAuth.error };+ }++ if (regularAuth.scope.accessLevel !== "project") {+ throw { status: 401, message: "Access denied - need basic auth with secret key" };+ }++ return regularAuth;+}+```++**Admin API Key Authentication** (self-hosted only):++```typescript+async function verifyAdminApiKeyAuth(req: NextApiRequest) {+ // Requires:+ // 1. Authorization: Bearer <ADMIN_API_KEY>+ // 2. x-langfuse-admin-api-key: <ADMIN_API_KEY>+ // 3. x-langfuse-project-id: <project-id>++ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {+ throw { status: 403, message: "Admin API key auth not available on Langfuse Cloud" };+ }++ const adminApiKey = env.ADMIN_API_KEY;+ const bearerToken = req.headers.authorization?.replace("Bearer ", "");+ const adminApiKeyHeader = req.headers["x-langfuse-admin-api-key"];++ // Timing-safe comparison+ const isValid =+ crypto.timingSafeEqual(Buffer.from(bearerToken), Buffer.from(adminApiKey)) &&+ crypto.timingSafeEqual(Buffer.from(adminApiKeyHeader), Buffer.from(adminApiKey));++ if (!isValid) throw { status: 401, message: "Invalid admin API key" };++ const projectId = req.headers["x-langfuse-project-id"];+ const project = await prisma.project.findUnique({ where: { id: projectId } });++ if (!project) throw { status: 404, message: "Project not found" };++ return { validKey: true, scope: { projectId, accessLevel: "project" } };+}+```++---++## Error Handling Middleware++### tRPC Error Transformation++All tRPC errors go through `withErrorHandling` middleware:++**Error types handled:**++1. **ClickHouseResourceError** β `SERVICE_UNAVAILABLE` (524)+2. **BaseError** β Preserves httpCode and message+3. **5xx errors** β Sanitized as "Internal error" (hides stack traces)+4. **4xx errors** β Original error message preserved++**Example:**++```typescript+if (!res.ok) {+ if (res.error.cause instanceof ClickHouseResourceError) {+ res.error = new TRPCError({+ code: "SERVICE_UNAVAILABLE",+ message: ClickHouseResourceError.ERROR_ADVICE_MESSAGE,+ });+ } else {+ const { code, httpStatus } = resolveError(res.error);+ const isSafeToExpose = httpStatus >= 400 && httpStatus < 500;++ res.error = new TRPCError({+ code,+ cause: null,+ message: isSafeToExpose ? res.error.message : "Internal error.",+ });+ }+}+```++### Public API Error Handling++Public API uses `withMiddlewares` for error handling:++```typescript+catch (error) {+ // 1. BaseError (custom application errors)+ if (error instanceof BaseError) {+ if (error.httpCode >= 500) traceException(error);+ return res.status(error.httpCode).json({+ message: error.message,+ error: error.name,+ });+ }++ // 2. ClickHouseResourceError (query timeouts, memory limits)+ if (error instanceof ClickHouseResourceError) {+ return res.status(524).json({+ message: ClickHouseResourceError.ERROR_ADVICE_MESSAGE,+ error: "Request is taking too long to process.",+ });+ }++ // 3. Zod validation errors+ if (isZodError(error)) {+ return res.status(400).json({+ message: "Invalid request data",+ error: error.issues,+ });+ }++ // 4. Prisma errors+ if (isPrismaException(error)) {+ traceException(error);+ return res.status(500).json({+ message: "Internal Server Error",+ error: "An unknown error occurred",+ });+ }++ // 5. Unknown errors+ traceException(error);+ return res.status(500).json({+ message: "Internal Server Error",+ error: error instanceof Error ? error.message : "Unknown error",+ });+}+```++---++## OpenTelemetry Instrumentation++All requests (tRPC and public API) propagate OpenTelemetry context with Langfuse-specific baggage.++### Context Propagation Pattern++```typescript+import { contextWithLangfuseProps } from "@langfuse/shared/src/server";+import * as opentelemetry from "@opentelemetry/api";++// Create context with Langfuse baggage+const ctx = contextWithLangfuseProps({+ headers: req.headers,+ userId: session?.user?.id,+ projectId: input?.projectId,+});++// Execute with context+return opentelemetry.context.with(ctx, async () => {+ // All instrumented code inside here will have access to baggage+ return await handler();+});+```++**Baggage includes:**+- `userId` - User ID from session+- `projectId` - Project ID from input+- `headers` - Request headers for trace propagation++### tRPC Instrumentation++```typescript+const withOtelInstrumentation = t.middleware(async (opts) => {+ const actualInput = await opts.getRawInput();++ const baggageCtx = contextWithLangfuseProps({+ headers: opts.ctx.headers,+ userId: opts.ctx.session?.user?.id,+ projectId: (actualInput as Record<string, string>)?.projectId,+ });++ return opentelemetry.context.with(baggageCtx, () => opts.next());+});++// Used with Baselime tracing+const withOtelTracingProcedure = t.procedure+ .use(withOtelInstrumentation)+ .use(tracing({ collectInput: true, collectResult: true }));+```++---++## Composable Procedures++tRPC procedures are composed by chaining middleware:++### Composition Pattern++```typescript+// Base procedure with tracing + error handling+const baseProcedure = withOtelTracingProcedure.use(withErrorHandling);++// Add authentication+const authedProcedure = baseProcedure.use(enforceUserIsAuthed);++// Add project scoping+const projectProcedure = authedProcedure.use(enforceUserIsAuthedAndProjectMember);+```++### Using Procedures in Routers++```typescript+import { protectedProjectProcedure } from "@/src/server/api/trpc";++export const tracesRouter = createTRPCRouter({+ // Input automatically validated against Zod schema+ all: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ page: z.number().optional(),+ limit: z.number().optional(),+ })+ )+ .query(async ({ input, ctx }) => {+ // ctx.session.projectId is guaranteed to exist+ // ctx.session.projectRole contains user's role++ const traces = await getTraces({+ projectId: input.projectId,+ page: input.page ?? 0,+ limit: input.limit ?? 50,+ });++ return traces;+ }),++ byId: protectedGetTraceProcedure+ .input(+ z.object({+ traceId: z.string(),+ projectId: z.string(),+ timestamp: z.date().nullish(),+ })+ )+ .query(async ({ input, ctx }) => {+ // ctx.trace is guaranteed to exist (fetched by middleware)+ // No need to refetch+ return ctx.trace;+ }),+});+```++### Middleware Execution Order++Middleware executes in the order it's chained:++```typescript+protectedProjectProcedure+ .use(withErrorHandling) // 1. Wraps entire execution+ .use(enforceUserIsAuthed) // 2. Validates session exists+ .use(enforceUserIsAuthedAndProjectMember) // 3. Validates project membership+ .input(schema) // 4. Validates input+ .query(async ({ input, ctx }) => { // 5. Executes query+ // ...+ });+```++**Context enrichment:**++Each middleware can enrich the context:++```typescript+// After enforceUserIsAuthed:+ctx.session.user // NonNullable<User>++// After enforceUserIsAuthedAndProjectMember:+ctx.session.projectId // string+ctx.session.projectRole // Role (OWNER | ADMIN | MEMBER | VIEWER)+ctx.session.orgId // string+ctx.session.orgRole // Role++// After enforceTraceAccess:+ctx.trace // TraceRecord (pre-fetched)+```++---++**Related Files:**++- [SKILL.md](../SKILL.md) - Main backend development guidelines+- [architecture-overview.md](architecture-overview.md) - System architecture+- [async-and-errors.md](async-and-errors.md) - Error handling patternsdiff --git a/.claude/skills/backend-dev-guidelines/resources/routing-and-controllers.md b/.claude/skills/backend-dev-guidelines/resources/routing-and-controllers.mdnew file mode 100644index 0000000000..99fec4c5d6--- /dev/null+++ b/.claude/skills/backend-dev-guidelines/resources/routing-and-controllers.md@@ -0,0 +1,844 @@+# Routing Patterns - Next.js & tRPC++Complete guide to routing and separation of concerns in Langfuse's Next.js + tRPC architecture.++## Table of Contents++- [Architecture Overview](#architecture-overview)+- [tRPC Routers](#trpc-routers)+- [Public REST API Routes](#public-rest-api-routes)+- [Service Layer](#service-layer)+- [Repository Layer](#repository-layer)+- [Separation of Concerns](#separation-of-concerns)+- [Anti-Patterns](#anti-patterns)++---++## Architecture Overview++Langfuse uses a **layered architecture** with clear separation of concerns:++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β ENTRY POINTS β+β ββββββββββββββββββββββββ βββββββββββββββββββββββββββ β+β β tRPC Procedures β β Public REST API Routes β β+β β (Internal UI API) β β (SDK/External API) β β+β ββββββββββββββββββββββββ βββββββββββββββββββββββββββ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ βΌ+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β SERVICE LAYER β+β Business logic, orchestration, validation β+β web/src/features/*/server/ or packages/shared/services/ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ βΌ+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β REPOSITORY LAYER β+β Complex queries, data transformation β+β packages/shared/src/server/repositories/ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ βΌ+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β DATABASE LAYER β+β PostgreSQL (Prisma) + ClickHouse (Direct Client) β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++### Key Principles++**Entry Points (Routes/Procedures):**+- β Define routing and procedure signatures+- β Handle authentication/authorization (via middleware)+- β Validate input (Zod schemas)+- β Delegate to services+- β Return responses++**Entry Points should NEVER:**+- β Contain business logic+- β Access database directly+- β Perform complex data transformations+- β Make direct repository calls (use services)++**Services:**+- β Contain business logic+- β Orchestrate multiple operations+- β Call repositories or Prisma/ClickHouse+- β Handle complex workflows+- β Should NOT know about HTTP, tRPC, or request/response objects++**Repositories:**+- β Complex database queries+- β Data transformation (DB β domain models)+- β ClickHouse query builders+- β Reusable query logic+- β Should NOT contain business logic++---++## tRPC Routers++**Location:** `web/src/server/api/routers/`++tRPC routers define type-safe procedures for the internal UI. Each router groups related operations.++### Router Structure++**File:** `web/src/server/api/routers/scores.ts`++```typescript+import { z } from "zod/v4";+import { createTRPCRouter, protectedProjectProcedure } from "@/src/server/api/trpc";+import { paginationZod, singleFilter, orderBy } from "@langfuse/shared";+import {+ getScoresUiTable,+ getScoresUiCount,+ upsertScore,+} from "@langfuse/shared/src/server";++const ScoreAllOptions = z.object({+ projectId: z.string(),+ filter: z.array(singleFilter),+ orderBy: orderBy,+ ...paginationZod,+});++export const scoresRouter = createTRPCRouter({+ /**+ * Get all scores for a project+ */+ all: protectedProjectProcedure+ .input(ScoreAllOptions)+ .query(async ({ input, ctx }) => {+ // Delegate to repository for data fetching+ const clickhouseScoreData = await getScoresUiTable({+ projectId: input.projectId,+ filter: input.filter ?? [],+ orderBy: input.orderBy,+ limit: input.limit,+ offset: input.page * input.limit,+ });++ // Delegate to Prisma for related data+ const [jobExecutions, users] = await Promise.all([+ ctx.prisma.jobExecution.findMany({+ where: {+ jobOutputScoreId: {+ in: clickhouseScoreData.map((score) => score.id),+ },+ },+ }),+ ctx.prisma.user.findMany({+ where: {+ id: {+ in: clickhouseScoreData+ .map((s) => s.authorUserId)+ .filter((id): id is string => id !== null),+ },+ },+ }),+ ]);++ // Transform and combine data+ return clickhouseScoreData.map((score) => ({+ ...score,+ jobConfigurationId:+ jobExecutions.find((j) => j.jobOutputScoreId === score.id)+ ?.jobConfigurationId ?? null,+ authorUserImage:+ users.find((u) => u.id === score.authorUserId)?.image ?? null,+ authorUserName:+ users.find((u) => u.id === score.authorUserId)?.name ?? null,+ }));+ }),++ /**+ * Create or update score+ */+ createAnnotationScore: protectedProjectProcedure+ .input(CreateAnnotationScoreData)+ .mutation(async ({ input, ctx }) => {+ // Validation+ validateConfigAgainstBody(input);++ // Delegate to repository+ await upsertScore({+ id: input.id ?? randomUUID(),+ traceId: input.traceId,+ projectId: input.projectId,+ name: input.name,+ value: input.value,+ source: ScoreSource.ANNOTATION,+ authorUserId: ctx.session.user.id,+ comment: input.comment,+ });++ // Audit log+ await auditLog({+ session: ctx.session,+ resourceType: "score",+ resourceId: input.id,+ action: "create",+ });++ return { success: true };+ }),+});+```++**Key Points:**+- Use appropriate procedure type (`protectedProjectProcedure`, `authenticatedProcedure`, etc.)+- Define input schema with Zod (`.input()`)+- Use `.query()` for reads, `.mutation()` for writes+- Delegate to services/repositories for data access+- Keep procedures thin - no business logic+- Type-safe throughout (TypeScript infers types from Zod schemas)++### Registering Routers++**File:** `web/src/server/api/root.ts`++```typescript+import { createTRPCRouter } from "@/src/server/api/trpc";+import { scoresRouter } from "./routers/scores";+import { tracesRouter } from "./routers/traces";+import { dashboardRouter } from "@/src/features/dashboard/server/dashboard-router";++export const appRouter = createTRPCRouter({+ scores: scoresRouter,+ traces: tracesRouter,+ dashboard: dashboardRouter,+ // ... other routers+});++export type AppRouter = typeof appRouter;+```++**Calling from frontend:**++```typescript+// Type-safe client call+const { data, isLoading } = api.scores.all.useQuery({+ projectId: "proj_123",+ page: 0,+ limit: 50,+ filter: [],+ orderBy: null,+});+```++---++## Public REST API Routes++**Location:** `web/src/pages/api/public/`++Public API routes use **Next.js file-based routing** and provide REST endpoints for SDKs and external integrations.++### File-based Routing++Next.js uses file system for routing:++```+web/src/pages/api/public/+βββ scores/+β βββ index.ts β GET/POST /api/public/scores+β βββ [scoreId].ts β GET/PATCH/DELETE /api/public/scores/:scoreId+βββ traces/+β βββ index.ts β GET /api/public/traces+β βββ [traceId].ts β GET /api/public/traces/:traceId+βββ datasets/+ βββ [name]/+ βββ index.ts β GET/POST /api/public/datasets/:name+ βββ items/+ βββ index.ts β GET /api/public/datasets/:name/items+```++**Dynamic routes:**+- `[param].ts` β Single dynamic segment (e.g., `/api/public/scores/[scoreId].ts`)+- `[...param].ts` β Catch-all route (e.g., `/api/public/[...path].ts`)++### REST API Pattern++**File:** `web/src/pages/api/public/scores/index.ts`++```typescript+import { v4 } from "uuid";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";+import {+ GetScoresQueryV1,+ GetScoresResponseV1,+ PostScoresBodyV1,+ PostScoresResponseV1,+} from "@langfuse/shared";+import { eventTypes, processEventBatch } from "@langfuse/shared/src/server";+import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";++export default withMiddlewares({+ // POST /api/public/scores+ POST: createAuthedProjectAPIRoute({+ name: "Create Score",+ bodySchema: PostScoresBodyV1,+ responseSchema: PostScoresResponseV1,+ fn: async ({ body, auth, res }) => {+ const event = {+ id: v4(),+ type: eventTypes.SCORE_CREATE,+ timestamp: new Date().toISOString(),+ body,+ };++ if (!event.body.id) {+ event.body.id = v4();+ }++ const result = await processEventBatch([event], auth);++ if (result.errors.length > 0) {+ const error = result.errors[0];+ res.status(error.status).json({+ message: error.error ?? error.message,+ });+ return { id: "" };+ }++ return { id: event.body.id };+ },+ }),++ // GET /api/public/scores+ GET: createAuthedProjectAPIRoute({+ name: "Get Scores",+ querySchema: GetScoresQueryV1,+ responseSchema: GetScoresResponseV1,+ fn: async ({ query, auth }) => {+ const scoresApiService = new ScoresApiService("v1");++ const [items, count] = await Promise.all([+ scoresApiService.generateScoresForPublicApi({+ projectId: auth.scope.projectId,+ page: query.page,+ limit: query.limit,+ userId: query.userId,+ name: query.name,+ }),+ scoresApiService.getScoresCountForPublicApi({+ projectId: auth.scope.projectId,+ userId: query.userId,+ name: query.name,+ }),+ ]);++ return {+ data: items,+ meta: {+ page: query.page,+ limit: query.limit,+ totalItems: count,+ totalPages: Math.ceil(count / query.limit),+ },+ };+ },+ }),+});+```++**Key Points:**+- Use `withMiddlewares` for all public API routes (provides CORS, error handling, OpenTelemetry)+- Use `createAuthedProjectAPIRoute` for authenticated endpoints (handles auth, rate limiting, validation)+- Define separate handlers for each HTTP method+- Input/output validated with Zod schemas+- Delegate to services for business logic++### Simple Public Routes++For routes that don't need authentication:++```typescript+// web/src/pages/api/public/health.ts+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";++export default withMiddlewares({+ GET: async (req, res) => {+ res.status(200).json({ status: "ok" });+ },+});+```++---++## Service Layer++**Location:** `web/src/features/*/server/` or `packages/shared/src/server/services/`++Services contain business logic and orchestrate operations. They're called by tRPC procedures and API routes.++### Service Pattern++**File:** `web/src/features/public-api/server/scores-api-service.ts`++```typescript+import {+ _handleGenerateScoresForPublicApi,+ _handleGetScoresCountForPublicApi,+ type ScoreQueryType,+} from "@/src/features/public-api/server/scores";+import { _handleGetScoreById } from "@langfuse/shared/src/server";++export class ScoresApiService {+ constructor(private readonly apiVersion: "v1" | "v2") {}++ /**+ * Get a specific score by ID+ */+ async getScoreById({+ projectId,+ scoreId,+ source,+ }: {+ projectId: string;+ scoreId: string;+ source?: ScoreSourceType;+ }) {+ return _handleGetScoreById({+ projectId,+ scoreId,+ source,+ scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",+ preferredClickhouseService: "ReadOnly",+ });+ }++ /**+ * Get list of scores with version-aware filtering+ */+ async generateScoresForPublicApi(props: ScoreQueryType) {+ return _handleGenerateScoresForPublicApi({+ props,+ scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",+ });+ }++ /**+ * Get count of scores with version-aware filtering+ */+ async getScoresCountForPublicApi(props: ScoreQueryType) {+ return _handleGetScoresCountForPublicApi({+ props,+ scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",+ });+ }+}+```++**Key Points:**+- Services contain business logic, not routing logic+- Services should NOT import tRPC or Next.js types+- Services can call repositories, Prisma, ClickHouse directly+- Services orchestrate multiple operations+- Services are reusable across tRPC and public API++### Where to Put Services++**Feature-specific services:**+```+web/src/features/+βββ datasets/+β βββ server/+β βββ dataset-service.ts+βββ evals/+β βββ server/+β βββ eval-service.ts+βββ public-api/+ βββ server/+ βββ scores-api-service.ts+```++**Shared services:**+```+packages/shared/src/server/services/+βββ SlackService.ts+βββ DashboardService/+βββ StorageService.ts+βββ DefaultEvaluationModelService/+```++---++## Repository Layer++**Location:** `packages/shared/src/server/repositories/`++Repositories handle complex database queries, data transformation, and provide reusable query logic.++### Repository Structure++```+packages/shared/src/server/repositories/+βββ traces.ts # Trace queries (ClickHouse)+βββ observations.ts # Observation queries (ClickHouse)+βββ scores.ts # Score queries (ClickHouse)+βββ clickhouse.ts # Core ClickHouse helpers+βββ definitions.ts # Type definitions+```++### Repository Pattern++**File:** `packages/shared/src/server/repositories/traces.ts`++```typescript+import { queryClickhouse, upsertClickhouse } from "./clickhouse";+import { TraceRecordReadType } from "./definitions";+import { convertClickhouseToDomain } from "./traces_converters";++/**+ * Get traces by IDs+ */+export const getTracesByIds = async (+ projectId: string,+ traceIds: string[]+): Promise<TraceRecordReadType[]> => {+ const rows = await queryClickhouse<TraceRecordReadType>({+ query: `+ SELECT *+ FROM traces+ WHERE project_id = {projectId: String}+ AND id IN ({traceIds: Array(String)})+ ORDER BY event_ts DESC+ LIMIT 1 BY id, project_id+ `,+ params: { projectId, traceIds },+ tags: { feature: "tracing", type: "trace" },+ });++ return rows.map(convertClickhouseToDomain);+};++/**+ * Upsert trace to ClickHouse+ */+export const upsertTrace = async (+ trace: TraceRecordInsertType+): Promise<void> => {+ await upsertClickhouse({+ table: "traces",+ records: [trace],+ eventBodyMapper: (body) => ({+ id: body.id,+ name: body.name,+ user_id: body.user_id,+ // ... map fields+ }),+ tags: { feature: "ingestion", type: "trace" },+ });+};+```++**Key Points:**+- Use `queryClickhouse` for SELECT queries+- Use `upsertClickhouse` for INSERT/UPDATE+- Use `commandClickhouse` for DDL (ALTER TABLE, etc.)+- Include data converters (`convertClickhouseToDomain`)+- Add OpenTelemetry tags for observability+- Repositories should NOT contain business logic++### When to Use Repositories++β **Use repositories for:**+- Complex ClickHouse queries with CTEs, joins, aggregations+- Queries used in multiple places (DRY principle)+- Data transformation from DB types to domain models+- Streaming large result sets++β **Use direct Prisma/ClickHouse for:**+- Simple CRUD operations+- One-off queries+- Prototyping (can refactor to repository later)++---++## Separation of Concerns++### β Good Example: Proper Layering++**tRPC Procedure (Entry Point):**++```typescript+// web/src/server/api/routers/scores.ts+export const scoresRouter = createTRPCRouter({+ all: protectedProjectProcedure+ .input(ScoreFilterOptions)+ .query(async ({ input }) => {+ // β Thin procedure - delegates to repository+ return await getScoresUiTable({+ projectId: input.projectId,+ filter: input.filter,+ orderBy: input.orderBy,+ });+ }),++ create: protectedProjectProcedure+ .input(CreateScoreInput)+ .mutation(async ({ input, ctx }) => {+ // β Delegates to service for orchestration+ return await createScoreWithValidation({+ scoreData: input,+ userId: ctx.session.user.id,+ projectId: ctx.session.projectId,+ });+ }),+});+```++**Service (Business Logic):**++```typescript+// web/src/features/scores/server/score-service.ts+export async function createScoreWithValidation({+ scoreData,+ userId,+ projectId,+}: {+ scoreData: CreateScoreInput;+ userId: string;+ projectId: string;+}) {+ // β Business logic: validation+ const config = await prisma.scoreConfig.findUnique({+ where: { id: scoreData.configId },+ });++ if (!config) {+ throw new LangfuseNotFoundError("Score config not found");+ }++ validateConfigAgainstBody(config, scoreData);++ // β Business logic: orchestration+ const scoreId = randomUUID();++ await Promise.all([+ // Create score in ClickHouse+ upsertScore({+ id: scoreId,+ projectId,+ traceId: scoreData.traceId,+ name: scoreData.name,+ value: scoreData.value,+ authorUserId: userId,+ }),+ // Audit log in PostgreSQL+ auditLog({+ userId,+ resourceType: "score",+ resourceId: scoreId,+ action: "create",+ }),+ ]);++ return { id: scoreId };+}+```++**Repository (Data Access):**++```typescript+// packages/shared/src/server/repositories/scores.ts+export const upsertScore = async (+ score: ScoreInsertType+): Promise<void> => {+ // β Pure data access - no business logic+ await upsertClickhouse({+ table: "scores",+ records: [score],+ eventBodyMapper: (body) => ({+ id: body.id,+ trace_id: body.traceId,+ name: body.name,+ value: body.value,+ author_user_id: body.authorUserId,+ }),+ tags: { feature: "scoring" },+ });+};+```++### Why This Works++1. **tRPC Procedure**: Thin, delegates to service+2. **Service**: Contains all business logic (validation, orchestration)+3. **Repository**: Pure data access, reusable+4. **Service is protocol-agnostic**: Can be called from tRPC, public API, or worker+5. **Clear separation**: Easy to test, maintain, extend++---++## Anti-Patterns++### β Anti-Pattern 1: Business Logic in Routes++**Bad:**++```typescript+// β BAD: Business logic in tRPC procedure+export const scoresRouter = createTRPCRouter({+ create: protectedProjectProcedure+ .input(CreateScoreInput)+ .mutation(async ({ input, ctx }) => {+ // β Validation logic in route+ const config = await ctx.prisma.scoreConfig.findUnique({+ where: { id: input.configId },+ });++ if (!config) {+ throw new TRPCError({ code: "NOT_FOUND" });+ }++ if (config.dataType === "NUMERIC" && typeof input.value !== "number") {+ throw new TRPCError({ code: "BAD_REQUEST" });+ }++ // β Direct database access+ await ctx.prisma.score.create({+ data: {+ id: randomUUID(),+ projectId: ctx.session.projectId,+ traceId: input.traceId,+ name: input.name,+ value: input.value,+ },+ });++ // β More business logic+ await auditLog({ ... });++ return { success: true };+ }),+});+```++**Why it's bad:**+- Business logic tied to tRPC (can't reuse in public API)+- Hard to test (need to mock tRPC context)+- No separation of concerns+- Difficult to maintain++**Good:**++```typescript+// β GOOD: Thin procedure, delegates to service+export const scoresRouter = createTRPCRouter({+ create: protectedProjectProcedure+ .input(CreateScoreInput)+ .mutation(async ({ input, ctx }) => {+ return await createScoreWithValidation({+ scoreData: input,+ userId: ctx.session.user.id,+ projectId: ctx.session.projectId,+ });+ }),+});+```++### β Anti-Pattern 2: Database Calls in Routes++**Bad:**++```typescript+// β BAD: Direct database access in route+export default withMiddlewares({+ GET: createAuthedProjectAPIRoute({+ name: "Get Scores",+ fn: async ({ auth }) => {+ // β Direct ClickHouse query in route+ const scores = await queryClickhouse({+ query: "SELECT * FROM scores WHERE project_id = {projectId: String}",+ params: { projectId: auth.scope.projectId },+ });++ return { data: scores };+ },+ }),+});+```++**Good:**++```typescript+// β GOOD: Delegates to service or repository+export default withMiddlewares({+ GET: createAuthedProjectAPIRoute({+ name: "Get Scores",+ fn: async ({ auth, query }) => {+ const scoresService = new ScoresApiService("v1");++ return await scoresService.generateScoresForPublicApi({+ projectId: auth.scope.projectId,+ page: query.page,+ limit: query.limit,+ });+ },+ }),+});+```++### β Anti-Pattern 3: Business Logic in Repositories++**Bad:**++```typescript+// β BAD: Business logic in repository+export const upsertScore = async (+ score: ScoreInsertType+): Promise<void> => {+ // β Validation in repository+ if (!score.name) {+ throw new Error("Score name is required");+ }++ // β Authorization check in repository+ const project = await prisma.project.findUnique({+ where: { id: score.projectId },+ });++ if (!project) {+ throw new Error("Project not found");+ }++ // β Side effects in repository+ await auditLog({ ... });++ await upsertClickhouse({ ... });+};+```++**Good:**++```typescript+// β GOOD: Pure data access, no business logic+export const upsertScore = async (+ score: ScoreInsertType+): Promise<void> => {+ await upsertClickhouse({+ table: "scores",+ records: [score],+ eventBodyMapper: (body) => ({+ id: body.id,+ trace_id: body.traceId,+ name: body.name,+ value: body.value,+ }),+ tags: { feature: "scoring" },+ });+};+```++---++**Related Files:**++- [SKILL.md](../SKILL.md) - Main backend development guidelines+- [architecture-overview.md](architecture-overview.md) - System architecture+- [middleware-guide.md](middleware-guide.md) - Middleware patterns+- [database-patterns.md](database-patterns.md) - Database access patternsdiff --git a/.claude/skills/backend-dev-guidelines/resources/services-and-repositories.md b/.claude/skills/backend-dev-guidelines/resources/services-and-repositories.mdnew file mode 100644index 0000000000..749b26b6d6--- /dev/null+++ b/.claude/skills/backend-dev-guidelines/resources/services-and-repositories.md@@ -0,0 +1,789 @@+# Services and Repositories - Business Logic Layer++Complete guide to organizing business logic with services and data access with repositories.++## Table of Contents++- [Service Layer Overview](#service-layer-overview)+- [Dependency Injection Pattern](#dependency-injection-pattern)+- [Singleton Pattern](#singleton-pattern)+- [Repository Pattern](#repository-pattern)+- [Service Design Principles](#service-design-principles)+- [Caching Strategies](#caching-strategies)+- [Testing Services](#testing-services)++---++## Service Layer Overview++### Purpose of Services++**Services contain business logic** - the 'what' and 'why' of your application:++```+Controller asks: "Should I do this?"+Service answers: "Yes/No, here's why, and here's what happens"+Repository executes: "Here's the data you requested"+```++**Services are responsible for:**+- β Business rules enforcement+- β Orchestrating multiple repositories+- β Transaction management+- β Complex calculations+- β External service integration+- β Business validations++**Services should NOT:**+- β Know about HTTP (Request/Response)+- β Direct Prisma access (use repositories)+- β Handle route-specific logic+- β Format HTTP responses++---++## Dependency Injection Pattern++### Why Dependency Injection?++**Benefits:**+- Easy to test (inject mocks)+- Clear dependencies+- Flexible configuration+- Promotes loose coupling++### Excellent Example: NotificationService++**File:** `/blog-api/src/services/NotificationService.ts`++```typescript+// Define dependencies interface for clarity+export interface NotificationServiceDependencies {+ prisma: PrismaClient;+ batchingService: BatchingService;+ emailComposer: EmailComposer;+}++// Service with dependency injection+export class NotificationService {+ private prisma: PrismaClient;+ private batchingService: BatchingService;+ private emailComposer: EmailComposer;+ private preferencesCache: Map<string, { preferences: UserPreference; timestamp: number }> = new Map();+ private CACHE_TTL = (notificationConfig.preferenceCacheTTLMinutes || 5) * 60 * 1000;++ // Dependencies injected via constructor+ constructor(dependencies: NotificationServiceDependencies) {+ this.prisma = dependencies.prisma;+ this.batchingService = dependencies.batchingService;+ this.emailComposer = dependencies.emailComposer;+ }++ /**+ * Create a notification and route it appropriately+ */+ async createNotification(params: CreateNotificationParams) {+ const { recipientID, type, title, message, link, context = {}, channel = 'both', priority = NotificationPriority.NORMAL } = params;++ try {+ // Get template and render content+ const template = getNotificationTemplate(type);+ const rendered = renderNotificationContent(template, context);++ // Create in-app notification record+ const notificationId = await createNotificationRecord({+ instanceId: parseInt(context.instanceId || '0', 10),+ template: type,+ recipientUserId: recipientID,+ channel: channel === 'email' ? 'email' : 'inApp',+ contextData: context,+ title: finalTitle,+ message: finalMessage,+ link: finalLink,+ });++ // Route notification based on channel+ if (channel === 'email' || channel === 'both') {+ await this.routeNotification({+ notificationId,+ userId: recipientID,+ type,+ priority,+ title: finalTitle,+ message: finalMessage,+ link: finalLink,+ context,+ });+ }++ return notification;+ } catch (error) {+ ErrorLogger.log(error, {+ context: {+ '[NotificationService] createNotification': {+ type: params.type,+ recipientID: params.recipientID,+ },+ },+ });+ throw error;+ }+ }++ /**+ * Route notification based on user preferences+ */+ private async routeNotification(params: { notificationId: number; userId: string; type: string; priority: NotificationPriority; title: string; message: string; link?: string; context?: Record<string, any> }) {+ // Get user preferences with caching+ const preferences = await this.getUserPreferences(params.userId);++ // Check if we should batch or send immediately+ if (this.shouldBatchEmail(preferences, params.type, params.priority)) {+ await this.batchingService.queueNotificationForBatch({+ notificationId: params.notificationId,+ userId: params.userId,+ userPreference: preferences,+ priority: params.priority,+ });+ } else {+ // Send immediately via EmailComposer+ await this.sendImmediateEmail({+ userId: params.userId,+ title: params.title,+ message: params.message,+ link: params.link,+ context: params.context,+ type: params.type,+ });+ }+ }++ /**+ * Determine if email should be batched+ */+ shouldBatchEmail(preferences: UserPreference, notificationType: string, priority: NotificationPriority): boolean {+ // HIGH priority always immediate+ if (priority === NotificationPriority.HIGH) {+ return false;+ }++ // Check batch mode+ const batchMode = preferences.emailBatchMode || BatchMode.IMMEDIATE;+ return batchMode !== BatchMode.IMMEDIATE;+ }++ /**+ * Get user preferences with caching+ */+ async getUserPreferences(userId: string): Promise<UserPreference> {+ // Check cache first+ const cached = this.preferencesCache.get(userId);+ if (cached && Date.now() - cached.timestamp < this.CACHE_TTL) {+ return cached.preferences;+ }++ const preference = await this.prisma.userPreference.findUnique({+ where: { userID: userId },+ });++ const finalPreferences = preference || DEFAULT_PREFERENCES;++ // Update cache+ this.preferencesCache.set(userId, {+ preferences: finalPreferences,+ timestamp: Date.now(),+ });++ return finalPreferences;+ }+}+```++**Usage in Controller:**++```typescript+// Instantiate with dependencies+const notificationService = new NotificationService({+ prisma: PrismaService.main,+ batchingService: new BatchingService(PrismaService.main),+ emailComposer: new EmailComposer(),+});++// Use in controller+const notification = await notificationService.createNotification({+ recipientID: 'user-123',+ type: 'AFRLWorkflowNotification',+ context: { workflowName: 'AFRL Monthly Report' },+});+```++**Key Takeaways:**+- Dependencies passed via constructor+- Clear interface defines required dependencies+- Easy to test (inject mocks)+- Encapsulated caching logic+- Business rules isolated from HTTP++---++## Singleton Pattern++### When to Use Singletons++**Use for:**+- Services with expensive initialization+- Services with shared state (caching)+- Services accessed from many places+- Permission services+- Configuration services++### Example: PermissionService (Singleton)++**File:** `/blog-api/src/services/permissionService.ts`++```typescript+import { PrismaClient } from '@prisma/client';++class PermissionService {+ private static instance: PermissionService;+ private prisma: PrismaClient;+ private permissionCache: Map<string, { canAccess: boolean; timestamp: number }> = new Map();+ private CACHE_TTL = 5 * 60 * 1000; // 5 minutes++ // Private constructor prevents direct instantiation+ private constructor() {+ this.prisma = PrismaService.main;+ }++ // Get singleton instance+ public static getInstance(): PermissionService {+ if (!PermissionService.instance) {+ PermissionService.instance = new PermissionService();+ }+ return PermissionService.instance;+ }++ /**+ * Check if user can complete a workflow step+ */+ async canCompleteStep(userId: string, stepInstanceId: number): Promise<boolean> {+ const cacheKey = `${userId}:${stepInstanceId}`;++ // Check cache+ const cached = this.permissionCache.get(cacheKey);+ if (cached && Date.now() - cached.timestamp < this.CACHE_TTL) {+ return cached.canAccess;+ }++ try {+ const post = await this.prisma.post.findUnique({+ where: { id: postId },+ include: {+ author: true,+ comments: {+ include: {+ user: true,+ },+ },+ },+ });++ if (!post) {+ return false;+ }++ // Check if user has permission+ const canEdit = post.authorId === userId ||+ await this.isUserAdmin(userId);++ // Cache result+ this.permissionCache.set(cacheKey, {+ canAccess: isAssigned,+ timestamp: Date.now(),+ });++ return isAssigned;+ } catch (error) {+ console.error('[PermissionService] Error checking step permission:', error);+ return false;+ }+ }++ /**+ * Clear cache for user+ */+ clearUserCache(userId: string): void {+ for (const [key] of this.permissionCache) {+ if (key.startsWith(`${userId}:`)) {+ this.permissionCache.delete(key);+ }+ }+ }++ /**+ * Clear all cache+ */+ clearCache(): void {+ this.permissionCache.clear();+ }+}++// Export singleton instance+export const permissionService = PermissionService.getInstance();+```++**Usage:**++```typescript+import { permissionService } from '../services/permissionService';++// Use anywhere in the codebase+const canComplete = await permissionService.canCompleteStep(userId, stepId);++if (!canComplete) {+ throw new ForbiddenError('You do not have permission to complete this step');+}+```++---++## Repository Pattern++### Purpose of Repositories++**Repositories abstract data access** - the 'how' of data operations:++```+Service: "Get me all active users sorted by name"+Repository: "Here's the Prisma query that does that"+```++**Repositories are responsible for:**+- β All Prisma operations+- β Query construction+- β Query optimization (select, include)+- β Database error handling+- β Caching database results++**Repositories should NOT:**+- β Contain business logic+- β Know about HTTP+- β Make decisions (that's service layer)++### Repository Template++```typescript+// repositories/UserRepository.ts+import { PrismaService } from '@project-lifecycle-portal/database';+import type { User, Prisma } from '@project-lifecycle-portal/database';++export class UserRepository {+ /**+ * Find user by ID with optimized query+ */+ async findById(userId: string): Promise<User | null> {+ try {+ return await PrismaService.main.user.findUnique({+ where: { userID: userId },+ select: {+ userID: true,+ email: true,+ name: true,+ isActive: true,+ roles: true,+ createdAt: true,+ updatedAt: true,+ },+ });+ } catch (error) {+ console.error('[UserRepository] Error finding user by ID:', error);+ throw new Error(`Failed to find user: ${userId}`);+ }+ }++ /**+ * Find all active users+ */+ async findActive(options?: { orderBy?: Prisma.UserOrderByWithRelationInput }): Promise<User[]> {+ try {+ return await PrismaService.main.user.findMany({+ where: { isActive: true },+ orderBy: options?.orderBy || { name: 'asc' },+ select: {+ userID: true,+ email: true,+ name: true,+ roles: true,+ },+ });+ } catch (error) {+ console.error('[UserRepository] Error finding active users:', error);+ throw new Error('Failed to find active users');+ }+ }++ /**+ * Find user by email+ */+ async findByEmail(email: string): Promise<User | null> {+ try {+ return await PrismaService.main.user.findUnique({+ where: { email },+ });+ } catch (error) {+ console.error('[UserRepository] Error finding user by email:', error);+ throw new Error(`Failed to find user with email: ${email}`);+ }+ }++ /**+ * Create new user+ */+ async create(data: Prisma.UserCreateInput): Promise<User> {+ try {+ return await PrismaService.main.user.create({ data });+ } catch (error) {+ console.error('[UserRepository] Error creating user:', error);+ throw new Error('Failed to create user');+ }+ }++ /**+ * Update user+ */+ async update(userId: string, data: Prisma.UserUpdateInput): Promise<User> {+ try {+ return await PrismaService.main.user.update({+ where: { userID: userId },+ data,+ });+ } catch (error) {+ console.error('[UserRepository] Error updating user:', error);+ throw new Error(`Failed to update user: ${userId}`);+ }+ }++ /**+ * Delete user (soft delete by setting isActive = false)+ */+ async delete(userId: string): Promise<User> {+ try {+ return await PrismaService.main.user.update({+ where: { userID: userId },+ data: { isActive: false },+ });+ } catch (error) {+ console.error('[UserRepository] Error deleting user:', error);+ throw new Error(`Failed to delete user: ${userId}`);+ }+ }++ /**+ * Check if email exists+ */+ async emailExists(email: string): Promise<boolean> {+ try {+ const count = await PrismaService.main.user.count({+ where: { email },+ });+ return count > 0;+ } catch (error) {+ console.error('[UserRepository] Error checking email exists:', error);+ throw new Error('Failed to check if email exists');+ }+ }+}++// Export singleton instance+export const userRepository = new UserRepository();+```++**Using Repository in Service:**++```typescript+// services/userService.ts+import { userRepository } from '../repositories/UserRepository';+import { ConflictError, NotFoundError } from '../utils/errors';++export class UserService {+ /**+ * Create new user with business rules+ */+ async createUser(data: { email: string; name: string; roles: string[] }): Promise<User> {+ // Business rule: Check if email already exists+ const emailExists = await userRepository.emailExists(data.email);+ if (emailExists) {+ throw new ConflictError('Email already exists');+ }++ // Business rule: Validate roles+ const validRoles = ['admin', 'operations', 'user'];+ const invalidRoles = data.roles.filter((role) => !validRoles.includes(role));+ if (invalidRoles.length > 0) {+ throw new ValidationError(`Invalid roles: ${invalidRoles.join(', ')}`);+ }++ // Create user via repository+ return await userRepository.create({+ email: data.email,+ name: data.name,+ roles: data.roles,+ isActive: true,+ });+ }++ /**+ * Get user by ID+ */+ async getUser(userId: string): Promise<User> {+ const user = await userRepository.findById(userId);++ if (!user) {+ throw new NotFoundError(`User not found: ${userId}`);+ }++ return user;+ }+}+```++---++## Service Design Principles++### 1. Single Responsibility++Each service should have ONE clear purpose:++```typescript+// β GOOD - Single responsibility+class UserService {+ async createUser() {}+ async updateUser() {}+ async deleteUser() {}+}++class EmailService {+ async sendEmail() {}+ async sendBulkEmails() {}+}++// β BAD - Too many responsibilities+class UserService {+ async createUser() {}+ async sendWelcomeEmail() {} // Should be EmailService+ async logUserActivity() {} // Should be AuditService+ async processPayment() {} // Should be PaymentService+}+```++### 2. Clear Method Names++Method names should describe WHAT they do:++```typescript+// β GOOD - Clear intent+async createNotification()+async getUserPreferences()+async shouldBatchEmail()+async routeNotification()++// β BAD - Vague or misleading+async process()+async handle()+async doIt()+async execute()+```++### 3. Return Types++Always use explicit return types:++```typescript+// β GOOD - Explicit types+async createUser(data: CreateUserDTO): Promise<User> {}+async findUsers(): Promise<User[]> {}+async deleteUser(id: string): Promise<void> {}++// β BAD - Implicit any+async createUser(data) {} // No types!+```++### 4. Error Handling++Services should throw meaningful errors:++```typescript+// β GOOD - Meaningful errors+if (!user) {+ throw new NotFoundError(`User not found: ${userId}`);+}++if (emailExists) {+ throw new ConflictError('Email already exists');+}++// β BAD - Generic errors+if (!user) {+ throw new Error('Error'); // What error?+}+```++### 5. Avoid God Services++Don't create services that do everything:++```typescript+// β BAD - God service+class WorkflowService {+ async startWorkflow() {}+ async completeStep() {}+ async assignRoles() {}+ async sendNotifications() {} // Should be NotificationService+ async validatePermissions() {} // Should be PermissionService+ async logAuditTrail() {} // Should be AuditService+ // ... 50 more methods+}++// β GOOD - Focused services+class WorkflowService {+ constructor(+ private notificationService: NotificationService,+ private permissionService: PermissionService,+ private auditService: AuditService+ ) {}++ async startWorkflow() {+ // Orchestrate other services+ await this.permissionService.checkPermission();+ await this.workflowRepository.create();+ await this.notificationService.notify();+ await this.auditService.log();+ }+}+```++---++## Caching Strategies++### 1. In-Memory Caching++```typescript+class UserService {+ private cache: Map<string, { user: User; timestamp: number }> = new Map();+ private CACHE_TTL = 5 * 60 * 1000; // 5 minutes++ async getUser(userId: string): Promise<User> {+ // Check cache+ const cached = this.cache.get(userId);+ if (cached && Date.now() - cached.timestamp < this.CACHE_TTL) {+ return cached.user;+ }++ // Fetch from database+ const user = await userRepository.findById(userId);++ // Update cache+ if (user) {+ this.cache.set(userId, { user, timestamp: Date.now() });+ }++ return user;+ }++ clearUserCache(userId: string): void {+ this.cache.delete(userId);+ }+}+```++### 2. Cache Invalidation++```typescript+class UserService {+ async updateUser(userId: string, data: UpdateUserDTO): Promise<User> {+ // Update in database+ const user = await userRepository.update(userId, data);++ // Invalidate cache+ this.clearUserCache(userId);++ return user;+ }+}+```++---++## Testing Services++### Unit Tests++```typescript+// tests/userService.test.ts+import { UserService } from '../services/userService';+import { userRepository } from '../repositories/UserRepository';+import { ConflictError } from '../utils/errors';++// Mock repository+jest.mock('../repositories/UserRepository');++describe('UserService', () => {+ let userService: UserService;++ beforeEach(() => {+ userService = new UserService();+ jest.clearAllMocks();+ });++ describe('createUser', () => {+ it('should create user when email does not exist', async () => {+ // Arrange+ const userData = {+ email: '[email protected]',+ name: 'Test User',+ roles: ['user'],+ };++ (userRepository.emailExists as jest.Mock).mockResolvedValue(false);+ (userRepository.create as jest.Mock).mockResolvedValue({+ userID: '123',+ ...userData,+ });++ // Act+ const user = await userService.createUser(userData);++ // Assert+ expect(user).toBeDefined();+ expect(user.email).toBe(userData.email);+ expect(userRepository.emailExists).toHaveBeenCalledWith(userData.email);+ expect(userRepository.create).toHaveBeenCalled();+ });++ it('should throw ConflictError when email exists', async () => {+ // Arrange+ const userData = {+ email: '[email protected]',+ name: 'Test User',+ roles: ['user'],+ };++ (userRepository.emailExists as jest.Mock).mockResolvedValue(true);++ // Act & Assert+ await expect(userService.createUser(userData)).rejects.toThrow(ConflictError);+ expect(userRepository.create).not.toHaveBeenCalled();+ });+ });+});+```++---++**Related Files:**+- [SKILL.md](SKILL.md) - Main guide+- [routing-and-controllers.md](routing-and-controllers.md) - Controllers that use services+- [database-patterns.md](database-patterns.md) - Prisma and repository patterns+- [complete-examples.md](complete-examples.md) - Full service/repository examplesdiff --git a/.claude/skills/backend-dev-guidelines/resources/testing-guide.md b/.claude/skills/backend-dev-guidelines/resources/testing-guide.mdnew file mode 100644index 0000000000..4a69ca9c70--- /dev/null+++ b/.claude/skills/backend-dev-guidelines/resources/testing-guide.md@@ -0,0 +1,558 @@+# Testing Guide - Backend Testing Strategies++Complete guide to testing Langfuse backend services across web, worker, and shared packages.++## Table of Contents++- [Test Types Overview](#test-types-overview)+- [Integration Tests (Public API)](#integration-tests-public-api)+- [Service-Level Tests (Repository/Service)](#service-level-tests-repositoryservice)+- [tRPC Tests (Procedure Testing)](#trpc-tests-procedure-testing)+- [Worker Tests (Queue Processing)](#worker-tests-queue-processing)+- [Key Testing Principles](#key-testing-principles)+- [Running Tests](#running-tests)++---++## Test Types Overview++Langfuse uses multiple testing strategies for different layers:++| Test Type | Framework | Location | Purpose |+|-----------|-----------|----------|---------|+| Integration | Jest | `web/src/__tests__/async/` | Full API endpoint testing |+| tRPC | Jest | `web/src/__tests__/async/` | tRPC procedure testing with auth |+| Service | Jest | `web/src/__tests__/async/repositories/` | Repository/service function testing |+| Worker | Vitest | `worker/src/__tests__/` | Queue processors and streams |++---++## Integration Tests (Public API)++Test full REST API endpoints end-to-end using HTTP requests.++**File location:** `web/src/__tests__/async/datasets-api.servertest.ts`++```typescript+import { makeZodVerifiedAPICall } from "../helpers";+import { PostDatasetsV1Response } from "@/src/features/public-api/types/datasets";++describe("Dataset API", () => {+ it("should create dataset", async () => {+ const res = await makeZodVerifiedAPICall(+ PostDatasetsV1Response,+ "POST",+ "/api/public/datasets",+ { name: "test-dataset" },+ auth,+ );+ expect(res.status).toBe(200);+ });++ it("should validate input", async () => {+ const res = await makeZodVerifiedAPICall(+ PostDatasetsV1Response,+ "POST",+ "/api/public/datasets",+ { name: "" }, // Invalid empty name+ auth,+ );+ expect(res.status).toBe(400);+ });+});+```++**Key Points:**+- Uses `makeZodVerifiedAPICall` for type-safe API testing+- Tests HTTP status codes and response validation+- Tests both success and error cases++---++## Service-Level Tests (Repository/Service)++Test individual repository/service functions with isolated data.++**File location:** `web/src/__tests__/async/repositories/event-repository.servertest.ts`++```typescript+import {+ createEvent,+ createEventsCh,+ getObservationsWithModelDataFromEventsTable,+} from "@langfuse/shared/src/server";+import { prisma } from "@langfuse/shared/src/db";+import { randomUUID } from "crypto";++describe("Event Repository Tests", () => {+ it("should return observations with model data", async () => {+ const traceId = randomUUID();+ const generationId = randomUUID();+ const modelId = randomUUID();++ // Create test data+ await prisma.model.create({+ data: {+ id: modelId,+ projectId,+ modelName: `gpt-4-${modelId}`,+ matchPattern: `(?i)^(gpt-?4-${modelId})$`,+ startDate: new Date("2023-01-01"),+ unit: "TOKENS",+ Price: {+ create: [+ { usageType: "input", price: 0.03 },+ { usageType: "output", price: 0.06 },+ ],+ },+ },+ });++ const event = createEvent({+ id: generationId,+ span_id: generationId,+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: `test-generation-${generationId}`,+ model_id: modelId,+ });++ await createEventsCh([event]);++ // Test the service function+ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [{ type: "string", column: "id", operator: "=", value: generationId }],+ limit: 1000,+ offset: 0,+ });++ expect(result.length).toBeGreaterThan(0);+ const observation = result.find((o) => o.id === generationId);+ expect(observation?.internalModelId).toBe(modelId);+ expect(Number(observation?.inputPrice)).toBeCloseTo(0.03, 5);++ // Cleanup+ await prisma.model.delete({ where: { id: modelId } });+ });++ it("should handle filters correctly", async () => {+ const projectId = randomUUID();+ const traceId = randomUUID();++ const observations = [+ createEvent({+ id: randomUUID(),+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "test1",+ }),+ createEvent({+ id: randomUUID(),+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: "test2",+ }),+ ];++ await createEventsCh(observations);++ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [+ { type: "stringOptions", column: "type", operator: "any of", value: ["GENERATION"] }+ ],+ limit: 1000,+ offset: 0,+ });++ expect(result.every(o => o.type === "GENERATION")).toBe(true);+ });+});+```++**Key Points:**+- Tests service/repository functions directly+- Uses ClickHouse and Prisma test data+- Always cleanup test data after tests+- Use unique IDs to avoid test interference++---++## tRPC Tests (Procedure Testing)++Test tRPC procedures with caller pattern and auth context.++**File location:** `web/src/__tests__/async/automations-trpc.servertest.ts`++```typescript+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import { prisma } from "@langfuse/shared/src/db";+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";+import type { Session } from "next-auth";+import { v4 } from "uuid";+import { JobConfigState } from "@langfuse/shared";++async function prepare() {+ const { project, org } = await createOrgProjectAndApiKey();++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ name: "Demo User",+ organizations: [{+ id: org.id,+ name: org.name,+ role: "OWNER",+ projects: [{+ id: project.id,+ role: "ADMIN",+ name: project.name,+ }],+ }],+ },+ };++ const ctx = createInnerTRPCContext({ session, headers: {} });+ const caller = appRouter.createCaller({ ...ctx, prisma });++ return { project, org, session, ctx, caller };+}++describe("automations trpc", () => {+ it("should retrieve all automations for a project", async () => {+ const { project, caller } = await prepare();++ // Create test trigger+ const trigger = await prisma.trigger.create({+ data: {+ id: v4(),+ projectId: project.id,+ eventSource: "prompt",+ eventActions: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ },+ });++ // Create test action+ const action = await prisma.action.create({+ data: {+ id: v4(),+ projectId: project.id,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com/webhook",+ headers: { "Content-Type": "application/json" },+ },+ },+ });++ // Link trigger to action+ await prisma.automation.create({+ data: {+ projectId: project.id,+ triggerId: trigger.id,+ actionId: action.id,+ name: "Test Automation",+ },+ });++ // Call tRPC procedure+ const response = await caller.automations.getAutomations({+ projectId: project.id,+ });++ expect(response).toHaveLength(1);+ expect(response[0]).toMatchObject({+ name: "Test Automation",+ trigger: expect.objectContaining({+ id: trigger.id,+ eventSource: "prompt",+ }),+ });+ });++ it("should throw error when user lacks permissions", async () => {+ const { project, session } = await prepare();++ // Create limited session+ const limitedSession: Session = {+ ...session,+ user: {+ ...session.user!,+ organizations: [{+ ...session.user!.organizations[0],+ projects: [{+ ...session.user!.organizations[0].projects[0],+ role: "VIEWER", // VIEWER can't create automations+ }],+ }],+ },+ };++ const limitedCtx = createInnerTRPCContext({+ session: limitedSession,+ headers: {},+ });+ const limitedCaller = appRouter.createCaller({ ...limitedCtx, prisma });++ await expect(+ limitedCaller.automations.createAutomation({+ projectId: project.id,+ name: "Unauthorized",+ eventSource: "prompt",+ eventAction: ["created"],+ filter: [],+ status: JobConfigState.ACTIVE,+ actionType: "WEBHOOK",+ actionConfig: {+ type: "WEBHOOK",+ url: "https://example.com/webhook",+ requestHeaders: {},+ apiVersion: { prompt: "v1" },+ },+ }),+ ).rejects.toThrow("User does not have access");+ });+});+```++**Key Points:**+- Uses `prepare()` helper to set up test context+- Creates authenticated caller with `appRouter.createCaller`+- Tests both success and permission error cases+- Can test different user roles and permissions++---++## Worker Tests (Queue Processing)++Test queue processors and stream functions using vitest.++**File location:** `worker/src/__tests__/batchExport.test.ts`++```typescript+import { randomUUID } from "crypto";+import { expect, describe, it } from "vitest";+import {+ createObservation,+ createObservationsCh,+ createOrgProjectAndApiKey,+ createTraceScore,+ createScoresCh,+ createTrace,+ createTracesCh,+} from "@langfuse/shared/src/server";+import { getObservationStream } from "../features/database-read-stream/observation-stream";++describe("batch export test suite", () => {+ it("should export observations", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ const traceId = randomUUID();+ const trace = createTrace({+ project_id: projectId,+ id: traceId,+ });++ await createTracesCh([trace]);++ const observations = [+ createObservation({+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ }),+ createObservation({+ project_id: projectId,+ trace_id: randomUUID(),+ type: "GENERATION",+ }),+ ];++ const score = createTraceScore({+ project_id: projectId,+ trace_id: traceId,+ observation_id: observations[0].id,+ name: "test",+ value: 123,+ });++ await createScoresCh([score]);+ await createObservationsCh(observations);++ // Test the stream function+ const stream = await getObservationStream({+ projectId: projectId,+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),+ filter: [],+ });++ const rows: any[] = [];+ for await (const chunk of stream) {+ rows.push(chunk);+ }++ expect(rows).toHaveLength(2);+ expect(rows).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: observations[0].id,+ type: observations[0].type,+ test: [score.value],+ }),+ ]),+ );+ });++ it("should export with filters", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ const observations = [+ createObservation({+ project_id: projectId,+ trace_id: randomUUID(),+ type: "GENERATION",+ name: "test1",+ }),+ createObservation({+ project_id: projectId,+ trace_id: randomUUID(),+ type: "SPAN",+ name: "test2",+ }),+ ];++ await createObservationsCh(observations);++ const stream = await getObservationStream({+ projectId: projectId,+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),+ filter: [+ {+ type: "stringOptions",+ operator: "any of",+ column: "name",+ value: ["test1"],+ },+ ],+ });++ const rows: any[] = [];+ for await (const chunk of stream) {+ rows.push(chunk);+ }++ expect(rows).toHaveLength(1);+ expect(rows[0].name).toBe("test1");+ });+});+```++**Key Points:**+- Uses vitest (not Jest) for worker tests+- Tests stream functions with async iteration+- Creates isolated test data per test+- Use unique project IDs to avoid interference++---++## Key Testing Principles++### General Principles++1. **Test Isolation**: Each test should be independent and runnable in any order+2. **Unique IDs**: Use `randomUUID()` or unique project IDs to avoid test interference+3. **Cleanup**: Always clean up test data in service tests (or use unique project IDs)+4. **No `pruneDatabase`**: Avoid `pruneDatabase` calls, especially in `__tests__/async/` directory++### By Test Type++| Test Type | Key Principles |+|-----------|----------------|+| **Integration** | Test HTTP endpoints, validate status codes and response shapes |+| **tRPC** | Use `createInnerTRPCContext` and `appRouter.createCaller`, test auth/permissions |+| **Service** | Test individual functions with isolated data, always cleanup |+| **Worker** | Use vitest, test streams with async iteration, test filtering logic |++### Test Data Management++```typescript+// β GOOD: Use unique IDs+const projectId = randomUUID();+const traceId = randomUUID();++// β GOOD: Cleanup in service tests+afterAll(async () => {+ await prisma.model.delete({ where: { id: modelId } });+});++// β GOOD: Use unique projects (no cleanup needed)+const { projectId } = await createOrgProjectAndApiKey();++// β BAD: Shared test data between tests+const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";++// β BAD: Using pruneDatabase+await pruneDatabase();+```++---++## Running Tests++### Web Tests (Jest)++```bash+# Run all tests+pnpm test++# Run sync tests+pnpm test-sync++# Run async tests+pnpm test -- --testPathPattern="async"++# Run specific test file+pnpm test -- --testPathPattern="datasets-api"++# Run specific test+pnpm test -- --testPathPattern="datasets-api" --testNamePattern="should create dataset"+```++### Worker Tests (Vitest)++```bash+# Run all worker tests+pnpm run test --filter=worker++# Run specific test file+pnpm run test --filter=worker -- batchExport++# Run specific test+pnpm run test --filter=worker -- batchExport -t "should export observations"+```++### Coverage++```bash+# Web coverage+pnpm test -- --coverage++# Worker coverage+pnpm run test --filter=worker -- --coverage+```++---++**Related Files:**+- [SKILL.md](../SKILL.md) - Main backend guidelines+- [architecture-overview.md](architecture-overview.md) - Architecture patterns+- [complete-examples.md](complete-examples.md) - Full code examplesdiff --git a/.claude/skills/skill-developer/ADVANCED.md b/.claude/skills/skill-developer/ADVANCED.mdnew file mode 100644index 0000000000..6395f779f2--- /dev/null+++ b/.claude/skills/skill-developer/ADVANCED.md@@ -0,0 +1,197 @@+# Advanced Topics & Future Enhancements++Ideas and concepts for future improvements to the skill system.++---++## Dynamic Rule Updates++**Current State:** Requires Claude Code restart to pick up changes to skill-rules.json++**Future Enhancement:** Hot-reload configuration without restart++**Implementation Ideas:**+- Watch skill-rules.json for changes+- Reload on file modification+- Invalidate cached compiled regexes+- Notify user of reload++**Benefits:**+- Faster iteration during skill development+- No need to restart Claude Code+- Better developer experience++---++## Skill Dependencies++**Current State:** Skills are independent++**Future Enhancement:** Specify skill dependencies and load order++**Configuration Idea:**+```json+{+ "my-advanced-skill": {+ "dependsOn": ["prerequisite-skill", "base-skill"],+ "type": "domain",+ ...+ }+}+```++**Use Cases:**+- Advanced skill builds on base skill knowledge+- Ensure foundational skills loaded first+- Chain skills for complex workflows++**Benefits:**+- Better skill composition+- Clearer skill relationships+- Progressive disclosure++---++## Conditional Enforcement++**Current State:** Enforcement level is static++**Future Enhancement:** Enforce based on context or environment++**Configuration Idea:**+```json+{+ "enforcement": {+ "default": "suggest",+ "when": {+ "production": "block",+ "development": "suggest",+ "ci": "block"+ }+ }+}+```++**Use Cases:**+- Stricter enforcement in production+- Relaxed rules during development+- CI/CD pipeline requirements++**Benefits:**+- Environment-appropriate enforcement+- Flexible rule application+- Context-aware guardrails++---++## Skill Analytics++**Current State:** No usage tracking++**Future Enhancement:** Track skill usage patterns and effectiveness++**Metrics to Collect:**+- Skill trigger frequency+- False positive rate+- False negative rate+- Time to skill usage after suggestion+- User override rate (skip markers, env vars)+- Performance metrics (execution time)++**Dashbord Ideas:**+- Most/least used skills+- Skills with highest false positive rate+- Performance bottlenecks+- Skill effectiveness scores++**Benefits:**+- Data-driven skill improvement+- Identify problems early+- Optimize patterns based on real usage++---++## Skill Versioning++**Current State:** No version tracking++**Future Enhancement:** Version skills and track compatibility++**Configuration Idea:**+```json+{+ "my-skill": {+ "version": "2.1.0",+ "minClaudeVersion": "1.5.0",+ "changelog": "Added support for new workflow patterns",+ ...+ }+}+```++**Benefits:**+- Track skill evolution+- Ensure compatibility+- Document changes+- Support migration paths++---++## Multi-Language Support++**Current State:** English only++**Future Enhancement:** Support multiple languages for skill content++**Implementation Ideas:**+- Language-specific SKILL.md variants+- Automatic language detection+- Fallback to English++**Use Cases:**+- International teams+- Localized documentation+- Multi-language projects++---++## Skill Testing Framework++**Current State:** Manual testing with npx tsx commands++**Future Enhancement:** Automated skill testing++**Features:**+- Test cases for trigger patterns+- Assertion framework+- CI/CD integration+- Coverage reports++**Example Test:**+```typescript+describe('database-verification', () => {+ it('triggers on Prisma imports', () => {+ const result = testSkill({+ prompt: "add user tracking",+ file: "services/user.ts",+ content: "import { PrismaService } from './prisma'"+ });++ expect(result.triggered).toBe(true);+ expect(result.skill).toBe('database-verification');+ });+});+```++**Benefits:**+- Prevent regressions+- Validate patterns before deployment+- Confidence in changes++---++## Related Files++- [SKILL.md](SKILL.md) - Main skill guide+- [TROUBLESHOOTING.md](TROUBLESHOOTING.md) - Current debugging guide+- [HOOK_MECHANISMS.md](HOOK_MECHANISMS.md) - How hooks work todaydiff --git a/.claude/skills/skill-developer/HOOK_MECHANISMS.md b/.claude/skills/skill-developer/HOOK_MECHANISMS.mdnew file mode 100644index 0000000000..abe4768c5b--- /dev/null+++ b/.claude/skills/skill-developer/HOOK_MECHANISMS.md@@ -0,0 +1,306 @@+# Hook Mechanisms - Deep Dive++Technical deep dive into how the UserPromptSubmit and PreToolUse hooks work.++## Table of Contents++- [UserPromptSubmit Hook Flow](#userpromptsubmit-hook-flow)+- [PreToolUse Hook Flow](#pretooluse-hook-flow)+- [Exit Code Behavior (CRITICAL)](#exit-code-behavior-critical)+- [Session State Management](#session-state-management)+- [Performance Considerations](#performance-considerations)++---++## UserPromptSubmit Hook Flow++### Execution Sequence++```+User submits prompt+ β+.claude/settings.json registers hook+ β+skill-activation-prompt.sh executes+ β+npx tsx skill-activation-prompt.ts+ β+Hook reads stdin (JSON with prompt)+ β+Loads skill-rules.json+ β+Matches keywords + intent patterns+ β+Groups matches by priority (critical β high β medium β low)+ β+Outputs formatted message to stdout+ β+stdout becomes context for Claude (injected before prompt)+ β+Claude sees: [skill suggestion] + user's prompt+```++### Key Points++- **Exit code**: Always 0 (allow)+- **stdout**: β Claude's context (injected as system message)+- **Timing**: Runs BEFORE Claude processes prompt+- **Behavior**: Non-blocking, advisory only+- **Purpose**: Make Claude aware of relevant skills++### Input Format++```json+{+ "session_id": "abc-123",+ "transcript_path": "/path/to/transcript.json",+ "cwd": "/root/git/your-project",+ "permission_mode": "normal",+ "hook_event_name": "UserPromptSubmit",+ "prompt": "how does the layout system work?"+}+```++### Output Format (to stdout)++```+βββββββββββββββββββββββββββββββββββββββ+π― SKILL ACTIVATION CHECK+βββββββββββββββββββββββββββββββββββββββ++π RECOMMENDED SKILLS:+ β project-catalog-developer++ACTION: Use Skill tool BEFORE responding+βββββββββββββββββββββββββββββββββββββββ+```++Claude sees this output as additional context before processing the user's prompt.++---++## PreToolUse Hook Flow++### Execution Sequence++```+Claude calls Edit/Write tool+ β+.claude/settings.json registers hook (matcher: Edit|Write)+ β+skill-verification-guard.sh executes+ β+npx tsx skill-verification-guard.ts+ β+Hook reads stdin (JSON with tool_name, tool_input)+ β+Loads skill-rules.json+ β+Checks file path patterns (glob matching)+ β+Reads file for content patterns (if file exists)+ β+Checks session state (was skill already used?)+ β+Checks skip conditions (file markers, env vars)+ β+IF MATCHED AND NOT SKIPPED:+ Update session state (mark skill as enforced)+ Output block message to stderr+ Exit with code 2 (BLOCK)+ELSE:+ Exit with code 0 (ALLOW)+ β+IF BLOCKED:+ stderr β Claude sees message+ Edit/Write tool does NOT execute+ Claude must use skill and retry+IF ALLOWED:+ Tool executes normally+```++### Key Points++- **Exit code 2**: BLOCK (stderr β Claude)+- **Exit code 0**: ALLOW+- **Timing**: Runs BEFORE tool execution+- **Session tracking**: Prevents repeated blocks in same session+- **Fail open**: On errors, allows operation (don't break workflow)+- **Purpose**: Enforce critical guardrails++### Input Format++```json+{+ "session_id": "abc-123",+ "transcript_path": "/path/to/transcript.json",+ "cwd": "/root/git/your-project",+ "permission_mode": "normal",+ "hook_event_name": "PreToolUse",+ "tool_name": "Edit",+ "tool_input": {+ "file_path": "/root/git/your-project/form/src/services/user.ts",+ "old_string": "...",+ "new_string": "..."+ }+}+```++### Output Format (to stderr when blocked)++```+β οΈ BLOCKED - Database Operation Detected++π REQUIRED ACTION:+1. Use Skill tool: 'database-verification'+2. Verify ALL table and column names against schema+3. Check database structure with DESCRIBE commands+4. Then retry this edit++Reason: Prevent column name errors in Prisma queries+File: form/src/services/user.ts++π‘ TIP: Add '// @skip-validation' comment to skip future checks+```++Claude receives this message and understands it needs to use the skill before retrying the edit.++---++## Exit Code Behavior (CRITICAL)++### Exit Code Reference Table++| Exit Code | stdout | stderr | Tool Execution | Claude Sees |+|-----------|--------|--------|----------------|-------------|+| 0 (UserPromptSubmit) | β Context | β User only | N/A | stdout content |+| 0 (PreToolUse) | β User only | β User only | **Proceeds** | Nothing |+| 2 (PreToolUse) | β User only | β **CLAUDE** | **BLOCKED** | stderr content |+| Other | β User only | β User only | Blocked | Nothing |++### Why Exit Code 2 Matters++This is THE critical mechanism for enforcement:++1. **Only way** to send message to Claude from PreToolUse+2. stderr content is "fed back to Claude automatically"+3. Claude sees the block message and understands what to do+4. Tool execution is prevented+5. Critical for enforcement of guardrails++### Example Conversation Flow++```+User: "Add a new user service with Prisma"++Claude: "I'll create the user service..."+ [Attempts to Edit form/src/services/user.ts]++PreToolUse Hook: [Exit code 2]+ stderr: "β οΈ BLOCKED - Use database-verification"++Claude sees error, responds:+ "I need to verify the database schema first."+ [Uses Skill tool: database-verification]+ [Verifies column names]+ [Retries Edit - now allowed (session tracking)]+```++---++## Session State Management++### Purpose++Prevent repeated nagging in the same session - once Claude uses a skill, don't block again.++### State File Location++`.claude/hooks/state/skills-used-{session_id}.json`++### State File Structure++```json+{+ "skills_used": [+ "database-verification",+ "error-tracking"+ ],+ "files_verified": []+}+```++### How It Works++1. **First edit** of file with Prisma:+ - Hook blocks with exit code 2+ - Updates session state: adds "database-verification" to skills_used+ - Claude sees message, uses skill++2. **Second edit** (same session):+ - Hook checks session state+ - Finds "database-verification" in skills_used+ - Exits with code 0 (allow)+ - No message to Claude++3. **Different session**:+ - New session ID = new state file+ - Hook blocks again++### Limitation++The hook cannot detect when the skill is *actually* invoked - it just blocks once per session per skill. This means:++- If Claude doesn't use the skill but makes a different edit, it won't block again+- Trust that Claude follows the instruction+- Future enhancement: detect actual Skill tool usage++---++## Performance Considerations++### Target Metrics++- **UserPromptSubmit**: < 100ms+- **PreToolUse**: < 200ms++### Performance Bottlenecks++1. **Loading skill-rules.json** (every execution)+ - Future: Cache in memory+ - Future: Watch for changes, reload only when needed++2. **Reading file content** (PreToolUse)+ - Only when contentPatterns configured+ - Only if file exists+ - Can be slow for large files++3. **Glob matching** (PreToolUse)+ - Regex compilation for each pattern+ - Future: Compile once, cache++4. **Regex matching** (Both hooks)+ - Intent patterns (UserPromptSubmit)+ - Content patterns (PreToolUse)+ - Future: Lazy compile, cache compiled regexes++### Optimization Strategies++**Reduce patterns:**+- Use more specific patterns (fewer to check)+- Combine similar patterns where possible++**File path patterns:**+- More specific = fewer files to check+- Example: `form/src/services/**` better than `form/**`++**Content patterns:**+- Only add when truly necessary+- Simpler regex = faster matching++---++**Related Files:**+- [SKILL.md](SKILL.md) - Main skill guide+- [TROUBLESHOOTING.md](TROUBLESHOOTING.md) - Debug hook issues+- [SKILL_RULES_REFERENCE.md](SKILL_RULES_REFERENCE.md) - Configuration referencediff --git a/.claude/skills/skill-developer/PATTERNS_LIBRARY.md b/.claude/skills/skill-developer/PATTERNS_LIBRARY.mdnew file mode 100644index 0000000000..72209397f5--- /dev/null+++ b/.claude/skills/skill-developer/PATTERNS_LIBRARY.md@@ -0,0 +1,152 @@+# Common Patterns Library++Ready-to-use regex and glob patterns for skill triggers. Copy and customize for your skills.++---++## Intent Patterns (Regex)++### Feature/Endpoint Creation+```regex+(add|create|implement|build).*?(feature|endpoint|route|service|controller)+```++### Component Creation+```regex+(create|add|make|build).*?(component|UI|page|modal|dialog|form)+```++### Database Work+```regex+(add|create|modify|update).*?(user|table|column|field|schema|migration)+(database|prisma).*?(change|update|query)+```++### Error Handling+```regex+(fix|handle|catch|debug).*?(error|exception|bug)+(add|implement).*?(try|catch|error.*?handling)+```++### Explanation Requests+```regex+(how does|how do|explain|what is|describe|tell me about).*?+```++### Workflow Operations+```regex+(create|add|modify|update).*?(workflow|step|branch|condition)+(debug|troubleshoot|fix).*?workflow+```++### Testing+```regex+(write|create|add).*?(test|spec|unit.*?test)+```++---++## File Path Patterns (Glob)++### Frontend+```glob+frontend/src/**/*.tsx # All React components+frontend/src/**/*.ts # All TypeScript files+frontend/src/components/** # Only components directory+```++### Backend Services+```glob+form/src/**/*.ts # Form service+email/src/**/*.ts # Email service+users/src/**/*.ts # Users service+projects/src/**/*.ts # Projects service+```++### Database+```glob+**/schema.prisma # Prisma schema (anywhere)+**/migrations/**/*.sql # Migration files+database/src/**/*.ts # Database scripts+```++### Workflows+```glob+form/src/workflow/**/*.ts # Workflow engine+form/src/workflow-definitions/**/*.json # Workflow definitions+```++### Test Exclusions+```glob+**/*.test.ts # TypeScript tests+**/*.test.tsx # React component tests+**/*.spec.ts # Spec files+```++---++## Content Patterns (Regex)++### Prisma/Database+```regex+import.*[Pp]risma # Prisma imports+PrismaService # PrismaService usage+prisma\. # prisma.something+\.findMany\( # Prisma query methods+\.create\(+\.update\(+\.delete\(+```++### Controllers/Routes+```regex+export class.*Controller # Controller classes+router\. # Express router+app\.(get|post|put|delete|patch) # Express app routes+```++### Error Handling+```regex+try\s*\{ # Try blocks+catch\s*\( # Catch blocks+throw new # Throw statements+```++### React/Components+```regex+export.*React\.FC # React functional components+export default function.* # Default function exports+useState|useEffect # React hooks+```++---++**Usage Example:**++```json+{+ "my-skill": {+ "promptTriggers": {+ "intentPatterns": [+ "(create|add|build).*?(component|UI|page)"+ ]+ },+ "fileTriggers": {+ "pathPatterns": [+ "frontend/src/**/*.tsx"+ ],+ "contentPatterns": [+ "export.*React\\.FC",+ "useState|useEffect"+ ]+ }+ }+}+```++---++**Related Files:**+- [SKILL.md](SKILL.md) - Main skill guide+- [TRIGGER_TYPES.md](TRIGGER_TYPES.md) - Detailed trigger documentation+- [SKILL_RULES_REFERENCE.md](SKILL_RULES_REFERENCE.md) - Complete schemadiff --git a/.claude/skills/skill-developer/SKILL.md b/.claude/skills/skill-developer/SKILL.mdnew file mode 100644index 0000000000..4c26d2dd40--- /dev/null+++ b/.claude/skills/skill-developer/SKILL.md@@ -0,0 +1,426 @@+---+name: skill-developer+description: Create and manage Claude Code skills following Anthropic best practices. Use when creating new skills, modifying skill-rules.json, understanding trigger patterns, working with hooks, debugging skill activation, or implementing progressive disclosure. Covers skill structure, YAML frontmatter, trigger types (keywords, intent patterns, file paths, content patterns), enforcement levels (block, suggest, warn), hook mechanisms (UserPromptSubmit, PreToolUse), session tracking, and the 500-line rule.+---++# Skill Developer Guide++## Purpose++Comprehensive guide for creating and managing skills in Claude Code with auto-activation system, following Anthropic's official best practices including the 500-line rule and progressive disclosure pattern.++## When to Use This Skill++Automatically activates when you mention:+- Creating or adding skills+- Modifying skill triggers or rules+- Understanding how skill activation works+- Debugging skill activation issues+- Working with skill-rules.json+- Hook system mechanics+- Claude Code best practices+- Progressive disclosure+- YAML frontmatter+- 500-line rule++---++## System Overview++### Two-Hook Architecture++**1. UserPromptSubmit Hook** (Proactive Suggestions)+- **File**: `.claude/hooks/skill-activation-prompt.ts`+- **Trigger**: BEFORE Claude sees user's prompt+- **Purpose**: Suggest relevant skills based on keywords + intent patterns+- **Method**: Injects formatted reminder as context (stdout β Claude's input)+- **Use Cases**: Topic-based skills, implicit work detection++**2. Stop Hook - Error Handling Reminder** (Gentle Reminders)+- **File**: `.claude/hooks/error-handling-reminder.ts`+- **Trigger**: AFTER Claude finishes responding+- **Purpose**: Gentle reminder to self-assess error handling in code written+- **Method**: Analyzes edited files for risky patterns, displays reminder if needed+- **Use Cases**: Error handling awareness without blocking friction++**Philosophy Change (2025-10-27):** We moved away from blocking PreToolUse for Sentry/error handling. Instead, use gentle post-response reminders that don't block workflow but maintain code quality awareness.++### Configuration File++**Location**: `.claude/skills/skill-rules.json`++Defines:+- All skills and their trigger conditions+- Enforcement levels (block, suggest, warn)+- File path patterns (glob)+- Content detection patterns (regex)+- Skip conditions (session tracking, file markers, env vars)++---++## Skill Types++### 1. Guardrail Skills++**Purpose:** Enforce critical best practices that prevent errors++**Characteristics:**+- Type: `"guardrail"`+- Enforcement: `"block"`+- Priority: `"critical"` or `"high"`+- Block file edits until skill used+- Prevent common mistakes (column names, critical errors)+- Session-aware (don't repeat nag in same session)++**Examples:**+- `database-verification` - Verify table/column names before Prisma queries+- `frontend-dev-guidelines` - Enforce React/TypeScript patterns++**When to Use:**+- Mistakes that cause runtime errors+- Data integrity concerns+- Critical compatibility issues++### 2. Domain Skills++**Purpose:** Provide comprehensive guidance for specific areas++**Characteristics:**+- Type: `"domain"`+- Enforcement: `"suggest"`+- Priority: `"high"` or `"medium"`+- Advisory, not mandatory+- Topic or domain-specific+- Comprehensive documentation++**Examples:**+- `backend-dev-guidelines` - Node.js/Express/TypeScript patterns+- `frontend-dev-guidelines` - React/TypeScript best practices+- `error-tracking` - Sentry integration guidance++**When to Use:**+- Complex systems requiring deep knowledge+- Best practices documentation+- Architectural patterns+- How-to guides++---++## Quick Start: Creating a New Skill++### Step 1: Create Skill File++**Location:** `.claude/skills/{skill-name}/SKILL.md`++**Template:**+```markdown+---+name: my-new-skill+description: Brief description including keywords that trigger this skill. Mention topics, file types, and use cases. Be explicit about trigger terms.+---++# My New Skill++## Purpose+What this skill helps with++## When to Use+Specific scenarios and conditions++## Key Information+The actual guidance, documentation, patterns, examples+```++**Best Practices:**+- β **Name**: Lowercase, hyphens, gerund form (verb + -ing) preferred+- β **Description**: Include ALL trigger keywords/phrases (max 1024 chars)+- β **Content**: Under 500 lines - use reference files for details+- β **Examples**: Real code examples+- β **Structure**: Clear headings, lists, code blocks++### Step 2: Add to skill-rules.json++See [SKILL_RULES_REFERENCE.md](SKILL_RULES_REFERENCE.md) for complete schema.++**Basic Template:**+```json+{+ "my-new-skill": {+ "type": "domain",+ "enforcement": "suggest",+ "priority": "medium",+ "promptTriggers": {+ "keywords": ["keyword1", "keyword2"],+ "intentPatterns": ["(create|add).*?something"]+ }+ }+}+```++### Step 3: Test Triggers++**Test UserPromptSubmit:**+```bash+echo '{"session_id":"test","prompt":"your test prompt"}' | \+ npx tsx .claude/hooks/skill-activation-prompt.ts+```++**Test PreToolUse:**+```bash+cat <<'EOF' | npx tsx .claude/hooks/skill-verification-guard.ts+{"session_id":"test","tool_name":"Edit","tool_input":{"file_path":"test.ts"}}+EOF+```++### Step 4: Refine Patterns++Based on testing:+- Add missing keywords+- Refine intent patterns to reduce false positives+- Adjust file path patterns+- Test content patterns against actual files++### Step 5: Follow Anthropic Best Practices++β Keep SKILL.md under 500 lines+β Use progressive disclosure with reference files+β Add table of contents to reference files > 100 lines+β Write detailed description with trigger keywords+β Test with 3+ real scenarios before documenting+β Iterate based on actual usage++---++## Enforcement Levels++### BLOCK (Critical Guardrails)++- Physically prevents Edit/Write tool execution+- Exit code 2 from hook, stderr β Claude+- Claude sees message and must use skill to proceed+- **Use For**: Critical mistakes, data integrity, security issues++**Example:** Database column name verification++### SUGGEST (Recommended)++- Reminder injected before Claude sees prompt+- Claude is aware of relevant skills+- Not enforced, just advisory+- **Use For**: Domain guidance, best practices, how-to guides++**Example:** Frontend development guidelines++### WARN (Optional)++- Low priority suggestions+- Advisory only, minimal enforcement+- **Use For**: Nice-to-have suggestions, informational reminders++**Rarely used** - most skills are either BLOCK or SUGGEST.++---++## Skip Conditions & User Control++### 1. Session Tracking++**Purpose:** Don't nag repeatedly in same session++**How it works:**+- First edit β Hook blocks, updates session state+- Second edit (same session) β Hook allows+- Different session β Blocks again++**State File:** `.claude/hooks/state/skills-used-{session_id}.json`++### 2. File Markers++**Purpose:** Permanent skip for verified files++**Marker:** `// @skip-validation`++**Usage:**+```typescript+// @skip-validation+import { PrismaService } from './prisma';+// This file has been manually verified+```++**NOTE:** Use sparingly - defeats the purpose if overused++### 3. Environment Variables++**Purpose:** Emergency disable, temporary override++**Global disable:**+```bash+export SKIP_SKILL_GUARDRAILS=true # Disables ALL PreToolUse blocks+```++**Skill-specific:**+```bash+export SKIP_DB_VERIFICATION=true+export SKIP_ERROR_REMINDER=true+```++---++## Testing Checklist++When creating a new skill, verify:++- [ ] Skill file created in `.claude/skills/{name}/SKILL.md`+- [ ] Proper frontmatter with name and description+- [ ] Entry added to `skill-rules.json`+- [ ] Keywords tested with real prompts+- [ ] Intent patterns tested with variations+- [ ] File path patterns tested with actual files+- [ ] Content patterns tested against file contents+- [ ] Block message is clear and actionable (if guardrail)+- [ ] Skip conditions configured appropriately+- [ ] Priority level matches importance+- [ ] No false positives in testing+- [ ] No false negatives in testing+- [ ] Performance is acceptable (<100ms or <200ms)+- [ ] JSON syntax validated: `jq . skill-rules.json`+- [ ] **SKILL.md under 500 lines** β+- [ ] Reference files created if needed+- [ ] Table of contents added to files > 100 lines++---++## Reference Files++For detailed information on specific topics, see:++### [TRIGGER_TYPES.md](TRIGGER_TYPES.md)+Complete guide to all trigger types:+- Keyword triggers (explicit topic matching)+- Intent patterns (implicit action detection)+- File path triggers (glob patterns)+- Content patterns (regex in files)+- Best practices and examples for each+- Common pitfalls and testing strategies++### [SKILL_RULES_REFERENCE.md](SKILL_RULES_REFERENCE.md)+Complete skill-rules.json schema:+- Full TypeScript interface definitions+- Field-by-field explanations+- Complete guardrail skill example+- Complete domain skill example+- Validation guide and common errors++### [HOOK_MECHANISMS.md](HOOK_MECHANISMS.md)+Deep dive into hook internals:+- UserPromptSubmit flow (detailed)+- PreToolUse flow (detailed)+- Exit code behavior table (CRITICAL)+- Session state management+- Performance considerations++### [TROUBLESHOOTING.md](TROUBLESHOOTING.md)+Comprehensive debugging guide:+- Skill not triggering (UserPromptSubmit)+- PreToolUse not blocking+- False positives (too many triggers)+- Hook not executing at all+- Performance issues++### [PATTERNS_LIBRARY.md](PATTERNS_LIBRARY.md)+Ready-to-use pattern collection:+- Intent pattern library (regex)+- File path pattern library (glob)+- Content pattern library (regex)+- Organized by use case+- Copy-paste ready++### [ADVANCED.md](ADVANCED.md)+Future enhancements and ideas:+- Dynamic rule updates+- Skill dependencies+- Conditional enforcement+- Skill analytics+- Skill versioning++---++## Quick Reference Summary++### Create New Skill (5 Steps)++1. Create `.claude/skills/{name}/SKILL.md` with frontmatter+2. Add entry to `.claude/skills/skill-rules.json`+3. Test with `npx tsx` commands+4. Refine patterns based on testing+5. Keep SKILL.md under 500 lines++### Trigger Types++- **Keywords**: Explicit topic mentions+- **Intent**: Implicit action detection+- **File Paths**: Location-based activation+- **Content**: Technology-specific detection++See [TRIGGER_TYPES.md](TRIGGER_TYPES.md) for complete details.++### Enforcement++- **BLOCK**: Exit code 2, critical only+- **SUGGEST**: Inject context, most common+- **WARN**: Advisory, rarely used++### Skip Conditions++- **Session tracking**: Automatic (prevents repeated nags)+- **File markers**: `// @skip-validation` (permanent skip)+- **Env vars**: `SKIP_SKILL_GUARDRAILS` (emergency disable)++### Anthropic Best Practices++β **500-line rule**: Keep SKILL.md under 500 lines+β **Progressive disclosure**: Use reference files for details+β **Table of contents**: Add to reference files > 100 lines+β **One level deep**: Don't nest references deeply+β **Rich descriptions**: Include all trigger keywords (max 1024 chars)+β **Test first**: Build 3+ evaluations before extensive documentation+β **Gerund naming**: Prefer verb + -ing (e.g., "processing-pdfs")++### Troubleshoot++Test hooks manually:+```bash+# UserPromptSubmit+echo '{"prompt":"test"}' | npx tsx .claude/hooks/skill-activation-prompt.ts++# PreToolUse+cat <<'EOF' | npx tsx .claude/hooks/skill-verification-guard.ts+{"tool_name":"Edit","tool_input":{"file_path":"test.ts"}}+EOF+```++See [TROUBLESHOOTING.md](TROUBLESHOOTING.md) for complete debugging guide.++---++## Related Files++**Configuration:**+- `.claude/skills/skill-rules.json` - Master configuration+- `.claude/hooks/state/` - Session tracking+- `.claude/settings.json` - Hook registration++**Hooks:**+- `.claude/hooks/skill-activation-prompt.ts` - UserPromptSubmit+- `.claude/hooks/error-handling-reminder.ts` - Stop event (gentle reminders)++**All Skills:**+- `.claude/skills/*/SKILL.md` - Skill content files++---++**Skill Status**: COMPLETE - Restructured following Anthropic best practices β+**Line Count**: < 500 (following 500-line rule) β+**Progressive Disclosure**: Reference files for detailed information β++**Next**: Create more skills, refine patterns based on usagediff --git a/.claude/skills/skill-developer/SKILL_RULES_REFERENCE.md b/.claude/skills/skill-developer/SKILL_RULES_REFERENCE.mdnew file mode 100644index 0000000000..1cad7d9b38--- /dev/null+++ b/.claude/skills/skill-developer/SKILL_RULES_REFERENCE.md@@ -0,0 +1,315 @@+# skill-rules.json - Complete Reference++Complete schema and configuration reference for `.claude/skills/skill-rules.json`.++## Table of Contents++- [File Location](#file-location)+- [Complete TypeScript Schema](#complete-typescript-schema)+- [Field Guide](#field-guide)+- [Example: Guardrail Skill](#example-guardrail-skill)+- [Example: Domain Skill](#example-domain-skill)+- [Validation](#validation)++---++## File Location++**Path:** `.claude/skills/skill-rules.json`++This JSON file defines all skills and their trigger conditions for the auto-activation system.++---++## Complete TypeScript Schema++```typescript+interface SkillRules {+ version: string;+ skills: Record<string, SkillRule>;+}++interface SkillRule {+ type: 'guardrail' | 'domain';+ enforcement: 'block' | 'suggest' | 'warn';+ priority: 'critical' | 'high' | 'medium' | 'low';++ promptTriggers?: {+ keywords?: string[];+ intentPatterns?: string[]; // Regex strings+ };++ fileTriggers?: {+ pathPatterns: string[]; // Glob patterns+ pathExclusions?: string[]; // Glob patterns+ contentPatterns?: string[]; // Regex strings+ createOnly?: boolean; // Only trigger on file creation+ };++ blockMessage?: string; // For guardrails, {file_path} placeholder++ skipConditions?: {+ sessionSkillUsed?: boolean; // Skip if used in session+ fileMarkers?: string[]; // e.g., ["@skip-validation"]+ envOverride?: string; // e.g., "SKIP_DB_VERIFICATION"+ };+}+```++---++## Field Guide++### Top Level++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| `version` | string | Yes | Schema version (currently "1.0") |+| `skills` | object | Yes | Map of skill name β SkillRule |++### SkillRule Fields++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| `type` | string | Yes | "guardrail" (enforced) or "domain" (advisory) |+| `enforcement` | string | Yes | "block" (PreToolUse), "suggest" (UserPromptSubmit), or "warn" |+| `priority` | string | Yes | "critical", "high", "medium", or "low" |+| `promptTriggers` | object | Optional | Triggers for UserPromptSubmit hook |+| `fileTriggers` | object | Optional | Triggers for PreToolUse hook |+| `blockMessage` | string | Optional* | Required if enforcement="block". Use `{file_path}` placeholder |+| `skipConditions` | object | Optional | Escape hatches and session tracking |++*Required for guardrails++### promptTriggers Fields++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| `keywords` | string[] | Optional | Exact substring matches (case-insensitive) |+| `intentPatterns` | string[] | Optional | Regex patterns for intent detection |++### fileTriggers Fields++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| `pathPatterns` | string[] | Yes* | Glob patterns for file paths |+| `pathExclusions` | string[] | Optional | Glob patterns to exclude (e.g., test files) |+| `contentPatterns` | string[] | Optional | Regex patterns to match file content |+| `createOnly` | boolean | Optional | Only trigger when creating new files |++*Required if fileTriggers is present++### skipConditions Fields++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| `sessionSkillUsed` | boolean | Optional | Skip if skill already used this session |+| `fileMarkers` | string[] | Optional | Skip if file contains comment marker |+| `envOverride` | string | Optional | Environment variable name to disable skill |++---++## Example: Guardrail Skill++Complete example of a blocking guardrail skill with all features:++```json+{+ "database-verification": {+ "type": "guardrail",+ "enforcement": "block",+ "priority": "critical",++ "promptTriggers": {+ "keywords": [+ "prisma",+ "database",+ "table",+ "column",+ "schema",+ "query",+ "migration"+ ],+ "intentPatterns": [+ "(add|create|implement).*?(user|login|auth|tracking|feature)",+ "(modify|update|change).*?(table|column|schema|field)",+ "database.*?(change|update|modify|migration)"+ ]+ },++ "fileTriggers": {+ "pathPatterns": [+ "**/schema.prisma",+ "**/migrations/**/*.sql",+ "database/src/**/*.ts",+ "form/src/**/*.ts",+ "email/src/**/*.ts",+ "users/src/**/*.ts",+ "projects/src/**/*.ts",+ "utilities/src/**/*.ts"+ ],+ "pathExclusions": [+ "**/*.test.ts",+ "**/*.spec.ts"+ ],+ "contentPatterns": [+ "import.*[Pp]risma",+ "PrismaService",+ "prisma\\.",+ "\\.findMany\\(",+ "\\.findUnique\\(",+ "\\.findFirst\\(",+ "\\.create\\(",+ "\\.createMany\\(",+ "\\.update\\(",+ "\\.updateMany\\(",+ "\\.upsert\\(",+ "\\.delete\\(",+ "\\.deleteMany\\("+ ]+ },++ "blockMessage": "β οΈ BLOCKED - Database Operation Detected\n\nπ REQUIRED ACTION:\n1. Use Skill tool: 'database-verification'\n2. Verify ALL table and column names against schema\n3. Check database structure with DESCRIBE commands\n4. Then retry this edit\n\nReason: Prevent column name errors in Prisma queries\nFile: {file_path}\n\nπ‘ TIP: Add '// @skip-validation' comment to skip future checks",++ "skipConditions": {+ "sessionSkillUsed": true,+ "fileMarkers": [+ "@skip-validation"+ ],+ "envOverride": "SKIP_DB_VERIFICATION"+ }+ }+}+```++### Key Points for Guardrails++1. **type**: Must be "guardrail"+2. **enforcement**: Must be "block"+3. **priority**: Usually "critical" or "high"+4. **blockMessage**: Required, clear actionable steps+5. **skipConditions**: Session tracking prevents repeated nagging+6. **fileTriggers**: Usually has both path and content patterns+7. **contentPatterns**: Catch actual usage of technology++---++## Example: Domain Skill++Complete example of a suggestion-based domain skill:++```json+{+ "project-catalog-developer": {+ "type": "domain",+ "enforcement": "suggest",+ "priority": "high",++ "promptTriggers": {+ "keywords": [+ "layout",+ "layout system",+ "grid",+ "grid layout",+ "toolbar",+ "column",+ "cell editor",+ "cell renderer",+ "submission",+ "submissions",+ "blog dashboard",+ "datagrid",+ "data grid",+ "CustomToolbar",+ "GridLayoutDialog",+ "useGridLayout",+ "auto-save",+ "column order",+ "column width",+ "filter",+ "sort"+ ],+ "intentPatterns": [+ "(how does|how do|explain|what is|describe).*?(layout|grid|toolbar|column|submission|catalog)",+ "(add|create|modify|change).*?(toolbar|column|cell|editor|renderer)",+ "blog dashboard.*?"+ ]+ },++ "fileTriggers": {+ "pathPatterns": [+ "frontend/src/features/submissions/**/*.tsx",+ "frontend/src/features/submissions/**/*.ts"+ ],+ "pathExclusions": [+ "**/*.test.tsx",+ "**/*.test.ts"+ ]+ }+ }+}+```++### Key Points for Domain Skills++1. **type**: Must be "domain"+2. **enforcement**: Usually "suggest"+3. **priority**: "high" or "medium"+4. **blockMessage**: Not needed (doesn't block)+5. **skipConditions**: Optional (less critical)+6. **promptTriggers**: Usually has extensive keywords+7. **fileTriggers**: May have only path patterns (content less important)++---++## Validation++### Check JSON Syntax++```bash+cat .claude/skills/skill-rules.json | jq .+```++If valid, jq will pretty-print the JSON. If invalid, it will show the error.++### Common JSON Errors++**Trailing comma:**+```json+{+ "keywords": ["one", "two",] // β Trailing comma+}+```++**Missing quotes:**+```json+{+ type: "guardrail" // β Missing quotes on key+}+```++**Single quotes (invalid JSON):**+```json+{+ 'type': 'guardrail' // β Must use double quotes+}+```++### Validation Checklist++- [ ] JSON syntax valid (use `jq`)+- [ ] All skill names match SKILL.md filenames+- [ ] Guardrails have `blockMessage`+- [ ] Block messages use `{file_path}` placeholder+- [ ] Intent patterns are valid regex (test on regex101.com)+- [ ] File path patterns use correct glob syntax+- [ ] Content patterns escape special characters+- [ ] Priority matches enforcement level+- [ ] No duplicate skill names++---++**Related Files:**+- [SKILL.md](SKILL.md) - Main skill guide+- [TRIGGER_TYPES.md](TRIGGER_TYPES.md) - Complete trigger documentation+- [TROUBLESHOOTING.md](TROUBLESHOOTING.md) - Debugging configuration issuesdiff --git a/.claude/skills/skill-developer/TRIGGER_TYPES.md b/.claude/skills/skill-developer/TRIGGER_TYPES.mdnew file mode 100644index 0000000000..dd61951cf3--- /dev/null+++ b/.claude/skills/skill-developer/TRIGGER_TYPES.md@@ -0,0 +1,305 @@+# Trigger Types - Complete Guide++Complete reference for configuring skill triggers in Claude Code's skill auto-activation system.++## Table of Contents++- [Keyword Triggers (Explicit)](#keyword-triggers-explicit)+- [Intent Pattern Triggers (Implicit)](#intent-pattern-triggers-implicit)+- [File Path Triggers](#file-path-triggers)+- [Content Pattern Triggers](#content-pattern-triggers)+- [Best Practices Summary](#best-practices-summary)++---++## Keyword Triggers (Explicit)++### How It Works++Case-insensitive substring matching in user's prompt.++### Use For++Topic-based activation where user explicitly mentions the subject.++### Configuration++```json+"promptTriggers": {+ "keywords": ["layout", "grid", "toolbar", "submission"]+}+```++### Example++- User prompt: "how does the **layout** system work?"+- Matches: "layout" keyword+- Activates: `project-catalog-developer`++### Best Practices++- Use specific, unambiguous terms+- Include common variations ("layout", "layout system", "grid layout")+- Avoid overly generic words ("system", "work", "create")+- Test with real prompts++---++## Intent Pattern Triggers (Implicit)++### How It Works++Regex pattern matching to detect user's intent even when they don't mention the topic explicitly.++### Use For++Action-based activation where user describes what they want to do rather than the specific topic.++### Configuration++```json+"promptTriggers": {+ "intentPatterns": [+ "(create|add|implement).*?(feature|endpoint)",+ "(how does|explain).*?(layout|workflow)"+ ]+}+```++### Examples++**Database Work:**+- User prompt: "add user tracking feature"+- Matches: `(add).*?(feature)`+- Activates: `database-verification`, `error-tracking`++**Component Creation:**+- User prompt: "create a dashboard widget"+- Matches: `(create).*?(component)` (if component in pattern)+- Activates: `frontend-dev-guidelines`++### Best Practices++- Capture common action verbs: `(create|add|modify|build|implement)`+- Include domain-specific nouns: `(feature|endpoint|component|workflow)`+- Use non-greedy matching: `.*?` instead of `.*`+- Test patterns thoroughly with regex tester (https://regex101.com/)+- Don't make patterns too broad (causes false positives)+- Don't make patterns too specific (causes false negatives)++### Common Pattern Examples++```regex+# Database Work+(add|create|implement).*?(user|login|auth|feature)++# Explanations+(how does|explain|what is|describe).*?++# Frontend Work+(create|add|make|build).*?(component|UI|page|modal|dialog)++# Error Handling+(fix|handle|catch|debug).*?(error|exception|bug)++# Workflow Operations+(create|add|modify).*?(workflow|step|branch|condition)+```++---++## File Path Triggers++### How It Works++Glob pattern matching against the file path being edited.++### Use For++Domain/area-specific activation based on file location in the project.++### Configuration++```json+"fileTriggers": {+ "pathPatterns": [+ "frontend/src/**/*.tsx",+ "form/src/**/*.ts"+ ],+ "pathExclusions": [+ "**/*.test.ts",+ "**/*.spec.ts"+ ]+}+```++### Glob Pattern Syntax++- `**` = Any number of directories (including zero)+- `*` = Any characters within a directory name+- Examples:+ - `frontend/src/**/*.tsx` = All .tsx files in frontend/src and subdirs+ - `**/schema.prisma` = schema.prisma anywhere in project+ - `form/src/**/*.ts` = All .ts files in form/src subdirs++### Example++- File being edited: `frontend/src/components/Dashboard.tsx`+- Matches: `frontend/src/**/*.tsx`+- Activates: `frontend-dev-guidelines`++### Best Practices++- Be specific to avoid false positives+- Use exclusions for test files: `**/*.test.ts`+- Consider subdirectory structure+- Test patterns with actual file paths+- Use narrower patterns when possible: `form/src/services/**` not `form/**`++### Common Path Patterns++```glob+# Frontend+frontend/src/**/*.tsx # All React components+frontend/src/**/*.ts # All TypeScript files+frontend/src/components/** # Only components directory++# Backend Services+form/src/**/*.ts # Form service+email/src/**/*.ts # Email service+users/src/**/*.ts # Users service++# Database+**/schema.prisma # Prisma schema (anywhere)+**/migrations/**/*.sql # Migration files+database/src/**/*.ts # Database scripts++# Workflows+form/src/workflow/**/*.ts # Workflow engine+form/src/workflow-definitions/**/*.json # Workflow definitions++# Test Exclusions+**/*.test.ts # TypeScript tests+**/*.test.tsx # React component tests+**/*.spec.ts # Spec files+```++---++## Content Pattern Triggers++### How It Works++Regex pattern matching against the file's actual content (what's inside the file).++### Use For++Technology-specific activation based on what the code imports or uses (Prisma, controllers, specific libraries).++### Configuration++```json+"fileTriggers": {+ "contentPatterns": [+ "import.*[Pp]risma",+ "PrismaService",+ "\\.findMany\\(",+ "\\.create\\("+ ]+}+```++### Examples++**Prisma Detection:**+- File contains: `import { PrismaService } from '@project/database'`+- Matches: `import.*[Pp]risma`+- Activates: `database-verification`++**Controller Detection:**+- File contains: `export class UserController {`+- Matches: `export class.*Controller`+- Activates: `error-tracking`++### Best Practices++- Match imports: `import.*[Pp]risma` (case-insensitive with [Pp])+- Escape special regex chars: `\\.findMany\\(` not `.findMany(`+- Patterns use case-insensitive flag+- Test against real file content+- Make patterns specific enough to avoid false matches++### Common Content Patterns++```regex+# Prisma/Database+import.*[Pp]risma # Prisma imports+PrismaService # PrismaService usage+prisma\. # prisma.something+\.findMany\( # Prisma query methods+\.create\(+\.update\(+\.delete\(++# Controllers/Routes+export class.*Controller # Controller classes+router\. # Express router+app\.(get|post|put|delete|patch) # Express app routes++# Error Handling+try\s*\{ # Try blocks+catch\s*\( # Catch blocks+throw new # Throw statements++# React/Components+export.*React\.FC # React functional components+export default function.* # Default function exports+useState|useEffect # React hooks+```++---++## Best Practices Summary++### DO:+β Use specific, unambiguous keywords+β Test all patterns with real examples+β Include common variations+β Use non-greedy regex: `.*?`+β Escape special characters in content patterns+β Add exclusions for test files+β Make file path patterns narrow and specific++### DON'T:+β Use overly generic keywords ("system", "work")+β Make intent patterns too broad (false positives)+β Make patterns too specific (false negatives)+β Forget to test with regex tester (https://regex101.com/)+β Use greedy regex: `.*` instead of `.*?`+β Match too broadly in file paths++### Testing Your Triggers++**Test keyword/intent triggers:**+```bash+echo '{"session_id":"test","prompt":"your test prompt"}' | \+ npx tsx .claude/hooks/skill-activation-prompt.ts+```++**Test file path/content triggers:**+```bash+cat <<'EOF' | npx tsx .claude/hooks/skill-verification-guard.ts+{+ "session_id": "test",+ "tool_name": "Edit",+ "tool_input": {"file_path": "/path/to/test/file.ts"}+}+EOF+```++---++**Related Files:**+- [SKILL.md](SKILL.md) - Main skill guide+- [SKILL_RULES_REFERENCE.md](SKILL_RULES_REFERENCE.md) - Complete skill-rules.json schema+- [PATTERNS_LIBRARY.md](PATTERNS_LIBRARY.md) - Ready-to-use pattern librarydiff --git a/.claude/skills/skill-developer/TROUBLESHOOTING.md b/.claude/skills/skill-developer/TROUBLESHOOTING.mdnew file mode 100644index 0000000000..f8cd3d38f6--- /dev/null+++ b/.claude/skills/skill-developer/TROUBLESHOOTING.md@@ -0,0 +1,514 @@+# Troubleshooting - Skill Activation Issues++Complete debugging guide for skill activation problems.++## Table of Contents++- [Skill Not Triggering](#skill-not-triggering)+ - [UserPromptSubmit Not Suggesting](#userpromptsubmit-not-suggesting)+ - [PreToolUse Not Blocking](#pretooluse-not-blocking)+- [False Positives](#false-positives)+- [Hook Not Executing](#hook-not-executing)+- [Performance Issues](#performance-issues)++---++## Skill Not Triggering++### UserPromptSubmit Not Suggesting++**Symptoms:** Ask a question, but no skill suggestion appears in output.++**Common Causes:**++#### 1. Keywords Don't Match++**Check:**+- Look at `promptTriggers.keywords` in skill-rules.json+- Are the keywords actually in your prompt?+- Remember: case-insensitive substring matching++**Example:**+```json+"keywords": ["layout", "grid"]+```+- "how does the layout work?" β β Matches "layout"+- "how does the grid system work?" β β Matches "grid"+- "how do layouts work?" β β Matches "layout"+- "how does it work?" β β No match++**Fix:** Add more keyword variations to skill-rules.json++#### 2. Intent Patterns Too Specific++**Check:**+- Look at `promptTriggers.intentPatterns`+- Test regex at https://regex101.com/+- May need broader patterns++**Example:**+```json+"intentPatterns": [+ "(create|add).*?(database.*?table)" // Too specific+]+```+- "create a database table" β β Matches+- "add new table" β β Doesn't match (missing "database")++**Fix:** Broaden the pattern:+```json+"intentPatterns": [+ "(create|add).*?(table|database)" // Better+]+```++#### 3. Typo in Skill Name++**Check:**+- Skill name in SKILL.md frontmatter+- Skill name in skill-rules.json+- Must match exactly++**Example:**+```yaml+# SKILL.md+name: project-catalog-developer+```+```json+// skill-rules.json+"project-catalogue-developer": { // β Typo: catalogue vs catalog+ ...+}+```++**Fix:** Make names match exactly++#### 4. JSON Syntax Error++**Check:**+```bash+cat .claude/skills/skill-rules.json | jq .+```++If invalid JSON, jq will show the error.++**Common errors:**+- Trailing commas+- Missing quotes+- Single quotes instead of double+- Unescaped characters in strings++**Fix:** Correct JSON syntax, validate with jq++#### Debug Command++Test the hook manually:++```bash+echo '{"session_id":"debug","prompt":"your test prompt here"}' | \+ npx tsx .claude/hooks/skill-activation-prompt.ts+```++Expected: Your skill should appear in the output.++---++### PreToolUse Not Blocking++**Symptoms:** Edit a file that should trigger a guardrail, but no block occurs.++**Common Causes:**++#### 1. File Path Doesn't Match Patterns++**Check:**+- File path being edited+- `fileTriggers.pathPatterns` in skill-rules.json+- Glob pattern syntax++**Example:**+```json+"pathPatterns": [+ "frontend/src/**/*.tsx"+]+```+- Editing: `frontend/src/components/Dashboard.tsx` β β Matches+- Editing: `frontend/tests/Dashboard.test.tsx` β β Matches (add exclusion!)+- Editing: `backend/src/app.ts` β β Doesn't match++**Fix:** Adjust glob patterns or add the missing path++#### 2. Excluded by pathExclusions++**Check:**+- Are you editing a test file?+- Look at `fileTriggers.pathExclusions`++**Example:**+```json+"pathExclusions": [+ "**/*.test.ts",+ "**/*.spec.ts"+]+```+- Editing: `services/user.test.ts` β β Excluded+- Editing: `services/user.ts` β β Not excluded++**Fix:** If test exclusion too broad, narrow it or remove++#### 3. Content Pattern Not Found++**Check:**+- Does the file actually contain the pattern?+- Look at `fileTriggers.contentPatterns`+- Is the regex correct?++**Example:**+```json+"contentPatterns": [+ "import.*[Pp]risma"+]+```+- File has: `import { PrismaService } from './prisma'` β β Matches+- File has: `import { Database } from './db'` β β Doesn't match++**Debug:**+```bash+# Check if pattern exists in file+grep -i "prisma" path/to/file.ts+```++**Fix:** Adjust content patterns or add missing imports++#### 4. Session Already Used Skill++**Check session state:**+```bash+ls .claude/hooks/state/+cat .claude/hooks/state/skills-used-{session-id}.json+```++**Example:**+```json+{+ "skills_used": ["database-verification"],+ "files_verified": []+}+```++If the skill is in `skills_used`, it won't block again in this session.++**Fix:** Delete the state file to reset:+```bash+rm .claude/hooks/state/skills-used-{session-id}.json+```++#### 5. File Marker Present++**Check file for skip marker:**+```bash+grep "@skip-validation" path/to/file.ts+```++If found, the file is permanently skipped.++**Fix:** Remove the marker if verification is needed again++#### 6. Environment Variable Override++**Check:**+```bash+echo $SKIP_DB_VERIFICATION+echo $SKIP_SKILL_GUARDRAILS+```++If set, the skill is disabled.++**Fix:** Unset the environment variable:+```bash+unset SKIP_DB_VERIFICATION+```++#### Debug Command++Test the hook manually:++```bash+cat <<'EOF' | npx tsx .claude/hooks/skill-verification-guard.ts 2>&1+{+ "session_id": "debug",+ "tool_name": "Edit",+ "tool_input": {"file_path": "/root/git/your-project/form/src/services/user.ts"}+}+EOF+echo "Exit code: $?"+```++Expected:+- Exit code 2 + stderr message if should block+- Exit code 0 + no output if should allow++---++## False Positives++**Symptoms:** Skill triggers when it shouldn't.++**Common Causes & Solutions:**++### 1. Keywords Too Generic++**Problem:**+```json+"keywords": ["user", "system", "create"] // Too broad+```+- Triggers on: "user manual", "file system", "create directory"++**Solution:** Make keywords more specific+```json+"keywords": [+ "user authentication",+ "user tracking",+ "create feature"+]+```++### 2. Intent Patterns Too Broad++**Problem:**+```json+"intentPatterns": [+ "(create)" // Matches everything with "create"+]+```+- Triggers on: "create file", "create folder", "create account"++**Solution:** Add context to patterns+```json+"intentPatterns": [+ "(create|add).*?(database|table|feature)" // More specific+]+```++**Advanced:** Use negative lookaheads to exclude+```regex+(create)(?!.*test).*?(feature) // Don't match if "test" appears+```++### 3. File Paths Too Generic++**Problem:**+```json+"pathPatterns": [+ "form/**" // Matches everything in form/+]+```+- Triggers on: test files, config files, everything++**Solution:** Use narrower patterns+```json+"pathPatterns": [+ "form/src/services/**/*.ts", // Only service files+ "form/src/controllers/**/*.ts"+]+```++### 4. Content Patterns Catching Unrelated Code++**Problem:**+```json+"contentPatterns": [+ "Prisma" // Matches in comments, strings, etc.+]+```+- Triggers on: `// Don't use Prisma here`+- Triggers on: `const note = "Prisma is cool"`++**Solution:** Make patterns more specific+```json+"contentPatterns": [+ "import.*[Pp]risma", // Only imports+ "PrismaService\\.", // Only actual usage+ "prisma\\.(findMany|create)" // Specific methods+]+```++### 5. Adjust Enforcement Level++**Last resort:** If false positives are frequent:++```json+{+ "enforcement": "block" // Change to "suggest"+}+```++This makes it advisory instead of blocking.++---++## Hook Not Executing++**Symptoms:** Hook doesn't run at all - no suggestion, no block.++**Common Causes:**++### 1. Hook Not Registered++**Check `.claude/settings.json`:**+```bash+cat .claude/settings.json | jq '.hooks.UserPromptSubmit'+cat .claude/settings.json | jq '.hooks.PreToolUse'+```++Expected: Hook entries present++**Fix:** Add missing hook registration:+```json+{+ "hooks": {+ "UserPromptSubmit": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/skill-activation-prompt.sh"+ }+ ]+ }+ ]+ }+}+```++### 2. Bash Wrapper Not Executable++**Check:**+```bash+ls -l .claude/hooks/*.sh+```++Expected: `-rwxr-xr-x` (executable)++**Fix:**+```bash+chmod +x .claude/hooks/*.sh+```++### 3. Incorrect Shebang++**Check:**+```bash+head -1 .claude/hooks/skill-activation-prompt.sh+```++Expected: `#!/bin/bash`++**Fix:** Add correct shebang to first line++### 4. npx/tsx Not Available++**Check:**+```bash+npx tsx --version+```++Expected: Version number++**Fix:** Install dependencies:+```bash+cd .claude/hooks+npm install+```++### 5. TypeScript Compilation Error++**Check:**+```bash+cd .claude/hooks+npx tsc --noEmit skill-activation-prompt.ts+```++Expected: No output (no errors)++**Fix:** Correct TypeScript syntax errors++---++## Performance Issues++**Symptoms:** Hooks are slow, noticeable delay before prompt/edit.++**Common Causes:**++### 1. Too Many Patterns++**Check:**+- Count patterns in skill-rules.json+- Each pattern = regex compilation + matching++**Solution:** Reduce patterns+- Combine similar patterns+- Remove redundant patterns+- Use more specific patterns (faster matching)++### 2. Complex Regex++**Problem:**+```regex+(create|add|modify|update|implement|build).*?(feature|endpoint|route|service|controller|component|UI|page)+```+- Long alternations = slow++**Solution:** Simplify+```regex+(create|add).*?(feature|endpoint) // Fewer alternatives+```++### 3. Too Many Files Checked++**Problem:**+```json+"pathPatterns": [+ "**/*.ts" // Checks ALL TypeScript files+]+```++**Solution:** Be more specific+```json+"pathPatterns": [+ "form/src/services/**/*.ts", // Only specific directory+ "form/src/controllers/**/*.ts"+]+```++### 4. Large Files++Content pattern matching reads entire file - slow for large files.++**Solution:**+- Only use content patterns when necessary+- Consider file size limits (future enhancement)++### Measure Performance++```bash+# UserPromptSubmit+time echo '{"prompt":"test"}' | npx tsx .claude/hooks/skill-activation-prompt.ts++# PreToolUse+time cat <<'EOF' | npx tsx .claude/hooks/skill-verification-guard.ts+{"tool_name":"Edit","tool_input":{"file_path":"test.ts"}}+EOF+```++**Target metrics:**+- UserPromptSubmit: < 100ms+- PreToolUse: < 200ms++---++**Related Files:**+- [SKILL.md](SKILL.md) - Main skill guide+- [HOOK_MECHANISMS.md](HOOK_MECHANISMS.md) - How hooks work+- [SKILL_RULES_REFERENCE.md](SKILL_RULES_REFERENCE.md) - Configuration referencediff --git a/.claude/skills/skill-rules.json b/.claude/skills/skill-rules.jsonnew file mode 100644index 0000000000..2395d6d2ca--- /dev/null+++ b/.claude/skills/skill-rules.json@@ -0,0 +1,84 @@+{+ "version": "1.0",+ "description": "Skill activation triggers for Claude Code. Controls when skills automatically suggest or block actions.",+ "skills": {+ "skill-developer": {+ "type": "domain",+ "enforcement": "suggest",+ "priority": "high",+ "description": "Meta-skill for creating and managing Claude Code skills",+ "promptTriggers": {+ "keywords": [+ "skill system",+ "create skill",+ "add skill",+ "skill triggers",+ "skill rules",+ "hook system",+ "skill development",+ "skill-rules.json"+ ],+ "intentPatterns": [+ "(how do|how does|explain).*?skill",+ "(create|add|modify|build).*?skill",+ "skill.*?(work|trigger|activate|system)"+ ]+ }+ },+ "backend-dev-guidelines": {+ "type": "domain",+ "enforcement": "suggest",+ "priority": "high",+ "description": "Backend development patterns for Node.js/NextJS/Express/TypeScript",+ "promptTriggers": {+ "keywords": [+ "backend",+ "backend development",+ "microservice",+ "controller",+ "service",+ "repository",+ "route",+ "routing",+ "express",+ "API",+ "endpoint",+ "middleware",+ "validation",+ "Zod",+ "Prisma",+ "database access",+ "BaseController",+ "dependency injection",+ "unifiedConfig",+ "configuration"+ ],+ "intentPatterns": [+ "(create|add|implement|build).*?(route|endpoint|API|controller|service|repository)",+ "(fix|handle|debug).*?(error|exception|backend)",+ "(add|implement).*?(middleware|validation|error.*?handling)",+ "(organize|structure|refactor).*?(backend|service|API)",+ "(how to|best practice).*?(backend|route|controller|service)"+ ]+ },+ "fileTriggers": {+ "pathPatterns": [+ "worker/src/**/*.ts",+ "packages/shared/src/**/*.ts",+ "web/src/**/*.ts"+ ],+ "pathExclusions": [+ "**/*.test.ts",+ "**/*.spec.ts"+ ],+ "contentPatterns": [+ "router\\.",+ "app\\.(get|post|put|delete|patch)",+ "export.*Controller",+ "export.*Service",+ "prisma\\."+ ]+ }+ }+ }+}\ No newline at end of filediff --git a/REVIEW.md b/REVIEW.mdindex 47d2a5e905..ee9dfac627 100644--- a/REVIEW.md+++ b/REVIEW.md@@ -37,4 +37,9 @@- `h-screen-with-banner` / `min-h-screen-with-banner` - For full-height containers accounting for banners## JavaScript / TypeScript Style+- use concat instead of spread to avoid stack overflow with large arrays++## Seeder++- make sure that for new features with data model changes, the database seeder is adjusted.