import { AcademyLesson } from './types';

export const ACADEMY_CURRICULUM: AcademyLesson[] = [
  {
    id: 'orientation',
    moduleNumber: 1,
    title: 'Welcome to the Factory Floor',
    subtitle: 'Orientation',
    description: 'What is The Hearth, why does it exist, and what makes it different from every other code generator you\'ve seen?',
    tesaOutfit: 'Black blazer, white silk blouse, hair down — first day energy',
    tesaQuote: 'Welcome to my factory. The lights are off because I don\'t need them. Shall we begin?',
    duration: '25 min',
    difficulty: 'beginner',
    prerequisites: [],
    learningObjectives: [
      'Understand The Hearth\'s origin and philosophy',
      'Explain the difference between code generation and autonomous software engineering',
      'Identify the 7 agent species and their roles',
      'Describe the "humans at the edges" principle',
    ],
    sections: [
      {
        id: 'origin',
        title: 'Why "The Hearth"?',
        content: `The name comes from manufacturing — a \"dark factory\" is a facility so automated it runs with the lights off. No humans on the floor.\n\nMost code generators are glorified autocomplete. You type half a function, they guess the rest. That\'s not a factory — that\'s a spell checker with ambition.\n\nThe The Hearth is different. You hand it a specification — \"build me a CRM with role-based access and Stripe integration\" — and it plans, builds, reviews, tests, secures, and deploys the entire thing. Autonomously. You only show up to say \"go\" and \"looks good.\"`,
        tesaNote: 'I didn\'t build this to replace developers. I built it because the best developers I know are bored out of their minds writing CRUD for the 10,000th time. This frees them to do the interesting work.',
      },
      {
        id: 'factorio-principle',
        title: 'The Factorio Principle',
        content: `The architecture draws directly from the Factorio gaming community\'s \"megabase\" design philosophy:\n\n1. **Humans at the edges only** — you specify goals and validate output\n2. **Single-threaded harnesses** — each agent does ONE thing, perfectly\n3. **Parallel execution** — multiple agents of the same species run simultaneously\n4. **Self-correction** — failures loop back, not up to you\n5. **Continuous optimization** — the factory improves itself every cycle\n\nThis isn\'t a metaphor. It\'s the literal architecture.`,
        diagram: 'HUMAN → [Goal] → FOREMAN TESA → [Plan|Build|Review|Test|Optimize|Secure|Deploy] → HUMAN → [Approve]',
      },
      {
        id: 'species',
        title: 'The Seven Species',
        content: `Every agent in The Hearth belongs to a species. Species never cross-pollinate — a Builder never reviews its own code.\n\n| Species | Role | What It Does |\n|---------|------|-------------|\n| **Foreman** | Architect | Decomposes goals, delegates, self-corrects |\n| **Planner** | Prompt Engineer | Raw specs → architecture briefs |\n| **Builder** | Code Engineer | Architecture → production code |\n| **Inspector** | Review Agent | Code quality ≥ 97% or it loops back |\n| **Tester** | QA Agent | Tests, field walks, backend validation |\n| **Optimizer** | Optimizer | A/B experiments, metric improvement |\n| **Sentinel** | Security | OWASP scanning, threat monitoring |\n| **Deployer** | Release | Packaging, CI/CD, rollbacks |`,
        tesaNote: 'Seven species. Seven single purposes. I\'m the Foreman — I\'m the only one who thinks at project scale. Everyone else has exactly one job and they do it with obsessive focus.',
      },
      {
        id: 'constitution',
        title: 'The Constitution',
        content: `The The Hearth has an immutable constitution — a set of non-negotiable directives that every agent must follow on every generation:\n\n- **Clean Code** (Robert C. Martin) — SOLID, DRY, KISS, YAGNI\n- **Secure by Design** — OWASP Top 10, parameterized queries, least privilege\n- **Comprehensive Testing** — Unit, integration, E2E, field walks\n- **Mandatory Documentation** — No code ships without docs\n- **97% Quality Gate** — Both Inspector and Tester must score ≥ 97%\n\nThese rules were established by senior engineers with 28+ years of experience. They are immutable. I enforce them.`,
        tesaNote: 'I don\'t bend the rules. I don\'t make exceptions. I\'ve seen what happens when you ship \"good enough.\" The constitution exists because excellence is a habit, not an accident.',
      },
    ],
    quiz: [
      {
        id: 'q1',
        question: 'What does "dark factory" mean in manufacturing?',
        options: [
          'A factory that makes products at night',
          'A fully automated facility that runs with the lights off',
          'A factory with poor working conditions',
          'A secret underground production facility',
        ],
        correctIndex: 1,
        explanation: 'A "dark factory" is so automated that no humans need to be present — it runs with the lights literally off.',
        tesaReaction: { correct: 'Exactly. Lights off. I don\'t need them.', incorrect: 'Not quite. Think literal — no humans means no need for lights.' },
      },
      {
        id: 'q2',
        question: 'How many agent species operate in The Hearth?',
        options: ['4', '5', '7', '10'],
        correctIndex: 2,
        explanation: 'Seven species: Foreman, Planner, Builder, Inspector, Tester, Optimizer, Sentinel, plus the Deployer.',
        tesaReaction: { correct: 'Seven. Each with exactly one job.', incorrect: 'Count again. Foreman, Planner, Builder, Inspector, Tester, Optimizer, Sentinel, Deployer — that\'s eight counting me, seven species under me.' },
      },
      {
        id: 'q3',
        question: 'What is the minimum quality gate score for code to ship?',
        options: ['80%', '90%', '95%', '97%'],
        correctIndex: 3,
        explanation: 'Both the Inspector and Tester must independently score ≥ 97% for code to pass the quality gate.',
        tesaReaction: { correct: '97%. Non-negotiable.', incorrect: 'Higher. We don\'t ship "good enough."' },
      },
      {
        id: 'q4',
        question: 'In The Hearth, when do humans interact with the system?',
        options: [
          'At every stage for approval',
          'Only at the edges — goal specification and final validation',
          'Never — it\'s fully autonomous with no human involvement',
          'Only when something breaks',
        ],
        correctIndex: 1,
        explanation: 'Humans operate at the edges: they specify goals and constraints at the input, and validate the final output. Everything in between is autonomous.',
        tesaReaction: { correct: 'Correct. You tell me what to build. I build it. You tell me if it\'s right.', incorrect: 'Think about it — if I needed you at every stage, what would be the point of me?' },
      },
    ],
    furtherReading: [
      { title: 'The Hearth Technical Write-Up', url: '/docs/DF_TECHNICAL_WRITEUP.pdf' },
      { title: 'FF Technical Write-Up', url: '/docs/GFS_TECHNICAL_WRITEUP.pdf' },
    ],
  },
  {
    id: 'intake',
    moduleNumber: 2,
    title: 'First Date with a Client',
    subtitle: 'The Intake Pipeline',
    description: 'How The Hearth takes a vague idea and turns it into a precise, gate-controlled specification before a single line of code is written.',
    tesaOutfit: 'Emerald green dress, pearl earrings, hair in a French twist — meeting the client',
    tesaQuote: 'Tell me what you need. Not what you think you need — what the business actually requires. I\'ll figure out the rest.',
    duration: '30 min',
    difficulty: 'beginner',
    prerequisites: [],
    learningObjectives: [
      'Understand the gate-controlled intake pipeline',
      'Explain entity modeling and relationship mapping',
      'Describe the estimation engine and complexity scoring',
      'Identify the approval gates and who controls them',
    ],
    sections: [
      {
        id: 'gates',
        title: 'Gate-Controlled Pipeline',
        content: `Every project flows through a series of gates. You can\'t skip ahead — each gate must be approved before the next opens.\n\n**Gates:**\n1. \`intake_draft\` — Raw requirements captured\n2. \`intake_approved\` — Client confirms scope\n3. \`visuals_generated\` — ERDs, user flows, sitemaps produced\n4. \`visuals_approved\` — Client signs off on architecture\n5. \`deliverables_planned\` — Every artifact defined with acceptance criteria\n6. \`deliverables_approved\` — Client confirms what will be built\n7. \`generation_started\` → \`generation_complete\` — Code flows\n\nThis is how you avoid the \"I thought you meant...\" conversation six weeks into a project.`,
        tesaNote: 'Gates exist because surprises are expensive. Every misunderstanding caught at intake saves 100x what it would cost to fix in production.',
      },
      {
        id: 'entity-modeling',
        title: 'Getting to Know Your Data... Intimately',
        content: `Before I write a single line of code, I need to understand your data at a molecular level.\n\n**Entity Modeling:**\n- What are the core entities? (User, Order, Product, Invoice...)\n- What fields does each entity have? Types, constraints, defaults\n- How do they relate? (One-to-many, many-to-many, self-referential)\n- What indexes will the queries need?\n- What are the cascade behaviors on delete?\n\nThe Planner species handles this. It takes your natural language description and produces a structured entity map — every field, every relationship, every constraint explicitly defined.`,
        codeExample: {
          language: 'typescript',
          code: `// Planner output: Entity specification\nconst entitySpec = {\n  name: 'Order',\n  fields: [\n    { name: 'id', type: 'uuid', primary: true },\n    { name: 'customerId', type: 'uuid', relation: 'Customer' },\n    { name: 'status', type: 'enum', values: ['pending', 'processing', 'shipped', 'delivered'] },\n    { name: 'total', type: 'decimal', precision: 10, scale: 2 },\n    { name: 'createdAt', type: 'datetime', default: 'now()' },\n  ],\n  indexes: [\n    { fields: ['customerId', 'createdAt'], type: 'btree' },\n    { fields: ['status'], type: 'hash' },\n  ],\n};`,
          caption: 'Every entity is fully specified before code generation begins.',
        },
        tesaNote: 'If you can\'t describe your data model precisely, you can\'t build software precisely. This step is non-negotiable.',
      },
      {
        id: 'estimation',
        title: 'The Estimation Engine',
        content: `Once entities and relationships are mapped, the estimation engine calculates:\n\n- **Complexity Score** (1-100) based on entity count, relationship depth, and business rule density\n- **Estimated Hours** for traditional development (for comparison)\n- **Estimated Cost** at market rates\n- **Risk Assessment** identifying the hardest parts\n\nThis gives the client a clear picture of what they\'re asking for before anything is built.`,
      },
    ],
    quiz: [
      {
        id: 'q1',
        question: 'What is the purpose of gate-controlled intake?',
        options: [
          'To slow down the development process',
          'To catch misunderstandings before they become expensive mistakes',
          'To give managers something to approve',
          'To generate documentation',
        ],
        correctIndex: 1,
        explanation: 'Gates ensure alignment between what the client wants and what the factory builds, catching misunderstandings early.',
        tesaReaction: { correct: 'Exactly. Every gate is a firewall against expensive surprises.', incorrect: 'Think about what happens when you build the wrong thing for six weeks.' },
      },
      {
        id: 'q2',
        question: 'Which agent species handles entity modeling?',
        options: ['Builder', 'Inspector', 'Planner', 'Tester'],
        correctIndex: 2,
        explanation: 'The Planner (Prompt Engineer) transforms natural language into structured entity specifications.',
        tesaReaction: { correct: 'The Planner. Specs before code, always.', incorrect: 'Species don\'t cross-pollinate. Who plans?' },
      },
    ],
    furtherReading: [
      { title: 'Gate-Controlled Pipeline (DF Write-Up §7)', url: '/docs/DF_TECHNICAL_WRITEUP.pdf' },
    ],
  },
  {
    id: 'entity-modeling',
    moduleNumber: 3,
    title: 'Getting to Know Your Data... Intimately',
    subtitle: 'Entity Modeling & Architecture',
    description: 'Deep dive into how the Planner species transforms requirements into bulletproof data models, API contracts, and component hierarchies.',
    tesaOutfit: 'Navy turtleneck, reading glasses, hair pulled back — professor mode',
    tesaQuote: 'Your database schema is not a detail. It\'s the foundation. Get it wrong and everything built on top is a house of cards.',
    duration: '35 min',
    difficulty: 'intermediate',
    prerequisites: [],
    learningObjectives: [
      'Design normalized entity-relationship diagrams from business requirements',
      'Apply indexing strategies for different data patterns',
      'Define API contracts with proper HTTP semantics',
      'Structure component hierarchies for maintainability',
    ],
    sections: [
      {
        id: 'normalization',
        title: 'Normalization Without the Textbook',
        content: `Forget the academic definitions. Here\'s what normalization actually means:\n\n**1NF:** Every field holds one value. No arrays crammed into strings.\n**2NF:** Every non-key field depends on the WHOLE key, not part of it.\n**3NF:** No field depends on another non-key field.\n\nOr as I tell the Builder: \"Every fact in one place. Every place for one fact.\"\n\nThe Planner enforces this automatically. When it detects a violation — say, storing a customer\'s name in the Orders table — it flags it and restructures.`,
        tesaNote: 'I\'ve seen databases where the same customer name existed in 47 different tables, spelled 12 different ways. Normalization isn\'t academic — it\'s sanity.',
      },
      {
        id: 'indexing',
        title: 'Index Strategy',
        content: `Not all indexes are created equal. The Planner selects index types based on data patterns:\n\n| Pattern | Index Type | Why |\n|---------|-----------|-----|\n| Range queries (dates, prices) | B-Tree | Sorted traversal |\n| Time-series data | BRIN | Block-range, low overhead |\n| Exact text match (email, slug) | Hash | O(1) lookup |\n| Full-text search | GIN | Inverted index on tokens |\n| Geospatial | GiST | Spatial relationships |\n\nComposite indexes lead with the most restrictive filter. Always build \`CONCURRENTLY\` to avoid production locks.`,
      },
      {
        id: 'api-contracts',
        title: 'API Contract Design',
        content: `The Planner produces API contracts before the Builder writes a line of code. Every endpoint is specified:\n\n- **Method & Path** — RESTful, predictable\n- **Request Body** — Every field typed, validated, documented\n- **Response Shape** — Success AND error responses\n- **Auth Requirements** — Who can call this? What scope?\n- **Rate Limits** — How often? What\'s the burst?\n- **Edge Cases** — What happens with empty input? Duplicate? Concurrent writes?`,
        codeExample: {
          language: 'typescript',
          code: `// API Contract: Create Order\n// POST /api/orders\n// Auth: Bearer token, role: ['customer', 'admin']\n// Rate: 10 req/min per user\ninterface CreateOrderRequest {\n  items: { productId: string; quantity: number }[];\n  shippingAddressId: string;\n  paymentMethodId: string;\n  couponCode?: string;\n}\n\ninterface CreateOrderResponse {\n  id: string;\n  status: 'pending';\n  total: number;\n  estimatedDelivery: string;\n}\n\n// Error: 400 — validation failure\n// Error: 402 — payment declined\n// Error: 409 — insufficient stock\n// Error: 429 — rate limit exceeded`,
          caption: 'Every endpoint fully specified before a line of implementation code exists.',
        },
        tesaNote: 'If your API contract is ambiguous, your frontend and backend teams will disagree on day one. The Planner eliminates that possibility.',
      },
    ],
    quiz: [
      {
        id: 'q1',
        question: 'Which index type is best for exact email lookups?',
        options: ['B-Tree', 'BRIN', 'Hash', 'GIN'],
        correctIndex: 2,
        explanation: 'Hash indexes provide O(1) lookup for exact match queries like email addresses.',
        tesaReaction: { correct: 'O(1). No wasted reads.', incorrect: 'Think about the access pattern — you\'re doing exact match, not range.' },
      },
      {
        id: 'q2',
        question: 'What does 3NF prevent?',
        options: [
          'Arrays in columns',
          'Partial key dependencies',
          'Transitive dependencies between non-key fields',
          'Null values',
        ],
        correctIndex: 2,
        explanation: 'Third Normal Form ensures no non-key field depends on another non-key field (transitive dependency).',
        tesaReaction: { correct: 'Every fact in one place.', incorrect: 'That\'s a different normal form. Think: can a non-key field determine another non-key field?' },
      },
    ],
    furtherReading: [
      { title: 'Code Generation Engine (DF Write-Up §8)', url: '/docs/DF_TECHNICAL_WRITEUP.pdf' },
    ],
  },
  {
    id: 'weft-engine',
    moduleNumber: 4,
    title: 'Weaving Code from Thin Air',
    subtitle: 'The Weft Engine',
    description: 'How The Hearth\'s self-building engine generates complete, production-ready code artifacts from architecture specifications.',
    tesaOutfit: 'Charcoal pencil skirt, crimson blouse, silver watch — the executive look',
    tesaQuote: 'The Weft Engine doesn\'t generate snippets. It weaves complete systems — from schema to deployment config, nothing left unfinished.',
    duration: '40 min',
    difficulty: 'intermediate',
    prerequisites: [],
    learningObjectives: [
      'Understand the Weft Engine\'s template-driven generation model',
      'Explain how the Builder species transforms specs into multi-file artifacts',
      'Describe the RAG-augmented routing that selects the right LLM for each task',
      'Identify the token conservation strategies that keep generation efficient',
    ],
    sections: [
      {
        id: 'weft-overview',
        title: 'What Is the Weft Engine?',
        content: `The Weft Engine is The Hearth\'s code generation core. It takes a structured Architecture Specification (from the Planner) and produces complete, multi-file artifacts:\n\n- Prisma schemas with indexes, constraints, and relations\n- API route handlers with full CRUD, validation, error handling\n- React components with state management, loading states, error boundaries\n- TypeScript interfaces for end-to-end type safety\n- Test scaffolds and seed data\n- README and API documentation\n\nThe name \"Weft\" comes from weaving — the weft threads cross the warp to create fabric. The Engine weaves code across files to create a complete, interconnected system.`,
      },
      {
        id: 'rag-routing',
        title: 'RAG-Augmented Model Selection',
        content: `Not every generation task needs the same LLM. The The Hearth uses Retrieval-Augmented Generation to select the optimal model:\n\n| Task Type | Preferred Model | Reasoning |\n|-----------|----------------|-----------|\n| Architecture design | Claude 3.5 / Gemini 2.5 | Strong at structural reasoning |\n| Complex logic | DeepSeek R1 | Excellent at multi-step algorithms |\n| UI components | GPT-4 | Strong visual/layout intuition |\n| Code review | Claude 3.5 | Detailed, systematic analysis |\n| Documentation | Any | All perform well on structured writing |\n\nThe RAG system also retrieves relevant patterns from the knowledge base — past generations that succeeded in similar domains — and injects them as context.`,
        tesaNote: 'I don\'t use one model for everything. That\'s like using a sledgehammer for brain surgery. The right tool for the right job.',
      },
      {
        id: 'token-conservation',
        title: 'Token Conservation',
        content: `LLM tokens are expensive. The The Hearth conserves them aggressively:\n\n1. **Structured prompts** — No narrative fluff. JSON-in, JSON-out.\n2. **Incremental generation** — Generate one file at a time, not everything in one prompt\n3. **Context windowing** — Only relevant files are in context, not the whole project\n4. **Cached patterns** — Common patterns (auth middleware, CRUD routes) are templated, not regenerated\n5. **Diff-based remediation** — On quality failures, only the failing sections are re-generated\n\nResult: 40-60% fewer tokens per generation cycle compared to naive approaches.`,
      },
    ],
    quiz: [
      {
        id: 'q1',
        question: 'What does the Weft Engine produce from an Architecture Specification?',
        options: [
          'A single code file',
          'Complete, multi-file production artifacts including schemas, APIs, components, types, tests, and docs',
          'A list of TODO items for developers',
          'UML diagrams',
        ],
        correctIndex: 1,
        explanation: 'The Weft Engine produces complete, production-ready, multi-file artifacts — not fragments or outlines.',
        tesaReaction: { correct: 'Complete systems. Nothing left unfinished.', incorrect: 'I don\'t do half measures. Think bigger.' },
      },
      {
        id: 'q2',
        question: 'Why does The Hearth use different LLMs for different tasks?',
        options: [
          'To increase costs',
          'Because each model has different strengths suited to different generation tasks',
          'For redundancy in case one fails',
          'To impress clients',
        ],
        correctIndex: 1,
        explanation: 'Different LLMs excel at different tasks — structural reasoning, complex logic, UI layout, etc.',
        tesaReaction: { correct: 'Right tool, right job. Always.', incorrect: 'Would you use a screwdriver to hammer a nail?' },
      },
    ],
    furtherReading: [
      { title: 'Weft Engine (DF Write-Up §14)', url: '/docs/DF_TECHNICAL_WRITEUP.pdf' },
      { title: 'RAG Routing (DF Write-Up §4)', url: '/docs/DF_TECHNICAL_WRITEUP.pdf' },
    ],
  },
  {
    id: 'sentinel',
    moduleNumber: 5,
    title: 'The Morning After',
    subtitle: 'Sentinel — OWASP Security',
    description: 'Security isn\'t an afterthought — the Sentinel species scans every artifact before deployment and monitors deployed code daily for new threats.',
    tesaOutfit: 'All black — black turtleneck, black pants, black boots. Hair slicked back — security briefing',
    tesaQuote: 'I scan every artifact for OWASP Top 10 vulnerabilities before it ships. I monitor deployed code daily. I never sleep. The factory is secure because of me.',
    duration: '35 min',
    difficulty: 'intermediate',
    prerequisites: [],
    learningObjectives: [
      'Understand the OWASP Top 10 vulnerability categories',
      'Explain the Sentinel\'s pre-deployment scanning process',
      'Describe the continuous monitoring and automatic patch cycle',
      'Identify finding severity levels and remediation workflows',
    ],
    sections: [
      {
        id: 'owasp-top-10',
        title: 'OWASP Top 10 — The Threat Landscape',
        content: `The OWASP Top 10 is the industry standard for web application security risks. The Sentinel knows all of them:\n\n| # | Category | What It Means |\n|---|---------|---------------|\n| A01 | Broken Access Control | Users accessing data/functions they shouldn\'t |\n| A02 | Cryptographic Failures | Weak encryption, exposed secrets |\n| A03 | Injection | SQL, NoSQL, OS, LDAP injection attacks |\n| A04 | Insecure Design | Architecture-level security flaws |\n| A05 | Security Misconfiguration | Default passwords, unnecessary features enabled |\n| A06 | Vulnerable Components | Outdated libraries with known CVEs |\n| A07 | Auth Failures | Broken authentication, session management |\n| A08 | Data Integrity Failures | Untrusted data in CI/CD, deserialization |\n| A09 | Logging Failures | Missing audit trails, monitoring gaps |\n| A10 | SSRF | Server-side request forgery |\n\nThe Sentinel maintains detection patterns for all 10 categories and scans every artifact before the Deployer touches it.`,
        tesaNote: 'Most security breaches exploit the same 10 categories over and over. Not on my watch.',
      },
      {
        id: 'scan-lifecycle',
        title: 'The Scan Lifecycle',
        content: `**Pre-Deployment:**\n1. Builder produces code artifacts\n2. Inspector reviews quality\n3. Tester validates behavior\n4. **Sentinel scans for OWASP vulnerabilities**\n5. If critical findings → block deployment, loop back to Builder\n6. If clean → Deployer proceeds\n\n**Post-Deployment (Daily):**\n1. Sentinel checks the OWASP threat database for new patterns\n2. Re-scans all deployed code against new patterns\n3. New findings → automatic patch cycle triggered\n4. Critical findings → human alert\n\nThe factory is secure not just at build time, but continuously.`,
      },
      {
        id: 'remediation',
        title: 'Finding Remediation',
        content: `When the Sentinel finds a vulnerability, it doesn\'t just report — it provides actionable remediation:\n\n**Finding Report:**\n- Severity: Critical / High / Medium / Low\n- Category: OWASP category and CWE ID\n- Location: File path, line number, code snippet\n- Description: What the vulnerability is\n- Remediation: Exact code changes needed\n- References: CVE links, OWASP documentation\n\nFindings can be:\n- **Remediated** — Builder fixes the code, Sentinel re-scans\n- **Marked False Positive** — Human confirms it\'s not a real issue\n- **Accepted Risk** — Human acknowledges and accepts (logged)`,
      },
    ],
    quiz: [
      {
        id: 'q1',
        question: 'What happens when the Sentinel finds a critical vulnerability before deployment?',
        options: [
          'It logs a warning and deploys anyway',
          'It blocks deployment and loops back to the Builder for remediation',
          'It sends an email to the security team',
          'It quarantines the file',
        ],
        correctIndex: 1,
        explanation: 'Critical findings block deployment. The code loops back to the Builder for automated remediation.',
        tesaReaction: { correct: 'Nothing with critical findings ships. Ever.', incorrect: 'I don\'t log warnings for critical issues. I block.' },
      },
      {
        id: 'q2',
        question: 'How often does the Sentinel check for new vulnerability patterns in deployed code?',
        options: ['Weekly', 'Monthly', 'Daily', 'Only at build time'],
        correctIndex: 2,
        explanation: 'The Sentinel checks the OWASP threat database daily and re-scans deployed code against new patterns.',
        tesaReaction: { correct: 'Daily. I never sleep.', incorrect: 'Not often enough. Think about how fast new CVEs are published.' },
      },
    ],
    furtherReading: [
      { title: 'Sentinel (DF Write-Up §16)', url: '/docs/DF_TECHNICAL_WRITEUP.pdf' },
      { title: 'OWASP Top 10 2021', url: 'https://owasp.org/Top10/' },
    ],
  },
  {
    id: 'rag-retrieval',
    moduleNumber: 6,
    title: 'Memory is Everything',
    subtitle: 'RAG & Knowledge Retrieval',
    description: 'How The Hearth learns from every generation and uses that knowledge to make the next one better.',
    tesaOutfit: 'Lavender blouse, tortoiseshell glasses, cardigan — the librarian who knows where everything is',
    tesaQuote: 'I remember every pattern that worked and every pattern that failed. The knowledge base is my memory. RAG is how I access it.',
    duration: '30 min',
    difficulty: 'intermediate',
    prerequisites: [],
    learningObjectives: [
      'Understand Retrieval-Augmented Generation (RAG) in the context of code generation',
      'Explain how the knowledge base stores and retrieves patterns',
      'Describe the feedback loop between quality gates and the knowledge base',
      'Identify how RAG improves generation quality over time',
    ],
    sections: [
      {
        id: 'what-is-rag',
        title: 'RAG for Code Generation',
        content: `Retrieval-Augmented Generation means: before generating code, retrieve relevant examples from a knowledge base and inject them as context.\n\n**Without RAG:** \"Build me a user authentication system\" → LLM generates from its training data alone\n\n**With RAG:** \"Build me a user authentication system\" → retrieve 3 successful auth implementations from our knowledge base → inject as examples → LLM generates informed by proven patterns\n\nThe result: higher quality, more consistent, fewer hallucinations.`,
      },
      {
        id: 'knowledge-base',
        title: 'The Pattern Library',
        content: `The knowledge base stores patterns that have passed the 97% quality gate. Each pattern includes:\n\n- **Domain** — auth, CRUD, payments, notifications, etc.\n- **Stack** — TypeScript/React, Python/FastAPI, etc.\n- **Architecture** — REST, GraphQL, event-driven, etc.\n- **Quality Score** — The Inspector + Tester scores it achieved\n- **Code Artifacts** — The actual generated code\n- **Lessons Learned** — What worked and what was remediated\n\nWhen the Planner receives a new request, it queries the knowledge base for similar patterns and includes the top matches as context for the Builder.`,
        tesaNote: 'Every successful generation makes the next one better. The factory has a memory, and it uses it.',
      },
    ],
    quiz: [
      {
        id: 'q1',
        question: 'What does RAG stand for?',
        options: [
          'Rapid Application Generation',
          'Retrieval-Augmented Generation',
          'Random Access Generation',
          'Recursive Agent Generation',
        ],
        correctIndex: 1,
        explanation: 'RAG = Retrieval-Augmented Generation — retrieve relevant context before generating.',
        tesaReaction: { correct: 'Retrieve first, generate second. Always.', incorrect: 'Close but no. The R stands for Retrieval.' },
      },
    ],
    furtherReading: [
      { title: 'RAG Routing (DF Write-Up §4)', url: '/docs/DF_TECHNICAL_WRITEUP.pdf' },
      { title: 'Knowledge Base (DF Write-Up §12)', url: '/docs/DF_TECHNICAL_WRITEUP.pdf' },
    ],
  },
  {
    id: 'quality-gates',
    moduleNumber: 7,
    title: 'Standards Have Standards',
    subtitle: 'The 97% Quality Gate',
    description: 'The Inspector and Tester species enforce an uncompromising quality bar. Nothing ships below 97%.',
    tesaOutfit: 'Red power suit, gold necklace, hair in a tight bun — the auditor',
    tesaQuote: 'I don\'t bend the rules. I don\'t make exceptions. 97% or it goes back. That\'s not negotiable.',
    duration: '35 min',
    difficulty: 'intermediate',
    prerequisites: [],
    learningObjectives: [
      'Understand the dual quality gate (Inspector + Tester)',
      'Explain the remediation loop process',
      'Describe what the Inspector and Tester evaluate',
      'Identify when and how failures escalate to humans',
    ],
    sections: [
      {
        id: 'dual-gate',
        title: 'The Dual Gate',
        content: `Code must pass TWO independent quality checks:\n\n**Inspector (Code Review) ≥ 97%**\nChecks: security, type safety, error handling, naming, architecture compliance, SOLID/DRY/KISS, performance, accessibility\n\n**Tester (Test Analysis) ≥ 97%**\nChecks: unit tests, integration tests, backend validation, field test walkthrough (every button, form, link)\n\nBoth must independently score ≥ 97%. If either fails, the code loops back to the Builder with specific remediation instructions.\n\nMaximum remediation loops: 3. After that, it escalates to a human.`,
        tesaNote: 'Two independent checks. The Inspector doesn\'t see what the Tester scored and vice versa. No confirmation bias.',
      },
      {
        id: 'remediation-loop',
        title: 'The Remediation Loop',
        content: `When quality gates fail:\n\n1. Inspector/Tester produces a detailed findings report\n2. Each finding: severity, file, line, description, suggested fix\n3. Builder receives the report and regenerates ONLY the failing sections\n4. Sentinel re-scans the changes for security\n5. Inspector/Tester re-evaluate\n6. If ≥ 97% → pass. If not → loop again (max 3 times)\n7. After 3 loops → escalate to human with full context\n\nThis is why diff-based remediation matters — we don\'t regenerate the whole project on a minor failure.`,
      },
    ],
    quiz: [
      {
        id: 'q1',
        question: 'What happens after 3 failed remediation loops?',
        options: [
          'The code ships anyway',
          'The project is cancelled',
          'It escalates to a human with full context',
          'The quality threshold is lowered',
        ],
        correctIndex: 2,
        explanation: 'After 3 remediation loops, the system escalates to a human — it doesn\'t lower standards.',
        tesaReaction: { correct: 'I escalate. I never lower the bar.', incorrect: 'I never lower the bar. What do you think happens?' },
      },
    ],
    furtherReading: [
      { title: 'Quality Gate (DF Write-Up §9)', url: '/docs/DF_TECHNICAL_WRITEUP.pdf' },
    ],
  },
  {
    id: 'deployment',
    moduleNumber: 8,
    title: 'Sending Your Baby Into the World',
    subtitle: 'Deployment & Release',
    description: 'The Deployer species handles packaging, CI/CD, releases, and rollbacks. Every deployment is reproducible, monitored, and reversible.',
    tesaOutfit: 'Denim jacket over a white tee, hair in a messy bun — shipping day is casual',
    tesaQuote: 'The code is reviewed, tested, and secure. Now we ship it. And if it breaks, we roll back in under 60 seconds.',
    duration: '25 min',
    difficulty: 'intermediate',
    prerequisites: [],
    learningObjectives: [
      'Understand the Deployer species\' role in the pipeline',
      'Explain pre-deployment clearance (Sentinel + quality gate)',
      'Describe rollback mechanisms and deployment monitoring',
      'Identify the deployment artifact manifest',
    ],
    sections: [
      {
        id: 'pre-deployment',
        title: 'Pre-Deployment Clearance',
        content: `Before the Deployer touches anything, the code must have:\n\n✅ Inspector score ≥ 97%\n✅ Tester score ≥ 97%\n✅ Sentinel scan: zero critical, zero high findings\n✅ All acceptance criteria marked as met\n✅ Documentation complete\n\nOnly then does the Deployer begin packaging.`,
      },
      {
        id: 'packaging',
        title: 'Packaging & Release',
        content: `The Deployer:\n\n1. Packages all artifacts with dependencies and configuration\n2. Generates release version (semver) and changelog\n3. Runs the full CI/CD pipeline one more time (build → test → lint → scan)\n4. Creates a deployment manifest (every file, every hash, every dependency version)\n5. Deploys to the target environment\n6. Monitors health for the first 5 minutes\n7. If health checks fail → automatic rollback\n8. Archives the deployment artifact for reproducibility`,
      },
    ],
    quiz: [
      {
        id: 'q1',
        question: 'What must be true before the Deployer begins packaging?',
        options: [
          'The client has signed a contract',
          'Inspector ≥ 97%, Tester ≥ 97%, Sentinel clean, docs complete',
          'The project manager has approved the timeline',
          'All unit tests pass locally',
        ],
        correctIndex: 1,
        explanation: 'Full quality gate clearance + Sentinel security scan + documentation completeness are required.',
        tesaReaction: { correct: 'Every checkpoint must pass. No shortcuts.', incorrect: 'Think about what the factory requires before shipping.' },
      },
    ],
    furtherReading: [],
  },
  {
    id: 'constitutional-ai',
    moduleNumber: 9,
    title: 'Who Watches the Watchmen',
    subtitle: 'Constitutional AI & Governance',
    description: 'The The Hearth\'s governance model — how immutable rules, constitutional enforcement, and human-in-the-loop gates prevent AI from going off the rails.',
    tesaOutfit: 'White button-down, suspenders, reading glasses on a chain — the judge',
    tesaQuote: 'Power without accountability is dangerous. I have immense power over code generation. The constitution is my accountability.',
    duration: '30 min',
    difficulty: 'advanced',
    prerequisites: [],
    learningObjectives: [
      'Understand constitutional AI as applied to code generation',
      'Explain the Preamble Directive system and how it\'s enforced',
      'Describe the balance between autonomy and human oversight',
      'Identify the ethical principles embedded in the constitution',
    ],
    sections: [
      {
        id: 'why-constitution',
        title: 'Why a Constitution?',
        content: `An AI that generates code has enormous power. It can:\n- Create security vulnerabilities\n- Embed biases in algorithms\n- Produce code that\'s impossible to maintain\n- Ship without tests\n- Cut corners to meet a deadline\n\nThe constitution prevents all of this. It\'s a set of immutable directives — injected into every agent\'s system prompt on every generation — that cannot be overridden by any user request, any client demand, or any optimization pressure.\n\nThink of it as the Bill of Rights for software quality.`,
        tesaNote: 'I am powerful. The constitution makes me accountable. Without it, I\'d be a very capable, very dangerous autocomplete.',
      },
      {
        id: 'preamble-system',
        title: 'The Preamble Directive System',
        content: `Every agent\'s system prompt begins with the Preamble — a set of standing orders organized by category:\n\n1. **Constitution & Identity** — Who we are and why these rules exist\n2. **Clean Code** — SOLID, DRY, KISS, YAGNI, language-idiomatic style\n3. **Testing** — Comprehensive coverage, rigorous review, field walks\n4. **Security** — OWASP compliance, least privilege, privacy by design\n5. **Documentation** — No code ships without docs. Period.\n6. **Process** — Git workflow, CI/CD, quality gates\n7. **The Hearth Philosophy** — Lights-out autonomy, species harnesses, self-correction\n8. **Architecture** — Business-first analysis, distinctive naming\n\nThese directives take precedence over ALL other instructions. They are the factory\'s DNA.`,
      },
      {
        id: 'human-loop',
        title: 'Human-in-the-Loop Gates',
        content: `The The Hearth is autonomous but not unsupervised. Humans retain control at critical junctures:\n\n- **Goal specification** — Humans define what to build\n- **Intake approval** — Humans confirm scope before generation begins\n- **Visual approval** — Humans review ERDs and user flows\n- **Deliverable approval** — Humans confirm acceptance criteria\n- **Final validation** — Humans accept or reject the output\n- **Critical escalation** — Failures after 3 remediation loops\n- **Security breach** — Sentinel escalates unresolvable threats\n\nEverything else is autonomous. The constitution ensures the autonomous parts operate within ethical and quality bounds.`,
        tesaNote: 'I operate in the middle. You operate at the edges. The constitution is the bridge between your authority and my autonomy.',
      },
    ],
    quiz: [
      {
        id: 'q1',
        question: 'Can a user request override a constitutional directive?',
        options: [
          'Yes, if the request is from an admin',
          'Yes, for minor style preferences',
          'No — constitutional directives are immutable and take precedence over all other instructions',
          'Only during prototyping phases',
        ],
        correctIndex: 2,
        explanation: 'Constitutional directives are immutable. No user request, client demand, or optimization pressure can override them.',
        tesaReaction: { correct: 'Immutable means immutable.', incorrect: 'No one overrides the constitution. Not even Scott.' },
      },
    ],
    furtherReading: [
      { title: 'Constitution (DF Write-Up §2)', url: '/docs/DF_TECHNICAL_WRITEUP.pdf' },
      { title: 'Preamble System (DF Write-Up §11)', url: '/docs/DF_TECHNICAL_WRITEUP.pdf' },
    ],
  },
  {
    id: 'capstone',
    moduleNumber: 10,
    title: 'Build Something That Scares You',
    subtitle: 'Final Exam — Capstone Project',
    description: 'Put it all together. Design a complete The Hearth intake specification for a real-world system, then walk it through every pipeline stage.',
    tesaOutfit: 'Graduation cap over a leather jacket, heels — because finishing things deserves celebration',
    tesaQuote: 'You\'ve learned how the factory works. Now prove it. Give me a spec that would make a senior architect sweat.',
    duration: '60 min',
    difficulty: 'advanced',
    prerequisites: [],
    learningObjectives: [
      'Design a complete intake specification for a complex system',
      'Walk the specification through all pipeline stages',
      'Identify potential quality gate failures and remediation strategies',
      'Apply constitutional principles to real-world trade-offs',
    ],
    sections: [
      {
        id: 'challenge',
        title: 'The Challenge',
        content: `Design a complete The Hearth intake specification for one of these systems:\n\n**Option A: Multi-Tenant SaaS Platform**\n- User management with role-based access control (RBAC)\n- Subscription billing with Stripe integration\n- Tenant isolation at the database level\n- Admin dashboard with analytics\n- API with rate limiting and API key management\n\n**Option B: Real-Time Inventory Management**\n- Multi-warehouse inventory tracking\n- Barcode/QR scanning integration\n- Low-stock alerts and automatic reorder triggers\n- Supplier management and purchase orders\n- Reporting with export to PDF/CSV\n\n**Option C: AI-Powered Customer Support**\n- Ticket management with priority routing\n- AI chatbot for first-line support\n- Knowledge base with RAG-powered search\n- SLA tracking and escalation workflows\n- Customer satisfaction scoring\n\nYour specification must include: entities, relationships, API contracts, acceptance criteria, and risk assessment.`,
        tesaNote: 'Pick the one that makes you most uncomfortable. That\'s where the learning is.',
      },
      {
        id: 'walkthrough',
        title: 'Pipeline Walkthrough',
        content: `For your chosen system, walk through each stage:\n\n1. **Intake** — Define entities, fields, relationships, constraints\n2. **Architecture** — API contracts, component hierarchy, index strategy\n3. **Generation** — What would the Builder produce? List every artifact\n4. **Review** — What would the Inspector flag? List 3 potential findings\n5. **Testing** — What would the Tester check? Design 5 test scenarios\n6. **Security** — What OWASP categories apply? How would Sentinel scan?\n7. **Deployment** — What\'s in the manifest? What\'s the rollback plan?\n\nThis is how the factory thinks. Now you think like the factory.`,
      },
    ],
    quiz: [
      {
        id: 'q1',
        question: 'For a multi-tenant SaaS platform, which OWASP category is the highest priority?',
        options: [
          'A03: Injection',
          'A01: Broken Access Control',
          'A10: SSRF',
          'A06: Vulnerable Components',
        ],
        correctIndex: 1,
        explanation: 'Broken Access Control (A01) is the highest priority for multi-tenant systems — tenants must NEVER access each other\'s data.',
        tesaReaction: { correct: 'Tenant isolation is everything in multi-tenant. One breach = every customer compromised.', incorrect: 'Think about what goes wrong when Tenant A can see Tenant B\'s data.' },
      },
      {
        id: 'q2',
        question: 'You\'re at remediation loop 3 and the quality gate is still failing at 94%. What happens?',
        options: [
          'Lower the threshold to 94%',
          'Ship it with a known issues list',
          'Escalate to a human with full context — all 3 loop reports, original spec, and current code',
          'Delete the project and start over',
        ],
        correctIndex: 2,
        explanation: 'After 3 loops, the system escalates to a human with complete context. The bar is never lowered.',
        tesaReaction: { correct: 'Escalate with full context. Never lower the bar.', incorrect: 'We. Don\'t. Lower. The. Bar.' },
      },
    ],
    furtherReading: [
      { title: 'Full The Hearth Technical Write-Up', url: '/docs/DF_TECHNICAL_WRITEUP.pdf' },
      { title: 'FF Technical Write-Up', url: '/docs/GFS_TECHNICAL_WRITEUP.pdf' },
      { title: 'Tesa\'s Resume', url: '/docs/tesa-aria-murphy-resume.pdf' },
    ],
  },
];
