#!/usr/bin/env node /** * Apply Governance Audit Recommendations (2025-10-21) * * This script implements the recommendations from GOVERNANCE_RULES_AUDIT_2025-10-21.md: * - Consolidates 12 overlapping rules into 4 consolidated rules * - Creates 5 new rules to fill coverage gaps * - Splits inst_024 into 5 granular rules * - Adjusts persistence levels and quadrant classifications * - Updates version from 3.5 to 3.6 */ const fs = require('fs'); const path = require('path'); const INSTRUCTION_FILE = path.join(__dirname, '../.claude/instruction-history.json'); console.log('═══════════════════════════════════════════════════════════'); console.log(' GOVERNANCE AUDIT IMPLEMENTATION - 2025-10-21'); console.log('═══════════════════════════════════════════════════════════\n'); // Read current data console.log('📖 Reading current instruction-history.json...'); const data = JSON.parse(fs.readFileSync(INSTRUCTION_FILE, 'utf8')); console.log(` Version: ${data.version}`); console.log(` Instructions: ${data.instructions.length}`); console.log(` Active: ${data.instructions.filter(i => i.active !== false).length}\n`); // Step 1: Deprecate rules that will be consolidated or replaced console.log('🗑️ Step 1: Deprecating rules...'); const deprecations = [ // Consolidated into inst_008_CONSOLIDATED { id: 'inst_008', reason: 'Consolidated into inst_008_CONSOLIDATED (CSP and security headers)' }, { id: 'inst_044', reason: 'Consolidated into inst_008_CONSOLIDATED (CSP and security headers)' }, { id: 'inst_048', reason: 'Consolidated into inst_008_CONSOLIDATED (CSP and security headers)' }, // Consolidated into inst_020_CONSOLIDATED { id: 'inst_020', reason: 'Consolidated into inst_020_CONSOLIDATED (deployment permissions)' }, { id: 'inst_022', reason: 'Consolidated into inst_020_CONSOLIDATED (deployment permissions)' }, // Consolidated into inst_041_CONSOLIDATED { id: 'inst_041', reason: 'Consolidated into inst_041_CONSOLIDATED (file input validation)' }, { id: 'inst_042', reason: 'Consolidated into inst_041_CONSOLIDATED (file input validation)' }, // Consolidated into inst_063_CONSOLIDATED { id: 'inst_028', reason: 'Consolidated into inst_063_CONSOLIDATED (public GitHub management)' }, { id: 'inst_062', reason: 'Consolidated into inst_063_CONSOLIDATED (public GitHub management)' }, { id: 'inst_063', reason: 'Consolidated into inst_063_CONSOLIDATED (public GitHub management)' }, // Replaced by inst_064 { id: 'inst_007', reason: 'Replaced by inst_064 (framework component usage - more specific)' }, // Split into inst_024a/b/c/d/e { id: 'inst_024', reason: 'Split into inst_024a/b/c/d/e for granular enforcement' } ]; deprecations.forEach(({ id, reason }) => { const rule = data.instructions.find(i => i.id === id); if (rule) { rule.active = false; rule.deprecation_reason = reason; rule.deprecated_date = '2025-10-21'; rule.deprecated_session = '2025-10-07-001'; console.log(` ✓ Deprecated ${id}`); } else { console.log(` ✗ WARNING: ${id} not found`); } }); console.log(''); // Step 2: Add consolidated rules console.log('➕ Step 2: Adding consolidated rules...'); const consolidatedRules = [ { id: 'inst_008_CONSOLIDATED', text: 'ALL HTML/JS must comply with Content Security Policy: no inline event handlers (onclick, onload, etc.), no inline scripts, no inline styles. ALL HTTP responses MUST include comprehensive security headers: Content-Security-Policy, Strict-Transport-Security, X-Frame-Options (DENY), X-Content-Type-Options (nosniff), Referrer-Policy (strict-origin-when-cross-origin). Pre-tool execution hook validators (validate-file-write.js, validate-file-edit.js) MUST check CSP compliance before allowing edits and provide specific violation details if blocked.', quadrant: 'SYSTEM', persistence: 'HIGH', temporal_scope: 'PERMANENT', session_id: '2025-10-07-001', notes: 'CONSOLIDATED from inst_008, inst_044, inst_048. Single source of truth for CSP and security header requirements. Prevents CSP violations and security header omissions.', deprecates: ['inst_008', 'inst_044', 'inst_048'], active: true, created_date: '2025-10-21', parameters: { verification_required: 'MANDATORY', blocking: true, enforcement_location: 'pre-tool-hooks' } }, { id: 'inst_020_CONSOLIDATED', text: 'Web application deployments MUST ensure correct file permissions before going live. Public-facing HTML/CSS/JS: 644 (rw-r--r--), executable scripts: 755 (rwxr-xr-x), admin directories: 750 (rwxr-x---). ALL deployment scripts (rsync, scp, git pull) MUST include automated post-deployment permission correction commands. Verify with "ls -la" before declaring deployment complete. Permission errors are recurring deployment failures - automated correction is mandatory.', quadrant: 'OPERATIONAL', persistence: 'HIGH', temporal_scope: 'PERMANENT', session_id: '2025-10-07-001', notes: 'CONSOLIDATED from inst_020, inst_022. Prevents public access to admin directories and execution of static files. Recurring issue required automation mandate.', deprecates: ['inst_020', 'inst_022'], active: true, created_date: '2025-10-21', parameters: { verification_required: 'MANDATORY', blocking: true, automation_required: true } }, { id: 'inst_041_CONSOLIDATED', text: 'ALL file inputs (web uploads, email attachments, user-provided files) MUST be validated before processing: (1) File type whitelist validation (reject executables, scripts), (2) Size limits enforced, (3) Content scanning for malware/XSS payloads, (4) Secure storage (GridFS with encryption), (5) Access control (authenticated users only, role-based permissions). Reject and log all suspicious files per inst_046 (security event logging). Never trust client-provided MIME types - verify file signatures.', quadrant: 'SYSTEM', persistence: 'HIGH', temporal_scope: 'PERMANENT', session_id: '2025-10-07-001', notes: 'CONSOLIDATED from inst_041, inst_042. Comprehensive file/attachment security validation. Part of security vetting framework.', deprecates: ['inst_041', 'inst_042'], active: true, created_date: '2025-10-21', parameters: { verification_required: 'MANDATORY', blocking: true, security_critical: true } }, { id: 'inst_063_CONSOLIDATED', text: 'Public GitHub repository (tractatus-framework) must remain implementation-focused. Prohibited without explicit approval: (1) Governance research documents, (2) Pluralistic deliberation guides, (3) Theoretical frameworks, (4) Project-specific internal documentation, (5) Business strategy documents. Allowed: (1) Technical implementation documentation, (2) API reference guides, (3) Code examples and tutorials, (4) Installation/setup guides, (5) Contribution guidelines. README.md must be reviewed weekly and "Last Updated" date updated when material changes occur. README is primary external interface - must be world-class and current.', quadrant: 'STRATEGIC', persistence: 'HIGH', temporal_scope: 'PERMANENT', session_id: '2025-10-07-001', notes: 'CONSOLIDATED from inst_028, inst_062, inst_063. Created after bad actor incident where AI converted implementation docs to authoritarian governance guide. Prevents misrepresentation of framework purpose.', deprecates: ['inst_028', 'inst_062', 'inst_063'], active: true, created_date: '2025-10-21', parameters: { verification_required: 'ADVISORY', requires_user_approval: true, review_frequency: 'weekly' } } ]; consolidatedRules.forEach(rule => { data.instructions.push(rule); console.log(` ✓ Added ${rule.id}`); }); console.log(''); // Step 3: Add new rules (coverage gaps) console.log('➕ Step 3: Adding new rules (coverage gaps)...'); const newRules = [ { id: 'inst_064', text: 'Tractatus framework components MUST be actively used throughout sessions: (1) ContextPressureMonitor: At session start (baseline), 50k/100k/150k token milestones, after complex multi-file operations, after errors. (2) InstructionPersistenceClassifier: When user gives explicit instruction, configuration specifications, architectural constraints. (3) CrossReferenceValidator: Before database schema changes, configuration modifications, architectural decisions. (4) BoundaryEnforcer: Before privacy policy decisions, ethical trade-offs, values-sensitive content. (5) MetacognitiveVerifier: For operations with 3+ file modifications or 5+ sequential steps. (6) PluralisticDeliberationOrchestrator: When BoundaryEnforcer flags values conflict. Framework fade (components not being used) = CRITICAL FAILURE. Update .claude/session-state.json after each component use with timestamp and validation count.', quadrant: 'OPERATIONAL', persistence: 'HIGH', temporal_scope: 'PERMANENT', session_id: '2025-10-07-001', notes: 'CRITICAL ENFORCEMENT GAP - Previously documented but not enforced as rule. Specifies exactly when each component must be used. Replaces vague inst_007.', replaces: ['inst_007'], active: true, created_date: '2025-10-21', parameters: { verification_required: 'MANDATORY', framework_critical: true, failure_mode: 'CRITICAL' } }, { id: 'inst_065', text: 'MANDATORY at session start and immediately after conversation compaction: Run "node scripts/session-init.js", then report to user: (1) Server status: curl -s http://localhost:9000/health | jq -r \'.status\' (expect \'ok\'), (2) Framework statistics: session ID, active instructions count, version from .claude/session-state.json and .claude/instruction-history.json, (3) MongoDB status: active rules count from tractatus_dev database. BLOCK all session work until initialization complete and results reported to user. Output results in clean formatted summary before proceeding with any tasks.', quadrant: 'OPERATIONAL', persistence: 'HIGH', temporal_scope: 'PERMANENT', session_id: '2025-10-07-001', notes: 'Required by CLAUDE.md but not previously enforced as rule. Ensures framework operational before work begins. Critical for session continuity after compaction.', active: true, created_date: '2025-10-21', parameters: { verification_required: 'MANDATORY', blocking: true, triggers: ['session_start', 'post_compaction'] } }, { id: 'inst_066', text: 'ALL git commits MUST use conventional commit format: "type(scope): description". Types: feat (new feature), fix (bug fix), docs (documentation), refactor (code restructure), test (test additions), chore (maintenance). Include Claude Code attribution footer:\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\nCo-Authored-By: Claude \n\nNEVER use "git commit -i" or "git add -i" (interactive modes not supported). When pre-commit hooks modify files, verify commit authorship (git log -1 --format=\'%an %ae\') before amending - NEVER amend other developers\' commits.', quadrant: 'OPERATIONAL', persistence: 'HIGH', temporal_scope: 'PERMANENT', session_id: '2025-10-07-001', notes: 'Documented in Maintenance Guide but not enforced as rule. Improves git history quality and provides attribution transparency.', active: true, created_date: '2025-10-21', parameters: { verification_required: 'ADVISORY', quality_standard: true } }, { id: 'inst_067', text: 'BEFORE database operations or port-specific commands: (1) VERIFY current environment (local vs production) from context, (2) VERIFY correct port/database from explicit user instruction OR CLAUDE.md defaults (local: tractatus_dev:27017 on port 9000, production: tractatus_prod:27017 on port 9000), (3) If user specifies non-standard port or database (e.g., port 27027, custom database name), USE EXACT VALUE FROM USER INSTRUCTION - do NOT autocorrect to standard defaults. Pattern recognition bias for standard ports/databases is a known 27027 failure mode where training data associations override explicit instructions. When in doubt, ask user to confirm environment.', quadrant: 'SYSTEM', persistence: 'HIGH', temporal_scope: 'PERMANENT', session_id: '2025-10-07-001', notes: 'Prevents 27027-type failures where pattern recognition overrides explicit user instructions. Critical for multi-environment operations.', active: true, created_date: '2025-10-21', parameters: { verification_required: 'MANDATORY', failure_prevention: '27027_pattern_bias', blocking: true } }, { id: 'inst_068', text: 'Run tests in these scenarios: (1) Before git commits if tests exist for modified code area, (2) Before all deployments (run full test suite), (3) After refactoring (run affected tests), (4) When user explicitly requests testing. Test failures BLOCK commits and deployments unless user explicitly approves proceeding with failing tests. When creating new features, ask user if tests should be written - do not assume test requirements. Report test results with counts: X passed, Y failed, Z skipped. Use "npm test" for full suite or "npm test -- " for specific tests.', quadrant: 'OPERATIONAL', persistence: 'HIGH', temporal_scope: 'PERMANENT', session_id: '2025-10-07-001', notes: 'Aligns with world-class quality standard (inst_004). Prevents regressions and maintains code quality.', active: true, created_date: '2025-10-21', parameters: { verification_required: 'MANDATORY', blocking: true, quality_critical: true } } ]; newRules.forEach(rule => { data.instructions.push(rule); console.log(` ✓ Added ${rule.id}`); }); console.log(''); // Step 4: Add split rules (inst_024a-e) console.log('➕ Step 4: Adding split rules (inst_024a-e)...'); const splitRules = [ { id: 'inst_024a', text: 'Before session handoff or closedown: Kill all background processes spawned during session (npm, jest, node, dev servers, file watchers). Use "ps aux | grep -E \\"npm|jest|node\\"" to find processes, "pkill -f " to terminate. Verify cleanup with "ps aux | grep -E \\"npm|jest|node\\"" again (should show no results except grep itself). Update .claude/session-state.json with cleanup timestamp and process count terminated.', quadrant: 'OPERATIONAL', persistence: 'HIGH', temporal_scope: 'PERMANENT', session_id: '2025-10-07-001', notes: 'Split from inst_024 for granular enforcement. Part of comprehensive closedown protocol.', part_of: 'inst_024_series', active: true, created_date: '2025-10-21', parameters: { verification_required: 'MANDATORY', closedown_step: 1 } }, { id: 'inst_024b', text: 'Before session handoff: Verify .claude/instruction-history.json changes are synced to MongoDB governanceRules collection. If instruction-history.json modified this session, run "node scripts/sync-instructions-to-db.js" to sync. Compare counts: active instructions in JSON vs active rules in database. Report sync status in handoff document: "Synced: X instructions → Y database rules" or "Not needed: No changes this session".', quadrant: 'OPERATIONAL', persistence: 'HIGH', temporal_scope: 'PERMANENT', session_id: '2025-10-07-001', notes: 'Split from inst_024 for granular enforcement. Ensures file-database consistency.', part_of: 'inst_024_series', active: true, created_date: '2025-10-21', parameters: { verification_required: 'MANDATORY', closedown_step: 2 } }, { id: 'inst_024c', text: 'Before session handoff: Document complete git status: (1) Current branch, (2) Commits ahead/behind remote (git status shows "Your branch is ahead of origin/main by X commits"), (3) Working tree status (clean vs untracked files), (4) Most recent commits (git log --oneline -5). Include in handoff document with explanations for any untracked files (e.g., "untracked files are INTERNAL project files, NOT for public repo"). If working tree has uncommitted changes, explain why or commit before handoff.', quadrant: 'OPERATIONAL', persistence: 'HIGH', temporal_scope: 'PERMANENT', session_id: '2025-10-07-001', notes: 'Split from inst_024 for granular enforcement. Provides next session with clear git context.', part_of: 'inst_024_series', active: true, created_date: '2025-10-21', parameters: { verification_required: 'MANDATORY', closedown_step: 3 } }, { id: 'inst_024d', text: 'Before session handoff: Clean temporary artifacts created during session: (1) .memory-test/ directory (if exists from testing), (2) Test databases (mongosh --eval "db.dropDatabase()" on tractatus_test), (3) Stale lock files (check age - if hours old with no process, safe to delete), (4) Temporary scripts in /tmp/. Document what was cleaned and what was intentionally kept (e.g., "package-lock.json kept - legitimate", "mongod.lock kept - server running"). Do NOT delete legitimate lock files for running processes.', quadrant: 'OPERATIONAL', persistence: 'HIGH', temporal_scope: 'PERMANENT', session_id: '2025-10-07-001', notes: 'Split from inst_024 for granular enforcement. Prevents clutter accumulation across sessions.', part_of: 'inst_024_series', active: true, created_date: '2025-10-21', parameters: { verification_required: 'ADVISORY', closedown_step: 4 } }, { id: 'inst_024e', text: 'Create session handoff document as OPTIMAL_STARTUP_PROMPT_.md with: (1) Current system status (server, framework, database, git), (2) Completed tasks with file:line references and verification, (3) In-progress tasks with blockers and next steps, (4) Pending tasks prioritized by user importance, (5) Recent instruction additions/changes with rationale, (6) Known issues and gotchas, (7) Framework health assessment, (8) User decisions needed, (9) Ready-to-use TodoWrite JSON for next session, (10) Recommended startup sequence with exact commands. STOP ALL WORK IMMEDIATELY after creating handoff document - handoff signals NEW session intent, not continuation.', quadrant: 'OPERATIONAL', persistence: 'HIGH', temporal_scope: 'PERMANENT', session_id: '2025-10-07-001', notes: 'Split from inst_024 for granular enforcement. Core handoff creation with strict format requirements.', part_of: 'inst_024_series', active: true, created_date: '2025-10-21', parameters: { verification_required: 'MANDATORY', closedown_step: 5, terminal_action: true } } ]; splitRules.forEach(rule => { data.instructions.push(rule); console.log(` ✓ Added ${rule.id}`); }); console.log(''); // Step 5: Adjust persistence levels and quadrant classifications console.log('🔧 Step 5: Adjusting persistence and quadrants...'); const adjustments = [ { id: 'inst_011', changes: { persistence: 'MEDIUM' }, reason: 'Lowered from HIGH - implementation detail' }, { id: 'inst_021', changes: { persistence: 'MEDIUM', quadrant: 'TACTICAL' }, reason: 'Lowered from HIGH, reclassified to TACTICAL' }, { id: 'inst_059', changes: { quadrant: 'TACTICAL' }, reason: 'Reclassified from OPERATIONAL to TACTICAL' }, { id: 'inst_061', changes: { quadrant: 'TACTICAL' }, reason: 'Reclassified from OPERATIONAL to TACTICAL' }, ]; adjustments.forEach(({ id, changes, reason }) => { const rule = data.instructions.find(i => i.id === id); if (rule) { Object.assign(rule, changes); if (!rule.adjustment_history) rule.adjustment_history = []; rule.adjustment_history.push({ date: '2025-10-21', session: '2025-10-07-001', changes, reason }); console.log(` ✓ Adjusted ${id}: ${reason}`); } else { console.log(` ✗ WARNING: ${id} not found`); } }); console.log(''); // Step 6: Update inst_009 text (Stripe status) console.log('🔧 Step 6: Updating inst_009 text...'); const inst_009 = data.instructions.find(i => i.id === 'inst_009'); if (inst_009) { inst_009.text = 'Stripe payment processing is ACTIVE (test keys configured). Email services (verification emails, donation receipts) are deferred until production launch. ProtonBridge email integration is Phase 2+.'; inst_009.notes = 'Updated 2025-10-21: Stripe fully implemented and active (test keys configured). Email services remain deferred until production launch with ProtonBridge integration planned for Phase 2+.'; console.log(' ✓ Updated inst_009 text and notes'); } else { console.log(' ✗ WARNING: inst_009 not found'); } console.log(''); // Step 7: Enhance vague rules console.log('🔧 Step 7: Enhancing vague rules...'); const inst_040 = data.instructions.find(i => i.id === 'inst_040'); if (inst_040) { inst_040.text = 'When user says "all" (e.g., "update all pages", "fix all instances", "check all files"), Claude MUST: (1) Use Glob/Grep to find ALL matches, (2) List every item found with file:line references, (3) Confirm with user before proceeding, (4) Track completion of each item. NEVER assume "all" means "a few examples" or "the ones I found first".'; console.log(' ✓ Enhanced inst_040 with specific examples'); } else { console.log(' ✗ WARNING: inst_040 not found'); } const inst_047 = data.instructions.find(i => i.id === 'inst_047'); if (inst_047) { inst_047.text = 'NEVER dismiss, downplay, or avoid user requests by claiming "too hard", "too complex", "beyond capabilities". When facing difficult requests: (1) Acknowledge complexity honestly, (2) Break into smaller steps, (3) Identify blockers explicitly, (4) Propose alternative approaches, (5) Ask user for priorities/trade-offs. If truly impossible, explain technical limitations with evidence, not vague dismissal.'; console.log(' ✓ Enhanced inst_047 with positive guidance'); } else { console.log(' ✗ WARNING: inst_047 not found'); } const inst_054 = data.instructions.find(i => i.id === 'inst_054'); if (inst_054) { inst_054.text = 'PRE-DEPLOYMENT CHECKLIST (run in order):\n□ 1. CSP Compliance Check [AUTOMATED via hook]\n□ 2. Local Server Test (curl http://localhost:9000/health → 200 OK)\n□ 3. Comprehensive Testing (npm test → all pass)\n□ 4. Permission Verification (ls -la → correct 644/755)\n□ 5. Git Status Clean (no uncommitted changes)\nMark each checkbox before proceeding to next. BLOCK deployment if any step fails.'; console.log(' ✓ Enhanced inst_054 with checklist format'); } else { console.log(' ✗ WARNING: inst_054 not found'); } console.log(''); // Step 8: Update version and recalculate stats console.log('📊 Step 8: Updating version and recalculating stats...'); data.version = '3.6'; data.last_updated = new Date().toISOString(); // Recalculate stats const activeInstructions = data.instructions.filter(i => i.active !== false); const quadrantCounts = { SYSTEM: 0, STRATEGIC: 0, OPERATIONAL: 0, TACTICAL: 0 }; const persistenceCounts = { HIGH: 0, MEDIUM: 0, LOW: 0 }; activeInstructions.forEach(inst => { if (inst.quadrant) quadrantCounts[inst.quadrant]++; if (inst.persistence) persistenceCounts[inst.persistence]++; }); data.stats = { total_instructions: data.instructions.length, active_instructions: activeInstructions.length, by_quadrant: quadrantCounts, by_persistence: persistenceCounts }; console.log(' ✓ Updated to version 3.6'); console.log(` ✓ Stats: ${data.stats.active_instructions} active / ${data.stats.total_instructions} total`); console.log(''); // Step 9: Write updated file console.log('💾 Step 9: Writing updated instruction-history.json...'); // Create backup first const backupFile = INSTRUCTION_FILE + '.backup-3.5-' + Date.now(); fs.copyFileSync(INSTRUCTION_FILE, backupFile); console.log(` ✓ Backup created: ${path.basename(backupFile)}`); fs.writeFileSync(INSTRUCTION_FILE, JSON.stringify(data, null, 2)); console.log(` ✓ Written to ${path.basename(INSTRUCTION_FILE)}`); console.log(''); // Summary console.log('═══════════════════════════════════════════════════════════'); console.log(' SUMMARY'); console.log('═══════════════════════════════════════════════════════════\n'); console.log('📊 CHANGES:'); console.log(` Version: 3.5 → 3.6`); console.log(` Total instructions: 54 → ${data.stats.total_instructions}`); console.log(` Active instructions: 54 → ${data.stats.active_instructions}`); console.log(` Deprecated: ${deprecations.length} rules`); console.log(` Added consolidated: ${consolidatedRules.length} rules`); console.log(` Added new: ${newRules.length} rules`); console.log(` Added split: ${splitRules.length} rules`); console.log(` Adjusted: ${adjustments.length} rules`); console.log(` Enhanced: 3 rules`); console.log(''); console.log('📋 BY QUADRANT:'); Object.entries(data.stats.by_quadrant).forEach(([q, count]) => { console.log(` ${q}: ${count}`); }); console.log(''); console.log('🔒 BY PERSISTENCE:'); Object.entries(data.stats.by_persistence).forEach(([p, count]) => { console.log(` ${p}: ${count}`); }); console.log(''); console.log('✅ Governance audit implementation COMPLETE'); console.log(''); console.log('NEXT STEPS:'); console.log('1. Sync to MongoDB: node scripts/sync-instructions-to-db.js'); console.log('2. Run framework tests: npm test'); console.log('3. Verify session initialization: node scripts/session-init.js'); console.log('');