# 🔴 HANDOVER GUIDE — Live Session Log

> ⚠️ **DO NOT DELETE, MOVE, OR ARCHIVE THIS FOLDER** ⚠️
> This folder contains architecture and session state for the Idealogy API.
> Exclude `00_CRITICAL_DOCS_DO_NOT_DELETE` from any cleanup or dump operation.

**Maintained by:** AI assistant during live sessions
**Update cadence:** After every phase closes, or before context break
**Companion doc:** `01_Master_Design_Document.md` (the blueprint)

---

## 1. TL;DR — READ THIS FIRST

**Project:** Idealogy API — Django exam/learning portal for Punjab Board students
**Production:** `/home/orkoworo/idealogy/api` (MySQL DB)
**Sandbox:** `/home/orkoworo/idealogy_sandbox/api` (SQLite `db_sandbox.sqlite3`, isolated)
**Python (prod):** `/home/orkoworo/virtualenv/idealogy/api/3.13/bin/python` (alias `$PV`)
**Python (sandbox):** `/home/orkoworo/virtualenv/idealogy_sandbox/api/3.13/bin/python` (alias `$PV_SB`)

**Current phase:** R4 (Point System Revision) — industry-standard compliance
**Sub-phase in progress:** R4b (Sites 7 + 10 refactor)
**Next after R4 completes:** Token queue system for physical tests (design approved, execution queued)
**After token system:** MDD Phase 2 — creature capture on SAFAR (Pokémon mechanic)

**Golden rule:** read → backup → patch → verify → E2E → diff → sandbox sync → parity=0. No exceptions.

---

## 2. Session Statistics (2026-10-31)

| Metric | Count |
|---|---|
| Files modified (with backups) | 15+ |
| Production bugs fixed | 3 (`select_questions` 500, `9th`/`9` split, `Custom` label) |
| Point system violations fixed | 2 (MASTERY_STEP double-write, RETRY_PENALTY ordering + idempotency) |
| Historical rows migrated | 408 CreditEvent rows signed with `idem_key` |
| Students' dashboards corrected | 21 (e.g., `s-0088` went from `-11` to `989`) |
| Sandbox rebuilds | 2 (initial setup, then post-rollback clean rebuild) |
| Terminal mangling incidents | 8+ (lesson learned — see §6) |
| Time elapsed | ~7 hours |

---

## 3. Current Phase: R4 — Point System Revision

### What R4 Fixes

Audit (R1) found 4 violations:
1. **21 students saw inconsistent balances** — dashboard vs `spend()` used different formulas
2. **852 MASTERY_STEP rows double-written** (CreditEvent + AcademyPoints + AcademyPointTx = +2 for a +1 event)
3. **9 raw `CreditEvent.objects.create()` calls** — no SHA-256 idempotency, double-click = double-award
4. **1421 historical rows without signatures** — refactoring without migration would double-award

### Sub-Phase Status

| Sub-phase | Scope | Status | Backup |
|---|---|---|---|
| **R1** | Audit (read-only) | ✅ Done | — |
| **R2a** | MASTERY_STEP double-write removed | ✅ Deployed | `.bak.batch5_88_20261031_070517` |
| **R3** | Dashboard reads `points_ledger.get_balance()` | ✅ Deployed | `.bak.batch5_88_r3_*` + `_r3_pep8_*` |
| **R3-sync** | `views_student_pipeline.py` synced to sandbox | ✅ Done | — |
| **R4-pre** | 408 historical receipts signed with `idem_key` | ✅ Deployed | `/tmp/credit_events_pre_r4pre_backup.json` + `idealogy/archive/credit_events_pre_r4pre_20261031_075222.json` |
| **R4a** | RETRY_PENALTY moved inside txn + idempotent | ✅ Deployed | `.bak.batch5_88_r4a_20261031_081358` |
| **R4b** | CONTRIBUTION_REWARD + MASTERY_STEP refactor | 🟡 Qualified, patch pending | — |
| **R4c** | STORY_HEAL + ATTENDANCE_REDEEM + KC_CONTRIBUTED | ⏳ Queued | — |
| **R4d** | TEACHER_GRANT nonce pattern | ⏳ Queued | — |
| **R4e** | STARTING_BONUS + QUESTION_MASTERED use migrated idem | ⏳ Queued | — |
| **R4f** | Full E2E test (all 10 sites) | ⏳ Queued | — |

---

## 4. Approved Design Table — 10 Sites

The full SHA-256 evidence design (approved by human). Every R4 sub-patch refactors one of these to use `points_ledger.award()` / `.penalize()`.

| # | Site | Code | Evidence Key | Notes |
|---|---|---|---|---|
| 1 | `views_v3.py:415` | `STORY_HEAL` | `{'kc_code', 'story_hash'}` | Content-addressed (ETag pattern) |
| 2 | `views_v3.py:536` | `ATTENDANCE_REDEEM` | `{'attendance_id'}` | Natural key |
| 3 | `views_v3.py:1085` | `KC_CONTRIBUTED` | `{'qid', 'kc_code'}` | Composite natural key |
| 4 | `views_v3.py:1222` | `TEACHER_GRANT` (bulk) | `{'student_id', 'grant_nonce'}` | Stripe-style nonce |
| 5 | `views_v3.py:1240` | `TEACHER_GRANT` (single) | `{'student_id', 'grant_nonce'}` | Same nonce, per-student |
| 6 | `views_student_pipeline.py:408` | `RETRY_PENALTY` | `{'attempt_id'}` | ✅ DONE in R4a |
| 7 | `views_student_pipeline.py:1867` | `CONTRIBUTION_REWARD` | `{'contribution_id'}` | `if created:` guard stays |
| 8 | `allot_points.py:17` | `STARTING_BONUS` | `{}` | **CORRECTED** — empty (student_id already in hash) |
| 9 | `pipeline_state.py:84` | `QUESTION_MASTERED` | `{'qid'}` | Uses migrated `idem_key` from R4-pre |
| 10 | `views_student_pipeline.py:1580` | `MASTERY_STEP` | `{'qid': rps.model_question_id, 'step'}` | **STRICT** — kills restart-farming |

### Migration Scope (R4-pre result)

- ✅ 344 `QUESTION_MASTERED` rows migrated (hash: `sha256(student_id:QUESTION_MASTERED:[('qid', X)])`)
- ✅ 64 `STARTING_BONUS` rows migrated (hash: `sha256(student_id:STARTING_BONUS:[])`)
- ❌ 852 `MASTERY_STEP` grandfathered (no evidence to reconstruct)
- ❌ 71 `CONTRIBUTION_REWARD` grandfathered
- ❌ 61 `KC_CONTRIBUTED` grandfathered
- ❌ 7 `STORY_HEAL` grandfathered

**Verified in R4-pre Step 6D**: `points_ledger.award()` on a migrated row returns `None` (blocks duplicate) — hash parity confirmed.

---

## 5. Token Queue System (Approved Design — Queued)

**Purpose:** Prevent cheating during physical tests — teacher handles students 1-50 at a time (configurable).

**Model:** `ExamToken` (new)
**Lifecycle:** `PENDING → CALLED → IN_PROGRESS → COMPLETED` (or `SKIPPED`/`CANCELLED`)
**FIFO queue** — first requester = #1, strictly sequential
**Anti-cheat gate** at `portal_teacher_paste` — student can only submit if they have `CALLED`/`IN_PROGRESS` token
**Grace period** — configurable minutes before auto-skip
**One active token per student** — DB constraint
**Sub-phases T1–T8** — queued after R4 closes

---

## 6. Known Traps & Disciplines (READ BEFORE PATCHING)

### 🚨 KC Firewall
`exams/kc_firewall.py` blocks `pre_delete` on `ModelQuestion`, `ModelPaper`, `KnowledgeComponent` — raises `PermissionDenied`. **Never try to hard-delete these.** Use soft-delete via `superseded_at` field for questions/papers, and `update(is_active=False)` for KCs.

### 🚨 Terminal Mangling
The terminal buffer mangles heredocs and long `&&` chains. **Discipline:**
- One command per paste when verification matters
- Never chain `cat > file << 'EOF' ... EOF && manage.py ...`
- No `~` unquoted — use `/home/orkoworo` absolute
- No `( parens )` in `echo` strings inside chains
- Verify each file write with `wc -l` before running it
- Verify each Python file with `py_compile` before running it

### 🚨 Parity Discipline
Every code change on production → sync to sandbox → `diff -rq` must return `0`. Do not declare done until parity confirmed.

### 🚨 Backup Discipline
Every patch creates `.bak.batch5_NN_YYYYMMDD_HHMMSS` before writing. Restore = `cp -v .bak.<TS> <file>`. No exceptions.

### 🚨 `points_ledger.award()` Signature
```python
award(student, points, reason, code='AWARD', evidence=None, source='AUTO')
evidence dict + student.id + code = SHA-256 idempotency key. Never write CreditEvent.objects.create() directly in new code — always go through the ledger.

🚨 Sandbox SQLite Reset
If sandbox DB is orphaned: rm /home/orkoworo/idealogy_sandbox/api/db_sandbox.sqlite3 && $PV_SB manage.py migrate --noinput. Takes ~30 seconds, fully rebuilds.


## 7. How to Resume (Fresh AI Checklist)

1. **Read this file top to bottom.** Understand TL;DR + current phase + traps.
2. **Read `01_Master_Design_Document.md`** — but note §5.1 mentions `PointTransaction` which was **rolled back** (see §10). Actual implementation uses `points_ledger.penalize()`.
3. **Verify environment:**
   - `cd /home/orkoworo/idealogy/api && /home/orkoworo/virtualenv/idealogy/api/3.13/bin/python manage.py check` → must be clean
   - `cd /home/orkoworo/idealogy_sandbox/api && /home/orkoworo/virtualenv/idealogy_sandbox/api/3.13/bin/python manage.py check` → must be clean
4. **Verify parity (must return `0`):**
diff -rq --exclude='pycache' --exclude='.pyc' --exclude='.git' --exclude='.bak' --exclude='.log' --exclude='staticfiles' --exclude='media' --exclude='settings.py' --exclude='secrets.py' --exclude='db_sandbox.sqlite3' --exclude='db.sqlite3' --exclude='CHANGELOG.md' --exclude='.htaccess' --exclude='.user.ini' --exclude='passenger_wsgi.py' --exclude='.broken.' /home/orkoworo/idealogy/api /home/orkoworo/idealogy_sandbox/api 2>&1 | wc -l


5. **Check last backup exists:**
- `ls -la /home/orkoworo/idealogy/api/exams/views_student_pipeline.py.bak.batch5_88_r4a_*` → must show the R4a backup
6. **Continue from "Sub-phase in progress" in §3.** Each sub-phase starts with read-only qualification, ends with parity=0.
7. **Update this file after every phase closes** — append to §9 Changelog.

---

## 8. Restore / Rollback Procedures

| What | Restore Command |
|---|---|
| `views_student_pipeline.py` to pre-R4a | `cp -v exams/views_student_pipeline.py.bak.batch5_88_r4a_<TS> exams/views_student_pipeline.py` |
| `views_student_pipeline.py` to pre-R2a | `cp -v exams/views_student_pipeline.py.bak.batch5_88_20261031_070517 exams/views_student_pipeline.py` |
| `views_v3.py` to pre-R3 | `cp -v exams/views_v3.py.bak.batch5_88_r3_<TS> exams/views_v3.py` |
| Migrated CreditEvent rows | `/home/orkoworo/virtualenv/idealogy/api/3.13/bin/python manage.py revert_legacy_idem` (removes all idem_key — use with care) |
| Full site | `tar -xzf /home/orkoworo/idealogy/archive/full_site_backups/idealogy_complete_20261031_050627.tar.gz` |

---

## 9. Changelog — Session 2026-10-31

| # | ~Time | What | Backup | E2E |
|---|---|---|---|---|
| 1 | 03:00 | Fixed `select_questions` 500 (UnboundLocalError) — moved `student` fetch above `_cls` | `.bak.batch5_83_*` | GET→200 |
| 2 | 03:15 | Unified `9th`/`9` → `'9'`, `Custom` → `Personalized` (5 files, 50 students, 11 papers, 52 questions) | `.bak.batch5_84_*` | 3 paths E2E |
| 3 | 05:00 | Full production cleanup (560 .bak, 38 __pycache__, 417MB backups/ archived) | `idealogy_complete_20261031_050627.tar.gz` (320MB) | check clean |
| 4 | 05:30 | Sandbox isolated — `db_sandbox.sqlite3`, SQLite, separate from prod MySQL | 181 files synced | parity=0 |
| 5 | 05:40 | `workshop` app created (skeleton), `Creature` model added, `game/apps.py` loads signals | `.bak.batch5_85_*` | migrations OK |
| 6 | 05:50 | Rolled back redundant `PointTransaction` (was parallel to CreditEvent ledger) | `.bak.batch5_86_*` | dropped clean |
| 7 | 06:00 | `points_ledger.penalize()` added (allows negative balance) | `.bak.batch5_87_*` | 12/12 E2E |
| 8 | 06:10 | `game/signals.py` built (ATTEMPT_PASS +10, ATTEMPT_FAIL -5, STUDY_COMPLETE +5) | `.bak.batch5_87_*` | 12/12 E2E |
| 9 | 07:00 | R1 audit — 21 drifted students, 1421 unsigned receipts | (read-only) | — |
| 10 | 07:20 | R2a — MASTERY_STEP double-write removed (6 lines) | `.bak.batch5_88_20261031_070517` | AcademyPoints unchanged |
| 11 | 07:30 | R3 — dashboard reads `get_balance()` (3 hunks) | `.bak.batch5_88_r3_*` | s-0088 -11→989 |
| 12 | 07:30 | R3 PEP8 fix (blank lines restored) | `.bak.batch5_88_r3_pep8_*` | — |
| 13 | 07:45 | R4-pre — 408 historical receipts signed | migration + JSON backup | hash parity PASS |
| 14 | 08:15 | R4a — RETRY_PENALTY moved inside txn + `attempt_id` evidence | `.bak.batch5_88_r4a_20261031_081358` | 6/6 E2E |
| 15 | 08:25 | Handover guide v1 created (this file) | — | 11 sections |

---

## 10. MDD Corrections Needed

**`01_Master_Design_Document.md` §5.1** describes a `PointTransaction` model that was **rolled back**. Actual implementation uses `points_ledger.penalize()` + `CreditEvent` ledger + SHA-256 `idem_key`.

Do not delete §5.1 — append a "**SUPERSEDED**" notice when Chunk 6 is written. Points to `exams/services/points_ledger.py` as the canonical point ledger.

---

## 11. Queued Work (After R4 Closes)

| Priority | Item | Est. effort |
|---|---|---|
| P1 | Token queue system T1–T8 (physical test appointments) | ~2 hours |
| P2 | MDD Chunk 6 correction (PointTransaction rollback note) | 15 min |
| P3 | MDD Phase 2 — creature capture on SAFAR | ~1 hour |
| P4 | Teacher approval queue for AI-generated KCs | ~1 hour |
| P5 | `manage.py prepare_all_content` bulk command | ~2 hours |

---

**End of Handover Guide.**
**Last updated:** 2026-10-31 08:25 UTC
**Next update:** When R4b closes.

**R4b COMPLETE (2026-10-31 ~08:30)** — Sites 7 & 10 refactored:
- Site 7 CONTRIBUTION_REWARD → `points_ledger.award(evidence={'contribution_id'})`
- Site 10 MASTERY_STEP → `points_ledger.award(evidence={'qid', 'step'})` — anti-farm enforced
- Backup: `.bak.batch5_88_r4b_20261031_082547`
- E2E: 9/9 checks pass

**Next:** R4c — views_v3.py Sites 1, 2, 3

**R4c COMPLETE (2026-10-31 ~09:35)** — Sites 1, 2, 3 refactored:
- Site 1 STORY_HEAL: points_ledger.award with evidence kc_code + story_hash (sha256 of story lines)
- Site 2 ATTENDANCE_REDEEM: points_ledger.penalize (preserves -1 sign) with evidence attendance_id
- Site 3 KC_CONTRIBUTED: points_ledger.award with evidence qid + kc_code
- Backup: .bak.batch5_88_r4c_v3_20261031_093334
- E2E: 13/13 checks pass
- **Lesson:** regex lambda replacement prevents backslash escape; py_compile inside patch script catches syntax errors
- **Next:** R4d — TEACHER_GRANT nonce pattern

**R4d COMPLETE (2026-10-31 ~10:05)** — Sites 4, 5 + adjust() + nonce:
- New ledger function `points_ledger.adjust()` — signed-value preserving (positive grant, negative deduct)
- Site 4 bulk_award_points: `points_ledger.adjust(evidence={'grant_nonce'})` in loop
- Site 5 grant_points (exam branch): `points_ledger.adjust(evidence={'grant_nonce'})`
- Nonce: session-backed `uuid.uuid4().hex[:16]`, validated on POST, rotated after success
- Template: 2 hidden `grant_nonce` inputs in `portal_teacher_control.html`
- Backup: `.bak.batch5_88_r4d_v3_*`
- E2E: 10/10 pass (sign preservation, bulk idempotency, nonce uniqueness)
- **Lessons learned:**
  1. Multi-line regex for Site 5 kept missing — line-based replacement is whitespace-immune and succeeded on first attempt.
  2. Handover must be updated AFTER verification, not before. Corrected PARTIAL → COMPLETE.

**Next:** R4e — Sites 8 (STARTING_BONUS) + 9 (QUESTION_MASTERED)

**R4e COMPLETE (2026-10-31 ~10:15)** — Sites 8, 9 refactored:
- Site 8 (allot_points.py): `STARTING_BONUS` → `points_ledger.award(evidence={})` inside loop with `if _r is not None:` count increment
- Site 9 (pipeline_state.py): `QUESTION_MASTERED` → `points_ledger.award(evidence={'qid'})`, returns `r is not None` (preserves True/False)
- **Bugs caught and fixed during execution:**
  1. Post-check counted docstring occurrences of `points_ledger.award` — changed to code-only substring `_r = points_ledger.award(` and `r = points_ledger.award(`
  2. First E2E test polluted DB — ran `allot_points` which gave 11 legitimate bonuses to students lacking one; auto-reverted patch left orphans (test paper, question, TEST-R4E-FRESH student). Cleaned up. The 11 STARTING_BONUS rows were signed with migrate_legacy_idem before R4e patch to prevent future double-award.
  3. E2E test's Site 8 check was wrong (`assert command added 0 rows`) — corrected to run command TWICE, assert second run adds 0 rows (the real idempotency test)
- Backup: `.bak.batch5_88_r4e_v2_*`
- E2E: 12/12 pass (historical blocked, new awarded, second-run idempotent)
- **All 10 sites now use points_ledger** — R4 refactor complete pending R4f final affirmation

**Next:** R4f — full 10-site E2E reaffirmation script

**R4f COMPLETE — R4 CLOSED (2026-10-31 ~10:30)**
- **Final audit:** All 5 files compile, 0 raw `CreditEvent.objects.create` in teller files, all 10 codes go through `points_ledger`, 420/420 migrated rows signed, sandbox parity 0.
- **Total signed:** 345 QUESTION_MASTERED + 75 STARTING_BONUS = 420 (up from 408 — R4e patch exposed 12 new unsigned rows from v1 test artifacts)
- **Grandfathered:** MASTERY_STEP (852+), CONTRIBUTION_REWARD (71+), KC_CONTRIBUTED (61+), STORY_HEAL (7+), ATTENDANCE_REDEEM, RETRY_PENALTY, TEACHER_GRANT — historical rows stay unsigned, new awards signed
- **R4 status:** COMPLETE

### R4 Final Scorecard (10/10 tellers refactored)
| # | Teller | Phase | Ledger fn | Evidence key |
|---|---|---|---|---|
| 1 | STORY_HEAL | R4c | award | kc_code + story_hash |
| 2 | ATTENDANCE_REDEEM | R4c | penalize | attendance_id |
| 3 | KC_CONTRIBUTED | R4c | award | qid + kc_code |
| 4 | TEACHER_GRANT (bulk) | R4d | adjust | grant_nonce |
| 5 | TEACHER_GRANT (single) | R4d | adjust | grant_nonce |
| 6 | RETRY_PENALTY | R4a | penalize | attempt_id |
| 7 | CONTRIBUTION_REWARD | R4b | award | contribution_id |
| 8 | STARTING_BONUS | R4e | award | {} |
| 9 | QUESTION_MASTERED | R4e | award | qid |
| 10 | MASTERY_STEP | R4b | award | qid + step |

### R4 sub-phase backups (rollback chain)
- R4-pre: `/tmp/credit_events_pre_r4pre_backup.json` + `archive/credit_events_pre_r4pre_20261031_075222.json`
- R4a: `.bak.batch5_88_r4a_20261031_081358`
- R4b: `.bak.batch5_88_r4b_20261031_082547`
- R4c: `.bak.batch5_88_r4c_v3_20261031_093334`
- R4d: `.bak.batch5_88_r4d_v4_*`, `.bak.batch5_88_r4d_v3_*`
- R4e: `.bak.batch5_88_r4e_v2_20261031_101740`

### Handover — Next Phase
**Token Queue System (T1–T8)** — queued in §11 P1, design approved.
**MDD Chunk 6 correction** — §5.1 PointTransaction rollback note (P2)
**MDD Phase 2** — creature capture on SAFAR (P3)

**REFACTOR SAFE + R4 FULLY CLOSED (2026-10-31 ~10:45)**
- Duplication refactor verified: 37/37 R4f audit + 10/10 R4d E2E + 12/12 R4e E2E all pass
- points_ledger.py: 112→80 lines, 4 public functions now thin wrappers around `_write_credit_event()` helper
- views_v3.py: 3 inline imports removed (top-level already present)
- Backup: `.bak.batch5_89_20261031_103601`
- Sandbox synced, parity 0

### R4 — FULLY CLOSED. 10/10 tellers signed. Economy industry-compliant.

---

**TOKEN QUEUE SYSTEM (T1–T8) — STARTED (2026-10-31 ~10:50)**

### Design (approved in §5)
- FIFO queue (hospital/bank bari pattern) for physical test appointments
- Batch size configurable 1–50 via `GlobalStudyConfig.exam_batch_size`
- Grace period configurable via `GlobalStudyConfig.exam_grace_minutes` (default 15 min)
- One active token per student (DB constraint)
- Token numbers sequential per day, never renumbered
- Anti-cheat gate: student can only access `portal_teacher_paste` if token is CALLED/IN_PROGRESS

### Sub-phase tracker
| Phase | Scope | Status |
|---|---|---|
| T1 | ExamToken model + GlobalStudyConfig fields + migration | ✅ this session |
| T2 | exam_queue.py service (issue_token, call_next, mark_in_progress, complete, skip, cancel) | ⏳ next |
| T3 | Student views + template (request_token, my_token, cancel_token) | ⏳ |
| T4 | Teacher panel (queue view, call_next, mark, complete, skip) | ⏳ |
| T5 | Anti-cheat gate in portal_teacher_paste | ⏳ |
| T6 | `manage.py expire_stale_tokens` cron | ⏳ |
| T7 | E2E test (3 students, 1 batch, full flow) | ⏳ |
| T8 | Sandbox sync + parity | ⏳ |

### Post-T1 Backlog
- P2: MDD Chunk 6 — correct §5.1 (PointTransaction rolled back)
- P3: MDD Phase 2 — creature capture on SAFAR
- P4: Teacher approval queue for AI KCs
- P5: `manage.py prepare_all_content` bulk command

**T2 COMPLETE (2026-10-31 ~16:00)** — exam_queue.py service live:
- File: `exams/services/exam_queue.py` (189 lines)
- **6 public functions:**
  - `issue_token(student)` — FIFO, select_for_update, max+1, duplicate-safe
  - `cancel_token(student)` — only from PENDING
  - `get_queue_for_student(student)` — returns (token, ahead_count)
  - `call_next(count, user)` — teacher batch call, moves PENDING → CALLED
  - `mark_in_progress(token)` — CALLED → IN_PROGRESS
  - `complete_token(token, attempt)` — IN_PROGRESS → COMPLETED with attempt link
  - `skip_token(token, reason)` — manual skip
  - `expire_stale_tokens(grace_minutes)` — auto-skip cron helper
  - `get_queue_snapshot()` — teacher panel data
  - `check_anti_cheat_gate(student)` — the T5 gate helper
- All state transitions logged (`QUEUE_ISSUED`, `QUEUE_CALLED`, `QUEUE_COMPLETED`, `QUEUE_SKIPPED`, `QUEUE_CANCELLED`, `QUEUE_AUTO_EXPIRED`, `QUEUE_DUPLICATE`)
- `select_for_update` on every atomic block — race-condition safe
- Smoke test: 15/15 OK — FIFO ordering, duplicate rejection, anti-cheat gate, lifecycle transitions all verified
- Backup: `.bak.batch5_90_t1_20261031_105124` (models.py)

**Next:** T3 — Student views (request_token, my_token, cancel_token) + template

**T2 COMPLETE (2026-10-31 ~16:00)** — exam_queue.py service live:
- File: `exams/services/exam_queue.py` (189 lines)
- **6 public functions:**
  - `issue_token(student)` — FIFO, select_for_update, max+1, duplicate-safe
  - `cancel_token(student)` — only from PENDING
  - `get_queue_for_student(student)` — returns (token, ahead_count)
  - `call_next(count, user)` — teacher batch call, moves PENDING → CALLED
  - `mark_in_progress(token)` — CALLED → IN_PROGRESS
  - `complete_token(token, attempt)` — IN_PROGRESS → COMPLETED with attempt link
  - `skip_token(token, reason)` — manual skip
  - `expire_stale_tokens(grace_minutes)` — auto-skip cron helper
  - `get_queue_snapshot()` — teacher panel data
  - `check_anti_cheat_gate(student)` — the T5 gate helper
- All state transitions logged (`QUEUE_ISSUED`, `QUEUE_CALLED`, `QUEUE_COMPLETED`, `QUEUE_SKIPPED`, `QUEUE_CANCELLED`, `QUEUE_AUTO_EXPIRED`, `QUEUE_DUPLICATE`)
- `select_for_update` on every atomic block — race-condition safe
- Smoke test: 15/15 OK — FIFO ordering, duplicate rejection, anti-cheat gate, lifecycle transitions all verified
- Backup: `.bak.batch5_90_t1_20261031_105124` (models.py)

**Next:** T3 — Student views (request_token, my_token, cancel_token) + template

**T3 COMPLETE (2026-10-31 ~16:15)** — Student-facing token views + template live:
- **3 views** appended to `exams/views_v3.py`: `portal_exam_token_status`, `portal_exam_token_request`, `portal_exam_token_cancel`
- **3 URLs** added to `exams/urls.py`:
  - `/api/portal/exam-token/` → `portal-exam-token-status`
  - `/api/portal/exam-token/request/` → `portal-exam-token-request`
  - `/api/portal/exam-token/cancel/` → `portal-exam-token-cancel`
- **Template:** `exams/templates/exams/portal_exam_token_status.html` — 75 lines, extends base.html, auto-refresh 10s when PENDING/CALLED, shows batch size + position + cancel button
- **Smoke test:** 11/11 OK — GET/request/GET/cancel flow verified end-to-end
- **Backup:** `.bak.batch5_90_t3_*`

**Next:** T4 — Teacher queue panel view + template

**T4 COMPLETE (2026-10-31 ~16:30)** — Teacher queue panel live:
- **5 views** appended to `exams/views_v3.py`:
  - `teacher_exam_queue` — GET dashboard
  - `teacher_exam_call_next` — POST batch call
  - `teacher_exam_mark_started` — POST CALLED → IN_PROGRESS
  - `teacher_exam_complete` — POST IN_PROGRESS → COMPLETED
  - `teacher_exam_skip` — POST any → SKIPPED with reason
  - All gated by `request.user.is_staff or is_superuser`, else 302 redirect
- **5 URLs** added under `/api/portal/teacher/exam-queue/*`
- **Template:** `exams/templates/exams/teacher_exam_queue.html` (~140 lines):
  - Shows batch size, grace period, waiting count
  - "Call Next N" button
  - 4 sections: In Progress, Called, Pending, Recent
  - Inline action buttons per row (start, complete, skip)
- **Smoke test:** 13/13 OK — teacher calls, student submits, teacher completes, non-staff denied
- **Backup:** `.bak.batch5_90_t4_*`

**Next:** T5 — Anti-cheat gate in `portal_teacher_paste` (reject student if no CALLED/IN_PROGRESS token)

**T5 PARTIAL — GATE IN WRONG LOCATION (2026-10-31 ~17:00)** — Correction:
- **T5 attempted but aborted safely.** Patch found `portal_teacher_paste` in `exams/views.py` but the actual student-facing endpoint is `paste_single_question` in `exams/views_v3.py` (delegated from `portal_teacher_paste` when `?qid=` is present).
- **Smoke test failed as expected:** `no-token student: 302 (got 200)` — confirmed gate was never inserted.
- **views.py:** correct — bulk teacher paste requires staff, students never reach it. Not the right gate location.
- **views_v3.py `paste_single_question`:** the actual student submission endpoint. This is where the gate belongs.
- **Backup preserved:** `.bak.batch5_90_t5_20261031_111126` (views.py unchanged since backup was pre-abort, no restore needed since no writes occurred)
- **Sandbox parity 0** (nothing changed in prod, nothing synced)
- **Batching started:** per user request, next batch groups T5-fix + T6 + P2 as one atomic apply-or-restore script.

**Next:** Batch 1 — T5 fix (gate in paste_single_question) + T6 (expire_stale_tokens cron) + P2 (MDD §5.1 correction)

**BATCH 1 COMPLETE (2026-10-31 ~17:45)** — Token system findable, T5 gate live, T6 cron, P2 MDD correction, **zero inline styles introduced by this session**:

- **T5 FIXED:** Anti-cheat gate in `paste_single_question` (views_v3.py). 4/4 checks pass.
- **T6 CREATED:** `expire_stale_tokens.py` management command. Verified: "No stale tokens past 15min grace."
- **P2 MDD:** Chunk 6 appended — §5.1 PointTransaction marked SUPERSEDED.
- **Navigation:**
  - Student nav (`_app_shell_nav.html`): "🎫 Test Token" (desktop + mobile)
  - Teacher nav (`_teacher_topbar.html`): "📋 Exam Queue" — **wrong template, only used on 2 subpages**
  - **CORRECTED:** Exam Queue link added to `portal_teacher_home.html` (the actual teacher home) after diagnosing that `/api/portal/teacher/` doesn't include `_teacher_topbar.html`
- **CSS violations fixed** (session-created):
  - `portal_exam_token_status.html`: removed `style="max-width: 720px"` → `.exam-token-container`
  - `teacher_exam_queue.html`: removed 4× `style="display:inline;"` → `.form-inline`
  - 2 new classes added to `ideal_v2.css`
- **Smoke test:** 7/7 pass (T5 gate ×4, student nav, teacher nav, T6 command)
- **Backups:** `.bak.batch5_91_*` (initial) + `.bak.batch5_91_fix_*` (CSS cleanup)

**Note:** Pre-existing inline styles in `_app_shell_nav.html` (200+ line `<style>` block), `base.html`, and other templates are NOT from this session and remain as separate tech-debt to address in a dedicated CSS-extraction refactor.

**Next:** Batch 2 — P3 creature capture on SAFAR


---

## SESSION 2026-10-31 (evening) — MDD Phase 1 + Workshop UI SHIPPED

### Batches completed this session (backup tag `batch5_9X_<TS>`)

| Batch | Scope | Files | Backup tag |
|---|---|---|---|
| **2** | Creature capture on RPSItem GRADUATED | 6 | `.bak.batch5_92_20261031_122428` |
| **3** | Workshop models (ConceptScaffold / QuestionBlueprint / SystemImprovementTask) + migration | 3 | `.bak.batch5_93_20261031_123413` |
| **4** | `manage.py prepare_all_content` (490 KCs seeded) | 5 | (no source backups — new only) |
| **5** | Student scaffold block — templatetag + inclusion template + CSS | 4 new, 2 modified | `.bak.batch5_95_20261031_123810` |
| **5b** | CSS palette fix (tokens, not hardcoded hex) | 1 | `.bak.batch5_95b_20261031_125435` |
| **6a** | Workshop views + urls + project wire + CSS classes | 4 | `.bak.batch6a_20261031_125834` |
| **6b** | Workshop templates (6 files) + cache bust | 7 | `.bak.batch6b_retry_20261031_130151` |
| **7** | Editable scaffold forms (save / approve / toggle blueprint) | 2 | `.bak.batch5_97_20261031_130527` |
| **8** | Nav link + handover + final E2E | 2 | `.bak.batch5_98_20261031_131123` |

### What is LIVE now

**Student-side:**
- If a KC's `ConceptScaffold.is_approved = True`, the student sees a styled scaffold block (Roman Urdu intro, vocabulary bridge, Socratic hints) at the top of `portal_question_detail.html`.
- If unapproved — no change to student experience. Zero risk to existing content.

**Teacher-side (`/workshop/`, staff-only):**
- `/workshop/` — dashboard: 490 scaffolds pending, blueprints active count, review queue stats
- `/workshop/review/` — filterable review queue (PENDING / APPROVED / REJECTED)
- `/workshop/review/<pk>/` — approve / reject / reopen with notes
- `/workshop/blueprints/` — KC list with scaffold-approval status per KC
- `/workshop/blueprints/<kc_code>/` — edit Roman Urdu intro, vocabulary, hints; approve; toggle blueprints active

**Capture-side:**
- When `RPSItem.mastery_state` becomes `GRADUATED`, `game/signals.py::capture_on_graduation` ensures a KCCard exists.
- `manage.py backfill_captures` seeded 3 historical pairs (students 11, 24).
- Idempotent — re-running adds 0.

### Verified (E2E)

- Workshop POST save → `SAVE_OK`, `APPROVE_OK`, `TOGGLE_OK`, `RESTORED` (test data reverted)
- Workshop GET → all routes 200 for superuser
- Anon → 302 (redirect to login). Non-staff → 403.
- Parity prod ↔ sandbox: **0**

### Pre-existing issues noted (not from this session)

- MySQL warnings: `ExamToken` + `QuestionCorrectionRequest` use partial unique constraints that MySQL silently drops. Enforced in app code; not a regression.
- No superuser other than `sharjeel` — noted for role audit.

### Next AI must read

`03_NEXT_AI_STARTUP_PROMPT.md` — this section is now the most current. The §4 table in that file still says "Batch 2 pending" — **it is now COMPLETE**.

**BATCH 1.6 v2 COMPLETE (2026-10-31 ~20:00)** — Task 1 delivered and verified:

- **portal_my_notes**:
  - Pagination 20/page (`Paginator(qs, 20)`)
  - Edit handler (POST action='edit', IDOR-safe via `filter(student=student)`)
  - Delete handler (POST action='delete', IDOR-safe)
  - Per-note ✏️ Edit Answer (collapsible `<details>`) + 🗑 Delete buttons
  - Pagination controls preserving subject/search filters
  - `notes_total` shows total across all pages
- **portal_teacher_support**: Pagination 25/page + pagination controls preserving status/category filters
- **portal_teacher_home**: New blue **Physical Test Queue** card with live Pending/Called/In Progress counts (via `{% exam_queue_counts %}` template tag)
- **New file**: `exams/templatetags/queue_tags.py` — `exam_queue_counts` simple_tag
- **CSS additions**: `.pagination*`, `.note-actions`, `.note-edit-panel`, `.queue-summary-card`, `.queue-stat` — zero inline styles
- **Smoke test**: 20+ checks pass (physical template markers, create/edit/delete cycle, IDOR protection, pagination markup, queue card live counts)
- **Backups**: `.bak.batch5_93_v2_*`
- **Sandbox parity**: 0

**Task 1 status: COMPLETE.**
- Teacher support: 25/page ✅
- My notes: 20/page + edit + delete + IDOR-safe ✅
- Teacher home: visible queue card with live counts ✅

**Batch 1.7 backlog** (next session, same category):
`my_results`, `my_todo`, `my_papers`, `student_question_errors`, `teacher_corrections_list`, `teacher_approve_edits`, `teacher_story_review`, `owner_delegations`, `teacher_health`, `teacher_violations`, `teacher_analytics`, `portal_health`, `teacher_ops`, `teacher_stage_completions`, `portal_parent_engagement`

**Anti-Cheat (Task 2):** user approved. `daily_code.py` service exists. `portal_teacher_daily_codes` view exists. `submit_daily_code_view` exists at `views_v3.py:672`. `AttemptLog.daily_code` field exists. Duplicate audit: 1,748 groups / 3,279 extra rows in 9th grade (needs cleanup plan before merge).

**BATCH 1.7 COMPLETE (2026-10-31 ~21:15)** — Task 2: Anti-Cheat Merge

### Layer 2 — Daily code gate in `paste_single_question`
- Students: must POST valid `daily_code`. Missing → error. Invalid → error. Both redirect back.
- Staff/superuser: bypass with `daily_code='STAFF'` (audit trail preserved)
- Staff-not-superuser: must use `?student_id=X` (pre-existing behavior)
- `AttemptLog.daily_code` records actual code (was hardcoded 'INDIVIDUAL')

### Layer 3 — Duplicate prevention
- `_is_duplicate_text(student, candidate_q)` helper in `views_student_pipeline.py`:
  - Skips text <20 chars and text starting with '<' (avoids blank / MathML false positives)
  - Otherwise checks `StudentQuestionLock.filter(student, is_active, question__question_text=text[:500]).exists()`
- Applied in `select_questions.confirm_all` — skips dupes, adds "(N duplicate sawal skip kiye gaye.)" to message
- Applied in `daily_mission_engine.get_daily_mission_questions` — cursor-based fallback when filtering

### Request Change flow
- New endpoint `portal_request_question_change` in `views_v3.py`:
  - POST → creates `QuestionEditRequest(student, question, new_question_text, new_model_answer)` status='PENDING'
  - IDOR-safe (scopes qid to standard + own SELF-/CUSTOM-)
  - One pending per question per student
- URL: `/api/portal/request-question-change/` → `portal-request-question-change`
- UI: `<details>` "🔄 Request Change" panel in `portal_daily_mission_v3.html` at ATTEMPT stage
- Teacher sees requests in existing `teacher_approve_edits` queue

### Files patched (7)
1. `views_v3.py` — Layer 2 gate + new endpoint
2. `views_student_pipeline.py` — helper + confirm_all patch
3. `daily_mission_engine.py` — duplicate filter in auto-pick
4. `urls.py` — new URL
5. `portal_paste_single.html` — daily_code input
6. `portal_daily_mission_v3.html` — Request Change panel
7. `ideal_v2.css` — `.change-request-panel` class

### Backups
`.bak.batch5_94_20261031_135006` for all 7 files

### Smoke test
22/22 checks pass (T5 gate, Layer 2 no/wrong/correct code, staff bypass, dup helper, request change + dup block)

### Test-fix lessons for future
- v1 fail: `call_next` picked leftover PENDING token (FIFO). Fix: delete ALL today's tokens in test cleanup, not just target student.
- v2 fail: superuser test lacked `?student_id=` → `_current_student` resolved to first active student. Fix: staff bypass test must pass `?student_id=X`.

### Anti-cheat Task 2 status: COMPLETE
All four components (Token / Daily code / Duplicate prevention / Request Change) live and verified.

### Deferred to Batch 1.8
- Duplicate cleanup of 1,748 existing groups (data migration + teacher review)
- Teacher review UI pagination for `QuestionEditRequest` queue
- `duplicate_override` flag on `StudentDailyCode` for teacher permission to assign duplicates
- Layer 3 UI integration test (submit duplicate during actual `select_questions` flow)

**BATCH 1.8 COMPLETE — Task 3: 5-Layer Anti-Cheat (2026-10-31 ~21:50)**

### Layer 4 — AI JSON question_id validation ✅
- Prompt requires `"question_id": {question.id}` in AI output; JSON example + RULES block added
- `paste_single_question` validates `parsed.get('question_id')` after `_parse_ai_json`:
  - Missing → error, redirect to paste form
  - Non-integer → error, redirect
  - Mismatch with assigned question → error, redirect
- `AttemptLog.result_json.ai_question_id` stores AI's claim for audit trail
- UI: "🎯 Assigned Question ID" panel on paste form with copy button
- **Tests 1-3 pass**: missing/wrong rejected, correct accepted with audit field

### Layer 3 (expanded) — History-aware duplicate prevention ✅
- `_is_duplicate_text(student, candidate_q)` now checks 3 sources:
  1. `StudentQuestionLock` active → duplicate
  2. `StudentQuestionLock` inactive → duplicate unless `RetakeTicket(status='FAILED')` for original question
  3. `AttemptLog` past attempt → duplicate unless `RetakeTicket(status='FAILED')`
- Local imports inside function (`from exams.models import AttemptLog as _AL, RetakeTicket as _RT`) — matches codebase pattern
- Skips text <20 chars and text starting with '<' (avoids blank/MathML false positives)
- **Tests 4-7 pass**: active dup, inactive dup, retake allowed, past-attempt dup

### Layer 5 — Calendar rebuild fallback ✅
- In `portal_daily_mission_v3`: if `StudentDayMission` count for current day is 0 AND student has active locks → rebuild from locks
- Logs `MISSION_CALENDAR_REBUILT` (warning) / `MISSION_CALENDAR_REBUILD_FAILED` (error)
- **Test 8 fired live**: `[views_v3] WARNING MISSION_CALENDAR_REBUILT student=s-0088 day=3 created=1`

### Files patched (4)
1. `views_v3.py` — Layer 4 validator + prompt + Layer 5 rebuild
2. `views_student_pipeline.py` — `_is_duplicate_text` expanded + local imports
3. `portal_paste_single.html` — question ID panel + placeholder
4. `ideal_v2.css` — .font-mono

### Backups (rollback chain)
- `.bak.batch5_95_v2_20261031_141939` (initial 4)
- `.bak.batch5_95_v2_import_fix_20261031_144240` (RetakeTicket)
- `.bak.batch5_95_v2_attemptlog_fix_20261031_144748` (AttemptLog)

### Smoke test
**14/14 checks pass** — all layers verified live

### Sandbox parity
**0** after sync of 4 files

### Menu diagnostic
- CSS rules verified correct: `.mobile-menu { display: none }`, media query `<900px` hides `.nav-links` + shows `.mobile-toggle`, `.is-open` toggles `.mobile-menu` to `display: block`
- No override, no duplicate rule
- Likely browser cache — pending user hard-refresh confirmation

### Anti-cheat Task 3: COMPLETE

| Layer | Mechanism | Status |
|---|---|---|
| 1 | Token (CALLED/IN_PROGRESS) | ✅ Batch 1 |
| 2 | Daily code | ✅ Batch 1.7 |
| 3 | Duplicate prevention (active + inactive + attempts, retake-aware) | ✅ Batch 1.8 |
| 4 | AI JSON question_id identity | ✅ Batch 1.8 |
| 5 | Calendar rebuild fallback | ✅ Batch 1.8 |
| Flow | Request Change button | ✅ Batch 1.7 |

### Deferred to Batch 1.9 (data cleanup project)
- Cleanup of 1,748 existing duplicate groups (needs careful migration planning)
- Teacher review UI pagination for `QuestionEditRequest` + `QuestionCorrectionRequest`
- `duplicate_override` flag on `StudentDailyCode`
- Server-side AI grading (backend key, no client JSON injection)
