# ARTH_CODEX: From Zero to C++ Mastery

## Step 1: Architecture and acceptance contract

An original, activity-centered C++17 learning application for people with no programming experience. The five simulated delivery robots are B21K, R07M, T14Q, D33P, and K05L. Lessons introduce concepts before using them. The product title describes the learning goal; mastery requires independent projects and assessed evidence, not clicks or XP.

### Product scope
Initial usable release: ten beginner lessons, editable C++ code, genuine isolated execution, deterministic assessment, guided visual traces, one robot mission, authenticated saved progress. Full course: functions, references, collections, strings, testing, modular compilation, object-oriented programming, memory ownership, standard library algorithms, and independent projects. No Coddy text, graphics, branding, or implementation is copied.

### Learning contract
Explain → Visualize → Show code → Predict → Complete code → Trace/Run → Apply → Check → Debug → Interpret. Each complete lesson has a goal, prerequisites, short verified example, prediction, coding task, trace, mission, debugging task, tests, explanation, and rubric. Predictions receive explanatory feedback but cannot alone establish mastery. XP rewards verified completions once; repeated submissions do not farm XP. Solutions follow a learner attempt. Visual traces describe a known example; they do not claim to execute edited source.

### Roles and authorization
Learner: view published lessons; read/write own attempts and progress. Instructor: manage lessons and assessments; view consented, assigned course results. Administrator: manage roles, publication, and operational limits. Service worker: update execution jobs through authenticated internal endpoints. These are planned roles; the Step 2 private foundation has no role selector that pretends to enforce authorization. Server-side checks must bind every record to an authenticated principal. Client flags never authorize access. Instructor answer keys and hidden tests remain server-side.

### Architecture decision
Use a dependency-free static shell for Step 2, followed by a server-capable Sites application using React/TypeScript and the supplied framework starter when authenticated services are added. Hosted application records use D1; file assets use R2 when needed. This avoids assuming PostgreSQL/TCP support in the hosted Worker runtime. The SQL supplied here is a locally validated design, not a deployed database.

The selected Step 8 design is browsercc 0.1.1, a Clang/LLD WebAssembly toolchain, with browser-local practice execution. This replaces the requirement to provision an owned compiler server. No learner code runs in the application Worker. Compiler assets must be pinned and served through a verified delivery path, with license notices preserved. The existing HTTPS runner implementation is retained as disabled legacy code, not the selected default.

Compilation and execution will use dedicated browser Workers. A controller must enforce bounded source/input/output, terminate Workers for cancellation and deadlines, reject pending operations, ignore stale messages, and support repeated runs. C++17 is explicit; exceptions are disabled in the evaluated WASI configuration. WASI imports must expose only a bounded in-memory filesystem and stdin/stdout/stderr, with no networking or application credentials. A browser-worker termination design is not itself evidence that these controls passed.

The stock browsercc API compiles one translation unit and supplies extra files. Separate .cpp builds require compiling each translation unit then linking all resulting objects; the application adapter implements that path and real WebAssembly worker checks under Node passed. Browser delivery, memory behavior, cancellation and resource/isolation checks remain open. Step 8 must stay incomplete until these gates pass.

Browser-local results support practice and debugging. They are client-controlled and cannot authorize XP, prerequisite unlocking or trusted grading by themselves. Step 9 now uses approved practice-only program checks plus server-checked concept answers. These checks do not authorize mastery awards; instructor answer keys for concept checks remain server-side. AI tutor remains optional and server-mediated: hints first, no grading authority, explicit provider disclosure, minimal retained data, user deletion.

### API contract to implement
GET /api/lessons: published lesson metadata.
GET /api/lessons/:id: learner content without hidden tests.
POST /api/attempts: authenticated lesson id, lesson version, source (maximum 32 KiB), prediction; return queued attempt id.
GET /api/attempts/:id: owner-authorized status, compiler diagnostics, bounded stdout/stderr and test summary.
GET /api/progress: authenticated learner's completions and earned XP.
DELETE /api/me/data: remove personal attempts/progress and invalidate related queued work.
POST /api/tutor/hint: authenticated current task and bounded learner code; optional later integration.
All writes require validated input, authorization, and CSRF protection where cookie-based authentication is used. Failures distinguish invalid request, unauthorized, forbidden, rate limit, compilation error, runtime error, timeout, and assessment failure.

### Data model
Users have roles. Versioned lessons own challenges and prerequisites. Attempts bind user, lesson and version; lifecycle is queued/running/passed/failed/error. Progress has one row per user/lesson; one award per completion. Fleet robot definitions are immutable seed data; simulated user state is separated in a future table. No passwords or API keys are stored in this schema. Authentication identifiers must come from the verified identity service. Retention proposal: execution logs 30 days, attempts until user deletion or course policy; retention requires implementation and disclosure before collecting data.

### Release gates
Step 1: schema creates successfully; invalid roles, battery ranges, orphan references, duplicate awards fail; prerequisite graph is acyclic; five robot values are consistent; introductory examples compile and produce expected output. This verifies the design artifacts, not production security.
Step 2: project has reproducible checks, source control, responsive shell, working navigation and prediction feedback, accessible form labels, reduced-motion preference, explicit local-only progress, no fake compiler or AI, and private publication. Browser QA must be recorded separately from static checks.
Later gates: identity/authorization integration tests; durable data migrations; real runner isolation tests; content completeness; automated learning tests; accessible browser testing; final independent capstone.

## Ordered development roadmap
1. Requirements, architecture, learning contract, schema and gate tests.
2. Source repository, application shell, robot mission interface and project checks.
3. Authentication and server-enforced roles.
4. Durable database migrations and user progress APIs.
5. Curriculum/content schema and authoring validation.
6. Ten complete beginner lessons.
7. Editable code workspace and file management.
8. Browsercc WebAssembly practice compiler, worker lifecycle and verified containment.
9. Automated deterministic assessment.
10. Guided execution and memory visualizations.
11. Robot simulation and incremental milestones.
12. Anti-duplication XP, badges and prerequisite unlocking.
13. Hint-first AI tutor.
14. Functions, branches, loops and testing track.
15. References, strings, arrays, vectors and C strings track.
16. Defaults, overloads, preprocessor and separate files track.
17. Salary and hostname case studies.
18. Advanced C++ and independent capstones.
19. Instructor analytics, accessibility and privacy review.
20. End-to-end release, load/security tests and operational documentation.

Release gates remain sequential. On 2026-10-13 the user explicitly authorized independent Step 9 development while Step 8 browser QA remains incomplete. This exception permits implementation, not a claim that either release gate passed. Steps 1–7 have implementation and local checks; hosted checks remain open.

## Step 8 integration budgets
Pinned browsercc 0.1.1 assets are stored as gzip files and checksum-verified after decoding. Compiler and linker linear memory are each capped at 256 MiB. Program linear memory is capped at 128 MiB and validated before execution. These do not cap browser-process/JavaScript heap memory, so actual device pressure is a browser release gate. Asset loading has a 120-second deadline, compilation a 60-second deadline, execution a 2-second deadline, diagnostics/output a 64-KiB cap, stdin an 8-KiB cap, and compiled programs a 16-MiB cap. Compilation/run Workers are terminated at phase completion/cancel/deadline.

Web Locks and device-local timestamps coordinate one active compilation and ten starts/minute per account scope across browser tabs. These are advisory client controls, not hostile-client-proof server quotas. No browser execution result is persisted as trusted grading evidence. The release switch remains disabled pending supported browser QA.

## Step 9 concept assessment and trust boundary
GET/POST /api/lessons/:id/assessment requires verified ChatGPT identity. GET returns a versioned two-question concept rubric; POST validates same-origin JSON, a 2 KiB body limit, exact answer fields and lesson/assessment versions. The server grades predictions and single code gaps using its lesson keys. Each item is worth one point. Only outer whitespace is ignored, case is significant, and the math gap explicitly accepts 60 or 60.0. Incorrect responses receive a targeted hint, not a returned answer key. Existing instructional solution reveal remains available after an attempt, so these are formative checks rather than a secret examination.

Results are stateless and private/no-store. They neither write progress nor execute learner code, award mastery/XP, or unlock prerequisites. Request-provided result/identity/score fields are rejected. No browser output or submitted assertion of success is accepted as trusted program evidence. On 2026-10-13 the user approved practice-only program grading without verified mastery awards. Trusted full-program grading is outside the revised Step 9 scope; authenticated browser QA remains mandatory. Browser-local execution is not authoritative evidence. UI results bind to the submitted answers and lesson generation; editing or changing lesson invalidates stale feedback.

### Step 9 public program practice
Assessment definitions expose the original 13 example cases, not secret tests. A browser suite controller snapshots source once and sequentially runs each case through the existing compiler and account coordinator; quotas apply per case. Exact stdout/stderr/exit comparison distinguishes expected nonzero exits from traps, output caps, compiler errors and interrupted checks. Remaining cases after a stopped run are explicitly not run. Results stay client-controlled and cannot authorize server awards. The test button shares the disabled compiler release switch.

## Step 10: guided execution and memory
The user authorized independent Step 10 implementation while the earlier browser gates remain open. Each of the ten original examples has an authored walkthrough in content/guided-traces.json, tied to the exact lesson source and version. The learner API supplies the matching walkthrough. Validation rejects stale source, invalid line numbers, duplicate variable identities, variables outside active call frames, inconsistent reference aliases, and incorrect terminal output/scope.

The UI shows the original source with a current-line highlight, previous/next/restart controls, call frames, a logical variable table, changed-value labels and cumulative stdout. The input lesson explicitly uses stdin 3; this is not an input simulator. Arrays and vectors show indexed logical elements, references identify a shared caller variable, and ended scopes disappear. No physical addresses, ABI layout or interpreter capability is implied. Examples are authored conceptual snapshots, not a trace of workspace edits. They do not call the compiler, write records or award mastery.

Browser visual/accessibility and hosted checks remain pending; unit DOM fixtures are not browser QA. The compiler release switch remains disabled. nextStep still denotes the earliest unresolved full release gate, not the latest independent implementation.

## Step 11: illustrative robot practice
The Mission control simulation uses the five canonical robot identities, battery levels and speeds without mutating the original fleet or learner records. Each scenario starts at the depot. A pure state transition model supports inspection, instantaneous charging, dispatch and advances of up to five minutes. Battery use is an illustrative two percentage points per kilometre; dispatch needs at least 40% charge and a predicted arrival reserve of at least 20%. Routes must be positive and at most 20 km. The final tick advances only the remaining travel time.

Four ordered practice milestones cover inspecting the fleet, charging D33P, dispatching it on a 5.5 km route and arriving with sufficient reserve. Milestones are unique and session-memory-only; reset clears them. They do not represent execution, assessed mastery, XP or prerequisite unlocking. The simulation uses no compiler, network requests, storage or server writes. Native controls, live status and progress labels have local fixture coverage; hosted accessibility and visual QA remain open.

## Step 12: rewards foundation (partial)
GET /api/rewards requires verified ChatGPT identity and returns private/no-store availability information and canonical prerequisite edges for the ten published lessons. It has no database or evidence ingestion path. All write methods are rejected; query parameters cannot supply ownership or results. Browser runs, concept responses, existing prediction records and simulation milestones never become verified completion evidence. All original lessons remain open for practice. The Learning journey panel distinguishes recommended prerequisites from verified unlocking.

Verified XP, earned badges and mastery are unavailable. Step 12 is not complete. A future user-authorized trusted assessment must bind evidence to the authenticated learner, lesson and rubric versions. Durable award creation must be atomic and unique per learner/lesson award, with retry/concurrency tests, before any XP or badge can be issued. Verified prerequisite enforcement must use this server-owned ledger. The disabled ledger foundation is implemented as described below; the instructor-review integration below is implemented but disabled, and the practice-only Step 9 scope remains unchanged.

### Disabled ledger implementation
The additive 0002 migration creates assessment_evidence, verified_completions and reward_awards without changing existing tables. A future trusted assessor must write server-owned evidence with an assessment proof digest, learner identity, lesson version, rubric version, outcome and timestamp. A digest field only binds provenance; its presence does not validate a program. The instructor review route below can create human-review evidence after its separate release gate is enabled; it remains disabled. The reward route can reconcile approved reviews only when both review and reward release switches are enabled; both remain disabled.

The internal award writer selects existing passing evidence for the exact learner, lesson and current lesson/rubric versions. It checks current-version prerequisite completions, then inserts completion and award in one transactional D1 batch. Composite foreign keys bind completion to the same evidence owner and version. A learner/lesson unique key prevents repeated XP, including after re-verifying a newer lesson version. Current implementation policy is 100 XP and one lesson badge per first verified completion; this policy remains inactive. Completion records can exist for multiple lesson versions, while stale versions cannot satisfy prerequisites. All current practice access stays unchanged.

Local tests use the real generated SQL with SQLite transactions, including separate concurrent connections. This is not hosted D1 validation or proof that a trusted assessor exists. Retention/deletion, evidence verification, production transaction checks, browser QA and the activation decision must be completed before collecting real evidence or issuing awards.

### Instructor-reviewed evidence (disabled pending verification)
The user authorized instructor review by replying Next to the direct proposal on 2026-10-13. This is human assessment of a fixed source snapshot, not automated execution or a grading upgrade to Step 9. The review release switch is false. The production runtime currently has no configured instructor or administrator IDs. Site-scoped identities must come from verified sign-in, not workspace IDs; sharing and roles were not changed.

GET/POST/DELETE /api/reviews requires authenticated identity. The learner submits a UUID retry key, current lesson version, up to eight source files totaling at most 32 KiB and an explanation. The server normalizes and hashes the complete snapshot and binds it to the signed-in learner; snapshots cannot be edited. SQL limits each learner to five pending and twenty total submissions. A retry with the same key and snapshot returns the saved row; changed snapshots require a new key. Saved submissions cannot be inferred through another learner's identifier.

GET /api/instructor/reviews and POST /api/instructor/reviews/:id require an instructor/admin role from server configuration. Self-review is forbidden. The queue includes source text, explanation and lesson objectives. Approval requires four affirmative attestations: independently compile/run the exact snapshot with C++17, test relevant boundary/invalid cases, review the reasoning, and confirm lesson objectives. Feedback is required. These declarations are attributable human attestations, not machine verification of compilation or infallible mastery evidence. The application never executes submitted source on the server.

A transaction creates one final review decision and, on approval, matching assessment evidence. The proof digest binds learner, reviewer, source snapshot, lesson/rubric versions, checks and feedback. Competing decisions cannot overwrite each other. SQL repeats the snapshot/owner checks inside the write transaction, so delete-and-recreate races cannot approve replaced source. Approval itself does not run the award writer. The separately gated reconciliation below can consume approved evidence; no live XP is currently issued. Changes requested require a new immutable submission for another review.

Storage is disclosed before submission and lasts until the learner deletes their review data. DELETE requires same-origin JSON and explicit confirmation; its transaction clears that learner's review source, decisions, all verification evidence, completions and awards, preserving other learners and existing practice records. No source or email is logged by these handlers. Local tests use synthetic learners/reviewers; hosted identity, database and browser verification remain required. A configured reviewer and distinct learner need explicitly authorized access before actual review can occur; the existing owner-private audience is preserved.

### Owner instructor designation
On 2026-10-13 the user explicitly approved the existing owner account as instructor. Native Sites access metadata confirmed one owner and no other viewers/groups. That owner's email is stored only as the secret runtime value ARTH_OWNER_INSTRUCTOR_EMAIL. Authorization compares it exactly with the email supplied by the server-only getChatGPTUser helper, requiring a nonempty authenticated site user ID and email. It does not accept request-body role/email claims, wildcard matches, aliases, or partial matches. Existing site-ID grants and admin precedence are preserved; the email grant gives instructor access only.

This is an explicitly configured role designation, not a sign-in mechanism or an authentication workaround. Records, review ownership and self-review checks remain bound to authenticated site user IDs. No workspace account ID was reused as a site identity. Sharing is unchanged. If the owner's authenticated email changes, update the server configuration explicitly; no fuzzy matching applies. Hosted signed-in role verification remains outstanding, and compiler/review/reward activation gates remain disabled. This designation supersedes the earlier observation that no instructor runtime configuration existed.

### Review-to-reward integration (disabled)
GET /api/rewards reads only the authenticated learner’s server ledger when both release switches are enabled. POST accepts only the explicit action sync-approved-reviews with same-origin JSON, a 128-byte limit and no client grade/identity fields. It selects matching current-version instructor approvals and proof digests, excludes self-review, and reconciles lessons in curriculum order in one D1 batch. Prerequisite checks and unique lifetime awards remain enforced in SQL. Retries cannot multiply XP. Failed storage returns unavailable, never a fabricated zero verified balance.

The dashboard shows server XP, badges and current-version prerequisites, with an explicit Sync approved reviews button. All practice lessons stay open. This is human-reviewed completion, not automated program grading. Local tests use synthetic reviewers and SQLite; hosted transaction and browser checks remain required. No schema or sharing change accompanies this integration.

## Temporary guest learning (2026-10-14)
The user explicitly requested temporary removal of site login. The authorized policy is public learning access with optional platform sign-in. The runtime switch `ARTH_GUEST_ACCESS=true` opens only the HTML shell, original ten lesson endpoints, stateless concept assessment and instructional feedback. Its default is false; no request-body or URL flag can enable it. The host must also use Sites public access. Native Sites metadata records the effective audience and deployment revision.

Guests can view authored traces and the robot simulation, and edit/download code in memory. Guest code is never loaded from or saved into authenticated account draft keys. Concept/prediction responses remain practice-only and do not create records or awards. Every account, review, reward, privileged and legacy execution handler still requires the real platform-authenticated principal; the guest switch creates no synthetic user or role. Existing records and instructor secret are preserved. Compiler, review and reward release switches remain disabled.

To restore required login, set Sites access back to custom with the retained owner allowlist, set the runtime switch false and redeploy the current saved version. No automatic expiry was requested. This access-policy exception does not satisfy the outstanding Steps 8–12 browser or hosted review/reward gates.

## Step 13: authored hint foundation (partial, 2026-10-14)
Each published lesson now includes a source/version-bound authored hint guide with Notice, Reason and Check stages. The browser panel asks for a local reflection note, reveals one hint at a time and requests a revised note before the next hint. Notes are not transmitted or stored. Restart and lesson navigation clear them. No code is inspected/executed and no reward or completion endpoint is called.

This is a useful non-AI foundation, explicitly labeled as authored guidance. The AI tutor still needs a user-authorized provider or approved local model design and actual hint-policy, failure, privacy and browser tests. No provider/key is configured and no external request is made. Full Step 13 remains incomplete. Steps 14–20 now expose their planned scope and required checks in the Development log; see docs/remaining-roadmap.md and docs/tutor.md. Earlier release gates and temporary guest access remain unchanged.

## Steps 14–18: extension tracks

The user explicitly requested Steps 14–20 on 2026-10-14, authorizing independent implementation while existing release gates stay open. The original `content/course.json` and ten beginner lessons remain intact. `content/advanced-tracks.json` defines five additional tracks and sixteen versioned lessons. Each includes the full ten-phase learning cycle, complete C++17 project files, a prediction/code-gap rubric, authored reasoning steps, application/debugging exercises and public example cases. The learner catalog returns original `lessons` plus separate `tracks`; the lesson, feedback and stateless concept endpoints resolve either group. Instructor answer keys and compiler-negative cases are stripped from learner lesson responses.

A multi-file starter loads all supplied `.cpp` and header files into the existing account-separated workspace. Every downloadable file is checked against its authored source. Original lessons retain their rich memory walkthroughs and tutor hints. Extension lessons use their own explicitly authored trace activities; they do not claim dynamic edited-code traces or AI hints. Practice-only concept results do not produce XP. The existing reward graph remains the original ten lessons and is not silently extended to award capstone mastery.

Tracks include functions/control flow/testing; references and safe string/collection handling; defaults/overloads/preprocessor/separate compilation; integer-cent salary and ASCII-only hostname cases; RAII, unique ownership and standard algorithms; and two independent robot-fleet capstones. Capstones provide complete baseline examples plus different, explicitly specified independent tasks, test plans and rubrics. Downloaded projects can be reviewed independently. No review release or mastery assertion is introduced by displaying a capstone.

## Step 19: minimal instructor analytics and learner data controls

`GET /api/instructor/analytics` uses the existing platform-authenticated role check. It returns per-lesson counts of pending work available to the reviewer and decisions that reviewer wrote. It returns no learner IDs, emails, source or rankings. These are review activity counts, not learning gains or measured mastery. No new tracking collection or table is introduced.

`GET /api/me/data` performs a bounded transactional export of the signed-in learner's records across all seven application tables plus review decisions they authored. Other learners' snapshots and reviewer identifiers are excluded. Any category above 1000 rows rejects the entire export rather than silently truncating it. `DELETE /api/me/data` requires same-origin JSON and exact confirmation; it transactionally removes the learner's awards, completions, evidence, decisions on their own submissions, submissions, practice and terminal legacy jobs. Active-job guards are repeated inside the transaction to avoid a preflight race. Reviews authored for other learners remain as attribution on their records; this retention is disclosed before deletion. Platform identity and sharing are not deleted.

Browser draft clearing hashes the authenticated account scope and removes only its workspace keys. Guest drafts are memory-only. Server records have no automated expiry and persist until deletion. The UI explains this accurately rather than claiming an unimplemented retention purge. Skip-to-content, focus after navigation, semantic tables/labels, text-only feedback, overflow containment and reduced-motion styling are implemented. Hosted screen-reader/keyboard/mobile and real account deletion/export checks remain required.

## Step 20: release tooling and operations

`verify:release:local` combines content, sequential Node regression, schema, native example, TypeScript and local handler load checks; optional `--wasm` adds actual WASM worker suites. Native tests compile each translation unit separately before linking. Four negative examples check ambiguous calls, undeclared functions, missing definitions and duplicate definitions. The local recovery drill verifies a copied synthetic SQLite database's integrity and rows. No live load test, production backup, restore, monitoring service or full browser end-to-end pass is implied. `docs/operations.md` defines deployment/rollback, privacy retention, recovery limitations and the required hosted evidence. The persisted gate explicitly tracks Steps 14–20 and keeps `nextStep` at the earliest unresolved gate.

## Practice-driven topic review (2026-10-14)
Public topic metadata binds all 26 learner lessons to versioned Development log review pages. The practice tutor accepts only current checked prediction/concept results, retains bounded in-tab topic counts and incorrect-item IDs, and chooses authored review prompts by repeated-error count. It ignores stale results and makes no claim that practice frequency establishes learning. The assessment UI provides immediate review links beside incorrect items. Original hint notes may match a topic through local keyword rules, without semantic grading or provider transmission.

Review pages fetch the existing learner-safe lesson endpoint, validate lesson ID/version, show every complete project file and the authored trace, and return to the originating concept check. Notes/answers are not used to train a model. No new durable records, AI service, execution capability or reward authority is introduced. The compiler and Step 13 AI release gates remain open.
