PLAN — Phase 0 → Phase 4
How to use this file
This is the single source of truth for phased delivery. Tick boxes as work lands. A phase is not done until its "Exit criteria" all pass with real command output. Every number below comes from the verified facts file — do not adjust them.
---
Invariants (read before any phase)
1. The question model is the IP: port 1:1, never "simplify" it. docs/DOMAIN-MODEL.md is the checklist.
2. questions.id stays TEXT (TB-000001).
3. correct is a choice id string, never an index.
4. Item sets (case groups) are first-class and served or withheld as a whole.
5. usage.timesUsed / lastUsed / testsUsedIn must survive the port (drives "prefer never-used").
6. versions history is preserved verbatim.
7. No browser talks to the database. Everything goes through /api.
8. The current single-file app is not deleted until the modular version passes the manual QA checklist.
---
Phase 0 — Decisions and scaffold (this session)
/api proxy)__Host- cookie, server-side sessions table, Google OAuth via oauth2 crate)owner_id, admin-only lessons)apps/, content/, infra/, packages/)ADR-004-content-decisions.md---
Phase 1 — Foundation
1.1 Repository layer (highest-leverage refactor, do this first)
The fact is 176 state.db.* occurrences on 162 lines of index (3).html (not ~80). Define a Repo interface and replace all call sites.
Tasks
Repo trait with:questions.list(filter), questions.get(id), questions.create(q), questions.update(q), questions.archive(id)caseGroups.list(), caseGroups.get(id)taxonomy.list(type?)tests.list(), tests.get(id)settings.get(), settings.set(k, v)IndexedDBRepo (for the current app) and ApiRepo (for the modular app) behind the same traitstate.repo object in the classic script holds only UI state (filters, search, page, pageSize, sort, favoritesOnly, includeArchived, browseMode) — it is NOT a data repository and must not be confused with the new data RepoRepo interfaceAcceptance
grep -c "state.db\." "index (3).html"
# Acceptance: the only remaining occurrences are inside the Repo implementation. There must be zero occurrences in render/UI code — verify by reviewing every hit, not by counting.
1.2 Backend skeleton
tracing, tower-http, dotenvy0001_init.sql with tables:users(id, email, password_hash, role, created_at, email_verified)sessions(token_hash, user_id, expires_at, idle_expires_at, created_at)questions(id TEXT PK, owner_id UUID NULL, pool_visible BOOL, subject TEXT, body JSONB, versions JSONB, usage JSONB, archived BOOL, deleted_at TIMESTAMPTZ)case_groups(id TEXT PK, title TEXT, scenario TEXT)taxonomy(id TEXT PK, type TEXT, parent_id TEXT NULL, name TEXT, metadata JSONB)tests(id TEXT PK, title TEXT, created_at TIMESTAMPTZ, versions JSONB, question_count INT, folder TEXT, source_folder TEXT)questions_versions(question_id, snapshot JSONB, created_at) — for when versions array grows largeapp_settings(key TEXT PK, value JSONB)Acceptance
cargo build --workspace # clean, no warnings
sqlx migrate run # applies to an empty Neon database
1.3 Auth
Per ADR-002: signup/login/logout/me + Google callback, Argon2id, HttpOnly __Host- cookie, sessions(token_hash), require_auth / require_admin extractors.
Acceptance
signup → login → me → logout round-trips401require_admin returns 403 for a non-admin user1.4 Frontend split
index.html is ONE classic <script> (line 671). Split into ES modules under apps/web/app/lib/ while KEEPING the pure functions verbatim, with their names:
computeQualitygroupQuestionsIntoBlockstheoryFirstSortcompleteCaseGroupsrenderTextWithInlineTablesparseMarkdownTableLinesvalidateDatabasededupeQuestionIdsnormalizeDatabasereplaceDatabaseSafelyAcceptance
1.5 Landing + auth pages
Static, SEO-ready, no testimonials (leave visible TODO(user) slots for later copy).
1.6 Seed binary
apps/api/src/bin/seed.rs reads content/questions/*.json, upserts by id, runs the ported integrity checks (validateDatabase, normalizeDatabase, dedupeQuestionIds).
Exit criteria (Phase 1)
1. cargo build --workspace clean
2. sqlx migrate run applies to empty DB
3. Auth round-trip test passes (signup→login→me→logout, 401 without cookie, 403 for non-admin)
4. grep -c "state.db\." "index (3).html" shows only Repo-implementation lines
5. Frontend loads from ES modules, all 10 pure functions retain exact names
6. Seed binary imports all 2,343 questions from JSON files, upsert by id, integrity checks pass
7. Landing + auth pages render statically
---
Phase 2 — Admin parity
Port every mutation to REST. Server-side CSV/JSON/paste import (parsers move to Rust, behaviour must stay identical). Keep quality checker + case-group logic in the frontend. Port replaceDatabaseSafely / validateDatabase / normalizeDatabase / dedupeQuestionIds as import-time checks.
Specific tasks
Exit criteria (Phase 2)
1. All admin mutations (create/update/archive question, case group CRUD, taxonomy CRUD, test CRUD, settings) work via REST endpoints
2. CSV/JSON/paste import produces bit-for-bit identical results to the current frontend implementation
3. Import-time checks (validateDatabase, normalizeDatabase, dedupeQuestionIds, replaceDatabaseSafely) run server-side and return same pass/fail as frontend
4. 45 dangling case groups: decision documented and implemented (flagged, rejected, or repaired)
5. 1,858 empty explanations: decision documented and implemented (imported as-is, flagged, or suppressed in UI)
---
Phase 3 — Learner experience
/learn dashboard, lessons viewer, practice generation from GET /questions/pool, attempt taking, results, history. Server picks the questions and grades; the client never decides a score. Note the explanation gap: the results screen must degrade gracefully (show "No explanation available" for the 79% without one).
Exit criteria (Phase 3)
1. /learn dashboard renders the six LECPA subjects; three have content (FAR, Management Services, Taxation), three are empty (AFAR, Auditing, RFBT) and are shown as "coming soon" rather than as broken links
2. Lessons viewer shows admin-authored lessons only (lessons.published = true)
3. Practice test generation: GET /questions/pool?subject=Financial%20Accounting%20and%20Reporting&count=20 returns curated questions, respects usage counters (prefer never-used) (subject strings must be the six canonical LECPA names; the export's "Theory of Accounts" rows are remapped at import or excluded until remapped)
4. Attempt taking: client submits answers, server grades, returns score + per-question result
5. Results screen handles empty explanations gracefully (no broken layout, clear "No explanation available")
6. History page shows past attempts with scores, dates, subject breakdown
---
Phase 4 — Billing and launch
Stripe Checkout with stubbed tiers (Free/Pro/Firm, no real prices), tier gating middleware, admin stats, docs site, rate limiting, audit log, GDPR delete-account, WAF.
Exit criteria (Phase 4)
1. Stripe Checkout session creates for each stubbed tier, returns success URL
2. Tier middleware gates /learn features (e.g., Pro unlocks unlimited practice, Firm unlocks admin panel)
3. Admin stats endpoint returns: total users, active users (30d), questions in pool, tests taken, avg score
4. Docs site deployed (Markdown → static HTML)
5. Rate limiting on /api/auth/* (5 req/min signup, 10 req/min login) and /api/* (100 req/min)
6. Audit log table captures: user_id, action, resource, timestamp, metadata JSONB
7. GDPR delete-account: anonymizes user data, marks questions deleted_at, revokes sessions
8. Cloudflare WAF rules enabled (block SQLi, XSS, rate-limit bypass patterns)
---
Task table
| ID | Phase | Task | Depends on | Can run in parallel with | Acceptance |
|-------|-------|------------------------------------------------|------------|--------------------------|----------------------------------------------------------------------------|
| P1-01 | 1 | Define Repo trait + IndexedDBRepo impl | — | P1-02, P1-03 | Trait compiles; all 176 occurrences on 162 lines route through it |
| P1-02 | 1 | Backend skeleton (Axum, SQLx, migrations) | — | P1-01, P1-03 | cargo build clean; sqlx migrate run on empty DB |
| P1-03 | 1 | Auth module (signup, login, logout, me, Google) | P1-02 | P1-01 | Round-trip test passes; 401/403 checks pass |
| P1-04 | 1 | Frontend split to ES modules (keep 10 fn names) | P1-01 | — | App runs from modules; grep confirms 10 function names unchanged |
| P1-05 | 1 | Landing + auth static pages | — | P1-01, P1-02, P1-03 | Pages render; TODO(user) slots visible |
| P1-06 | 1 | Seed binary (reads content/questions/*.json) | P1-02 | — | Imports 2,343 questions; integrity checks pass |
| P2-01 | 2 | Admin REST mutations (questions, case groups, taxonomy, tests, settings) | P1-02, P1-03 | P2-02 | All CRUD endpoints return 200/201; integration tests pass |
| P2-02 | 2 | Server-side import parsers (CSV/JSON/paste) | P1-02 | P2-01 | Identical output to current frontend for 5 sample files |
| P2-03 | 2 | Import-time integrity checks (port 4 functions) | P2-02 | — | Same pass/fail as frontend on 10 test payloads |
| P2-04 | 2 | Repair 45 dangling case groups | P2-01 | P2-03 | Decision documented; 0 dangling refs remain or all flagged |
| P2-05 | 2 | Handle 1,858 empty explanations | P2-01 | P2-03 | Decision documented; UI degrades gracefully |
| P3-01 | 3 | /learn dashboard + subject cards | P1-04, P1-06 | P3-02 | Six LECPA subjects listed; 3 with content, 3 marked "coming soon" |
| P3-02 | 3 | Lessons viewer (admin-authored only) | P1-02, P1-03 | P3-01 | Only published=true lessons visible; 404 for draft |
| P3-03 | 3 | Practice generation (GET /questions/pool) | P1-02, P2-01 | P3-04 | Respects subject filter, count, usage priority (never-used first) |
| P3-04 | 3 | Attempt taking + server-side grading | P1-02, P3-03 | — | Client submits answers; server returns score + per-question result |
| P3-05 | 3 | Results screen (graceful empty explanations) | P3-04 | — | 79% empty handled: no layout break, clear "No explanation available" |
| P3-06 | 3 | History page | P3-04 | — | Shows past attempts with scores, dates, subject breakdown |
| P4-01 | 4 | Stripe Checkout (stubbed Free/Pro/Firm) | P1-03 | P4-02 | Creates session; returns success URL; webhook updates tier |
| P4-02 | 4 | Tier gating middleware | P4-01 | — | Pro/Firm gates enforced on /learn features |
| P4-03 | 4 | Admin stats endpoint | P1-02, P1-03 | P4-04 | Returns users, active-30d, pool size, tests taken, avg score |
| P4-04 | 4 | Docs site (Markdown → static HTML) | — | P4-03 | Deploys; all ADR/CONTENT-INVENTORY/DOMAIN-MODEL pages render |
| P4-05 | 4 | Rate limiting + audit log + GDPR delete | P1-03 | P4-06 | Limits enforced; audit log captures mutations; delete-account anonymizes |
| P4-06 | 4 | Cloudflare WAF rules | — | P4-05 | SQLi/XSS/bypass rules active; test requests blocked |
Parallel-safe pairs (at least 4):
Strictly sequential (at least 2):
---
Risk register
| Risk | Likelihood | Impact | Mitigation | Signal it's happening |
|------|------------|--------|------------|-----------------------|
| 176-occurrence refactor breaks behaviour silently | High | High | Keep pure functions verbatim; add integration test that loads a known DB snapshot through old and new Repo and compares outputs | grep shows call sites not updated; manual QA finds mismatch |
| 45 dangling case groups render as broken item sets | Medium | Medium | Decide in P2-04: reject at import, flag for manual entry, or create placeholder scenarios | Import logs show warnings; admin UI shows "incomplete group" badges |
| 1,858 missing explanations degrade learner trust | High | Medium | Results screen must show "No explanation available" cleanly; track as content debt | User feedback: "where's the explanation?"; analytics show high bounce on results |
| SQLx compile-time checks need a DB in CI | Medium | High | Check in .sqlx cache; run sqlx prepare in CI against a test Neon branch; document update procedure | CI fails with "query not checked" after migration |
| Wordpress-style scope creep into a React rewrite | Medium | Critical | Phase 1.4 explicitly keeps vanilla ES modules; ADR-001/002/003 freeze stack; "Out of scope" list enforced | PR adds package.json with React/Next; issue asks for "modern frontend" |
---
Out of scope
index (3).html) until modular version passes manual QA checklist---
*Generated from verified facts. Every number traces to /tmp/opencode/phase0-facts.md and docs/CONTENT-INVENTORY.md. Do not adjust counts.*