Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@ The format is inspired by [Keep a Changelog](https://keepachangelog.com/en/1.1.0

### Fixed

- Example pages now show their intro paragraphs. Every source file opens with two or three paragraphs of explanation that the loader parsed and the page template then dropped, so the definition and the "when to use this" of most pages never reached a reader. They render under the summary and are part of the search index.
- Runner output reads like Python, not like the harness: tracebacks show only the learner's frames with their source lines (`File "example.py", line 3`), `exit()` and `sys.exit()` end the program instead of returning "Internal Server Error", stderr is shown in program order, and `input()` explains that the sandbox has no terminal. Pages that teach something the sandbox lacks (`sandbox_limit` in frontmatter: the venv module, child processes, threads, sockets) say so when Run fails.
- The editor has undo history, auto-indent after a block opener, Tab indentation (Esc then Tab leaves the editor), bracket matching, and Ctrl/⌘+Enter to run. Ctrl+Z used to fall through to the browser and corrupt the document.
- Figures stay readable on phones. A figure now fills the banner up to its intrinsic width and, when wider than the screen, keeps 72% of that width and scrolls sideways inside its own box; labels that shrank to under 6px now render at 9px or more.
- Journey pages render inline code; section titles and outcomes used to show literal backticks.
- `HEAD` requests are answered for every rendered page and `/sitemap.xml` (they returned 405), and trailing-slash URLs such as `/examples/values/` redirect to the canonical path (they returned 404).
- Cache hits leave the Worker with the intended `max-age=300`; a response read back from the Workers cache was reaching browsers with a four-hour lifetime.
- The Turnstile clearance cookie is bound to the client address that passed the check, so a copied cookie is not accepted elsewhere.
- Search finds pages by everyday words ("dictionary", "mutable", "regex") and by names a page uses in its prose or code (`zip`, `join`, `docstring`).
- The `hello-world` quality waiver is permanent; it would have expired on 2026-12-01 and failed `make verify` on every pull request.
- Early pages no longer depend on `def`, `class` or `try` before those are taught; `operators` no longer defines a class to demonstrate `@`.

- Deployment smoke now proves the production Turnstile secret. Its bypass header skips Siteverify, so a wrong, rotated, or test secret used to pass smoke while every new session's first run failed. With `PBE_SMOKE_BYPASS_SECRET`, `scripts/smoke_deployment.py` calls the header-gated `POST /__smoke/turnstile`. The Worker sends its secret with Cloudflare's dummy token and reports `valid`, `invalid`, `testing_key`, `unverified`, `unexpected`, or `absent`. Smoke fails unless the secret is a working production secret with a site key, or Turnstile is off.

- A Run whose Turnstile token the server rejects now ends with the server's message instead of re-challenging. The runner used to solve again every time the response carried the challenge marker, so a persistently failing Siteverify (wrong secret, hostname, or action) turned one click into an unbounded loop of solves, Worker POSTs, and Siteverify subrequests. Each Run now earns at most one challenge, and the failure message says to press Run again.
Expand All @@ -18,12 +30,22 @@ The format is inspired by [Keep a Changelog](https://keepachangelog.com/en/1.1.0

### Changed

- CodeMirror and Shiki are bundled from npm packages pinned in `package-lock.json` (`make browser-bundles`, sources in `web/`) instead of being imported from esm.sh at page load. An example page went from about 100 requests and 617 KB of third-party script to two first-party bundles, the CSP no longer allows esm.sh or `wasm-unsafe-eval`, and the code visitors run can only change with a commit. The privacy notice is updated.
- `generics-and-typevar` leads with PEP 695 type parameter syntax and shows `TypeVar` as the legacy spelling; `dataclasses`, `typed-dicts`, `warnings` and generics now use features introduced in Python 3.13 (`copy.replace()`, `ReadOnly`, `warnings.deprecated`, type parameter defaults).
- The scoring heuristic no longer credits a page for containing `print(` or particular name strings.
- The home page hero, About and privacy pages describe what the site does today.

- Figures now paint with `--fig-ink`, `--fig-ink-soft`, `--fig-accent` and `--fig-soft` tokens instead of literal colours, and `site.css` defines the tokens for both colour schemes. Dark mode recolours every figure with the page; the light "paper chip" behind figures is gone. Figure mono and sans faces follow the page's own font stacks, and mono runs are pinned to the grammar's character advance with `textLength` so divider positions hold on every platform. Paired figures in a banner share a baseline (a two-row subgrid). Five figures lost an accent that marked an arbitrary row (`naming-decisions`, `iteration-loop-selector`, `type-shape-catalog`, `reliability-signal-map`, `container-methods`); nine arrows that were mostly arrowhead were lengthened to the new 20-unit minimum.
- Ten figures redrawn as mechanisms carrying the lesson's own values: closures is an environment diagram with the returned frame ghosted and one live `__closure__` reference; generators shows the cell's two `next()` calls on `countdown(3)` with the surviving local beside each; recursion shows the example's tree at the deepest frame of `total(tree)` with the values each frame returns; dicts shows the cell's keys hashed to slots with the insert of `"year"`; sentinel iteration shows `read_chunk` yielding `"py"` and `"thon"` and stopping on the empty string; string formatting's format spec is a railroad tracing the cell's `05.1f`, skipped stations ghosted under a bypass rail; bytes-and-bytearray draws the example's bytes as integer slots with the in-place write and moves to the cell that performs it; regular expressions shows the cell's two capture groups landing on `Ada: 10`; values shows `text` bound to a `str` object and the `type()` hop to where `upper()` lives; logging shows the cell's three records crossing the handler's INFO gate. The binding figure is a parametrised factory, so `variables` shows `message → "hi"` and `constants` shows `MAX_RETRIES → 3`.
- The rubric states that table-shaped figures are redrawn rather than removed, that a figure whose caption names no single element carries no accent, and how cell-0 anchors are scored. The review, principles and queue are in `docs/diagram-upgrade-plan.md`.

### Added

- `files-and-pathlib` example: `Path` joining, whole-file and line-by-line text I/O, directory listing, and the missing-file boundary.
- `/llms.txt`, and every example's authored Markdown at `/examples/<slug>.md`.
- `make runtime-examples-test` (part of `make verify`): posts every example's complete program to the local dev Worker and compares the sandbox output with the expected output. `verify-examples` only ever ran the catalog under host CPython.
- The browser gate now checks editor keys, the smallest figure label on a 390px phone, and that an example page makes no third-party request before Run.

- `/about` page describing how the site is made — the verified-output pipeline, the runner sandbox, the figure grammar, and the quality gates — with a design-language section that renders the live CSS tokens (color swatches, spacing scale, type specimens, and a real walkthrough cell as a specimen). Linked from the nav on every page and listed in the sitemap.
- Copy buttons on read-only source cells: injected client-side onto `.cell-source` wrappers (so no-JS pages render no dead buttons), clipboard API with a hidden-textarea fallback, and a quiet icon-in-pill treatment — the Lucide copy glyph drawn as a `currentColor` CSS mask (checkmark on success, x on failure), a visually hidden live region announcing the result, and a ~44px tap target around the small pill. These are the site's first and only UI icons; every other action stays text.
- Keyboard navigation on example pages: `←`/`→` follow the existing `rel="prev"`/`rel="next"` links, ignoring keystrokes with modifiers or focus inside the editor, inputs, or any editable surface. Arrows only fire while the editor is unedited (so a slip never discards work), and the prev/next links carry title hints naming the shortcut.
Expand Down
7 changes: 5 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@ Do not edit generated files by hand:
src/example_sources_data.py
src/asset_manifest.py
public/*.css/js fingerprinted copies
public/editor.js and public/highlighter.js (bundled from web/*.js)
```

The editor and syntax highlighter live in `web/`; their npm dependencies are pinned in `package-lock.json` and bundled into `public/` by `make browser-bundles`, which `make build` runs.

Regenerate them with:

```bash
Expand Down Expand Up @@ -66,7 +69,7 @@ make check-generated

## Quality checks

These scripts enforce the catalog-level rules from `docs/example-quality-rubric.md`. Run them together with `make quality-checks`. CI does not schedule a waiver-expiry run; before a release or once a month, run `make check-waiver-expiry`, which fails while any waiver has 30 days or fewer left.
These scripts enforce the catalog-level rules from `docs/example-quality-rubric.md`. Run them together with `make quality-checks`. CI does not schedule a waiver-expiry run; before a release or once a month, run `make check-waiver-expiry`, which fails while any time-boxed waiver has 30 days or fewer left. A waiver whose reason can never stop being true sets `permanent = true` instead of `expires` (Hello World is the only one); the two fields are mutually exclusive.

| Script | What it gates |
| --- | --- |
Expand All @@ -79,7 +82,7 @@ These scripts enforce the catalog-level rules from `docs/example-quality-rubric.
| `scripts/check_prose_duplication.py` | No verbatim repeated paragraphs, no cell prose copied from the intro, no duplicate note bullets. |
| `scripts/check_inline_links.py` | Inline `[text](target)` links in prose resolve to real `/examples` or `/journeys` pages. |
| `scripts/score_example_criteria.py` | Heuristic criterion scores per example; fails when a curated score exceeds the heuristic by more than the delta bound, so the score registry cannot inflate without the page changing. |
| `scripts/check_quality_scores.py` | Curated scores meet the 9.0 target / 8.5 hard minimum, waivers carry future expiry dates (with a warning in their last 30 days) and are dropped when stale, and the journey-section average stays above its floor. |
| `scripts/check_quality_scores.py` | Curated scores meet the 9.0 target / 8.5 hard minimum, waivers carry either a future expiry date (with a warning in its last 30 days) or `permanent = true`, and are dropped when stale, and the journey-section average stays above its floor. |
| `scripts/check_no_figure_rationales.py` | No-figure opt-outs carry a reason and an unexpired `review_after` date. |
| `scripts/check_journey_outcomes.py` | Every journey section declares learner outcomes. |
| `scripts/audit_example_graph.py --check` | The `see_also` graph has no broken targets, self-links, over-linked pages, or orphaned examples. |
Expand Down
25 changes: 18 additions & 7 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
PY := uv run --python 3.13
NODE_DEPS_STAMP := node_modules/.package-lock.json

.PHONY: check-node-version node-deps test embed-examples embed-editorial-registry build-search-index build check-generated fingerprint prototypes browser-layout-test search-ranking-test social-cards check-social-cards seo-cache-lint verify-examples check-registry-integrity check-confusable-pairs check-broad-surface-tours check-footgun-coverage check-notes-supported check-program-covers-cells check-prose-duplication check-inline-links score-example-criteria check-quality-scores check-waiver-expiry check-no-figure-rationales check-journey-outcomes audit-example-graph quality-checks rubric-audit format-examples verify-python-version verify smoke-deployment post-deploy-smoke dev deploy upgrade-runtime-deps lint
.PHONY: check-node-version node-deps test embed-examples embed-editorial-registry build-search-index build check-generated fingerprint prototypes browser-bundles browser-layout-test runtime-examples-test search-ranking-test social-cards check-social-cards seo-cache-lint verify-examples check-registry-integrity check-confusable-pairs check-broad-surface-tours check-footgun-coverage check-notes-supported check-program-covers-cells check-prose-duplication check-inline-links score-example-criteria check-quality-scores check-waiver-expiry check-no-figure-rationales check-journey-outcomes audit-example-graph quality-checks rubric-audit format-examples verify-python-version verify smoke-deployment post-deploy-smoke dev deploy upgrade-runtime-deps lint

check-node-version:
@major="$$(node -p 'process.versions.node.split(".")[0]')"; \
Expand Down Expand Up @@ -32,11 +32,16 @@ build-search-index: embed-examples
build: embed-examples embed-editorial-registry build-search-index fingerprint prototypes

check-generated: build check-social-cards
git diff --exit-code src/example_sources_data.py src/editorial_registry_data.py src/asset_manifest.py public/_headers public/prototyping public/search-index.json
git diff --exit-code src/example_sources_data.py src/editorial_registry_data.py src/asset_manifest.py public/_headers public/prototyping public/search-index.json public/editor.js public/highlighter.js
# Tracked generated changes may be staged for commit; reject only untracked output here because git diff above already catches unstaged tracked drift.
test -z "$$(git ls-files --others --exclude-standard -- public/prototyping public/*.css public/*.js public/*.json)"

fingerprint: embed-examples embed-editorial-registry build-search-index
# public/editor.js and public/highlighter.js are bundles of web/*.js plus the
# npm packages pinned in package-lock.json. Edit the sources in web/.
browser-bundles: node-deps
node scripts/build_browser_bundles.mjs

fingerprint: embed-examples embed-editorial-registry build-search-index browser-bundles
$(PY) scripts/fingerprint_assets.py

prototypes: embed-examples
Expand All @@ -46,6 +51,11 @@ prototypes: embed-examples
browser-layout-test:
scripts/check_browser_layout.mjs

# Run every example's complete program in the real sandbox (the local dev
# Worker) and compare with its expected output.
runtime-examples-test:
$(PY) scripts/check_runtime_examples.py

search-ranking-test:
scripts/check_search_ranking.mjs

Expand Down Expand Up @@ -92,9 +102,10 @@ score-example-criteria:
check-quality-scores:
$(PY) scripts/check_quality_scores.py

# Manual gate, not run in CI: fail while a quality waiver has 30 days or fewer
# left, so an expiry can be caught before it turns every pull request red.
# `make verify` (CI) already prints a warning inside the same 30-day window.
# Manual gate, not run in CI: fail while a time-boxed quality waiver has 30
# days or fewer left, so an expiry can be caught before it turns every pull
# request red. `make verify` (CI) already prints a warning inside the same
# 30-day window. Waivers marked `permanent = true` have no date and are skipped.
check-waiver-expiry:
$(PY) scripts/check_quality_scores.py --fail-within-days 30

Expand All @@ -121,7 +132,7 @@ verify-python-version: build
lint:
uv run ruff check src tests scripts

verify: build test seo-cache-lint verify-examples quality-checks browser-layout-test search-ranking-test lint check-generated
verify: build test seo-cache-lint verify-examples quality-checks browser-layout-test runtime-examples-test search-ranking-test lint check-generated

dev: node-deps
uv run --group workers pywrangler dev --port 9696
Expand Down
14 changes: 10 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Production: <https://www.pythonbyexample.dev> (`workers.dev` is disabled so the
- Learner-behavior reporting from Worker wide events (`docs/learner-analytics.md`)
- A quality-gate suite for registries, rubric scores, coverage, and teaching structure that fails builds when content regresses
- `/about` page describing the verification pipeline, runner sandbox, figure grammar, and live design tokens
- `/privacy` notice covering runner submissions, operational logs, Invisible Turnstile, cookies, and optional browser CDNs
- `/privacy` notice covering runner submissions, operational logs, Invisible Turnstile, cookies, and the self-hosted editor scripts
- Copy buttons on read-only source cells
- Keyboard prev/next navigation (`←`/`→`) on example pages
- "Copy link" sharing of the runner's current code via `#code=` URLs
Expand Down Expand Up @@ -125,6 +125,8 @@ git diff --check
- Worker Cache API keys include the HTML version
- prototype layout pages are not cached

`make runtime-examples-test` posts every example's complete program to the local Worker and compares what the sandbox prints with the expected output.

`make browser-layout-test` launches headless Chrome against the local Worker. It checks the rendered Shiki code-block layout so generated line markup does not create visual blank rows, drives the runner, sharing, copy, search and keyboard navigation through the page, and measures computed styles (pressed states, touch targets, contrast in both themes, marginalia figure colours against the grammar's `--fig-*` tokens, the reader's font size, reduced-transparency and more-contrast fallbacks) in place of unit tests that matched CSS text.

## Asset fingerprinting and cache busting
Expand All @@ -138,6 +140,8 @@ public/editor.js
public/runner.js
```

`public/editor.js` and `public/highlighter.js` are bundles: their sources are `web/editor.js` and `web/highlighter.js`, built with the npm packages pinned in `package-lock.json`.

Before tests/deploy, regenerate embedded example data, fingerprinted asset copies, and Python manifests:

```bash
Expand Down Expand Up @@ -185,7 +189,7 @@ make upgrade-runtime-deps
make verify
```

Dependabot proposes npm, GitHub Actions, and development-tool updates weekly. It skips runtime packages (their versions depend on which Pyodide wheels exist) and Ruff (upgrades are deliberate because they change lint rules). The browser libraries loaded from esm.sh are pinned in `public/editor.js` and `public/syntax-highlight.js` and are updated by hand.
Dependabot proposes npm, GitHub Actions, and development-tool updates weekly. It skips runtime packages (their versions depend on which Pyodide wheels exist) and Ruff (upgrades are deliberate because they change lint rules). The browser libraries (CodeMirror and Shiki) are npm dev dependencies pinned in `package-lock.json`; `make browser-bundles` bundles `web/editor.js` and `web/highlighter.js` into `public/`, so pages load no third-party CDN and Dependabot proposes their updates.

## Contributing

Expand Down Expand Up @@ -229,8 +233,10 @@ footgun, notes, program/cell, prose-duplication, inline-link, scoring,
figure, journey, and example-graph gates.

`make check-waiver-expiry` is a manual check, not run in CI: it fails while
any quality waiver has 30 days or fewer left. `make quality-checks` (and so CI)
only prints a warning in that window, then fails once the waiver has expired.
any time-boxed quality waiver has 30 days or fewer left. `make quality-checks`
(and so CI) only prints a warning in that window, then fails once the waiver
has expired. A waiver whose reason is permanent sets `permanent = true`
instead of `expires` and is never date-checked; Hello World is the only one.

`src/example_sources_data.py` is generated and committed so Cloudflare Workers can load examples in production. Do not edit it by hand.

Expand Down
Loading
Loading