From 8ccfbc4a57eddc13a4b528405d75add7ed150f4c Mon Sep 17 00:00:00 2001 From: Mohammad Galib Date: Mon, 30 Nov 2026 23:41:46 +0530 Subject: [PATCH 1/5] fix: course author links point to galib9690 (course 0.4.3), with a regression test The GitHub handle and profile links in courses/intro-to-hydrology/course.json pointed to an unrelated account. api/courses.json regenerated (course.json sha256 and content_sha256 change). tests/test_repo.py fails if the wrong account reappears in any tracked file or if authorUrl/profileUrl disagree with the github handle. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 8 +++++++ api/courses.json | 10 ++++---- courses/intro-to-hydrology/course.json | 8 +++---- tests/test_repo.py | 33 ++++++++++++++++++++++++++ 4 files changed, 50 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8478d68..7f868b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ All notable changes to the learning modules. Versions are per module (`manifest.json` and the manifest embedded in `module.html` carry the same number). +## 2026-11-30 — Author link corrected + +Owner request (2026-11-30): "fix the author link". No lesson content changed; module versions are unchanged. + +### Course intro-to-hydrology 0.4.2 → 0.4.3 +- The author's GitHub handle and links in `course.json` (`authors[0].github`, `authors[0].profileUrl`, `authorUrl`) pointed to an unrelated account; they now point to `galib9690` (`https://github.com/galib9690`). `api/courses.json` regenerated (the `course.json` sha256 and the course `content_sha256` change). +- `tests/test_repo.py`: fails if a link or handle of the wrong account reappears in any tracked file, and if a course author's `profileUrl` or the course `authorUrl` disagrees with the `github` handle. + ## 2026-11-30 — Contribution-ready (licences, standalone lessons, credit) No lesson content changed; module versions are unchanged. Owner approval: "go ahead with the fixes" (2026-11-30), covering CC BY 4.0 for lesson content and MIT for code. diff --git a/api/courses.json b/api/courses.json index 6d31740..ce41fd8 100644 --- a/api/courses.json +++ b/api/courses.json @@ -3,15 +3,15 @@ "courseId": "intro-hydro-2026", "title": "Introduction to Hydrology", "abstract": "A hands-on, animated tour through the whole hydrologic cycle \u2014 from the first flash of water vapour rising off the ocean, through precipitation, evapotranspiration and runoff generation, to a full basin characterisation at your fingertips. Ten learning modules, each showcasing a different interactive capability of the AI-Hydro learning hub, followed by a personalised certificate of completion.", - "version": "0.4.2", + "version": "0.4.3", "author": "Mohammad Galib, Purdue University", "authorAffiliation": "Purdue University", - "authorUrl": "https://github.com/mgalib", + "authorUrl": "https://github.com/galib9690", "trustLevel": "official", "contributors": [ { "name": "Mohammad Galib", - "github": "mgalib", + "github": "galib9690", "affiliation": "Purdue University", "roles": [ "author", @@ -135,7 +135,7 @@ "files": [ { "path": "courses/intro-to-hydrology/course.json", - "sha256": "1aea2b433cf037c151546e252451448000485713788bc9b2ca81df9bc3ba699e" + "sha256": "84cb985a1089bee3843fdea8da9037c62405c18a5a87ad74b0c72dc59585d1c6" }, { "path": "modules/baseflow-separation/module.html", @@ -182,7 +182,7 @@ "sha256": "7aa0db1fce57748df698be6e5383cd0e1b7c19d8fbad28e28bf69f713b198a3a" } ], - "content_sha256": "8dda0cb91e8b594daee23dc997f2a12056c0c96d83804b2dafe315599dc89698", + "content_sha256": "372185f6ed9f5af4c807ade08ef0235e41575b0fb920a4375c9b7ba46e89147c", "updatedAt": "2026-11-24" } ] diff --git a/courses/intro-to-hydrology/course.json b/courses/intro-to-hydrology/course.json index 03d734a..bd2b9c6 100644 --- a/courses/intro-to-hydrology/course.json +++ b/courses/intro-to-hydrology/course.json @@ -4,18 +4,18 @@ "authors": [ { "name": "Mohammad Galib", - "github": "mgalib", + "github": "galib9690", "affiliation": "Purdue University", - "profileUrl": "https://github.com/mgalib", + "profileUrl": "https://github.com/galib9690", "roles": ["author", "maintainer"] } ], - "authorUrl": "https://github.com/mgalib", + "authorUrl": "https://github.com/galib9690", "trustLevel": "official", "citation": "Galib, M. (2026). Introduction to Hydrology — an interactive AI-Hydro course. AI-Hydro Learning Hub.", "citationUrl": "https://github.com/AI-Hydro/Modules/tree/main/courses/intro-to-hydrology", "topic": "Hydrology Fundamentals", - "version": "0.4.2", + "version": "0.4.3", "license": "CC-BY-4.0", "abstract": "A hands-on, animated tour through the whole hydrologic cycle — from the first flash of water vapour rising off the ocean, through precipitation, evapotranspiration and runoff generation, to a full basin characterisation at your fingertips. Ten learning modules, each showcasing a different interactive capability of the AI-Hydro learning hub, followed by a personalised certificate of completion.", "kernel": "isolated", diff --git a/tests/test_repo.py b/tests/test_repo.py index 2953649..ec74a44 100644 --- a/tests/test_repo.py +++ b/tests/test_repo.py @@ -164,3 +164,36 @@ def test_dingman_is_cited_consistently_as_a_book_without_chapters(): for m in re.finditer(r"Dingman[^<]{0,120}", module_text(mod)): assert "Chapter" not in m.group(0), mod assert "Physical Hydrology" in (ROOT / "CITATIONS.verified.md").read_text() + + +def _tracked_text_files(): + r = subprocess.run(["git", "ls-files", "-z"], cwd=ROOT, capture_output=True, text=True) + names = [n for n in r.stdout.split("\0") if n] if r.returncode == 0 else [] + paths = [ROOT / n for n in names] or [p for p in ROOT.rglob("*") if ".git" not in p.parts] + return [p for p in paths if p.is_file() and p.suffix in {".md", ".json", ".html", ".py", ".js", ".yml", ".yaml", ".cff", ".css", ".txt", ""}] + + +def test_no_link_to_the_wrong_github_account(): + """The author's GitHub account is galib9690. The handle spelled like the university e-mail name is an + unrelated account; the e-mail address itself (…@purdue.edu) is correct and is not matched here.""" + wrong = re.compile(r"github\.com/" + "mgalib" + r"(?![\w-])|\"github\"\s*:\s*\"" + "mgalib" + "\"", re.I) + hits = [] + for p in _tracked_text_files(): + try: + text = p.read_text(encoding="utf-8") + except (UnicodeDecodeError, OSError): + continue + hits += [f"{p.relative_to(ROOT)}:{i}" for i, line in enumerate(text.splitlines(), 1) if wrong.search(line)] + assert not hits, f"link or handle of the wrong GitHub account: {hits}" + + +def test_course_author_links_agree_with_the_github_handle(): + for cpath in sorted((ROOT / "courses").glob("*/course.json")): + course = json.loads(cpath.read_text()) + profiles = set() + for a in course.get("authors", []): + if a.get("github") or a.get("profileUrl"): + assert a.get("profileUrl") == f"https://github.com/{a.get('github')}", f"{cpath.parent.name}: {a.get('name')}" + profiles.add(a["profileUrl"]) + if course.get("authorUrl", "").startswith("https://github.com/") and profiles: + assert course["authorUrl"] in profiles, f"{cpath.parent.name}: authorUrl is not one of the authors' profiles" From 82fb450f7f7f582b27e3e07bd7b319694ce43a7f Mon Sep 17 00:00:00 2001 From: Mohammad Galib Date: Mon, 30 Nov 2026 23:54:10 +0530 Subject: [PATCH 2/5] fix: a standalone lesson passes the checks; createdAt required in the manifest; clearer failures Found by adding a standalone lesson in a scratch copy, following CONTRIBUTING: - test_wave2_repo required every module on the flagship course page; it now requires the course's own members there. - build_api.py --check failed on a correctly built new lesson because createdAt fell back to a git date (null before the first commit, different after it and after a merge). createdAt (YYYY-MM-DD) is now required by validate_manifests.py; all 11 lessons already carry it. - validate_manifests.py rejects scaffold placeholders left in a lesson. - Failure messages for the CHANGELOG heading, the theme-ratchet baseline and the checkpoint shape say what to do. No check is loosened. Co-Authored-By: Claude Fable 5.2 --- api/README.md | 2 +- scripts/build_api.py | 3 ++- scripts/validate_manifests.py | 21 ++++++++++++++++++--- tests/test_quiz_answers.py | 19 ++++++++++++------- tests/test_repo.py | 4 +++- tests/test_theme_ratchet.py | 3 ++- tests/test_wave2_repo.py | 31 +++++++++++++++++++++++++++++-- 7 files changed, 67 insertions(+), 16 deletions(-) diff --git a/api/README.md b/api/README.md index 5887cd5..6836666 100644 --- a/api/README.md +++ b/api/README.md @@ -10,7 +10,7 @@ An array, one entry per `modules//manifest.json`, sorted by module id. Every |---|---| | `moduleId`, `title`, `description`, `version`, `license`, `author`, `topic`, `level`, `estimatedMinutes`, `tags`, `requires`, `citation`, `isFeatured`, `courseId`, `courseOrder` | `manifest.json` | | `downloadUrl`, `githubUrl` | manifest value, else derived from `moduleId` | -| `createdAt` | manifest value, else the date of the first git commit touching `modules//` | +| `createdAt` | the manifest's `createdAt` (required, `YYYY-MM-DD`) | | `updatedAt` | **author date of the last git commit that touched `modules//`** (not the build date; without history it keeps the previous value) | | `downloadCount`, `githubReactions`, `discussionUrl` | kept from the previous file; **not refreshed**: Discussions are disabled on this repository, so `githubReactions` stays 0 and `discussionUrl` empty (the extension still reads `githubReactions`, so the field stays) | | `certification` | see below | diff --git a/scripts/build_api.py b/scripts/build_api.py index 34bfbee..5e50beb 100644 --- a/scripts/build_api.py +++ b/scripts/build_api.py @@ -6,7 +6,8 @@ * updatedAt = author date of the last git commit that touched modules// (courses// for a course). Without git history (a shallow clone) it falls back to the committed value. - * createdAt = the manifest's createdAt, else the date of the first commit touching the module. + * createdAt = the manifest's createdAt (required by validate_manifests.py). The first-commit date is a + fallback only for a manifest that fails validation; it is not stable across a merge. * certification has two independent fields: metadata_complete True when the manifest carries a citation, description, tags and a positive estimatedMinutes (checks_passed / checks_failed list them). It diff --git a/scripts/validate_manifests.py b/scripts/validate_manifests.py index bd66838..f9de580 100644 --- a/scripts/validate_manifests.py +++ b/scripts/validate_manifests.py @@ -4,7 +4,9 @@ Checks (exit 1 on any failure): * modules// has module.html, manifest.json and README.md; * manifest.json has the required fields with valid values (see CONTRIBUTING.md), moduleId equals the - directory name, version is semver, level is intro/intermediate/advanced, tags are a non-empty list; + directory name, version is semver, level is intro/intermediate/advanced, tags are a non-empty list, + createdAt is a YYYY-MM-DD date; + * no scaffold placeholder (scripts/new_module.py) is left in module.html, manifest.json or README.md; * the manifest embedded in module.html equals the one generated from manifest.json (scripts/build_modules.py embedded_manifest), so the two never disagree; * the module footer shows the manifest version; @@ -25,7 +27,11 @@ from build_modules import embedded_manifest # noqa: E402 from repo_lib import ROOT, courses, raw_path, read_json # noqa: E402 -REQUIRED = ["moduleId", "title", "description", "version", "license", "author", "topic", "level", "estimatedMinutes", "tags", "requires"] +REQUIRED = ["moduleId", "title", "description", "version", "license", "author", "topic", "level", "estimatedMinutes", "tags", "requires", + "createdAt"] +# what scripts/new_module.py writes wherever the author still has to write something +PLACEHOLDER = "TODO(new_module)" +DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$") LEVELS = {"intro", "intermediate", "advanced"} SEMVER = re.compile(r"^\d+\.\d+\.\d+$") EMBEDDED = re.compile(r'', re.S) @@ -44,9 +50,18 @@ def check_module(d: Path) -> list[str]: return [f"{d.name}: manifest.json is not valid JSON ({e})"] for k in REQUIRED: if k not in m or m[k] in ("", None, []): - errs.append(f"{d.name}: manifest.json missing or empty {k!r}") + hint = " (the date the lesson is first published, YYYY-MM-DD)" if k == "createdAt" else "" + errs.append(f"{d.name}: manifest.json missing or empty {k!r}{hint}") if errs: return errs + # The API copies createdAt from the manifest. A date taken from git instead would differ between the + # contributor's commit, the pull-request merge commit and main, and `build_api.py --check` would fail. + if not (isinstance(m["createdAt"], str) and DATE.match(m["createdAt"])): + errs.append(f"{d.name}: createdAt {m['createdAt']!r} must be a date written YYYY-MM-DD") + for f in ("module.html", "manifest.json", "README.md"): + n = (d / f).read_text(encoding="utf-8").count(PLACEHOLDER) + if n: + errs.append(f"{d.name}: {f} still has {n} scaffold placeholder(s); replace every {PLACEHOLDER!r} with the lesson's own text") if m["moduleId"] != d.name: errs.append(f"{d.name}: moduleId {m['moduleId']!r} must equal the directory name") if not SEMVER.match(m["version"]): diff --git a/tests/test_quiz_answers.py b/tests/test_quiz_answers.py index 47d3526..87622a1 100644 --- a/tests/test_quiz_answers.py +++ b/tests/test_quiz_answers.py @@ -26,6 +26,8 @@ def q_cfs(mod, name): def test_every_module_with_a_checkpoint_uses_the_shared_engine(): + missing = sorted(set(QUIZ_MODULES) - set(quiz_dump())) + assert not missing, f"no checkpoint found (HydroQuiz.mount with the shared engine, see CONTRIBUTING 'Checkpoints'): {missing}" assert sorted(quiz_dump()) == QUIZ_MODULES for mod in QUIZ_MODULES: t = module_text(mod) @@ -38,16 +40,18 @@ def test_every_module_with_a_checkpoint_uses_the_shared_engine(): def test_each_checkpoint_keeps_its_three_content_questions_and_adds_computed_ones(): for mod in QUIZ_MODULES: items = quiz_dump()[mod]["items"] - assert len(items) >= 4, mod - assert sum(1 for i in items if i["type"] == "choice") >= 3, mod + kinds = [i["type"] for i in items] + assert len(items) >= 4, f"{mod}: the checkpoint has {len(items)} item(s); at least 4 are required" + assert kinds.count("choice") >= 3, f"{mod}: the checkpoint has {kinds.count('choice')} 'choice' item(s); at least 3 are required" numeric = [i for i in items if i["type"] == "numeric"] - assert numeric, mod # at least one numeric item (every current lesson has one) + assert numeric, f"{mod}: the checkpoint needs at least 1 'numeric' item whose answer is a function computed from the lesson" for i in numeric: - assert isinstance(i["expected"], (int, float)) and math.isfinite(i["expected"]) + assert isinstance(i["expected"], (int, float)) and math.isfinite(i["expected"]), \ + f"{mod}/{i['id']}: the numeric answer function did not return a finite number" for i in items: if i["type"] == "choice": - assert 0 <= i["expected"] < len(i["options"]) - assert i["explain"], (mod, i["id"]) + assert 0 <= i["expected"] < len(i["options"]), f"{mod}/{i['id']}: 'correct' is not the index of an option" + assert i["explain"], f"{mod}/{i['id']}: every item needs an 'explain'" def test_numeric_items_are_not_typed_into_the_page(): @@ -55,7 +59,8 @@ def test_numeric_items_are_not_typed_into_the_page(): for mod in QUIZ_MODULES: t = module_text(mod) for m in re.finditer(r"type: 'numeric'.*?answer: ([^,}]+)", t, re.S): - assert not re.match(r"[-+]?[0-9.]", m.group(1).strip()), (mod, m.group(1)) + assert not re.match(r"[-+]?[0-9.]", m.group(1).strip()), \ + f"{mod}: a numeric item has the typed answer {m.group(1).strip()!r}; write `answer: function () {{ ... }}` computed from the lesson" def test_baseflow_answers(): diff --git a/tests/test_repo.py b/tests/test_repo.py index ec74a44..3565e00 100644 --- a/tests/test_repo.py +++ b/tests/test_repo.py @@ -60,7 +60,9 @@ def test_manifest_and_embedded_versions_agree(mod): def test_changelog_records_each_version(mod): ver = json.loads((MODULES / mod / "manifest.json").read_text())["version"] log = (ROOT / "CHANGELOG.md").read_text() - assert re.search(rf"### {re.escape(mod)} .*→ {re.escape(ver)}", log), mod + assert re.search(rf"### {re.escape(mod)} .*→ {re.escape(ver)}", log), ( + f"CHANGELOG.md needs a heading for this version, for example '### {mod} new → {ver}' " + f"(or '### {mod} → {ver}' for an update)") @pytest.mark.parametrize("mod", IDS) diff --git a/tests/test_theme_ratchet.py b/tests/test_theme_ratchet.py index 3b5bb56..f04dd48 100644 --- a/tests/test_theme_ratchet.py +++ b/tests/test_theme_ratchet.py @@ -44,7 +44,8 @@ def _baseline() -> dict: def test_every_module_has_a_baseline_and_none_is_over_it(): base, now = _baseline()["max"], counts() - assert set(now) == set(base), f"modules without a baseline: {sorted(set(now) ^ set(base))}" + assert set(now) == set(base), (f"modules without a baseline (or a baseline without a module): {sorted(set(now) ^ set(base))}. " + "For a new lesson run `python tests/test_theme_ratchet.py --write` and commit tests/theme_hex_baseline.json.") over = {m: (now[m], base[m]) for m in now if now[m] > base[m]} assert not over, f"new hard-coded colours (count, allowed): {over}. Use a --hy-* token from shared/theme.css." diff --git a/tests/test_wave2_repo.py b/tests/test_wave2_repo.py index bc6dfeb..033b18a 100644 --- a/tests/test_wave2_repo.py +++ b/tests/test_wave2_repo.py @@ -68,6 +68,32 @@ def test_validate_manifests_catches_disagreement_and_bad_fields(tmp_path): assert any("license" in e for e in validate_manifests.check_module(d)) +def test_validate_manifests_requires_a_created_date_and_rejects_scaffold_placeholders(tmp_path): + d = tmp_path / "dem-to-twi"; d.mkdir() + for f in ("module.html", "manifest.json", "README.md"): + (d / f).write_bytes((MODULES / "dem-to-twi" / f).read_bytes()) + man = json.loads((d / "manifest.json").read_text()) + created = man.pop("createdAt") + (d / "manifest.json").write_text(json.dumps(man)) + assert any("'createdAt'" in e and "YYYY-MM-DD" in e for e in validate_manifests.check_module(d)) + for bad in ("30 November 2026", "2026-11-30T10:00:00Z", 20261130): + man["createdAt"] = bad + (d / "manifest.json").write_text(json.dumps(man)) + assert any("createdAt" in e and "YYYY-MM-DD" in e for e in validate_manifests.check_module(d)), bad + (d / "manifest.json").write_bytes((MODULES / "dem-to-twi" / "manifest.json").read_bytes()) + assert validate_manifests.check_module(d) == [] and re.fullmatch(r"\d{4}-\d{2}-\d{2}", created) + (d / "README.md").write_text((d / "README.md").read_text() + "\n" + validate_manifests.PLACEHOLDER + ": objectives\n") + errs = validate_manifests.check_module(d) + assert len(errs) == 1 and "README.md still has 1 scaffold placeholder" in errs[0] + + +def test_the_api_created_date_is_the_manifest_date_for_every_module(): + """Not a git date: that differs between a contributor's commit, the merge commit and main.""" + api = {m["moduleId"]: m["createdAt"] for m in json.loads((ROOT / "api/modules.json").read_text())} + for mod in IDS: + assert api[mod] == json.loads((MODULES / mod / "manifest.json").read_text())["createdAt"], mod + + def test_course_graph_is_valid_and_matches_manifest_order(): from repo_lib import courses for path, c in courses(): @@ -83,9 +109,10 @@ def test_readme_table_and_course_page_are_generated_from_the_manifests(): assert f"(modules/{mod}/)" in readme, mod course = (ROOT / "courses/intro-to-hydrology/README.md").read_text() assert "flowchart TD" in course - for mod in IDS: - assert f"(../../modules/{mod}/)" in course, mod cj = json.loads((ROOT / "courses/intro-to-hydrology/course.json").read_text()) + # the course page lists the course's own lessons; a standalone lesson is in the README table only + for mod in [m["id"] for m in cj["modules"]]: + assert f"(../../modules/{mod}/)" in course, mod for m in cj["modules"]: for p in m.get("prerequisites", []): i, j = [x["id"] for x in cj["modules"]].index(p) + 1, [x["id"] for x in cj["modules"]].index(m["id"]) + 1 From 045e4cebce42d7501d5cbb6f4820eda745a839a1 Mon Sep 17 00:00:00 2001 From: Mohammad Galib Date: Mon, 30 Nov 2026 23:54:10 +0530 Subject: [PATCH 3/5] feat: scripts/new_module.py scaffold and a corrected contributor guide new_module.py writes the skeleton of a standalone lesson with the structure the checks expect and prints the next commands in the order that works; tests/test_new_module.py takes a skeleton through render, build, validation, CSP and the checkpoint shape in a scratch directory. CONTRIBUTING gains a Start here section, the correct generated-files order, the cell markup, an honest account of the citation gate and the meaning of the usual failing checks. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 9 ++ CONTRIBUTING.md | 49 +++++++++-- DECISIONS.md | 6 ++ PROGRESS.md | 6 ++ scripts/new_module.py | 119 ++++++++++++++++++++++++++ scripts/templates/module.html.tmpl | 133 +++++++++++++++++++++++++++++ tests/test_new_module.py | 110 ++++++++++++++++++++++++ 7 files changed, 423 insertions(+), 9 deletions(-) create mode 100644 scripts/new_module.py create mode 100644 scripts/templates/module.html.tmpl create mode 100644 tests/test_new_module.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f868b0..29a52e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ All notable changes to the learning modules. Versions are per module (`manifest.json` and the manifest embedded in `module.html` carry the same number). +## 2026-11-30 — Contributor path tested end to end + +A new standalone lesson was written as an outside contributor would, by following CONTRIBUTING.md literally in a scratch copy (the test lesson is not in the repository). What that found, and what changed. No lesson content changed; module versions are unchanged. +- **A standalone lesson could not pass the tests.** `tests/test_wave2_repo.py` required every module to appear on the flagship course page. It now requires the course's own members there; every module is still required in the README table. +- **The API check failed on a correctly built new lesson.** `createdAt` fell back to a git date, which is empty before the first commit and differs between the contributor's commit, the merge commit and `main`. `createdAt` (YYYY-MM-DD) is now a required manifest field (`scripts/validate_manifests.py`; all 11 lessons already had it) and a test pins that the API copies it. +- **`scripts/new_module.py`** (new, with `scripts/templates/module.html.tmpl`): writes the skeleton of a standalone lesson that has the structure the checks expect and prints the next commands in the order that works. Its `TODO(new_module)` placeholders fail `validate_manifests.py` until they are written. `tests/test_new_module.py` takes a skeleton through render, build, validation, the CSP check and the checkpoint shape in a scratch directory. +- **CONTRIBUTING.md:** a "Start here" section (what to install, the scaffold, how to look at the page); the generated-files order corrected (render the cells before `build_modules.py`); the markup of an executable cell; what the citation gate is and that its tool is not in this repository; `createdAt`; what the usual failing checks mean. +- **Failure messages** of the checks a new lesson usually trips now say what to do (CHANGELOG heading, theme-ratchet baseline, checkpoint shape, typed numeric answer). No check was loosened: unique ids, `downloadUrl`, per-file hashes, CSP and the 250,000-byte page cap are unchanged. + ## 2026-11-30 — Author link corrected Owner request (2026-11-30): "fix the author link". No lesson content changed; module versions are unchanged. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6a94f25..556d142 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,5 +1,18 @@ # Contributing a Learning Module +## Start here + +You need Python with `pytest numpy matplotlib pillow`, and Node (CI uses Python 3.12 and Node 22) for the JavaScript tests and for rendering cells; there is nothing else to install. Run every command from the repository root. + +```bash +python -m pip install pytest numpy matplotlib pillow +python scripts/new_module.py my-lesson-id --title "My Lesson Title" --author "Your Name, Your Institution" +``` + +`scripts/new_module.py` writes `modules/my-lesson-id/` with a `module.html`, `manifest.json` and `README.md` that already have the structure the checks expect (shared theme, accessibility and quiz code behind their markers, one Python cell with its static-output marker, a checkpoint of the required shape, Sources, footer) and prints the commands to run next, in order. The lesson it writes is standalone. Every place you must write is marked `TODO(new_module)`; `validate_manifests.py` fails while one is left. You can also copy an existing lesson instead; the checklist below is the same either way. + +To look at the lesson, open `modules/my-lesson-id/module.html` in a browser after `build_modules.py` has run: it renders with no server and no AI-Hydro (the Run buttons are disabled there and the pre-rendered outputs are shown). + ## Quick checklist A lesson can stand alone or belong to a course. **Course membership is not required**: a standalone lesson has no `courseId` or `courseOrder`, and no `course.json` lists it. Items with a bracket are enforced by CI (`.github/workflows/checks.yml`) through the named check; items marked **human review** are not machine-checked and are what the reviewer reads for. @@ -12,7 +25,7 @@ Files - [ ] `modules//data/` and `static/` if the lesson bundles data or pre-rendered outputs (see below) - [ ] An entry in `CHANGELOG.md`, with a heading of the form `### … → ` (for example `### new → 0.1.0`; the id, an arrow and the manifest version are matched) [`tests/test_repo.py::test_changelog_records_each_version`] - [ ] A baseline entry for the theme ratchet: run `python tests/test_theme_ratchet.py --write` once the page is final; it records your count of hard-coded colours in `tests/theme_hex_baseline.json`, and the count may only go down afterwards [`tests/test_theme_ratchet.py::test_every_module_has_a_baseline_and_none_is_over_it`] -- [ ] Every DOI the lesson cites passes the cite-verify gate and has a `| | PASS |` row in `CITATIONS.verified.md` [`tests/test_repo.py::test_every_doi_in_the_modules_passed_the_gate`] +- [ ] Every DOI the lesson cites has a `| | PASS |` row in `CITATIONS.verified.md` [`tests/test_repo.py::test_every_doi_in_the_modules_passed_the_gate`]. The test only finds the row; see "Data and citations" for what the row asserts and who runs the gate Lesson - [ ] Renders in a plain browser with no AI-Hydro bridge (standalone rule below); every executable cell has a pre-rendered output, with alt text for each figure [`test_wave2_repo`] @@ -22,9 +35,9 @@ Lesson - [ ] **Human review:** data sources and citations in a Sources & Further Reading section; real data come from `scripts/extract_camels.py` with `data/PROVENANCE.json`; anything else is labelled SYNTHETIC (see "Data and citations"). Only the existing lessons' SYNTHETIC labels are tested; a new lesson's label is read by the reviewer - [ ] **Human review:** Python cells have been read for risky calls: `python scripts/lint_cell_risk.py` (see "Security review") -Generated files (regenerate, do not edit) +Generated files (regenerate, do not edit; run them in this order) +- [ ] `python scripts/render_static_outputs.py --only ` first: it runs each cell and stores the output in `static/`. `build_modules.py` stops with "no static output for cell" if a cell has none yet - [ ] `python scripts/build_modules.py` (inlines shared code, data, manifest and static outputs) -- [ ] `python scripts/render_static_outputs.py` - [ ] `python scripts/gen_docs.py` (README module table; course page) - [ ] `python scripts/gen_contributors.py` (CONTRIBUTORS.md) - [ ] `python scripts/build_api.py` (api/*.json with the per-file sha256) @@ -63,14 +76,15 @@ Attribution expected from reuse of a lesson: the author(s) named in its `manifes "executable": true, "python": ["numpy"] }, - "citation": { "text": "Author (Year). Title. Venue.", "doi": "10.xxxx/xxxx" } + "citation": { "text": "Author (Year). Title. Venue.", "doi": "10.xxxx/xxxx" }, + "createdAt": "2026-11-30" } ``` -Optional: `"contributors": ["Name, Institution"]`, `createdAt`. `courseId` and `courseOrder` are set only by a lesson that a `courses//course.json` lists, and must then match it; a standalone lesson has neither. `moduleId` equals the directory name, `version` is `major.minor.patch` and the page footer shows `v`. +`citation.doi` is optional (a book may have none); `citation.text` is needed for `certification.metadata_complete`. Optional: `"contributors": ["Name, Institution"]`. `courseId` and `courseOrder` are set only by a lesson that a `courses//course.json` lists, and must then match it; a standalone lesson has neither. `moduleId` equals the directory name, `version` is `major.minor.patch` and the page footer shows `v`. **Valid levels:** `intro`, `intermediate`, `advanced`. **Suggested topics:** `terrain-analysis`, `streamflow`, `hydrograph`, `water-quality`, `modelling`, `remote-sensing`, `data-access`. -`updatedAt` is not kept in the manifest: the API takes it from the last git commit that touched the module. `createdAt` is optional (otherwise the first commit date is used). +`updatedAt` is not kept in the manifest: the API takes it from the last git commit that touched the module, and `build_api.py --check` ignores it. `createdAt` is required, written `YYYY-MM-DD`: the day the lesson is first proposed. It is not taken from git, because a git date differs between your commit, the pull-request merge commit and `main`, and the API check would then fail on a file you built correctly. ## One manifest, two naming schemes @@ -102,6 +116,20 @@ Every module must follow the [AI-Hydro brand guide](https://github.com/AI-Hydro/ Without the `window.aihydro` bridge (a plain browser tab) a module must still be meaningful: - **Code panes update.** Controls that rewrite a cell's source must do it themselves, then ask the bridge to mirror it (`aihydro.rewriteCell`) only if it is present. +- **An executable cell has this structure** (the checks and the bridge look for these class names and attributes; the cell id is unique on the page): + + ```html +
+
+ Python + What the cell does + +
+
print("the code the learner sees")
+
+
+ ``` + - **Every executable cell shows a pre-rendered output.** Put `` inside the cell's `.aihydro-output`, then run `python scripts/render_static_outputs.py` (it runs each cell headless with `python -s -E` and stores text plus a PNG in `modules//static/`; add alt text for each figure to `static/alt.json`). The bridge replaces the static block when the learner runs the cell. A cell that cannot run headless (network, a long render) gets an authored note saying so, never made-up output. - **Interactive widgets work in plain JavaScript.** Where a map or 3-D view needs the bridge, draw a plain fallback in a *separate* element, only when `window.parent === window` and there is no bridge (`shared/cmap.js` has a shaded-relief renderer, `shared/geosketch.js` a longitude/latitude sketch). Never invent geometry. - **Run buttons** show "Open in AI-Hydro to run" outside the preview. @@ -152,7 +180,8 @@ Every control that works by dragging also works from the keyboard (`HydroA11y.sl ## Data and citations - Real-data slices come from CAMELS-US via `scripts/extract_camels.py` and ship with `data/PROVENANCE.json` (source member, sha256, period, units, QC flags, citations). Label anything else SYNTHETIC; do not give synthetic series real gauge ids. -- Every number a lesson states must come from a cell or from a cited, verified source; run each citation through the cite-verify gate and record it in `CITATIONS.verified.md`. +- Every number a lesson states must come from a cell or from a cited, verified source, recorded in `CITATIONS.verified.md`. +- **The citation gate.** A reference with a DOI is kept only if two or more of Crossref, OpenAlex and Semantic Scholar resolve that DOI to the same work (title, authors, year). The tool the maintainers use for this (`cite-verify`) is not in this repository, so as a contributor: look the DOI up yourself (for example at `https://doi.org/` and in Crossref), check that title, authors and year match what you cite, and add the row to `CITATIONS.verified.md` with the indexes you checked. **Human review:** the automated test only finds the row; the reviewer re-runs the gate before merging and removes a reference that fails. A book or handbook with no DOI goes in the "Books and handbooks without a DOI" table and is cited without chapter or page numbers you have not checked. ## Checks @@ -167,11 +196,13 @@ python scripts/validate_manifests.py # manifests valid; embedded blo python scripts/check_csp.py # no external hosts except Google Fonts, no eval/fetch/WebSocket python scripts/build_api.py --check # api/*.json are current (including the per-file sha256) python scripts/lint_cell_risk.py # reviewer aid: risky calls in cell code (warnings; not a sandbox) -python -m pytest tests -q # use /opt/miniconda3/bin/python -s -E locally in the AI-Hydro workspace +python -m pytest tests -q # maintainers, in the AI-Hydro workspace: /opt/miniconda3/bin/python -s -E node --test tests/js/*.test.js ``` -Regenerate instead of editing by hand: `build_modules.py`, `render_static_outputs.py` (after a cell changes), `gen_docs.py`, `build_api.py`. +Regenerate instead of editing by hand: `render_static_outputs.py` (after a cell changes), `build_modules.py`, `gen_docs.py`, `gen_contributors.py`, `build_api.py`. `build_api.py --check` compares everything except `updatedAt`, so the API you build before committing stays valid after you commit. + +A failing check names the lesson and what to do. The usual ones for a new lesson: "CHANGELOG.md needs a heading" (add `### new → `), "modules without a baseline" (run `python tests/test_theme_ratchet.py --write`), "static output missing or stale" (run `render_static_outputs.py --only `, then `build_modules.py`), "stale: api/modules.json" (run `build_api.py` again after the last edit). ## PR review diff --git a/DECISIONS.md b/DECISIONS.md index 7cbdef6..835bd52 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -67,3 +67,9 @@ Owner approved the pilot ("go ahead with the three.js feasibility check") and ru - **Page budget.** watershed-runoff is at 246,682 B of the 250,000 B cap. The added-bytes budget was raised 130,000 → 140,000 for the shared theme code; the cap was not raised. Any further growth in that lesson needs a trim first. - **Ratchet, not a zero target.** `tests/theme_hex_baseline.json` stores the allowed colour literals per lesson (outside generated regions); it may only go down. Counts before and after are in the file (`main_before` and `max`). +## 2026-11-30 — `createdAt` is a required manifest field; a scaffold instead of a longer checklist + +- **`createdAt` comes from the manifest, never from git.** `build_api.py` used the first commit date when a manifest had none. For a new lesson that date is empty before the first commit (the API was built with `null`), then changes when the contributor commits, and again on a squash merge, while `build_api.py --check` compared it; a contributor who followed CONTRIBUTING exactly got "stale: api/modules.json" in CI (reproduced in a scratch clone). Ignoring the field in `--check`, as the Skills repository does for its dates, would have published `null`. Requiring it in the manifest is deterministic and tightens validation; the 11 existing lessons already carried it. `updatedAt` stays git-derived and ignored by `--check`. +- **A scaffold (`scripts/new_module.py`) rather than more prose.** The undocumented part of a lesson was its structure (which shared markers a page needs, the cell markup the static-output test expects, a checkpoint of the required shape). A generated skeleton states that once, in code a test exercises, and cannot drift from the checks unnoticed. Its placeholders fail validation, so a skeleton cannot be merged as a lesson. +- **The standalone promise is tested by doing it.** The one remaining test that assumed every module is in the flagship course was found only by adding a lesson; `tests/test_new_module.py` keeps a skeleton passing the per-lesson checks. +- **Citation gate.** The gate tool is not in this repository, so the test can only find a PASS row a contributor wrote. CONTRIBUTING now says so and makes the reviewer's re-run of the gate the control. Bringing the tool into the repository is left to the owner. diff --git a/PROGRESS.md b/PROGRESS.md index 033a255..0c38dac 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -51,3 +51,9 @@ Implemented the pre-AGU contribution fixes of `docs/vision-2040/findings/skills- Verification: the commands of CONTRIBUTING.md "Checks" plus `gen_contributors.py --check`; real counts in the hand-off report. Not done: the Skills-repo and extension-side authoring-skill fixes of the same scout report; a branch-protection setting for `main`; a DOI for CITATION.cff. +## 2026-11-30 — Author link, and the contributor path tested as an outside contributor + +Owner request: fix the author link; test and improve the contribution path. Course `intro-to-hydrology` 0.4.3 points to `galib9690` (regression test in `tests/test_repo.py`). +A standalone "Rational Method peak discharge" lesson was written twice in a scratch clone by following CONTRIBUTING.md literally (once by hand, once from the new scaffold) and removed; findings and fixes are in CHANGELOG.md ("Contributor path tested end to end") and DECISIONS.md. +Verification: the commands of CONTRIBUTING.md "Checks" on this branch, and on the scratch clone with the test lesson committed; real counts in the hand-off report. +Not done: the page was not opened in a browser or in Studio (the node smoke and standalone tests ran on it); the citation-gate tool is still not in this repository (documented, owner decision); `build_api.py` keeps its now-unused git fallback for `createdAt`. diff --git a/scripts/new_module.py b/scripts/new_module.py new file mode 100644 index 0000000..a058962 --- /dev/null +++ b/scripts/new_module.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Start a new lesson from a skeleton that already has the structure the checks expect. + +Creates modules// with module.html, manifest.json and README.md: the shared theme, accessibility +and quiz code behind their markers, the embedded-manifest marker, one executable Python cell with its +static-output marker, a checkpoint of the required shape (3 choice items and 1 numeric item computed from +the cell), a Sources section and the footer with the version. The lesson is standalone (no courseId). + +Every place you must write is marked `TODO(new_module)`; scripts/validate_manifests.py fails while one is +left, so a skeleton cannot be merged by accident. Nothing else is generated here: the script prints the +commands to run next, in the order that works. + +Usage: python scripts/new_module.py --title "Lesson title" --author "Your Name, Your Institution" + [--topic streamflow] [--level intro] [--minutes 15] +""" +from __future__ import annotations + +import argparse +import datetime +import html +import json +import re +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from repo_lib import ROOT # noqa: E402 + +TEMPLATE = Path(__file__).resolve().parent / "templates" / "module.html.tmpl" +PLACEHOLDER = "TODO(new_module):" +MODULE_ID = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$") +LEVELS = ("intro", "intermediate", "advanced") + + +def scaffold(root: Path, module_id: str, title: str, author: str, topic: str = "streamflow", level: str = "intro", + minutes: int = 15, today: str | None = None) -> Path: + """Write the three files under root/modules// and return that directory. Raises ValueError.""" + if not MODULE_ID.match(module_id): + raise ValueError(f"module id {module_id!r} must be lowercase letters, digits and single hyphens (for example 'unit-hydrograph')") + d = root / "modules" / module_id + if d.exists(): + raise ValueError(f"modules/{module_id}/ already exists; module ids are unique") + name, _, affiliation = author.partition(",") + if not name.strip() or not affiliation.strip(): + raise ValueError('--author must be "Your Name, Your Institution" (a person; AI tools are not authors)') + if level not in LEVELS: + raise ValueError(f"--level must be one of {', '.join(LEVELS)}") + if minutes <= 0: + raise ValueError("--minutes must be a positive integer") + if not title.strip(): + raise ValueError("--title must not be empty") + manifest = { + "moduleId": module_id, + "title": title.strip(), + "description": f"{PLACEHOLDER} one or two sentences shown on the marketplace card.", + "version": "0.1.0", + "license": "CC-BY-4.0", + "author": f"{name.strip()}, {affiliation.strip()}", + "topic": topic, + "level": level, + "estimatedMinutes": minutes, + "tags": [topic], + "requires": {"executable": True, "python": []}, + "citation": {"text": f"{PLACEHOLDER} Author (Year). Title. Venue."}, + "createdAt": today or datetime.date.today().isoformat(), + } + page = TEMPLATE.read_text(encoding="utf-8") + for key, value in { + "{{TITLE}}": html.escape(title.strip()), + "{{ID}}": module_id, + "{{AUTHOR_NAME}}": html.escape(name.strip()), + "{{AFFILIATION_SUFFIX}}": ", " + html.escape(affiliation.strip()), + "{{PLACEHOLDER}}": PLACEHOLDER, + }.items(): + page = page.replace(key, value) + readme = (f"# {title.strip()}\n\n{PLACEHOLDER} what the lesson teaches, in a paragraph.\n\n" + f"## Learning objectives\n- {PLACEHOLDER} first objective\n\n## Prerequisites\n{PLACEHOLDER} none, or the lessons to take first.\n") + d.mkdir(parents=True) + (d / "module.html").write_text(page, encoding="utf-8") + (d / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + (d / "README.md").write_text(readme, encoding="utf-8") + return d + + +def next_steps(module_id: str) -> str: + return f"""Created modules/{module_id}/ (module.html, manifest.json, README.md). + +Next, in this order: + 1. Write the lesson: replace every '{PLACEHOLDER}' in the three files (keep the @@BEGIN/@@END markers). + 2. python scripts/render_static_outputs.py --only {module_id} # runs each cell, stores its output in static/ + a cell that draws a figure also needs alt text in modules/{module_id}/static/alt.json: {{"": "..."}} + 3. python scripts/build_modules.py # inlines shared code, manifest and static outputs + 4. python tests/test_theme_ratchet.py --write # records the lesson's hard-coded colour count + 5. Add to CHANGELOG.md a heading: ### {module_id} new → 0.1.0 + 6. python scripts/gen_docs.py && python scripts/gen_contributors.py && python scripts/build_api.py + 7. Run the commands under "Checks" in CONTRIBUTING.md. +After any later edit of a cell repeat 2 and 3; after any other edit of module.html or manifest.json repeat 3; then 6.""" + + +def main() -> int: + ap = argparse.ArgumentParser(description="Create the skeleton of a new standalone lesson.") + ap.add_argument("module_id", help="directory name and moduleId: lowercase, hyphens") + ap.add_argument("--title", required=True) + ap.add_argument("--author", required=True, help='"Your Name, Your Institution"') + ap.add_argument("--topic", default="streamflow", help="see the suggested topics in CONTRIBUTING.md") + ap.add_argument("--level", default="intro", choices=LEVELS) + ap.add_argument("--minutes", type=int, default=15) + a = ap.parse_args() + try: + scaffold(ROOT, a.module_id, a.title, a.author, a.topic, a.level, a.minutes) + except ValueError as e: + print(f"error: {e}", file=sys.stderr) + return 1 + print(next_steps(a.module_id)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/templates/module.html.tmpl b/scripts/templates/module.html.tmpl new file mode 100644 index 0000000..f6c20ae --- /dev/null +++ b/scripts/templates/module.html.tmpl @@ -0,0 +1,133 @@ + + + + +{{TITLE}} — AI-Hydro Interactive Module + + + + + + + + +
+ +
+ + AI-Hydro · Interactive Module +
+ +

{{TITLE}}

+ +

SYNTHETIC values: the numbers in this lesson are illustrative, not observations of a real basin.

+ +
+

1. {{PLACEHOLDER}} First section

+

{{PLACEHOLDER}} Explain the idea in two or three sentences. Every number you state must come from a cell on this page or from a cited source.

+ + +
+
+ Python + {{PLACEHOLDER}} What the cell does (computes only; no files, no network) + +
+
A = 2.0   # first value (SYNTHETIC)
+B = 3.5   # second value (SYNTHETIC)
+
+total = A + B
+print(f"A + B = {total:.2f}")
+
+
+
+ +
+

2. Checkpoint

+

Answer every item to complete the lesson. Wrong answers can be changed and checked again.

+
+
+ +
+

Sources & Further Reading

+
    +
  1. {{PLACEHOLDER}} Author (Year). Title. Venue. Each DOI you cite needs a PASS row in CITATIONS.verified.md.
  2. +
+
+ +
+ {{AUTHOR_NAME}}{{AFFILIATION_SUFFIX}} · CC-BY-4.0 · + Module {{ID}} · v0.1.0 · Made with AI-Hydro +
+ +
+ + + + + diff --git a/tests/test_new_module.py b/tests/test_new_module.py new file mode 100644 index 0000000..a84da17 --- /dev/null +++ b/tests/test_new_module.py @@ -0,0 +1,110 @@ +"""scripts/new_module.py: the skeleton it writes passes the same checks a contributed lesson must pass. + +The scaffold is run in a scratch copy of scripts/, shared/ and tests/js/ (never in this repository), then taken +through the commands the script prints: render the cell, build, validate, CSP, and the checkpoint shape.""" +import json +import re +import shutil +import subprocess +import sys + +import pytest + +from helpers import ROOT + +sys.path.insert(0, str(ROOT / "scripts")) +import new_module # noqa: E402 +import validate_manifests # noqa: E402 + +MOD = "unit-hydrograph-basics" + + +def run(root, *args): + return subprocess.run([sys.executable, "-s", "-E", *args], capture_output=True, text=True, cwd=root) + + +@pytest.fixture(scope="module") +def scratch(tmp_path_factory): + root = tmp_path_factory.mktemp("scaffold") + ignore = shutil.ignore_patterns("__pycache__") + shutil.copytree(ROOT / "scripts", root / "scripts", ignore=ignore) + shutil.copytree(ROOT / "shared", root / "shared", ignore=ignore) + shutil.copytree(ROOT / "tests" / "js", root / "tests" / "js", ignore=ignore) + (root / "modules").mkdir() + r = run(root, "scripts/new_module.py", MOD, "--title", "Unit Hydrograph ", "--author", "Ada Lovelace, Analytical Society") + assert r.returncode == 0, r.stderr + return root, r.stdout + + +def test_the_skeleton_is_standalone_dated_and_marked(scratch): + root, out = scratch + d = root / "modules" / MOD + assert sorted(p.name for p in d.iterdir()) == ["README.md", "manifest.json", "module.html"] + man = json.loads((d / "manifest.json").read_text()) + assert man["moduleId"] == MOD and man["license"] == "CC-BY-4.0" and man["version"] == "0.1.0" + assert man["author"] == "Ada Lovelace, Analytical Society" + assert "courseId" not in man and "courseOrder" not in man + assert re.fullmatch(r"\d{4}-\d{2}-\d{2}", man["createdAt"]) + page = (d / "module.html").read_text() + assert "Unit Hydrograph <Basics>" in page and "" not in page # the title is escaped + assert "{{" not in page and new_module.PLACEHOLDER in page + # the printed steps name the commands in the order that works: render before build + assert out.index("render_static_outputs.py --only " + MOD) < out.index("build_modules.py") < out.index("build_api.py") + assert f"### {MOD} new → 0.1.0" in out + + +def test_the_skeleton_passes_the_checks_once_the_placeholders_are_written(scratch): + root, _ = scratch + d = root / "modules" / MOD + r = run(root, "scripts/build_modules.py") + assert r.returncode != 0 and "render_static_outputs.py" in r.stdout + r.stderr # build before render says what to run + for cmd in (["scripts/render_static_outputs.py", "--only", MOD], ["scripts/build_modules.py"], + ["scripts/build_modules.py", "--check"], ["scripts/render_static_outputs.py", "--check"], ["scripts/check_csp.py"]): + r = run(root, *cmd) + assert r.returncode == 0, (cmd, r.stdout + r.stderr) + assert (d / "static" / "example.txt").read_text() == "A + B = 5.50\n" + # the only complaint left is the unwritten text + errs = validate_manifests.check_module(d) + assert len(errs) == 3 and all("scaffold placeholder" in e for e in errs), errs + r = run(root, "scripts/validate_manifests.py") + assert r.returncode == 1 and "scaffold placeholder" in r.stdout + r.stderr + for f in ("module.html", "manifest.json", "README.md"): + (d / f).write_text((d / f).read_text().replace(new_module.PLACEHOLDER, "Written")) + for cmd in (["scripts/build_modules.py"], ["scripts/validate_manifests.py"], ["scripts/check_csp.py"], ["scripts/build_modules.py", "--check"]): + r = run(root, *cmd) + assert r.returncode == 0, (cmd, r.stdout + r.stderr) + page = (d / "module.html").read_text() + assert len(page.encode()) < 250_000 + m = re.search(r"(.*?)", page, re.S) + assert 'data-static-output="prerendered"' in m[1] and "A + B = 5.50" in m[1] + assert page[:m.start()].rstrip().endswith('aria-live="polite">') + assert not re.search(r"\son(click|change|input|keydown)=", page) and not re.search(r"\bunlock\b", page, re.I) + assert "SYNTHETIC" in page and "v0.1.0" in page + # the checkpoint has the required shape, and its numeric answer is computed from the cell + q = subprocess.run(["node", "tests/js/dump_quiz.js"], capture_output=True, text=True, cwd=root) + assert q.returncode == 0, q.stderr + items = json.loads(q.stdout)[MOD]["items"] + kinds = [i["type"] for i in items] + assert len(items) >= 4 and kinds.count("choice") >= 3 and kinds.count("numeric") >= 1 + assert next(i for i in items if i["type"] == "numeric")["expected"] == pytest.approx(5.5) + assert all(i["explain"] for i in items) + + +@pytest.mark.parametrize("args,needle", [ + (("Bad_Id", "T", "A B, C"), "lowercase"), + (("ok-id", "T", "Only Name"), "Your Name, Your Institution"), + (("ok-id", " ", "A B, C"), "--title"), +]) +def test_bad_input_is_refused_with_a_reason_and_writes_nothing(tmp_path, args, needle): + with pytest.raises(ValueError, match=re.escape(needle)): + new_module.scaffold(tmp_path, *args) + assert not (tmp_path / "modules").exists() + + +def test_an_existing_module_id_is_never_overwritten(tmp_path): + d = new_module.scaffold(tmp_path, "ok-id", "T", "A B, C", today="2026-01-02") + before = (d / "module.html").read_bytes() + assert json.loads((d / "manifest.json").read_text())["createdAt"] == "2026-01-02" + with pytest.raises(ValueError, match="already exists"): + new_module.scaffold(tmp_path, "ok-id", "Other", "A B, C") + assert (d / "module.html").read_bytes() == before From ea095d358d990593ad0e98e0ad5a7ba23973023e Mon Sep 17 00:00:00 2001 From: Mohammad Galib Date: Mon, 30 Nov 2026 23:54:11 +0530 Subject: [PATCH 4/5] chore: regenerate api/courses.json (updatedAt of the course) Co-Authored-By: Claude Fable 5.2 --- api/courses.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/courses.json b/api/courses.json index ce41fd8..e4b5d72 100644 --- a/api/courses.json +++ b/api/courses.json @@ -183,6 +183,6 @@ } ], "content_sha256": "372185f6ed9f5af4c807ade08ef0235e41575b0fb920a4375c9b7ba46e89147c", - "updatedAt": "2026-11-24" + "updatedAt": "2026-11-30" } ] From 094b158d24eeaa1db69e521aecd3422ea48cd40f Mon Sep 17 00:00:00 2001 From: Mohammad Galib Date: Tue, 1 Dec 2026 00:00:32 +0530 Subject: [PATCH 5/5] fix(scaffold): fullmatch module id (reject trailing newline); clean error on mkdir race Review follow-up. Co-Authored-By: Claude Opus 5.5 --- scripts/new_module.py | 7 +++++-- tests/test_new_module.py | 1 + 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/scripts/new_module.py b/scripts/new_module.py index a058962..5e78f8e 100644 --- a/scripts/new_module.py +++ b/scripts/new_module.py @@ -35,7 +35,7 @@ def scaffold(root: Path, module_id: str, title: str, author: str, topic: str = "streamflow", level: str = "intro", minutes: int = 15, today: str | None = None) -> Path: """Write the three files under root/modules// and return that directory. Raises ValueError.""" - if not MODULE_ID.match(module_id): + if not isinstance(module_id, str) or not MODULE_ID.fullmatch(module_id): raise ValueError(f"module id {module_id!r} must be lowercase letters, digits and single hyphens (for example 'unit-hydrograph')") d = root / "modules" / module_id if d.exists(): @@ -75,7 +75,10 @@ def scaffold(root: Path, module_id: str, title: str, author: str, topic: str = " page = page.replace(key, value) readme = (f"# {title.strip()}\n\n{PLACEHOLDER} what the lesson teaches, in a paragraph.\n\n" f"## Learning objectives\n- {PLACEHOLDER} first objective\n\n## Prerequisites\n{PLACEHOLDER} none, or the lessons to take first.\n") - d.mkdir(parents=True) + try: + d.mkdir(parents=True) + except FileExistsError: + raise ValueError(f"modules/{module_id}/ already exists; module ids are unique") from None (d / "module.html").write_text(page, encoding="utf-8") (d / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") (d / "README.md").write_text(readme, encoding="utf-8") diff --git a/tests/test_new_module.py b/tests/test_new_module.py index a84da17..21785cf 100644 --- a/tests/test_new_module.py +++ b/tests/test_new_module.py @@ -92,6 +92,7 @@ def test_the_skeleton_passes_the_checks_once_the_placeholders_are_written(scratc @pytest.mark.parametrize("args,needle", [ (("Bad_Id", "T", "A B, C"), "lowercase"), + (("ok-id\n", "T", "A B, C"), "lowercase"), (("ok-id", "T", "Only Name"), "Your Name, Your Institution"), (("ok-id", " ", "A B, C"), "--title"), ])