tractatus/scripts/generate-missing-pdfs.js
TheFlow 0e6be3eaf1 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

202 lines
4.8 KiB
JavaScript

#!/usr/bin/env node
/**
* Generate Missing PDFs for Public Documents
* Uses document markdown from database
*/
require('dotenv').config();
const { connect, close } = require('../src/utils/db.util');
const Document = require('../src/models/Document.model');
const puppeteer = require('puppeteer');
const marked = require('marked');
const fs = require('fs').promises;
const path = require('path');
const MISSING_PDFS = [
'case-studies-real-world-llm-failure-modes-appendix',
'implementation-guide-python-examples',
'tractatus-framework-enforcement-claude-code',
'research-topic-concurrent-session-architecture',
'research-topic-rule-proliferation-transactional-overhead',
'architectural-safeguards-against-llm-hierarchical-dominance-prose'
];
function generatePdfHtml(title, content) {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>${title}</title>
<style>
@page {
margin: 2cm;
size: A4;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
font-size: 11pt;
line-height: 1.6;
color: #1f2937;
}
.cover {
page-break-after: always;
display: flex;
flex-direction: column;
justify-content: center;
min-height: 80vh;
text-align: center;
border-bottom: 3px solid #2563eb;
}
.cover h1 {
font-size: 2.5rem;
font-weight: 700;
color: #111827;
margin-bottom: 1rem;
}
.cover .metadata {
font-size: 1rem;
color: #6b7280;
margin-top: 2rem;
}
h1 { font-size: 1.875rem; color: #111827; margin-top: 2rem; }
h2 { font-size: 1.5rem; color: #1f2937; margin-top: 1.5rem; }
h3 { font-size: 1.25rem; color: #374151; margin-top: 1.25rem; }
p { margin-bottom: 1rem; }
code {
background: #f3f4f6;
padding: 0.2rem 0.4rem;
border-radius: 0.25rem;
font-family: 'Courier New', monospace;
font-size: 0.9em;
}
pre {
background: #f9fafb;
border: 1px solid #e5e7eb;
border-radius: 0.5rem;
padding: 1rem;
overflow-x: auto;
page-break-inside: avoid;
}
pre code {
background: none;
padding: 0;
}
blockquote {
border-left: 4px solid #2563eb;
padding-left: 1rem;
margin-left: 0;
color: #4b5563;
font-style: italic;
}
table {
border-collapse: collapse;
width: 100%;
margin: 1rem 0;
page-break-inside: avoid;
}
th, td {
border: 1px solid #e5e7eb;
padding: 0.5rem;
text-align: left;
}
th {
background: #f3f4f6;
font-weight: 600;
}
</style>
</head>
<body>
<div class="cover">
<h1>${title}</h1>
<div class="metadata">
<p><strong>Tractatus Framework Documentation</strong></p>
<p>© 2025 Tractatus Project</p>
<p>https://agenticgovernance.digital</p>
</div>
</div>
<div class="content">
${content}
</div>
</body>
</html>`;
}
async function generatePdf(slug, outputDir) {
const doc = await Document.findBySlug(slug);
if (!doc) {
console.log(`⚠️ Document not found: ${slug}`);
return false;
}
console.log(`\n📄 Generating: ${doc.title}`);
console.log(` Slug: ${slug}`);
if (!doc.content_markdown) {
console.log(` ❌ No markdown content`);
return false;
}
const html = marked.parse(doc.content_markdown);
const fullHtml = generatePdfHtml(doc.title, html);
const browser = await puppeteer.launch({
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
const page = await browser.newPage();
await page.setContent(fullHtml, { waitUntil: 'networkidle0' });
const pdfPath = path.join(outputDir, `${slug}.pdf`);
await page.pdf({
path: pdfPath,
format: 'A4',
printBackground: true,
margin: { top: '2cm', right: '2cm', bottom: '2cm', left: '2cm' }
});
await browser.close();
console.log(` ✅ Generated: ${pdfPath}`);
return true;
}
async function main() {
await connect();
console.log('\n' + '='.repeat(70));
console.log('GENERATING MISSING PDFs');
console.log('='.repeat(70) + '\n');
const outputDir = path.join(__dirname, '../public/downloads');
let generated = 0;
let failed = 0;
for (const slug of MISSING_PDFS) {
try {
const success = await generatePdf(slug, outputDir);
if (success) {
generated++;
} else {
failed++;
}
} catch (error) {
console.log(` ❌ Error: ${error.message}`);
failed++;
}
}
console.log('\n' + '='.repeat(70));
console.log('\n📊 Summary:');
console.log(` ✅ Generated: ${generated}`);
console.log(` ❌ Failed: ${failed}`);
console.log(` 📦 Total: ${MISSING_PDFS.length}`);
console.log('\n' + '='.repeat(70) + '\n');
await close();
}
main();