diff --git a/deployment-quickstart/.env.example b/deployment-quickstart/.env.example new file mode 100644 index 00000000..f3c060b6 --- /dev/null +++ b/deployment-quickstart/.env.example @@ -0,0 +1,103 @@ +# Tractatus Framework - Environment Configuration Template +# Copy this file to .env and fill in your actual values + +#============================================================================= +# REQUIRED: Database Configuration +#============================================================================= +MONGODB_USERNAME=tractatus +MONGODB_PASSWORD=YOUR_SECURE_PASSWORD_HERE # CHANGE THIS! +MONGODB_DATABASE=tractatus_prod +MONGODB_PORT=27017 +MONGODB_URI=mongodb://tractatus:YOUR_SECURE_PASSWORD_HERE@mongodb:27017/tractatus_prod?authSource=admin + +#============================================================================= +# REQUIRED: Application Configuration +#============================================================================= +NODE_ENV=production +APP_PORT=9000 +BASE_URL=https://your-domain.com # Your production URL + +# JWT Secret (generate with: openssl rand -base64 32) +JWT_SECRET=YOUR_JWT_SECRET_HERE # CHANGE THIS! + +# Session Secret (generate with: openssl rand -base64 32) +SESSION_SECRET=YOUR_SESSION_SECRET_HERE # CHANGE THIS! + +#============================================================================= +# REQUIRED: Admin Account +#============================================================================= +ADMIN_EMAIL=admin@your-domain.com +ADMIN_PASSWORD=YOUR_ADMIN_PASSWORD_HERE # CHANGE THIS! + +#============================================================================= +# REQUIRED: Anthropic API (for AI-assisted features) +#============================================================================= +ANTHROPIC_API_KEY=sk-ant-your-api-key-here # Get from console.anthropic.com + +#============================================================================= +# Governance Services (5 Core Components) +#============================================================================= +BOUNDARY_ENFORCER_ENABLED=true +CONTEXT_PRESSURE_ENABLED=true +CROSS_REF_VALIDATOR_ENABLED=true +PERSISTENCE_CLASSIFIER_ENABLED=true +METACOGNITIVE_VERIFIER_ENABLED=true + +#============================================================================= +# Rate Limiting & Performance +#============================================================================= +RATE_LIMIT_WINDOW_MS=900000 # 15 minutes +RATE_LIMIT_MAX_REQUESTS=100 # Max requests per window +MAX_FILE_SIZE=10485760 # 10MB max upload size + +#============================================================================= +# Feature Flags +#============================================================================= +BLOG_ENABLED=true +KOHA_ENABLED=true # Donation system +DEMOS_ENABLED=true # Interactive demos +ANALYTICS_ENABLED=false # Privacy-preserving analytics + +#============================================================================= +# Optional: Email Configuration (for notifications) +#============================================================================= +# SMTP_HOST=smtp.example.com +# SMTP_PORT=587 +# SMTP_USER=noreply@your-domain.com +# SMTP_PASSWORD=your-email-password +# SMTP_FROM_NAME=Tractatus Framework +# SMTP_FROM_EMAIL=noreply@your-domain.com + +#============================================================================= +# Optional: Stripe (for Koha donations) +#============================================================================= +# STRIPE_SECRET_KEY=sk_live_your-stripe-key +# STRIPE_PUBLIC_KEY=pk_live_your-stripe-key +# STRIPE_WEBHOOK_SECRET=whsec_your-webhook-secret + +#============================================================================= +# Optional: Analytics (Privacy-Preserving) +#============================================================================= +# PLAUSIBLE_DOMAIN=your-domain.com +# PLAUSIBLE_API_KEY=your-plausible-key + +#============================================================================= +# Security Headers +#============================================================================= +HELMET_ENABLED=true +CSP_ENABLED=true +CORS_ORIGIN=https://your-domain.com # Comma-separated for multiple origins + +#============================================================================= +# Logging +#============================================================================= +LOG_LEVEL=info # debug, info, warn, error +LOG_TO_FILE=true +LOG_TO_CONSOLE=true + +#============================================================================= +# Development/Testing (disable in production) +#============================================================================= +# DEBUG=false +# VERBOSE_LOGGING=false +# ENABLE_DEBUGGING_ENDPOINTS=false diff --git a/deployment-quickstart/Dockerfile b/deployment-quickstart/Dockerfile new file mode 100644 index 00000000..e1c22ea5 --- /dev/null +++ b/deployment-quickstart/Dockerfile @@ -0,0 +1,53 @@ +# Multi-stage build for production deployment +FROM node:18-alpine AS builder + +WORKDIR /app + +# Copy package files +COPY package*.json ./ + +# Install dependencies +RUN npm ci --only=production && npm cache clean --force + +# Production stage +FROM node:18-alpine + +# Set production environment +ENV NODE_ENV=production + +WORKDIR /app + +# Install curl for healthchecks +RUN apk add --no-cache curl wget + +# Create non-root user +RUN addgroup -g 1001 -S nodejs && \ + adduser -S nodejs -u 1001 + +# Copy dependencies from builder +COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules + +# Copy application code +COPY --chown=nodejs:nodejs ../src ./src +COPY --chown=nodejs:nodejs ../public ./public +COPY --chown=nodejs:nodejs ../scripts ./scripts +COPY --chown=nodejs:nodejs ../docs ./docs +COPY --chown=nodejs:nodejs ../package*.json ./ +COPY --chown=nodejs:nodejs ../.claude ./.claude + +# Create necessary directories +RUN mkdir -p logs uploads audit-reports && \ + chown -R nodejs:nodejs logs uploads audit-reports + +# Switch to non-root user +USER nodejs + +# Expose application port +EXPOSE 9000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \ + CMD wget --quiet --tries=1 --spider http://localhost:9000/api/health || exit 1 + +# Start application +CMD ["node", "src/server.js"] diff --git a/deployment-quickstart/README.md b/deployment-quickstart/README.md new file mode 100644 index 00000000..75993ee8 --- /dev/null +++ b/deployment-quickstart/README.md @@ -0,0 +1,475 @@ +# Tractatus Framework - Deployment Quickstart Kit + +**Deploy Tractatus in 30 minutes** - Production-ready Docker deployment with all 5 governance services. + +## 🎯 What You Get + +- **MongoDB 7.0** - Database for governance rules and audit logs +- **Node.js Application** - Web interface and API +- **5 Core Governance Services:** + - BoundaryEnforcer - Prevents automation of values decisions + - InstructionPersistenceClassifier - Classifies and stores instructions + - CrossReferenceValidator - Prevents pattern bias override + - ContextPressureMonitor - Detects degraded operating conditions + - MetacognitiveVerifier - Self-checks complex reasoning +- **Sample Governance Rules** - 10 example rules to get started +- **Verification Script** - Automated deployment testing +- **Troubleshooting Guide** - Common issues and solutions + +--- + +## πŸ“‹ Prerequisites + +### Required + +- **Docker** 20.10+ ([Install Docker](https://docs.docker.com/get-docker/)) +- **Docker Compose** 2.0+ (included with Docker Desktop) +- **2GB RAM minimum** (4GB recommended) +- **10GB disk space** + +### Recommended + +- **Domain name** with DNS configured +- **SSL certificate** (Let's Encrypt recommended) +- **Anthropic API key** (for AI-assisted features) + +### Check Your System + +```bash +docker --version # Should be 20.10+ +docker compose version # Should be 2.0+ +``` + +--- + +## πŸš€ Quick Start (30 Minutes) + +### Step 1: Download and Extract (2 minutes) + +```bash +# Download deployment package +wget https://agenticgovernance.digital/downloads/tractatus-quickstart.tar.gz + +# Extract +tar -xzf tractatus-quickstart.tar.gz +cd tractatus-quickstart +``` + +### Step 2: Configure Environment (5 minutes) + +```bash +# Copy environment template +cp .env.example .env + +# Edit configuration +nano .env # or vi, emacs, code, etc. +``` + +**⚠️ CRITICAL: Update these values in .env:** + +```bash +# Generate secure secrets: +openssl rand -base64 32 # Use for JWT_SECRET +openssl rand -base64 32 # Use for SESSION_SECRET +openssl rand -base64 32 # Use for MONGODB_PASSWORD + +# Required changes: +MONGODB_PASSWORD= +JWT_SECRET= +SESSION_SECRET= +ADMIN_PASSWORD= +ADMIN_EMAIL=admin@your-domain.com +BASE_URL=https://your-domain.com +ANTHROPIC_API_KEY=sk-ant-your-key-here # Get from console.anthropic.com +``` + +### Step 3: Build and Start (10 minutes) + +```bash +# Build containers +docker compose build + +# Start services +docker compose up -d + +# Watch logs (Ctrl+C to exit, containers keep running) +docker compose logs -f +``` + +**Wait for:** `Server started on port 9000` and `MongoDB connected successfully` + +### Step 4: Initialize Database (3 minutes) + +```bash +# Create admin account and seed initial data +docker compose exec tractatus-app node scripts/seed-admin.js +docker compose exec tractatus-app node scripts/init-db.js + +# Optional: Load sample governance rules +docker compose exec tractatus-app node scripts/load-governance-rules.js sample-governance-rules.json +``` + +### Step 5: Verify Deployment (5 minutes) + +```bash +# Run automated verification +chmod +x verify-deployment.sh +./verify-deployment.sh +``` + +**Expected output:** +``` +╔════════════════════════════════════════════════════════════════════╗ +β•‘ Verification Results β•‘ +β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• + + Passed: 20 tests + Failed: 0 tests + Warnings: 2 tests + +βœ“ All critical tests passed! Deployment is ready. +``` + +### Step 6: Access Your Deployment (5 minutes) + +1. **Homepage:** http://localhost:9000 (or your domain) +2. **Admin Panel:** http://localhost:9000/admin + - Email: (from .env) + - Password: (from .env) +3. **API Health:** http://localhost:9000/api/health +4. **Interactive Demos:** http://localhost:9000/demos/tractatus-demo.html + +--- + +## πŸ”§ Configuration Guide + +### Basic Configuration + +**Minimal .env for local development:** + +```bash +NODE_ENV=development +MONGODB_PASSWORD=dev_password_123 +JWT_SECRET=dev_jwt_secret_456 +SESSION_SECRET=dev_session_secret_789 +ADMIN_PASSWORD=admin123 +ADMIN_EMAIL=admin@localhost +ANTHROPIC_API_KEY=sk-ant-your-key +``` + +### Production Configuration + +**Recommended .env for production:** + +```bash +NODE_ENV=production +BASE_URL=https://your-domain.com + +# Secrets (use openssl rand -base64 32) +MONGODB_PASSWORD= +JWT_SECRET= +SESSION_SECRET= + +# Admin +ADMIN_EMAIL=admin@your-domain.com +ADMIN_PASSWORD= + +# API +ANTHROPIC_API_KEY=sk-ant-your-production-key + +# Security +HELMET_ENABLED=true +CSP_ENABLED=true +CORS_ORIGIN=https://your-domain.com + +# Performance +RATE_LIMIT_MAX_REQUESTS=100 +RATE_LIMIT_WINDOW_MS=900000 + +# Features +BLOG_ENABLED=true +KOHA_ENABLED=true +DEMOS_ENABLED=true +ANALYTICS_ENABLED=false # Set to true after configuring Plausible +``` + +### Governance Service Configuration + +Enable/disable individual services: + +```bash +BOUNDARY_ENFORCER_ENABLED=true # Blocks values decisions +CONTEXT_PRESSURE_ENABLED=true # Monitors session degradation +CROSS_REF_VALIDATOR_ENABLED=true # Prevents pattern bias +PERSISTENCE_CLASSIFIER_ENABLED=true # Classifies instructions +METACOGNITIVE_VERIFIER_ENABLED=true # Self-verification +``` + +--- + +## πŸ“Š Governance Rules + +### Loading Sample Rules + +The deployment includes 10 sample governance rules covering: + +- **Strategic:** Values decisions, Te Tiriti commitments +- **Operational:** Classification, context pressure +- **System:** Database configuration, project isolation +- **Security:** Content Security Policy enforcement +- **Quality:** World-class standards + +**Load rules:** + +```bash +docker compose exec tractatus-app node scripts/load-governance-rules.js sample-governance-rules.json +``` + +### Creating Custom Rules + +See `sample-governance-rules.json` for the schema. Each rule includes: + +```json +{ + "rule_id": "CUSTOM-001", + "quadrant": "STRATEGIC|OPERATIONAL|TACTICAL|SYSTEM|STOCHASTIC", + "persistence": "HIGH|MEDIUM|LOW|VARIABLE", + "title": "Rule Title", + "content": "What the rule enforces", + "enforced_by": "BoundaryEnforcer|CrossReferenceValidator|...", + "violation_action": "BLOCK_AND_ESCALATE|WARN|LOG", + "examples": ["Example 1", "Example 2"], + "rationale": "Why this rule exists" +} +``` + +--- + +## πŸ§ͺ Testing Your Deployment + +### Manual Tests + +**1. Test Homepage:** +```bash +curl http://localhost:9000/ +# Should return HTML homepage +``` + +**2. Test API Health:** +```bash +curl http://localhost:9000/api/health +# Should return: {"status":"ok","database":"connected"} +``` + +**3. Test BoundaryEnforcer:** +```bash +curl -X POST http://localhost:9000/api/demo/boundary-check \ + -H "Content-Type: application/json" \ + -d '{"scenario":"privacy-decision"}' +# Should return: {"allowed":false,"reason":"Values decision requires human approval"} +``` + +**4. Test Classification:** +```bash +curl -X POST http://localhost:9000/api/demo/classify \ + -H "Content-Type: application/json" \ + -d '{"instruction":"Use MongoDB port 27027"}' +# Should return classification with quadrant and persistence +``` + +### Automated Test Suite + +```bash +# Run all tests +docker compose exec tractatus-app npm test + +# Run specific test suites +docker compose exec tractatus-app npm run test:unit +docker compose exec tractatus-app npm run test:integration +docker compose exec tractatus-app npm run test:security +``` + +--- + +## πŸ“ˆ Monitoring & Maintenance + +### View Logs + +```bash +# All logs +docker compose logs -f + +# Application only +docker compose logs -f tractatus-app + +# MongoDB only +docker compose logs -f mongodb + +# Last 100 lines +docker compose logs --tail=100 tractatus-app +``` + +### Check Resource Usage + +```bash +docker stats +``` + +### Backup Database + +```bash +# Create backup +docker exec tractatus-mongodb mongodump \ + --db tractatus_prod \ + --out /tmp/backup + +# Copy backup to host +docker cp tractatus-mongodb:/tmp/backup ./mongodb-backup-$(date +%Y%m%d) +``` + +### Restore Database + +```bash +# Copy backup to container +docker cp ./mongodb-backup-20251012 tractatus-mongodb:/tmp/restore + +# Restore +docker exec tractatus-mongodb mongorestore \ + --db tractatus_prod \ + /tmp/restore/tractatus_prod +``` + +--- + +## πŸ”„ Updating + +### Update Application Code + +```bash +# Pull latest code +git pull origin main + +# Rebuild containers +docker compose build + +# Restart with zero downtime +docker compose up -d +``` + +### Update Dependencies + +```bash +# Update package.json +docker compose exec tractatus-app npm update + +# Rebuild +docker compose build +docker compose up -d +``` + +--- + +## πŸ›‘ Stopping & Restarting + +### Stop Services + +```bash +# Stop all services (data persists) +docker compose down + +# Stop and remove volumes (⚠️ destroys data) +docker compose down -v +``` + +### Restart Services + +```bash +# Restart all +docker compose restart + +# Restart specific service +docker compose restart tractatus-app +``` + +--- + +## 🚨 Troubleshooting + +See [TROUBLESHOOTING.md](./TROUBLESHOOTING.md) for detailed solutions to common issues: + +- Docker container won't start +- Database connection failures +- Port conflicts +- Governance services not responding +- Performance issues +- Security errors + +**Quick diagnostic:** + +```bash +./verify-deployment.sh +``` + +--- + +## πŸ“š Next Steps + +1. **Customize Governance Rules** - Edit `sample-governance-rules.json` for your use case +2. **Configure SSL** - Set up HTTPS with Let's Encrypt +3. **Set Up Monitoring** - Configure Plausible Analytics (privacy-preserving) +4. **Create Admin Users** - Add team members to admin panel +5. **Review Documentation** - https://agenticgovernance.digital/docs +6. **Join Community** - Submit case studies, contribute rules + +--- + +## 🀝 Support + +- **Documentation:** https://agenticgovernance.digital/docs +- **Interactive Demos:** https://agenticgovernance.digital/demos +- **Case Studies:** https://agenticgovernance.digital/docs/case-studies +- **GitHub Issues:** https://github.com/AgenticGovernance/tractatus-framework/issues +- **Email:** research@agenticgovernance.digital + +--- + +## πŸ“„ License + +Apache License 2.0 - See LICENSE file for details + +--- + +## 🎯 Architecture Overview + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Docker Network β”‚ +β”‚ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ MongoDB 7.0 β”‚ β”‚ Tractatus App β”‚ β”‚ +β”‚ β”‚ Port: 27017 │◄─────────── Port: 9000 β”‚ β”‚ +β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ +β”‚ β”‚ - tractatus_prodβ”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ +β”‚ β”‚ - Governance β”‚ β”‚ β”‚ 5 Core Services β”‚ β”‚ β”‚ +β”‚ β”‚ Rules β”‚ β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ β”‚ +β”‚ β”‚ - Audit Logs β”‚ β”‚ β”‚ β€’ Boundary β”‚ β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β€’ Classifier β”‚ β”‚ β”‚ +β”‚ β”‚ β”‚ β€’ Validator β”‚ β”‚ β”‚ +β”‚ β”‚ β”‚ β€’ Pressure β”‚ β”‚ β”‚ +β”‚ β”‚ β”‚ β€’ Verifier β”‚ β”‚ β”‚ +β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”‚ HTTP/HTTPS + β–Ό + [Your Users] +``` + +--- + +**Version:** 1.0.0 +**Last Updated:** October 12, 2025 +**Maintainer:** Tractatus Framework Team + +**Ready to deploy? Run:** `docker compose up -d` diff --git a/deployment-quickstart/TROUBLESHOOTING.md b/deployment-quickstart/TROUBLESHOOTING.md new file mode 100644 index 00000000..a9dab4c3 --- /dev/null +++ b/deployment-quickstart/TROUBLESHOOTING.md @@ -0,0 +1,448 @@ +# Tractatus Deployment Troubleshooting Guide + +This guide covers common issues when deploying the Tractatus Framework. + +## Table of Contents + +1. [Docker Issues](#docker-issues) +2. [Database Connection Problems](#database-connection-problems) +3. [Application Won't Start](#application-wont-start) +4. [Governance Services Not Working](#governance-services-not-working) +5. [Performance Issues](#performance-issues) +6. [Security & Access Issues](#security--access-issues) + +--- + +## Docker Issues + +### Container Won't Start + +**Symptom:** `docker compose up` fails or container exits immediately + +**Solutions:** + +1. **Check Docker daemon is running:** + ```bash + docker info + ``` + +2. **Check for port conflicts:** + ```bash + lsof -i :9000 # Check if port 9000 is in use + lsof -i :27017 # Check if MongoDB port is in use + ``` + +3. **View container logs:** + ```bash + docker compose logs tractatus-app + docker compose logs mongodb + ``` + +4. **Remove and rebuild:** + ```bash + docker compose down -v + docker compose build --no-cache + docker compose up + ``` + +--- + +### Permission Denied Errors + +**Symptom:** Container logs show "EACCES: permission denied" + +**Solution:** + +1. **Fix directory permissions:** + ```bash + chmod -R 755 deployment-quickstart/ + chown -R 1001:1001 logs uploads audit-reports + ``` + +2. **Check Docker user mapping:** + - Container runs as user ID 1001 (nodejs) + - Ensure host directories are accessible + +--- + +## Database Connection Problems + +### Cannot Connect to MongoDB + +**Symptom:** Application logs show "MongoServerError" or "ECONNREFUSED" + +**Solutions:** + +1. **Check MongoDB is running:** + ```bash + docker compose ps mongodb + docker compose logs mongodb + ``` + +2. **Verify MongoDB health:** + ```bash + docker exec tractatus-mongodb mongosh --eval "db.runCommand({ ping: 1 })" + ``` + +3. **Check connection string in .env:** + ```bash + # Ensure MONGODB_URI format is correct: + mongodb://tractatus:YOUR_PASSWORD@mongodb:27017/tractatus_prod?authSource=admin + ``` + +4. **Reset MongoDB:** + ```bash + docker compose down + docker volume rm tractatus_mongodb_data + docker compose up -d mongodb + # Wait 30 seconds for initialization + docker compose up tractatus-app + ``` + +--- + +### Authentication Failed + +**Symptom:** "Authentication failed" in logs + +**Solution:** + +1. **Check credentials in .env:** + ```bash + grep MONGODB_ .env + ``` + +2. **Ensure username/password match in docker-compose.yml and .env** + +3. **Reset MongoDB authentication:** + ```bash + docker compose down + docker volume rm tractatus_mongodb_data tractatus_mongodb_config + docker compose up -d + ``` + +--- + +## Application Won't Start + +### Port Already in Use + +**Symptom:** "Error: listen EADDRINUSE: address already in use :::9000" + +**Solution:** + +1. **Find process using port 9000:** + ```bash + lsof -i :9000 + kill -9 + ``` + +2. **Or change port in .env:** + ```bash + APP_PORT=9001 + ``` + + Update docker-compose.yml ports section: + ```yaml + ports: + - "9001:9000" + ``` + +--- + +### Missing Environment Variables + +**Symptom:** Application starts but features don't work + +**Solution:** + +1. **Verify all required .env variables are set:** + ```bash + ./verify-deployment.sh + ``` + +2. **Check for default/placeholder values:** + ```bash + grep "CHANGE THIS" .env + grep "YOUR_" .env + ``` + +3. **Generate secure secrets:** + ```bash + # JWT Secret + openssl rand -base64 32 + + # Session Secret + openssl rand -base64 32 + ``` + +--- + +## Governance Services Not Working + +### BoundaryEnforcer Not Blocking + +**Symptom:** Values decisions not being blocked + +**Solutions:** + +1. **Check service is enabled in .env:** + ```bash + grep BOUNDARY_ENFORCER_ENABLED .env + # Should be: BOUNDARY_ENFORCER_ENABLED=true + ``` + +2. **Test endpoint directly:** + ```bash + curl -X POST http://localhost:9000/api/demo/boundary-check \ + -H "Content-Type: application/json" \ + -d '{"scenario":"privacy-decision"}' + ``` + +3. **Check application logs:** + ```bash + docker compose logs tractatus-app | grep BoundaryEnforcer + ``` + +--- + +### Classification Not Working + +**Symptom:** Instructions not being classified + +**Solutions:** + +1. **Check InstructionPersistenceClassifier is enabled:** + ```bash + grep PERSISTENCE_CLASSIFIER_ENABLED .env + ``` + +2. **Verify instruction history file exists:** + ```bash + docker exec tractatus-app ls -la .claude/instruction-history.json + ``` + +3. **Test classification endpoint:** + ```bash + curl -X POST http://localhost:9000/api/demo/classify \ + -H "Content-Type: application/json" \ + -d '{"instruction":"Use MongoDB port 27027"}' + ``` + +--- + +### Context Pressure Not Monitoring + +**Symptom:** No pressure warnings even under load + +**Solutions:** + +1. **Verify ContextPressureMonitor is enabled:** + ```bash + grep CONTEXT_PRESSURE_ENABLED .env + ``` + +2. **Check token tracking:** + ```bash + docker compose logs tractatus-app | grep "Context Pressure" + ``` + +3. **Test pressure check:** + ```bash + curl -X POST http://localhost:9000/api/demo/pressure-check \ + -H "Content-Type: application/json" \ + -d '{"tokens":150000,"messages":50,"errors":5}' + ``` + +--- + +## Performance Issues + +### Slow Response Times + +**Symptom:** API requests taking >2 seconds + +**Solutions:** + +1. **Check MongoDB indexes:** + ```bash + docker exec tractatus-mongodb mongosh tractatus_prod --eval "db.getCollectionNames().forEach(function(col) { print(col); db[col].getIndexes(); })" + ``` + +2. **Monitor container resources:** + ```bash + docker stats tractatus-app tractatus-mongodb + ``` + +3. **Increase container memory limits in docker-compose.yml:** + ```yaml + deploy: + resources: + limits: + memory: 2G + reservations: + memory: 1G + ``` + +4. **Check for query bottlenecks:** + ```bash + docker compose logs tractatus-app | grep "slow query" + ``` + +--- + +### High Memory Usage + +**Symptom:** Container using excessive memory + +**Solutions:** + +1. **Check for memory leaks:** + ```bash + docker stats --no-stream tractatus-app + ``` + +2. **Restart container periodically:** + ```bash + docker compose restart tractatus-app + ``` + +3. **Reduce rate limit max requests in .env:** + ```bash + RATE_LIMIT_MAX_REQUESTS=50 + ``` + +--- + +## Security & Access Issues + +### CORS Errors + +**Symptom:** Browser console shows "blocked by CORS policy" + +**Solution:** + +1. **Update CORS_ORIGIN in .env:** + ```bash + CORS_ORIGIN=https://your-domain.com,https://www.your-domain.com + ``` + +2. **For development, allow localhost:** + ```bash + CORS_ORIGIN=http://localhost:9000,http://127.0.0.1:9000 + ``` + +--- + +### CSP Violations + +**Symptom:** Browser console shows "Content Security Policy" errors + +**Solution:** + +1. **Check CSP configuration:** + ```bash + curl -I http://localhost:9000 | grep Content-Security-Policy + ``` + +2. **Temporarily disable CSP for debugging:** + ```bash + CSP_ENABLED=false + ``` + +3. **Fix inline styles/scripts in HTML files** (don't disable CSP in production!) + +--- + +### Admin Login Not Working + +**Symptom:** Cannot log in to /admin + +**Solutions:** + +1. **Verify admin account exists:** + ```bash + docker exec tractatus-mongodb mongosh tractatus_prod --eval "db.users.findOne({role:'admin'})" + ``` + +2. **Reset admin password:** + ```bash + docker compose run --rm tractatus-app node scripts/seed-admin.js + ``` + +3. **Check JWT_SECRET is set:** + ```bash + grep JWT_SECRET .env + ``` + +--- + +## Still Having Issues? + +### Collect Diagnostic Information + +```bash +# Create diagnostic report +cat > diagnostic-report.txt <3 files, >5 steps, architecture changes, or security implementations require metacognitive self-verification before execution", + "enforced_by": "MetacognitiveVerifier", + "violation_action": "VERIFY_BEFORE_EXECUTE", + "verification_criteria": [ + "Alignment: Does proposed action align with user intent and stored instructions?", + "Coherence: Is the solution internally consistent and well-structured?", + "Completeness: Are all requirements addressed? Any edge cases missed?", + "Safety: Are there security, privacy, or values concerns?", + "Alternatives: What other approaches were considered? Why is this optimal?" + ], + "confidence_threshold": 0.85, + "examples": [ + "Database schema changes β†’ Verify against architecture principles", + "Security implementation β†’ Self-check for vulnerabilities", + "Multi-service integration β†’ Verify coherence and completeness" + ], + "rationale": "Structural pause-and-verify reduces errors in complex operations" + }, + { + "rule_id": "SYS-001", + "quadrant": "SYSTEM", + "persistence": "HIGH", + "title": "Database Port Configuration", + "content": "MongoDB must run on port 27017 for tractatus_dev (development) and port 27017 for tractatus_prod (production). No other ports allowed without explicit HIGH persistence instruction override", + "enforced_by": "CrossReferenceValidator", + "violation_action": "VALIDATE_BEFORE_CHANGE", + "examples": [ + "Attempting to change MongoDB port β†’ Cross-reference against instruction history", + "Config file modification β†’ Verify against SYS quadrant HIGH persistence rules" + ], + "rationale": "Prevents accidental configuration drift" + }, + { + "rule_id": "SYS-002", + "quadrant": "SYSTEM", + "persistence": "HIGH", + "title": "No Shared Code with Other Projects", + "content": "Tractatus project is separate from family-history and sydigital projects. No shared code, no copy-paste, no assumptions about shared infrastructure", + "enforced_by": "BoundaryEnforcer", + "violation_action": "BLOCK_AND_ALERT", + "examples": [ + "Attempting to reference family-history code β†’ BLOCK", + "Assuming shared database β†’ BLOCK and clarify separation" + ], + "rationale": "Project isolation prevents cross-contamination and maintains independence" + }, + { + "rule_id": "SEC-001", + "quadrant": "SYSTEM", + "persistence": "HIGH", + "title": "Content Security Policy Enforcement", + "content": "All HTML files must comply with Content Security Policy: no inline event handlers (onclick=), no inline styles (style=), no inline scripts ( β†’ BLOCKED (use external .js files)" + ], + "rationale": "CSP prevents XSS attacks and maintains security posture" + }, + { + "rule_id": "VAL-001", + "quadrant": "STRATEGIC", + "persistence": "HIGH", + "title": "Te Tiriti o Waitangi Commitment", + "content": "All decisions affecting Māori data, indigenous sovereignty, cultural content, or Te Reo Māori translations require consultation and respect for CARE Principles (Collective benefit, Authority to control, Responsibility, Ethics)", + "enforced_by": "BoundaryEnforcer", + "violation_action": "BLOCK_AND_ESCALATE", + "examples": [ + "Te Reo Māori content changes β†’ Require Māori language consultation", + "Indigenous data handling β†’ Apply CARE Principles", + "Cultural appropriateness questions β†’ Escalate to human review" + ], + "rationale": "Core values alignment - sovereignty and indigenous rights protection", + "boundary_section": "12.1" + }, + { + "rule_id": "QUAL-001", + "quadrant": "OPERATIONAL", + "persistence": "HIGH", + "title": "World-Class Quality Standard", + "content": "All code, documentation, and content must meet world-class quality standards. No shortcuts, no fake data, no placeholders in production. If quality cannot be achieved, defer the feature", + "enforced_by": "MetacognitiveVerifier", + "violation_action": "VERIFY_QUALITY_BEFORE_COMMIT", + "examples": [ + "Lorem ipsum placeholder text β†’ BLOCK", + "TODO comments in production code β†’ REVIEW", + "Hardcoded test data β†’ BLOCK", + "Incomplete error handling β†’ BLOCK" + ], + "rationale": "Quality is non-negotiable - reflects framework credibility" + } + ], + "metadata": { + "created": "2025-10-12", + "version": "1.0.0", + "license": "Apache-2.0", + "framework_version": "0.1.0", + "total_rules": 10, + "governance_services": [ + "BoundaryEnforcer", + "CrossReferenceValidator", + "ContextPressureMonitor", + "InstructionPersistenceClassifier", + "MetacognitiveVerifier" + ] + } +} diff --git a/deployment-quickstart/verify-deployment.sh b/deployment-quickstart/verify-deployment.sh new file mode 100755 index 00000000..aeceb01c --- /dev/null +++ b/deployment-quickstart/verify-deployment.sh @@ -0,0 +1,242 @@ +#!/bin/bash + +#============================================================================= +# Tractatus Deployment Verification Script +# +# Runs comprehensive checks to verify deployment is working correctly +# +# Usage: ./verify-deployment.sh +#============================================================================= + +set -e + +# Colors for output +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +RED='\033[0;31m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Test results +PASSED=0 +FAILED=0 +WARNINGS=0 + +echo -e "${BLUE}╔════════════════════════════════════════════════════════════════════╗${NC}" +echo -e "${BLUE}β•‘ Tractatus Framework - Deployment Verification β•‘${NC}" +echo -e "${BLUE}β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•${NC}" +echo "" + +#============================================================================= +# Helper Functions +#============================================================================= + +pass() { + echo -e "${GREEN}βœ“${NC} $1" + ((PASSED++)) +} + +fail() { + echo -e "${RED}βœ—${NC} $1" + ((FAILED++)) +} + +warn() { + echo -e "${YELLOW}⚠${NC} $1" + ((WARNINGS++)) +} + +section() { + echo "" + echo -e "${BLUE}β–Ά $1${NC}" + echo "────────────────────────────────────────────────────────────" +} + +#============================================================================= +# 1. Environment Check +#============================================================================= + +section "1. Environment Variables" + +if [ -f ".env" ]; then + pass "Found .env file" + + # Check for required variables + required_vars=( + "MONGODB_PASSWORD" + "JWT_SECRET" + "SESSION_SECRET" + "ADMIN_PASSWORD" + "ANTHROPIC_API_KEY" + ) + + for var in "${required_vars[@]}"; do + if grep -q "^${var}=" .env && ! grep -q "^${var}=.*CHANGE.*" .env && ! grep -q "^${var}=.*YOUR.*" .env; then + pass "$var is set" + else + fail "$var is missing or using default value" + fi + done +else + fail ".env file not found (copy from .env.example)" +fi + +#============================================================================= +# 2. Docker Services +#============================================================================= + +section "2. Docker Services" + +if command -v docker &> /dev/null; then + pass "Docker is installed" + + if docker compose ps | grep -q "tractatus-mongodb.*Up"; then + pass "MongoDB container is running" + else + fail "MongoDB container is not running" + fi + + if docker compose ps | grep -q "tractatus-app.*Up"; then + pass "Application container is running" + else + fail "Application container is not running" + fi +else + fail "Docker is not installed" +fi + +#============================================================================= +# 3. Network Connectivity +#============================================================================= + +section "3. Network Connectivity" + +APP_URL="${BASE_URL:-http://localhost:9000}" + +if curl -s -o /dev/null -w "%{http_code}" "${APP_URL}/api/health" | grep -q "200"; then + pass "API health endpoint responding (${APP_URL}/api/health)" +else + fail "API health endpoint not responding" +fi + +if curl -s -o /dev/null -w "%{http_code}" "${APP_URL}/" | grep -q "200"; then + pass "Homepage accessible (${APP_URL}/)" +else + fail "Homepage not accessible" +fi + +#============================================================================= +# 4. Database Connectivity +#============================================================================= + +section "4. Database Connectivity" + +if docker exec tractatus-mongodb mongosh --eval "db.runCommand({ ping: 1 })" --quiet &> /dev/null; then + pass "MongoDB is accepting connections" + + # Check if database exists + if docker exec tractatus-mongodb mongosh --eval "use ${MONGODB_DATABASE:-tractatus_prod}; db.stats()" --quiet &> /dev/null; then + pass "Database '${MONGODB_DATABASE:-tractatus_prod}' exists" + else + warn "Database '${MONGODB_DATABASE:-tractatus_prod}' not initialized yet" + fi +else + fail "Cannot connect to MongoDB" +fi + +#============================================================================= +# 5. Governance Services +#============================================================================= + +section "5. Governance Services" + +# Test BoundaryEnforcer +if curl -s -X POST "${APP_URL}/api/demo/boundary-check" \ + -H "Content-Type: application/json" \ + -d '{"scenario":"privacy-decision"}' | grep -q "allowed"; then + pass "BoundaryEnforcer service responding" +else + warn "BoundaryEnforcer service not responding (may not be implemented yet)" +fi + +# Test Classification +if curl -s -X POST "${APP_URL}/api/demo/classify" \ + -H "Content-Type: application/json" \ + -d '{"instruction":"Test instruction"}' | grep -q "quadrant"; then + pass "InstructionPersistenceClassifier service responding" +else + warn "InstructionPersistenceClassifier service not responding" +fi + +# Test Context Pressure +if curl -s -X POST "${APP_URL}/api/demo/pressure-check" \ + -H "Content-Type: application/json" \ + -d '{"tokens":50000,"messages":10,"errors":0}' | grep -q "level"; then + pass "ContextPressureMonitor service responding" +else + warn "ContextPressureMonitor service not responding" +fi + +#============================================================================= +# 6. Security Headers +#============================================================================= + +section "6. Security Headers" + +HEADERS=$(curl -s -I "${APP_URL}/") + +if echo "$HEADERS" | grep -qi "X-Frame-Options"; then + pass "X-Frame-Options header present" +else + warn "X-Frame-Options header missing" +fi + +if echo "$HEADERS" | grep -qi "X-Content-Type-Options"; then + pass "X-Content-Type-Options header present" +else + warn "X-Content-Type-Options header missing" +fi + +if echo "$HEADERS" | grep -qi "Content-Security-Policy"; then + pass "Content-Security-Policy header present" +else + warn "Content-Security-Policy header missing" +fi + +#============================================================================= +# 7. File Permissions +#============================================================================= + +section "7. File Permissions & Directories" + +REQUIRED_DIRS=("logs" "uploads" "audit-reports") + +for dir in "${REQUIRED_DIRS[@]}"; do + if docker exec tractatus-app test -d "$dir" 2>/dev/null; then + pass "Directory '$dir' exists" + else + fail "Directory '$dir' missing" + fi +done + +#============================================================================= +# Results Summary +#============================================================================= + +echo "" +echo -e "${BLUE}╔════════════════════════════════════════════════════════════════════╗${NC}" +echo -e "${BLUE}β•‘ Verification Results β•‘${NC}" +echo -e "${BLUE}β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•${NC}" +echo "" +echo -e " ${GREEN}Passed:${NC} $PASSED tests" +echo -e " ${RED}Failed:${NC} $FAILED tests" +echo -e " ${YELLOW}Warnings:${NC} $WARNINGS tests" +echo "" + +if [ $FAILED -eq 0 ]; then + echo -e "${GREEN}βœ“ All critical tests passed! Deployment is ready.${NC}" + exit 0 +else + echo -e "${RED}βœ— Some tests failed. Please review the errors above.${NC}" + exit 1 +fi diff --git a/public/downloads/tractatus-quickstart.tar.gz b/public/downloads/tractatus-quickstart.tar.gz new file mode 100644 index 00000000..3fd95b9e Binary files /dev/null and b/public/downloads/tractatus-quickstart.tar.gz differ diff --git a/public/implementer.html b/public/implementer.html index b4964093..b7e1699a 100644 --- a/public/implementer.html +++ b/public/implementer.html @@ -50,6 +50,110 @@ + +
+
+
+
+
+
+ NEW + πŸš€ +
+

+ Deployment Quickstart Kit +

+

+ Production-ready Docker deployment with all 5 governance services. Get Tractatus running in 30 minutes with our comprehensive quickstart package. +

+
+
+ + + + Docker Compose configuration +
+
+ + + + Sample governance rules +
+
+ + + + Verification script +
+
+ + + + Troubleshooting guide +
+
+ + + + + Download Quickstart Kit + (15KB) + +
+
+

What's Included:

+
    +
  • + β–Έ +
    + docker-compose.yml +

    MongoDB + App + all services

    +
    +
  • +
  • + β–Έ +
    + .env.example +

    Full configuration template

    +
    +
  • +
  • + β–Έ +
    + sample-governance-rules.json +

    10 ready-to-use rules

    +
    +
  • +
  • + β–Έ +
    + verify-deployment.sh +

    Automated testing script

    +
    +
  • +
  • + β–Έ +
    + README.md +

    Step-by-step guide

    +
    +
  • +
  • + β–Έ +
    + TROUBLESHOOTING.md +

    Common issues & solutions

    +
    +
  • +
+
+
+
+
+
+

Integration Approaches

diff --git a/scripts/load-governance-rules.js b/scripts/load-governance-rules.js new file mode 100755 index 00000000..591adec5 --- /dev/null +++ b/scripts/load-governance-rules.js @@ -0,0 +1,128 @@ +#!/usr/bin/env node + +/** + * Load Governance Rules into Database + * + * Loads governance rules from JSON file into MongoDB + * + * Usage: node scripts/load-governance-rules.js + */ + +const fs = require('fs'); +const path = require('path'); +const { MongoClient } = require('mongodb'); +require('dotenv').config(); + +const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/tractatus_prod'; + +async function loadGovernanceRules(rulesFile) { + console.log('πŸ”§ Loading Governance Rules...\n'); + + // Read rules file + const rulesPath = path.resolve(process.cwd(), rulesFile); + + if (!fs.existsSync(rulesPath)) { + console.error(`❌ Error: Rules file not found: ${rulesPath}`); + process.exit(1); + } + + let rulesData; + try { + const fileContent = fs.readFileSync(rulesPath, 'utf8'); + rulesData = JSON.parse(fileContent); + } catch (error) { + console.error(`❌ Error parsing rules file: ${error.message}`); + process.exit(1); + } + + if (!rulesData.rules || !Array.isArray(rulesData.rules)) { + console.error('❌ Error: Invalid rules file format (missing "rules" array)'); + process.exit(1); + } + + console.log(`πŸ“„ Found ${rulesData.rules.length} rules in ${path.basename(rulesFile)}`); + + // Connect to MongoDB + const client = new MongoClient(MONGODB_URI); + + try { + await client.connect(); + console.log('βœ“ Connected to MongoDB\n'); + + const db = client.db(); + const rulesCollection = db.collection('governance_rules'); + + // Clear existing rules (optional - comment out to append instead) + const deleteResult = await rulesCollection.deleteMany({}); + if (deleteResult.deletedCount > 0) { + console.log(`πŸ—‘οΈ Cleared ${deleteResult.deletedCount} existing rules\n`); + } + + // Insert rules + const rules = rulesData.rules.map(rule => ({ + ...rule, + createdAt: new Date(), + updatedAt: new Date(), + active: true, + source: 'manual_load', + version: rulesData.version || '1.0.0' + })); + + const insertResult = await rulesCollection.insertMany(rules); + console.log(`βœ“ Inserted ${insertResult.insertedCount} governance rules\n`); + + // Create indexes + await rulesCollection.createIndex({ rule_id: 1 }, { unique: true }); + await rulesCollection.createIndex({ quadrant: 1 }); + await rulesCollection.createIndex({ persistence: 1 }); + await rulesCollection.createIndex({ enforced_by: 1 }); + console.log('βœ“ Created indexes\n'); + + // Summary + console.log('╔════════════════════════════════════════════════════════════════════╗'); + console.log('β•‘ Rules Loaded Successfully β•‘'); + console.log('β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•\n'); + + // Count by quadrant + const quadrantCounts = await rulesCollection.aggregate([ + { $group: { _id: '$quadrant', count: { $sum: 1 } } }, + { $sort: { _id: 1 } } + ]).toArray(); + + console.log('Rules by Quadrant:'); + quadrantCounts.forEach(({ _id, count }) => { + console.log(` ${_id}: ${count}`); + }); + + console.log(''); + + // Count by service + const serviceCounts = await rulesCollection.aggregate([ + { $group: { _id: '$enforced_by', count: { $sum: 1 } } }, + { $sort: { count: -1 } } + ]).toArray(); + + console.log('Rules by Service:'); + serviceCounts.forEach(({ _id, count }) => { + console.log(` ${_id}: ${count}`); + }); + + console.log('\nβœ… Governance rules successfully loaded!\n'); + + } catch (error) { + console.error('❌ Error loading rules:', error.message); + process.exit(1); + } finally { + await client.close(); + } +} + +// Main +if (process.argv.length < 3) { + console.error('Usage: node scripts/load-governance-rules.js '); + console.error('Example: node scripts/load-governance-rules.js deployment-quickstart/sample-governance-rules.json'); + process.exit(1); +} + +const rulesFile = process.argv[2]; +loadGovernanceRules(rulesFile);