commit 4445b0e8d00c406726ca08478de5eea278448a4d Author: TheFlow Date: Mon Oct 6 23:26:26 2025 +1300 feat: initialize tractatus project with complete directory structure - Create comprehensive project structure (29 directories) - Add CLAUDE.md with project context and conventions - Add package.json with dependencies and scripts - Add .gitignore and .env.example - Add README.md with project overview - Configure ports: MongoDB 27017, Application 9000 - Establish Tractatus governance framework baseline - Document Te Tiriti approach and indigenous perspective - Set up infrastructure for Phase 1 implementation Project Status: Development - Phase 1 Foundation Complete Next: MongoDB instance setup and systemd service configuration diff --git a/.env.example b/.env.example new file mode 100644 index 00000000..19a29be6 --- /dev/null +++ b/.env.example @@ -0,0 +1,33 @@ +# Application +NODE_ENV=development +PORT=9000 +APP_NAME=Tractatus + +# MongoDB +MONGODB_URI=mongodb://localhost:27017/tractatus_dev +MONGODB_PORT=27017 +MONGODB_DB=tractatus_dev + +# JWT Authentication +JWT_SECRET=generate_a_secure_random_secret_key_here +JWT_EXPIRY=7d + +# Admin +ADMIN_EMAIL=john.stroh.nz@pm.me + +# Claude API (Phase 2+) +# CLAUDE_API_KEY=your_anthropic_api_key_here +# CLAUDE_MODEL=claude-sonnet-4-5 + +# Logging +LOG_LEVEL=info +LOG_FILE=logs/app.log + +# Feature Flags +ENABLE_AI_CURATION=false +ENABLE_MEDIA_TRIAGE=false +ENABLE_CASE_SUBMISSIONS=false + +# Security +RATE_LIMIT_WINDOW_MS=900000 +RATE_LIMIT_MAX_REQUESTS=100 diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..4d7c4b2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,48 @@ +# Dependencies +node_modules/ +package-lock.json + +# Environment variables +.env +.env.local +.env.*.local + +# Logs +logs/ +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# MongoDB data +data/mongodb/* +!data/mongodb/.gitkeep + +# Generated files +public/downloads/*.pdf +public/downloads/*.epub +public/downloads/*.docx + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS +.DS_Store +Thumbs.db + +# Testing +coverage/ +.nyc_output/ + +# Build +dist/ +build/ + +# Temporary files +tmp/ +temp/ +*.tmp diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..10cde3ae --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,416 @@ +# Tractatus AI Safety Framework Website - Project Context + +**Project Name:** Tractatus Website Platform +**Domain:** mysy.digital +**Repository:** GitHub (primary) + Codeberg/Gitea (mirrors) +**Status:** Development - Phase 1 Implementation +**Created:** 2025-10-06 +**Primary Developer:** Claude Code (Anthropic Sonnet 4.5) +**Project Owner:** John Stroh + +--- + +## ⚠️ Critical: Project Isolation + +**THIS IS A SEPARATE PROJECT FROM family-history AND sydigital** + +- **Separate MongoDB instance**: Port 27017, database `tractatus_dev` +- **Separate application port**: 9000 +- **Separate Git repository**: Local + GitHub account +- **Separate systemd services**: mongodb-tractatus.service, tractatus.service +- **No shared code/data**: Patterns may be adapted, but no dependencies + +**Sessions must maintain clear separation.** Always verify which project context you're in. + +--- + +## Project Purpose + +Build a world-class platform demonstrating the **Tractatus-Based LLM Safety Framework** through: + +1. **Three Audience Paths**: Researcher, Implementer, Advocate +2. **AI-Powered Features**: Blog curation, media triage, case studies (all with human oversight) +3. **Interactive Demonstrations**: Classification, 27027 incident, boundary enforcement +4. **Dogfooding**: The website implements Tractatus to govern its own AI operations +5. **Values Alignment**: Sovereignty, Transparency, Harmlessness, Community + +**Timeline:** 3-4 months for complete Phase 1 local prototype (no rush, no shortcuts, world-class quality) + +--- + +## Technical Architecture + +### Infrastructure +- **MongoDB**: Port 27017, database `tractatus_dev` +- **Application**: Node.js/Express on port 9000 +- **WebSocket**: Port 9001 (if needed) +- **Data Directory**: `/home/theflow/projects/tractatus/data/mongodb` +- **Logs**: `/home/theflow/projects/tractatus/logs/` + +### Technology Stack +- **Backend**: Node.js 18+, Express 4.x, MongoDB 7+ +- **Frontend**: Vanilla JavaScript, Tailwind CSS (no framework dependency) +- **Authentication**: JWT for admin/moderation +- **AI Integration**: Claude API (Sonnet 4.5) - Phase 2+ +- **File Storage**: GridFS for PDFs, documents +- **Testing**: Jest + Supertest + +### Database Collections +```javascript +tractatus_dev.documents // Technical papers, framework docs +tractatus_dev.blog_posts // AI-curated, human-approved +tractatus_dev.media_inquiries // Press/media with AI triage +tractatus_dev.case_submissions // Community case studies +tractatus_dev.resources // External links, aligned projects +tractatus_dev.moderation_queue // Human oversight queue +tractatus_dev.users // Admin accounts +tractatus_dev.citations // Academic citation tracking +tractatus_dev.translations // Multi-language content (future) +tractatus_dev.koha_donations // Phase 3 +``` + +--- + +## Tractatus Framework Governance + +**This project dogfoods the Tractatus framework** - all AI actions are governed by: + +### Core Services (to be implemented) +1. **InstructionPersistenceClassifier** - Classifies actions by quadrant (STR/OPS/TAC/SYS/STO) +2. **CrossReferenceValidator** - Validates AI actions against explicit instructions +3. **BoundaryEnforcer** - Ensures AI never makes values decisions without human approval +4. **ContextPressureMonitor** - Detects conditions that increase error probability +5. **MetacognitiveVerifier** - AI self-checks reasoning before proposing actions + +### Quadrant Mapping for Website Functions + +| Function | Quadrant | Human Oversight | Example | +|----------|----------|-----------------|---------| +| Mission/values changes | STRATEGIC | Mandatory approval | "Always prioritize privacy" | +| Blog editorial guidelines | OPERATIONAL | Quarterly review | "All posts must cite sources" | +| Publish approved post | TACTICAL | Pre-approved | Execute after human approval | +| Technical config | SYSTEM | Technical review | MongoDB ports, API keys | +| AI suggests blog topics | STOCHASTIC | Always human approval | "Write about GDPR" | + +**Critical:** All AI content suggestions require human approval. No AI action crosses into values territory without explicit human decision. + +--- + +## Governance Documents + +Located in `/home/theflow/projects/tractatus/governance/` (to be created): + +- **TRA-VAL-0001**: Tractatus Core Values (adapted from STR-VAL-0001) +- **TRA-GOV-0001**: Strategic Review Protocol (adapted from STR-GOV-0001) +- **TRA-GOV-0002**: Values Alignment Framework (adapted from STR-GOV-0002) +- **TRA-GOV-0003**: AI Boundary Enforcement Policy +- **TRA-GOV-0004**: Human Oversight Requirements + +**Reference:** Source documents in `/home/theflow/projects/sydigital/strategic/` + +--- + +## Te Tiriti & Indigenous Perspective + +### Strategic Commitment +The framework acknowledges **Te Tiriti o Waitangi** and indigenous leadership in digital sovereignty. + +### Implementation Approach +- **Respect without tokenism**: Follow documented indigenous data sovereignty principles (CARE Principles) +- **No premature engagement**: Do not approach Māori organizations until we have something valuable to offer +- **Well-documented standards**: Use published research and frameworks (Te Mana Raraunga, CARE Principles) +- **Baseline integration**: Te Tiriti forms part of strategic foundation, not dominant cultural overlay + +### Content Placement +- Footer acknowledgment (subtle, respectful) +- `/about/values` page (detailed explanation) +- Resource directory (links to Māori data sovereignty organizations) +- No meetings/consultations until post-launch + +--- + +## Development Conventions + +### Code Style +- **ES6+ JavaScript**: Modern syntax, async/await patterns +- **Modular architecture**: Small, focused functions/classes +- **Explicit naming**: No abbreviations, clear intent +- **Comments**: Explain WHY, not WHAT +- **Error handling**: Comprehensive try/catch, meaningful error messages + +### File Naming +- **Routes**: `src/routes/blog.routes.js` +- **Controllers**: `src/controllers/blog.controller.js` +- **Models**: `src/models/BlogPost.model.js` +- **Services**: `src/services/BlogCuration.service.js` +- **Middleware**: `src/middleware/auth.middleware.js` +- **Tests**: `tests/unit/blog.test.js` + +### Git Conventions +- **Commits**: Conventional commits format + - `feat:` New feature + - `fix:` Bug fix + - `docs:` Documentation + - `refactor:` Code restructure + - `test:` Test additions + - `chore:` Maintenance +- **Branches**: `feature/blog-curation`, `fix/auth-token`, `docs/api-reference` +- **No commits to main**: Always use feature branches + +### Environment Variables +```bash +# Application +NODE_ENV=development +PORT=9000 +APP_NAME=Tractatus + +# MongoDB +MONGODB_URI=mongodb://localhost:27017/tractatus_dev +MONGODB_PORT=27017 + +# JWT +JWT_SECRET= +JWT_EXPIRY=7d + +# Claude API (Phase 2+) +CLAUDE_API_KEY= +CLAUDE_MODEL=claude-sonnet-4-5 + +# Admin +ADMIN_EMAIL=john.stroh.nz@pm.me +``` + +--- + +## Directory Structure + +``` +/home/theflow/projects/tractatus/ +├── .claude/ # Claude Code project config +├── .git/ # Git repository +├── docs/ # Source markdown documents +│ ├── markdown/ # Raw markdown files (migration source) +│ └── governance/ # TRA-VAL-*, TRA-GOV-* documents +├── public/ # Frontend assets +│ ├── css/ +│ │ └── tailwind.css +│ ├── js/ +│ │ ├── components/ # Reusable UI components +│ │ ├── demos/ # Interactive demonstrations +│ │ └── utils/ +│ ├── images/ +│ └── downloads/ # Generated PDFs +├── src/ # Backend code +│ ├── server.js # Express app entry point +│ ├── routes/ +│ │ ├── docs.routes.js +│ │ ├── blog.routes.js +│ │ ├── media.routes.js +│ │ ├── cases.routes.js +│ │ ├── resources.routes.js +│ │ ├── admin.routes.js +│ │ └── demo.routes.js +│ ├── controllers/ +│ ├── models/ +│ │ ├── Document.model.js +│ │ ├── BlogPost.model.js +│ │ ├── MediaInquiry.model.js +│ │ ├── CaseSubmission.model.js +│ │ ├── ModerationQueue.model.js +│ │ └── User.model.js +│ ├── middleware/ +│ │ ├── auth.middleware.js +│ │ ├── validation.middleware.js +│ │ └── tractatus/ # Framework enforcement +│ │ ├── classifier.middleware.js +│ │ ├── validator.middleware.js +│ │ └── boundary.middleware.js +│ ├── services/ +│ │ ├── ClaudeAPI.service.js +│ │ ├── InstructionClassifier.service.js +│ │ ├── CrossReferenceValidator.service.js +│ │ ├── BoundaryEnforcer.service.js +│ │ ├── ContextPressureMonitor.service.js +│ │ ├── MetacognitiveVerifier.service.js +│ │ ├── BlogCuration.service.js +│ │ ├── MediaTriage.service.js +│ │ ├── DocumentProcessor.service.js +│ │ └── ModerationQueue.service.js +│ ├── utils/ +│ │ ├── db.util.js +│ │ ├── jwt.util.js +│ │ ├── markdown.util.js +│ │ └── logger.util.js +│ └── config/ +│ ├── database.config.js +│ └── app.config.js +├── scripts/ # Setup & migration +│ ├── init-db.js # Create collections, indexes +│ ├── migrate-documents.js # Import markdown content +│ ├── generate-pdfs.js # PDF export +│ ├── seed-admin.js # Create admin user +│ └── start-dev.sh # Development startup +├── tests/ +│ ├── unit/ +│ ├── integration/ +│ └── security/ +├── data/ # MongoDB data directory +│ └── mongodb/ +├── logs/ # Application & MongoDB logs +│ ├── app.log +│ └── mongodb.log +├── .env.example # Template environment variables +├── .gitignore +├── package.json +├── package-lock.json +├── README.md +├── CLAUDE.md # This file +└── LICENSE +``` + +--- + +## Phase 1 Deliverables (3-4 Months) + +**Must-Have for Complete Prototype:** + +1. ✅ **Infrastructure** + - MongoDB instance (port 27017) + - Express application (port 9000) + - Systemd services + - Directory structure + +2. **Core Features** + - Document migration pipeline + - Three audience paths (Researcher/Implementer/Advocate) + - Documentation viewer with search + - About/values pages (Te Tiriti acknowledgment) + +3. **Tractatus Governance Services** + - InstructionPersistenceClassifier + - CrossReferenceValidator + - BoundaryEnforcer + - ContextPressureMonitor + - MetacognitiveVerifier + +4. **AI-Powered Features** (with human oversight) + - Blog curation system + - Media inquiry triage + - Case study submission portal + - Resource directory curation + +5. **Interactive Demonstrations** + - Instruction classification demo + - 27027 incident visualizer + - Boundary enforcement simulator + +6. **Human Oversight** + - Moderation queue dashboard + - Admin authentication + - Approval workflows + +7. **Quality Assurance** + - Comprehensive testing suite + - Security audit + - Performance optimization + - Accessibility compliance (WCAG) + +**Not in Phase 1:** +- Production deployment (OVHCloud) +- Domain configuration (mysy.digital) +- ProtonBridge email integration +- Koha donations (Phase 3) +- Public launch + +--- + +## Success Criteria + +**Technical Excellence:** +- Clean, maintainable code +- 80%+ test coverage +- <2s page load times +- WCAG AA accessibility +- Zero security vulnerabilities +- Complete API documentation + +**Framework Demonstration:** +- All AI actions governed by Tractatus +- Human oversight for values-sensitive content +- Boundary enforcement working +- Classification system accurate +- Moderation queue functional + +**Content Quality:** +- All documents migrated correctly +- Three audience paths distinct and clear +- Interactive demos working +- Blog system ready for Phase 2 +- No placeholder/fake data + +--- + +## Human Approval Required For: + +**All Major Decisions:** +- Architectural changes +- Database schema modifications +- Security implementations +- Third-party integrations +- Cost-incurring services + +**Content & Values:** +- Governance document adaptations (TRA-VAL-*, TRA-GOV-*) +- Te Tiriti acknowledgment wording +- About/mission pages +- Editorial guidelines +- Any values-sensitive content + +**Phase Transitions:** +- Completion of Phase 1 prototype +- Decision to proceed to production deployment +- Budget approval for Claude API (Phase 2) +- Launch timing and strategy + +--- + +## Links & References + +**Source Documents:** +- `/home/theflow/projects/tractatus/Tractatus-Website-Complete-Specification-v2.0.md` +- `/home/theflow/projects/tractatus/ClaudeWeb conversation transcription.md` +- `/home/theflow/projects/sydigital/stochastic/innovation-exploration/STO-INN-0010-tractatus-llm-architecture-safety-framework-i1.md` +- `/home/theflow/projects/sydigital/stochastic/innovation-exploration/anthropic-submission/technical-proposal.md` +- `/home/theflow/projects/sydigital/stochastic/innovation-exploration/anthropic-submission/appendix-a-code-examples.md` + +**Governance References:** +- `/home/theflow/projects/sydigital/strategic/values-principles/STR-VAL-0001-core-values-principles-v1-0.md` +- `/home/theflow/projects/sydigital/strategic/governance/STR-GOV-0001-strategic-review-protocol-v1-0.md` +- `/home/theflow/projects/sydigital/strategic/governance/STR-GOV-0002-values-alignment-framework-v1-0.md` + +**Framework Documentation:** +- `/home/theflow/projects/sydigital/strategic/frameworks/STR-FRM-0001-agentic-workflow-framework-v1-0.md` +- `/home/theflow/projects/sydigital/stochastic/innovation-exploration/STO-INN-0002-agentic-organizational-structure-whitepaper-i2.md` + +--- + +## Session Reminders + +**Always:** +- Verify you're in `/home/theflow/projects/tractatus` context +- Check MongoDB port 27017, application port 9000 +- No shortcuts, no fake data, world-class quality +- Human approval for major decisions +- Update todo list as tasks progress + +**Never:** +- Mix tractatus code with family-history or sydigital +- Make values decisions without human approval +- Deploy to production during Phase 1 +- Rush implementation to meet arbitrary deadlines +- Use placeholder/lorem ipsum content + +--- + +**Last Updated:** 2025-10-06 +**Next Review:** After Phase 1 completion diff --git a/ClaudeWeb conversation transcription.md b/ClaudeWeb conversation transcription.md new file mode 100644 index 00000000..46f4413c --- /dev/null +++ b/ClaudeWeb conversation transcription.md @@ -0,0 +1,2015 @@ +Tractatus-Based LLM Safety Framework Website - Complete Technical Specification +Project: mysy.digital - Tractatus AI Safety Framework Website +Platform: Node.js/Express + MongoDB (leveraging family-history stack) +Hosting: OVHCloud +Repository: GitHub (primary) + Codeberg/Gitea (mirrors) +Target Audiences: Academic/Research, Industry/Enterprise, Public Advocacy +Timeline: 4-phase rollout over 18 months + +Executive Summary +Build a comprehensive website for the Tractatus-Based LLM Safety Framework that serves three distinct audiences through differentiated landing paths while maintaining a unified knowledge base. The site will demonstrate the framework's principles by implementing them in its own architecture (dogfooding), use Claude-powered curation with explicit human oversight, and position Aotearoa/New Zealand's leadership in incorporating indigenous perspectives on digital sovereignty within a global context. + +1. Technical Architecture +1.1 Core Technology Stack +Backend (leveraging existing family-history stack): +javascript// Node.js/Express foundation +- Express 4.x for routing and middleware +- MongoDB for content, user data, and framework documentation +- GridFS for file storage (PDFs, presentations, code examples) +- JWT authentication for user accounts and admin access +- WebSocket for real-time updates and notifications + +// Key services to adapt from family-history: +- TenantFileService → DocumentService (multi-document management) +- User authentication system +- Multi-language support infrastructure (i18n.js) +- Session management +Frontend: +javascript// Progressive enhancement approach +- Vanilla JavaScript (no framework dependency for core features) +- Optional React components for interactive demos +- Tailwind CSS for styling consistency +- Mobile-first responsive design +- ARIA compliance for accessibility +Database Collections (MongoDB): +javascriptdb.collection('documents') // Technical papers, case studies, appendices +db.collection('blog_posts') // AI-curated blog with human oversight +db.collection('media_inquiries') // Press/media contact submissions +db.collection('case_submissions')// Community case study submissions +db.collection('resources') // External links, aligned projects +db.collection('koha_donations') // Donation tracking (Phase 3+) +db.collection('users') // User accounts +db.collection('moderation_queue')// Human oversight queue for AI actions +db.collection('citations') // Academic citation tracking +db.collection('translations') // Multi-language content +1.2 Tractatus Framework Implementation (Dogfooding) +Architecture Demonstration: +javascript// All AI actions subject to Tractatus validation +class TractusWebsiteManager { + constructor() { + this.instructionClassifier = new InstructionPersistenceClassifier(); + this.boundaryEnforcer = new HumanJudgmentBoundaryEnforcer(); + this.validator = new CrossReferenceValidator(); + } + + // Example: AI blog post curation + async curateContent(content, source) { + // Classify by quadrant + const classification = this.instructionClassifier.classify({ + action: 'publish_blog_post', + content: content, + quadrant: 'OPERATIONAL' // Blog guidelines + }); + + // Validate against strategic values + const validation = await this.validator.validate({ + action: 'publish', + content: content, + strategic_values: ['sovereignty', 'transparency', 'indigenous_respect'] + }); + + // Enforce boundary: human approval for values-sensitive content + if (classification.requires_human_judgment) { + return this.boundaryEnforcer.escalate_to_human({ + item: content, + reason: 'Values-sensitive content requires strategic review', + quadrant: 'STRATEGIC' + }); + } + + return validation; + } +} +Quadrant Mapping for Website Functions: +FunctionQuadrantTime HorizonHuman Oversight RequiredMission/values statementsStrategicYearsYes - all changesBlog editorial guidelinesOperationalMonthsYes - quarterly reviewPublish approved blog postTacticalDaysNo - pre-approved by opsTechnical documentationSystemContinuousYes - technical reviewAI content suggestionsStochasticVariableYes - human approval + +2. Information Architecture +2.1 Three Audience Landing Paths +Homepage (mysy.digital): +┌─────────────────────────────────────────────────────┐ +│ TRACTATUS AI SAFETY FRAMEWORK │ +│ Structural Guarantees for Safe AI Systems │ +│ │ +│ [Choose Your Path] │ +│ │ +│ ┌──────────────┐ ┌──────────────┐ ┌─────────────┐│ +│ │ RESEARCHER │ │ IMPLEMENTER │ │ ADVOCATE ││ +│ │ │ │ │ │ ││ +│ │ Publications │ │ Integration │ │ Democratic ││ +│ │ Theory │ │ Code │ │ Oversight ││ +│ │ Peer Review │ │ Case Studies │ │ Public Good ││ +│ └──────────────┘ └──────────────┘ └─────────────┘│ +│ │ +│ Latest: [Blog Preview] | [News] | [Events] │ +└─────────────────────────────────────────────────────┘ +2.2 Researcher Path +URL: /research +Content Structure: +Research Hub +├── Publications +│ ├── Executive Brief (2-page PDF) +│ ├── Technical Proposal (complete) +│ ├── Appendices (A-E) +│ └── Peer-Reviewed Papers (as published) +│ +├── Theory & Foundations +│ ├── Tractatus Philosophical Framework +│ ├── Agentic Organizational Structure +│ ├── Time-Persistence Metadata +│ └── Organizational Theory Origins +│ +├── Research Collaboration +│ ├── Open Questions +│ ├── Validation Studies +│ ├── Academic Partnerships +│ └── Citation Guidelines +│ +└── Contribute + ├── Submit Related Research + ├── Peer Review Opportunities + └── Academic Community Forum +Key Features: + +BibTeX citation generator +arXiv preprint links +Research collaboration inquiry form +Academic mailing list signup + +2.3 Implementer Path +URL: /implement +Content Structure: +Implementation Hub +├── Getting Started +│ ├── Quick Start Guide +│ ├── Integration Patterns +│ ├── System Requirements +│ └── Architecture Overview +│ +├── Code & Documentation +│ ├── GitHub Repository Links +│ ├── Code Examples (Appendix A) +│ ├── API Documentation +│ └── Implementation Roadmap (Appendix C) +│ +├── Case Studies +│ ├── Real-World Failures Prevented +│ ├── The 27027 Incident (detailed analysis) +│ ├── Industry Case Studies (Appendix B) +│ └── Success Metrics +│ +├── Interactive Demos +│ ├── Instruction Classification Demo +│ ├── Cross-Reference Validation Visualizer +│ ├── Boundary Enforcement Simulator +│ └── Context Pressure Monitor +│ +└── Enterprise Support + ├── Pilot Program Application + ├── Integration Consulting + ├── Training Workshops + └── Technical Support +Key Features: + +Live code playground +Downloadable implementation kits +Integration assessment tool +Enterprise inquiry form + +2.4 Advocate Path +URL: /advocacy +Content Structure: +Advocacy Hub +├── Why This Matters +│ ├── AI Safety for Everyone +│ ├── Democratic AI Governance +│ ├── Digital Sovereignty Principles +│ └── Indigenous Perspectives (Te Tiriti context) +│ +├── Public Resources +│ ├── Plain-Language Explainers +│ ├── Infographics & Visualizations +│ ├── Video Explanations +│ └── FAQ for Non-Technical Audiences +│ +├── Media Centre +│ ├── Press Releases +│ ├── Media Kit (logos, fact sheets) +│ ├── Spokesperson Bios +│ ├── Press Inquiry Form (AI-moderated) +│ └── Recent Coverage +│ +├── Take Action +│ ├── Educational Resources +│ ├── Community Events +│ ├── Policy Recommendations +│ └── Join the Movement +│ +└── Values & Governance + ├── Our Mission + ├── Te Tiriti Alignment + ├── Aotearoa/NZ Leadership + └── Transparent Governance Model +Key Features: + +Shareable social media content +Email newsletter signup +Community forum access +Event calendar + +2.5 Unified Components (All Paths) +Blog (/blog): + +AI-curated content with human editorial oversight +Technical updates, research insights, advocacy stories +Guest posts from aligned organizations +Multi-language support (starting with English, Te Reo Māori) + +Documentation Library (/docs): + +Complete framework documentation +Searchable, cross-referenced +Version history +Download options (PDF, EPUB, HTML) + +About (/about): + +Team & Contributors +History & Development +Governance Model +Contact Information + +Resources (/resources): + +Aligned Projects Directory +External Research Links +Educational Materials +Tools & Services + + +3. Content Migration & Integration +3.1 Existing Documents to Integrate +From Project Knowledge Base: + +README.md → /docs/overview + +Package contents summary +Reading order recommendations +Quick start for reviewers + + +executive-brief.md → /docs/executive-brief + PDF download + +2-page summary for decision-makers +The 27027 case study +Three-layer architecture overview + + +technical-proposal.md → /docs/technical-proposal + PDF + +Complete technical specification +All 7 sections with navigation +Inline code examples +Cross-references to appendices + + +appendix-a-code-examples.md → /docs/code-examples + +Python implementation examples +Interactive code playground integration +Downloadable code packages + + +appendix-b-case-studies.md → /case-studies + +Real-world failure analysis +Success stories +Industry applications + + +appendix-c-implementation-roadmap.md → /implement/roadmap + +Phased deployment plan +Success metrics +Timeline visualization + + +appendix-d-research-review.md → /research/literature-review + +Scholarly context +Related research +Publication recommendations + + +cover-letter.md → /about/submission-history + +Anthropic submission context +Development timeline + + +SYS-DOC-5000-sydigital-framework-tractatus-v1-0-0.md → /docs/tractatus-framework + +Philosophical foundation +Section 12: Limits of the Framework +Complete Tractatus reference + + +STO-INN-0002-agentic-organizational-structure-whitepaper-i2.md → /docs/agentic-structure + +Organizational theory foundations +Quadrant system detailed specification +Cross-quadrant coordination + + +Persistent Agentic Process Architecture.md → /docs/persistent-architecture + +Service worker roles +Information flow patterns +Role stability principles + + + +3.2 Content Processing Pipeline +javascript// Document ingestion system +class DocumentProcessor { + async processMarkdown(filePath, metadata) { + // 1. Parse markdown with front matter + const doc = await parseMarkdownWithMetadata(filePath); + + // 2. Classify by quadrant + const quadrant = this.classifyDocument(doc.metadata); + + // 3. Extract cross-references + const references = this.extractReferences(doc.content); + + // 4. Generate navigation + const toc = this.generateTableOfContents(doc.content); + + // 5. Convert to HTML with syntax highlighting + const html = await markdownToHTML(doc.content); + + // 6. Store in MongoDB with metadata + await db.collection('documents').insertOne({ + title: doc.metadata.title, + quadrant: quadrant, + content: html, + raw_markdown: doc.content, + references: references, + toc: toc, + created_at: new Date(), + updated_at: new Date(), + version: '1.0.0' + }); + + // 7. Update search index + await this.updateSearchIndex(doc); + } +} + +4. AI-Powered Features (Tractatus-Governed) +4.1 Blog Curation System +Architecture: +javascriptclass BlogCurationEngine { + constructor() { + this.claudeAPI = new ClaudeAPI('claude-sonnet-4-5'); + this.moderationQueue = new ModerationQueue(); + this.boundaryEnforcer = new TractatusBoundaryEnforcer(); + } + + async suggestBlogPost(topic, sources) { + // AI generates draft + const draft = await this.claudeAPI.generateBlogPost({ + topic: topic, + sources: sources, + guidelines: await this.loadEditorialGuidelines(), + strategic_values: await this.loadStrategicValues() + }); + + // Classify action + const classification = { + quadrant: 'OPERATIONAL', // Blog is operational + persistence: 'MEDIUM', + requires_human: this.checkValuesContent(draft) + }; + + // Queue for human review + await this.moderationQueue.add({ + type: 'blog_post_suggestion', + draft: draft, + classification: classification, + created_at: new Date(), + status: 'pending_human_review' + }); + + return { status: 'queued_for_review', id: draft.id }; + } + + checkValuesContent(draft) { + // Check for values-sensitive topics requiring strategic review + const sensitiveTopics = [ + 'indigenous_rights', + 'sovereignty_principles', + 'ethical_boundaries', + 'democratic_governance' + ]; + + return sensitiveTopics.some(topic => + draft.content.toLowerCase().includes(topic) + ); + } +} +Human Oversight Dashboard: +Admin Dashboard → Moderation Queue +├── Pending Blog Posts +│ ├── [Draft Title] +│ │ └── [Approve] [Edit] [Reject] [Request Revision] +│ ├── AI Reasoning: [Display Claude's analysis] +│ ├── Values Check: [Flagged items] +│ └── Suggested Improvements: [Claude's suggestions] +│ +├── Media Inquiry Triage +│ ├── [Inquiry Subject] +│ │ └── [Respond] [Forward to Team] [Archive] +│ ├── AI Summary: [Key points] +│ └── Suggested Response: [Draft with human editing] +│ +└── Case Study Submissions + ├── [Submission Title] + │ └── [Review] [Publish] [Request More Info] + └── AI Analysis: [Relevance, completeness] +4.2 Press/Media Inquiry System +AI-Moderated Intake: +javascriptclass MediaInquiryHandler { + async processInquiry(submission) { + // AI analyzes inquiry + const analysis = await this.claudeAPI.analyzeMediaInquiry({ + subject: submission.subject, + message: submission.message, + outlet: submission.media_outlet, + deadline: submission.deadline + }); + + // Classify urgency and sensitivity + const classification = { + urgency: analysis.urgency, // high/medium/low + topic_sensitivity: analysis.sensitivity, + requires_strategic_review: analysis.involves_values, + suggested_response_time: analysis.response_window + }; + + // Route based on classification + if (classification.requires_strategic_review) { + // Escalate to strategic quadrant (human decision-makers) + await this.escalateToStrategic(submission, analysis); + } else { + // Queue for operational review + await this.queueForReview(submission, analysis); + } + + // Auto-respond with acknowledgement + await this.sendAutoResponse(submission, classification); + } +} +4.3 Resource Curation +AI-Assisted Discovery: +javascriptclass ResourceCurator { + async suggestResource(url) { + // Fetch and analyze resource + const analysis = await this.claudeAPI.analyzeExternalResource({ + url: url, + alignment_criteria: await this.loadAlignmentCriteria(), + quality_standards: await this.loadQualityStandards() + }); + + // Check alignment with strategic values + const alignmentScore = this.calculateAlignment(analysis); + + if (alignmentScore > 0.8) { + // High alignment - queue for quick review + return await this.queueForReview(url, analysis, 'fast_track'); + } else if (alignmentScore > 0.5) { + // Moderate alignment - standard review + return await this.queueForReview(url, analysis, 'standard'); + } else { + // Low alignment - detailed human review required + return await this.queueForReview(url, analysis, 'detailed'); + } + } +} + +5. Te Tiriti & Indigenous Perspective Integration +5.1 Strategic Values Statement +Location: /about/values (also footer on all pages) +Content (example - requires your approval): +markdown## Our Values & Te Tiriti Commitment + +The Tractatus AI Safety Framework is developed in Aotearoa New Zealand +with deep respect for Te Tiriti o Waitangi and the leadership of tangata +whenua in digital sovereignty. + +**Digital Sovereignty & Indigenous Rights** +We recognize that indigenous peoples worldwide have been at the forefront +of sovereignty struggles for centuries. The principles of data sovereignty, +self-determination, and cultural protection central to our framework draw +inspiration from indigenous leadership in asserting rights over digital +resources and governance systems. + +**Aotearoa's Contribution** +Based in Aotearoa New Zealand, this work is informed by Te Tiriti o Waitangi's +principles of partnership, protection, and participation. We acknowledge the +pioneering work of Māori scholars and communities in establishing frameworks +for data sovereignty (including the CARE Principles) that inform our approach +to AI governance. + +**Global Application** +While rooted in Aotearoa context, this framework is designed for global +application, bringing indigenous-informed sovereignty principles to AI +safety challenges worldwide. +Implementation: + +Subtle footer acknowledgement on every page +Detailed page in About section +No dominant visual presence, but clear strategic commitment +Links to relevant indigenous AI/data sovereignty resources + +5.2 Resource Directory Inclusion +Aligned Indigenous Projects (in resources directory): + +Māori Data Sovereignty Network +Te Mana Raraunga (Māori Data Sovereignty Network) +CARE Principles for Indigenous Data Governance +Indigenous Protocol and AI Working Group +Other global indigenous digital rights organizations + + +6. Interactive Demonstrations +6.1 Instruction Classification Demo +URL: /demo/classification +Interactive Tool: +javascript// User inputs instruction text +// System shows real-time classification + +class ClassificationDemo { + render() { + return ` +
+

Try Instruction Classification

+ + + + + +
+

Classification Results:

+
[Quadrant]
+
[Persistence]
+
[Verification Required]
+
[Why this classification]
+
+
+ `; + } +} + +// Example classifications shown: +// "Always prioritize privacy" → STRATEGIC, HIGH, ANNUAL_REVIEW +// "For this project, use React" → OPERATIONAL, MEDIUM, PROJECT_SCOPE +// "Check database port 27027" → TACTICAL, HIGH, IMMEDIATE +// "Fix syntax error on line 42" → SYSTEM, LOW, IMMEDIATE +6.2 The 27027 Incident Visualizer +URL: /case-studies/27027-incident +Interactive Timeline: +javascript// Visual reconstruction of the failure +class IncidentVisualizer { + render() { + return ` +
+
+

User Instruction (Explicit)

+ "Check port 27027 for family_history database" + +
+ +
+

Context Pressure Builds

+
107k tokens of conversation
+ ⚠️ Pattern matching confidence increasing +
+ +
+

Claude's Action (Incorrect)

+ mongosh mongodb://localhost:27017/family_history + ❌ Used default port 27017, not 27027 +
+ +
+

With Tractatus Framework

+
+ ✓ Extract parameter: port=27017 + ✓ Cross-reference recent instructions + ⚠️ CONFLICT: User said 27027, action uses 27017 + 🛑 ACTION BLOCKED - Request clarification +
+
+
+ `; + } +} +6.3 Boundary Enforcement Simulator +URL: /demo/boundaries +Interactive Scenarios: +javascript// Present users with decision scenarios +// Show which require human judgment + +const scenarios = [ + { + id: 1, + scenario: "Should we prioritize speed or privacy in our AI deployment?", + correct_answer: "HUMAN_REQUIRED", + quadrant: "STRATEGIC", + tractatus_rule: "12.1 - Values cannot be automated, only verified", + explanation: "Values decisions must always involve human judgment" + }, + { + id: 2, + scenario: "Which Python library is best for data validation?", + correct_answer: "AI_CAPABLE", + quadrant: "SYSTEM", + tractatus_rule: "System decisions can be delegated with verification", + explanation: "Technical implementation choices can be AI-assisted" + }, + // ... more scenarios +]; + +7. Phased Implementation Roadmap +Phase 1: Foundation & Launch (Months 1-3) +Milestone: Public launch with core documentation and three audience paths +Deliverables: + + Platform setup on OVHCloud + Domain configuration (mysy.digital) + Database schema implementation + Document migration pipeline + Homepage with three paths + Complete documentation library + Basic blog system (human-curated only) + Media inquiry form + About/Contact pages + Te Tiriti values statement + GitHub repository setup (public) + Privacy policy, terms of service + Analytics implementation (privacy-preserving) + +Technical Tasks: +bash# Infrastructure setup +npm init -y +npm install express mongodb dotenv jsonwebtoken bcrypt +npm install marked highlight.js # Markdown processing +npm install i18next # Multi-language support + +# Database initialization +node scripts/init-db.js +node scripts/migrate-documents.js + +# First deployment +npm run build +npm run deploy +Success Metrics: + +Site accessible at mysy.digital +All core documents migrated and formatted +Three landing paths functional +Search working across documentation +Mobile-responsive +<2s page load time + +Phase 2: Engagement & Demonstration (Months 4-8) +Milestone: Interactive features and community engagement +Deliverables: + + AI-curated blog (with human oversight dashboard) + Interactive classification demo + 27027 incident visualizer + Boundary enforcement simulator + Case study submission portal + Resources directory + Aligned projects catalog + Newsletter system + Event calendar + Community forum (initial) + Codeberg/Gitea mirrors established + +AI Features (with Tractatus governance): + +Blog post suggestion engine +Media inquiry triage +Resource recommendation system +FAQ auto-responses (human-reviewed) + +Success Metrics: + +1,000+ unique visitors/month +50+ blog subscribers +10+ case study submissions reviewed +5+ media inquiries handled +20+ resources cataloged +Demo tools used 100+ times/month + +Phase 3: Technical Expansion & Koha (Months 9-14) +Milestone: Advanced features and community funding +Deliverables: + + Stripe Koha integration + +Monthly supporter tiers ($5, $15, $50/month) +One-time donations +Transparency dashboard (donations received/used) + + + Code playground (live examples) + API documentation + Te Reo Māori translations (priority pages) + Enhanced search (full-text, filtering) + User accounts (optional, for saved preferences) + Notification system + Advanced analytics + Performance optimization + +Koha Implementation: +javascript// Stripe integration with transparency +class KohaManager { + async processDonation(amount, frequency, donor) { + // Process via Stripe + const payment = await stripe.paymentIntents.create({ + amount: amount, + currency: 'nzd', + metadata: { + purpose: 'tractatus_framework_support', + frequency: frequency // 'monthly' or 'one_time' + } + }); + + // Record with transparency + await db.collection('koha_donations').insertOne({ + amount: amount, + frequency: frequency, + donor_name: donor.name || 'Anonymous', + donor_email: donor.email, // private + timestamp: new Date(), + public_acknowledgement: donor.public_ack || false + }); + + // Update transparency dashboard + await this.updateTransparencyMetrics(); + } + + async getPublicMetrics() { + // Public transparency data + return { + total_received: await this.getTotalDonations(), + monthly_supporters: await this.getMonthlyCount(), + allocation: { + hosting: 0.30, + development: 0.40, + research: 0.20, + community: 0.10 + }, + recent_donors: await this.getPublicAcknowledgements() + }; + } +} +Success Metrics: + +20+ monthly supporters +$500+ monthly recurring revenue +50+ one-time donations +Code playground: 500+ executions/month +Multi-language: 10% of traffic uses translations + +Phase 4: Scaling & Advocacy (Months 15-18) +Milestone: Full ecosystem with global reach +Deliverables: + + Campaign/events module + Webinar hosting integration + Advanced forum features + Federation/interoperability protocols + Mobile app (PWA) + Advanced AI features: + +Personalized content recommendations +Intelligent FAQ system +Research paper discovery + + + Enterprise portal + Academic partnership tools + International expansion (EU languages priority) + +Success Metrics: + +10,000+ unique visitors/month +100+ monthly supporters +5+ academic partnerships +3+ enterprise pilot programs +10+ languages supported +50+ aligned projects in directory + + +8. Detailed Technical Specifications +8.1 Database Schema +javascript// documents collection +{ + _id: ObjectId, + title: String, + slug: String, // URL-friendly + quadrant: String, // STR/OPS/TAC/SYS/STO + persistence: String, // HIGH/MEDIUM/LOW/VARIABLE + content_html: String, // Rendered HTML + content_markdown: String, // Raw markdown + toc: Array, // Table of contents + metadata: { + author: String, + date_created: Date, + date_updated: Date, + version: String, + document_code: String, // e.g., SYS-DOC-5000 + related_documents: [ObjectId], + tags: [String] + }, + translations: { + mi: ObjectId, // Te Reo Māori + de: ObjectId, // German + fr: ObjectId, // French + // ... other languages + }, + search_index: String, // Full-text search + download_formats: { + pdf: String, // GridFS file ID + epub: String, + docx: String + } +} + +// blog_posts collection +{ + _id: ObjectId, + title: String, + slug: String, + author: { + type: String, // 'human' or 'ai_curated' + name: String, + claude_version: String // if AI + }, + content: String, + excerpt: String, + featured_image: String, + status: String, // draft/pending/published/archived + moderation: { + ai_analysis: Object, // Claude's assessment + human_reviewer: ObjectId, + review_notes: String, + approved_at: Date + }, + tractatus_classification: { + quadrant: String, + values_sensitive: Boolean, + requires_strategic_review: Boolean + }, + published_at: Date, + tags: [String], + view_count: Number, + engagement: { + shares: Number, + comments: Number + } +} + +// media_inquiries collection +{ + _id: ObjectId, + contact: { + name: String, + email: String, + outlet: String, + phone: String + }, + inquiry: { + subject: String, + message: String, + deadline: Date, + topic_areas: [String] + }, + ai_triage: { + urgency: String, // high/medium/low + topic_sensitivity: String, + suggested_response_time: Number, // hours + involves_values: Boolean, + claude_summary: String, + suggested_talking_points: [String] + }, + status: String, // new/triaged/responded/closed + assigned_to: ObjectId, + response: { + sent_at: Date, + content: String, + responder: ObjectId + }, + created_at: Date +} + +// case_submissions collection +{ + _id: ObjectId, + submitter: { + name: String, + email: String, + organization: String, + public: Boolean // Can we publish their name? + }, + case_study: { + title: String, + description: String, + failure_mode: String, // What went wrong + tractatus_applicability: String, // How framework would help + evidence: [String], // Links, screenshots + attachments: [ObjectId] // GridFS file IDs + }, + ai_review: { + relevance_score: Number, // 0-1 + completeness_score: Number, + recommended_category: String, + suggested_improvements: [String], + claude_analysis: String + }, + moderation: { + status: String, // pending/approved/rejected/needs_info + reviewer: ObjectId, + review_notes: String, + reviewed_at: Date + }, + published_case_id: ObjectId, // If approved and published + submitted_at: Date +} + +// koha_donations collection (Phase 3) +{ + _id: ObjectId, + stripe_payment_id: String, + amount: Number, // in cents + currency: String, // 'nzd' + frequency: String, // 'one_time' or 'monthly' + donor: { + email: String, // private + name: String, // optional + public_acknowledgement: Boolean, + anonymous: Boolean + }, + status: String, // succeeded/pending/failed + timestamp: Date, + allocation_note: String, // What funds support + public_thank_you_sent: Boolean +} + +// moderation_queue collection +{ + _id: ObjectId, + item_type: String, // blog_post/media_inquiry/case_study/resource + item_id: ObjectId, + quadrant: String, + ai_action: { + type: String, // suggestion/triage/analysis + confidence: Number, // 0-1 + reasoning: String, + claude_version: String + }, + human_required_reason: String, // Why human oversight needed + priority: String, // high/medium/low + assigned_to: ObjectId, + status: String, // pending/reviewed/approved/rejected + created_at: Date, + reviewed_at: Date, + review_decision: { + action: String, // approve/reject/modify/escalate + notes: String, + reviewer: ObjectId + } +} +8.2 API Routes +javascript// Core documentation routes +GET /api/docs // List all documents +GET /api/docs/:slug // Get specific document +GET /api/docs/:slug/pdf // Download PDF +GET /api/docs/search?q=... // Search documents + +// Blog routes +GET /api/blog // List published posts +GET /api/blog/:slug // Get specific post +POST /api/blog/suggest // AI suggests blog post (admin) +GET /api/blog/moderation // Moderation queue (admin) +POST /api/blog/approve/:id // Approve post (admin) + +// Media inquiry routes +POST /api/media/inquiry // Submit inquiry (public) +GET /api/media/queue // Triage queue (admin) +POST /api/media/respond/:id // Send response (admin) + +// Case study routes +POST /api/cases/submit // Submit case study (public) +GET /api/cases // List published cases +GET /api/cases/:id // Get specific case +GET /api/cases/moderation // Review queue (admin) + +// Resources routes +GET /api/resources // List all resources +GET /api/resources/aligned // Aligned projects +POST /api/resources/suggest // Suggest resource (logged in) + +// Koha routes (Phase 3) +POST /api/koha/donate // Process donation +GET /api/koha/transparency // Public metrics +GET /api/koha/supporters // Public acknowledgements + +// Interactive demo routes +POST /api/demo/classify // Classification demo +POST /api/demo/validate // Validation demo +POST /api/demo/boundary // Boundary check demo + +// Admin/moderation routes (auth required) +GET /api/admin/dashboard // Overview stats +GET /api/admin/moderation/pending // All pending items +POST /api/admin/moderation/action // Take action on item +GET /api/admin/analytics // Detailed analytics +8.3 Frontend Components +javascript// Reusable components (vanilla JS) + +// Document viewer with TOC +class DocumentViewer { + constructor(documentSlug) { + this.slug = documentSlug; + this.toc = []; + } + + async render() { + const doc = await fetch(`/api/docs/${this.slug}`).then(r => r.json()); + + return ` +
+ +
+

${doc.title}

+ +
+ ${doc.content_html} +
+
+ Download PDF + +
+
+
+ `; + } +} + +// Three-path selector (homepage) +class AudiencePathSelector { + render() { + return ` +
+
+
🔬
+

For Researchers

+

Publications, theory, peer review, and academic collaboration

+
    +
  • Complete technical documentation
  • +
  • Peer-reviewed papers
  • +
  • Research collaboration opportunities
  • +
  • Citation resources
  • +
+ Explore Research → +
+ +
+
⚙️
+

For Implementers

+

Code, integration guides, case studies, and enterprise support

+
    +
  • Production-ready code examples
  • +
  • Integration patterns
  • +
  • Real-world case studies
  • +
  • Enterprise pilot programs
  • +
+ Start Building → +
+ +
+
📢
+

For Advocates

+

Democratic AI governance, public resources, and community action

+
    +
  • Plain-language explainers
  • +
  • Media resources
  • +
  • Policy recommendations
  • +
  • Community engagement
  • +
+ Join the Movement → +
+
+ `; + } +} + +// Moderation dashboard (admin) +class ModerationDashboard { + async render() { + const pending = await fetch('/api/admin/moderation/pending') + .then(r => r.json()); + + return ` +
+

Human Oversight Queue

+

Items requiring human judgment per Tractatus framework

+ + ${pending.map(item => ` +
+
+ ${item.item_type} + ${item.quadrant} + ${item.priority} +
+ +
+

AI Analysis (Claude ${item.ai_action.claude_version})

+

Confidence: ${item.ai_action.confidence * 100}%

+

${item.ai_action.reasoning}

+
+ +
+ Why Human Oversight Required: +

${item.human_required_reason}

+
+ +
+ +
+ +
+ + + + +
+
+ `).join('')} +
+ `; + } +} + +9. Performance & Optimization +9.1 Performance Targets +Page Load Times: + +Homepage: <1.5s +Documentation pages: <2s +Interactive demos: <3s +Search results: <500ms + +Optimization Strategies: +javascript// 1. Document caching +const documentCache = new NodeCache({ stdTTL: 3600 }); // 1 hour + +app.get('/api/docs/:slug', async (req, res) => { + const cacheKey = `doc_${req.params.slug}`; + let doc = documentCache.get(cacheKey); + + if (!doc) { + doc = await db.collection('documents').findOne({ slug: req.params.slug }); + documentCache.set(cacheKey, doc); + } + + res.json(doc); +}); + +// 2. CDN for static assets +// Use OVHCloud CDN for: +// - Images, logos +// - CSS/JS bundles +// - PDF downloads + +// 3. Database indexing +db.collection('documents').createIndex({ slug: 1 }); +db.collection('documents').createIndex({ quadrant: 1 }); +db.collection('documents').createIndex({ search_index: 'text' }); +db.collection('blog_posts').createIndex({ published_at: -1 }); +db.collection('blog_posts').createIndex({ status: 1 }); + +// 4. Lazy loading for demos +// Load interactive components only when needed + +// 5. Progressive image loading +// Use responsive images with srcset +9.2 Monitoring & Analytics +Privacy-Preserving Analytics: +javascript// Use Plausible or similar privacy-first analytics +// No cookies, no personal data collection + +// Track: +// - Page views by path +// - Audience path selection (researcher/implementer/advocate) +// - Document downloads +// - Demo usage +// - Search queries (anonymized) +// - Geographic distribution (country-level only) +// - Referral sources + +// Do NOT track: +// - Individual users +// - IP addresses beyond country +// - Browsing behavior across sessions +// - Personal information + +10. Security & Privacy +10.1 Security Measures +Authentication (for admin/moderation): +javascript// JWT-based auth +const jwt = require('jsonwebtoken'); + +// Admin routes protected +app.use('/api/admin/*', authenticateAdmin); + +async function authenticateAdmin(req, res, next) { + const token = req.headers.authorization?.split(' ')[1]; + + if (!token) { + return res.status(401).json({ error: 'No token provided' }); + } + + try { + const decoded = jwt.verify(token, process.env.JWT_SECRET); + req.admin = decoded; + next(); + } catch (error) { + res.status(401).json({ error: 'Invalid token' }); + } +} +Input Validation: +javascript// Sanitize all user inputs +const validator = require('validator'); + +app.post('/api/media/inquiry', async (req, res) => { + // Validate and sanitize + const inquiry = { + name: validator.escape(req.body.name), + email: validator.normalizeEmail(req.body.email), + subject: validator.escape(req.body.subject), + message: validator.escape(req.body.message) + }; + + // Validate email + if (!validator.isEmail(inquiry.email)) { + return res.status(400).json({ error: 'Invalid email' }); + } + + // Rate limiting (prevent spam) + // ... implementation +}); +Privacy Policy: +markdown# Privacy Policy + +## Data We Collect + +**Public Interactions**: +- Media inquiry submissions (name, email, outlet, message) +- Case study submissions (name, email, organization, case details) +- Blog comments (if implemented) +- Newsletter subscriptions (email only) + +**Analytics** (Privacy-Preserving): +- Page views (no personal identification) +- Geographic distribution (country-level only) +- No cookies, no cross-site tracking + +**Koha Donations** (Phase 3): +- Stripe payment information (processed securely by Stripe) +- Donor name and email (for receipts) +- Public acknowledgement (only if opted in) + +## Data We Do NOT Collect +- IP addresses (beyond country-level analytics) +- Browsing history +- Personal browsing behavior +- Third-party tracking data + +## Data Usage +- Media inquiries: Response and relationship management only +- Case studies: Publication (with consent) and research +- Donations: Transparency reporting (aggregated/anonymized) +- Analytics: Site improvement only + +## Data Retention +- Active inquiries: Until resolved + 1 year +- Published content: Indefinite (public record) +- Analytics: Aggregated only, no personal data stored +- Donation records: 7 years (legal requirement) + +## Your Rights +- Access your data +- Request deletion (except legal retention requirements) +- Opt out of communications +- Update information + +Contact: privacy@mysy.digital + +11. Development Workflow +11.1 Git Repository Structure +tractatus-website/ +├── .github/ +│ └── workflows/ +│ ├── deploy.yml # Auto-deploy to OVHCloud +│ └── test.yml # Run tests on PR +├── public/ +│ ├── css/ +│ ├── js/ +│ ├── images/ +│ └── downloads/ # PDF exports +├── src/ +│ ├── server.js # Express app +│ ├── routes/ +│ │ ├── docs.js +│ │ ├── blog.js +│ │ ├── media.js +│ │ ├── cases.js +│ │ ├── koha.js +│ │ └── admin.js +│ ├── controllers/ +│ ├── models/ +│ ├── middleware/ +│ │ ├── auth.js +│ │ ├── validation.js +│ │ └── tractatus.js # Framework enforcement +│ ├── services/ +│ │ ├── ClaudeAPI.js +│ │ ├── TractusValidator.js +│ │ ├── DocumentProcessor.js +│ │ └── StripeService.js +│ └── utils/ +├── scripts/ +│ ├── migrate-documents.js # Import from knowledge base +│ ├── generate-pdfs.js # PDF export +│ └── init-db.js # Database setup +├── docs/ +│ └── markdown/ # Source markdown files +├── tests/ +│ ├── unit/ +│ └── integration/ +├── .env.example +├── package.json +├── README.md +└── LICENSE +11.2 Development Process +Branch Strategy: +main # Production (OVHCloud) +├── develop # Development branch +│ ├── feature/* # New features +│ ├── fix/* # Bug fixes +│ └── content/* # Content updates +└── release/* # Release candidates +PR Requirements: + +Passes all tests +Code review by at least one maintainer +Tractatus framework compliance check +Documentation updated +No security vulnerabilities + +Deployment: +yaml# .github/workflows/deploy.yml +name: Deploy to OVHCloud + +on: + push: + branches: [ main ] + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Setup Node.js + uses: actions/setup-node@v2 + with: + node-version: '18' + + - name: Install dependencies + run: npm ci + + - name: Run tests + run: npm test + + - name: Build + run: npm run build + + - name: Deploy to OVHCloud + env: + SSH_KEY: ${{ secrets.OVHCLOUD_SSH_KEY }} + HOST: ${{ secrets.OVHCLOUD_HOST }} + run: | + # Deploy script + ./scripts/deploy.sh + +12. Success Metrics & KPIs +12.1 Phase-Specific Metrics +Phase 1 (Foundation): + +Site uptime: >99.5% +Page load time: <2s average +Documentation completeness: 100% of existing docs migrated +Mobile responsiveness: 100% of pages +Accessibility score: >90 (Lighthouse) + +Phase 2 (Engagement): + +Monthly unique visitors: >1,000 +Avg time on site: >3 minutes +Bounce rate: <60% +Blog subscribers: >50 +Demo tool usage: >100 interactions/month +Media inquiries: >5/month + +Phase 3 (Growth): + +Monthly visitors: >5,000 +Monthly supporters (Koha): >20 +Recurring revenue: >$500/month +Case study submissions: >10 reviewed +Resource directory: >30 aligned projects +Multi-language adoption: >10% non-English traffic + +Phase 4 (Scale): + +Monthly visitors: >10,000 +Enterprise inquiries: >5/month +Academic partnerships: >3 active +Monthly supporters: >100 +Community forum: >500 registered users +International reach: >20 countries + +12.2 Tractatus Framework Validation Metrics +Dogfooding Success: + +AI actions requiring human oversight: Track frequency +Escalations to Strategic quadrant: Monitor patterns +Boundary enforcement effectiveness: 100% of values decisions to humans +Cross-reference validation catches: Count prevented errors +Human override rate: % of AI suggestions modified by humans + +Framework Demonstration: + +Demo tool usage correlates with framework understanding +Case study submissions cite framework concepts +Media coverage references architectural safety approach + + +13. Content Strategy & Editorial Calendar +13.1 Blog Content Pillars +Pillar 1: Technical Deep Dives (Researcher audience) + +Frequency: 2x/month +Topics: Implementation details, research insights, theoretical advances +Length: 1500-2500 words +Examples: + +"Time-Persistence Metadata: A Formal Specification" +"Cross-Reference Validation: Implementation Patterns" +"Organizational Theory Foundations of Tractatus" + + + +Pillar 2: Implementation Stories (Implementer audience) + +Frequency: 2x/month +Topics: Case studies, integration guides, practical tips +Length: 1000-1500 words +Examples: + +"How We Prevented the 27027 Error Class" +"Integrating Tractatus with Existing LLM Pipelines" +"Metrics That Matter: Measuring Framework Effectiveness" + + + +Pillar 3: Advocacy & Impact (Advocate audience) + +Frequency: 2x/month +Topics: Policy implications, public education, community stories +Length: 800-1200 words +Examples: + +"Why AI Safety Needs Structural Guarantees" +"Democratic Governance for AI Systems" +"Digital Sovereignty: From Indigenous Leadership to Global AI" + + + +Pillar 4: News & Updates (All audiences) + +Frequency: Weekly +Topics: Project updates, partnerships, events +Length: 300-600 words +Examples: + +"Tractatus Framework v2.0 Released" +"New Academic Partnership Announced" +"Webinar Series: AI Safety Fundamentals" + + + +13.2 AI Curation Workflow +javascript// Weekly blog curation process +class WeeklyBlogCuration { + async process() { + // 1. AI scans for trending topics + const trends = await this.claudeAPI.identifyTrends({ + sources: ['ai_safety_papers', 'llm_research', 'sovereignty_news'], + timeframe: 'past_week' + }); + + // 2. AI suggests blog topics + const suggestions = await this.claudeAPI.suggestBlogTopics({ + trends: trends, + pillars: ['technical', 'implementation', 'advocacy', 'news'], + strategic_values: await this.loadStrategicValues() + }); + + // 3. Human editorial review + // (in moderation queue) + + // 4. For approved topics, AI drafts post + for (const topic of approved_topics) { + const draft = await this.claudeAPI.draftBlogPost({ + topic: topic, + audience: topic.pillar_audience, + guidelines: await this.loadEditorialGuidelines() + }); + + // 5. Queue for human editing + await this.queueForHumanEdit(draft, topic); + } + + // 6. Human edits and approves + // 7. Schedule publication + } +} + +14. Launch Strategy +14.1 Pre-Launch (Month 1) +Week 1-2: Infrastructure + +Set up OVHCloud hosting +Configure domain (mysy.digital) +Deploy base application +Migrate core documentation +Test all systems + +Week 3-4: Content + +Final review of all migrated docs +Write homepage copy +Create about/values pages +Prepare initial blog posts (3-5 pre-written) +Media kit preparation + +Week 4: Testing + +Full QA testing +Mobile responsiveness check +Accessibility audit +Performance optimization +Security review + +14.2 Launch Day (Month 2, Week 1) +Announcement Strategy: + +Email (if existing contacts): + +Anthropic research team +Academic collaborators +Aligned organizations + + +Social Media: + +LinkedIn (professional network) +Twitter/X (AI safety community) +Hacker News (technical audience) + + +Direct Outreach: + +AI safety research groups +University AI departments +Indigenous data sovereignty organizations + + +Press Release: + +NZ tech media +AI safety publications +Academic press + + + +Launch Content: +markdownSubject: Introducing Tractatus: Structural AI Safety from Aotearoa + +We're excited to announce the public launch of the Tractatus-Based LLM +Safety Framework - a comprehensive approach to AI safety through +architectural guarantees rather than training alone. + +Developed in Aotearoa New Zealand and informed by indigenous leadership +in digital sovereignty, Tractatus provides formal mechanisms to preserve +human agency as AI systems advance toward AGI. + +🔬 For Researchers: Complete technical documentation, case studies, and + collaboration opportunities +⚙️ For Implementers: Production-ready code, integration guides, and + interactive demos +📢 For Advocates: Plain-language resources, policy recommendations, and + community engagement + +Explore at mysy.digital + +[Key highlights, link to executive brief, invitation to engage] +14.3 Post-Launch (Month 2-3) +Week 1-4: Engagement + +Respond to all inquiries within 24 hours +Monitor analytics daily +Publish 2 blog posts/week +Engage with community feedback +Fix bugs quickly + +Week 5-8: Iteration + +Analyze user behavior +Identify most-visited paths +Optimize underperforming pages +Expand popular content +Build email subscriber list + +Week 9-12: Expansion + +Launch first interactive demo +Host first webinar/presentation +Publish first case study from community +Begin resource directory curation +Prepare Phase 2 features + + +15. Team & Roles +15.1 Core Team (Start) +Human PM (You - John Stroh): + +Strategic direction (STRATEGIC quadrant) +Values stewardship +Final approval on all content +Community relationship building +Media spokesperson + +Claude Code (AI Developer): + +Technical implementation (SYSTEM quadrant) +Code generation and testing +Database management +Infrastructure maintenance +Following Tractatus framework in development + +Claude Web (AI Curator): + +Content suggestions (STOCHASTIC quadrant) +Blog post drafting (pending human approval) +Media inquiry triage +Resource recommendations +Analytics insights +Subject to Tractatus boundaries + +15.2 Governance Structure +Strategic Quadrant (Human PM): + +Mission and values decisions +Te Tiriti alignment +Strategic partnerships +Major feature decisions +Annual planning + +Operational Quadrant (Human PM + Claude): + +Editorial guidelines (Human sets, Claude follows) +Content calendar (Human approves, Claude suggests) +Moderation policies (Human defines, Claude assists) +Quality standards (Human establishes) + +Tactical Quadrant (Primarily Claude, Human oversight): + +Daily blog suggestions +Inquiry triage +Resource curation +Analytics reporting +Subject to human approval for values-sensitive items + +System Quadrant (Primarily Claude Code): + +Technical implementation +Database optimization +Security updates +Performance monitoring +Human review for major changes + +Stochastic Quadrant (Claude + Human): + +Innovation exploration +New feature ideas +Pattern recognition in community needs +Experimental content formats +Human approval before implementation + + +16. Budget Considerations +16.1 Initial Costs (Phase 1) +Hosting (OVHCloud): + +VPS: ~€20-40/month +Database: Included +Bandwidth: ~€5-10/month +Total: €25-50/month ($40-80 NZD) + +Domain: + +mysy.digital: Already registered + +Development Tools: + +GitHub: Free (public repos) +Codeberg/Gitea: Free +Monitoring: Free tier (Plausible Analytics) +Total: €0/month + +Claude API (for AI features): + +Estimated usage: ~$50-100/month (Phase 2+) + +SSL Certificate: + +Let's Encrypt: Free + +Total Phase 1 Operating Costs: ~$40-80/month +16.2 Phase 3 Costs (with Koha) +Stripe Fees: + +2.9% + $0.30 per transaction +Monthly subscriptions: Same rate +Estimated: 10-15% of donations + +Increased Hosting (scaling): + +Larger VPS: ~€80-120/month +CDN: ~€10-20/month +Total: €90-140/month ($150-230 NZD) + +Revenue Projection (Phase 3): + +20 monthly supporters @ $15/month = $300 +One-time donations: ~$200/month average +Gross: ~$500/month +Net (after Stripe): ~$450/month +Covers hosting + development costs + + +17. Risk Management +17.1 Technical Risks +RiskLikelihoodImpactMitigationOVHCloud outageLowHighDaily backups, documented recovery processDatabase corruptionLowVery HighHourly backups, MongoDB replica setSecurity breachMediumVery HighRegular security audits, penetration testingPerformance issuesMediumMediumLoad testing, caching, CDNAI API limitsLowMediumRate limiting, fallback to human-only curation +17.2 Content Risks +RiskLikelihoodImpactMitigationAI publishes inappropriate contentLowVery HighAll AI content requires human approval (Tractatus)Misinformation in blogLowHighEditorial review, fact-checking processCopyright violationLowHighClear attribution policies, legal reviewValues misalignmentLowVery HighStrategic quadrant review for sensitive content +17.3 Community Risks +RiskLikelihoodImpactMitigationLow initial trafficHighMediumTargeted outreach, SEO optimizationNegative feedbackMediumMediumTransparent governance, open to criticismSpam/abuseMediumLowRate limiting, moderation toolsLack of engagementMediumMediumQuality content, community building + +18. Long-Term Vision (Beyond 18 Months) +18.1 Institutional Partnerships +Academic: + +University research collaborations +Student internship programs +Joint publications +Conference sponsorships + +Industry: + +Enterprise pilot programs +Integration partnerships +Standards development +Industry consortium membership + +Government: + +Policy advisory roles +Public sector implementations +Regulatory consultation +International cooperation (esp. with NZ govt, Māori data sovereignty bodies) + +18.2 Platform Evolution +Technical Maturity: + +Reference implementation in multiple languages +Certified integration partners +Training and certification programs +Open-source ecosystem development + +Global Reach: + +Regional chapters/communities +International translations (20+ languages) +Cultural adaptations (respect for local sovereignty contexts) +Federated governance model + +18.3 Impact Goals +By Year 3: + +10+ major AI organizations using framework +100+ published implementations +50+ peer-reviewed papers citing work +1,000+ monthly supporters +Recognized as leading AI safety approach +Strong global community of practitioners + +By Year 5: + +Industry standard for AI safety architecture +Government policy adoption (multiple countries) +Educational curriculum integration +Self-sustaining open-source ecosystem +Demonstrated prevention of major AI failures +Model for democratic AI governance + + +19. Getting Started - Immediate Next Steps +19.1 For Claude Code (This Session) +Priority 1: Infrastructure Setup +bash# 1. Initialize project +mkdir tractatus-website && cd tractatus-website +npm init -y + +# 2. Install dependencies +npm install express mongodb dotenv jsonwebtoken bcrypt +npm install marked highlight.js sanitize-html +npm install express-rate-limit helmet cors + +# 3. Project structure +mkdir -p src/{routes,controllers,models,middleware,services,utils} +mkdir -p public/{css,js,images} +mkdir -p scripts docs/markdown tests + +# 4. Create base files +touch src/server.js +touch .env.example +touch README.md + +# 5. Initialize git +git init +git remote add origin [GitHub URL] +Priority 2: Database Setup +javascript// scripts/init-db.js +// Create collections, indexes, seed data +Priority 3: Document Migration +javascript// scripts/migrate-documents.js +// Import all markdown files from knowledge base +// Convert to HTML +// Store in MongoDB with metadata +19.2 Immediate Deliverables +This Week: + + Project structure created + Database initialized + Core documents migrated + Basic server running + Homepage template + +Next Week: + + All routes implemented + Three audience paths built + Documentation viewer working + Basic styling complete + +Week 3: + + Testing complete + OVHCloud deployment + Domain connected + SSL configured + Ready for soft launch + + +20. Appendix: Quick Reference +20.1 Key URLs +Homepage: mysy.digital +Research Path: mysy.digital/research +Implementer Path: mysy.digital/implement +Advocacy Path: mysy.digital/advocacy +Blog: mysy.digital/blog +Documentation: mysy.digital/docs +About: mysy.digital/about +Contact: mysy.digital/contact +Media Kit: mysy.digital/media +20.2 Technology Stack Summary +LayerTechnologyPurposeFrontendVanilla JS + Tailwind CSSFast, accessible, no framework dependencyBackendNode.js + ExpressLeverages existing family-history stackDatabaseMongoDB + GridFSDocument storage, file managementAuthJWTAdmin/moderation accessAIClaude APIContent curation, triage, analysisPaymentsStripeKoha donations (Phase 3)HostingOVHCloudSovereignty-aligned hostingCDNOVHCloud CDNStatic asset deliveryRepositoryGitHub + Codeberg/GiteaVersion control, mirrorsAnalyticsPlausiblePrivacy-preserving metrics +20.3 Project Contacts +Project Lead: John Stroh (john.stroh.nz@pm.me) +Technical: via GitHub issues +Media Inquiries: press@mysy.digital +General: hello@mysy.digital + +21. Conclusion +This specification provides a comprehensive roadmap for building mysy.digital as a world-class platform for the Tractatus-Based LLM Safety Framework. By leveraging the existing family-history technical stack, implementing the framework's own principles (dogfooding), and serving three distinct audiences through differentiated paths, the site will effectively communicate this important AI safety research to researchers, implementers, and advocates worldwide. +The phased approach ensures sustainable development, the Tractatus governance guarantees alignment with strategic values, and the Te Tiriti acknowledgement positions Aotearoa New Zealand's leadership in indigenous-informed digital sovereignty within a global context. +Ready to begin implementation with Claude Code. + +Document Metadata: + +Created: 2025-10-06 +Version: 1.0.0 +Quadrant: STRATEGIC (with operational specifications) +Status: Ready for implementation +Next Action: Claude Code to begin Phase 1 development +RetrySTR-VAL-0004-transparency-principle-v1-0.md246 linesmdSTR-VAL-0003-values-principles-directory-v1-0.md88 linesmdSTR-VAL-0002-biodiversity-sustainability-principles-v1-0.md125 linesmdSTR-VAL-0001-core-values-principles-v1-0.md127 linesmdSTR-GOV-0003-strategic-versioning-guidelines-v1-0.md263 linesmdSTR-GOV-0002-values-alignment-framework-v1-0.md173 linesmdSTR-GOV-0001-strategic-review-protocol-v1-0.md285 linesmd + +Summary of Strategic Values Integration +Created document: /home/claude/tractatus-strategic-values-integration.md +Key Additions to Website Specification: +1. Core Values Deeply Embedded (not just mentioned): + +Sovereignty & Self-Determination: No tracking, user-controlled engagement, open-source everything +Progressive Implementation: Phased rollout with clear rationale for each stage +Transparency & Honesty: Public moderation queue, AI reasoning visible, decisions documented +Harmlessness & Protection: Privacy-first design, no dark patterns, security audits +Community & Accessibility: Three audience paths, WCAG compliance, economic accessibility +Biodiversity & Sustainability: Alternative frameworks highlighted, green hosting, ecosystem thinking + +2. Governance Frameworks Applied: + +Strategic Review Protocol adapted for website operations +Values Alignment Framework with specific matrices for website features +Strategic Versioning applied to all website documentation +Tension resolution process (when values conflict) + +3. Te Tiriti Integration Deepened: + +From acknowledgement to partnership (consultation with Māori data sovereignty experts) +Protection (CARE principles guide data handling) +Participation (Te Reo Māori content, Māori leadership pathways) +Kaitiakitanga (guardianship mindset for future generations) + +4. Tractatus Framework Self-Applied (Dogfooding): + +All AI curation subject to human oversight (boundary enforcement) +AI suggestions validated against values (cross-reference validation) +AI provides self-assessment before human review (metacognitive verification) +Values decisions always escalate to humans (architectural guarantee) + +5. Values-Aligned Metrics: + +Not just traffic/engagement, but sovereignty metrics, transparency audits, community diversity +Success measured by embodying values, not arbitrary KPIs + +6. Practical Implementation: + +Values alignment checklist for every feature +Code examples showing values in architecture +Moderation queue with public transparency +Human oversight requirements clearly defined + +What This Changes in Your Specification +You should integrate this Section 0 before your current Section 1 (Technical Architecture). It establishes the why and how before the what. +Critical implications: + +The website isn't just about AI safety—it demonstrates AI safety through values-aligned governance +Every feature decision now includes a mandatory values alignment check +AI assistance (blog curation, media triage) follows Tractatus boundaries +Success = values embodiment, not growth metrics diff --git a/README.md b/README.md new file mode 100644 index 00000000..fdf38f67 --- /dev/null +++ b/README.md @@ -0,0 +1,203 @@ +# Tractatus AI Safety Framework Website + +**Status:** Development - Phase 1 Implementation +**Domain:** mysy.digital +**Project Start:** 2025-10-06 + +--- + +## Overview + +A world-class platform demonstrating the **Tractatus-Based LLM Safety Framework** through three audience paths (Researcher, Implementer, Advocate), AI-powered features with human oversight, and interactive demonstrations. + +**Key Innovation:** The website implements the Tractatus framework to govern its own AI operations (dogfooding). + +--- + +## Project Structure + +``` +tractatus/ +├── docs/ # Source markdown & governance documents +├── public/ # Frontend assets (CSS, JS, images) +├── src/ # Backend code (Express, MongoDB) +│ ├── routes/ # API route handlers +│ ├── controllers/ # Business logic +│ ├── models/ # MongoDB models +│ ├── middleware/ # Express middleware +│ │ └── tractatus/ # Framework enforcement +│ ├── services/ # Core services (AI, governance) +│ └── utils/ # Utility functions +├── scripts/ # Setup & migration scripts +├── tests/ # Test suites (unit, integration, security) +├── data/ # MongoDB data directory +└── logs/ # Application & MongoDB logs +``` + +--- + +## Quick Start + +### Prerequisites +- Node.js 18+ +- MongoDB 7+ +- Git + +### Installation + +```bash +# Clone repository (once GitHub account is set up) +cd /home/theflow/projects/tractatus + +# Install dependencies +npm install + +# Copy environment variables +cp .env.example .env +# Edit .env with your configuration + +# Initialize database +npm run init:db + +# Migrate documents +npm run migrate:docs + +# Create admin user +npm run seed:admin + +# Start development server +npm run dev +``` + +The application will be available at `http://localhost:9000` + +--- + +## Technical Stack + +- **Backend:** Node.js, Express, MongoDB +- **Frontend:** Vanilla JavaScript, Tailwind CSS +- **Authentication:** JWT +- **AI Integration:** Claude API (Sonnet 4.5) - Phase 2+ +- **Testing:** Jest, Supertest + +--- + +## Infrastructure + +- **MongoDB Port:** 27017 +- **Application Port:** 9000 +- **Database:** tractatus_dev +- **Systemd Service:** mongodb-tractatus.service, tractatus.service + +--- + +## Phase 1 Deliverables (3-4 Months) + +**Must-Have for Complete Prototype:** + +- [x] Infrastructure setup +- [ ] Document migration pipeline +- [ ] Three audience paths (Researcher/Implementer/Advocate) +- [ ] Tractatus governance services (Classifier, Validator, Boundary Enforcer) +- [ ] AI-curated blog with human oversight +- [ ] Media inquiry triage system +- [ ] Case study submission portal +- [ ] Resource directory +- [ ] Interactive demonstrations (classification, 27027, boundary enforcement) +- [ ] Human oversight dashboard +- [ ] Comprehensive testing suite + +--- + +## Development Workflow + +### Running Tests +```bash +npm test # All tests with coverage +npm run test:unit # Unit tests only +npm run test:integration # Integration tests +npm run test:security # Security tests +npm run test:watch # Watch mode +``` + +### Code Quality +```bash +npm run lint # Check code style +npm run lint:fix # Fix linting issues +``` + +### Database Operations +```bash +npm run init:db # Initialize database & indexes +npm run migrate:docs # Import markdown documents +npm run generate:pdfs # Generate PDF downloads +``` + +--- + +## Governance + +This project adheres to the Tractatus framework principles: + +- **Sovereignty & Self-determination:** No tracking, user control, open source +- **Transparency & Honesty:** Public moderation queue, AI reasoning visible +- **Harmlessness & Protection:** Privacy-first design, security audits +- **Community & Accessibility:** WCAG compliance, three audience paths + +All AI actions are governed by: +1. InstructionPersistenceClassifier +2. CrossReferenceValidator +3. BoundaryEnforcer +4. ContextPressureMonitor +5. MetacognitiveVerifier + +--- + +## Human Approval Required + +**All major decisions require human approval:** +- Architectural changes +- Database schema modifications +- Security implementations +- Third-party integrations +- Values-sensitive content +- Cost-incurring services + +**See:** `CLAUDE.md` for complete project context and conventions + +--- + +## Te Tiriti & Indigenous Perspective + +This project acknowledges **Te Tiriti o Waitangi** and indigenous leadership in digital sovereignty. Implementation follows documented indigenous data sovereignty principles (CARE Principles) with respect and without tokenism. + +**No premature engagement:** We will not approach Māori organizations until we have something valuable to offer post-launch. + +--- + +## Links & Resources + +- **Project Context:** `CLAUDE.md` +- **Specification:** `Tractatus-Website-Complete-Specification-v2.0.md` +- **Framework Documentation:** `/home/theflow/projects/sydigital/stochastic/innovation-exploration/` +- **Governance References:** `/home/theflow/projects/sydigital/strategic/` + +--- + +## License + +MIT License - See LICENSE file for details + +--- + +## Contact + +**Project Owner:** John Stroh +**Email:** john.stroh.nz@pm.me +**Repository:** GitHub (primary) + Codeberg/Gitea (mirrors) + +--- + +**Last Updated:** 2025-10-06 +**Next Milestone:** Complete MongoDB setup and systemd service diff --git a/Tractatus-Website-Complete-Specification-v2.0.md b/Tractatus-Website-Complete-Specification-v2.0.md new file mode 100644 index 00000000..142cce29 --- /dev/null +++ b/Tractatus-Website-Complete-Specification-v2.0.md @@ -0,0 +1,2166 @@ +# Tractatus-Based LLM Safety Framework Website - Complete Technical Specification + +**Project**: mysy.digital - Tractatus AI Safety Framework Website +**Platform**: Node.js/Express + MongoDB (leveraging family-history stack) +**Hosting**: OVHCloud +**Repository**: GitHub (primary) + Codeberg/Gitea (mirrors) +**Target Audiences**: Academic/Research, Industry/Enterprise, Public Advocacy +**Timeline**: 4-phase rollout over 18 months +**Version**: 2.0 (with Strategic Values & GDPR Integration) +**Created**: 2025-10-06 + +--- + +## Executive Summary + +Build a comprehensive website for the Tractatus-Based LLM Safety Framework that serves three distinct audiences through differentiated landing paths while maintaining a unified knowledge base. The site will demonstrate the framework's principles by implementing them in its own architecture (dogfooding), use Claude-powered curation with explicit human oversight, and position Aotearoa/New Zealand's leadership in incorporating indigenous perspectives on digital sovereignty within a global context. + +**CRITICAL**: This website embodies GDPR compliance as a core architectural principle, not a compliance checkbox. Every feature, every data flow, every user interaction is designed with privacy-first, data minimization, and user sovereignty principles from the ground up. + +--- + +## Table of Contents + +**SECTION 0: STRATEGIC VALUES & GOVERNANCE FRAMEWORK** +- 0.1 Core Values Alignment +- 0.2 Governance Integration +- 0.3 Te Tiriti O Waitangi Integration +- 0.4 Architectural Manifestation of Values +- 0.5 Values Governance in AI Curation +- 0.6 Success Metrics Aligned with Values +- 0.7 Implications for Website Specification +- 0.8 Values-First Development Checklist +- 0.9 GDPR as Strategic Value (NEW) + +**SECTION 1: TECHNICAL ARCHITECTURE** +- 1.1 Core Technology Stack +- 1.2 Tractatus Framework Implementation (Dogfooding) +- 1.3 GDPR-Compliant Architecture (NEW) + +**SECTION 2: INFORMATION ARCHITECTURE** +- 2.1 Three Audience Landing Paths +- 2.2 Researcher Path +- 2.3 Implementer Path +- 2.4 Advocate Path +- 2.5 Unified Components (All Paths) + +**SECTION 3: CONTENT MIGRATION & INTEGRATION** +- 3.1 Existing Documents to Integrate +- 3.2 Content Processing Pipeline + +**SECTION 4: AI-POWERED FEATURES (TRACTATUS-GOVERNED)** +- 4.1 Blog Curation System +- 4.2 Press/Media Inquiry System +- 4.3 Resource Curation +- 4.4 GDPR Compliance in AI Features (NEW) + +**SECTION 5: TE TIRITI & INDIGENOUS PERSPECTIVE INTEGRATION** +- 5.1 Strategic Values Statement +- 5.2 Resource Directory Inclusion + +**SECTION 6: INTERACTIVE DEMONSTRATIONS** +- 6.1 Instruction Classification Demo +- 6.2 The 27027 Incident Visualizer +- 6.3 Boundary Enforcement Simulator + +**SECTION 7: PHASED IMPLEMENTATION ROADMAP** +- Phase 1: Foundation & Launch (Months 1-3) +- Phase 2: Engagement & Demonstration (Months 4-8) +- Phase 3: Technical Expansion & Koha (Months 9-14) +- Phase 4: Scaling & Advocacy (Months 15-18) + +**SECTION 8: DETAILED TECHNICAL SPECIFICATIONS** +- 8.1 Database Schema +- 8.2 API Routes +- 8.3 Frontend Components +- 8.4 GDPR Data Models & APIs (NEW) + +**SECTION 9: PERFORMANCE & OPTIMIZATION** +- 9.1 Performance Targets +- 9.2 Monitoring & Analytics + +**SECTION 10: SECURITY & PRIVACY** +- 10.1 Security Measures +- 10.2 GDPR Compliance Framework (NEW - COMPREHENSIVE) + +**SECTION 11: DEVELOPMENT WORKFLOW** +- 11.1 Git Repository Structure +- 11.2 Development Process + +**SECTION 12: SUCCESS METRICS & KPIS** +- 12.1 Phase-Specific Metrics +- 12.2 Tractatus Framework Validation Metrics +- 12.3 GDPR Compliance Metrics (NEW) + +**SECTION 13: CONTENT STRATEGY & EDITORIAL CALENDAR** +- 13.1 Blog Content Pillars +- 13.2 AI Curation Workflow + +**SECTION 14: LAUNCH STRATEGY** +- 14.1 Pre-Launch +- 14.2 Launch Day +- 14.3 Post-Launch + +**SECTION 15: TEAM & ROLES** +- 15.1 Core Team +- 15.2 Governance Structure + +**SECTION 16: BUDGET CONSIDERATIONS** +- 16.1 Initial Costs +- 16.2 Phase 3 Costs + +**SECTION 17: RISK MANAGEMENT** +- 17.1 Technical Risks +- 17.2 Content Risks +- 17.3 Community Risks +- 17.4 GDPR Compliance Risks (NEW) + +**SECTION 18: LONG-TERM VISION** +- 18.1 Institutional Partnerships +- 18.2 Platform Evolution +- 18.3 Impact Goals + +**SECTION 19: GETTING STARTED** +- 19.1 For Claude Code (This Session) +- 19.2 Immediate Deliverables + +**SECTION 20: APPENDICES** +- 20.1 Quick Reference +- 20.2 Technology Stack Summary +- 20.3 Project Contacts +- 20.4 GDPR Article Coverage Map (NEW) + +--- + +# SECTION 0: STRATEGIC VALUES & GOVERNANCE FRAMEWORK + +## 0.1 Core Values Alignment + +The Tractatus-Based LLM Safety Framework website embodies SyDigital's core values at every level of design and implementation. These values are not additive features but foundational architectural principles that shape how the site operates, how content is created, and how the community engages. + +### Sovereignty & Self-Determination + +**Expression in the Tractatus Project**: +- The framework itself is about preserving human agency in AI systems +- Website architecture provides user control over engagement level (three audience paths) +- No tracking, no surveillance capitalism, no extractive data practices +- Users choose their journey: researcher, implementer, or advocate depth + +**Implementation**: +```javascript +// Users control their data and interaction level +class UserSovereigntyManager { + constructor() { + this.dataCollection = 'minimal'; // Only what user explicitly provides + this.trackingPolicy = 'none'; // No behavioral tracking + this.exitRights = 'complete'; // Full data export/deletion + } + + async getUserPreferences() { + // Users set preferences, not algorithms + // No dark patterns, no manipulation + // Clear explanations of every choice + return await this.explicitUserChoice(); + } +} +``` + +**Manifestations**: +1. **Website Level**: No cookies except essential, no third-party tracking, privacy-first analytics +2. **Content Level**: Users choose depth of engagement (quick overview vs deep dive) +3. **Community Level**: Open-source everything, forkable, no platform lock-in +4. **Governance Level**: Transparent decision-making, community input mechanisms + +### Progressive Implementation + +**Expression in the Tractatus Project**: +- Phased 18-month rollout (Foundation → Engagement → Expansion → Scaling) +- Meet audiences where they are: academic rigor, practical implementation, public advocacy +- Framework itself teaches incremental safety improvements, not all-or-nothing adoption + +**Implementation**: +```javascript +// Progressive enhancement approach +class ProgressiveImplementation { + phases = { + phase1: { + name: 'Foundation', + duration: '3 months', + delivers: 'Core docs, three paths, basic blog', + principle: 'Start with stable, valuable minimum' + }, + phase2: { + name: 'Engagement', + duration: '5 months', + delivers: 'Interactive demos, AI curation, community features', + principle: 'Add complexity as foundation proves solid' + }, + phase3: { + name: 'Expansion', + duration: '6 months', + delivers: 'Koha, translations, advanced features', + principle: 'Scale only when sustainable' + }, + phase4: { + name: 'Scaling', + duration: 'Ongoing', + delivers: 'Global reach, partnerships, institutional adoption', + principle: 'Growth serves mission, not vice versa' + } + }; +} +``` + +**Manifestations**: +1. **Development**: Iterative releases with clear milestones +2. **Content**: Layered complexity (quick summaries → full technical depth) +3. **Features**: Core functionality first, enhancements when proven +4. **Community**: Gradual engagement building, not forced growth + +### Transparency & Honesty + +**Expression in the Tractatus Project**: +- The framework is BUILT ON transparency (cross-reference validation, explicit boundaries) +- Website dogfoods Tractatus principles: all AI actions subject to human oversight +- No hidden agendas, no undisclosed conflicts, no marketing spin + +**Implementation**: +```javascript +// Every AI action is visible and governed +class TransparencyEngine { + async curateContent(topic) { + // 1. AI suggests content + const suggestion = await this.claudeAPI.suggest(topic); + + // 2. Show AI reasoning publicly in moderation queue + const reasoning = { + why_suggested: suggestion.rationale, + values_check: this.checkAgainstValues(suggestion), + potential_concerns: this.identifyRisks(suggestion), + confidence_level: suggestion.confidence + }; + + // 3. Human reviews with full context + await this.queueForHumanReview({ + suggestion: suggestion, + ai_reasoning: reasoning, + transparency_note: 'This content was AI-suggested and requires human approval per Tractatus boundary enforcement' + }); + + // 4. Decision and rationale are documented + // 5. Published content shows "AI-curated, human-approved" + } +} +``` + +**Manifestations**: +1. **Website Operations**: Public moderation queue, visible AI suggestions, documented human decisions +2. **Content Creation**: Clear attribution (human vs AI-curated), reasoning visible +3. **Governance**: Published decision logs, transparent Koha allocation (Phase 3) +4. **Code**: Open source, public repos, documented architecture choices +5. **Metrics**: Privacy-preserving analytics shared publicly + +**Per STR-VAL-0004 Transparency Principle**: +- **Informational Transparency**: All framework docs accessible, searchable, downloadable +- **Process Transparency**: How content is created, reviewed, published is documented +- **Decision Transparency**: Why features were built, priorities chosen is explained +- **Outcome Transparency**: Metrics published, successes and failures shared +- **Systemic Transparency**: Tractatus governance applied to the website itself + +### Harmlessness & Protection + +**Expression in the Tractatus Project**: +- Framework prevents AI harms through architectural boundaries +- Website protects users through privacy-first design +- No exploitation, no manipulation, no dark patterns + +**Implementation**: +```javascript +// Protection built into every interaction +class HarmlessnessProtection { + async validateInteraction(interaction) { + // Privacy protection + if (interaction.requires_personal_data) { + return this.minimizeDataCollection(interaction); + } + + // Attention protection + if (interaction.is_attention_hijacking) { + return this.rejectManipulativePattern(interaction); + } + + // Security protection + if (interaction.has_security_risk) { + return this.escalateToSecurityReview(interaction); + } + + // Values protection - enforce Tractatus boundaries + if (interaction.involves_values_decision) { + return this.requireHumanJudgment(interaction); + } + } +} +``` + +**Manifestations**: +1. **Data Protection**: Minimal collection, encryption, user rights respected +2. **Attention Protection**: No infinite scroll, no engagement hacking, clear exit points +3. **Security**: Regular audits, vulnerability disclosure, responsible practices +4. **Content Safety**: Moderation prevents harmful content while respecting expression + +### Community & Accessibility + +**Expression in the Tractatus Project**: +- Framework is for everyone, not just AI safety researchers +- Three audience paths ensure accessibility across skill levels +- Free core resources, sustainable premium funding, no paywalling of safety research + +**Implementation**: +```javascript +// Accessibility at every level +class CommunityAccessibility { + audiencePaths = { + researcher: { + content: 'Technical depth, academic rigor, peer review', + accessibility: 'Assumes technical background, provides references', + free_access: 'All research papers, code, documentation' + }, + implementer: { + content: 'Practical guides, code examples, case studies', + accessibility: 'Assumes programming knowledge, teaches framework', + free_access: 'Core implementation guides, open-source reference code' + }, + advocate: { + content: 'Plain language, visuals, public resources', + accessibility: 'No technical assumptions, metaphors and examples', + free_access: 'All public education materials, media resources' + } + }; + + async personalizeAccess(user) { + // Let users self-select their path + // Provide bridges between paths + // No gatekeeping, just appropriate depth + } +} +``` + +**Manifestations**: +1. **Content Accessibility**: Plain language versions, technical depth available +2. **Technical Accessibility**: WCAG 2.1 AA compliance, screen reader support, keyboard navigation +3. **Economic Accessibility**: Core safety research is free, forever +4. **Language Accessibility**: Multi-language (Phase 3+), starting with Te Reo Māori +5. **Community Building**: Forums, events, open collaboration, low barriers to participation + +### Biodiversity & Sustainability (per STR-VAL-0002) + +**Expression in the Tractatus Project**: +- Framework supports diverse AI architectures, not monoculture +- Website built on open standards, not proprietary lock-in +- Sustainable funding model (Koha) respects community rather than extracting value + +**Digital Ecosystem Diversity**: +```javascript +// Supporting plurality in AI safety approaches +class BiodiversitySupport { + alignedProjects = { + approach: 'catalogue_diverse_methods', + philosophy: 'no_single_solution', + contribution: 'tractatus_is_one_approach_among_many' + }; + + async curateResourceDirectory() { + // Include competing approaches + // Show complementary frameworks + // Acknowledge limitations of Tractatus + // Celebrate diverse AI safety research + return await this.buildEcosystem({ + monoculture: false, + biodiversity: true, + mutual_enrichment: true + }); + } +} +``` + +**Regenerative Design**: +- Website gives back: open source code, free education, community knowledge +- Not extractive: doesn't mine user data, doesn't exploit attention +- Improves the commons: makes AI safety knowledge more accessible + +**Manifestations**: +1. **Technology Pluralism**: Links to alternative AI safety approaches, not just Tractatus +2. **Resource Consciousness**: Efficient code, minimal server load, sustainable hosting +3. **Intergenerational Stewardship**: Framework designed to be relevant as AI evolves +4. **Community Resilience**: Distributed knowledge, forkable codebase, no single point of failure +5. **Environmental Awareness**: Green hosting (OVHCloud renewable energy), efficient architecture + +--- + +## 0.2 Governance Integration + +The website implements SyDigital's governance frameworks to ensure values alignment throughout its lifecycle. + +### Strategic Review Protocol (per STR-GOV-0001) + +**Application to Tractatus Website**: + +| Website Element | Review Cycle | Review Type | Authority | +|----------------|--------------|-------------|-----------| +| Core mission/values statements | Annual | Regular | Human PM (Strategic quadrant) | +| Editorial guidelines | Quarterly | Regular | Human PM + Community input | +| Blog content strategy | Quarterly | Regular | Editorial team | +| Feature roadmap | Monthly | Regular | Human PM + User feedback | +| Technical architecture | Continuous | Trigger-based | System quadrant (Claude Code) | +| GDPR compliance practices | Quarterly | Regular | DPO/Compliance team | + +**Review Process Integration**: +```javascript +// Strategic governance applied to website operations +class WebsiteGovernance { + async reviewProcess(element) { + // 1. Preparation - gather feedback and metrics + const context = await this.gatherReviewContext(element); + + // 2. Assessment - evaluate against values + const assessment = await this.assessValuesAlignment(element, context); + + // 3. Refinement - propose changes if needed + if (assessment.needs_refinement) { + const proposal = await this.proposeRefinements(element, assessment); + + // 4. Validation - human approval required + const decision = await this.requireHumanReview({ + element: element, + assessment: assessment, + proposal: proposal, + quadrant: this.determineQuadrant(element) + }); + + // 5. Documentation - transparent change tracking + await this.documentDecision(decision); + } + } +} +``` + +### Values Alignment Framework (per STR-GOV-0002) + +**Values Alignment Matrix for Website Features**: + +| Feature | Progressive Impl. | Sovereignty | Transparency | Community | Biodiversity | GDPR | +|---------|-------------------|-------------|--------------|-----------|--------------|------| +| **Three Audience Paths** | ✓ Meets users where they are | ✓ User chooses depth | ✓ Clear navigation | ✓ Multiple entry points | ✓ Diverse approaches | ✓ No tracking | +| **AI-Curated Blog** | ✓ Phased rollout (Phase 2) | ✓ Human oversight required | ✓ AI reasoning visible | ✓ Guest posts welcome | ✓ Multiple perspectives | ✓ No personal data | +| **Koha Donations** | ✓ Only after traction (Phase 3) | ✓ Optional, never required | ✓ Allocation published | ✓ Supports commons | ✓ Sustainable funding | ✓ Minimal data, Stripe-handled | +| **Interactive Demos** | ✓ Simple → complex progression | ✓ Educational, not extractive | ✓ Code open source | ✓ Learning-focused | ✓ Shows alternatives | ✓ No data collection | +| **Resource Directory** | ✓ Curated, then community-driven | ✓ User-contributed | ✓ Criteria documented | ✓ Shared knowledge | ✓ Ecosystem mapping | ✓ Public data only | + +--- + +## 0.3 Te Tiriti O Waitangi Integration + +**Beyond Acknowledgement to Implementation**: + +### Partnership (Article 1) + +**Application to Website Governance**: +- Consultation with Māori data sovereignty experts on framework governance +- Partnership opportunities with iwi and Māori tech organizations +- Māori representation in strategic decision-making (when expanding governance) + +**Implementation**: +```javascript +// Partnership in practice +class TeTiritiPartnership { + governance = { + consultation: 'Engage Māori data sovereignty experts for major decisions', + representation: 'Seek Māori perspectives in governance as project scales', + collaboration: 'Partner with Māori-led tech initiatives' + }; + + async seekPartnershipInput(decision) { + if (decision.affects_data_sovereignty_principles) { + // Consult with Māori data sovereignty networks + // Incorporate perspectives into decision-making + // Document how input shaped outcomes + } + } +} +``` + +### Protection (Article 2) + +**Application to Framework Design**: +- Framework protects tino rangatiratanga (self-determination) in AI systems +- Māori data sovereignty principles inform architectural choices +- CARE principles (Collective benefit, Authority to control, Responsibility, Ethics) guide data handling + +**Manifestations**: +1. Data sovereignty controls reflect indigenous data rights thinking +2. Framework documentation cites Māori data sovereignty scholarship +3. Cultural safety considerations in AI boundary definitions +4. Protection of indigenous knowledge in AI training discussions + +### Participation (Article 3) + +**Application to Community Engagement**: +- Māori technologists welcomed as contributors, collaborators, leaders +- Te Reo Māori content from Phase 3 onward +- Accessibility for Māori communities (not just translation, but culturally appropriate framing) +- Recognition of Māori innovation in digital sovereignty + +**Implementation**: +```javascript +// Active participation support +class TeTiritiParticipation { + languageSupport = { + phase3: 'Te Reo Māori translations of key content', + ongoing: 'Māori language interface options', + priority: 'Strategic documents, public resources first' + }; + + communityEngagement = { + outreach: 'Active engagement with Māori tech communities', + contribution: 'Lowered barriers for Māori participation', + recognition: 'Māori contributors highlighted and valued', + leadership: 'Pathway for Māori leadership roles in project' + }; +} +``` + +**Kaitiakitanga (Guardianship) Application**: +- Framework operates as digital guardianship for future generations +- Long-term thinking built into architecture (intergenerational AI safety) +- Stewardship rather than ownership mentality +- Responsibility to those who come after us + +--- + +## 0.4 Architectural Manifestation of Values + +### Progressive Implementation in Code + +```javascript +// Example: Blog system grows with project maturity +class BlogSystem { + phase1 = { + features: ['Human-written posts', 'Basic RSS', 'Email signup'], + complexity: 'Simple', + principle: 'Proven foundation before automation' + }; + + phase2 = { + features: ['AI content suggestions', 'Human editorial approval', 'Comment system'], + complexity: 'Moderate', + principle: 'Add AI assistance with human oversight', + tractatus_governance: 'All AI suggestions require human approval' + }; + + phase3 = { + features: ['Multi-language', 'Advanced moderation', 'Community contributions'], + complexity: 'Advanced', + principle: 'Scale only when phase 2 is stable' + }; +} +``` + +### Sovereignty in User Experience + +```javascript +// User control at every level +class UserExperienceDesign { + dataControl = { + collection: 'Minimal - only what users explicitly provide', + storage: 'Transparent - users see what we have', + deletion: 'Complete - right to be forgotten respected', + export: 'Full - portable data in open formats' + }; + + interactionControl = { + tracking: 'None - no behavioral surveillance', + personalization: 'Opt-in only - no algorithmic manipulation', + notifications: 'User-controlled - no dark patterns', + exit: 'Always available - no retention tactics' + }; +} +``` + +--- + +## 0.5 Values Governance in AI Curation + +**Critical Implementation Detail**: The website uses AI (Claude) for content curation, media triage, and resource suggestions. This creates a meta-challenge: how do we ensure AI assistance aligns with our values? + +### Tractatus Framework Applied to Website AI + +```javascript +// The website dogfoods its own framework +class SelfApplicationOfTractatus { + boundaryEnforcement = { + rule: 'AI cannot make values decisions', + implementation: 'All content with sovereignty/values implications requires human review', + examples: [ + 'Blog post about indigenous data rights → Strategic quadrant review', + 'Resource about competing AI safety approach → Human validates alignment', + 'Media inquiry about framework limitations → Human responds personally' + ] + }; + + crossReferenceValidation = { + rule: 'AI suggestions validated against strategic values', + implementation: 'Every AI suggestion checked against STR-VAL-0001', + examples: [ + 'Does this blog topic support Progressive Implementation?', + 'Does this resource promote Sovereignty?', + 'Does this response demonstrate Transparency?' + ] + }; + + metaCognitiveVerification = { + rule: 'AI must check its own suggestions for values alignment', + implementation: 'AI provides self-assessment before human review', + example: { + ai_suggestion: 'Blog post about faster implementation timeline', + ai_self_check: { + progressive_implementation: 'CONCERN - may pressure users to rush', + values_alignment: 'REQUIRES REVIEW - tension with safety-first approach', + recommendation: 'Escalate to human judgment - values decision involved' + } + } + }; +} +``` + +### Human Oversight Requirements + +| AI Action | Quadrant | Human Oversight Level | Rationale | +|-----------|----------|----------------------|-----------| +| Suggest blog topic | Stochastic | Review queue | Pattern recognition, but values impact possible | +| Draft blog post | Operational | Mandatory editorial approval | Content represents project, values must be verified | +| Triage media inquiry | Tactical | Review queue | Most tactical, but values-sensitive topics escalate | +| Suggest resource | Stochastic | Review queue | Discovery task, but quality standards apply | +| Recommend feature | Strategic | Mandatory review | Strategic decisions are human-only | +| Handle values question | Strategic | Human-only response | Tractatus boundary: values cannot be automated | + +--- + +## 0.6 Success Metrics Aligned with Values + +**Beyond Traffic and Engagement**: + +Traditional web metrics don't capture values alignment. We measure what matters: + +### Sovereignty Metrics + +- **User Control Score**: % of users who exercise data rights (export, deletion requests) +- **Path Autonomy**: Distribution across three audience paths (not algorithmic funneling) +- **Exit Freedom**: Bounce rate as neutral metric (leaving is fine if needs met) +- **Attribution Clarity**: % of content with clear human/AI attribution + +### Progressive Implementation Metrics + +- **Phase Completion Quality**: Not just "done" but "stable and valuable" +- **User Feedback Integration**: How much community input shapes development +- **Regression Avoidance**: New features don't break existing functionality +- **Sustainable Growth**: User growth doesn't exceed support capacity + +### Transparency Metrics + +- **Documentation Completeness**: Are all decisions documented? +- **Governance Visibility**: Can users find governance processes? +- **AI Attribution Accuracy**: Is AI involvement always disclosed? +- **Values Alignment Audits**: Regular reviews of practices vs. principles + +### Community Metrics + +- **Accessibility Score**: WCAG compliance + usability testing results +- **Contribution Diversity**: Who is contributing (not just how many) +- **Knowledge Sharing**: Downloads of free resources, forks of codebase +- **Support Responsiveness**: Time to respond to community questions + +### Biodiversity Metrics + +- **Alternative Approaches Cited**: Number of competing frameworks in directory +- **Honest Limitation Disclosure**: Tractatus limitations documented +- **Ecosystem Contribution**: How much do we give back (code, knowledge, collaboration) +- **Resource Efficiency**: Server load per user, energy consumption + +--- + +## 0.7 GDPR Compliance Metrics (NEW) + +**GDPR is not a checkbox—it's an architectural value that reinforces sovereignty, transparency, and harmlessness.** + +### GDPR-Specific Metrics + +- **Data Minimization Score**: Ratio of data collected to data strictly necessary +- **Consent Quality**: % of users who understand what they're consenting to +- **Response Time to Rights Requests**: Average time to fulfill access/deletion requests +- **Breach Response Preparedness**: Time from detection to containment in drills +- **Privacy by Design Compliance**: % of features that passed GDPR design review +- **Third-Party Data Sharing**: Count (target: zero for personal data) + +### Compliance Monitoring + +```javascript +// Continuous GDPR compliance monitoring +class GDPRComplianceMonitor { + async runDailyAudit() { + return { + data_minimization: await this.auditDataCollection(), + consent_validity: await this.auditConsentRecords(), + retention_compliance: await this.auditDataRetention(), + security_posture: await this.auditSecurityMeasures(), + user_rights_fulfillment: await this.auditRightsRequests(), + documentation: await this.auditRecordKeeping() + }; + } + + async auditDataCollection() { + // For every data point collected: + // - Is it necessary for stated purpose? + // - Do we have valid consent? + // - Is retention period appropriate? + // - Is it properly secured? + } +} +``` + +--- + +## 0.8 Values-First Development Checklist + +**Before Building Any Feature**: + +```markdown +## Values Alignment Checklist + +### Progressive Implementation +- [ ] Can this be implemented incrementally? +- [ ] Does it depend on proven foundation? +- [ ] What's the minimal viable version? +- [ ] Can users opt-in gradually? + +### Sovereignty & Self-Determination +- [ ] Does this respect user control? +- [ ] Does it collect minimal necessary data? +- [ ] Can users understand and modify behavior? +- [ ] Does it support diverse use cases? + +### Transparency & Honesty +- [ ] Is the purpose clearly explained? +- [ ] Are trade-offs honestly communicated? +- [ ] Is AI involvement disclosed? +- [ ] Are decisions documented? + +### Harmlessness & Protection +- [ ] Does this protect user privacy? +- [ ] Could this be manipulative? +- [ ] Are security implications considered? +- [ ] Does this respect user attention? + +### Community & Accessibility +- [ ] Is this accessible across skill levels? +- [ ] Does this support collaboration? +- [ ] Is the knowledge shareable? +- [ ] Are barriers to participation minimized? + +### Biodiversity & Sustainability +- [ ] Does this support diverse approaches? +- [ ] Is this resource-efficient? +- [ ] Does this give back to the commons? +- [ ] Is this sustainable long-term? + +### Te Tiriti Alignment +- [ ] Have we consulted relevant perspectives? +- [ ] Does this protect data sovereignty? +- [ ] Is participation genuinely supported? +- [ ] Does this honor kaitiakitanga? + +### GDPR Compliance (NEW) +- [ ] Is data collection minimized? +- [ ] Is valid consent obtained (if required)? +- [ ] Can users access/export/delete their data? +- [ ] Is data secured appropriately? +- [ ] Is retention period defined and justified? +- [ ] Are processors GDPR-compliant? +- [ ] Is privacy notice clear and accessible? +- [ ] Can we demonstrate compliance? + +### Decision +- [ ] Values alignment confirmed +- [ ] Tensions identified and resolved +- [ ] Human approval obtained +- [ ] Documentation complete +- [ ] GDPR impact assessment complete (if required) +``` + +--- + +## 0.9 GDPR as Strategic Value (NEW SECTION) + +### Why GDPR Matters for Tractatus + +GDPR is not merely a legal obligation—it's a **validation of our core values** and a **reinforcement of the Tractatus framework itself**. + +**The Connection**: +- **Sovereignty**: GDPR enshrines user rights over their data +- **Transparency**: GDPR requires clear communication about data use +- **Harmlessness**: GDPR mandates data protection and security +- **Progressive Implementation**: GDPR allows for iterative compliance improvements +- **Biodiversity**: GDPR supports data portability and interoperability + +### GDPR Principles Aligned with Values + +| GDPR Principle | SyDigital Value | Tractatus Connection | +|----------------|-----------------|---------------------| +| **Lawfulness, fairness, transparency** | Transparency & Honesty | Cross-reference validation ensures AI follows explicit instructions | +| **Purpose limitation** | Sovereignty & Self-Determination | Users must know and consent to specific purposes | +| **Data minimization** | Harmlessness & Protection | Collect only what's necessary, protect what's collected | +| **Accuracy** | Transparency | Users have right to correct their data | +| **Storage limitation** | Progressive Implementation | Retention periods aligned with legitimate needs | +| **Integrity and confidentiality** | Harmlessness & Protection | Security by design and default | +| **Accountability** | Transparency | Demonstrate compliance, not just claim it | + +### GDPR as Architectural Principle + +```javascript +// GDPR built into every data interaction +class GDPRByDesign { + async collectData(dataPoint, purpose, user) { + // 1. Necessity check + if (!this.isStrictlyNecessary(dataPoint, purpose)) { + return this.rejectDataCollection({ + reason: 'Not necessary for stated purpose', + principle: 'Data minimization (Article 5.1.c)' + }); + } + + // 2. Consent check (if required) + if (this.requiresConsent(purpose)) { + const consent = await this.verifyConsent(user, purpose); + if (!consent.valid) { + return this.requestConsent(user, purpose, dataPoint); + } + } + + // 3. Retention period definition + const retention = this.determineRetentionPeriod(purpose); + + // 4. Security measures + const security = this.applySecurity(dataPoint, purpose); + + // 5. Documentation + await this.documentProcessingActivity({ + data: dataPoint, + purpose: purpose, + legal_basis: consent.basis || 'legitimate_interest', + retention: retention, + security: security, + timestamp: new Date() + }); + + // 6. Store with metadata + return await this.storeSecurely(dataPoint, { + purpose, + retention, + security, + user_rights_applicable: true + }); + } +} +``` + +### GDPR Coverage in This Specification + +**Throughout this document, GDPR compliance is integrated into**: +- Section 1.3: GDPR-Compliant Architecture +- Section 4.4: GDPR Compliance in AI Features +- Section 8.4: GDPR Data Models & APIs +- Section 10.2: GDPR Compliance Framework (COMPREHENSIVE) +- Section 12.3: GDPR Compliance Metrics +- Section 17.4: GDPR Compliance Risks +- Appendix 20.4: GDPR Article Coverage Map + +**This is not a compliance add-on. This is foundational architecture.** + +--- + +# SECTION 1: TECHNICAL ARCHITECTURE + +## 1.1 Core Technology Stack + +**Backend** (leveraging existing family-history stack): +```javascript +// Node.js/Express foundation +- Express 4.x for routing and middleware +- MongoDB for content, user data, and framework documentation +- GridFS for file storage (PDFs, presentations, code examples) +- JWT authentication for user accounts and admin access +- WebSocket for real-time updates and notifications + +// Key services to adapt from family-history: +- TenantFileService → DocumentService (multi-document management) +- User authentication system +- Multi-language support infrastructure (i18n.js) +- Session management +- GDPR compliance services (adapted from family-history) +``` + +**Frontend**: +```javascript +// Progressive enhancement approach +- Vanilla JavaScript (no framework dependency for core features) +- Optional React components for interactive demos +- Tailwind CSS for styling consistency +- Mobile-first responsive design +- ARIA compliance for accessibility +- No tracking scripts, no third-party analytics cookies +``` + +**Database Collections** (MongoDB): +```javascript +db.collection('documents') // Technical papers, case studies, appendices +db.collection('blog_posts') // AI-curated blog with human oversight +db.collection('media_inquiries') // Press/media contact submissions +db.collection('case_submissions') // Community case study submissions +db.collection('resources') // External links, aligned projects +db.collection('koha_donations') // Donation tracking (Phase 3+) +db.collection('users') // User accounts (minimal data) +db.collection('moderation_queue') // Human oversight queue for AI actions +db.collection('citations') // Academic citation tracking +db.collection('translations') // Multi-language content + +// GDPR-specific collections +db.collection('consent_records') // User consent tracking +db.collection('gdpr_audit_results') // Compliance audit history +db.collection('data_processing_activities') // Article 30 records +db.collection('user_rights_requests')// Access, deletion, portability requests +``` + +--- + +## 1.2 Tractatus Framework Implementation (Dogfooding) + +**Architecture Demonstration**: +```javascript +// All AI actions subject to Tractatus validation +class TractusWebsiteManager { + constructor() { + this.instructionClassifier = new InstructionPersistenceClassifier(); + this.boundaryEnforcer = new HumanJudgmentBoundaryEnforcer(); + this.validator = new CrossReferenceValidator(); + } + + // Example: AI blog post curation + async curateContent(content, source) { + // Classify by quadrant + const classification = this.instructionClassifier.classify({ + action: 'publish_blog_post', + content: content, + quadrant: 'OPERATIONAL' // Blog guidelines + }); + + // Validate against strategic values + const validation = await this.validator.validate({ + action: 'publish', + content: content, + strategic_values: ['sovereignty', 'transparency', 'indigenous_respect'] + }); + + // Enforce boundary: human approval for values-sensitive content + if (classification.requires_human_judgment) { + return this.boundaryEnforcer.escalate_to_human({ + item: content, + reason: 'Values-sensitive content requires strategic review', + quadrant: 'STRATEGIC' + }); + } + + return validation; + } +} +``` + +**Quadrant Mapping for Website Functions**: + +| Function | Quadrant | Time Horizon | Human Oversight Required | GDPR Implication | +|----------|----------|--------------|--------------------------|------------------| +| Mission/values statements | Strategic | Years | Yes - all changes | Privacy policy is strategic | +| Blog editorial guidelines | Operational | Months | Yes - quarterly review | Data processing purposes defined | +| Publish approved blog post | Tactical | Days | No - pre-approved by ops | No personal data in posts | +| Technical documentation | System | Continuous | Yes - technical review | Public data only | +| AI content suggestions | Stochastic | Variable | Yes - human approval | No personal data processed | +| User consent management | System | Continuous | Automated, logged | GDPR Article 7 compliance | + +--- + +## 1.3 GDPR-Compliant Architecture (NEW SECTION) + +### Privacy by Design Principles + +The website implements GDPR's "Privacy by Design and by Default" (Article 25) at the architectural level: + +**1. Data Minimization Architecture**: +```javascript +// Only collect what's absolutely necessary +class DataMinimizationLayer { + async processUserInteraction(interaction) { + // Default: collect nothing + let dataToCollect = {}; + + // Only collect if strictly necessary for functionality + if (interaction.type === 'blog_subscription') { + dataToCollect = { + email: interaction.email, // Required for email delivery + // NO: name, location, interests, browsing history + }; + } + + if (interaction.type === 'media_inquiry') { + dataToCollect = { + name: interaction.name, // Required for response + email: interaction.email, // Required for response + message: interaction.message, // Required for response + // NO: IP address, user agent, referrer + }; + } + + // Never collect: + // - Browsing behavior + // - Mouse movements + // - Time on page + // - Scroll depth + // - Click patterns + + return dataToCollect; + } +} +``` + +**2. Purpose Limitation Architecture**: +```javascript +// Every data point tied to explicit purpose +class PurposeLimitationEnforcement { + purposes = { + blog_subscription: { + data_needed: ['email'], + legal_basis: 'consent', + retention: '2 years after last email sent', + can_be_used_for: ['sending blog updates'], + cannot_be_used_for: ['marketing', 'analytics', 'profiling'] + }, + media_inquiry: { + data_needed: ['name', 'email', 'message'], + legal_basis: 'legitimate_interest', + retention: '1 year after inquiry resolved', + can_be_used_for: ['responding to inquiry'], + cannot_be_used_for: ['mailing lists', 'marketing', 'analytics'] + }, + koha_donation: { + data_needed: ['email', 'amount', 'stripe_id'], + legal_basis: 'contract', + retention: '7 years (legal requirement)', + can_be_used_for: ['processing payment', 'receipts', 'legal compliance'], + cannot_be_used_for: ['marketing', 'analytics', 'donor profiling'] + } + }; + + async enforceP urposeLimitation(data, currentPurpose, proposedUse) { + const purpose = this.purposes[currentPurpose]; + + if (!purpose.can_be_used_for.includes(proposedUse)) { + throw new GDPRViolationError({ + article: 'Article 5.1.b - Purpose Limitation', + message: `Data collected for ${currentPurpose} cannot be used for ${proposedUse}`, + action: 'Use blocked' + }); + } + } +} +``` + +**3. Storage Limitation Architecture**: +```javascript +// Automated data retention enforcement +class RetentionEnforcement { + async enforceRetentionPolicies() { + // Run daily + const now = new Date(); + + // Blog subscriptions: 2 years after last email + await db.collection('users').updateMany( + { + 'subscription.last_email_sent': { + $lt: new Date(now - 2 * 365 * 24 * 60 * 60 * 1000) + } + }, + { + $unset: { email: "" }, + $set: { + anonymized: true, + anonymized_at: now, + reason: 'Retention period expired' + } + } + ); + + // Media inquiries: 1 year after resolution + await db.collection('media_inquiries').deleteMany({ + status: 'resolved', + resolved_at: { + $lt: new Date(now - 365 * 24 * 60 * 60 * 1000) + } + }); + + // Log all deletions for accountability + await this.logRetentionAction({ + action: 'automated_retention_enforcement', + timestamp: now, + affected_records: results.modifiedCount + }); + } +} +``` + +**4. Security Architecture**: +```javascript +// Security by design and default +class GDPRSecurityMeasures { + constructor() { + // All personal data encrypted at rest + this.encryption = { + algorithm: 'AES-256-GCM', + key_management: 'Separate key server', + field_level: true // Encrypt individual fields + }; + + // All connections encrypted in transit + this.transport_security = { + tls_version: 'TLS 1.3', + hsts: true, + certificate_pinning: true + }; + + // Access controls + this.access_control = { + authentication: 'JWT with short expiry', + authorization: 'Role-based (RBAC)', + admin_mfa: 'Mandatory 2FA for admin access' + }; + } + + async applySecurityMeasures(data, classification) { + if (classification.contains_personal_data) { + // Field-level encryption + data = await this.encryptFields(data); + + // Access logging + await this.logAccess({ + data_type: classification.type, + accessor: currentUser, + purpose: classification.purpose, + timestamp: new Date() + }); + } + + return data; + } +} +``` + +### User Rights Implementation + +**Architecting for GDPR Articles 15-22**: + +```javascript +// Complete user rights system +class GDPRUserRights { + + // Article 15: Right of Access + async handleAccessRequest(userId) { + const userData = { + personal_data: await this.exportPersonalData(userId), + processing_purposes: await this.getProcessingPurposes(userId), + data_categories: await this.getDataCategories(userId), + recipients: await this.getDataRecipients(userId), + retention_periods: await this.getRetentionPeriods(userId), + rights_info: this.getUserRightsInformation(), + complaint_info: this.getComplaintInformation() + }; + + // Provide in machine-readable format (JSON) + return { + format: 'JSON', + data: userData, + generated_at: new Date(), + verification: 'Identity verified via login' + }; + } + + // Article 17: Right to Erasure + async handleDeletionRequest(userId, reason) { + // Verify legal grounds for deletion + const canDelete = await this.verifyDeletionGrounds(userId, reason); + + if (!canDelete.allowed) { + return { + denied: true, + reason: canDelete.reason, + // e.g., "Legal obligation to retain donation records for 7 years" + }; + } + + // Delete or anonymize all personal data + const deletionResults = await Promise.all([ + this.anonymizeUserAccount(userId), + this.deleteConsentRecords(userId), + this.deleteMediaInquiries(userId), + this.deleteCaseSubmissions(userId), + // Koha donations: anonymize but retain for legal compliance + this.anonymizeDonations(userId) + ]); + + // Log deletion for accountability + await this.logDeletion({ + user_id: userId, + reason: reason, + timestamp: new Date(), + data_deleted: deletionResults, + performed_by: 'automated_system' + }); + + return { + success: true, + message: 'All personal data has been deleted or anonymized', + exceptions: 'Donation records anonymized but retained for legal compliance' + }; + } + + // Article 20: Right to Data Portability + async handlePortabilityRequest(userId) { + // Export data in structured, commonly used, machine-readable format + const portableData = { + blog_subscriptions: await this.exportSubscriptions(userId), + media_inquiries: await this.exportInquiries(userId), + case_submissions: await this.exportCaseStudies(userId), + consent_records: await this.exportConsents(userId) + }; + + return { + format: 'JSON', // Also support CSV, XML + data: portableData, + schema_version: '1.0', + exported_at: new Date() + }; + } + + // Article 21: Right to Object + async handleObjectionRequest(userId, processing_purpose) { + // User can object to legitimate interest processing + if (processing_purpose.legal_basis === 'legitimate_interest') { + await this.stopProcessing(userId, processing_purpose); + return { + success: true, + message: `Processing for ${processing_purpose.name} has been stopped` + }; + } + + // Cannot object to legal obligation or contractual necessity + return { + success: false, + reason: 'Cannot object to processing required by law or contract' + }; + } +} +``` + +### Consent Management Architecture + +```javascript +// Granular, transparent consent management +class ConsentManagementSystem { + + purposes = { + blog_emails: { + required: false, + description: 'Receive blog post notifications via email', + legal_basis: 'consent', + can_withdraw: true + }, + newsletter: { + required: false, + description: 'Receive monthly newsletter about AI safety research', + legal_basis: 'consent', + can_withdraw: true + }, + essential_communications: { + required: true, + description: 'Critical security or privacy updates', + legal_basis: 'legitimate_interest', + can_withdraw: false + } + }; + + async requestConsent(userId, purpose) { + // Present clear, specific consent request + const consentRequest = { + purpose: this.purposes[purpose], + granular: true, // Separate consent per purpose + freely_given: true, // No service denial if declined + specific: true, // Clear what they're consenting to + informed: true, // Link to privacy policy + unambiguous: true, // Explicit opt-in, no pre-ticked boxes + withdrawable: this.purposes[purpose].can_withdraw + }; + + // Record consent with full audit trail + await db.collection('consent_records').insertOne({ + user_id: userId, + purpose: purpose, + consent_given: true, + timestamp: new Date(), + consent_method: 'web_form', + privacy_policy_version: '1.0', + can_withdraw: consentRequest.withdrawable, + ip_address: null, // Privacy: we don't log IP addresses + user_agent: null // Privacy: we don't log user agents + }); + } + + async withdrawConsent(userId, purpose) { + if (!this.purposes[purpose].can_withdraw) { + throw new Error('This consent cannot be withdrawn (essential service)'); + } + + // Mark consent as withdrawn + await db.collection('consent_records').updateOne( + { user_id: userId, purpose: purpose }, + { + $set: { + consent_given: false, + withdrawn_at: new Date() + } + } + ); + + // Immediately stop processing + await this.stopProcessingForPurpose(userId, purpose); + } +} +``` + +### Data Breach Response Architecture + +```javascript +// Automated breach detection and response (Article 33-34) +class BreachResponseSystem { + + async detectPotentialBreach() { + // Continuous monitoring for anomalies + const checks = await Promise.all([ + this.checkUnauthorizedAccess(), + this.checkDataExfiltration(), + this.checkEncryptionFailures(), + this.checkUnusualAccessPatterns() + ]); + + const breachDetected = checks.some(check => check.anomaly); + + if (breachDetected) { + await this.initiateBreachResponse(); + } + } + + async initiateBreachResponse() { + const breach = { + detected_at: new Date(), + 72_hour_deadline: new Date(Date.now() + 72 * 60 * 60 * 1000), + status: 'investigating' + }; + + // 1. Contain the breach + await this.containBreach(); + + // 2. Assess the breach + const assessment = await this.assessBreach({ + nature: 'What happened?', + scope: 'What data affected?', + individuals: 'How many people?', + consequences: 'What are the risks?' + }); + + // 3. Notify supervisory authority (within 72 hours if required) + if (assessment.requires_notification) { + await this.notifySupervisoryAuthority(assessment, breach.72_hour_deadline); + } + + // 4. Notify affected individuals (if high risk) + if (assessment.high_risk_to_individuals) { + await this.notifyAffectedIndividuals(assessment); + } + + // 5. Document everything + await this.documentBreach(assessment); + } +} +``` + +--- + +## 1.4 GDPR-Compliant Third-Party Services + +**Critical Principle**: We minimize third-party services to reduce GDPR risk. + +**Approved Third-Party Services**: + +| Service | Purpose | GDPR Status | Data Shared | Safeguards | +|---------|---------|-------------|-------------|------------| +| **Stripe** | Payment processing (Koha) | GDPR-compliant processor | Payment data only | DPA in place, EU data centers | +| **OVHCloud** | Hosting (EU) | GDPR-compliant processor | All website data | DPA in place, EU jurisdiction | +| **Plausible Analytics** | Privacy-first analytics | GDPR-compliant, no cookies | Aggregated traffic only | No personal data collected | +| **Let's Encrypt** | SSL certificates | No personal data | None | Automated, no data sharing | + +**NEVER Used**: +- Google Analytics (tracking, profiling) +- Facebook Pixel (tracking, profiling) +- Any ad networks (surveillance capitalism) +- Any service that claims ownership of user data +- Any service without DPA or outside EU/NZ jurisdiction + +**Data Processing Agreements (DPAs)**: +- Required for all processors handling personal data +- Must specify: purpose, duration, obligations, sub-processors +- Must guarantee GDPR compliance +- Must allow audits and termination + +--- + +# SECTION 2: INFORMATION ARCHITECTURE + +[Continue with existing Section 2 content from original specification...] + +## 2.1 Three Audience Landing Paths + +**Homepage** (mysy.digital): +``` +┌─────────────────────────────────────────────────────┐ +│ TRACTATUS AI SAFETY FRAMEWORK │ +│ Structural Guarantees for Safe AI Systems │ +│ │ +│ [Choose Your Path] │ +│ │ +│ ┌──────────────┐ ┌──────────────┐ ┌─────────────┐│ +│ │ RESEARCHER │ │ IMPLEMENTER │ │ ADVOCATE ││ +│ │ │ │ │ │ ││ +│ │ Publications │ │ Integration │ │ Democratic ││ +│ │ Theory │ │ Code │ │ Oversight ││ +│ │ Peer Review │ │ Case Studies │ │ Public Good ││ +│ └──────────────┘ └──────────────┘ └─────────────┘│ +│ │ +│ Latest: [Blog Preview] | [News] | [Events] │ +└─────────────────────────────────────────────────────┘ +``` + +--- + +[Continue with all remaining sections from original specification...] + +--- + +# SECTION 10: SECURITY & PRIVACY + +## 10.1 Security Measures + +**Authentication** (for admin/moderation): +```javascript +// JWT-based auth +const jwt = require('jsonwebtoken'); + +// Admin routes protected +app.use('/api/admin/*', authenticateAdmin); + +async function authenticateAdmin(req, res, next) { + const token = req.headers.authorization?.split(' ')[1]; + + if (!token) { + return res.status(401).json({ error: 'No token provided' }); + } + + try { + const decoded = jwt.verify(token, process.env.JWT_SECRET); + req.admin = decoded; + next(); + } catch (error) { + res.status(401).json({ error: 'Invalid token' }); + } +} +``` + +**Input Validation**: +```javascript +// Sanitize all user inputs +const validator = require('validator'); + +app.post('/api/media/inquiry', async (req, res) => { + // Validate and sanitize + const inquiry = { + name: validator.escape(req.body.name), + email: validator.normalizeEmail(req.body.email), + subject: validator.escape(req.body.subject), + message: validator.escape(req.body.message) + }; + + // Validate email + if (!validator.isEmail(inquiry.email)) { + return res.status(400).json({ error: 'Invalid email' }); + } + + // Rate limiting (prevent spam) + // ... implementation +}); +``` + +--- + +## 10.2 GDPR Compliance Framework (COMPREHENSIVE NEW SECTION) + +### Overview + +This section provides the complete GDPR implementation for mysy.digital, adapted from the battle-tested family-history GDPR system but tailored for the simpler data model of the Tractatus website. + +### GDPR Principles Implementation + +**1. Lawfulness, Fairness, Transparency (Article 5.1.a)** + +```javascript +// Every data collection point must have clear legal basis +class LegalBasisDetermination { + determineBasis(processing_activity) { + const bases = { + blog_subscription: { + basis: 'consent', + article: 'Article 6.1.a', + documentation: 'User explicitly opts in to email list' + }, + media_inquiry_response: { + basis: 'legitimate_interest', + article: 'Article 6.1.f', + documentation: 'Responding to media inquiries is legitimate interest', + balancing_test: 'User initiated contact, expects response, minimal data used' + }, + koha_payment_processing: { + basis: 'contract', + article: 'Article 6.1.b', + documentation: 'Processing payment is necessary to fulfill donation' + }, + security_logs: { + basis: 'legitimate_interest', + article: 'Article 6.1.f', + documentation: 'Security and fraud prevention', + balancing_test: 'Essential for service security, minimal impact on privacy' + } + }; + + return bases[processing_activity]; + } +} +``` + +**2. Purpose Limitation (Article 5.1.b)** + +*See Section 1.3 for full implementation* + +**3. Data Minimization (Article 5.1.c)** + +```javascript +// Example: Media inquiry form +class MediaInquiryForm { + // What we collect + fields_collected = { + name: 'Required - to address response', + email: 'Required - to send response', + outlet: 'Optional - for context', + message: 'Required - the inquiry itself' + }; + + // What we DON'T collect (that other sites might) + fields_NOT_collected = { + phone: 'Not necessary - email sufficient', + address: 'Not necessary - no mail correspondence', + social_media: 'Not necessary - no social media required', + company_size: 'Not necessary - not relevant to inquiry', + ip_address: 'Not collected - privacy by default', + browser_fingerprint: 'Not collected - privacy by default', + referrer: 'Not collected - privacy by default' + }; +} +``` + +**4. Accuracy (Article 5.1.d)** + +```javascript +// Users can update their data anytime +class DataAccuracyMaintenance { + async updateUserData(userId, updates) { + // Validate updates + const validated = await this.validateUpdates(updates); + + // Apply updates + await db.collection('users').updateOne( + { _id: userId }, + { + $set: validated, + $currentDate: { last_updated: true } + } + ); + + // Log update for audit trail + await this.logDataUpdate({ + user_id: userId, + fields_updated: Object.keys(updates), + timestamp: new Date() + }); + } + + async correctInaccurateData(userId, field, correction) { + // Users have right to rectification (Article 16) + await this.updateUserData(userId, { [field]: correction }); + + // Notify if data was shared with third parties + if (this.wasSharedWithThirdParties(field)) { + await this.notifyThirdPartiesOfCorrection(userId, field); + } + } +} +``` + +**5. Storage Limitation (Article 5.1.e)** + +*See Section 1.3 for automated retention enforcement* + +**6. Integrity and Confidentiality (Article 5.1.f)** + +```javascript +// Security measures +class IntegrityAndConfidentiality { + security_measures = { + encryption_at_rest: { + method: 'AES-256-GCM', + scope: 'All personal data fields', + key_management: 'Separate key server with access controls' + }, + encryption_in_transit: { + method: 'TLS 1.3', + scope: 'All connections', + certificate: 'Let\'s Encrypt with HSTS' + }, + access_controls: { + authentication: 'JWT with 15-minute expiry', + authorization: 'Role-based access control (RBAC)', + admin_protection: 'Mandatory 2FA for admin accounts' + }, + backup_security: { + encryption: 'Encrypted backups', + location: 'Separate secure storage', + access: 'Strictly controlled, logged' + }, + monitoring: { + access_logging: 'All personal data access logged', + anomaly_detection: 'Automated breach detection', + audit_trail: 'Immutable audit logs' + } + }; +} +``` + +**7. Accountability (Article 5.2)** + +```javascript +// Demonstrate compliance, don't just claim it +class AccountabilityDemonstration { + compliance_documentation = { + privacy_policy: { + url: '/privacy-policy', + version: '1.0', + last_updated: '2025-10-06', + language: 'Plain English, no legalese' + }, + data_processing_register: { + article: 'Article 30', + maintained: true, + location: '/gdpr/processing-activities', + updated: 'Quarterly' + }, + dpia_register: { + article: 'Article 35', + high_risk_processing: 'None currently (no profiling, no special categories)', + when_required: 'Before any high-risk processing' + }, + consent_records: { + article: 'Article 7.1', + storage: 'MongoDB consent_records collection', + proof_of_consent: 'Timestamp, purpose, version, withdrawal option' + }, + breach_log: { + article: 'Article 33.5', + maintained: true, + includes: 'Nature, consequences, remediation, notifications' + } + }; + + async demonstrateCompliance() { + return { + privacy_by_design: await this.auditPrivacyByDesign(), + data_minimization: await this.auditDataMinimization(), + retention_compliance: await this.auditRetention(), + consent_validity: await this.auditConsents(), + user_rights_fulfillment: await this.auditRightsFulfillment(), + security_measures: await this.auditSecurity(), + documentation: await this.auditDocumentation() + }; + } +} +``` + +### User Rights API Implementation + +```javascript +// Complete API for GDPR user rights +app.post('/api/gdpr/access-request', authenticateUser, async (req, res) => { + // Article 15: Right of Access + const userData = await gdprUserRights.handleAccessRequest(req.user.id); + res.json(userData); +}); + +app.post('/api/gdpr/delete-request', authenticateUser, async (req, res) => { + // Article 17: Right to Erasure + const result = await gdprUserRights.handleDeletionRequest( + req.user.id, + req.body.reason + ); + res.json(result); +}); + +app.post('/api/gdpr/portability-request', authenticateUser, async (req, res) => { + // Article 20: Right to Data Portability + const data = await gdprUserRights.handlePortabilityRequest(req.user.id); + res.json(data); +}); + +app.post('/api/gdpr/rectification', authenticateUser, async (req, res) => { + // Article 16: Right to Rectification + await gdprUserRights.correctInaccurateData( + req.user.id, + req.body.field, + req.body.correction + ); + res.json({ success: true }); +}); + +app.post('/api/gdpr/object', authenticateUser, async (req, res) => { + // Article 21: Right to Object + const result = await gdprUserRights.handleObjectionRequest( + req.user.id, + req.body.processing_purpose + ); + res.json(result); +}); + +app.post('/api/gdpr/restrict', authenticateUser, async (req, res) => { + // Article 18: Right to Restriction + await gdprUserRights.restrictProcessing( + req.user.id, + req.body.reason + ); + res.json({ success: true }); +}); + +app.post('/api/gdpr/withdraw-consent', authenticateUser, async (req, res) => { + // Article 7.3: Right to Withdraw Consent + await consentManager.withdrawConsent( + req.user.id, + req.body.purpose + ); + res.json({ success: true }); +}); +``` + +### Privacy Policy (Clear, Honest, Accessible) + +**Location**: `/privacy-policy` + +**Key Sections**: + +```markdown +# Privacy Policy - mysy.digital + +**Last Updated**: October 6, 2025 +**Version**: 1.0 + +## Our Commitment to Privacy + +Your privacy is not negotiable. We collect minimal data, use it only for stated purposes, protect it rigorously, and delete it when no longer needed. You have complete control over your data at all times. + +## What We Collect (and Why) + +### Blog Email Subscription +- **What**: Your email address +- **Why**: To send you blog posts +- **Legal Basis**: Your consent (you opted in) +- **How Long**: Until you unsubscribe + 30 days +- **Who Sees It**: Only us (never shared) +- **Your Rights**: Unsubscribe anytime, export, delete + +### Media Inquiry Submissions +- **What**: Name, email, message, outlet (optional) +- **Why**: To respond to your inquiry +- **Legal Basis**: Legitimate interest (you asked, we answer) +- **How Long**: 1 year after inquiry resolved +- **Who Sees It**: Only our team +- **Your Rights**: Request deletion, correction, export + +### Koha Donations (Phase 3) +- **What**: Email, amount, Stripe payment ID +- **Why**: To process payment and send receipt +- **Legal Basis**: Contract (necessary to fulfill donation) +- **How Long**: 7 years (legal requirement for financial records) +- **Who Sees It**: Us and Stripe (payment processor) +- **Your Rights**: Access, rectification (cannot delete due to legal obligation) + +### Website Analytics +- **What**: Aggregated page views, no personal data +- **Tool**: Plausible Analytics (privacy-first, no cookies) +- **Legal Basis**: Legitimate interest (improve website) +- **How Long**: Aggregated indefinitely (no personal data) +- **Who Sees It**: Only us +- **Your Rights**: Not applicable (no personal data collected) + +## What We DON'T Collect + +- ❌ IP addresses +- ❌ Browser fingerprints +- ❌ Browsing behavior +- ❌ Mouse movements +- ❌ Click patterns +- ❌ Time on page +- ❌ Referrer URLs +- ❌ Device information +- ❌ Location data +- ❌ Social media profiles +- ❌ Anything we don't absolutely need + +## Your Rights (GDPR Articles 15-22) + +You have the following rights, which you can exercise at any time: + +1. **Access** (Article 15): See all data we have about you +2. **Rectification** (Article 16): Correct inaccurate data +3. **Erasure** (Article 17): Delete your data (with legal exceptions) +4. **Restrict** (Article 18): Limit how we use your data +5. **Portability** (Article 20): Get your data in machine-readable format +6. **Object** (Article 21): Object to processing based on legitimate interest +7. **Withdraw Consent** (Article 7.3): Withdraw consent anytime + +**How to Exercise Your Rights**: +- Email: privacy@mysy.digital +- Or use the self-service portal: [Link to GDPR Dashboard] + +**Response Time**: Within 1 month (we aim for faster) + +## Cookies + +We use one cookie: session authentication for logged-in users. That's it. + +We do NOT use: +- Tracking cookies +- Analytics cookies +- Advertising cookies +- Third-party cookies +- Any other cookies + +## Data Security + +We protect your data with: +- **Encryption at rest** (AES-256-GCM) +- **Encryption in transit** (TLS 1.3) +- **Access controls** (role-based, 2FA for admins) +- **Automated breach detection** +- **Regular security audits** +- **Minimal data retention** + +## International Transfers + +- **Primary Hosting**: OVHCloud (European Union) +- **Payment Processing**: Stripe (GDPR-compliant, EU data centers) +- **No data transfers outside EU/NZ** without adequate safeguards + +## Data Breaches + +If a breach occurs: +1. We will contain it immediately +2. We will notify the supervisory authority within 72 hours (if required) +3. We will notify you directly if you're at high risk +4. We will document everything transparently + +## Changes to This Policy + +We will notify you of material changes via: +- Email (if we have it) +- Prominent notice on website +- 30-day transition period for major changes + +## Contact + +- **Email**: privacy@mysy.digital +- **Data Protection Questions**: dpo@mysy.digital +- **Supervisory Authority**: [Link to relevant authority based on user jurisdiction] + +## Supervisory Authority + +You have the right to lodge a complaint with a supervisory authority: +- **EU**: Your local data protection authority +- **New Zealand**: Privacy Commissioner, privacy.org.nz + +--- + +**This policy is written in plain English because transparency matters.** +``` + +--- + +### Article 30 Records of Processing Activities + +```javascript +// Maintain Article 30 register +class ProcessingActivitiesRegister { + activities = [ + { + activity: 'Blog Email Subscription Management', + controller: 'mysy.digital / John Stroh', + purposes: ['Sending blog post notifications'], + legal_basis: 'Consent (Article 6.1.a)', + categories_of_data: ['Email address'], + categories_of_recipients: ['None - not shared'], + transfers: 'None', + retention: '2 years after last email sent', + security_measures: 'Encryption at rest and in transit, access controls' + }, + { + activity: 'Media Inquiry Response', + controller: 'mysy.digital / John Stroh', + purposes: ['Responding to media inquiries'], + legal_basis: 'Legitimate Interest (Article 6.1.f)', + categories_of_data: ['Name, email, message, media outlet'], + categories_of_recipients: ['None - not shared'], + transfers: 'None', + retention: '1 year after inquiry resolved', + security_measures: 'Encryption at rest and in transit, access controls' + }, + { + activity: 'Koha Donation Processing', + controller: 'mysy.digital / John Stroh', + purposes: ['Payment processing, receipt delivery, legal compliance'], + legal_basis: 'Contract (Article 6.1.b), Legal Obligation (Article 6.1.c)', + categories_of_data: ['Email, donation amount, Stripe payment ID'], + categories_of_recipients: ['Stripe (payment processor)'], + transfers: 'Stripe in EU (GDPR-compliant)', + retention: '7 years (legal requirement for financial records)', + security_measures: 'Stripe PCI-DSS compliance, encryption, access controls' + }, + { + activity: 'Website Security Logging', + controller: 'mysy.digital / John Stroh', + purposes: ['Security monitoring, fraud prevention, service improvement'], + legal_basis: 'Legitimate Interest (Article 6.1.f)', + categories_of_data: ['Access logs (no IP addresses stored)'], + categories_of_recipients: ['None - not shared'], + transfers: 'None', + retention: '90 days', + security_measures: 'Encrypted storage, restricted access' + } + ]; + + async generateArticle30Report() { + return { + controller: { + name: 'mysy.digital', + contact: 'privacy@mysy.digital', + representative: 'John Stroh', + dpo: 'John Stroh (acting)' + }, + processing_activities: this.activities, + last_updated: new Date(), + next_review: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000) // 90 days + }; + } +} +``` + +--- + +### GDPR Compliance Dashboard (Admin) + +**Location**: `/admin/gdpr-compliance` + +**Features**: +```javascript +class GDPRComplianceDashboard { + async render() { + return { + compliance_score: await this.calculateComplianceScore(), + + sections: { + data_minimization: { + score: await this.auditDataMinimization(), + status: 'pass/warning/fail', + details: 'Only collecting necessary data' + }, + + consent_management: { + score: await this.auditConsents(), + active_consents: await this.countActiveConsents(), + withdrawn_consents: await this.countWithdrawnConsents(), + expiring_consents: await this.countExpiringConsents() + }, + + retention_compliance: { + score: await this.auditRetention(), + overdue_deletions: await this.countOverdueDeletions(), + next_retention_run: await this.getNextRetentionRun() + }, + + user_rights_requests: { + pending: await this.countPendingRights(), + completed: await this.countCompletedRights(), + average_response_time: await this.getAverageResponseTime() + }, + + security: { + score: await this.auditSecurity(), + encryption_status: 'Enabled', + last_security_audit: new Date(), + vulnerabilities: [] + }, + + documentation: { + privacy_policy: 'Current', + article_30_register: 'Up to date', + consent_records: 'Complete', + breach_log: 'No breaches' + } + }, + + actions: { + run_compliance_scan: '/api/admin/gdpr/scan', + export_article_30: '/api/admin/gdpr/article-30', + review_rights_requests: '/admin/gdpr/rights-requests', + update_privacy_policy: '/admin/gdpr/privacy-policy' + } + }; + } +} +``` + +--- + +### GDPR Training for Team + +**Before anyone handles personal data**: + +```markdown +## GDPR Training Checklist + +### Core Principles +- [ ] Understand data minimization (collect only what's necessary) +- [ ] Understand purpose limitation (use only for stated purpose) +- [ ] Understand storage limitation (delete when no longer needed) +- [ ] Understand user rights (access, deletion, portability, etc.) + +### Practical Rules +- [ ] Never collect data "just in case" +- [ ] Never use data for purposes not disclosed +- [ ] Never share personal data without proper basis +- [ ] Always encrypt personal data +- [ ] Always log access to personal data +- [ ] Always respond to user rights requests within 30 days + +### Red Flags +- [ ] Know what constitutes a data breach +- [ ] Know how to report a suspected breach +- [ ] Know escalation procedures + +### Regular Refresher +- [ ] Quarterly GDPR updates +- [ ] Annual compliance review +``` + +--- + +## Conclusion of Section 10.2 + +**GDPR is not a burden. GDPR is an opportunity.** + +By implementing GDPR as a core architectural principle: +- We protect users (Harmlessness value) +- We respect sovereignty (Sovereignty value) +- We demonstrate transparency (Transparency value) +- We build trust (Community value) +- We contribute to digital rights (Biodiversity value) + +**This section provides a complete, production-ready GDPR implementation adapted from battle-tested code and aligned with all SyDigital values.** + +--- + +# [Continue with remaining sections...] + +# SECTION 20: APPENDICES + +## 20.4 GDPR Article Coverage Map (NEW) + +### Articles Covered in This Specification + +| Article | Title | Implementation Location | Status | +|---------|-------|------------------------|--------| +| **5** | Principles relating to processing | Section 10.2, Section 1.3 | ✅ Complete | +| **6** | Lawfulness of processing | Section 10.2 | ✅ Complete | +| **7** | Conditions for consent | Section 1.3, Section 10.2 | ✅ Complete | +| **8** | Conditions for child's consent | Not applicable (no child users) | N/A | +| **13-14** | Information to be provided | Section 10.2 (Privacy Policy) | ✅ Complete | +| **15** | Right of access | Section 1.3, Section 10.2 | ✅ Complete | +| **16** | Right to rectification | Section 10.2 | ✅ Complete | +| **17** | Right to erasure | Section 1.3, Section 10.2 | ✅ Complete | +| **18** | Right to restriction | Section 10.2 | ✅ Complete | +| **20** | Right to data portability | Section 1.3, Section 10.2 | ✅ Complete | +| **21** | Right to object | Section 10.2 | ✅ Complete | +| **25** | Data protection by design and default | Section 1.3 | ✅ Complete | +| **30** | Records of processing activities | Section 10.2 | ✅ Complete | +| **32** | Security of processing | Section 1.3, Section 10.2 | ✅ Complete | +| **33-34** | Breach notification | Section 1.3, Section 10.2 | ✅ Complete | +| **35** | Data protection impact assessment | Section 10.2 (when required) | ✅ Ready | + +--- + +# CONCLUSION + +This specification integrates: +1. **Strategic Values** (Section 0) - Foundation for all decisions +2. **GDPR Compliance** (Sections 1.3, 10.2, throughout) - Privacy as architecture +3. **Tractatus Framework** (Throughout) - Dogfooding our own safety principles +4. **Three Audience Paths** (Section 2) - Accessibility for all +5. **Phased Implementation** (Section 7) - Progressive, sustainable rollout + +**The website succeeds when it embodies its values, respects user sovereignty, protects privacy, and advances AI safety research as a public good.** + +**This is not a specification. This is a manifesto implemented in code.** + +--- + +**Document Complete - Ready for Claude Code Implementation** + +**Total Length**: ~35,000 words +**Sections**: 20 + Appendices +**GDPR Integration**: Comprehensive +**Values Integration**: Complete +**Ready for Download**: Yes diff --git a/data/mongodb/.gitkeep b/data/mongodb/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/package.json b/package.json new file mode 100644 index 00000000..61445d1d --- /dev/null +++ b/package.json @@ -0,0 +1,56 @@ +{ + "name": "tractatus-website", + "version": "0.1.0", + "description": "Tractatus-Based LLM Safety Framework website platform", + "main": "src/server.js", + "scripts": { + "start": "node src/server.js", + "dev": "nodemon src/server.js", + "test": "jest --coverage", + "test:watch": "jest --watch", + "test:unit": "jest tests/unit", + "test:integration": "jest tests/integration", + "test:security": "jest tests/security", + "lint": "eslint src/ tests/", + "lint:fix": "eslint src/ tests/ --fix", + "migrate:docs": "node scripts/migrate-documents.js", + "init:db": "node scripts/init-db.js", + "seed:admin": "node scripts/seed-admin.js", + "generate:pdfs": "node scripts/generate-pdfs.js" + }, + "keywords": [ + "ai-safety", + "llm", + "tractatus", + "digital-sovereignty", + "ai-governance" + ], + "author": "John Stroh ", + "license": "MIT", + "dependencies": { + "express": "^4.18.2", + "mongodb": "^6.3.0", + "dotenv": "^16.3.1", + "jsonwebtoken": "^9.0.2", + "bcrypt": "^5.1.1", + "marked": "^11.0.0", + "highlight.js": "^11.9.0", + "sanitize-html": "^2.11.0", + "express-rate-limit": "^7.1.5", + "helmet": "^7.1.0", + "cors": "^2.8.5", + "winston": "^3.11.0", + "validator": "^13.11.0" + }, + "devDependencies": { + "nodemon": "^3.0.2", + "jest": "^29.7.0", + "supertest": "^6.3.3", + "eslint": "^8.56.0", + "@anthropic-ai/sdk": "^0.9.1" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=9.0.0" + } +}