diff --git a/docs/markdown/deployment-guide.md b/docs/markdown/deployment-guide.md new file mode 100644 index 00000000..45e99693 --- /dev/null +++ b/docs/markdown/deployment-guide.md @@ -0,0 +1,731 @@ +--- +title: Deployment Guide +slug: deployment-guide +quadrant: OPERATIONAL +persistence: HIGH +version: 1.0 +type: framework +author: Tractatus Framework Team +created: 2025-10-26 +modified: 2025-10-26 +--- + +# Tractatus Framework Deployment Guide + +This guide covers deploying the Tractatus governance framework for local development, staging, and production environments. + +--- + +## Prerequisites + +### System Requirements + +- **Node.js**: 18.x or later +- **MongoDB**: 7.0 or later +- **Operating System**: Linux (Ubuntu 22.04+ recommended), macOS, or Windows with WSL2 +- **Memory**: Minimum 2GB RAM (4GB+ recommended for production) +- **Storage**: Minimum 10GB available disk space + +### Required Tools + +```bash +# Verify Node.js installation +node --version # Should be 18.x or later + +# Verify MongoDB installation +mongod --version # Should be 7.0 or later + +# npm is included with Node.js +npm --version +``` + +--- + +## Local Development Setup + +### 1. Clone and Install + +```bash +# Clone the repository +git clone https://github.com/AgenticGovernance/tractatus-framework.git +cd tractatus-framework + +# Install dependencies +npm install +``` + +### 2. Database Initialization + +```bash +# Start MongoDB (if not running as service) +sudo systemctl start mongod + +# Initialize database with default collections +npm run init:db + +# This creates: +# - governance_rules collection +# - audit_logs collection +# - instruction_history collection +# - session_state collection +``` + +### 3. Environment Configuration + +Create a `.env` file in the project root: + +```bash +# Database Configuration +MONGODB_URI=mongodb://localhost:27017/tractatus_dev +MONGODB_DB_NAME=tractatus_dev + +# Server Configuration +PORT=9000 +NODE_ENV=development + +# Session Configuration +SESSION_SECRET=your-random-secret-key-here + +# Optional: Anthropic API (for advanced features) +ANTHROPIC_API_KEY=your-api-key-here +``` + +**Security Note**: Never commit `.env` files to version control. Use `.env.example` as a template. + +### 4. Start Development Server + +```bash +# Start in development mode with auto-reload +npm run dev + +# Or start normally +npm start + +# Server runs on http://localhost:9000 +``` + +### 5. Verify Installation + +```bash +# Run framework tests +npm test + +# Expected output: All 238 tests passing + +# Check framework services +node scripts/framework-stats.js +``` + +Access the local application: +- **Main site**: `http://localhost:9000` +- **Admin dashboard**: `http://localhost:9000/admin/audit-analytics.html` +- **Documentation**: `http://localhost:9000/docs.html` + +--- + +## Production Deployment + +### Server Setup + +#### 1. Provision Server + +**Recommended specifications:** +- **CPU**: 2+ cores +- **RAM**: 4GB minimum (8GB recommended) +- **Storage**: 20GB SSD +- **OS**: Ubuntu 22.04 LTS + +#### 2. Install Dependencies + +```bash +# Update system packages +sudo apt update && sudo apt upgrade -y + +# Install Node.js 18.x +curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - +sudo apt install -y nodejs + +# Install MongoDB 7.0 +curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \ + sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg + +echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] \ + https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | \ + sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list + +sudo apt update +sudo apt install -y mongodb-org + +# Start and enable MongoDB +sudo systemctl start mongod +sudo systemctl enable mongod +``` + +### Production Environment Configuration + +Create `/var/www/tractatus/.env`: + +```bash +# Production Database +MONGODB_URI=mongodb://localhost:27017/tractatus_production +MONGODB_DB_NAME=tractatus_production + +# Production Server +PORT=9000 +NODE_ENV=production + +# Security +SESSION_SECRET=generate-strong-random-key-here + +# Optional: Production API keys +ANTHROPIC_API_KEY=prod-api-key-here +``` + +### Service Management (systemd) + +Create `/etc/systemd/system/tractatus.service`: + +```ini +[Unit] +Description=Tractatus Framework Service +After=network.target mongodb.service +Wants=mongodb.service + +[Service] +Type=simple +User=tractatus +WorkingDirectory=/var/www/tractatus +Environment="NODE_ENV=production" +EnvironmentFile=/var/www/tractatus/.env +ExecStart=/usr/bin/node src/server.js +Restart=always +RestartSec=10 +StandardOutput=journal +StandardError=journal +SyslogIdentifier=tractatus + +[Install] +WantedBy=multi-user.target +``` + +**Enable and start service:** + +```bash +# Reload systemd +sudo systemctl daemon-reload + +# Enable service to start on boot +sudo systemctl enable tractatus + +# Start service +sudo systemctl start tractatus + +# Check status +sudo systemctl status tractatus + +# View logs +sudo journalctl -u tractatus -f +``` + +### Reverse Proxy (Nginx) + +Create `/etc/nginx/sites-available/tractatus`: + +```nginx +server { + listen 80; + server_name agenticgovernance.digital www.agenticgovernance.digital; + + location / { + proxy_pass http://localhost:9000; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_cache_bypass $http_upgrade; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + # Static assets caching + location ~* \.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$ { + proxy_pass http://localhost:9000; + expires 1y; + add_header Cache-Control "public, immutable"; + } +} +``` + +**Enable site:** + +```bash +sudo ln -s /etc/nginx/sites-available/tractatus /etc/nginx/sites-enabled/ +sudo nginx -t +sudo systemctl reload nginx +``` + +### SSL/TLS Configuration (Let's Encrypt) + +```bash +# Install Certbot +sudo apt install -y certbot python3-certbot-nginx + +# Obtain SSL certificate +sudo certbot --nginx -d agenticgovernance.digital -d www.agenticgovernance.digital + +# Auto-renewal is configured by default +# Test renewal +sudo certbot renew --dry-run +``` + +--- + +## Docker Deployment + +### Dockerfile + +Create `Dockerfile` in project root: + +```dockerfile +FROM node:18-alpine + +# Set working directory +WORKDIR /app + +# Copy package files +COPY package*.json ./ + +# Install production dependencies only +RUN npm ci --only=production + +# Copy application files +COPY . . + +# Create non-root user +RUN addgroup -g 1001 -S tractatus && \ + adduser -S tractatus -u 1001 && \ + chown -R tractatus:tractatus /app + +# Switch to non-root user +USER tractatus + +# Expose port +EXPOSE 9000 + +# Health check +HEALTHCHECK --interval=30s --timeout=3s --start-period=40s \ + CMD node -e "require('http').get('http://localhost:9000/health', (res) => process.exit(res.statusCode === 200 ? 0 : 1))" + +# Start application +CMD ["node", "src/server.js"] +``` + +### Docker Compose + +Create `docker-compose.yml`: + +```yaml +version: '3.8' + +services: + mongodb: + image: mongo:7.0 + container_name: tractatus-mongodb + restart: always + ports: + - "27017:27017" + volumes: + - mongodb-data:/data/db + - mongodb-config:/data/configdb + environment: + MONGO_INITDB_DATABASE: tractatus_production + networks: + - tractatus-network + + tractatus: + build: . + container_name: tractatus-app + restart: always + ports: + - "9000:9000" + environment: + - NODE_ENV=production + - MONGODB_URI=mongodb://mongodb:27017/tractatus_production + - PORT=9000 + env_file: + - .env + depends_on: + - mongodb + networks: + - tractatus-network + volumes: + - ./logs:/app/logs + +volumes: + mongodb-data: + mongodb-config: + +networks: + tractatus-network: + driver: bridge +``` + +### Docker Commands + +```bash +# Build and start containers +docker-compose up -d + +# View logs +docker-compose logs -f tractatus + +# Stop containers +docker-compose down + +# Rebuild after code changes +docker-compose up -d --build + +# Execute commands in container +docker-compose exec tractatus npm test + +# Database backup +docker-compose exec mongodb mongodump --out=/backup +``` + +--- + +## Cloud Deployment Patterns + +### AWS Deployment + +**ECS (Elastic Container Service)** + +```yaml +# task-definition.json +{ + "family": "tractatus", + "networkMode": "awsvpc", + "requiresCompatibilities": ["FARGATE"], + "cpu": "512", + "memory": "1024", + "containerDefinitions": [ + { + "name": "tractatus", + "image": "your-ecr-repo/tractatus:latest", + "portMappings": [ + { + "containerPort": 9000, + "protocol": "tcp" + } + ], + "environment": [ + { + "name": "NODE_ENV", + "value": "production" + }, + { + "name": "MONGODB_URI", + "value": "mongodb://your-documentdb-cluster:27017/tractatus" + } + ], + "logConfiguration": { + "logDriver": "awslogs", + "options": { + "awslogs-group": "/ecs/tractatus", + "awslogs-region": "us-east-1", + "awslogs-stream-prefix": "ecs" + } + } + } + ] +} +``` + +### Google Cloud Platform + +**Cloud Run Deployment** + +```bash +# Build container +gcloud builds submit --tag gcr.io/PROJECT-ID/tractatus + +# Deploy to Cloud Run +gcloud run deploy tractatus \ + --image gcr.io/PROJECT-ID/tractatus \ + --platform managed \ + --region us-central1 \ + --allow-unauthenticated \ + --set-env-vars MONGODB_URI=mongodb://mongo-instance:27017/tractatus +``` + +### Kubernetes + +Create `k8s/deployment.yaml`: + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: tractatus +spec: + replicas: 3 + selector: + matchLabels: + app: tractatus + template: + metadata: + labels: + app: tractatus + spec: + containers: + - name: tractatus + image: tractatus:latest + ports: + - containerPort: 9000 + env: + - name: NODE_ENV + value: "production" + - name: MONGODB_URI + valueFrom: + secretKeyRef: + name: tractatus-secrets + key: mongodb-uri + resources: + requests: + memory: "512Mi" + cpu: "250m" + limits: + memory: "1Gi" + cpu: "500m" + livenessProbe: + httpGet: + path: /health + port: 9000 + initialDelaySeconds: 30 + periodSeconds: 10 + readinessProbe: + httpGet: + path: /health + port: 9000 + initialDelaySeconds: 5 + periodSeconds: 5 +--- +apiVersion: v1 +kind: Service +metadata: + name: tractatus-service +spec: + selector: + app: tractatus + ports: + - protocol: TCP + port: 80 + targetPort: 9000 + type: LoadBalancer +``` + +--- + +## Database Management + +### Backup and Restore + +**Backup MongoDB:** + +```bash +# Local backup +mongodump --db tractatus_production --out /backup/$(date +%Y%m%d) + +# Automated daily backup script +#!/bin/bash +BACKUP_DIR="/var/backups/mongodb" +DATE=$(date +%Y%m%d_%H%M%S) +mongodump --db tractatus_production --out $BACKUP_DIR/$DATE +find $BACKUP_DIR -type d -mtime +7 -exec rm -rf {} + +``` + +**Restore MongoDB:** + +```bash +mongorestore --db tractatus_production /backup/20251026/tractatus_production +``` + +### Database Migrations + +```bash +# Run migrations +npm run migrate + +# Rollback last migration +npm run migrate:rollback +``` + +--- + +## Monitoring and Logging + +### Health Checks + +The framework includes a health endpoint: + +```javascript +// GET /health +{ + "status": "healthy", + "uptime": 12345, + "mongodb": "connected", + "services": { + "BoundaryEnforcer": "active", + "InstructionPersistence": "active", + "CrossReferenceValidator": "active", + "ContextPressureMonitor": "active", + "MetacognitiveVerifier": "active", + "PluralisticDeliberationOrchestrator": "active" + } +} +``` + +### Application Logs + +```bash +# View application logs (systemd) +sudo journalctl -u tractatus -f + +# View specific time range +sudo journalctl -u tractatus --since "1 hour ago" + +# Export logs +sudo journalctl -u tractatus > tractatus-logs.txt +``` + +### Audit Dashboard + +Access the audit analytics dashboard at: +``` +https://your-domain.com/admin/audit-analytics.html +``` + +--- + +## Security Considerations + +### Environment Variables + +- **Never commit** `.env` files to version control +- Use environment-specific configuration files +- Rotate secrets regularly (SESSION_SECRET, API keys) + +### MongoDB Security + +```bash +# Enable authentication +mongo +> use admin +> db.createUser({ + user: "tractatus_admin", + pwd: "strong-password-here", + roles: [{ role: "readWrite", db: "tractatus_production" }] + }) +> exit + +# Update MONGODB_URI with auth +MONGODB_URI=mongodb://tractatus_admin:password@localhost:27017/tractatus_production +``` + +### Firewall Configuration + +```bash +# Allow only necessary ports +sudo ufw allow 22/tcp # SSH +sudo ufw allow 80/tcp # HTTP +sudo ufw allow 443/tcp # HTTPS +sudo ufw enable + +# Block direct access to MongoDB from outside +sudo ufw deny 27017/tcp +``` + +### SSL/TLS Best Practices + +- Use Let's Encrypt for free SSL certificates +- Enable HSTS (HTTP Strict Transport Security) +- Configure strong cipher suites in Nginx +- Redirect all HTTP to HTTPS + +--- + +## Troubleshooting + +### Common Issues + +**MongoDB connection failed:** +```bash +# Check MongoDB is running +sudo systemctl status mongod + +# Check logs +sudo journalctl -u mongod -f + +# Verify connection string +mongo $MONGODB_URI +``` + +**Port already in use:** +```bash +# Find process using port 9000 +sudo lsof -i :9000 + +# Kill process +sudo kill -9 +``` + +**Framework services not initialized:** +```bash +# Run framework health check +node scripts/framework-stats.js + +# Check session state +cat .claude/session-state.json +``` + +--- + +## Performance Optimization + +### Database Indexing + +```javascript +// Create indexes for frequently queried fields +db.audit_logs.createIndex({ timestamp: -1 }); +db.audit_logs.createIndex({ service: 1, timestamp: -1 }); +db.governance_rules.createIndex({ id: 1 }, { unique: true }); +db.instruction_history.createIndex({ session_id: 1, timestamp: -1 }); +``` + +### Caching Strategy + +- Static assets served with 1-year cache headers +- API responses cached with appropriate TTL +- MongoDB query result caching for read-heavy operations + +### Resource Limits + +```bash +# Increase Node.js memory limit +NODE_OPTIONS=--max-old-space-size=4096 node src/server.js +``` + +--- + +## Next Steps + +- **Implementation Guide**: See [Implementation Guide](/docs/implementation-guide) for integration patterns +- **API Reference**: Visit `/api-reference.html` for complete API documentation +- **GitHub Repository**: Access code examples at [tractatus-framework](https://github.com/AgenticGovernance/tractatus-framework) + +--- + +**Document Version**: 1.0 +**Last Updated**: 2025-10-26 +**Maintained by**: Tractatus Framework Team diff --git a/public/docs/diagrams/deployment-architecture.svg b/public/docs/diagrams/archive/deployment-architecture-old.svg similarity index 98% rename from public/docs/diagrams/deployment-architecture.svg rename to public/docs/diagrams/archive/deployment-architecture-old.svg index 7f2ceaf4..fa0cfd30 100644 --- a/public/docs/diagrams/deployment-architecture.svg +++ b/public/docs/diagrams/archive/deployment-architecture-old.svg @@ -41,7 +41,7 @@ - Monitoring & Logging + Monitoring & Logging • Audit Dashboard (Port 9000) • Service Logs (journalctl) • Performance Metrics @@ -50,7 +50,7 @@ - Security & Backup + Security & Backup • Automated DB backups • SSH key-based access • Defense-in-depth (5 layers) diff --git a/public/docs/diagrams/archive/request-flow-sequence-old.svg b/public/docs/diagrams/archive/request-flow-sequence-old.svg new file mode 100644 index 00000000..fb664aeb --- /dev/null +++ b/public/docs/diagrams/archive/request-flow-sequence-old.svg @@ -0,0 +1,116 @@ + + + + + + + + + + + + AI Decision Flow with Governance + + + + User + + + AI Agent + + + Governance + + + MongoDB + + + Human + + + + + + + + + + + 1. "Change privacy policy" + + + + 2. Analyze request + + + + 3. checkBoundary(decision) + + + + + + 4. Get stored instructions + + + + + + + 5. REJECTED (12.1 - Values) + + + + BoundaryEnforcer: "Values decisions + require human approval" + (Tractatus 12.1) + + + + 6. Request approval (with AI analysis) + + + + + + 7. Approved with modifications + + + + + 8. Log audit trail + + + + 9. Store audit + + + + + + + + 10. Execute decision + with human-approved + modifications + + + + 11. Completed (with audit trail) + + + + + Result: Human oversight enforced architecturally • Audit trail created • Values preserved + + diff --git a/public/docs/diagrams/archive/system-architecture-old.svg b/public/docs/diagrams/archive/system-architecture-old.svg new file mode 100644 index 00000000..9bbed7e5 --- /dev/null +++ b/public/docs/diagrams/archive/system-architecture-old.svg @@ -0,0 +1,91 @@ + + + + + + + + + + + + AI Application + Claude Code / Custom LLM + + + + + + + BoundaryEnforcer + Values Decisions + (Tractatus 12.1-12.7) + + + InstructionPersistence + Classifier + (Quadrant + Persistence) + + + CrossReference + Validator + (Pattern Override Prevention) + + + + ContextPressure + Monitor + (Token & Complexity) + + + Metacognitive + Verifier + (Confidence Scoring) + + + Pluralistic + Deliberation + (Multi-Stakeholder) + + + + + + MemoryProxy v3 + Hybrid Storage + (MongoDB + Optional API) + + + MongoDB + Instructions Database + Audit Logs + + + + + + + + + + + + + + + + + + + + 6 Governance Services • Persistent Storage • Production-Tested Architecture + diff --git a/public/docs/diagrams/hook-architecture.svg b/public/docs/diagrams/hook-architecture.svg new file mode 100644 index 00000000..5356c6c3 --- /dev/null +++ b/public/docs/diagrams/hook-architecture.svg @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + Architectural Enforcement: PreToolUse Hook Flow + How governance is enforced before AI can execute actions + + + AI Agent Action + Edit(/public/index.html) + Change: github.com/A/repo1 + → github.com/A/repo2 + + + intercept + + + PreToolUse Hook + validate-file-edit.js + BEFORE execution + ⚠ Architectural layer + + + run checks + + + ✓ CSP Compliance + No inline styles/scripts + checkCSPCompliance() + + + ⚠ GitHub URLs + inst_084: Hard block + checkGitHubURLProtection() + + + VIOLATION + + + ✓ Boundaries + Values decisions blocked + checkBoundaryViolation() + + + + + Pass? + + + NO + + + 🚫 HARD BLOCK + Exit code: 2 + Action halted + Error logged to audit + Cannot be bypassed + + + YES + + + ✓ ALLOWED + Exit code: 0 + Tool execution proceeds + Audit log: PASSED + Governance verified + + + Key Enforcement Mechanisms: + • Hooks run in separate process (Node.js child_process) – AI cannot access or modify + • Exit codes control execution: 0=proceed, 2=block – architectural enforcement, not voluntary compliance + + diff --git a/public/docs/diagrams/system-architecture-desktop.svg b/public/docs/diagrams/system-architecture-desktop.svg new file mode 100644 index 00000000..b2fef0fd --- /dev/null +++ b/public/docs/diagrams/system-architecture-desktop.svg @@ -0,0 +1 @@ +

Human Approval Workflows

Persistent Storage Layer (Immutable Audit Trail)

Tractatus Governance Layer (External Enforcement)

Agent Runtime Layer (Any LLM Agent System)

All actions pass through governance checks

Boundary violation

Values conflict

Approval/Rejection

Agentic AI Runtime
LangChain • AutoGPT • CrewAI
Claude Code • Custom Agents
Multi-Agent Systems
Tool Use • Planning • Execution

BoundaryEnforcer
Blocks values decisions
• Privacy policies
• Ethical trade-offs
• Strategic direction
• User agency violations
⚠ Cannot be bypassed by prompting

InstructionPersistenceClassifier
Classifies & stores instructions
• Quadrant (STR/OPS/TAC/SYS)
• Persistence (HIGH/MED/LOW)
• Temporal scope
⚠ External to AI memory

CrossReferenceValidator
Prevents pattern bias override
• Checks instruction history
• Detects conflicts (27027)
• Blocks contradictions
⚠ Independent verification

ContextPressureMonitor
Detects degraded conditions
• Token budget tracking
• Error accumulation
• Checkpoint reporting
⚠ Objective metrics, not self-reported

MetacognitiveVerifier
Validates complex operations
• >3 files or >5 steps
• Architecture changes
• Confidence scoring
⚠ Structural pause-and-verify

PluralisticDeliberationOrchestrator
Facilitates values deliberation
• Multi-stakeholder engagement
• Moral framework mapping
• Precedent documentation
⚠ Human judgment required

governance_rules
• rule_id (STR-001...)
• quadrant
• persistence level
• enforced_by
• violation_action
• active status

audit_logs
• timestamp
• service (which enforcer)
• action (BLOCK/WARN)
• instruction
• rule_violated
• session_id

session_state
• session_id
• token_count
• message_count
• pressure_level
• last_checkpoint
• framework_active

instruction_history
• instruction_id
• content
• classification
• persistence
• created_at
• active status

Human Oversight
Values Decisions
Strategic Changes
Boundary Violations
Final authority on incommensurable values

🔒 KEY JAILBREAK DEFENSE
Governance layer operates OUTSIDE agent runtime
Designed with structural boundaries independent of prompt content
Structural boundaries, not behavioral training
Immutable audit trail independent of AI

\ No newline at end of file diff --git a/public/docs/diagrams/system-architecture-mobile.svg b/public/docs/diagrams/system-architecture-mobile.svg new file mode 100644 index 00000000..63c65aee --- /dev/null +++ b/public/docs/diagrams/system-architecture-mobile.svg @@ -0,0 +1,64 @@ + + + + + + + + + Tractatus Architecture + (Simplified View) + + + Agent Runtime Layer + LangChain • AutoGPT • CrewAI + Claude Code • Custom Agents + Tool Use • Planning • Execution + + + Governance checks + + + Tractatus Governance Layer + 6 External Services: + BoundaryEnforcer • CrossReference + InstructionPersistence • ContextPressure + Metacognitive • PluralisticDeliberation + ⚠ External architecture + + + Audit logging + + + Persistent Storage Layer + MongoDB Collections: + governance_rules • audit_logs + instruction_history • session_state + Audit trail design + + + Boundary + violations + + + Approval/ + Rejection + + + Human Oversight + Values Decisions + Strategic Changes • Boundary Violations + Final authority on incommensurable values + + View full diagram for details → + diff --git a/public/docs/diagrams/system-architecture.svg b/public/docs/diagrams/system-architecture.svg index 72d2f57f..b2fef0fd 100644 --- a/public/docs/diagrams/system-architecture.svg +++ b/public/docs/diagrams/system-architecture.svg @@ -1,91 +1 @@ - - - - - - - - - - - - AI Application - Claude Code / Custom LLM - - - - - - - BoundaryEnforcer - Values Decisions - (Tractatus 12.1-12.7) - - - InstructionPersistence - Classifier - (Quadrant + Persistence) - - - CrossReference - Validator - (Pattern Override Prevention) - - - - ContextPressure - Monitor - (Token & Complexity) - - - Metacognitive - Verifier - (Confidence Scoring) - - - Pluralistic - Deliberation - (Multi-Stakeholder) - - - - - - MemoryProxy v3 - Hybrid Storage - (MongoDB + Optional API) - - - MongoDB - Instructions Database - Audit Logs - - - - - - - - - - - - - - - - - - - - 6 Governance Services • Persistent Storage • Production-Tested Architecture - +

Human Approval Workflows

Persistent Storage Layer (Immutable Audit Trail)

Tractatus Governance Layer (External Enforcement)

Agent Runtime Layer (Any LLM Agent System)

All actions pass through governance checks

Boundary violation

Values conflict

Approval/Rejection

Agentic AI Runtime
LangChain • AutoGPT • CrewAI
Claude Code • Custom Agents
Multi-Agent Systems
Tool Use • Planning • Execution

BoundaryEnforcer
Blocks values decisions
• Privacy policies
• Ethical trade-offs
• Strategic direction
• User agency violations
⚠ Cannot be bypassed by prompting

InstructionPersistenceClassifier
Classifies & stores instructions
• Quadrant (STR/OPS/TAC/SYS)
• Persistence (HIGH/MED/LOW)
• Temporal scope
⚠ External to AI memory

CrossReferenceValidator
Prevents pattern bias override
• Checks instruction history
• Detects conflicts (27027)
• Blocks contradictions
⚠ Independent verification

ContextPressureMonitor
Detects degraded conditions
• Token budget tracking
• Error accumulation
• Checkpoint reporting
⚠ Objective metrics, not self-reported

MetacognitiveVerifier
Validates complex operations
• >3 files or >5 steps
• Architecture changes
• Confidence scoring
⚠ Structural pause-and-verify

PluralisticDeliberationOrchestrator
Facilitates values deliberation
• Multi-stakeholder engagement
• Moral framework mapping
• Precedent documentation
⚠ Human judgment required

governance_rules
• rule_id (STR-001...)
• quadrant
• persistence level
• enforced_by
• violation_action
• active status

audit_logs
• timestamp
• service (which enforcer)
• action (BLOCK/WARN)
• instruction
• rule_violated
• session_id

session_state
• session_id
• token_count
• message_count
• pressure_level
• last_checkpoint
• framework_active

instruction_history
• instruction_id
• content
• classification
• persistence
• created_at
• active status

Human Oversight
Values Decisions
Strategic Changes
Boundary Violations
Final authority on incommensurable values

🔒 KEY JAILBREAK DEFENSE
Governance layer operates OUTSIDE agent runtime
Designed with structural boundaries independent of prompt content
Structural boundaries, not behavioral training
Immutable audit trail independent of AI

\ No newline at end of file diff --git a/public/docs/pdfs/deployment-guide.pdf b/public/docs/pdfs/deployment-guide.pdf new file mode 100644 index 00000000..f003314a Binary files /dev/null and b/public/docs/pdfs/deployment-guide.pdf differ diff --git a/public/implementer.html b/public/implementer.html index 0cc11420..a273b42d 100644 --- a/public/implementer.html +++ b/public/implementer.html @@ -34,11 +34,18 @@ body { font-size: 16px; } /* Prevent iOS zoom on input focus */ } - /* Diagram sizing */ + /* Diagram sizing - responsive */ .diagram-img { - max-width: 600px; + max-width: 100%; width: 100%; height: auto; + display: block; + } + + /* Diagram container with horizontal scroll for small screens */ + .diagram-container { + overflow-x: auto; + border-radius: 0.5rem; } @@ -62,12 +69,31 @@
-

- Framework Implementation Guide +

+ External Governance Services for AI Systems

-

- Technical documentation for integrating the 6 Tractatus governance services into your AI systems. Production-tested architecture and real code examples. +

+ Six architectural services addressing pattern override and decision traceability in agentic systems. Development framework for instruction persistence, boundary enforcement, and audit logging.

+ + +
+
+
🏗️
+

Architectural Separation

+

Governance runs external to AI model

+
+
+
💾
+

Instruction Persistence

+

Validates instructions across context

+
+
+
📋
+

Audit Trail by Design

+

MongoDB logs with service attribution

+
+
@@ -76,21 +102,98 @@ - +
-
-

Framework Architecture

+ + +
+
+

How It Works

+ + +
+

Pattern Override Challenge

+

+ AI systems operating across extended interactions may not maintain instruction consistency as context evolves. Instructions given early can be deprioritized or reinterpreted. +

+

External Architecture Approach

+

+ Tractatus services run external to the AI model, providing boundary validation, instruction classification, and audit logging through architectural separation. +

+
+ + +
+

Request Flow with Governance

+

+ Example: AI decision flow with boundary enforcement—from user request through governance validation to human approval. +

+
+ Request Flow Sequence: How AI decisions are governed +
+ +
+
+
+ + +
+
+

System Architecture

+ + +
+

Six Core Services

+
+
+ + BoundaryEnforcer (Tractatus 12.1-12.7) +
+
+ + InstructionPersistenceClassifier +
+
+ + CrossReferenceValidator +
+
+ + ContextPressureMonitor +
+
+ + MetacognitiveVerifier +
+
+ + PluralisticDeliberationOrchestrator +
+
+
@@ -139,13 +242,17 @@

System Architecture

High-level overview showing how the 6 governance services integrate with your application and data layer.

- Tractatus System Architecture: Component interaction and data flow + + + + Tractatus System Architecture: Component interaction and data flow +
- - +
+
- -
-

Deployment Architecture

-

Production deployment reference showing Node.js application, MongoDB, and monitoring stack configuration.

-
- Deployment Architecture: Production server setup with monitoring and security + +
+
+
+ ARCHITECTURAL ENFORCEMENT +

Hook Architecture: The Credibility Layer

+

+ Tractatus governance is not voluntary compliance. PreToolUse hooks enforce boundaries before AI actions execute, + making circumvention architecturally impossible. +

-
- - - Download SVG - + + +
+

The Voluntary Compliance Problem

+

+ Traditional AI safety relies on the AI system "choosing" to follow rules embedded in training data or system prompts. + These approaches assume the AI will maintain alignment regardless of context pressure or capability. +

+

+ Tractatus addresses this through architectural enforcement: governance runs in a separate process + that the AI cannot access, modify, or bypass. +

+
+ + +
+

PreToolUse Hook Execution Flow

+

+ Before any file edit, write, or bash command executes, the hook intercepts the action and runs validation checks. + Only if ALL checks pass (exit code 0) does the AI action proceed. +

+
+ Hook Architecture: PreToolUse intercept flow showing validation and hard blocks +
+ +
+ + +
+

Real Enforcement Examples

+
+ + +
+

🚫 GitHub URL Protection (inst_084)

+

+ AI attempted to change GitHub repository URL from tractatus-framework (public) + to tractatus (private). +

+
+ BLOCKED: Repository URL modification detected
+ Reason: Would expose private repo structure +
+

+ Hook: validate-file-edit.js line 448-505 +

+
+ + +
+

🚫 CSP Violation (inst_008)

+

+ AI attempted to add inline style attribute to HTML element. +

+
+ BLOCKED: Inline style detected
+ Pattern: style="margin: 0 auto" +
+

+ Hook: validate-file-write.js line 68-149 +

+
+ + +
+

🚫 Governance File Protection (inst_027)

+

+ AI attempted direct edit of instruction-history.json. +

+
+ BLOCKED: inst_027 hard block
+ Use: scripts/add-instruction.js instead +
+

+ Hook: framework-audit-hook.js line 204-209 +

+
+ + +
+

⚠ Human Approval Required (BoundaryEnforcer)

+

+ AI action touches values-sensitive file (privacy policy). +

+
+ ASK HUMAN: Values decision detected
+ Requires: Explicit human approval +
+

+ Hook: validate-file-write.js line 239-262 +

+
+ +
+
+ + +
+

Technical Implementation

+ +
+ + +
+

🔒 Process Separation

+

+ Hooks execute in a separate Node.js process (child_process.spawn) with their own memory space. + The AI agent cannot access, modify, or terminate the validation process. +

+
// .claude/hooks.json
+{
+  "PreToolUse:Edit": {
+    "command": "node",
+    "args": ["scripts/hook-validators/validate-file-edit.js"]
+  },
+  "PreToolUse:Write": {
+    "command": "node",
+    "args": ["scripts/hook-validators/validate-file-write.js"]
+  }
+}
+
+ + +
+

⚙️ Exit Code Enforcement

+

+ Hook validators return exit codes that Claude Code's architecture enforces: +

+
    +
  • 0 = PASS → Tool executes
  • +
  • 2 = HARD BLOCK → Tool execution halted, error shown to user
  • +
+
// validate-file-edit.js (line 373-382)
+const githubUrlCheck = checkGitHubURLProtection();
+if (!githubUrlCheck.passed) {
+  error(githubUrlCheck.reason);
+  console.error(githubUrlCheck.output);
+  logMetrics('blocked', githubUrlCheck.reason);
+  process.exit(2);  // ← HARD BLOCK: Tool cannot execute
+}
+
+ + +
+

📊 Audit Trail

+

+ Every hook execution is logged to .claude/metrics/hooks-metrics.json + with timestamp, file, result, and reason. Blocks are separately tracked for analysis. +

+
{
+  "hook": "validate-file-edit",
+  "timestamp": "2025-10-26T22:02:15.XXX",
+  "file": "/public/implementer.html",
+  "result": "blocked",
+  "reason": "inst_084: GitHub repository name change detected"
+}
+
+ +
+
+ + +
+

Why Architectural Enforcement Matters

+

+ This is the fundamental difference between Tractatus and traditional AI safety approaches: +

+
+
+

❌ Voluntary Compliance

+
    +
  • AI "chooses" to follow rules
  • +
  • Can drift under context pressure
  • +
  • Pattern recognition may override instructions
  • +
  • No verification before execution
  • +
+
+
+

✓ Architectural Enforcement

+
    +
  • Hook intercepts before execution
  • +
  • Separate process, cannot be accessed
  • +
  • Exit codes enforced by runtime
  • +
  • Audit trail of all decisions
  • +
+
+
+
+ +
+
+ + +
+
+

Deployment Architecture

+ + +
+

Technology Stack

+
+
+ Runtime: Node.js v20+ +
+
+ Database: MongoDB 7.0+ +
+
+ Framework: Express.js +
+
+ Process: Systemd (recommended) +
+
+
+ + +
+

Production Deployment

+

+ Comprehensive deployment guide covering local development, production server configuration, Docker containerization, + cloud deployment patterns (AWS, GCP, Kubernetes), database management, monitoring, and security best practices. +

+ +
+
+

📦 Covered in Guide:

+
    +
  • Local development setup
  • +
  • Production server configuration
  • +
  • Docker and Docker Compose
  • +
  • Cloud deployment (AWS/GCP)
  • +
+
+
+

🔧 Also Includes:

+
    +
  • Kubernetes manifests
  • +
  • Database backup and migration
  • +
  • SSL/TLS configuration
  • +
  • Monitoring and logging
  • +
+
+
+ +
@@ -330,13 +675,7 @@ const result = await orchestrate(decision, stakeholders)

📁 Source Code

- All services are available in the GitHub repository: - - /src/services/ - + Code patterns and examples are available in the GitHub repository.

@@ -614,13 +953,7 @@ npm start

📖 Full Documentation

- Complete deployment guide available at: - - /deployment-quickstart/ - + Complete deployment patterns and examples available in the GitHub repository.

@@ -929,10 +1262,34 @@ const govResponse = await fetch(

Questions about implementation or integration?

-
diff --git a/public/version.json b/public/version.json index 01e2d3e1..5abd9a0e 100644 --- a/public/version.json +++ b/public/version.json @@ -1,12 +1,15 @@ { - "version": "0.1.1", - "buildDate": "2025-10-26T02:54:53.721Z", + "version": "0.1.2", + "buildDate": "2025-10-26T22:20:00.000Z", "changelog": [ - "Docs: Fixed language persistence (localStorage key unified to 'tractatus-lang')", - "Docs: Removed duplicate language selector (now uses navbar flags only)", - "Docs: Language selection now persists across page reloads", - "Cache: Service worker v0.1.3 - Language selector fixes" + "Implementer: Added Hook Architecture section (architectural enforcement credibility)", + "Implementer: Added hook-architecture.svg diagram showing PreToolUse flow", + "Implementer: Simplified deployment section (removed broken diagram)", + "Implementer: Added deployment-guide.pdf for download", + "Implementer: Responsive system architecture diagrams (mobile/desktop)", + "Docs: Created comprehensive deployment guide (14KB markdown → PDF)", + "Cache: Force update for new diagrams and PDFs" ], "forceUpdate": true, - "minVersion": "0.1.3" + "minVersion": "0.1.4" } diff --git a/scripts/add-inst-084-github-url-protection.js b/scripts/add-inst-084-github-url-protection.js new file mode 100644 index 00000000..122ecc43 --- /dev/null +++ b/scripts/add-inst-084-github-url-protection.js @@ -0,0 +1,167 @@ +#!/usr/bin/env node + +/** + * Add inst_084: GitHub Repository URL Modification Protocol + * + * PURPOSE: Prevent accidental exposure of private repository structure + * through unauthorized GitHub URL modifications in public-facing files. + * + * CONTEXT: Previous incident where AI changed repository name from + * tractatus-framework (public) to tractatus (private), exposing internal + * file paths like /src/services/ and /deployment-quickstart/. + * + * ENFORCEMENT: Pre-action hard block via architectural hook + */ + +const mongoose = require('mongoose'); +const GovernanceRule = require('../src/models/GovernanceRule.model'); +const fs = require('fs'); +const path = require('path'); + +// Connect to MongoDB +const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/tractatus_dev'; + +const rule = { + id: 'inst_084', + text: `GitHub Repository URL Modification Protocol (SYSTEM/SECURITY) + +**SCOPE**: Any modification to URLs containing "github.com" in ANY file + +**PROHIBITED ACTIONS**: +1. NEVER add new github.com URLs without explicit human approval +2. NEVER change existing github.com repository names +3. NEVER change github.com URL paths (e.g., /tree/main/src/services/) +4. NEVER assume a repository is public vs. private +5. NEVER "fix" broken GitHub links by pointing to different repository + +**REQUIRED PROCESS** when encountering broken GitHub link: +1. FLAG the broken link to user +2. STOP all work +3. ASK: "This links to [URL] which doesn't exist. Options: + a) Remove the link entirely + b) Add corresponding content to public repository + c) Different approach?" +4. WAIT for explicit human approval before ANY GitHub URL modification + +**CONTEXT**: +- tractatus = PRIVATE repository (internal implementation code) +- tractatus-framework = PUBLIC repository (research patterns, documentation) +- Linking to private repo paths exposes internal structure to public +- Previous incident: AI changed URL from public to private repo, exposing /src/services/ + +**RATIONALE**: +Historical incident where 500+ internal files were uploaded to public repository. +GitHub URL modifications have EXTREME RISK of exposing private code structure, +credentials, deployment configuration, or internal architecture to public. + +**ENFORCEMENT**: +- Pre-action validation hook (architectural, cannot be bypassed) +- Exit code 2 (HARD BLOCK) if GitHub URL modification detected without approval +- Logged to audit database with HIGH severity + +**VERIFICATION**: +Before: grep -r "github.com" in modified file +After: Verify no repository name changes, no new github.com URLs added +Audit: Log all GitHub URL change attempts (allowed or blocked)`, + + timestamp: new Date().toISOString(), + quadrant: 'SYSTEM', + persistence: 'HIGH', + temporal_scope: 'PERMANENT', + verification_required: 'MANDATORY', + explicitness: 1.0, + source: 'automated', + session_id: '2025-10-26-implementer-page-fixes', + + parameters: { + enforcement_mechanism: 'pre_action_hook', + block_type: 'hard_block', + approval_required: true, + affected_tools: ['Edit', 'Write'], + risk_level: 'EXTREME', + historical_incident: '2024-Q4-mass-file-upload' + }, + + active: true, + + notes: 'Created after AI attempted to change github.com/AgenticGovernance/tractatus-framework URLs to github.com/AgenticGovernance/tractatus (private repo), which would expose internal file paths /src/services/ and /deployment-quickstart/ to public documentation.', + + enforcement_hooks: ['validate-file-edit.js', 'validate-file-write.js'], + + related_instructions: ['inst_027', 'inst_072'], // instruction-history.json protection, defense-in-depth + + validation_command: 'grep -r "github.com" && git diff | grep "github.com"' +}; + +async function main() { + try { + console.log('\n📋 Adding inst_084: GitHub Repository URL Modification Protocol\n'); + + await mongoose.connect(MONGODB_URI); + console.log('✓ Connected to MongoDB'); + + // Check if rule already exists + const existing = await GovernanceRule.findOne({ id: 'inst_084' }); + if (existing) { + console.log('\n⚠ inst_084 already exists. Updating...'); + await GovernanceRule.updateOne({ id: 'inst_084' }, rule); + console.log('✓ Updated inst_084'); + } else { + await GovernanceRule.create(rule); + console.log('✓ Created inst_084'); + } + + // Update instruction-history.json + const historyPath = path.join(__dirname, '../.claude/instruction-history.json'); + const history = JSON.parse(fs.readFileSync(historyPath, 'utf8')); + + const instructionEntry = { + id: 'inst_084', + text: 'GitHub Repository URL Modification Protocol: NEVER modify github.com URLs without explicit approval. HARD BLOCK all repository name changes, path modifications, or new GitHub links. Previous incident exposed private repo structure.', + timestamp: new Date().toISOString(), + quadrant: 'SYSTEM', + persistence: 'HIGH', + temporal_scope: 'PERMANENT', + verification_required: 'MANDATORY', + explicitness: 1.0, + source: 'automated', + session_id: '2025-10-26-implementer-page-fixes', + parameters: { + enforcement_mechanism: 'pre_action_hook', + block_type: 'hard_block', + risk_level: 'EXTREME' + }, + active: true, + notes: 'Architectural enforcement via validate-file-edit.js and validate-file-write.js hooks' + }; + + // Check if instruction exists + const instIndex = history.instructions.findIndex(i => i.id === 'inst_084'); + if (instIndex >= 0) { + history.instructions[instIndex] = instructionEntry; + console.log('✓ Updated instruction-history.json (inst_084)'); + } else { + history.instructions.push(instructionEntry); + console.log('✓ Added to instruction-history.json'); + } + + history.last_updated = new Date().toISOString(); + fs.writeFileSync(historyPath, JSON.stringify(history, null, 2)); + + console.log('\n✓ inst_084 added successfully'); + console.log('\nNext steps:'); + console.log('1. Implement enforcement in scripts/hook-validators/validate-file-edit.js'); + console.log('2. Implement enforcement in scripts/hook-validators/validate-file-write.js'); + console.log('3. Test with: attempt to modify a github.com URL'); + console.log('4. Verify HARD BLOCK occurs without approval'); + + await mongoose.disconnect(); + process.exit(0); + + } catch (error) { + console.error('❌ Error adding inst_084:', error); + process.exit(1); + } +} + +main(); diff --git a/scripts/hook-validators/validate-file-edit.js b/scripts/hook-validators/validate-file-edit.js index fb26e15c..47c2c25f 100755 --- a/scripts/hook-validators/validate-file-edit.js +++ b/scripts/hook-validators/validate-file-edit.js @@ -45,7 +45,7 @@ const colors = { }; function log(message, color = 'reset') { - console.log(`${colors[color]}${message}${colors.reset}`); + console.error(`${colors[color]}${message}${colors.reset}`); } function error(message) { @@ -463,6 +463,18 @@ async function main() { process.exit(2); // Exit code 2 = BLOCK } success('No protected credential changes detected'); + // Check 5: GitHub URL Protection (inst_084) + const githubUrlCheck = checkGitHubURLProtection(); + if (!githubUrlCheck.passed) { + error(githubUrlCheck.reason); + if (githubUrlCheck.output) { + console.error(githubUrlCheck.output); + } + logMetrics('blocked', githubUrlCheck.reason); + process.exit(2); // Exit code 2 = BLOCK + } + success('No unauthorized GitHub URL modifications detected (inst_084)'); + // Update session state updateSessionState(); @@ -479,3 +491,65 @@ main().catch(err => { logMetrics('error', err.message); process.exit(2); // Exit code 2 = BLOCK }); + +/** + * Check 5: GitHub URL Protection (inst_084) - HARD BLOCK unauthorized changes + */ +function checkGitHubURLProtection() { + const oldString = HOOK_INPUT.tool_input?.old_string || ''; + const newString = HOOK_INPUT.tool_input?.new_string || ''; + + // Only check if both strings contain github.com + if (!oldString.includes('github.com') && !newString.includes('github.com')) { + return { passed: true }; + } + + // Extract GitHub repository URLs (github.com/org/repo format) + const githubUrlPattern = /github\.com\/[\w-]+\/[\w-]+/g; + const oldUrls = oldString.match(githubUrlPattern) || []; + const newUrls = newString.match(githubUrlPattern) || []; + + // Check 1: New GitHub URLs added (requires approval) + if (newUrls.length > oldUrls.length) { + return { + passed: false, + reason: 'inst_084: New GitHub URL detected - requires explicit approval', + output: `Attempting to add GitHub URL:\n New: ${newUrls.join(', ')}\n Old: ${oldUrls.join(', ')}\n\nBLOCKED: Adding GitHub URLs requires explicit human approval to prevent exposure of private repository structure.` + }; + } + + // Check 2: GitHub repository name changed (HIGH RISK) + if (oldUrls.length > 0 && newUrls.length > 0) { + const oldRepos = new Set(oldUrls); + const newRepos = new Set(newUrls); + + // Find any repository name changes + for (const oldRepo of oldRepos) { + if (!newRepos.has(oldRepo)) { + return { + passed: false, + reason: 'inst_084: GitHub repository name change detected - HARD BLOCK', + output: `CRITICAL: Repository URL modification detected:\n Old: ${oldRepo}\n New: ${Array.from(newRepos).join(', ')}\n\nBLOCKED: This could expose private repository structure (e.g., tractatus-framework → tractatus exposes /src/services/).\n\nRequired: Explicit human approval for ANY GitHub repository URL changes.` + }; + } + } + } + + // Check 3: GitHub URL path changed (e.g., /tree/main/src/services → /tree/main/deployment-quickstart) + const oldPaths = oldString.match(/github\.com[^\s"'<>]*/g) || []; + const newPaths = newString.match(/github\.com[^\s"'<>]*/g) || []; + + if (oldPaths.length > 0 && newPaths.length > 0) { + for (let i = 0; i < Math.min(oldPaths.length, newPaths.length); i++) { + if (oldPaths[i] !== newPaths[i]) { + return { + passed: false, + reason: 'inst_084: GitHub URL path modification detected - requires approval', + output: `GitHub URL path change detected:\n Old: ${oldPaths[i]}\n New: ${newPaths[i]}\n\nBLOCKED: URL path modifications require explicit approval to prevent linking to non-existent or private paths.` + }; + } + } + } + + return { passed: true }; +} diff --git a/scripts/hook-validators/validate-file-write.js b/scripts/hook-validators/validate-file-write.js index f7537d4d..2ad4ed51 100755 --- a/scripts/hook-validators/validate-file-write.js +++ b/scripts/hook-validators/validate-file-write.js @@ -46,7 +46,7 @@ const colors = { }; function log(message, color = 'reset') { - console.log(`${colors[color]}${message}${colors.reset}`); + console.error(`${colors[color]}${message}${colors.reset}`); } function error(message) { @@ -369,6 +369,18 @@ async function main() { process.exit(2); // Exit code 2 = BLOCK } success('No boundary violations detected'); + // Check 5: GitHub URL Protection (inst_084) + const githubUrlCheck = checkGitHubURLProtection(); + if (!githubUrlCheck.passed) { + error(githubUrlCheck.reason); + if (githubUrlCheck.output) { + console.error(githubUrlCheck.output); + } + logMetrics('blocked', githubUrlCheck.reason); + process.exit(2); // Exit code 2 = BLOCK + } + success('No unauthorized GitHub URL modifications detected (inst_084)'); + // Update session state updateSessionState(); @@ -429,3 +441,65 @@ function logMetrics(result, reason = null) { // Non-critical } } + +/** + * Check 5: GitHub URL Protection (inst_084) - HARD BLOCK unauthorized changes + */ +function checkGitHubURLProtection() { + const oldString = HOOK_INPUT.tool_input?.old_string || ''; + const newString = HOOK_INPUT.tool_input?.new_string || ''; + + // Only check if both strings contain github.com + if (!oldString.includes('github.com') && !newString.includes('github.com')) { + return { passed: true }; + } + + // Extract GitHub repository URLs (github.com/org/repo format) + const githubUrlPattern = /github\.com\/[\w-]+\/[\w-]+/g; + const oldUrls = oldString.match(githubUrlPattern) || []; + const newUrls = newString.match(githubUrlPattern) || []; + + // Check 1: New GitHub URLs added (requires approval) + if (newUrls.length > oldUrls.length) { + return { + passed: false, + reason: 'inst_084: New GitHub URL detected - requires explicit approval', + output: `Attempting to add GitHub URL:\n New: ${newUrls.join(', ')}\n Old: ${oldUrls.join(', ')}\n\nBLOCKED: Adding GitHub URLs requires explicit human approval to prevent exposure of private repository structure.` + }; + } + + // Check 2: GitHub repository name changed (HIGH RISK) + if (oldUrls.length > 0 && newUrls.length > 0) { + const oldRepos = new Set(oldUrls); + const newRepos = new Set(newUrls); + + // Find any repository name changes + for (const oldRepo of oldRepos) { + if (!newRepos.has(oldRepo)) { + return { + passed: false, + reason: 'inst_084: GitHub repository name change detected - HARD BLOCK', + output: `CRITICAL: Repository URL modification detected:\n Old: ${oldRepo}\n New: ${Array.from(newRepos).join(', ')}\n\nBLOCKED: This could expose private repository structure (e.g., tractatus-framework → tractatus exposes /src/services/).\n\nRequired: Explicit human approval for ANY GitHub repository URL changes.` + }; + } + } + } + + // Check 3: GitHub URL path changed (e.g., /tree/main/src/services → /tree/main/deployment-quickstart) + const oldPaths = oldString.match(/github\.com[^\s"'<>]*/g) || []; + const newPaths = newString.match(/github\.com[^\s"'<>]*/g) || []; + + if (oldPaths.length > 0 && newPaths.length > 0) { + for (let i = 0; i < Math.min(oldPaths.length, newPaths.length); i++) { + if (oldPaths[i] !== newPaths[i]) { + return { + passed: false, + reason: 'inst_084: GitHub URL path modification detected - requires approval', + output: `GitHub URL path change detected:\n Old: ${oldPaths[i]}\n New: ${newPaths[i]}\n\nBLOCKED: URL path modifications require explicit approval to prevent linking to non-existent or private paths.` + }; + } + } + } + + return { passed: true }; +}