# FINAL HANDOVER - IDEALOGY API

**Current State:** STABLE. Multi-step reasoning, Workshop, CHOICE mode, and Daily Code uploads are LIVE.
**Server clock:** UTC. All cron times below are UTC.

## GOLDEN RULES (NON-NEGOTIABLE)

**READ, BACKUP, REWRITE. NO CHANGE WITHOUT QUALIFICATION.**

Qualify every file before patching:
1. Read the exact current bytes (ast.parse for line numbers).
2. Read every file that imports it and every file it imports.
3. Read every caller of functions you change.
4. Read the template if touching a view that renders it.
5. State: what it does now, what your change does, why it is safe, what breaks if wrong.

**If you guess, it will fail.** Prior sessions burned hours on UnboundLocalError and MySQL Duplicate entry bugs.

### Batching rule
- Max 10 files per batch.
- Each batch is atomic: apply-or-restore.
- Each batch creates .bak.batchN_TS backups.
- If py_compile, manage.py check, or the smoke test fails, restore all files and report failure.
- Do not declare COMPLETE until a django.test.Client smoke test passes.

## TRAPS TO AVOID

1. **Heredocs and multi-line pastes corrupt in this SSH session.** Five cat EOF attempts truncated or mangled (manage.pEOFssign_daily_questions). For critical files use nano, or printf chunks, and verify with wc -l.
2. **Do not paste multi-line blocks into this shell.** Long pastes collapse newlines and drop spaces. One command per paste when long; otherwise write to a file and bash -n it first.
3. **Duplicate entries:** in smoke tests use get_or_create with a dummy ID (day_number=99) to avoid MySQL 1062.
4. **Template syntax:** {% %}, never {{% %}}.
5. **AST over string matching:** do not .replace() on code blocks. Use ast.parse to find line range and slice.

## PROJECT OVERVIEW (LIVE)

1. **Workshop** /workshop/ - teacher control panel.
2. **Multi-Step Reasoning** /api/portal/step-reasoning/<qid>/ - works with 0 questions populated; student hits roadblock, copies prompt, pastes AI response, unlocks for everyone.
3. **Upload Center** /api/portal/upload-center/
   - Morning (07:00-14:00) / Evening (14:00-07:00) split by server time.
   - Reads StudentDailyCode.per_book_codes (e.g. PH:1, MA:2).
   - Audit ledger via StudentDayMission.
   - CHOICE mode: when a teacher grants CHOICE delegation, the daily code check is bypassed and one upload applies to all questions in the subject.
4. **Auto-assignment** manage.py assign_daily_questions - runs via cron at 03:00 UTC = 08:00 PKT.
5. **StudentNotification** - in-app notifications, expire after 1 hour. Migration 0138_studentnotification.

## WHAT TO DO NEXT

1. **Verify the cron line fires.** Check /home/orkoworo/idealogy/logs/auto_assign.log after 03:00 UTC.
2. **Test assign_daily_questions manually.** Past 08:00 PKT; running now should populate StudentDayMission for students with an empty ledger today:
   cd /home/orkoworo/idealogy/api && /home/orkoworo/virtualenv/idealogy/api/3.13/bin/python manage.py assign_daily_questions
3. **Test upload flow in browser:** grant CHOICE key at /workshop/upload-keys/, open /api/portal/upload-center/ as that student, confirm Morning/Evening list matches server time, upload - code check should be bypassed.

## SANDBOX PARITY

Sandbox is a partial mirror, not byte-identical. Parity script: /home/orkoworo/parity.sh.
Excludes: settings.py, secrets.py, db*.sqlite3, staticfiles, media, __pycache__, *.bak*, *.swp, passenger_wsgi.py, .user.ini.
Synced last session: models.py, models_delegation.py, services/daily_code.py, migrations 0136/0137/0138, static CSS (ideal_main_p3, kc_studio, main_v4), seven templates/exams/*.html.
0138 applied in both DBs. makemigrations --check --dry-run returns No changes detected on sandbox.

## CRON (UTC)

12 active jobs. Notable:
- 0 3 * * * - assign_daily_questions (08:00 PKT)
- 0 2 * * * - nightly DB backup
- 0 3 * * 0 / 15 3 * * 0 / 30 3 * * 0 - Sunday session purges
- 0 * * * * - expire_discipline_delegations
- */15 6-22 * * * - audit_lint and control_room_verify

If you add a job, create its log dir first - cron drops output silently otherwise.

## RECENT MIGRATIONS

- 0136_alter_taskdelegation_task_type
- 0137_taskdelegation_delegation_mode
- 0138_studentnotification

---

**Read the files, qualify your changes, back them up, verify with a smoke test.**
Also synced later: exams/urls.py, views_student_pipeline.py, views_task_hub.py, utils_class.py, idealogy_api/middleware.py, PIPELINE_PHYSICAL_TEST.md, portal_teacher_daily_codes.html, portal_upload_center.html, and workshop/{urls.py, views.py, physical_pipeline_hub.html, pipeline_guide.html, teacher_upload_hub.html, teacher_upload_student.html, upload_keys_hub.html}.

## BUG FIXES (post-handover)

- assign_daily_questions.py: pytz -> zoneinfo (pytz missing in prod venv). Backup: .bak.pytz_fix
- assign_daily_questions.py: now filters question_index=qnum (was always Q1). Backup: .bak.qnum_fix
- daily_code.py edit_code: now writes nested per_book_codes[session][abbr]. Backup: .bak.edit_code_fix
- Known anomaly: day 2 has 37 rows where code != 1, plus duplicate s-0062 entries (manual clicks, prior test scripts). Not cleaned up. Day 3+ will be clean via fixed cron.

## SESSION 2026-11-02 EVENING — select_questions writes SDM

- `views_student_pipeline.py` `confirm_all` now writes `StudentDayMission` rows with `position=1..N` matching student selected order. Previously only wrote `StudentQuestionLock`, so selections vanished at midnight reset. Backup `.bak.select_sdm`.
- Verified: S-0002 staged 8 books × 3 qids, POST → 302, SDM got 24 rows pos1/2/3 → Q1/Q2/Q3 per subject.

## STILL OPEN (priority order)

1. CHOICE delegation copies to StudentQuestionLock, not SDM. When master answer graded correct, must credit all SDM rows for the same (student, day, subject).

2. portal_submit_custom_question (write-own) and teacher_approve_edits (custom approval) write SDM without position - will reappear as null rows.

3. AttemptLog.master_attempt_id FK not added (currently result_json.copied_from as JSON string, no referential integrity).

4. UploadAudit append-only table not created. Every upload attempt (pass/fail) should log: student, token, day, subject, question, code, accepted, reason, IP.

5. Anti-cheat gate (exams/services/exam_queue.check_anti_cheat_gate) allows PENDING tokens. Should require CALLED or IN_PROGRESS per ISO 27001 A.9.4.

6. select_questions guardrail (block re-selection after upload today) not yet added.

## TOMORROW-MORNING WATCH

- 03:00 UTC: cron fires. Check `/home/orkoworo/idealogy/logs/auto_assign.log` — should show S-XXXX lines for every active student with content.
- Day 3 SDM should have one row per (subject, position=1..pace) per student, `position` populated everywhere.
- Teachers use `/api/portal/teacher/daily-codes/` to set codes. Upload center shows matching question per code.
- If any student shows "No question assigned" — check their SDM exists for that subject/position, or their pace, or that class has ModelPaper content.


## ATTEMPT POLICY SYSTEM (Phase 4 Complete)

- `DayAttemptPolicy` model: per-day status (LOCKED / PAST_REATTEMPT / FUTURE_PRACTICE), max_attempts, late_penalty_pct
- `AttemptLog` new fields: is_practice, is_late, target_day_number
- Upload flow: policy gate FIRST, then time gate (current-day only), then attempt creation
- Teacher UI: date nav (Y/T/T), policy toggle card on /teacher/daily-codes/
- Student UI: 🔄 Retry / ▶️ Practice badges on calendar
- Mizan excludes is_practice=True attempts from missed count
- Late penalty (10% default) applied to past-day re-attempts
- Backups: all `.bak_phaseX` files preserved for rollback
