diff --git a/cypress/e2e/adaptive-learning.cy.ts b/cypress/e2e/adaptive-learning.cy.ts new file mode 100644 index 0000000..156607a --- /dev/null +++ b/cypress/e2e/adaptive-learning.cy.ts @@ -0,0 +1,325 @@ +import { + checkAccessibility, + expectMainNavigation, + expectNoPageOverflow, + exploreNotAnd, +} from '../support/checks'; + +const choicesKey = 'chipsandcode.learning-choices.v1'; +function openChoices() { + cy.get('.topic-coach > summary').click(); +} +function openTopics() { + cy.get('.topic-navigation > summary').click(); +} +function focusSummary(selector: string) { + // Native summary elements are focusable, but Cypress's focusable-element + // allowlist omits them. Keep the browser's real focus/keyboard behavior. + cy.get(selector).then(($summary) => $summary[0].focus()); + cy.get(selector).should('have.focus'); +} +function pressEnter() { + // Cypress 15.21's cy.press omits Enter's text/virtual-key data in CDP. + // Supply the full native event for the Electron/Chromium CI browser so + // summary/button activation is exercised, rather than simulating a click. + cy.window().then((win) => win.focus()); + const key = { key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 }; + cy.then(() => + Cypress.automation('remote:debugger:protocol', { + command: 'Input.dispatchKeyEvent', + params: { type: 'keyDown', ...key, text: '\r', unmodifiedText: '\r' }, + }), + ); + cy.then(() => + Cypress.automation('remote:debugger:protocol', { + command: 'Input.dispatchKeyEvent', + params: { type: 'keyUp', ...key }, + }), + ); +} + +describe('Learner choices and topic-level suggestions', () => { + it('keeps a fresh beginner entry and allows direct experienced entry without completing basics', () => { + cy.visit('/learn'); + cy.get('.computer-game').should('have.attr', 'data-ready', 'true'); + cy.findByRole('heading', { name: 'A computer starts with a signal.' }).should('be.visible'); + cy.get('.topic-coach').should('not.have.attr', 'open'); + expectMainNavigation(); + openTopics(); + cy.screenshot('adaptive-desktop-topic-picker', { capture: 'fullPage' }); + cy.findByRole('navigation', { name: 'Choose a learning topic' }).within(() => { + cy.findByRole('link', { name: /Build logic gates/ }).should('contain', '0 / 5 checked'); + cy.findByRole('link', { name: /Select & route/ }).click(); + }); + cy.location('search').should('eq', '?mission=mux'); + cy.findByRole('heading', { name: 'Select a data path' }).should('be.visible'); + cy.window().then((win) => { + expect(win.localStorage.getItem('chipsandcode.progress.v1')).to.equal(null); + expect(win.localStorage.getItem('chipsandcode.signal-intro.v1')).to.equal(null); + }); + openChoices(); + cy.get('.topic-coach').should('contain', 'Revisit build logic gates'); + cy.injectAxe(); + checkAccessibility(); + cy.screenshot('adaptive-desktop-topic-choice', { capture: 'fullPage' }); + }); + + it('keeps forward progression and reload aligned after choosing a later mission directly', () => { + cy.visit('/learn?mission=and'); + cy.get('.computer-game').should('have.attr', 'data-ready', 'true'); + cy.findByRole('combobox', { name: 'Editor view' }).select('code'); + cy.findByLabelText('HDL source') + .clear() + .type('CHIP And { IN a, b; OUT out; PARTS: Nand(a=a, b=b, out=n); Not(in=n, out=out); }', { + parseSpecialCharSequences: false, + delay: 0, + }); + cy.findByRole('button', { name: 'Test circuit' }).click(); + cy.findByRole('button', { name: 'Continue' }).click(); + cy.findByRole('heading', { name: 'AND works.' }).should('be.visible'); + cy.findByRole('button', { name: 'Continue' }).click(); + cy.location('search').should('eq', '?mission=or'); + cy.findByRole('heading', { name: 'Merge two signals' }).should('be.visible'); + cy.reload(); + cy.get('.computer-game').should('have.attr', 'data-ready', 'true'); + cy.findByRole('heading', { name: 'Merge two signals' }).should('be.visible'); + cy.window().then((win) => + expect( + JSON.parse(win.localStorage.getItem('chipsandcode.progress.v1') || '[]'), + ).to.deep.equal(['and']), + ); + }); + + it('updates an explicit signals link when the introduction reaches NAND', () => { + cy.visit('/learn?topic=signals'); + cy.get('.computer-game').should('have.attr', 'data-ready', 'true'); + cy.findByRole('switch', { name: 'Signal' }).click().click(); + cy.findByRole('button', { name: 'Continue' }).click(); + exploreNotAnd(); + cy.location('search').should('eq', '?mission=nand'); + cy.reload(); + cy.get('.computer-game').should('have.attr', 'data-ready', 'true'); + cy.findByRole('heading', { name: 'AND, with its answer flipped.' }).should('be.visible'); + }); + + it('persists explicit topic skips without credit and keeps manual recovery available', () => { + cy.visit('/learn'); + cy.get('.computer-game').should('have.attr', 'data-ready', 'true'); + openChoices(); + cy.findByRole('button', { name: 'Familiar? Skip this topic' }).click(); + cy.get('.topic-coach .adaptive-suggestion').click(); + cy.findByRole('heading', { name: 'AND, with its answer flipped.' }).should('be.visible'); + cy.get('.topic-coach').should('have.attr', 'data-topic', 'gates'); + openChoices(); + cy.findByRole('button', { name: 'Familiar? Skip this topic' }).click(); + cy.get('.topic-coach .adaptive-suggestion').click(); + cy.findByRole('heading', { name: 'Select a data path' }).should('be.visible'); + cy.reload(); + cy.get('.computer-game').should('have.attr', 'data-ready', 'true'); + openTopics(); + cy.findByRole('navigation', { name: 'Choose a learning topic' }) + .findByRole('link', { name: /Build logic gates/ }) + .should('contain', '0 / 5 checked') + .and('contain', 'Skipped by choice') + .click(); + cy.findByRole('heading', { name: 'AND, with its answer flipped.' }).should('be.visible'); + openChoices(); + cy.findByRole('button', { name: 'Need more help' }).click(); + cy.get('.topic-coach').should('not.contain', 'Skipped by your choice'); + cy.window().then((win) => { + expect(win.localStorage.getItem('chipsandcode.progress.v1')).to.equal(null); + expect(win.localStorage.getItem('chipsandcode.signal-intro.v1')).to.equal(null); + }); + }); + + it('keeps skipped signal observations unearned after directly checking NAND and reloading', () => { + cy.visit('/learn?mission=nand'); + cy.get('.computer-game').should('have.attr', 'data-ready', 'true'); + cy.findByRole('button', { name: 'Output 1' }).click(); + cy.findByRole('button', { name: 'Next combination' }).click(); + cy.findByRole('button', { name: 'Input b 0' }).click(); + cy.findByRole('button', { name: 'Output 1' }).click(); + cy.findByRole('button', { name: 'Next combination' }).click(); + cy.findByRole('button', { name: 'Input a 0' }).click(); + cy.findByRole('button', { name: 'Output 0' }).click(); + cy.findByRole('button', { name: 'Next combination' }).click(); + cy.findByRole('button', { name: 'Input b 1' }).click(); + cy.findByRole('button', { name: 'Output 1' }).click(); + cy.findByRole('button', { name: 'Continue' }).click(); + cy.findByRole('heading', { name: 'NAND, explored.' }).should('be.visible'); + cy.window().then((win) => + expect(win.localStorage.getItem('chipsandcode.signal-intro.v1')).to.equal('not-observed'), + ); + cy.reload(); + cy.get('.computer-game').should('have.attr', 'data-ready', 'true'); + openTopics(); + cy.findByRole('navigation', { name: 'Choose a learning topic' }) + .findByRole('link', { name: /Signals & first gates/ }) + .should('contain', 'Not explored here'); + }); + + it('makes feedback optional, scoped to one topic, persistent and reversible', () => { + cy.visit('/learn?mission=not'); + cy.get('.computer-game').should('have.attr', 'data-ready', 'true'); + openChoices(); + cy.findByRole('button', { name: 'Too easy' }).click(); + cy.get('.topic-coach .adaptive-suggestion').should('have.attr', 'href', '/learn?mission=xor'); + cy.get('.topic-coach .adaptive-suggestion').click(); + cy.findByRole('heading', { name: 'Detect a difference' }).should('be.visible'); + cy.findByRole('button', { name: 'Need more help' }).click(); + cy.get('.topic-coach').should('contain', 'A smaller step'); + cy.get('.topic-coach .adaptive-suggestion').should('have.attr', 'href', '/learn?mission=nand'); + cy.reload(); + cy.get('.computer-game').should('have.attr', 'data-ready', 'true'); + openChoices(); + cy.findByRole('button', { name: 'Need more help' }).should('have.attr', 'aria-pressed', 'true'); + cy.findByRole('button', { name: 'About right' }).click(); + cy.get('.topic-coach').should('not.contain', 'A smaller step'); + cy.findByRole('button', { name: 'Reset this topic’s choices' }).click(); + cy.findByRole('button', { name: 'About right' }).should('have.attr', 'aria-pressed', 'false'); + cy.window().then((win) => { + expect(JSON.parse(win.localStorage.getItem(choicesKey) || '{}')).to.deep.equal({ + version: 1, + topics: {}, + }); + expect(win.localStorage.getItem('chipsandcode.progress.v1')).to.equal(null); + }); + }); + + it('skips by choice and recovers a mistaken placement while retaining an unfinished chapter draft', () => { + cy.visit('/learn/path/arithmetic?task=alu'); + cy.get('.course-page') + .should('have.attr', 'data-task', 'alu') + .and('have.attr', 'data-ready', 'true'); + cy.findByRole('combobox', { name: 'Construction view' }).select('code'); + cy.findByRole('textbox', { name: 'HDL source' }) + .clear() + .type('// my unfinished ALU', { parseSpecialCharSequences: false, delay: 0 }); + openChoices(); + cy.findByRole('button', { name: 'Familiar? Skip this topic' }).click(); + cy.get('.topic-coach').should('contain', 'Nothing in this topic was marked complete'); + cy.get('.topic-coach .adaptive-suggestion').should( + 'have.attr', + 'href', + '/learn/path/memory?task=bit', + ); + cy.findByRole('button', { name: 'Need more help' }).click(); + cy.get('.topic-coach .adaptive-suggestion') + .should('have.attr', 'href', '/learn/path/arithmetic?task=halfadder') + .click(); + cy.get('.course-page').should('have.attr', 'data-task', 'halfadder'); + cy.findByRole('heading', { name: 'Add two bits' }).should('have.focus'); + cy.contains('summary', 'Steps in this layer').click(); + cy.findByRole('button', { name: /Control a calculation/ }).click(); + cy.get('.course-page').should('have.attr', 'data-task', 'alu'); + cy.location('search').should('eq', '?task=alu'); + cy.findByRole('combobox', { name: 'Construction view' }).select('code'); + cy.findByRole('textbox', { name: 'HDL source' }).should('have.value', '// my unfinished ALU'); + cy.reload(); + cy.get('.course-page') + .should('have.attr', 'data-ready', 'true') + .and('have.attr', 'data-task', 'alu'); + cy.findByRole('combobox', { name: 'Construction view' }).select('code'); + cy.findByRole('textbox', { name: 'HDL source' }).should('have.value', '// my unfinished ALU'); + cy.window().then((win) => { + expect(win.localStorage.getItem('chipsandcode.part-one.progress.v1')).to.equal(null); + expect( + JSON.parse(win.localStorage.getItem(choicesKey) || '{}').topics.arithmetic, + ).to.deep.equal({ feedback: 'need-help' }); + }); + }); + + it('preserves old progress and drafts, switches chapters, and restores direct entry on browser back', () => { + cy.visit('/learn?mission=not', { + onBeforeLoad(win) { + win.localStorage.setItem('chipsandcode.signal-isles.progress.v1', '["nand","not"]'); + win.localStorage.setItem('chipsandcode.part-one.progress.v1', '["buses/not16"]'); + win.localStorage.setItem( + 'chipsandcode.part-one.draft.buses/and16', + '// saved before learning choices', + ); + }, + }); + cy.get('.computer-game').should('have.attr', 'data-ready', 'true'); + openTopics(); + cy.findByRole('navigation', { name: 'Choose a learning topic' }).within(() => { + cy.findByRole('link', { name: /Build logic gates/ }).should('contain', '2 / 5 checked'); + cy.findByRole('link', { name: /Work with words/ }) + .should('contain', '1 / 9 checked') + .click(); + }); + cy.get('.course-page').should('have.attr', 'data-task', 'not16'); + cy.contains('summary', 'Steps in this layer').click(); + cy.findByRole('button', { name: /Combine two words/ }).click(); + cy.findByRole('combobox', { name: 'Construction view' }).select('code'); + cy.findByRole('textbox', { name: 'HDL source' }).should( + 'have.value', + '// saved before learning choices', + ); + openTopics(); + cy.findByRole('navigation', { name: 'Choose a learning topic' }) + .findByRole('link', { name: /Turn names into instructions/ }) + .click(); + cy.get('.course-page').should('have.attr', 'data-chapter', 'assembler'); + cy.go('back'); + cy.get('.course-page') + .should('have.attr', 'data-ready', 'true') + .and('have.attr', 'data-task', 'and16'); + cy.findByRole('combobox', { name: 'Construction view' }).select('code'); + cy.findByRole('textbox', { name: 'HDL source' }).should( + 'have.value', + '// saved before learning choices', + ); + }); + + it('keeps choices and drafts usable through client navigation when storage is unavailable', () => { + cy.visit('/learn/path/arithmetic?task=alu', { + onBeforeLoad(win) { + cy.stub(win.Storage.prototype, 'getItem').throws(new Error('Storage denied')); + cy.stub(win.Storage.prototype, 'setItem').throws(new Error('Storage denied')); + }, + }); + cy.get('.course-page').should('have.attr', 'data-ready', 'true'); + cy.findByRole('combobox', { name: 'Construction view' }).select('code'); + cy.findByRole('textbox', { name: 'HDL source' }) + .clear() + .type('// session ALU', { parseSpecialCharSequences: false, delay: 0 }); + openChoices(); + cy.findByRole('button', { name: 'Need more help' }).click(); + cy.get('.topic-coach').should('contain', 'Reloading may lose them'); + cy.get('.topic-coach .adaptive-suggestion').click(); + cy.get('.course-page').should('have.attr', 'data-task', 'halfadder'); + cy.contains('summary', 'Steps in this layer').click(); + cy.findByRole('button', { name: /Control a calculation/ }).click(); + cy.findByRole('combobox', { name: 'Construction view' }).select('code'); + cy.findByRole('textbox', { name: 'HDL source' }).should('have.value', '// session ALU'); + cy.findByRole('button', { name: 'Need more help' }).should('have.attr', 'aria-pressed', 'true'); + }); + + it('supports narrow screens, keyboard activation, and accessible optional guidance', () => { + cy.viewport(320, 760); + cy.visit('/learn/path/memory?task=pc'); + cy.get('.course-page').should('have.attr', 'data-ready', 'true'); + cy.get('h1').should('have.focus'); + focusSummary('.topic-navigation > summary'); + pressEnter(); + cy.get('.topic-navigation').should('have.attr', 'open'); + cy.screenshot('adaptive-mobile-topic-picker', { capture: 'fullPage' }); + cy.injectAxe(); + checkAccessibility(); + expectNoPageOverflow(); + focusSummary('.topic-navigation > summary'); + pressEnter(); + focusSummary('.topic-coach > summary'); + pressEnter(); + cy.findByRole('button', { name: 'Need more help' }).focus(); + pressEnter(); + cy.findByRole('button', { name: 'Need more help' }).should('have.attr', 'aria-pressed', 'true'); + cy.screenshot('adaptive-mobile-help-and-refreshers', { capture: 'fullPage' }); + checkAccessibility(); + expectNoPageOverflow(); + cy.findByRole('button', { name: 'Close adjustments' }).click(); + cy.get('.topic-coach').should('not.have.attr', 'open'); + cy.get('.topic-coach > summary').should('have.focus'); + }); +}); diff --git a/docs/adaptive-learning-decision.md b/docs/adaptive-learning-decision.md new file mode 100644 index 0000000..1d12a9b --- /dev/null +++ b/docs/adaptive-learning-decision.md @@ -0,0 +1,74 @@ +# Topic choices and transparent recommendations + +Decision for [#49](https://github.com/durasj/chipsandcode/issues/49), stacked on revamp [#47](https://github.com/durasj/chipsandcode/pull/47), inspected at `17da6ded505c6859ce2adc955a1ef750680fbcf2`. Sources reviewed 15 November 2026. + +## The problem in this course + +The signal introduction is deliberately guided. Gate missions previously resumed at the first unchecked gate; only verified gates could be reopened. Projects 1–6 already allowed task selection, but there was no direct gate/topic entry, no shared view of progress, and no way to express that a topic was familiar or that help was needed. Construction checks establish that a particular answer meets its modeled specification. They do not establish retention, independent reasoning, or transfer to a new task. + +## Alternatives and evidence + +| Approach | Benefit | Cost / uncertainty | Decision | +| ---------------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | +| Self-selected starting topic | Experienced learners bypass familiar material; beginners retain the original entry | Self-reports can be mistaken | Add optional topic navigation, explicit skips, and recovery links | +| Optional diagnostic questions | Could identify narrower gaps before a project | Needs validated questions, variants and explanations; a short quiz could overstate understanding | Defer a separate placement test | +| Challenge-first entry | Existing circuit/assembly checks offer useful, immediate task-specific evidence | One construction can be copied or solved with help; success does not verify all prerequisites | Offer existing synthesis tasks, without crediting earlier tasks | +| Automatic performance placement | Could respond without requiring feedback | Current data cannot reliably distinguish misconceptions from exploration, editor errors or outside experience | Use verified task IDs to suggest unfinished work, never infer learner ability | +| Permanent beginner/advanced tracks | Simple presentation | Knowledge varies by topic and labels impede recovery | Keep preferences per topic | + +[Khan Academy's Course and Unit Mastery](https://support.khanacademy.org/hc/en-us/articles/115002552631-What-are-Course-and-Unit-Mastery) is a useful comparison: it distinguishes skill-level evidence and reports how activities affect progress. Its multi-level mastery system depends on assessment activities that this course does not have. We borrow topic-level granularity and visible evidence, not its ratings or thresholds. + +[Carnegie Mellon's learning principles](https://www.cmu.edu/teaching/principles/learning.html) describe the importance of prior knowledge, component skills followed by integration, targeted feedback and learner self-monitoring. These support our choice to expose prerequisite refreshers, smaller practice steps and synthesis tasks. This is a design inference, not evidence that these particular rules improve circuit-learning outcomes. + +## Chosen interaction + +- `/learn` still starts immediately with the signal. There is no onboarding question or compulsory assessment. +- **Choose a topic** is a closed, keyboard-operable disclosure near the top of Learn, the path, and each project. It exposes nine topics through the assembler. Direct links accept stable mission/task IDs; ordinary step controls update the URL so reload/back restores the selected work. Unrecognized IDs safely fall back to normal progress. +- **Adjust this topic** is a closed disclosure near the work, also available at gate milestones. It does not interrupt every edit, test, hint or successful action. Closing it dismisses the interaction and restores focus. Feedback remains changeable at any time. +- **Too easy** offers an existing synthesis challenge in the same topic. If that challenge is current/already checked, it offers the next unfinished, unskipped topic. Nothing navigates automatically. +- **About right** offers the first unchecked activity in this topic, then the next available topic. +- **Need more help** exposes a task-specific hint and offers the smaller first activity. This also reverses a previous skip. Full explanations and relevant prerequisite activities remain linked. +- **Familiar? Skip this topic** records a learner choice, keeps earlier work accessible and excludes that topic from forward suggestions. It never adds verified tasks or observed intro steps. Reset one topic or all learning choices without touching work. + +| Topic | More challenge | More help / focused starting point | +| --------------------------------- | -------------------------- | -------------------------------------------------------------------- | +| Signals, NOT and AND observations | Begin gate construction | Signal switch and first-gate observations | +| Logic gates | XOR composition | NAND behavior; current construction hint | +| Routing | Demultiplexor construction | Multiplexor and logic-gate refreshers | +| Words and buses | Eight-way demultiplexor | Single-bit inversion applied to a word | +| Arithmetic | ALU control | Half adder, gates and buses | +| Memory | Program counter | One stored bit, routing and buses | +| Machine language | Keyboard-to-screen program | Decode an instruction, arithmetic and memory | +| Architecture | Complete Computer | Memory interface, arithmetic, memory and machine-language refreshers | +| Assembler | Implement an assembler | Encode a computation, machine-language refresher | + +“Harder” means combining more existing ideas, not reducing explanation access or imposing stricter verification. “Easier” means a smaller construction and an immediately available hint, not lowering the correctness requirement. Visual/Code/Split preferences and all six tool types are unchanged. New task variants are not necessary for voluntary challenge entry; variants and multiple independent demonstrations would be necessary before claiming measured mastery. + +## Signals, uncertainty and dependencies + +`model.ts` is a pure, deterministic ruleset. Its inputs are stable topic/task IDs, explicit topic feedback/skips, checked task IDs, and the existing observed-introduction flag. There are no learner timestamps, elapsed/completion/dwell times, inactivity, hint counts, failed attempts or editor errors. Simulator clocks and assembler safety timeouts continue to function independently. + +Topic prerequisites are explicit in `topics.ts`, including hardware branches: memory depends on routing/buses rather than requiring arithmetic, and the assembler depends on machine language rather than every hardware construction. Incomplete prerequisite activities remain listed as optional refreshers even when skipped by choice. A skip is not proof of understanding, nor is absence of a checked task proof of a gap. The UI says what has been checked here and uses “suggestion,” never a mastery score. + +Default suggestions resume unfinished work. Completing every activity permits suggesting the next topic; this describes activity completion only. One pass affects only that task. One failure or use of help cannot demote the learner, lock navigation or change their stated preference. + +## State, migration and failure handling + +The new `chipsandcode.learning-choices.v1` payload contains only `{ version: 1, topics: { [topicId]: { feedback?, skipped? } } }`. Familiarity is recorded only as the learner's explicit skip, not as an assessment score. Feedback is a separate field and does not imply familiarity. Unknown topics/values, invalid JSON and unsupported versions are ignored. There is no account, network request, analytics or new backend. + +Existing completion/draft keys are retained: + +- Gate progress: `chipsandcode.progress.v1`, with `chipsandcode.signal-isles.progress.v1` fallback. +- Intro observations: `chipsandcode.signal-intro.v1`; pre-existing NAND progress with no intro flag retains the revamp's legacy inference that the introduction has been seen. A newly checked NAND reached through direct entry stores `not-observed` when the introduction was not explored, preventing that historical fallback from crediting skipped observations. Actually exploring the introduction replaces it with `complete`. +- Gate drafts: `chipsandcode:workbench:draft::v2`, with the existing legacy draft reader. +- Project progress and drafts: `chipsandcode.part-one.progress.v1` and `chipsandcode.part-one.draft./`. + +An additive evidence reader joins these views without rewriting old work. Current in-memory task completions are included immediately. A small storage adapter caches read and written values; when local storage fails, latest drafts, progress and choices remain usable through client-side topic navigation. Failed writes never resurrect stale persisted drafts. Notices explain the limits: a full reload or closed tab can lose session-only work. Recovering storage permits subsequent writes again. Resetting choices cannot clear completion or draft keys. + +Each save/reset also emits the browser event `chipsandcode:learning-choices-changed` with the same versioned payload in `event.detail`. Optional visual-journey consumers can update immediately without importing this feature; the payload includes session-only changes when storage writes fail. No completion, draft or timing data is included. + +## Verification and limits + +Unit coverage exercises novice defaults, skips without credit, challenge/help/normal rules, topic-specific uncertainty, prerequisites, resets, schema validation, old-store reads, failed storage and unchanged recommendations under radically different clocks and unrelated metadata. Browser coverage adds direct and repeated task navigation, recovery with saved drafts, feedback changes/reload, legacy progress, denied storage, keyboard controls, 320px layouts and accessibility checks. The existing full learner/tool suites remain required. + +This first version makes controllable, explainable recommendations. It does not claim accurate personalization or learning effectiveness. Follow-up learner testing should examine whether people find the controls, whether synthesis steps are suitable, whether suggested prerequisites are useful, and whether beginners retain their approachable entry. Any future diagnostic/mastery feature needs independent task variants, misconception evidence, and evaluation with learners before introducing scoring. diff --git a/src/lib/course/Chapter.svelte b/src/lib/course/Chapter.svelte index 0766f66..2e4c492 100644 --- a/src/lib/course/Chapter.svelte +++ b/src/lib/course/Chapter.svelte @@ -1,5 +1,7 @@ + +
+ Adjust this topic{#if choice?.skipped} + · skipped{:else if choice?.feedback} + · preference saved{/if} +
+
+ How does {topic.title.toLowerCase()} feel? +

Optional. This changes the suggestion for this topic, never your checked work.

+ +
+ {#if choice?.skipped} +

+ Skipped by your choice. Nothing in this topic was marked complete. +

+ {/if} +
+ {#if choice?.feedback === 'need-help' && hint} +

A smaller step
{hint}

+ {/if} + {#if suggestion} +

{suggestion.reason}

+ {suggestion.task.title} → + {:else} +

+ No later unfinished topic is suggested. You can revisit any task or explore the Tools. +

+ {/if} +
+

+ A suggestion, not a mastery rating. Hints and explanations are always available. +

+ {#if refreshers.length} +
+

+ This topic builds on these ideas. Their activities have not all been checked here; refresh + only what you need. +

+ +
+ {/if} + Full explanation for this topic ↗ +
+ {#if !choice?.skipped}{/if} + {#if choice}{/if} + +
+ {#if $choicesNotice}

{$choicesNotice}

{/if} +
+
diff --git a/src/lib/learning/adaptive/TopicNavigator.svelte b/src/lib/learning/adaptive/TopicNavigator.svelte new file mode 100644 index 0000000..765dc2e --- /dev/null +++ b/src/lib/learning/adaptive/TopicNavigator.svelte @@ -0,0 +1,76 @@ + + +
+ Choose a topic +
+

+ Start anywhere. Unfinished work stays available, and choosing a topic never marks earlier work + complete. +

+ {#if mounted && recommendation} +

+ Suggested next { + opened = false; + }}>{recommendation.task.title} → +

+ {/if} + + {#if Object.keys($learningChoices.topics).length} + +

Resets suggestions and skips. Checked work and drafts stay saved.

+ {/if} +
+
diff --git a/src/lib/learning/adaptive/adaptive.css b/src/lib/learning/adaptive/adaptive.css new file mode 100644 index 0000000..cebc500 --- /dev/null +++ b/src/lib/learning/adaptive/adaptive.css @@ -0,0 +1,190 @@ +.adaptive-panel { + color: #e3e3ef; + font-family: Inter, ui-sans-serif, system-ui, sans-serif; + font-size: 14px; + line-height: 1.6; + text-align: left; +} +.adaptive-panel > summary { + cursor: pointer; + min-height: 44px; + padding: 11px 0; + color: #bbb5ee; +} +.adaptive-panel[open] > summary { + color: #f0edf9; +} +.adaptive-content { + border: 1px solid #343446; + border-radius: 4px; + background: #11141e; + padding: 20px; +} +.adaptive-content p { + margin: 0 0 16px; + max-width: 68ch; +} +.adaptive-panel a { + color: #c3baff; + text-decoration: underline; + text-underline-offset: 4px; +} +.adaptive-panel button { + font: inherit; + cursor: pointer; +} +.adaptive-panel :is(a, button, summary):focus-visible { + outline: 2px solid #c3baff !important; + outline-offset: 4px; +} +.topic-navigation { + width: min(1060px, 100%); + margin: 0 auto; + padding: 0 28px; +} +.topic-navigation nav ol { + padding: 0; + margin: 0; + list-style: none; + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 1px; + background: #343446; + border: 1px solid #343446; +} +.topic-navigation nav li { + min-width: 0; + background: #11141e; +} +.topic-navigation nav a { + display: flex; + height: 100%; + flex-direction: column; + gap: 5px; + padding: 16px; + text-decoration: none; +} +.topic-navigation nav a:hover { + background: #1b1d2d; +} +.topic-title { + color: #ece9fb; + font-weight: 500; +} +.topic-description, +.topic-evidence, +.adaptive-note { + color: #b2b5c5; + font-size: 12px; +} +.topic-evidence { + margin-top: auto; + padding-top: 8px; + color: #c3baff; +} +.adaptive-next { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 6px 14px; +} +.adaptive-next > span { + color: #b2b5c5; + font-size: 12px; +} +.topic-coach { + margin: 24px auto; + width: min(960px, calc(100% - 56px)); +} +.course-page > .topic-coach, +.course-page > .topic-navigation { + width: 100%; + padding: 0; +} +.learning-milestone > .topic-coach { + width: 100%; +} +.adaptive-panel fieldset { + border: 0; + margin: 0; + padding: 0; + min-width: 0; +} +.adaptive-panel legend { + font-size: 17px; + font-weight: 500; + margin-bottom: 6px; +} +.adaptive-panel fieldset p { + color: #b2b5c5; + font-size: 13px; +} +.feedback-options { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-bottom: 20px; +} +.feedback-options button { + color: #ddd9f4; + min-height: 44px; + padding: 8px 14px; + border: 1px solid #57516f; + border-radius: 3px; +} +.feedback-options button[aria-pressed='true'] { + border-color: #b9adff; + background: #30294f; + color: white; +} +.adaptive-recommendation { + border-top: 1px solid #343446; + padding-top: 16px; + margin-bottom: 16px; +} +.adaptive-recommendation p { + margin-bottom: 8px; +} +.adaptive-refreshers { + border-top: 1px solid #343446; + padding-top: 16px; +} +.adaptive-refreshers ul { + padding-left: 20px; + margin: 0 0 16px; +} +.adaptive-refreshers a { + display: inline-block; + padding: 8px 0; +} +.adaptive-reading { + display: inline-block; + padding: 8px 0; +} +.adaptive-choice-actions { + display: flex; + flex-wrap: wrap; + gap: 4px 22px; + margin-top: 14px; +} +.adaptive-text-button { + color: #c8c1df; + text-decoration: underline; + text-underline-offset: 4px; + min-height: 44px; + padding: 8px 0; +} +@media (max-width: 700px) { + .topic-navigation nav ol { + grid-template-columns: 1fr; + } + .topic-navigation { + padding: 0 20px; + } + .topic-coach { + width: calc(100% - 40px); + } + .adaptive-content { + padding: 16px; + } +} diff --git a/src/lib/learning/adaptive/model.test.ts b/src/lib/learning/adaptive/model.test.ts new file mode 100644 index 0000000..c24d0e3 --- /dev/null +++ b/src/lib/learning/adaptive/model.test.ts @@ -0,0 +1,227 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { courseChapters } from '#lib/course/data.js'; +import { missions } from '#lib/game/missions.js'; +import { + changeChoice, + completedTasks, + emptyChoices, + nextTopic, + parseChoices, + recommend, + suggestedRefreshers, + topicFinished, + type LearningEvidence, +} from './model.js'; +import { learningTopics, topicById, topicForMission } from './topics.js'; + +const fresh: LearningEvidence = { verifiedTasks: [], exploredSignals: false }; +afterEach(() => vi.useRealTimers()); + +describe('A topic path with learner agency', () => { + it('starts a novice at signals without an assessment', () => { + expect(nextTopic(emptyChoices(), fresh)?.task.href).toBe('/learn?topic=signals'); + expect(recommend('signals', emptyChoices(), fresh)?.task.id).toBe('signals'); + }); + + it('recognizes an explored introduction separately from checked constructions', () => { + expect(completedTasks('signals', fresh)).toEqual([]); + expect(completedTasks('signals', { ...fresh, exploredSignals: true })).toEqual(['signals']); + expect(nextTopic(emptyChoices(), { ...fresh, exploredSignals: true })?.task.id).toBe( + 'missions/nand', + ); + expect(topicFinished('gates', { ...fresh, exploredSignals: true })).toBe(false); + }); + + it('skips a familiar topic without adding evidence or hiding its tasks', () => { + const choices = changeChoice(emptyChoices(), 'signals', { skipped: true }); + expect(nextTopic(choices, fresh)?.task.id).toBe('missions/nand'); + expect(recommend('signals', choices, fresh)?.task.id).toBe('missions/nand'); + expect(fresh.verifiedTasks).toEqual([]); + expect(topicFinished('signals', fresh)).toBe(false); + expect(topicById('signals').tasks[0].href).toBe('/learn?topic=signals'); + }); + + it('chooses a synthesis task only after an explicit too-easy preference', () => { + const choices = changeChoice(emptyChoices(), 'gates', { feedback: 'too-easy' }); + expect(recommend('gates', choices, fresh, 'missions/not')?.task.id).toBe('missions/xor'); + expect(recommend('gates', emptyChoices(), fresh, 'missions/not')?.task.id).toBe( + 'missions/nand', + ); + expect( + recommend('memory', changeChoice(choices, 'memory', { feedback: 'too-easy' }), fresh)?.task + .id, + ).toBe('memory/pc'); + }); + + it('offers a later topic when already at the synthesis task, without marking earlier tasks', () => { + const choices = changeChoice(emptyChoices(), 'gates', { feedback: 'too-easy' }); + expect(recommend('gates', choices, fresh, 'missions/xor')?.task.id).toBe('missions/mux'); + expect( + recommend('gates', choices, { ...fresh, verifiedTasks: ['missions/xor'] })?.task.id, + ).toBe('missions/mux'); + expect(completedTasks('gates', { ...fresh, verifiedTasks: ['missions/xor'] })).toEqual([ + 'missions/xor', + ]); + }); + + it('uses a small starting task for help even after completion and can reverse mistaken skipping', () => { + const skipped = changeChoice(emptyChoices(), 'arithmetic', { + skipped: true, + feedback: 'too-easy', + }); + const choices = changeChoice(skipped, 'arithmetic', { feedback: 'need-help' }); + const result = recommend( + 'arithmetic', + choices, + { ...fresh, verifiedTasks: ['arithmetic/halfadder'] }, + 'arithmetic/alu', + ); + expect(result?.task.id).toBe('arithmetic/halfadder'); + expect(result?.reason).toContain('more help'); + expect(choices.topics.arithmetic?.skipped).toBeUndefined(); + expect(skipped.topics.arithmetic?.skipped).toBe(true); + }); + + it('uses task evidence for the next unverified task, never a broad ability rating', () => { + const evidence = { ...fresh, verifiedTasks: ['buses/not16'] }; + const choices = changeChoice(emptyChoices(), 'buses', { feedback: 'about-right' }); + expect(recommend('buses', choices, evidence)?.task.id).toBe('buses/and16'); + expect(topicFinished('buses', evidence)).toBe(false); + expect(completedTasks('gates', evidence)).toEqual([]); + }); + + it('moves on when all activities of one topic are checked and stops at the guided boundary', () => { + const evidence = { + ...fresh, + verifiedTasks: topicById('assembler').tasks.map((task) => task.id), + }; + expect(topicFinished('assembler', evidence)).toBe(true); + expect(recommend('assembler', emptyChoices(), evidence)).toBeNull(); + expect(nextTopic(emptyChoices(), fresh, 'assembler')).toBeNull(); + const all = { + exploredSignals: true, + verifiedTasks: learningTopics.flatMap((topic) => topic.tasks.map((task) => task.id)), + }; + expect(nextTopic(emptyChoices(), all)).toBeNull(); + }); + + it('keeps unknown prerequisite refreshers visible after a skip or unrelated success', () => { + expect(suggestedRefreshers('signals', fresh)).toEqual([]); + expect(suggestedRefreshers('architecture', fresh)).toEqual([ + 'arithmetic', + 'memory', + 'machine-language', + ]); + const evidence = { + ...fresh, + verifiedTasks: topicById('arithmetic').tasks.map((task) => task.id), + }; + expect(suggestedRefreshers('architecture', evidence)).toEqual(['memory', 'machine-language']); + expect(suggestedRefreshers('gates', { ...fresh, exploredSignals: true })).toEqual([]); + }); + + it('resets only choices and retains the original evidence', () => { + const evidence = { ...fresh, verifiedTasks: ['missions/not'] }; + const choices = changeChoice(emptyChoices(), 'gates', { feedback: 'too-easy' }); + const reset = changeChoice(choices, 'gates', null); + expect(reset).toEqual(emptyChoices()); + expect(evidence.verifiedTasks).toEqual(['missions/not']); + expect(choices.topics.gates?.feedback).toBe('too-easy'); + }); + + it('makes identical recommendations regardless of elapsed time or extraneous event metadata', () => { + vi.useFakeTimers(); + const choices = changeChoice(emptyChoices(), 'memory', { feedback: 'too-easy' }); + vi.setSystemTime(new Date('2020-01-01')); + const before = recommend('memory', choices, fresh); + vi.setSystemTime(new Date('2040-01-01')); + expect( + recommend('memory', choices, { + ...fresh, + ...{ elapsed: 1e9, failedAttempts: 500, hintCount: 500 }, + }), + ).toEqual(before); + expect( + recommend('memory', choices, { + ...fresh, + ...{ elapsed: 0, failedAttempts: 0, hintCount: 0 }, + }), + ).toEqual(before); + }); +}); + +describe('Versioned learning choices', () => { + it.each([ + null, + '', + '{', + 'null', + '[]', + '{}', + '{"version":2,"topics":{}}', + '{"version":1,"topics":false}', + ])('recovers from absent, malformed or unsupported input %s', (raw) => { + expect(parseChoices(raw)).toEqual(emptyChoices()); + }); + it('accepts only known topics and feedback; drops timestamps, scores and unknown fields', () => { + expect( + parseChoices( + JSON.stringify({ + version: 1, + topics: { + gates: { skipped: true, feedback: 'too-easy', mastery: 99, seconds: 1 }, + signals: { skipped: false, feedback: 'need-help' }, + routing: { feedback: 'about-right' }, + buses: { feedback: 'advanced', skipped: 'true' }, + memory: 'advanced', + unknown: { skipped: true }, + }, + }), + ), + ).toEqual({ + version: 1, + topics: { + gates: { skipped: true, feedback: 'too-easy' }, + signals: { feedback: 'need-help' }, + routing: { feedback: 'about-right' }, + }, + }); + }); + it('round-trips choices independently of progress', () => { + const choices = changeChoice(emptyChoices(), 'memory', { + skipped: true, + feedback: 'need-help', + }); + expect(parseChoices(JSON.stringify(choices))).toEqual(choices); + }); +}); + +describe('Topic contracts cover the existing guided course', () => { + it('maps every mission and project task exactly once and uses valid prerequisite/challenge IDs', () => { + const ids = learningTopics.flatMap((topic) => topic.tasks.map((task) => task.id)); + expect(new Set(ids).size).toBe(ids.length); + expect(ids).toEqual([ + 'signals', + ...missions.map((mission) => `missions/${mission.id}`), + ...courseChapters.flatMap((chapter) => + chapter.tasks.map((task) => `${chapter.id}/${task.id}`), + ), + ]); + learningTopics.forEach((topic, index) => { + expect(topic.tasks.some((task) => task.id === topic.challenge)).toBe(true); + topic.prerequisites.forEach((id) => + expect(learningTopics.findIndex((item) => item.id === id)).toBeLessThan(index), + ); + topic.tasks.forEach((task) => { + const url = new URL(task.href, 'https://example.test'); + expect(url.pathname === '/learn' || url.pathname === `/learn/path/${topic.id}`).toBe(true); + expect(url.search).not.toBe(''); + }); + }); + }); + it('keeps knowledge in topic groups rather than a permanent learner level', () => { + expect(topicForMission('not')).toBe('gates'); + expect(topicForMission('mux')).toBe('routing'); + expect(topicForMission('dmux')).toBe('routing'); + }); +}); diff --git a/src/lib/learning/adaptive/model.ts b/src/lib/learning/adaptive/model.ts new file mode 100644 index 0000000..0cae971 --- /dev/null +++ b/src/lib/learning/adaptive/model.ts @@ -0,0 +1,127 @@ +import { learningTopics, topicById, type LearningTask, type TopicId } from './topics.js'; + +export type DifficultyFeedback = 'too-easy' | 'about-right' | 'need-help'; +export interface TopicChoice { + skipped?: true; + feedback?: DifficultyFeedback; +} +export interface LearningChoices { + version: 1; + topics: Partial>; +} +export interface LearningEvidence { + /** A passed task is evidence about that task, never a claim of topic mastery. */ + verifiedTasks: string[]; + exploredSignals: boolean; +} +export interface Recommendation { + task: LearningTask; + reason: string; +} +export const emptyChoices = (): LearningChoices => ({ version: 1, topics: {} }); + +export function parseChoices(raw: string | null): LearningChoices { + try { + const value = JSON.parse(raw ?? 'null'); + if (value?.version !== 1 || !value.topics || typeof value.topics !== 'object') + return emptyChoices(); + const choices = emptyChoices(); + for (const topic of learningTopics) { + const item = value.topics[topic.id]; + if (!item || typeof item !== 'object') continue; + const choice: TopicChoice = {}; + if (item.skipped === true) choice.skipped = true; + if (['too-easy', 'about-right', 'need-help'].includes(item.feedback)) + choice.feedback = item.feedback; + if (Object.keys(choice).length) choices.topics[topic.id] = choice; + } + return choices; + } catch { + return emptyChoices(); + } +} + +export function changeChoice( + choices: LearningChoices, + id: TopicId, + change: TopicChoice | null, +): LearningChoices { + const topics = { ...choices.topics }; + if (change) topics[id] = change; + else delete topics[id]; + return { version: 1, topics }; +} + +export function completedTasks(id: TopicId, evidence: LearningEvidence): string[] { + return topicById(id) + .tasks.filter((task) => + task.id === 'signals' ? evidence.exploredSignals : evidence.verifiedTasks.includes(task.id), + ) + .map((task) => task.id); +} + +export function topicFinished(id: TopicId, evidence: LearningEvidence): boolean { + return completedTasks(id, evidence).length === topicById(id).tasks.length; +} + +/** Unknown prerequisites stay visible even when the learner says they are familiar. */ +export function suggestedRefreshers(id: TopicId, evidence: LearningEvidence): TopicId[] { + return topicById(id).prerequisites.filter( + (prerequisite) => !topicFinished(prerequisite, evidence), + ); +} + +export function nextTopic( + choices: LearningChoices, + evidence: LearningEvidence, + after?: TopicId, +): Recommendation | null { + const start = after ? learningTopics.findIndex((topic) => topic.id === after) + 1 : 0; + const next = learningTopics + .slice(start) + .find((topic) => !choices.topics[topic.id]?.skipped && !topicFinished(topic.id, evidence)); + if (!next) return null; + const done = completedTasks(next.id, evidence); + return { + task: next.tasks.find((task) => !done.includes(task.id))!, + reason: `A next step in ${next.title.toLowerCase()}. You can choose any topic.`, + }; +} + +/** Pure rules: no clock, duration, failure count, hints, editor errors, or ability label. */ +export function recommend( + id: TopicId, + choices: LearningChoices, + evidence: LearningEvidence, + currentTask?: string, +): Recommendation | null { + const topic = topicById(id); + const choice = choices.topics[id]; + const done = completedTasks(id, evidence); + if (choice?.skipped) return nextTopic(choices, evidence, id); + if (choice?.feedback === 'need-help') { + return { + task: topic.tasks[0], + reason: + 'You asked for more help. Try this smaller starting step, or use the hint and focused refreshers below.', + }; + } + if (choice?.feedback === 'too-easy') { + const challenge = topic.tasks.find((task) => task.id === topic.challenge)!; + if (challenge.id !== currentTask && !done.includes(challenge.id)) { + return { + task: challenge, + reason: + 'You asked for more challenge. This task combines ideas from this topic; earlier tasks remain available.', + }; + } + return nextTopic(choices, evidence, id); + } + const next = topic.tasks.find((task) => !done.includes(task.id)); + return next + ? { + task: next, + reason: 'Keep building one step at a time. This task has not been checked here yet.', + } + : nextTopic(choices, evidence, id); +} diff --git a/src/lib/learning/adaptive/storage.test.ts b/src/lib/learning/adaptive/storage.test.ts new file mode 100644 index 0000000..fcb9553 --- /dev/null +++ b/src/lib/learning/adaptive/storage.test.ts @@ -0,0 +1,152 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { get } from 'svelte/store'; +import { + createLearningStorage, + learningChoices, + learningChoicesKey, + learningStorage, + choicesNotice, + loadLearningChoices, + readLearningEvidence, + saveLearningChoices, +} from './storage.js'; +import { emptyChoices } from './model.js'; + +function fakeStorage() { + const data = new Map(); + return { + getItem: (key: string) => data.get(key) ?? null, + setItem: (key: string, value: string) => { + data.set(key, value); + }, + }; +} +afterEach(() => { + vi.unstubAllGlobals(); + learningChoices.set(emptyChoices()); + choicesNotice.set(''); +}); + +describe('Resilient progress and draft storage', () => { + it('reads old data and writes through without changing keys or payloads', () => { + const device = fakeStorage(); + device.setItem('old', 'draft'); + const store = createLearningStorage(() => device); + expect(store.getItem('old')).toBe('draft'); + store.setItem('old', 'changed draft'); + expect(device.getItem('old')).toBe('changed draft'); + expect(store.getItem('missing')).toBeNull(); + }); + it('retains edits if writes fail and never falls back to stale persisted content', () => { + const device = fakeStorage(); + device.setItem('draft', 'old'); + const store = createLearningStorage(() => device); + expect(store.getItem('draft')).toBe('old'); + const set = vi.spyOn(device, 'setItem').mockImplementation(() => { + throw new Error('quota'); + }); + expect(() => store.setItem('draft', 'new work')).toThrow('quota'); + expect(store.getItem('draft')).toBe('new work'); + set.mockRestore(); + store.setItem('draft', 'repaired'); + expect(device.getItem('draft')).toBe('repaired'); + }); + it('retains read data when access later fails and works when storage is denied from the start', () => { + const device = fakeStorage(); + device.setItem('draft', 'saved work'); + let blocked = false; + const store = createLearningStorage(() => { + if (blocked) throw new Error('denied'); + return device; + }); + expect(store.getItem('draft')).toBe('saved work'); + blocked = true; + expect(store.getItem('draft')).toBe('saved work'); + expect(store.getItem('unseen')).toBeNull(); + expect(() => store.setItem('unseen', 'session work')).toThrow('denied'); + expect(store.getItem('unseen')).toBe('session work'); + }); +}); + +describe('Additive learning choices and read-only legacy evidence', () => { + it('reads current gates, course completions and intro without touching drafts or accepting unknown IDs', () => { + const device = fakeStorage(); + vi.stubGlobal('window', { localStorage: device }); + device.setItem( + 'chipsandcode.progress.v1', + JSON.stringify(['nand', 'not', 'not', 'missing', 15]), + ); + device.setItem('chipsandcode.part-one.progress.v1', JSON.stringify(['buses/not16', 'made/up'])); + device.setItem('chipsandcode.part-one.draft.buses/not16', 'unfinished HDL'); + expect(readLearningEvidence(['missions/xor'])).toEqual({ + verifiedTasks: ['missions/nand', 'missions/not', 'buses/not16', 'missions/xor'], + exploredSignals: true, + }); + expect(device.getItem('chipsandcode.part-one.draft.buses/not16')).toBe('unfinished HDL'); + }); + it('supports legacy gate progress without rewriting it; a malformed new store can recover from the legacy one', () => { + const device = fakeStorage(); + vi.stubGlobal('window', { localStorage: device }); + device.setItem('chipsandcode.signal-isles.progress.v1', '["not"]'); + expect(readLearningEvidence().verifiedTasks).toEqual(['missions/not']); + device.setItem('chipsandcode.progress.v1', '{'); + expect(readLearningEvidence().verifiedTasks).toEqual(['missions/not']); + expect(device.getItem('chipsandcode.progress.v1')).toBe('{'); + }); + it('handles corrupt or missing progress and explicit signal observations', () => { + const device = fakeStorage(); + vi.stubGlobal('window', { localStorage: device }); + device.setItem('chipsandcode.progress.v1', '{}'); + device.setItem('chipsandcode.part-one.progress.v1', '{'); + expect(readLearningEvidence()).toEqual({ verifiedTasks: [], exploredSignals: false }); + expect(readLearningEvidence([], true).exploredSignals).toBe(true); + device.setItem('chipsandcode.signal-intro.v1', 'complete'); + expect(readLearningEvidence().exploredSignals).toBe(true); + }); + it('does not infer skipped signal observations from a newly checked NAND', () => { + const device = fakeStorage(); + vi.stubGlobal('window', { localStorage: device }); + device.setItem('chipsandcode.progress.v1', '["nand"]'); + expect(readLearningEvidence().exploredSignals).toBe(true); + device.setItem('chipsandcode.signal-intro.v1', 'not-observed'); + expect(readLearningEvidence()).toEqual({ + verifiedTasks: ['missions/nand'], + exploredSignals: false, + }); + device.setItem('chipsandcode.signal-intro.v1', 'complete'); + expect(readLearningEvidence().exploredSignals).toBe(true); + }); + it('saves, reloads and resets choices without erasing work', () => { + const device = fakeStorage(); + vi.stubGlobal('window', { localStorage: device }); + device.setItem('chipsandcode.part-one.draft.memory/pc', 'my design'); + saveLearningChoices({ version: 1, topics: { gates: { feedback: 'too-easy', skipped: true } } }); + const saved = get(learningChoices); + learningChoices.set(emptyChoices()); + loadLearningChoices(); + expect(get(learningChoices)).toEqual(saved); + expect(get(choicesNotice)).toBe(''); + saveLearningChoices(emptyChoices()); + expect(device.getItem(learningChoicesKey)).toBe(JSON.stringify(emptyChoices())); + expect(device.getItem('chipsandcode.part-one.draft.memory/pc')).toBe('my design'); + }); + it('keeps preferences usable in memory when device storage is unavailable and reports reload limits', () => { + const dispatchEvent = vi.fn(); + vi.stubGlobal('window', { + dispatchEvent, + get localStorage() { + throw new Error('denied'); + }, + }); + saveLearningChoices({ version: 1, topics: { memory: { feedback: 'need-help' } } }); + loadLearningChoices(); + expect(get(learningChoices).topics.memory?.feedback).toBe('need-help'); + expect(dispatchEvent).toHaveBeenCalledOnce(); + expect(dispatchEvent.mock.calls[0][0].type).toBe('chipsandcode:learning-choices-changed'); + expect(dispatchEvent.mock.calls[0][0].detail.topics.memory.feedback).toBe('need-help'); + expect(get(choicesNotice)).toContain('Reloading may lose them'); + const device = fakeStorage(); + vi.stubGlobal('window', { localStorage: device }); + learningStorage.setItem(learningChoicesKey, JSON.stringify(emptyChoices())); + }); +}); diff --git a/src/lib/learning/adaptive/storage.ts b/src/lib/learning/adaptive/storage.ts new file mode 100644 index 0000000..2bb417b --- /dev/null +++ b/src/lib/learning/adaptive/storage.ts @@ -0,0 +1,90 @@ +import { writable } from 'svelte/store'; +import { courseProgressKey } from '#lib/course/data.js'; +import { emptyChoices, parseChoices, type LearningEvidence } from './model.js'; +import { learningTopics } from './topics.js'; + +type StorageAccess = Pick; +/** Retains current work through client-side navigation if device storage is denied/full. */ +export function createLearningStorage(access: () => StorageAccess) { + const session = new Map(); + const unsaved = new Set(); + return { + getItem(key: string): string | null { + if (unsaved.has(key)) return session.get(key) ?? null; + try { + const value = access().getItem(key); + if (value !== null) session.set(key, value); + else session.delete(key); + return value; + } catch { + return session.get(key) ?? null; + } + }, + setItem(key: string, value: string): void { + session.set(key, value); + unsaved.add(key); + access().setItem(key, value); + unsaved.delete(key); + }, + }; +} + +export const learningStorage = createLearningStorage(() => window.localStorage); +export const learningChoicesKey = 'chipsandcode.learning-choices.v1'; +export const learningChoices = writable(emptyChoices()); +export const choicesNotice = writable(''); + +export function loadLearningChoices() { + learningChoices.set(parseChoices(learningStorage.getItem(learningChoicesKey))); +} + +export function saveLearningChoices(choices: ReturnType) { + learningChoices.set(choices); + try { + learningStorage.setItem(learningChoicesKey, JSON.stringify(choices)); + choicesNotice.set(''); + } catch { + choicesNotice.set('Choices are kept for this visit only. Reloading may lose them.'); + } + // Optional consumers (the visual journey) can stay independent of this module. + // Include session state: rereading device storage would lose failed writes. + if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') { + window.dispatchEvent( + new CustomEvent('chipsandcode:learning-choices-changed', { detail: choices }), + ); + } +} + +function savedList(key: string): string[] | null { + try { + const value = JSON.parse(learningStorage.getItem(key) ?? 'null'); + return Array.isArray(value) + ? value.filter((item): item is string => typeof item === 'string') + : null; + } catch { + return null; + } +} + +export function readLearningEvidence( + current: string[] = [], + exploredSignals = false, +): LearningEvidence { + const missions = + savedList('chipsandcode.progress.v1') ?? + savedList('chipsandcode.signal-isles.progress.v1') ?? + []; + const course = savedList(courseProgressKey) ?? []; + const known = new Set(learningTopics.flatMap((topic) => topic.tasks.map((task) => task.id))); + const verifiedTasks = [ + ...new Set([...missions.map((id) => `missions/${id}`), ...course, ...current]), + ].filter((id) => id !== 'signals' && known.has(id)); + const signalObservation = learningStorage.getItem('chipsandcode.signal-intro.v1'); + return { + verifiedTasks, + exploredSignals: + exploredSignals || + signalObservation === 'complete' || + (signalObservation === null && missions.includes('nand')), + }; +} diff --git a/src/lib/learning/adaptive/topics.ts b/src/lib/learning/adaptive/topics.ts new file mode 100644 index 0000000..6fd4bfd --- /dev/null +++ b/src/lib/learning/adaptive/topics.ts @@ -0,0 +1,84 @@ +import { courseChapters, type ChapterId } from '#lib/course/data.js'; +import { missions } from '#lib/game/missions.js'; + +export type TopicId = 'signals' | 'gates' | 'routing' | ChapterId; +export interface LearningTask { + id: string; + title: string; + href: string; +} +export interface LearningTopic { + id: TopicId; + title: string; + description: string; + prerequisites: TopicId[]; + reference: string; + tasks: LearningTask[]; + challenge: string; +} + +const gateTasks = (ids: string[]): LearningTask[] => + missions + .filter((mission) => ids.includes(mission.id)) + .map((mission) => ({ + id: `missions/${mission.id}`, + title: `${mission.chip}: ${mission.title.toLowerCase()}`, + href: `/learn?mission=${mission.id}`, + })); + +const prerequisites: Record = { + buses: ['gates', 'routing'], + arithmetic: ['gates', 'buses'], + memory: ['routing', 'buses'], + 'machine-language': ['arithmetic', 'memory'], + architecture: ['arithmetic', 'memory', 'machine-language'], + assembler: ['machine-language'], +}; + +export const learningTopics: LearningTopic[] = [ + { + id: 'signals', + title: 'Signals & first gates', + description: 'Two states, NOT, and AND. Start here if this is new.', + prerequisites: [], + reference: '/learn/reference/boolean-logic', + tasks: [{ id: 'signals', title: 'Explore a signal', href: '/learn?topic=signals' }], + challenge: 'signals', + }, + { + id: 'gates', + title: 'Build logic gates', + description: 'NAND, inversion, conditions, and comparing bits.', + prerequisites: ['signals'], + reference: '/learn/reference/boolean-logic/background', + tasks: gateTasks(['nand', 'not', 'and', 'or', 'xor']), + challenge: 'missions/xor', + }, + { + id: 'routing', + title: 'Select & route', + description: 'Use a control bit to choose where data goes.', + prerequisites: ['gates'], + reference: '/learn/reference/boolean-logic/project', + tasks: gateTasks(['mux', 'dmux']), + challenge: 'missions/dmux', + }, + ...courseChapters.map((chapter): LearningTopic => ({ + id: chapter.id, + title: chapter.title, + description: chapter.description, + prerequisites: prerequisites[chapter.id], + reference: chapter.reference, + tasks: chapter.tasks.map((task) => ({ + id: `${chapter.id}/${task.id}`, + title: task.title, + href: `/learn/path/${chapter.id}?task=${task.id}`, + })), + challenge: `${chapter.id}/${chapter.tasks.at(-1)!.id}`, + })), +]; + +export const topicById = (id: TopicId): LearningTopic => + learningTopics.find((topic) => topic.id === id)!; +export const topicForMission = (id: string): TopicId => + id === 'mux' || id === 'dmux' ? 'routing' : 'gates';