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)

  • [x] ADR-001 backend host (Axum + SQLx + Postgres on Fly.io/Railway, Cloudflare Pages + /api proxy)
  • [x] ADR-002 auth (roll own: Argon2id, HttpOnly __Host- cookie, server-side sessions table, Google OAuth via oauth2 crate)
  • [x] ADR-003 multitenancy (single global curated pool, CPALE subject scope, user-private questions via owner_id, admin-only lessons)
  • [x] DOMAIN-MODEL.md (JSON → Rust → Postgres port map with all 38 fields (29 always-present + 9 partially populated) and nested shapes)
  • [x] CONTENT-INVENTORY.md (2,343 questions, 45 dangling case groups, 1,858 empty explanations, 8 zero-populated fields, 15 tests, 4 subjects with content)
  • [x] This PLAN.md
  • [x] Repo scaffold exists (apps/, content/, infra/, packages/)
  • [x] ADRs ratified by the product owner on 2026-11-21; content decisions recorded in 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

  • Define 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)
  • Implement IndexedDBRepo (for the current app) and ApiRepo (for the modular app) behind the same trait
  • The existing state.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 Repo
  • Replace all 176 occurrences on 162 lines in the classic script to route through the new Repo interface
  • Acceptance

    
    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

  • Axum + SQLx + Postgres (Neon), tracing, tower-http, dotenvy
  • Migration 0001_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 large
  • - app_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

  • A test that signup → login → me → logout round-trips
  • A request without the cookie returns 401
  • require_admin returns 403 for a non-admin user
  • 1.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:

  • computeQuality
  • groupQuestionsIntoBlocks
  • theoryFirstSort
  • completeCaseGroups
  • renderTextWithInlineTables
  • parseMarkdownTableLines
  • validateDatabase
  • dedupeQuestionIds
  • normalizeDatabase
  • replaceDatabaseSafely
  • Plus the seeded PRNG (for reproducible test shuffles)
  • Acceptance

  • The app still runs from the split modules
  • All function names unchanged
  • No behavioural change in any pure function
  • 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

  • Repair the 45 dangling case groups (45 of 57 referenced ids have no scenario). Options: reject at import, flag for manual entry, or auto-create placeholder scenarios.
  • Decide what to do with the 2,343-question pool's 1,858 missing explanations (79%). Options: import as-is with empty string, flag for authoring, or suppress explanation UI for those questions.
  • 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):

  • P1-01 ⟂ P1-02 (repo layer and backend skeleton are independent); P1-03 starts once P1-02 lands
  • P1-05 ⟂ P1-01/02/03 (static pages independent)
  • P2-01 ⟂ P2-02 (mutations and parsers touch different endpoints)
  • P3-01 ⟂ P3-02 (dashboard and lessons viewer independent)
  • P4-03 ⟂ P4-04 (stats endpoint and docs site independent)
  • Strictly sequential (at least 2):

  • P1-04 requires P1-01 (Repo trait must exist before frontend split uses it)
  • P3-03 requires P2-01 (practice generation needs question pool endpoint)
  • P3-04 requires P3-03 (grading needs pool endpoint)
  • P4-02 requires P4-01 (tier gating needs Stripe webhook)
  • ---

    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

  • No React/Next migration (vanilla ES modules only)
  • No removing the single-file app (index (3).html) until modular version passes manual QA checklist
  • No per-firm tenancy (ADR-003: single global pool + user-private questions only)
  • No MFA (ADR-002: follow-up)
  • No mobile apps
  • No AI question generation
  • No SSO/SAML/OIDC federation (ADR-002: follow-up)
  • No email verification flow in v1 (ADR-002: prerequisite for recovery)
  • No user-facing session management UI (ADR-002: v1)
  • No password history/rotation policies (ADR-002: v1)
  • ---

    *Generated from verified facts. Every number traces to /tmp/opencode/phase0-facts.md and docs/CONTENT-INVENTORY.md. Do not adjust counts.*