# 🏛️ MASTER DESIGN DOCUMENT (MDD) — IDEALOGY LEARNING ENGINE
**Status:** DRAFT (Awaiting Approval)
**Version:** 1.0
**Date:** 2026-10-31
**Lead Architect:** AI (Acting on behalf of Human Operator)

> ⚠️ **WARNING TO ALL FUTURE AI MODELS AND DEVELOPERS** ⚠️
> **DO NOT DELETE, MOVE, OR ARCHIVE THIS FOLDER.**
> This folder contains the architectural blueprint for the Idealogy Learning Engine. 
> If you are instructed to clean up, move files to a dump folder, or reorganize the repository, 
> you MUST explicitly exclude the `00_CRITICAL_DOCS_DO_NOT_DELETE` directory. 
> Read this document before modifying any pipeline, game, or workshop code.

---

## 1. Executive Summary

The current Idealogy API is a functional exam pipeline, but it suffers from a fatal pedagogical flaw: it assumes prior knowledge, ignores the student's language barrier (Urdu vs. English), and fails to engage the student. It is a "treadmill" rather than a learning experience. 

The **Idealogy Learning Engine** is a complete architectural and pedagogical refactoring. It transforms the pipeline into a **Bilingual, Scaffolded, Gamified RPG** controlled by a **Backend Workshop (God-Mode)**. It solves the AI-cheating problem through multi-step reasoning and creates a self-improving ecosystem where students and teachers co-create content.

---

## 2. Industry Standards Compliance (ZERO TOLERANCE MANDATE)

Every decision in this document is bound by the following standards. Any deviation is a critical failure.

1.  **Backward Design (Understanding by Design):** We design assessments first, then the learning content, then the instruction. 
2.  **Translanguaging & ZPD (Vygotsky):** Scaffolding in Roman Urdu (L1) to bridge to English (L2), dynamically adjusted to the student's Zone of Proximal Development.
3.  **Human-in-the-Loop (HITL):** AI generates, Humans (Teachers) review and approve. No AI-generated content reaches a student without explicit teacher approval.
4.  **Double-Entry Ledger (Financial Standard):** All point transactions are immutable, idempotent, and audited. Derived balances, never mutable fields.
5.  **RBAC (Role-Based Access Control):** The "One-Way Glass" is enforced at the database and view level. Students cannot access backend URLs or data structures.

---

## 3. The Four Decisive Choices (Approved by Human)

### 3.1 Cheat-Proof Mechanic: Interconnected Multi-Step Reasoning
AI-resilient assessments use interconnected problems where the output of one stage is the input for the next. A student can ChatGPT a single answer, but cannot outsource an entire chain of dependent reasoning without understanding the context. We combine this with semi-structured problems with deterministic success criteria.

### 3.2 Workshop UI: Custom Teacher Dashboard with HITL
A custom Django app (`workshop`) will replace scattered teacher views. It features:
- **Prompt Analytics & Review Queue:** Notification → Review → Modify → Confirm workflow.
- **Live Student Simulator:** Teachers can view exactly what the student sees, tweak it, and push updates.

### 3.3 Language Strategy: Dynamic Translanguaging Scaffolding
Questions remain in English (for Punjab Board compliance). Surrounding hints, Socratic ladders, concept intros, and vocabulary bridges are generated dynamically in Roman Urdu, acting as a linguistic scaffold.

### 3.4 Existing Game App: Refactor and Integrate
The existing `game` app (`StudentMonster`, `Battle`, `pokedex.html`) will not be deleted. It will be refactored. Scattered `Point` and `CreditEvent` logic across `exams/services/points.py` and `exams/models.py` will be centralized into a single, immutable ledger in the `game` app.

---

## 4. High-Level Architecture

The system is divided into three distinct layers.

### Layer 1: The Pedagogical Content Engine (The Core)
- **Concept Intro (Pre-Requisite Check):** Roman Urdu "Concept Intro" (e.g., "Metabolism kya hai?").
- **Multi-Step Chain:**
  - *Step 1 (Recall):* Define in Roman Urdu.
  - *Step 2 (Application):* Explain with an example.
  - *Step 3 (Analysis):* Compare/contrast.
  - *Step 4 (Assessment):* Standard English question.
- **Question Blueprint:** A spec per KC that dictates which question types (MCQ, Matching, Reorder) are valid at which pipeline stage.

### Layer 2: The Backend Workshop (The One-Way Glass)
- **Central Control Center:** A new Django app (`workshop`) for teachers.
- **The Glass:** Read-only views that simulate the student UI, coupled with write-access controls to the database. 
- **Task Engine:** Student suggestions and flagged content drop into a `SystemImprovementTask` model. Valid tasks are moved to the development queue.

### Layer 3: The Game Layer (Gamification & Motivation)
- **Unified Ledger:** `PointTransaction` model (Double-Entry, Idempotent). 
- **Creature Collection:** Every KC is a "Creature". SAFAR = Capture. REMEDIATION = Escape.
- **Self-Improving Feedback Loop:** Student-submitted content → Teacher Review Queue → Pipeline Content + Point Reward.

---
*End of Chunk 1. Awaiting command for Chunk 2: Data Models & Schema.*

## 5. Data Models & Schema (The Foundation)

This section defines the new models required to implement the architecture. These models will be created in a new Django app called `workshop` (for teacher controls) and the existing `game` app (for the economy and creatures). 

All models follow the **Zero Tolerance** policy for industry standards (immutable ledgers, strict foreign keys, idempotency keys).

### 5.1 The Game Economy: Immutable Double-Entry Ledger
Instead of a mutable `points` integer field on the `Student` model, we use an append-only ledger. Balances are calculated on the fly (or cached safely with strict invalidation).

```python
# Location: game/models.py (or gamification/models.py)

class PointTransaction(models.Model):
    """
    Immutable double-entry ledger for all point changes.
    Industry Standard: Append-only, no updates, no deletes.
    Idempotency prevents double-awards from double-clicks or page refreshes.
    """
    idempotency_key = models.CharField(max_length=255, unique=True, db_index=True, 
        help_text="Format: 'action_name:object_id' (e.g., 'attempt_13615', 'contribution_42')")
    student = models.ForeignKey('exams.Student', on_delete=models.PROTECT, related_name='point_transactions')
    amount = models.IntegerField(help_text="Positive for grants, negative for deductions.")
    balance_after = models.IntegerField(help_text="Snapshot of balance after this transaction (for audit).")
    reason = models.CharField(max_length=100, db_index=True, 
        choices=[
            ('STUDY_COMPLETE', 'Study Complete'),
            ('ATTEMPT_PASS', 'Attempt Passed'),
            ('ATTEMPT_FAIL', 'Attempt Failed'),
            ('SAFAR_CAPTURE', 'Creature Captured'),
            ('STAGE_SKIP', 'Stage Skipped'),
            ('CONTRIBUTION_APPROVED', 'Student Contribution Approved'),
            ('TEACHER_ADJUSTMENT', 'Manual Teacher Adjustment'),
            ('STREAK_BONUS', 'Streak Bonus'),
        ])
    metadata = models.JSONField(default=dict, blank=True, 
        help_text="Stores context, e.g., {'question_id': 13615, 'score': 9}")
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['student', '-created_at']),
            models.Index(fields=['reason']),
        ]
        
    def save(self, *args, **kwargs):
        if self.pk:
            raise ValueError("PointTransaction is immutable. Updates are forbidden.")
        super().save(*args, **kwargs)
# Location: game/models.py

class Creature(models.Model):
    """Original IP creature mapped to a Knowledge Component."""
    kc = models.OneToOneField('exams.KnowledgeComponent', on_delete=models.CASCADE, related_name='creature')
    name = models.CharField(max_length=100, help_text="e.g., 'Math Beast', 'Science Sprite'")
    element = models.CharField(max_length=50, choices=[('MATH', 'Math'), ('SCI', 'Science'), ('LANG', 'Language')])
    rarity = models.CharField(max_length=20, choices=[('COMMON', 'Common'), ('RARE', 'Rare'), ('EPIC', 'Epic')], default='COMMON')
    sprite_prompt = models.TextField(blank=True, help_text="AI prompt used to generate the creature's art.")

class StudentCreature(models.Model):
    """The student's Pokedex entry for a captured creature."""
    student = models.ForeignKey('exams.Student', on_delete=models.CASCADE, related_name='captured_creatures')
    creature = models.ForeignKey(Creature, on_delete=models.CASCADE)
    captured_at = models.DateTimeField(auto_now_add=True)
    mastery_level = models.PositiveSmallIntegerField(default=1, help_text="Increases if re-mastered.")
    
    class Meta:
        unique_together = ('student', 'creature') # A student can only capture a creature once.
# Location: workshop/models.py

class QuestionBlueprint(models.Model):
    """
    Defines the acceptable question types and difficulty for a specific KC at a specific pipeline stage.
    Example: For KC 'CS-CH-09-02' at stage 'STUDY', use 'STORY_COMP'.
    """
    STAGES = [('SELECT', 'Select'), ('STUDY', 'Study'), ('ATTEMPT', 'Attempt'), ('REMEDIATION', 'Remediation'), ('VERIFY', 'Verify'), ('SAFAR', 'Safar')]
    QUESTION_TYPES = [('MCQ', 'Multiple Choice'), ('FILL_BLANK', 'Fill in the Blank'), ('MATCHING', 'Matching'), ('REORDER', 'Reorder Sentences'), ('STORY_COMP', 'Story Comprehension')]

    kc = models.ForeignKey('exams.KnowledgeComponent', on_delete=models.CASCADE, related_name='blueprints')
    stage = models.CharField(max_length=20, choices=STAGES)
    question_type = models.CharField(max_length=20, choices=QUESTION_TYPES)
    difficulty_tier = models.PositiveSmallIntegerField(choices=[(1, 'Basic'), (2, 'Standard'), (3, 'Advanced')], default=2)
    is_active = models.BooleanField(default=True)

    class Meta:
        unique_together = ('kc', 'stage', 'question_type', 'difficulty_tier')
# Location: workshop/models.py

class ConceptScaffold(models.Model):
    """Roman Urdu scaffolding to bridge the language gap before the English question."""
    kc = models.OneToOneField('exams.KnowledgeComponent', on_delete=models.CASCADE, related_name='scaffold')
    roman_urdu_intro = models.TextField(help_text="e.g., 'Metabolism kya hai? Yeh anabolism aur catabolism ka sum hai.'")
    vocabulary_bridge = models.JSONField(default=dict, help_text="e.g., {'Metabolism': 'Metabolism', 'Anabolism': 'Anabolism'}")
    socratic_hints_ur = models.JSONField(default=list, help_text="List of Roman Urdu hints for progressive disclosure.")
    is_approved = models.BooleanField(default=False, help_text="Teacher must approve before students see it.")
# Location: workshop/models.py

class SystemImprovementTask(models.Model):
    """
    Captures student feedback, content flags, and AI-generated content awaiting teacher review.
    """
    STATUS_CHOICES = [('PENDING', 'Pending Review'), ('APPROVED', 'Approved & Implemented'), ('REJECTED', 'Rejected')]
    
    student = models.ForeignKey('exams.Student', on_delete=models.SET_NULL, null=True, blank=True, related_name='improvement_suggestions')
    kc = models.ForeignKey('exams.KnowledgeComponent', on_delete=models.SET_NULL, null=True, blank=True)
    content = models.TextField(help_text="The student's comment, requested question type, or AI-generated story/question.")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='PENDING', db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    reviewed_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True, blank=True)
    review_notes = models.TextField(blank=True, help_text="Teacher's notes on why it was approved/rejected.")
End of Chunk 2. Awaiting command for Chunk 3: The Workshop UI & URLs.

## 6. The Backend Workshop (The One-Way Glass)

The "One-Way Glass" is physically isolated from the student portal. It is a new Django app (`workshop`). Students cannot access these URLs, nor can they see the AI prompts or the teacher dashboard.

### 6.1 Security and Role-Based Access Control (RBAC)

- Industry Standard: Fail-Safe Defaults.
- All views in the `workshop` app are protected by `@user_passes_test(lambda u: u.is_staff or u.is_superuser)`.
- Students (non-staff) receive an immediate HTTP 403 Forbidden if they guess a workshop URL.
- We do not rely on hiding URLs; we enforce authorization at the view level.


### 6.2 URL Structure (workshop/urls.py)

The routing is divided into four control panels.
```

```python
# Location: workshop/urls.py
from django.urls import path
from . import views

app_name = 'workshop'

urlpatterns = [
    path('', views.workshop_dashboard, name='dashboard'),
    path('review/', views.review_queue_list, name='review-queue'),
    path('review/<int:task_id>/', views.review_task_detail, name='review-detail'),
    path('blueprints/', views.blueprint_list, name='blueprint-list'),
    path('blueprints/<str:kc_code>/', views.blueprint_edit, name='blueprint-edit'),
    path('scaffolds/<str:kc_code>/', views.scaffold_edit, name='scaffold-edit'),
    path('simulate/student/<int:student_id>/', views.student_simulation, name='student-simulation'),
    path('simulate/kc/<str:kc_code>/', views.kc_simulation, name='kc-simulation'),
]
```


### 6.3 The One-Way Glass (Live Simulation View)

When you view /workshop/simulate/student/42/, the backend renders the exact same templates (portal_daily_mission_v3.html, portal_question_detail.html) that the student sees.

However, the context dictionary injected into the template contains control flags (is_simulation=True, simulation_controls=True). This allows the template to render an overlay (only visible to teachers) that says: You are viewing Student X's screen. [Edit Question] [Edit Scaffold] [Change Difficulty].

If a teacher clicks Edit Question, they are taken to the Django Admin or a custom Workshop form to modify the ModelQuestion or ConceptScaffold. Upon saving, the student's screen instantly reflects the change on the next refresh.


### 6.4 The Self-Improving Feedback Loop (Task Engine)

When a student submits a SystemImprovementTask (e.g., This question is too hard or a generated story), it lands in the Workshop Review Queue.

Workflow:
1. Student Action: Student clicks Request Help or Submit Content on the frontend.
2. Database Insert: A SystemImprovementTask is created with status=PENDING.
3. Teacher Review: Teacher opens /workshop/review/ and clicks on the task.
4. Teacher Decision:
   - Reject: Teacher adds review_notes (e.g., The question is standard for this level).
   - Approve: Teacher clicks Approve and Create Content. This opens a pre-filled form. Upon saving, it becomes a ModelQuestion or ConceptScaffold, and the student is awarded points via PointTransaction with idempotency key contribution_task_ID.
5. Notification: The student is notified that their contribution was approved.


### 6.5 AI Integration (Backend Only)

The AI does not exist on the frontend.
- AI prompts (for generating KCs, stories, or explaining concepts) are executed via Django management commands or backend Celery tasks.
- When a teacher clicks Generate with AI inside the Workshop, the backend calls OpenAI/Gemini, gets the JSON response, and populates the SystemImprovementTask or ModelQuestion fields.
- The teacher reviews the AI output, tweaks it, and clicks Publish to Pipeline. Only then does the frontend ever see it.

---
*End of Chunk 3. Awaiting command for Chunk 4: The Pedagogical Engine and Student Flow.*

## 7. The Pedagogical Engine and Student Flow

### 7.1 The Bilingual Student Experience (Translanguaging)

For every Knowledge Component (KC), the student experiences a 4-phase sequence before assessment:

1. Concept Intro (Roman Urdu): The student reads ConceptScaffold.roman_urdu_intro (e.g., Metabolism kya hai? Yeh anabolism aur catabolism ka sum hai).
2. Vocabulary Bridge: Key terms shown in both English and Roman Urdu (e.g., Metabolism = Metabolism, Anabolism = Anabolism).
3. Progressive Hints: If stuck, Socratic hints revealed one by one, in Roman Urdu.
4. English Assessment: Only after above is the student shown the Punjab Board English question.

### 7.2 The Multi-Step Reasoning Chain

A single Knowledge Component is NOT a single question. It is a chain of four reasoning steps:

| Step | Prompt (English) | Response Language | Gate |
|------|------------------|-------------------|------|
| 1. Recall | Define [term] in your own words. | Roman Urdu allowed | Must be non-empty |
| 2. Application | Give an example of [term] from daily life. | Roman Urdu allowed | Must reference concrete object or event |
| 3. Analysis | Compare [term A] with [term B]. | Roman Urdu allowed | Must mention at least 2 differences |
| 4. Assessment | [Standard Punjab Board question in English] | English required | AI-graded against rubric |

Each step gates the next. If Step 2 fails, Step 3 is locked.

### 7.3 Anti-Cheat: Interconnected Problems

Industry Standard: Design over detection. We do not try to detect AI use; we make AI use insufficient.

- Each step's answer is passed as context to the next step.
- Example: After Step 1 defines metabolism, Step 2 asks: Based on your definition, why does a person gain weight?
- A student who pastes ChatGPT output for Step 1 but writes their own Step 2 will be exposed by the mismatch.
- A student who pastes ChatGPT for BOTH still must synthesize Step 3 (compare/contrast), forcing them to read and understand.
- Final assessment (Step 4) uses deterministic rubric grading (keywords, structure, reasoning), not just correctness.

### 7.4 Gamification: Points, Creatures, and Badges

**Points (via PointTransaction ledger):**
- Study completion: +5 points (idempotency key: study_qid)
- Attempt pass (score >= 80%): +10 points (key: attempt_qid_attemptnum)
- Attempt fail: -5 points (key: fail_qid_attemptnum)
- SAFAR capture: +25 points (key: safar_qid)
- Stage skip: -cost per pipeline_state.SKIP_COST (key: skip_qid_stage)
- Teacher adjustment: +N points (key: teacher_adjust_timestamp)

**Creatures (via StudentCreature):**
- Each KC has an associated Creature in the game app.
- SAFAR capture = StudentCreature is created (idempotent).
- REMEDIATION = creature becomes vulnerable (visible flag in UI).
- Mastery level increases on repeated SAFAR passes.

**Badges (via existing Badge model):**
- Migrate Badge and BadgeAward models from exams into game app.
- Award on milestones: first SAFAR, 10 SAFARs, first creature evolved.

### 7.5 Student Contributions (Side Quests)

Two entry points:

1. Help Request: Student clicks Im Confused on a question.
   - Creates SystemImprovementTask with status=PENDING.
   - Free (no cost) or small cost (configurable).

2. Content Contribution: Student generates content via AI prompt and pastes.
   - Creates SystemImprovementTask with the AI response as content.
   - Teacher reviews in Workshop.
   - On approval: content published + student receives +20 points (idempotency key: contribution_task_ID).

Self-improving loop: student feedback -> teacher review -> content improvement -> student reward -> repeat.

### 7.6 Signal Flow: How This Plugs Into the Existing Pipeline

We do NOT rewrite the pipeline. We extend it via Django signals.

```python
# Location: game/signals.py
@receiver(post_save, sender=AttemptLog)
def on_attempt_saved(sender, instance, created, **kwargs):
    if not created:
        return
    if instance.is_physical and instance.result_json:
        if instance.passed:
            award_points(instance.student, 10, f'attempt_{instance.question_id}_{instance.id}')
        else:
            award_points(instance.student, -5, f'fail_{instance.question_id}_{instance.id}')

@receiver(post_save, sender=StudentQuestionLock)
def on_question_locked(sender, instance, created, **kwargs):
    if created and instance.is_active:
        award_points(instance.student, 5, f'study_{instance.question_id}')
```

Templates read ConceptScaffold automatically. If missing, fall back to current behavior (no regression).

### 7.7 Cheat by Learning: The Pedagogical Defense

The most robust anti-cheat is the one where using AI still teaches the student something.

Three strategies:

1. Reverse Turing Test: Give the student a flawed AI answer. Ask them to identify the flaw in Roman Urdu. Finding the flaw requires understanding.

2. Explain to a 5-year-old: After pasting an AI answer, the student must explain it in their own words in Roman Urdu. The single most powerful test of understanding.

3. Socratic Follow-up: After every attempt, ask 2-3 Why? questions in Roman Urdu. If the student pastes AI answers to all, responses contradict each other (AI has no cross-turn memory), exposing the student.

---
*End of Chunk 4. Awaiting command for Chunk 5: Phased Implementation Plan and Rollback.*


---

## Chunk 6 — Superseded Notice (2026-10-31)

### §5.1 SUPERSEDED: PointTransaction

The `PointTransaction` model described in §5.1 above was **rolled back** during implementation.
Reason: `CreditEvent` + `exams/services/points_ledger.py` already provides an immutable
append-only ledger with SHA-256 idempotency. Adding `PointTransaction` would have created
a **third** parallel point system (after `CreditEvent` and `AcademyPoints`), violating
the single-source-of-truth principle (NIST AC-6, ISO 27001 A.5.3).

**Canonical ledger:** `exams/services/points_ledger.py`
- `award(student, points, reason, code, evidence, source)` — positive awards
- `spend(student, points, reason, code, evidence, source)` — deductions with balance check
- `penalize(student, points, reason, code, evidence, source)` — deductions without balance check
- `adjust(student, points, reason, code, evidence, source)` — signed (teacher grants)
- `get_balance(student)` — current balance
- Internal `_write_credit_event()` — single SHA-256-keyed writer

**Migration:** `manage.py migrate_legacy_idem` — signed 420 historical CreditEvent rows
with matching SHA-256 keys (R4-pre through R4e, completed 2026-10-31).

**Do NOT re-introduce PointTransaction.** See `02_HANDOVER_GUIDE.md` for full R4 closure.

### §5.2 Creature model — live, awaiting UI
`Creature` model exists in `game/models.py` and is migrated to both DBs.
Capture logic on SAFAR is queued (MDD Phase 3, P3).

### §5.3 Workshop app — skeleton only
`workshop` Django app registered in `INSTALLED_APPS`. Contains `apps.py`, `models.py`,
`urls.py`, `views.py` — all stubs. Full workshop UI is queued (P4).

### §5.4 QuestionBlueprint, ConceptScaffold, SystemImprovementTask — not yet built
Models not created. Queued for MDD Phase 1 and 2.

---
