diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4d8bee0..d566a44 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -3,40 +3,15 @@ name: CI
on:
push:
branches: [main]
+ paths:
+ - 'v2/**'
+ - '.github/workflows/ci.yml'
pull_request:
+ paths:
+ - 'v2/**'
+ - '.github/workflows/ci.yml'
jobs:
- check:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v4
-
- - uses: actions/setup-node@v4
- with:
- node-version: 20
- cache: npm
-
- - name: Install dependencies
- run: npm ci
-
- - name: Build bundle
- run: npm run build
-
- - name: Lint
- run: npm run lint
-
- - name: Check formatting
- run: npm run format:check
-
- - name: Verify committed bundle is up to date
- run: git diff --exit-code -- index.html
-
- - name: Install Playwright browser
- run: npx playwright install --with-deps chromium
-
- - name: Test
- run: npm test
-
check-v2:
runs-on: ubuntu-latest
defaults:
@@ -47,7 +22,8 @@ jobs:
- uses: actions/setup-node@v4
with:
- node-version: 20
+ # 22: db-sql.test.ts runs the real SQL through node:sqlite (skipped on older Node).
+ node-version: 22
cache: npm
cache-dependency-path: v2/package-lock.json
@@ -62,3 +38,7 @@ jobs:
- name: Build
run: npm run build
+
+ - name: Verify committed Reader template is up to date
+ # Shared .html files are built from this generated bundle; a stale one ships old behavior.
+ run: npm run build:reader && git diff --exit-code -- src/lib/generated/reader-template.ts
diff --git a/.github/workflows/v1.yml b/.github/workflows/v1.yml
new file mode 100644
index 0000000..8fd4744
--- /dev/null
+++ b/.github/workflows/v1.yml
@@ -0,0 +1,72 @@
+name: CI v1
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - 'src/**'
+ - 'scripts/**'
+ - 'tests/**'
+ - 'index.html'
+ - 'index.template.html'
+ - 'package.json'
+ - 'package-lock.json'
+ - 'playwright.config.mjs'
+ - 'eslint.config.mjs'
+ - '.github/workflows/v1.yml'
+ pull_request:
+ paths:
+ - 'src/**'
+ - 'scripts/**'
+ - 'tests/**'
+ - 'index.html'
+ - 'index.template.html'
+ - 'package.json'
+ - 'package-lock.json'
+ - 'playwright.config.mjs'
+ - 'eslint.config.mjs'
+ - '.github/workflows/v1.yml'
+
+jobs:
+ check:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ cache: npm
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Build bundle
+ run: npm run build
+
+ - name: Lint
+ run: npm run lint
+
+ - name: Check formatting
+ run: npm run format:check
+
+ - name: Verify committed bundle is up to date
+ run: git diff --exit-code -- index.html
+
+ - name: Cache Playwright browser
+ id: playwright-cache
+ uses: actions/cache@v4
+ with:
+ path: ~/.cache/ms-playwright
+ key: playwright-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
+
+ - name: Install Playwright browser
+ if: steps.playwright-cache.outputs.cache-hit != 'true'
+ run: npx playwright install --with-deps chromium
+
+ - name: Install Playwright system deps
+ if: steps.playwright-cache.outputs.cache-hit == 'true'
+ run: npx playwright install-deps chromium
+
+ - name: Test
+ run: npm test
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9a813a2..faf1163 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,83 @@
Notable changes, following [Keep a Changelog](https://keepachangelog.com/). The notebook JSON
interchange format is versioned separately and migrated on import.
+## [0.3.0] — 2026-10-21
+
+The living handout: notebooks an LLM can draft, a teacher can trust, and a student can keep — plus a
+keyboard-first Study, zoom, the Cyberpunk theme and a much larger test suite.
+
+- **Shared files remember progress.** A shared Reader `.html` keeps each reader's answers, ticks,
+ practice streaks and notes in that browser, keyed by card content so an author's later fixes
+ keep everyone else's progress. "Reset my progress" starts over.
+- **Results for the teacher.** "My results" in the Reader summarizes progress per section and
+ graded answers; copy it or download it as JSON. Nothing leaves the device otherwise.
+- **`problem` slot (12th).** Randomized numeric practice: params drawn on a step grid each attempt,
+ the typed answer checked against an expression with a tolerance, "New numbers", a worked
+ explanation, done after `need` correct answers. Strict answer parsing; mobile keypad friendly.
+- **Guided card types.** Guided Explore (predict → explore with sliders and a chart → explain),
+ Worked Example (steps with self-explanation fading into practice) and Practice Set. Existing
+ installs receive new built-ins once through a preferences ledger; deleted ones stay deleted. Predictions with no answer key
+ are never marked wrong.
+- **Step-by-step** slot effect in the Factory: hide a slot until the earlier tasks on its card
+ are done.
+- **New notebook From AI.** A complete prompt for any chat AI (format, slot catalog, expression
+ grammar, card-scope rule, pedagogy); paste the reply, see problems with where / what / how to
+ fix and a copyable fix request, then create. Cards arrive as **drafts** to review; Share warns
+ while drafts remain.
+- **Published format.** JSON Schema 2020-12 (`v2/src/lib/schema/notebook.schema.json`) and
+ [`docs/FORMAT.md`](docs/FORMAT.md). Rejected imports show a readable report instead of a toast.
+- **Durability.** Saves are serialized and atomic (one batch per save), flushed on blur, window
+ close and Cmd+Q, and never written before startup loading finishes. Fixed: edits lost when
+ switching notebooks, the demo notebook overwriting a stored one at startup, interleaved saves
+ failing silently, card widths snapping back to full width after a relaunch, section resets
+ coming back after a restart.
+- **Version history.** Automatic snapshots (at most every 10 minutes, only on change), "Save
+ version now", and Restore (undoable). SQLite migration v6.
+- **Shared files on phones and offline.** Under 760 px the Reader starts with its panel collapsed
+ and cards go full width; the file makes no third-party request (the web-font import is
+ stripped at build, and the build fails on any external reference); a damaged file shows a
+ readable message instead of a blank page; the embedded payload escapes every `<`.
+- **Safer sharing.** Share is refused while the notebook fails validation (the report lists
+ why), so students never get a broken file; Export still writes the backup and then lists what
+ would stop it re-importing. Progress keys are a hash of a per-install id and the notebook id,
+ so two authors' files never share students' progress. Imported text is made well-formed
+ before it reaches SQLite.
+- **Examples.** `docs/examples/practice-lesson.json` (percent change) shows every new piece.
+- CI runs the v2 job on Node 22 (real-SQLite tests) and fails on a stale Reader template.
+- **Keyboard-first Study** — a whole study session runs from the keyboard: `j`/`k` (or the arrow
+ keys) move a focus ring from card to card, space or `f` flips, `1`-`9` pick an answer option,
+ `Enter` submits, `x` ticks the next checklist item, and `Escape` clears the focus. `?` opens a
+ shortcut overlay and Study carries a one-line hint under the notebook. The same bindings work
+ in a shared Reader file.
+- **Cyberpunk (dark green) theme** — phosphor green on near-black with a fixed grid, scanlines,
+ neon card glow, hover lift, and mono uppercase headers. Bold, italic, inline code and
+ strikethrough take accent colors in Study text under this theme.
+- **Syntax-highlighted code slots** — Python and JavaScript keywords, strings, numbers,
+ comments and callables get distinct colors via a dependency-free tokenizer; other languages
+ render plain.
+- **Zoom** — `Cmd/Ctrl` `+`, `-`, `0` scale the whole app between 50% and 200%.
+- **Three more builtin card types** — Cheatsheet, Iron Butterfly (a payoff explorer whose
+ breakevens and max profit and loss derive from three sliders), and Code Card, each with
+ accent varieties.
+- **Examples** — `docs/examples/grand-tour.json` exercises every slot type in one tutorial;
+ `docs/examples/quant-terminal.json` rebuilds the quant-prep-terminal cockpit with chapter
+ dividers, tagged flashcards, cheatsheets, a lab section, and per-section service bars.
+- **Styled DMG** — the disk image opens as a proper installer window with a
+ drag-to-Applications layout; `docs/install-macos.md` documents the build.
+- **Simulation test tier** — seeded generative suites cover variable-graph resolution,
+ interchange round-trips, progress semantics, and expression evaluation.
+- **Card type binding survives export** — a card stamped from a Factory type now carries its
+ `typeId` through JSON export and import, so the coverage matrix keeps its product dimension on
+ a round trip. A recipient without that type reads the card as untyped.
+- **Design tokens** — spacing, type, radius and motion tokens with a written governance rule;
+ components consolidated onto them with zero visual change.
+- **Fixed: Edit-in-Factory on typed cards** — the 🏭 action on a card stamped from a card type
+ silently did nothing instead of forking the type into a Factory bench.
+- **Hardened test suite** — the SQLite persistence layer, every example notebook, the Iron
+ Butterfly payoff math, undo restoration of card types and Factory benches, the shortcut
+ overlay, Reader authoring after Remix, and every slot component are now under test; the
+ suite is 2718 tests across 204 files, plus real-SQLite tests of every migration.
+
## [0.2.0] — 2026-07-23
NoteBuilder becomes a native macOS desktop app (`v2/`): Svelte 5 + TypeScript + Tauri 2, backed by
@@ -12,8 +89,8 @@ SQLite. Rebuilds the full prototype experience on a typed engine and moves it fo
card types, stamp independent copies into notebooks.
- **11 slots** — text, list, code, table, image, choice, slider, text input, compute, chart,
progress — composed on a 12-column grid with per-slot resize and fusing.
-- **Card-scoped variables** with a topologically sorted dependency graph; cycles and missing
- writers are rejected at import.
+- **Card-scoped variables** with a topologically sorted dependency graph; cycles are rejected
+ at import and missing writers load with a warning.
- **Hard Edit/Study separation** (`Cmd+Enter`); Study is the live, interactive render.
- **Three state layers**: document (persists + exports), reader state (persists locally, never
exports), session (transient).
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..731141d
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,83 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
+
+We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
+
+## Our Standards
+
+Examples of behavior that contributes to a positive environment for our community include:
+
+* Demonstrating empathy and kindness toward other people
+* Being respectful of differing opinions, viewpoints, and experiences
+* Giving and gracefully accepting constructive feedback
+* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
+* Focusing on what is best not just for us as individuals, but for the overall community
+
+Examples of unacceptable behavior include:
+
+* The use of sexualized language or imagery, and sexual attention or advances of any kind
+* Trolling, insulting or derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or email address, without their explicit permission
+* Other conduct which could reasonably be considered inappropriate in a professional setting
+
+## Enforcement Responsibilities
+
+Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
+
+Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at the maintainer's GitHub contact (@YuZh98, https://github.com/YuZh98). All complaints will be reviewed and investigated promptly and fairly.
+
+All community leaders are obligated to respect the privacy and security of the reporter of any incident.
+
+## Enforcement Guidelines
+
+Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
+
+### 1. Correction
+
+**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
+
+**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
+
+### 2. Warning
+
+**Community Impact**: A violation through a single incident or series of actions.
+
+**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
+
+### 3. Temporary Ban
+
+**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
+
+**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
+
+### 4. Permanent Ban
+
+**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
+
+**Consequence**: A permanent ban from any sort of public interaction within the community.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
+
+Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
+
+For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
+
+[homepage]: https://www.contributor-covenant.org
+[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
+[Mozilla CoC]: https://github.com/mozilla/diversity
+[FAQ]: https://www.contributor-covenant.org/faq
+[translations]: https://www.contributor-covenant.org/translations
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 63d3b2c..b6f2210 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,5 +1,16 @@
# Contributing to NoteBuilder
+## Scope
+
+NoteBuilder is one repo, two apps: the **v1 prototype** at the root (frozen, bug fixes only) and the
+**v2 product** in `v2/` (Svelte 5 + TypeScript + Tauri 2, active development).
+
+In scope: v2 app quality, interchange/Reader fidelity, tests, and docs accuracy.
+
+Out of scope: anything that adds a network call, telemetry, or an account system (NoteBuilder is
+local-first and stays that way); changes to the v1 root beyond bug fixes; features not grounded in an
+open issue.
+
Thanks for helping. Active development happens in **`v2/`** (Svelte 5 + TypeScript + Tauri 2); the
repository root is the legacy single-file prototype, kept building but not evolving.
@@ -8,7 +19,7 @@ repository root is the legacy single-file prototype, kept building but not evolv
```bash
cd v2
npm install
-npm run dev # browser dev server (persistence no-ops; demo notebook loads)
+npm run dev # browser dev server (persistence no-ops; demo notebook loads); Node 22+
npm run tauri dev # the real desktop app — needs Rust + Xcode CLT
```
@@ -18,21 +29,24 @@ Gates — keep all green before and after every change:
npm test # Vitest unit suite
npm run check # svelte-check, TypeScript strict
npm run build # Vite production build
-npm run build:reader # only when the Reader render path changes — commit the regenerated template
+npm run build:reader # when the Reader render path changes — commit the regenerated template (CI fails on a stale one)
```
## The shape of v2
-- Architecture map: Part B of [`docs/CODE-MAP.md`](docs/CODE-MAP.md). Product spec:
- [`docs/spec/v2-spec.md`](docs/spec/v2-spec.md).
+- Architecture map: Part B of [`docs/CODE-MAP.md`](docs/CODE-MAP.md).
- **Invariants** (don't break): variables are card-scoped, never cross a card boundary; three state
layers (document persists + exports · reader state persists locally, never exports · session is
transient); slot structure is sealed outside the Factory; every drag rides the one pointer engine
- in `v2/src/lib/drag/` — no native HTML5 drag; no `eval` on user content, escape-first before any
+ in `v2/src/lib/drag/` — no native HTML5 drag outside the Factory inventory chips; no `eval` on
+ user content, escape-first before any
`{@html}`; every document edit is undoable.
- **Migrations always.** A change to the SQLite shape ships a migration in
`v2/src-tauri/src/lib.rs`; a change to the JSON interchange shape bumps its schema version and
ships an import migration. Old saves and old exports must still load.
+- **The interchange format is published.** A change to it updates `v2/src/lib/schema/notebook.schema.json`,
+ `v2/src/lib/slot-catalog.ts` (for a new slot type) and `docs/FORMAT.md`; `schema-sync.test.ts` and
+ `ai-prompt.test.ts` name whatever is missing.
- **Behavior changes are test-driven** — add a failing test, then make it pass. Verify UI and
interaction changes by running the app, not by reading the diff.
diff --git a/README.md b/README.md
index c5150bb..f7e8bd3 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,7 @@
# NoteBuilder
[](https://github.com/YuZh98/notebuilder/actions/workflows/ci.yml)
-[](v2/)
+[](v2/)
[](v2/package.json)
[](v2/src-tauri/)
[](v2/)
@@ -9,6 +9,8 @@
**Study material that does something. Build notebooks from reactive cards, drill them in Study mode, and hand them to anyone as a single offline file.**
+Drag a slider, and the formula, the prose, and the chart in that card recompute together; export the notebook and those same live cards keep running inside one offline `.html` file, where nothing the reader answers ever comes back to you.
+
NoteBuilder is a local-first macOS desktop app. Your notebooks live in a local SQLite database. No account, no cloud, no backend.

@@ -19,18 +21,19 @@ NoteBuilder is a local-first macOS desktop app. Your notebooks live in a local S
Anyone who makes study material and wants it to be more than frozen text:
-- **Students and self-learners** who want flashcards that flip, quizzes that check themselves, and a progress meter that fills as *they* finish cards.
-- **Teachers and tutors** who want to send one file that works in any browser, offline, with nothing to install on the other end.
+- **Students and self-learners** who want flashcards that flip, quizzes that check themselves, practice problems with fresh numbers every attempt, and a progress meter that fills as *they* finish cards.
+- **Teachers and tutors** who want to send one file that works in any browser, offline, with nothing to install on the other end, that remembers each student's progress and hands back a results summary.
- **Anyone explaining something quantitative.** A slider, a formula, and a chart in one card wire together and react live. Drag the slider, watch the curve move.
## Why not a document?
| Problem | Static notes | NoteBuilder |
| --- | --- | --- |
-| Self-testing | Re-reading, highlighting | Flashcards flip, quizzes grade themselves, checklists tick |
+| Self-testing | Re-reading, highlighting | Flashcards flip, quizzes grade themselves, practice problems redraw their numbers, checklists tick |
| Quantitative intuition | A pasted screenshot of a plot | Slider drives formula drives chart, live, per card |
| Knowing where you stand | Gut feeling | Per-reader progress meters count what you have actually finished |
-| Sharing | Recipient needs your app or an account | One self-contained `.html`, opens offline in any browser |
+| Sharing | Recipient needs your app or an account | One self-contained `.html`, opens offline in any browser, remembers the reader's progress |
+| Authoring cost | Hours per lesson | Any chat AI drafts it from the built-in prompt; you review the drafts |
| Coverage | Scroll and hope | Tag every card, read the coverage matrix |
## Quick start
@@ -46,13 +49,15 @@ npm run tauri dev
That is the full desktop app, with SQLite persistence and native print. `npm run tauri build` produces an app bundle. For UI work without the native shell, `npm run dev` serves the app in a browser with a demo notebook (persistence no-ops there).
-First thing to try: import an example from [`docs/examples/`](docs/examples/) with the **⤒** button and hit **Study**.
+To package that build as a macOS disk image and install it like any other app, follow [`docs/install-macos.md`](docs/install-macos.md).
+
+First thing to try: import [`grand-tour.json`](docs/examples/grand-tour.json) with the **⤒** button and hit **Study**. It is a rocket mission that puts every slot type to work in one notebook. For a short lesson built from the guided card types, import [`practice-lesson.json`](docs/examples/practice-lesson.json). The rest of the examples live in [`docs/examples/`](docs/examples/). Then **+ → From AI…** to have your favourite chat AI draft a notebook on any topic.
## How it works
### Cards are built from slots
-A card is a small stack of primitives arranged on a 12-column grid: text, slider, formula, chart, choice, table, code, image, checklist, progress. Slots in the same card share variables and react to each other. Variables are strictly card-scoped; dependencies resolve by topological sort, and cycles or missing writers are caught at import. Nothing leaks across cards.
+A card is a small stack of primitives arranged on a 12-column grid: text, slider, formula, chart, choice, practice problem, table, code, image, checklist, text answer, progress. Slots in the same card share variables and react to each other. Variables are strictly card-scoped; dependencies resolve by topological sort, and cycles or missing writers are caught at import. Nothing leaks across cards.
### Edit and Study are hard-separated
@@ -62,29 +67,62 @@ Edit shows structure and configuration. Study *is* the rendered, interactive res
*The same notebook in Edit mode: every slot becomes its configuration fields, and the sidebar holds tags, section operations, and the card-type store.*
+### Have any AI draft it, then review
+
+**+ → From AI…** writes a complete prompt for ChatGPT, Claude, Gemini or any other chat AI: the format, every slot with an example, the formula grammar and the card-scope rule. Paste the reply back; NoteBuilder checks it (code fences and chatter are fine), lists any problems with where, what and how to fix, and gives you a fix request to paste back to the AI. Every card it creates is marked **draft** until you review it, and Share reminds you while drafts remain. No AI runs inside the app, and the format is published: [`docs/FORMAT.md`](docs/FORMAT.md).
+
### The Factory stamps card types
-Design a slot arrangement once, seal it as a card type, then stamp independent copies into any notebook. Stamped cards are copies, not references, so editing a notebook never mutates your library.
+Design a slot arrangement once, seal it as a card type, then stamp independent copies into any notebook. Stamped cards are copies, not references, so editing a notebook never mutates your library. Built-ins include research-backed patterns: **Guided Explore** (predict, explore with sliders and a chart, then explain), **Worked Example** (steps with self-explanation, fading into practice) and **Practice Set**.
### Sharing is a file
-Export a notebook as JSON for another NoteBuilder, or as a self-contained Reader `.html` that opens in any browser, offline. The recipient reads and interacts; their quiz answers and progress stay on their machine. A shared file carries only that notebook, never the rest of your library.
+Export a notebook as JSON for another NoteBuilder, or as a self-contained Reader `.html` that opens in any browser, offline. The recipient reads and interacts; their answers and progress are saved in their own browser and come back when they reopen the file. **My results** gives them a summary to copy or download for you. Nothing is sent anywhere. A shared file carries only that notebook, never the rest of your library.
-
+### The two ends of a notebook
-*A shared `.html` open in a plain browser: authoring chrome is gone, a single **Remix** unlocks editing, and the quiz is unanswered because the reader's state is their own.*
+|  |  |
+| --- | --- |
+| *Edit mode: every slot becomes its configuration fields, and the sidebar holds tags, section operations, and the card-type store.* | *The shared `.html` in a plain browser: authoring chrome is gone, a single **Remix** unlocks editing, and the quiz is unanswered because the reader's state is their own.* |
### And the comforts
-Full undo/redo, drag-and-drop everything (cards, slots, tags, services), tags with a coverage matrix, themes, GFM markdown with `$KaTeX$` math, native print.
+Full undo/redo, version history with restore, saves that survive a crash or a Cmd+Q, drag-and-drop everything (cards, slots, tags, services), tags with a coverage matrix, themes, GFM markdown with `$KaTeX$` math, native print. A whole Study session runs from the keyboard (`j`/`k` to move, space to flip, `1`-`9` to answer, `x` to tick), in the app and in a shared file alike, with `?` listing every shortcut.

*The [`regression-drill`](docs/examples/regression-drill.json) example mid-study: the quiz has been answered and explains itself, two checklist items are done, and the notebook-wide progress meter sits at 2/4.*
+### Eight themes, one picker
+
+Every screenshot above uses the default dark theme. Seven more ship with the app, switched from the palette button in the top bar; here are four of them on the same demo notebook.
+
+|  |  |
+| --- | --- |
+| *Tomoé: stationery. Cream paper, serif headings, ruled margins on every card.* | *Sketch: graph paper, wobbly ink frames, marker lettering.* |
+|  |  |
+| *Aurora: fantasy night sky, cards that glow at the edges.* | *Cyberpunk: amber wireframes and uppercase everything.* |
+
+## Where your data lives
+
+One SQLite file in your own account, written by the app itself:
+
+```text
+~/Library/Application Support/com.notebuilder.app/
+└── notebuilder.db notebooks, card types, tags, reader state, preferences
+```
+
+SQLite keeps its own `notebuilder.db-wal` and `notebuilder.db-shm` companion files next to it, so the folder shows three names for one database. Delete the database and NoteBuilder starts empty. Everything else NoteBuilder writes is a file you asked it to export, saved where you pointed the dialog. Run `npm run dev` in a browser instead of the desktop app and there is no database at all; the demo notebook lives only in memory.
+
## Built to last
-1202 tests across 87 files, TypeScript strict, svelte-check clean, CI on every push. Invariants are enforced by tests, not convention.
+2718 tests across 204 files, TypeScript strict, svelte-check clean, CI on every push. Invariants are enforced by tests, not convention.
+
+The long-form guides:
+
+- [Architecture](docs/architecture.md): the v2 layer split, where your data lives at runtime, and the two build targets.
+- [UI design system](docs/ui-design-system.md): the `app.css` design tokens, theming, and the rule that keeps them authoritative.
+- [Notebook format](docs/FORMAT.md): the version 2 notebook JSON, slot by slot, its published JSON Schema, and the rules an AI author must follow.
Engineering deep-dive
@@ -93,23 +131,24 @@ Full undo/redo, drag-and-drop everything (cards, slots, tags, services), tags wi
```text
v2/src/lib/slots/ slot primitives: one Edit + one Study component per slot, one contract
-v2/src/lib/drag/ a single pointer-based drag engine; no native HTML5 drag anywhere
+v2/src/lib/drag/ a single pointer-based drag engine for notebook and study surfaces; the Factory inventory chips still use native HTML5 drag
v2/src/lib/ variable graph, history, tags, import/export, themes, markdown
v2/src-tauri/ Rust shell: SQLite (migrations in lib.rs), native print, dialogs
```
- **State layers.** Document state persists and exports; reader state (answers, ticks, progress) persists locally and never exports; session state is transient. The separation is what makes a shared file safe to open.
- **Migrations always.** A persisted-shape change ships a SQLite migration; an interchange change bumps the JSON schema version and ships an import migration. Old files keep loading.
+- **Atomic, serialized saves.** Every database access rides one queue; each save is a single transaction batch; nothing is written before startup loading succeeds; the real SQL and every migration are tested against SQLite.
- **Security posture.** No `eval` on user content; formulas run through a small own-keys-only expression evaluator. All user text is escaped before markdown or KaTeX markup is applied. Parameterized SQL throughout. See [SECURITY.md](SECURITY.md).
-- **Guard tests.** Source-level sweep tests lock invariants: no props mutation in Edit components, no native drag, Reader/App prop parity. Regressions fail loudly.
+- **Guard tests.** Source-level sweep tests lock invariants: no props mutation in Edit components, no native drag outside the Factory inventory chips, Reader/App prop parity. Regressions fail loudly.
-Architecture map: [`docs/CODE-MAP.md`](docs/CODE-MAP.md). Product spec: [`docs/spec/v2-spec.md`](docs/spec/v2-spec.md). Contributing: [`CONTRIBUTING.md`](CONTRIBUTING.md).
+Architecture map: [`docs/CODE-MAP.md`](docs/CODE-MAP.md). Notebook format: [`docs/FORMAT.md`](docs/FORMAT.md). Contributing: [`CONTRIBUTING.md`](CONTRIBUTING.md).
## The original prototype
-The repository root holds the first NoteBuilder: a single-file web app (vanilla JS, localStorage, the whole product in one `index.html`) that proved the slot/card model and the one-file sharing story. Its Playwright suite still gates CI, but it is legacy. New work happens in [`v2/`](v2/).
+The repository root holds the first NoteBuilder: a single-file web app (vanilla JS, localStorage, the whole product in one `index.html`) that proved the slot/card model and the one-file sharing story. Its Playwright suite still gates CI whenever the root app changes, but it is legacy. New work happens in [`v2/`](v2/).
## License
diff --git a/SECURITY.md b/SECURITY.md
index 8d66755..20b699d 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -7,7 +7,8 @@ Please do not file public issues for vulnerabilities. We aim to acknowledge with
## Threat model
-NoteBuilder is local-first: there is no server, no account, and no network call at runtime. The
+NoteBuilder is local-first: there is no server and no account. The only runtime network requests
+are theme webfonts and remote images a notebook may embed. The
desktop app (`v2/`) persists to a local SQLite database; the legacy web prototype (repository root)
persists to `localStorage`. The main attack surface in both is **rendering untrusted notebook
content** — an imported JSON file or a shared Reader `.html` may contain attacker-authored text and
@@ -21,7 +22,8 @@ Mitigations in the code:
- **Escape-first rendering.** All user text is HTML-escaped before markdown/KaTeX markup is applied
and before it reaches any `{@html}` / `innerHTML` sink (`v2/src/lib/markdown.ts`).
- **No remote code.** KaTeX is bundled at build time; rendered markdown links carry
- `rel="noopener noreferrer"`, and notebook content cannot pull in remote assets.
+ `rel="noopener noreferrer"`. Notebook images may load from remote URLs, but nothing remote
+ executes.
- **Parameterized SQL** for all database access; ids are sanitized on import.
- **Slim export.** A shared file embeds only the exported notebook — never other notebooks, the
card-type library, or the reader's local state.
diff --git a/docs/CODE-MAP.md b/docs/CODE-MAP.md
index 29e9497..399e25c 100644
--- a/docs/CODE-MAP.md
+++ b/docs/CODE-MAP.md
@@ -218,48 +218,81 @@ import time.
v2/
src/
main.ts Svelte mount
- App.svelte Root component (32KB): mode/place routing, notebook CRUD, effects
+ App.svelte Root component (~48KB): mode/place routing, notebook CRUD, effects
app.css Global stylesheet
lib/
types.ts Core type definitions (Slot, Card, Section, Notebook — incl. Notebook.cats)
card-types.ts CardType, stampCard, placeType, builtinCardTypes
bench.svelte.ts Factory workbench state (Svelte 5 $state rune)
- session.svelte.ts Study session state (shuffle, search, archive toggle, live control values)
+ seal.ts Seal-modal draft: bench → CardType metadata capture
+ session.svelte.ts Study session state (shuffle, search, archive toggle, collapse, live values)
notebook-ops.ts CRUD ops: createNotebook, addSection, addChapter, duplicateCard, etc.
tags.ts The ONE tag write path: apply/remove/rename/delete/create/reorder + cats upkeep
coverage-matrix.ts Matrix axes, cell matching, same 3-axis model as v1
services.ts ServiceBar: SERVICE_ORDER, svcBarItems, reorderSvc, search
service-ops.ts Mutation helpers: toggleService, resetSection, flipAllSection
- json-io.ts Export/import (SCHEMA_VERSION 2) + validateNotebookJSON + graph validation
+ json-io.ts Export/import (SCHEMA_VERSION 2) + validateNotebook / validateNotebookIssues
+ (structured {code, path, message}) + graph validation
html-io.ts Shared-.html payload inject/extract (notebook-source script tag)
- share.ts Tauri file dialog wrappers for import/export
- db.ts SQLite layer (saveNotebook, loadNotebook, reader state, prefs)
+ share.ts Tauri file dialog wrappers for import/export; buildShareHtml (payload docId)
+ db.ts SQLite layer: ONE serialized queue (coalescing keys), atomic single-execute
+ batches (exported SQL constants), onDbError, dbIdle; notebooks, reader
+ state, prefs, card types, annotations, snapshots
+ autosave.ts Hydration-gated debounced channels (notebook / reader / factory); flush
+ snapshots.ts Version-history policy: contentHash, shouldAutoSnapshot, retention pruneIds
+ versions.ts Version keeper: when to snapshot (auto, manual, before-restore)
+ reader-store.ts Shared-Reader progress in localStorage: stable content keys, quota eviction
+ results.ts Student results summary (progress + graded score() tallies) + text form
+ drafts.ts AI drafts: markAllDraft, nextDraft, clear one/all (local authoring state)
+ rng.ts mulberry32 + step-grid draws for reproducible practice numbers
+ numeric-input.ts Strict parser for typed numeric answers (never evalExpr on input)
+ schema/ notebook.schema.json (published JSON Schema 2020-12) + schema.ts readers
+ slot-catalog.ts One entry per slot type for the AI kit (purpose + example; props from schema)
+ ai-prompt.ts buildAiPrompt: the "From AI" prompt (format, catalog, grammar, pedagogy)
+ import-hints.ts checkNotebookText: fence/prose-tolerant parse, own line/col, hintFor, fix request
+ clipboard.ts copyText with execCommand fallback
+ install-id.ts Per-install random id (pref install_id); shareDocId hashes it with the notebook id
+ well-formed.ts Replace lone UTF-16 surrogates (imports) so SQLite never stores invalid UTF-8
+ reader-boot.ts Shared-file boot: extract → validate → import; a readable error page on failure
db-map.ts Notebook ↔ relational row mapping
variable-graph.ts Topological sort, cycle detection, scope resolution
card-scope.ts Build scope from a card's slots (same invariant: card-scoped)
- expr.ts Safe expression evaluator (no eval, variable whitelist)
+ expr.ts Safe expression evaluator (no eval, variable whitelist); parseExpr (throws)
markdown.ts Markdown → HTML (inline + block) with KaTeX
mdbar.ts Formatting toolbar actions
verbs.ts Reveal/glow/emphasis evaluation
themes.ts Theme registry
toast.svelte.ts Notification state
uid.ts ID generator
- debounce.ts Utility
+ debounce.ts debounce with flush / cancel / pending
annotations.ts Reader annotations (local-only)
+ presentation.ts Volatile presentation keys stripped from persisted reader state
+ demo.ts First-run seed notebook
history.svelte.ts Undo/redo stacks: pushHistory/pushSnapshot/beginEdit (focus-coalesced)
history-focus.ts data-history="edit" input coalescing — one undo entry per edit session
+ keyboard.ts Pure key dispatcher: the v1 shortcut map as a decision over a KeyCtx
+ study-keys.ts Study cursor: focus order, stepping, per-key reader-state effect
+ card-reveal.ts Scroll a just-placed card into view and flash the study ring on it
+ modal-inert.ts `inert` on the shell behind a modal overlay, so Tab cannot reach it
+ zoom.ts App zoom factor (Cmd/Ctrl +/-/0) + viewport↔zoom-space conversion
+ print.ts Print: native print_page on desktop, window.print() in browser
+ visible-cards.ts The one render order: sections/cards the Stage shows (and the cursor walks)
shell.ts Shell/container styling logic
slot-contract.ts SlotType interface: create, variables, evaluate, isDone, stateLayer, render*
progress.ts Notebook/section/chapter progress computation
card-done.ts Per-card completion logic
var-colors.ts Variable key → color assignment
+ sim-notebook.ts Seeded notebook generator + canonical form (sim test tier)
+ sim-rng.ts Deterministic RNG + seed sweep for the sim suites
+ test-utils.ts Shared test scaffolding (pev, stubRect)
- slots/ Per-slot-type modules (11 types):
+ slots/ Per-slot-type modules (12 types):
registry.ts Slot type registry (registerSlot / getSlot / allSlots)
identifiers.ts Key naming helpers
text.ts + TextEdit.svelte + TextStudy.svelte
slider.ts + SliderEdit.svelte + SliderStudy.svelte
compute.ts + ComputeEdit.svelte + ComputeStudy.svelte (+ .test.ts)
+ problem.ts + ProblemEdit.svelte + ProblemStudy.svelte — randomized numeric practice
chart.ts + ChartEdit.svelte + ChartStudy.svelte + plot.ts
choice.ts + ChoiceEdit.svelte + ChoiceStudy.svelte (+ .test.ts)
list.ts + ListEdit.svelte + ListStudy.svelte (+ .test.ts)
@@ -283,6 +316,7 @@ v2/
CoverageMatrix.svelte 3-axis matrix grid (same v1 concept)
ServiceBar.svelte Per-section feature/action bar
SealModal.svelte Seal product: name, icon, store, varieties
+ ShortcutHelp.svelte Study shortcut overlay (toggled by ?)
ProductDetail.svelte Product info + fork/place
StoreLane.svelte Store shelf in sidebar
SlotConfig.svelte Slot field editor + verb builder
@@ -292,6 +326,11 @@ v2/
Toast.svelte Notifications
CardNotes.svelte Reader annotations
Reader.svelte Shared-.html shell — hand-mirrors the App shell (see DEBT P1 + drift guard)
+ ResultsModal.svelte Reader "My results": copy / download JSON
+ FromAiModal.svelte New notebook from AI: copy prompt → paste reply → check → create
+ ImportReport.svelte Import problems with where / what / fix + "Copy fix request"
+ DraftsBar.svelte "N drafts to review · Next · Mark all reviewed" (SideBar)
+ VersionsPanel.svelte Version history list, Save version now, Restore (SideBar, Tauri)
drag/ Drag-and-drop engine:
engine.ts Core pointer engine (startDrag, FLIP animation)
@@ -334,20 +373,26 @@ CardType = { id, name, description?, verbs?, slots: SlotTemplate[], back?, accen
store?, varieties? }
```
-**SQLite schema** (5 migrations in `lib.rs`):
+**SQLite schema** (6 migrations in `lib.rs`; never edit an applied one):
- `notebooks` (id, name, created_at, updated_at, data JSON)
- `sections` (id, notebook_id FK, name, position, data JSON)
- `cards` (id, section_id FK, type_id, position, data JSON)
- `reader_state` (card_id, slot_id, data JSON) — local progress, never exported
- `annotations` (id, card_id, kind, body, created_at) — local-only
- `card_types` (id, name, data JSON, created_at) — sealed products
-- `preferences` (key, value) — theme, etc.
+- `preferences` (key, value) — theme, `builtin_seeded`, etc.
+- `snapshots` (id, notebook_id, created_at, reason, hash, data JSON) — version history (v6); no FK,
+ deleted explicitly with the notebook
+
+`Card.draft?: boolean` is local authoring state (like `folded`): persisted in the card data blob,
+never exported, never in a share payload, ignored on import.
**Same invariants as v1:**
- Variables are **card-scoped** (front + back share one scope, never cross card boundaries).
- Study state: document (exported) · progress (persisted locally, never exported) · **session**
- (`session.svelte.ts` — shuffle/search/archive-view plus `session.live`, the per-card control
- values keyed by variable name; wiped on every Study entry, never persisted).
+ (`session.svelte.ts` — shuffle/search/archive-view/collapse plus `session.live`, the per-card
+ control values keyed by variable name; never persisted. Entering Study wipes shuffle and live;
+ search, archive view and collapse survive until the notebook changes).
- A slot declares which layer its Study writes belong to via `SlotType.stateLayer`
(`'progress'` default → readerState by slot id; `'session'` → `session.live` by variable name —
slider is the one session-layer slot).
@@ -371,17 +416,23 @@ Every slot type implements `SlotType
` (`slot-contract.ts`):
| `renderEdit` | Svelte component for Edit mode |
| `renderStudy` | Svelte component for Study mode |
-**Registered types** (11): `text`, `slider`, `compute`, `chart`, `choice`, `list`, `progress`,
-`code`, `image`, `table`, `text-input`.
+**Registered types** (12): `text`, `slider`, `compute`, `chart`, `choice`, `list`, `progress`,
+`code`, `image`, `table`, `text-input`, `problem`.
+
+Optional `score?(props, state) → {correct, answered} | null` feeds the Reader's results export
+(choice and problem implement it; a slot without an answer key returns null).
### B5. Key systems (v2)
1. **Drag engine** (`drag/engine.ts` + `kinds.ts`) — unified pointer engine with `DRAG_KINDS` registry
(9 kinds: card, section, qopt, product, slot, bench, tag, svc, svcattach). Same FLIP approach as
- v1, but with **no native-drag path at all** (WKWebView blocks custom dataTransfer types — see the
- `text/nb-svc` sweep test). A kind's `laneSel` makes arbitrary elements drop targets: tag → card
- applies, tag → `.tag-grid` reorders cats, svcattach → `.room` attaches / dustbin detaches.
- Separate header-drag for matrix axis reorder. Drop handlers split by context (notebook vs factory).
+ v1. The pointer engine drives every notebook and study surface; the Factory inventory chips still
+ use native HTML5 drag (`SideFactory.svelte`). A sweep test in `svc-attach.test.ts` checks that no
+ component source contains the old `text/nb-svc` MIME type (WKWebView blocks custom dataTransfer
+ types, which is why that native path was removed). A kind's `laneSel` makes arbitrary elements drop
+ targets: tag → card applies, tag → `.tag-grid` reorders cats, svcattach → `.room` attaches /
+ dustbin detaches. Separate header-drag for matrix axis reorder. Drop handlers split by context
+ (notebook vs factory).
2. **Variable graph** (`variable-graph.ts`) — topological-sort evaluator. Each slot declares reads/
writes; `resolveGraph` orders by dependency and evaluates once. `findGraphIssues` does static
@@ -390,26 +441,55 @@ Every slot type implements `SlotType
` (`slot-contract.ts`):
3. **Coverage matrix** (`coverage-matrix.ts`) — same 3 axes as v1 (section/product/tag). Appears when
≥2 axes have ≥2 values.
-4. **Service bar** (`services.ts` + `service-ops.ts`) — 6 services (pin, shuffle, flipAll, reset,
- search, archive). Features decorate cards; actions fire once. Custom order via `svcOrder`.
+4. **Service bar** (`services.ts` + `service-ops.ts`) — 7 services (pin, shuffle, flipAll, reset,
+ search, archive, notes). Features decorate cards; actions fire once. Custom order via `svcOrder`.
5. **JSON interchange** (`json-io.ts`) — versioned export/import with full validation including
variable-graph cycle detection. Static analysis catches broken variable references before notebooks
are loaded.
-6. **Persistence** (`db.ts`) — SQLite via Tauri plugin-sql. `isTauri()` guards DB calls so the code
- runs in tests/browser without the native layer. Notebook/section/card extras ride `data` JSON
- columns (`db-map.ts`) — new optional fields need no SQL migration.
+6. **Persistence** (`db.ts` + `autosave.ts`) — SQLite via Tauri plugin-sql. `isTauri()` guards DB
+ calls so the code runs in tests/browser without the native layer. Every read/write goes through
+ one serialized queue; a save is ONE `execute()` batch (`BEGIN IMMEDIATE … COMMIT`, rows via
+ `json_each`), so it is atomic on a pooled connection; on failure the pool is closed (rolling the
+ open transaction back) and the write retried once with the latest state. Nothing persists before
+ hydration succeeds. `flushAll()` runs on blur, hidden, window close and Cmd+Q (Rust holds the
+ quit until the frontend flushed). Notebook/section/card extras ride `data` JSON columns
+ (`db-map.ts`) — new optional fields need no SQL migration. `db-sql.test.ts` runs the real SQL and
+ every migration against `node:sqlite`.
7. **Tags** (`tags.ts` + `TagsPanel.svelte`) — `Notebook.cats` holds identity and order; membership
lives on `card.tags`. Every mutation (including the card's comma input) goes through `tags.ts`,
which keeps `cats` in sync. `pinned` is owned by the pin button and cannot be renamed.
+8. **Shared Reader** (`reader-main.ts` + `Reader.svelte` + `reader-store.ts` + `results.ts`) — the
+ share payload `{shared, docId, notebook, theme}` is embedded (every `<`, `>`, `&` escaped as
+ `\u003c`…) in the committed template
+ (`generated/reader-template.ts`, rebuilt by `npm run build:reader`, freshness-checked in CI).
+ Import regenerates ids each load, so progress is keyed by a hash of each card's CONTENT (slots,
+ props, verbs — not width/color/tags) + slot face/index and stored in localStorage under
+ `notebuilder:reader:v1:` (docId = hash of install id + notebook id). "My results"
+ summarizes progress and `score()` tallies. Phones: under 760 px the Reader starts with its
+ panel collapsed and cards go full width (rules scoped to `body.nb-reader`). The build strips
+ remote `@import`s (no font request leaves the file) and fails on any external reference.
+ Share is refused while the notebook fails validation (ImportReport lists why); Export still
+ writes the backup, then lists what would stop it re-importing.
+
+9. **Bring-your-own-LLM authoring** (`schema/` + `slot-catalog.ts` + `ai-prompt.ts` +
+ `import-hints.ts`) — the JSON Schema is the one source the prompt kit and hints read from; the
+ Reader bundle must never import them (`reader-boundary.test.ts`). Notebooks created From AI arrive
+ with every card `draft` (`drafts.ts`, `DraftsBar.svelte`); Share warns while drafts remain.
+
+10. **Version history** (`snapshots.ts` + `versions.ts` + `VersionsPanel.svelte`) — automatic
+ snapshots after saves (≥10 min apart, only when content changed), manual "Save version now",
+ Restore (snapshots current first, keeps the notebook id, undoable). Retention: last 24 h up to
+ 50, then one per day for 30 days; manual ones kept up to 20.
+
### B6. "I want to change X" → go here (v2)
| Goal | Where |
|---|---|
-| New slot type | Implement `SlotType
` in `slots/mytype.ts` + Edit/Study `.svelte` + register in `slots/registry.ts` |
+| New slot type | Implement `SlotType
` in `slots/mytype.ts` + Edit/Study `.svelte` + register in `slots/registry.ts` + `SLOT_ICONS` in `CardView.svelte` + a `$defs` entry and `if/then` branch in `schema/notebook.schema.json` + an entry in `slot-catalog.ts` (sync tests name what is missing) + `npm run build:reader` |
| New verb/effect | `verbs.ts` + wire in `slots/VerbWrapper.svelte` + update `VerbConfig` in `types.ts` |
| Card/section CRUD | `notebook-ops.ts` |
| Factory/seal workflow | `bench.svelte.ts` + `card-types.ts` + `SealModal.svelte` |
@@ -419,7 +499,12 @@ Every slot type implements `SlotType
` (`slot-contract.ts`):
- **Card-scoped variables** — reads/writes never cross card boundaries. `findGraphIssues` enforces.
- **SlotType contract** — every slot type must declare `variables()` and provide both render components.
- **SQLite parameterized queries** — no string interpolation of user data in SQL.
-- **Session state (`session.svelte.ts`)** is never persisted or exported — mode/notebook switches reset it.
-- **`folded` is local-only** — never included in JSON export (fold state is per-reader).
+- **Session state (`session.svelte.ts`)** is never persisted or exported — entering Study wipes
+ shuffle and live, and switching notebooks wipes all of it (`resetSession`).
+- **`folded` and `draft` are local-only** — never included in JSON export or share payloads.
+- **Never `INSERT OR REPLACE` a parent row** — with foreign keys on it deletes and cascades;
+ use `INSERT … ON CONFLICT(id) DO UPDATE`.
+- **Every DB access rides the queue in `db.ts`**; multi-statement writes are one `execute()` batch.
+- **Nothing persists before hydration** (`autosave.ts`); App writes check `persistOn()`.
+- **Reader bundle boundary** — `json-io.ts`/the Reader never import `schema/`, `ai-prompt`,
+ `import-hints`, `slot-catalog` (sweep-tested); the committed Reader template is regenerated with
+ `npm run build:reader` whenever the Reader render path changes (CI fails on a stale one).
+- **Never `evalExpr` on student input** — typed answers go through `numeric-input.ts`.
- **Tauri-guard pattern** — `isTauri()` gates all native calls so lib modules run in unit tests.
- **Structural immutability of placed cards** — slot add/remove only in the Factory bench; placed cards
allow only content and style edits (same rule as v1).
@@ -439,8 +533,11 @@ Every slot type implements `SlotType
` (`slot-contract.ts`):
(sweep-tested in `state-layer.test.ts`); every change flows through `onUpdate`/`onState` callbacks
to the owner.
- **One tag write path** — all `card.tags`/`Notebook.cats` mutations go through `tags.ts`.
-- **No native HTML5 drag** — every gesture rides `drag/engine.ts` (sweep-tested; WKWebView breaks
- custom dataTransfer MIME types).
+- **Pointer engine for notebook/study, native drag in the Factory** — `drag/engine.ts` drives every
+ notebook and study gesture; the Factory inventory chips still use native HTML5 drag
+ (`SideFactory.svelte`). WKWebView blocks custom dataTransfer MIME types, so that native path can't
+ extend past the Factory. A sweep test in `svc-attach.test.ts` checks that no component source
+ contains the old `text/nb-svc` MIME type.
- **Undo keeps live selections** — `restoreHistory` clears a selection only when the restored
snapshot no longer contains it (D25 revised).
@@ -464,11 +561,10 @@ Every slot type implements `SlotType
` (`slot-contract.ts`):
docs/
CODE-MAP.md this file
adr/ architecture decision records
- spec/v2-spec.md v2 product spec
- research/ market analysis, v1 feature inventory
- examples/ sample JSON notebook
+ spec/ v2 product spec (local, untracked)
+ research/ market analysis, v1 feature inventory (local, untracked)
+ examples/ example notebooks
DEBT.md debt ledger (local, untracked)
- superpowers/plans/ task plans (local, untracked)
scripts/
build.mjs v1 concatenation build
@@ -478,10 +574,11 @@ scratch/
p3-gate/ … p6-gate/ visual QA screenshots (v1 vs v2 side-by-side)
HANDOFF.md developer handoff notes
-tests/ v1 Playwright BDD suite (~65 specs)
+tests/ v1 Playwright BDD suite (66 specs, 240 tests)
.github/
- workflows/ci.yml CI: build + test on push/PR
+ workflows/ci.yml CI: v2 check/test/build (path-filtered to v2/**)
+ workflows/v1.yml CI: v1 build/lint/test (path-filtered to root app paths)
ISSUE_TEMPLATE/ bug/feature templates
pull_request_template.md
```
diff --git a/docs/FORMAT.md b/docs/FORMAT.md
new file mode 100644
index 0000000..ef2ba21
--- /dev/null
+++ b/docs/FORMAT.md
@@ -0,0 +1,279 @@
+# NoteBuilder notebook format (interchange JSON, version 2)
+
+This is the file the v2 app writes with **⤓ Backup as JSON**, reads with **⤒ import** / **+ → Import
+file…**, and the shape any LLM must produce for **+ → From AI…**. A shared Reader `.html` embeds the
+same document (as `{"shared": true, "notebook": }` in its ``;
});
- // Inline the stylesheet, rewriting KaTeX font refs to woff2 data URIs (D23).
+ // Inline the stylesheet, rewriting KaTeX font refs to woff2 data URIs (D23). The authoring
+ // app's remote webfont @import (Google Fonts) is dropped: opening a shared file must not send a
+ // student's IP to a third party, and offline it only logs an error. Font stacks fall back to
+ // system fonts.
html = html.replace(/]*\brel="stylesheet"[^>]*>/gi, (m) => {
const href = m.match(/href="([^"]+)"/)?.[1];
const file = href && resolveAsset(href);
if (!file) return m;
- return ``;
+ const { css, removed } = stripRemoteImports(readFileSync(file, 'utf8'));
+ for (const rule of removed) console.log(`› dropped remote ${rule.slice(0, 72)}…`);
+ return ``;
});
assertPlaceholder(html);
@@ -73,22 +79,11 @@ function assertPlaceholder(html) {
}
}
-// Fail loudly if anything would still hit the network. Script bodies are blanked first so JS/CSS
-// string literals (e.g. `src="…"` inside code) never trip the scan.
+// Fail loudly if anything would still hit the network: attributes, CSS url(), any CSS @import
+// (including the minified `@import"https://…"` form) and any http(s) URL left in a stylesheet.
+// The scan itself lives in reader-inline.mjs, where tests pin it.
function assertNoExternalRefs(html) {
- const scan = html.replace(/(
+
+{#if count > 0}
+