tractatus/scripts/migrate-doc-categories.js
TheFlow 2af47035ac refactor: remove website code and fix critical startup crashes (Phase 8)
CRITICAL FIX: Server would CRASH ON STARTUP (multiple import errors)

REMOVED (2 scripts):
1. scripts/framework-watchdog.js
   - Monitored .claude/session-state.json (OUR Claude Code setup)
   - Monitored .claude/token-checkpoints.json (OUR file structure)
   - Implementers won't have our .claude/ directory

2. scripts/init-db.js
   - Created website collections: blog_posts, media_inquiries, case_submissions
   - Created website collections: resources, moderation_queue, users, citations
   - Created website collections: translations, koha_donations
   - Next steps referenced deleted scripts (npm run seed:admin)

REWRITTEN (2 files):

src/models/index.js (29 lines → 27 lines)
- REMOVED imports: Document, BlogPost, MediaInquiry, CaseSubmission, Resource
- REMOVED imports: ModerationQueue, User (all deleted in Phase 2)
- KEPT imports: AuditLog, DeliberationSession, GovernanceLog, GovernanceRule
- KEPT imports: Precedent, Project, SessionState, VariableValue, VerificationLog
- Result: Only framework models exported

src/server.js (284 lines → 163 lines, 43% reduction)
- REMOVED: Imports to deleted middleware (csrf-protection, response-sanitization)
- REMOVED: Stripe webhook handling (/api/koha/webhook)
- REMOVED: Static file caching (for deleted public/ directory)
- REMOVED: Static file serving (public/ deleted in Phase 6)
- REMOVED: CSRF token endpoint
- REMOVED: Website homepage with "auth, documents, blog, admin" references
- REMOVED: Instruction sync (scripts/sync-instructions-to-db.js reference)
- REMOVED: Hardcoded log path (${process.env.HOME}/var/log/tractatus/...)
- REMOVED: Website-specific security middleware
- KEPT: Security headers, rate limiting, CORS, body parsers
- KEPT: API routes, governance services, MongoDB connections
- RESULT: Clean framework-only server

RESULT: Repository can now start without crashes, all imports resolve

🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-21 22:17:02 +13:00

142 lines
5.4 KiB
JavaScript
Executable file

#!/usr/bin/env node
/**
* Migrate documents to new granular category structure
*
* New Categories:
* - getting-started: Introduction, core concepts, quick start, FAQ
* - technical-reference: API docs, implementation guides, code examples
* - research-theory: Research papers, theoretical foundations
* - case-studies: Real-world examples, failure modes, success stories
* - deployment-operations: Deployment guides, architecture, troubleshooting
* - business-leadership: Business cases, executive briefs, ROI analysis
* - downloads-resources: PDFs, sample configs, external links
*/
// Load environment variables
require('dotenv').config();
const { getDb } = require('../src/utils/db.util');
// Slug-to-category mapping (precise, no fuzzy matching)
const slugToCategory = {
// Getting Started
'introduction-to-the-tractatus-framework': 'getting-started',
'core-concepts-of-the-tractatus-framework': 'getting-started',
// Technical Reference
'api-reference-complete': 'technical-reference',
'openapi-specification': 'technical-reference',
'implementation-guide': 'technical-reference',
'tractatus-framework-implementation-guide': 'technical-reference',
'api-python-examples': 'technical-reference',
'api-javascript-examples': 'technical-reference',
'technical-architecture-diagram': 'technical-reference',
'technical-architecture': 'technical-reference',
'tractatus-agentic-governance-system-glossary-of-terms': 'technical-reference',
'comparison-matrix-claude-code-claudemd-and-tractatus-framework': 'technical-reference',
// Research & Theory
'organizational-theory-foundations-of-the-tractatus-framework': 'research-theory',
'research-foundations-scholarly-review-and-context': 'research-theory',
'executive-brief-tractatus-based-llm-architecture-for-ai-safety': 'research-theory',
'structural-governance-for-agentic-ai-the-tractatus-inflection-point': 'research-theory',
'tractatus-ai-safety-framework-core-values-and-principles': 'research-theory',
'architectural-overview-and-research-status': 'research-theory',
// Advanced Topics
'value-pluralism-faq': 'advanced-topics',
'pluralistic-values-research-foundations': 'advanced-topics',
'pluralistic-values-deliberation-plan-v2': 'advanced-topics',
'research-scope-feasibility-of-llm-integrated-tractatus-framework': 'advanced-topics',
'research-topic-rule-proliferation-and-transactional-overhead-in-ai-governance': 'advanced-topics',
'research-topic-concurrent-session-architecture-limitations-in-claude-code-governance': 'advanced-topics',
// Case Studies
'case-studies-real-world-llm-failure-modes': 'case-studies',
'the-27027-incident-a-case-study-in-pattern-recognition-bias': 'case-studies',
'our-framework-in-action-detecting-and-correcting-ai-fabrications': 'case-studies',
'framework-governance-in-action-pre-publication-security-audit': 'case-studies',
'when-frameworks-fail-and-why-thats-ok': 'case-studies',
'real-world-ai-governance-a-case-study-in-framework-failure-and-recovery': 'case-studies',
// Business & Leadership
'ai-governance-business-case-template-tractatus-framework': 'business-leadership',
'business-case-for-ai-governance-tractatus-framework': 'business-leadership',
'executive-summary-tractatus-inflection-point': 'business-leadership',
'implementation-roadmap-24-month-deployment-plan': 'business-leadership',
// Archived
'phase-2': 'archived',
'phase-3': 'archived',
'phase-5-poc-session-1-summary': 'archived',
'phase-5-poc-session-2-summary': 'archived'
};
async function migrateCategories() {
console.log('🔄 Migrating document categories to new structure...\n');
const db = await getDb();
const collection = db.collection('documents');
// Get all documents
const documents = await collection.find({}).toArray();
console.log(`📚 Found ${documents.length} documents\n`);
let updated = 0;
let errors = 0;
for (const doc of documents) {
try {
// Use slug-based mapping (precise)
const newCategory = slugToCategory[doc.slug] || 'technical-reference';
// Update document if category changed
if (doc.category !== newCategory) {
await collection.updateOne(
{ _id: doc._id },
{
$set: {
category: newCategory,
'metadata.date_updated': new Date()
}
}
);
console.log(`✅ Updated: "${doc.title}"`);
console.log(` Category: ${doc.category || 'none'}${newCategory}\n`);
updated++;
}
} catch (error) {
console.error(`❌ Error updating "${doc.title}":`, error.message);
errors++;
}
}
console.log('\n' + '='.repeat(60));
console.log('📊 Migration Summary:');
console.log('='.repeat(60));
console.log(`Total documents: ${documents.length}`);
console.log(`✅ Updated: ${updated}`);
console.log(`⏭️ Unchanged: ${documents.length - updated - errors}`);
console.log(`❌ Errors: ${errors}`);
console.log('='.repeat(60));
// Show category breakdown
console.log('\n📂 Category Breakdown:');
const categoryCounts = await collection.aggregate([
{ $group: { _id: '$category', count: { $sum: 1 } } },
{ $sort: { count: -1 } }
]).toArray();
categoryCounts.forEach(({ _id, count }) => {
console.log(` ${_id || 'none'}: ${count}`);
});
process.exit(0);
}
// Run migration
migrateCategories().catch(error => {
console.error('❌ Migration failed:', error);
process.exit(1);
});