# Developer C — Learning Runtime (Learner-First)

**Scope:** the `learning` database (+ `engagement`-hosted parent-child link records and parental
control settings per the domain map). The runtime where learners actually consume catalog:
enrollment, progress & resume, attempts & grading, SRS state, flashcard/mind-map/notes work,
study plans, target-exam instances, AI companion state, and the parent-child link + parental
controls runtime.
**Depends on Track A for:** auth, entitlement (`SubscriptionService::isEntitled`), seats,
parent-child link *records*, consents.
**Depends on Track B for:** `CatalogService`, SRS config, AI config, exam definitions.
**Serves Track D via `ProgressService`** (dashboards, insights, parent monitoring).

Legend: `DEPS:` = hard dependency (must be DONE). `DEPS⚡:` = contract-only.

---

## PHASE 0 — Learning Foundations

### T-C-01 · Learning base model + connection lock
- `BaseLearningModel` extends A's base with `$connection = 'learning'`; models in
  `app/Models/Learning/`. Migration folder `database/migrations/learning/`.
- Cross-domain reference convention: `user_id`, `course_id`, `content_id` are **plain
  indexed columns (no FK)** pointing into identity_billing/catalog — enforced by lint/test.
- **DEPS:** T-A-01
- **AC:** test asserts all `Models/Learning` use learning connection AND contain no
  `$foreignKeyConstraints` cross-DB; migration folder green on learning SQLite sim.

### T-C-02 · `ProgressService` interface (contract for D)
- `App\Services\Learning\ProgressService`: `courseProgress(userId)`, `topicMastery(userId)`,
  `streak(userId)`, `attemptsSummary(userId)`, `timeSpent(userId, window)`,
  `weakTopics(userId)`.
- Stub in Phase 0 (empty) so D compiles; real impl lands with T-C-04/T-C-05/T-C-07.
- **DEPS:** T-A-01, T-A-06
- **AC:** interface + stub merged; D can inject via mock; docblock: never cross into other DBs.

### T-C-03 · Entitlement + access gate for playback
- `AccessGate` service composes: subscription entitlement (A, DEPS⚡ T-A-17) ∩ enrollment
  (T-C-04) ∩ parent content restrictions (T-C-13) ∩ DRM flags (B, DEPS⚡ T-B-06).
- Returns `allow | preview | deny(reason)` — reason drives the 403/upgrade message.
- **DEPS:** T-C-01, DEPS⚡ T-A-17, DEPS⚡ T-B-03
- **AC:** playback of entitled, enrolled, unrestricted content → allow; each of the 4 gate
  conditions failing independently produces the correct deny reason (4 tests); preview only
  for unentitled with sample access.

---

## PHASE 1 — Course Consumption

### T-C-04 · Enrollment + course/content progress + resume
- `enrollments`: user, course, status (not_started/in_progress/completed/dropped), progress %.
- Enroll/drop/re-enroll; drop requires confirmation, **progress preserved for re-enrollment**.
- `content_progress` (per video/episode/unit): state, `last_position_seconds`, speed pref;
  **complete only when watched to end (or completion threshold); re-watching never reverts
  status**; resume returns to last saved position; cross-device sync.
- Course completion requires **all required** content (optional doesn't block); feeds
  certificates (T-C-10) + analytics (event to D).
- Locked progression (from B's course rule): unit completion gates next unit; rule change
  never invalidates completed units.
- Emits `ContentCompleted` (feeds D gamification + parent + SRS).
- **DEPS:** T-C-03, DEPS⚡ T-B-05
- **AC:** progress % recomputed on complete (test); re-watch keeps complete (test); drop →
  re-enroll restores position (test); completion of all required → course complete event;
  locked unit: next unit 403 until prior complete (test).

### T-C-05 · Attempts, results, grading (quiz/exam/mock/past-paper)
- `attempts`/`answers`: per learner; states answered/flagged/unanswered; timer (auto-submit
  at expiry; unanswered recorded as unanswered, not zero-marked-answered).
- Instant objective grading; **multi-select: full marks only all-correct-and-no-incorrect;
  fill-in/numeric: configured tolerance; short-answer: rubric (auto-graded immediate,
  AI-graded with rationale per B's config)**.
- Adaptive exam: difficulty adjusts to correctness, **hidden from student**; ability estimate
  updates per answer (hidden during exam); ends at question or time limit.
- Practice quizzes: unlimited retakes, **never count toward exam attempts**; retake = new
  attempt (no overwrite).
- Mock exam: fixed time, **single submission per window, NO immediate feedback**, readiness
  score vs target exam.
- Results: score, pass/fail vs pass mark, per-question breakdown, explanations.
- Topic statistics (attempts, avg score, strength/weakness thresholds) → `weakTopics` for
  C's focus mode + D insights.
- Human override (B's config): reason recorded, AI grade preserved.
- Emits `AttemptSubmitted` (score, weakTopics) → D.
- **DEPS:** T-C-04, DEPS⚡ T-B-08
- **AC:** timer expiry auto-submits with unanswered marked (test); multi-select partial
  credit = 0 (test); adaptive: hidden state never in response payload (test asserts field
  absent); practice retake doesn't decrement exam allowance (test); mock no-feedback until
  window closes (test).

### T-C-06 · Bookmarks, notes, highlights — ✅ merged 2026-09-30 (d947a3d)
- `bookmarks` (video timestamp + note, or content-item), `notes` (char limit, autosave,
  per content/course), `highlights` (text span, color, note).
- Private, cross-device sync; **one bookmark per item (toggle)**; removing a
  bookmark/highlight removes its attached note.
- **DEPS:** T-C-04
- **AC:** toggle bookmark (add then add-again = remove, test); delete highlight cascades its
  note (test); note char-limit enforced (422 over); private: other user 404 (test).

### T-C-07 · Gamification state (points, streaks, badges)
- `points_ledger` (immutable; earn rules: videos/quizzes/exams/flashcards/streaks/content
  creation; balance; history; expiry rolling); badges (awarded once — no duplicates);
  achievements; challenges (expire at deadline); personal goals (auto-complete at target);
  streaks (consecutive days ≥1 study action; **protection/grace rule** — missed day doesn't
  always break).
- **Runtime state here; config (point rules, badge criteria) in D (T-D-08) — C reads config
  via `GamificationConfigService` (DEPS⚡ T-D-08).**
- Emits `StreakUpdated` → D (parent alerts, dashboard).
- **DEPS:** T-C-04, T-C-05, DEPS⚡ T-D-08
- **AC:** badge awarded once (2nd completion no-op, test); insufficient points on redeem →
  graceful 409 (test); streak protection: 1 protected miss keeps streak (test); ledger
  immutable (no update path, test).

---

## PHASE 2 — Personalized Learning

### T-C-08 · SRS runtime state
- Per-user SRS state: review queue (due-first, then priority, oldest-due tie-break), recall
  history (rating → next interval per B's `recall_adjustment_rules`), mastery levels
  (derived from recall-rate thresholds, no manual override), concept archive (graduation),
  retention predictions.
- **Config changes (B) apply to newly scheduled reviews only** — already-scheduled keep
  interval until re-evaluated (test).
- Daily review cap with carry-over; error-weighted resurfacing (never below floor,
  per-question cap); video reminder skip-if-rewatched.
- `GET /srs/due-queue`, `POST /srs/{itemId}/rate` (Again/Good/Easy).
- **DEPS:** T-C-07, DEPS⚡ T-B-10
- **AC:** rate Again → item earlier (resets bounded), Good → extended (bounded) (test);
  config change mid-session: existing due items keep old interval (test); daily cap
  carry-over to next day (test); mastered concept archived + re-entry on failed recall (test).

### T-C-09 · AI study companion runtime
- Per-user AI state: conversations (context retained, grounded in course content with topic
  refs), doubts (resolved/escalated-to-teacher), mood check-ins, burnout flags, chapter
  summaries (regenerable), recommendations (acted-on tracked), peer benchmark (**strictly
  anonymous percentiles** — no individual identified).
- Doubt escalation → teacher (event to D → parent-teacher comms).
- Study plan adjusts to recorded mood; break suggested on stress patterns.
- **AI behavior config from B (`AiConfigService`, DEPS⚡ T-B-11)** — question limits per plan
  enforced here (exceed → 429 with plan-upgrade message); escalation rules honored.
- **DEPS:** T-C-05, DEPS⚡ T-B-11, DEPS⚡ T-A-13
- **AC:** AI question over plan limit → 429 (test); peer benchmark response contains no
  peer names/IDs (test asserts only percentiles); doubt escalation event emitted;
  context retained across a conversation (test: 2nd answer references 1st).

### T-C-10 · Study plans + target-exam runtime — ✅ merged 2026-09-24 (7694d27)
- `study_plans` (AI planner + target-exam plans): tasks per day/week, reschedulable,
  adherence (on-track/behind/slid); **plan regenerates when prediction changes**; check-in
  prompt when adherence drops below threshold; parent approval required before applying to a
  minor (T-C-13).
- `target_exam_instances`: dates, subject-topic mappings, importance, time-split (must total
  100%, 422), **score prediction (real-time; confidence interval reflects data volume;
  insufficient data → "not shown", never false precision)**, what-if scenarios, countdown,
  readiness (coverage+mastery+time), actual result post-exam → accuracy history,
  post-exam reflection.
- Paused exam stops its study plan + reminders until resumed.
- Milestone triggers fire once per student per plan (from B's config).
- Emits `TargetExamRecorded`, `StudyPlanGenerated` → D.
- **DEPS:** T-C-08, T-C-09, DEPS⚡ T-B-11
- **AC:** time-split ≠ 100% → 422 (test); prediction below data threshold → null + practice
  prompt (test); paused target exam: plan + reminders halted (test); parent unapproved plan
  not applied to minor (test); actual result recorded → accuracy delta stored (test).

### T-C-11 · Learning paths runtime (institute/corporate) — ✅ merged 2026-09-24 (1123728)
- Runtime for B's learning-path definitions: per-student path progress (current step,
  completed steps, time, behind-pace flag); **steps with unmet prerequisites locked**;
  step complete only on criteria met; path complete on overall criteria; multiple paths
  per student; deadlines enforced.
- Completion → certificate (T-C-10 linkage) + event to D.
- **DEPS:** T-C-04, T-C-05, DEPS⚡ T-B-05
- **AC:** prerequisite unmet → next step 403 (test); criteria-gated completion (test);
  deadline exceeded → behind-pace flag (test); full completion → certificate issued (test).

---

## PHASE 3 — Learner Administration & Parent Runtime

### T-C-12 · Profile, onboarding, preferences (learner)
- `learner_profiles`: personal info (change history), learning preferences (style exactly
  one of visual/auditory/kinesthetic/mixed; subject focus/priority/avoid lists; daily
  study-time slider 30min–4h; time-of-day), academic goals + milestones, target scores
  (0–100 validated), exam dates (future).
- Onboarding (3 steps: basic info, learning prefs, goals) — required fields: grade, board,
  ≥1 subject, learning style; target score 0–100; exam dates future.
- Contact verification (email/phone via A's TokenService); old contact stays active until
  new verified (no gap); "avoid" topics excluded from recommendations but NOT from required
  assessments.
- Preference changes apply from point of change only.
- **DEPS:** T-C-01, DEPS⚡ T-A-07
- **AC:** onboarding validation (missing grade → 422, test); target score 105 → 422 (test);
  avoid-topic: excluded from recommendations, still in required assessment (test);
  learning style uniqueness enforced (test).

### T-C-13 · Parent-child link runtime + parental controls
- Link runtime (records in A, T-A-10; C consumes): **all parent reads scoped per child,
  filtered by monitoring consent scope**; relationship verification required before FULL
  activation (child data LIMITED until verified; failed verification does not activate).
- `parental_control_settings` (engagement per map): screen-time limit (resets daily; access
  PAUSED at limit, extendable; child warned approaching), time-of-day windows, content
  restrictions (**core learning NEVER blockable**), age filter (grade-aligned; override
  requires reason, logged), restricted-content requests (child submits → parent
  approve time-boxed / deny), mandatory study sessions (child required to complete; missed
  → alert), recurring session schedules (conflict detection, pause for holidays).
- **AI study plan approval: plan only applies to child AFTER parent approval**
  (modify-then-approve supported; approval history).
- Control presets (Balanced/Strict/Relaxed); control activity log.
- Emits parent alerts (missed session, limit reached) → D.
- **DEPS:** T-C-10, DEPS⚡ T-A-10, DEPS⚡ T-A-11
- **AC:** unverified link → parent gets LIMITED child data (test); verified → full (test);
  core-learning content restriction attempt → 409 (never blockable, test); screen-time
  limit reached → playback denied until reset/extend (test); unapproved AI plan not
  applied (test); override without reason → 422 (test).

### T-C-14 · Offline learning runtime
- `offline_downloads`: videos/lesson/course (quality), notes, resources, worksheets, quizzes,
  decks, papers/mocks — **all require active subscription**; expire on lapse or platform
  period (pre-expiry warning; re-download after re-subscribe).
- `sync_queue` (pending, retry), conflict handling (offline+online same item →
  latest-change-wins with merge where possible; some need manual review).
- Quiz/deck/paper must be downloaded before offline use; answers stored locally; **grading
  happens ON SYNC** (feeds T-C-05).
- Device limit enforced; removing device revokes offline access.
- **DEPS:** T-C-04, T-C-05, T-C-07, DEPS⚡ T-A-17, DEPS⚡ T-B-06
- **AC:** lapsed subscription → downloads expire + playback blocked (test); offline quiz
  answered → graded only on sync (test: no score until sync); device limit: N+1th device
  409 (test); conflict latest-wins (test).

### T-C-15 · Mobile app feature state
- Device prefs (dark mode synced to account, data saver — caps video quality/disables
  auto-play, gestures), app lock (biometric/PIN; token in secure storage; idle timeout),
  widgets (goal progress, current course, upcoming tests, streak — read from
  `ProgressService`), voice command mapping (confirmed before execution), quick actions,
  PiP (video continues while noting), data-usage tracker.
- **DEPS:** T-C-04, T-C-07, T-C-14
- **AC:** data-saver on → video quality capped (test); dark-mode pref persists across
  devices (test); app-lock: idle timeout invalidates (test); widget reads live streak
  (test via ProgressService).

---

## PHASE 4 — Learner Read Models

### T-C-16 · Progress & analytics read models (learner + parent views) — 🚀 PUSHED 2026-09-24 (track-c/T-C-16-progress-read-models, 633/633 passing)
- Course progress %, time spent (per course/subject/day/week, session log), activity log
  (chronological, **read-only** to learner), performance dashboard (scores, accuracy
  trends), strength/weakness analysis (topic accuracy vs thresholds → "focus on"/
  "maintain"), benchmark (grade-level percentile + gap), learning-pattern insight (peak
  times, error patterns, consistency), streak/consistency.
- Automated reports (weekly/monthly): time, completion, scores, trends; downloadable,
  **shareable with parent** (shared report appears in parent dashboard).
- Performance alerts (score drop, missed plan, streak risk) → D.
- Parent-facing projections: real-time activity, activity feed, exam-prep status (readiness
  from T-C-10), deadlines.
- `ProgressService` real implementation (for D).
- **DEPS:** T-C-04, T-C-05, T-C-07, T-C-10
- **AC:** activity log immutable to learner (no write endpoint, test); report share →
  visible in parent dashboard (test); weak-topic = accuracy below threshold (test);
  benchmark percentile grade-level (test); alert on planted score drop (test).

### T-C-17 · Learning seeding + E2E integration
- Seed: learner profile + enrollment in B's seeded courses, content progress, attempts,
  SRS state, 1 study plan, 1 target exam, parent-child link + controls.
- E2E test: register → onboard → enroll → play → complete → attempt quiz → SRS rate →
  target exam predict → parent sees progress + approves plan.
- **DEPS:** T-C-16, DEPS⚡ T-B-13, DEPS⚡ T-A-07
- **AC:** full E2E green; `ProgressService` returns non-empty for the seeded learner (test);
  cross-domain assertions (entitlement, consent scope) pass.

---

## Phase Gates (Track C)
- **Gate 1 (end Phase 0):** D can compile against `ProgressService`; learning DB green; no
  cross-DB FKs.
- **Gate 2 (end Phase 1):** a learner enrolls, plays with resume, takes a timed + adaptive
  exam, books notes, earns points/streak.
- **Gate 3 (end Phase 2):** SRS + AI companion + target-exam + study-plan + learning-path
  runtime live.
- **Gate 4 (end Phase 3/4):** parent-child link + controls + offline + read models live;
  full E2E learner journey green against B fixtures + A entitlement.

## Contract Stub Obligations (Track C must ship)
- `ProgressService` (real by Gate 3), `AccessGate`, all Learning events (ContentCompleted,
  AttemptSubmitted, StreakUpdated, TargetExamRecorded, StudyPlanGenerated,
  CertificateIssued), parental-control read interface for D dashboards.
