diff --git a/.github/workflows/build-api.yml b/.github/workflows/build-api.yml index a858010..b145814 100644 --- a/.github/workflows/build-api.yml +++ b/.github/workflows/build-api.yml @@ -4,9 +4,8 @@ name: Build Modules API # - On every push to main that can change the API, `verify` checks that the committed api/*.json # (including the per-file sha256 values) matches the files. PRs already have to commit the # regenerated API (checks.yml runs build_api.py --check), so main never needs a bot commit. -# - Discussion reaction counts are cosmetic. `refresh-reactions` runs only on manual dispatch: it -# rebuilds the API, refreshes the counts and pushes a branch `bot/api-refresh-`; open a PR -# from it and merge it like any other change. +# - There is no reaction-count refresh: Discussions are disabled on this repository, so the count was +# always 0. `githubReactions` stays in the API (the extension reads it) and is not refreshed. on: push: branches: [main] @@ -16,11 +15,9 @@ on: - 'shared/**' - 'api/**' - 'scripts/build_api.py' - workflow_dispatch: jobs: verify: - if: github.event_name == 'push' runs-on: ubuntu-latest permissions: contents: read @@ -30,91 +27,3 @@ jobs: fetch-depth: 0 # updatedAt comes from the last git commit touching each module - name: Committed API matches the files (hashes included) run: python3 scripts/build_api.py --check - - refresh-reactions: - if: github.event_name == 'workflow_dispatch' - runs-on: ubuntu-latest - permissions: - contents: write # pushes a bot/ branch only; main is protected by the repository ruleset - discussions: read - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - name: Build api/modules.json and api/courses.json - run: python3 scripts/build_api.py - - name: Scrape GitHub Discussion reactions - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - python3 - <<'EOF' - import json, subprocess, os - - api_path = "api/modules.json" - if not os.path.exists(api_path): - print("No api/modules.json found, skipping reaction scrape") - exit(0) - - with open(api_path) as f: - items = json.load(f) - - repo = "AI-Hydro/Modules" - updated = False - - for item in items: - module_id = item["moduleId"] - title = item.get("title", module_id) - - search_result = subprocess.run( - ["gh", "api", f"repos/{repo}/discussions", - "--jq", f'[.[] | select(.title == "Module: {title}")] | first'], - capture_output=True, text=True - ) - discussion = None - if search_result.returncode == 0 and search_result.stdout.strip() not in ("", "null"): - try: - discussion = json.loads(search_result.stdout.strip()) - except Exception: - pass - - if discussion: - reactions_result = subprocess.run( - ["gh", "api", f"repos/{repo}/discussions/{discussion['number']}/reactions", - "--jq", "length"], - capture_output=True, text=True - ) - if reactions_result.returncode == 0: - try: - count = int(reactions_result.stdout.strip()) - if item.get("githubReactions") != count: - item["githubReactions"] = count - updated = True - except ValueError: - pass - new_url = discussion.get("html_url", "") - if new_url and item.get("discussionUrl") != new_url: - item["discussionUrl"] = new_url - updated = True - - if updated: - with open(api_path, "w") as f: - json.dump(items, f, indent=2) - f.write("\n") - print("Updated reaction counts in api/modules.json") - else: - print("No reaction count changes") - EOF - - name: Push a refresh branch (open a PR from it) - run: | - git config user.name "github-actions[bot]" - git config user.email "github-actions[bot]@users.noreply.github.com" - git add api/modules.json api/courses.json - if git diff --staged --quiet; then - echo "No changes to the API files" - else - branch="bot/api-refresh-${{ github.run_id }}" - git switch -c "$branch" - git commit -m "ci: refresh API reaction counts" - git push origin "$branch" - echo "Open a PR: https://github.com/${{ github.repository }}/compare/main...$branch" - fi diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 08d0d15..cb4cef3 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -36,6 +36,9 @@ jobs: - name: README module table and course page are generated from the manifests run: python scripts/gen_docs.py --check + - name: CONTRIBUTORS.md is generated from the manifests + run: python scripts/gen_contributors.py --check + - name: Manifests, embedded manifests and course.json are valid and agree run: python scripts/validate_manifests.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6416c1d..8478d68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ 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 — 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. +- `LICENSE` (CC BY 4.0, lesson content) and `LICENSE-CODE` (MIT, 2026, "AI-Hydro contributors"; scripts, tests, shared and tools code, and the code inside lessons). README and CONTRIBUTING gain a Licence section; bundled data keeps its source licences (`PROVENANCE.json`). Every manifest and the course already say `CC-BY-4.0`: no conflict. +- A lesson may be standalone: `tests/test_repo.py` no longer requires every module to be in the flagship course. Kept: valid manifest, unique `moduleId`, course members exist with matching `courseId`/`courseOrder`. `validate_manifests.py` now also rejects a `courseId`/`courseOrder` on a module no course lists. +- `tests/test_wave2_repo.py`: the total page-growth budget (1.5 MB over the Wave 1 baseline, 1.13 MB already used) is removed so new lessons can be added; the 250,000-byte cap per page stays. +- CONTRIBUTING: complete checklist against the actual checks (CHANGELOG heading, theme-ratchet baseline, quiz shape, DOI gate, page cap, generated files), a Licence and a Credit section; optional manifest `contributors`. +- `CITATION.cff`, `CONTRIBUTORS.md` generated by `scripts/gen_contributors.py` (`--check` runs in `checks.yml`). Humans only; an entry naming an AI tool goes to an "AI assistance" note. +- Reaction counts: the `refresh-reactions` job and the manual dispatch are removed from `build-api.yml` (Discussions are disabled on this repository, so every count was 0). `githubReactions` stays in the API because the extension reads it; it is documented as not refreshed. + ## 2026-11-30 — Trust anchor (ADR-010 Amendment 1, step 1) No lesson content changed; module versions are unchanged. diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 0000000..67d92bd --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,20 @@ +cff-version: 1.2.0 +message: "If you use these lessons or code, please cite them as below (no DOI has been issued yet)." +title: "AI-Hydro Learning Modules" +type: dataset +authors: + - family-names: Galib + given-names: Mohammad + affiliation: "Purdue University" +repository-code: "https://github.com/AI-Hydro/Modules" +url: "https://github.com/AI-Hydro/Modules" +license: CC-BY-4.0 +abstract: >- + Interactive hydrology lessons and courses for AI-Hydro: self-contained HTML modules with + executable Python cells, a static catalogue API, and the scripts that build and check them. + Lesson content is CC BY 4.0; code is MIT (see LICENSE and LICENSE-CODE). +keywords: + - hydrology + - education + - interactive learning + - AI-Hydro diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c46b912..6a94f25 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,16 +2,48 @@ ## Quick checklist -- [ ] `modules//module.html` — the self-contained module -- [ ] `modules//manifest.json` — metadata (required fields below) -- [ ] `modules//README.md` — description, learning objectives, prerequisites -- [ ] `modules//thumbnail.png` — 640×360 screenshot (optional but recommended) -- [ ] Module renders correctly in a plain browser with no AI-Hydro bridge (standalone rule below) -- [ ] Module opens without CSP errors in AI-Hydro HTML Preview (`python scripts/check_csp.py` is clean) -- [ ] At least one interactive element (slider, quiz, map, chart) -- [ ] A checkpoint built with the shared quiz engine, with at least one numeric or interpretive item whose answer is computed from the lesson -- [ ] Provenance footer with data sources and citations -- [ ] `python scripts/build_modules.py`, `python scripts/gen_docs.py` and the tests pass (see "Checks") +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. + +Files +- [ ] `modules//module.html`: the self-contained lesson, under 250,000 bytes [`test_wave2_repo`]. The directory name is the `moduleId` (lowercase, hyphens) +- [ ] `modules//manifest.json`: metadata (fields below) [`validate_manifests.py`] +- [ ] `modules//README.md`: description, learning objectives, prerequisites (its presence is checked) [`validate_manifests.py`] +- [ ] `modules//thumbnail.png`: 640x360 screenshot (optional but recommended) +- [ ] `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`] + +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`] +- [ ] Opens without CSP errors: `python scripts/check_csp.py` is clean (no external scripts; Google Fonts is the only external host, at most two font links) +- [ ] **Human review:** every control that works by dragging also works from the keyboard (see Accessibility rules). CI only checks the structural hygiene: no inline `onclick`/`oninput`/`onchange`/`onkeydown`, no `contenteditable`, no `postMessage` to `'*'`, nothing "locked" [`tests/test_wave2_repo.py::test_hygiene`] +- [ ] The checkpoint uses the shared quiz engine and has **at least 4 items, at least 3 of type `choice`, and at least 1 `numeric` item whose answer is a function computed from the lesson** (not a typed number). Every item has an `explain`, and each choice's `correct` index is in range [`tests/test_quiz_answers.py`]. The course certificate is the only lesson without a checkpoint +- [ ] **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) +- [ ] `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) +- [ ] Every command in "Checks" below passes locally + +## Licence of what you contribute + +By opening a pull request you agree to license your contribution as follows (full texts: `LICENSE`, `LICENSE-CODE`): + +- **Lesson content** (the text, figures, diagrams and course materials in `module.html`, `README.md` and `courses/`) is **CC BY 4.0**. The manifest `license` field is the **content** licence and `tests/test_wave2_repo.py` requires exactly `CC-BY-4.0`. Code copied out of a lesson is MIT (see `LICENSE-CODE`). +- **Code** (`scripts/`, `tests/`, `shared/`, `tools/`, and the Python and JavaScript in lessons) is **MIT**. +- **Data files** may carry their own source licences (CAMELS-US and USGS NWIS, Daymet, Copernicus and others). Keep the notice in `data/PROVENANCE.json` (`licence_note`), cite the source, and do not bundle data whose licence forbids redistribution. +- Only submit work you have the right to license. Say in the pull-request description if AI tools helped; they are not listed as authors. + +Attribution expected from reuse of a lesson: the author(s) named in its `manifest.json` (`CONTRIBUTORS.md` lists everyone), the lesson title, the repository URL and the licence (see `CITATION.cff`). + +## Credit + +`author` is a person, written `"Name, Institution"`. People who helped but are not the lead author go in the optional `contributors` list of the same strings. `CONTRIBUTORS.md` is generated from these fields by `python scripts/gen_contributors.py`; CI fails if it is stale. AI tools are not authors: an entry that names one is moved to the "AI assistance" note of that file. ## Required manifest fields @@ -35,6 +67,8 @@ } ``` +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`. + **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). @@ -128,6 +162,7 @@ These run on every pull request (`.github/workflows/checks.yml`) and are the sam python scripts/build_modules.py --check # shared code, data, manifests and static outputs are inlined python scripts/render_static_outputs.py --check # a cell's pre-rendered output matches its current source python scripts/gen_docs.py --check # README table and course page match the manifests +python scripts/gen_contributors.py --check # CONTRIBUTORS.md matches the manifests python scripts/validate_manifests.py # manifests valid; embedded block agrees; course graph valid 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) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md new file mode 100644 index 0000000..6cfa13e --- /dev/null +++ b/CONTRIBUTORS.md @@ -0,0 +1,13 @@ +# Contributors + +Generated by `python scripts/gen_contributors.py` from the `author` and `contributors` fields of `modules/*/manifest.json` and `courses/*/course.json`. Do not edit by hand: change the manifest, run the script and commit both. `--check` runs in CI. + +People are credited for authoring or contributing to a lesson or course. Lesson content is licensed [CC BY 4.0](LICENSE) (attribute the authors named in the manifest and the Sources section of the lesson); code is [MIT](LICENSE-CODE). + +| Name | Affiliation | Roles | Work | +|---|---|---|---| +| Mohammad Galib | Purdue University | author, maintainer | module `baseflow-separation`; module `capstone-basin-story`; module `course-certificate`; module `dem-to-twi`; module `evapotranspiration-budyko`; module `precipitation-point-to-basin`; module `reading-a-hydrograph`; module `real-streamflow-data`; module `runoff-generation`; module `water-cycle-in-motion`; module `watershed-runoff`; course `intro-hydro-2026` | + +## AI assistance + +AI tools can assist with drafting and code in this repository. They are not authors and are not credited in the table above: a person is responsible for each lesson, and the pull-request review is the control (see the Security review in [CONTRIBUTING.md](CONTRIBUTING.md)). Disclose AI assistance in the pull-request description; add a line to `README.md` of the lesson if it matters for readers. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..92d06be --- /dev/null +++ b/LICENSE @@ -0,0 +1,396 @@ +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public licenses. +Notwithstanding, Creative Commons may elect to apply one of its public +licenses to material it publishes and in those instances will be +considered the “Licensor.” The text of the Creative Commons public +licenses is dedicated to the public domain under the CC0 Public Domain +Dedication. Except for the limited purpose of indicating that material +is shared under a Creative Commons public license or as otherwise +permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the public +licenses. + +Creative Commons may be contacted at creativecommons.org. + diff --git a/LICENSE-CODE b/LICENSE-CODE new file mode 100644 index 0000000..c58aa8e --- /dev/null +++ b/LICENSE-CODE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2026 AI-Hydro contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/PROGRESS.md b/PROGRESS.md index a36e483..033a255 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -45,3 +45,9 @@ Added per-file sha256 and `content_sha256` to the generated API, the risky-call Verification: `/opt/miniconda3/bin/python -s -E -m pytest tests`, `node --test tests/js/*.test.js` and the scripts of the PR workflow. Not done: the ruleset's required-review rule (owner setting; blocked by the `build-api.yml` push to `main`), and Studio-side verification of the hashes (step 2, extension repository). +## 2026-11-30 — Contribution-ready (branch feat/contrib-ready, stacked on PR #8) + +Implemented the pre-AGU contribution fixes of `docs/vision-2040/findings/skills-community-scout-2026-11-30.md` (see CHANGELOG.md): licences, standalone lessons, CITATION.cff and CONTRIBUTORS.md, reactions job removed, complete CONTRIBUTING checklist. +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. + diff --git a/README.md b/README.md index e2e6275..be41968 100644 --- a/README.md +++ b/README.md @@ -31,9 +31,10 @@ The table is generated from `modules/*/manifest.json` by `python scripts/gen_doc ## Contribute a module 1. Fork this repository -2. Create `modules//` with `module.html`, `manifest.json`, `README.md`, and optionally `thumbnail.png` -3. Your `manifest.json` must include: `moduleId`, `title`, `description`, `author`, `license`, `topic`, `level`, `estimatedMinutes` -4. Open a pull request — CI will validate the manifest and check for CSP violations +2. Create `modules//` with `module.html`, `manifest.json`, `README.md`, and optionally `thumbnail.png`. A lesson can stand alone; it does not have to join a course +3. Your `manifest.json` must include: `moduleId`, `title`, `description`, `version`, `author`, `license`, `topic`, `level`, `estimatedMinutes`, `tags`, `requires` +4. Add a `CHANGELOG.md` entry and a theme-ratchet baseline entry, and regenerate the generated files (CONTRIBUTING.md has the full checklist) +5. Open a pull request: CI validates the manifest, the quiz, the API hashes and CSP, and a maintainer reviews the code in the lesson See [CONTRIBUTING.md](CONTRIBUTING.md) for the full authoring guide and checklist. @@ -47,6 +48,10 @@ The static API is generated by GitHub Actions (`scripts/build_api.py`) from the `certification.metadata_complete` means the manifest is complete, not that the science was reviewed; `certification.scientific_review` is `null` until a human records one. -## License +## Licence -Individual modules carry their own licenses (default CC-BY-4.0). Repository infrastructure is MIT. +- **Lesson content** (module text, figures and course materials) is licensed [CC BY 4.0](LICENSE). Reuse it with attribution to the authors named in the module's `manifest.json` (see [CONTRIBUTORS.md](CONTRIBUTORS.md)), a link to this repository and a note of any changes. +- **Code** (`scripts/`, `tests/`, `shared/`, `tools/`, and the Python and JavaScript inside lessons) is licensed [MIT](LICENSE-CODE). +- **Data** bundled in lessons keeps the licence of its source (CAMELS-US and USGS NWIS, Daymet, Copernicus); see each module's `data/PROVENANCE.json`. + +To cite the repository, see [CITATION.cff](CITATION.cff). diff --git a/api/README.md b/api/README.md index 0f7c2a7..5887cd5 100644 --- a/api/README.md +++ b/api/README.md @@ -12,7 +12,7 @@ An array, one entry per `modules//manifest.json`, sorted by module id. Every | `downloadUrl`, `githubUrl` | manifest value, else derived from `moduleId` | | `createdAt` | manifest value, else the date of the first git commit touching `modules//` | | `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; reactions are refreshed from GitHub Discussions by the workflow | +| `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 | | `files`, `content_sha256` | the trust anchor, see below | diff --git a/scripts/build_api.py b/scripts/build_api.py index 6e92357..34bfbee 100644 --- a/scripts/build_api.py +++ b/scripts/build_api.py @@ -65,6 +65,7 @@ def build_modules(existing: dict[str, dict]) -> list[dict]: data.setdefault("createdAt", git_date(f"modules/{module_id}", first=True) or prev.get("createdAt")) data["updatedAt"] = git_date(f"modules/{module_id}") or prev.get("updatedAt") or data["createdAt"] data.setdefault("downloadCount", prev.get("downloadCount", 0)) + # not refreshed (Discussions are disabled on this repository); the extension still reads the field data.setdefault("githubReactions", prev.get("githubReactions", 0)) data.setdefault("discussionUrl", prev.get("discussionUrl", "")) data.setdefault("isFeatured", False) diff --git a/scripts/gen_contributors.py b/scripts/gen_contributors.py new file mode 100644 index 0000000..367c3fd --- /dev/null +++ b/scripts/gen_contributors.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Generate CONTRIBUTORS.md from the people named in the manifests. + +Sources (nothing else, so the list cannot disagree with what the API and the lessons say): + modules//manifest.json "author" "Name, Institution" (required) + "contributors" ["Name, Institution", ...] (optional) + courses//course.json "authors" [{name, affiliation, roles?}, ...] + "contributors" same shape as authors (optional) + +Handles are not linked (a handle in a manifest is not verified here). + +Humans only. A name is classified by three simple rules (never by a word anywhere in the name, so +"Claude Monet" or "Maria Bot" stay people): + AI tool the whole name (trimmed, case-insensitive) is in AI_NAMES ("AI-Hydro Agent", "Claude", + "ChatGPT", "Copilot", ...), or it ends in "[bot]", or its last word is "Agent" or "Bot" and + it has no other word that looks like a personal name (an "AI-Hydro Agent" has none). + Not credited: listed in the "AI assistance" note, a notice is printed, and the test fails + until the manifest is fixed (AI assistance is disclosed, it is not authorship). + organisation the whole name is in ORG_NAMES ("AI-Hydro Team", ...). Listed under "Not attributed to an + individual"; not an error. +Escape hatch: a manifest (or course author entry) with `"human_confirmed": true` is always a person. + +Usage: python scripts/gen_contributors.py rewrite CONTRIBUTORS.md + python scripts/gen_contributors.py --check exit 1 if CONTRIBUTORS.md is out of date +""" +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from repo_lib import ROOT, courses, manifests # noqa: E402 + +OUT = ROOT / "CONTRIBUTORS.md" +AI_NAMES = {"ai-hydro agent", "claude", "chatgpt", "copilot", "github copilot", "gemini", "codex", "gpt-4", "gpt-5", "llm", + "ai assistant", "ai-hydro assistant", "ai"} +ORG_NAMES = {"ai-hydro team", "ai-hydro contributors", "ai-hydro", "the ai-hydro team"} + + +def classify(name: str, confirmed: bool = False) -> str: + """'human', 'ai' or 'org' (see the module docstring).""" + n = " ".join(name.split()).casefold() + if confirmed: + return "human" + if n in ORG_NAMES: + return "org" + if n in AI_NAMES or n.endswith("[bot]"): + return "ai" + words = n.split() + if len(words) > 1 and words[-1] in ("agent", "bot"): + others = [w for w in words[:-1] if w not in ("ai-hydro", "ai", "the")] + if not others: + return "ai" + return "human" + + +def cell(text: str) -> str: + return text.replace("|", "\\|") + + +def split_person(text: str) -> tuple[str, str]: + name, _, affiliation = text.partition(",") + return name.strip(), affiliation.strip() + + +def collect() -> tuple[dict, list, list]: + """Return ({casefolded name: {name, affiliation, works, roles}}, AI-tool findings, organisational labels).""" + people: dict[str, dict] = {} + ai: list[tuple[str, str, str]] = [] + orgs: list[tuple[str, str, str]] = [] + + def add(name: str, affiliation: str, work: str, role: str, confirmed: bool = False) -> None: + if not name: + return + kind = classify(name, confirmed) + if kind == "ai": + ai.append((name, work, role)) + return + if kind == "org": + orgs.append((name, work, role)) + return + p = people.setdefault(name.casefold(), {"name": name, "affiliation": "", "works": [], "roles": set()}) + p["affiliation"] = p["affiliation"] or affiliation + if work not in p["works"]: + p["works"].append(work) + p["roles"].add(role) + + for mid, m in manifests().items(): + work = f"module `{mid}`" + confirmed = bool(m.get("human_confirmed")) + add(*split_person(m.get("author") or ""), work, "author", confirmed) + for c in m.get("contributors", []): + add(*split_person(c), work, "contributor", confirmed) + for path, c in courses(): + work = f"course `{c['courseId']}`" + for key, role in (("authors", "author"), ("contributors", "contributor")): + for a in c.get(key, []): + if isinstance(a, str): + a = dict(zip(("name", "affiliation"), split_person(a))) + add((a.get("name") or "").strip(), (a.get("affiliation") or "").strip(), work, + "maintainer" if "maintainer" in (a.get("roles") or []) else role, bool(a.get("human_confirmed"))) + return people, ai, orgs + + +def render() -> tuple[str, list]: + """(text, AI-tool findings). Organisational labels are listed but are not findings.""" + people, ai, orgs = collect() + L = ["# Contributors", "", + "Generated by `python scripts/gen_contributors.py` from the `author` and `contributors` fields of " + "`modules/*/manifest.json` and `courses/*/course.json`. Do not edit by hand: change the manifest, " + "run the script and commit both. `--check` runs in CI.", "", + "People are credited for authoring or contributing to a lesson or course. Lesson content is licensed " + "[CC BY 4.0](LICENSE) (attribute the authors named in the manifest and the Sources section of the lesson); " + "code is [MIT](LICENSE-CODE).", ""] + if people: + L += ["| Name | Affiliation | Roles | Work |", "|---|---|---|---|"] + for key in sorted(people): + p = people[key] + L.append(f"| {cell(p['name'])} | {cell(p['affiliation'])} | {', '.join(sorted(p['roles']))} | {cell('; '.join(p['works']))} |") + L.append("") + if orgs: + L += ["## Not attributed to an individual", "", + "Organisational labels found in the manifests. Name the responsible person in `author` instead.", ""] + L += [f"- {n} ({role} of {w})" for n, w, role in orgs] + L.append("") + L += ["## AI assistance", "", + "AI tools can assist with drafting and code in this repository. They are not authors and are not credited " + "in the table above: a person is responsible for each lesson, and the pull-request review is the control " + "(see the Security review in [CONTRIBUTING.md](CONTRIBUTING.md)). Disclose AI assistance in the pull-request " + "description; add a line to `README.md` of the lesson if it matters for readers.", ""] + if ai: + L += ["Entries naming an AI tool found in the manifests (moved here from the credits; remove them from the manifest):", ""] + L += [f"- {n} ({role} of {w})" for n, w, role in ai] + L.append("") + return "\n".join(L).rstrip("\n") + "\n", ai + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--check", action="store_true", help="exit 1 if CONTRIBUTORS.md is out of date") + args = ap.parse_args() + text, ai = render() + for n, w, role in ai: + print(f"notice: {n!r} ({role} of {w}) names an AI tool; not credited as a person", file=sys.stderr) + if args.check: + if not OUT.exists() or OUT.read_text(encoding="utf-8") != text: + print("stale: CONTRIBUTORS.md (run python scripts/gen_contributors.py)") + return 1 + print("CONTRIBUTORS.md is up to date") + return 0 + OUT.write_text(text, encoding="utf-8") + print("wrote CONTRIBUTORS.md") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/validate_manifests.py b/scripts/validate_manifests.py index 868bc49..bd66838 100644 --- a/scripts/validate_manifests.py +++ b/scripts/validate_manifests.py @@ -9,7 +9,8 @@ (scripts/build_modules.py embedded_manifest), so the two never disagree; * the module footer shows the manifest version; * each course.json lists only modules that exist, its prerequisite graph is acyclic and refers to - modules of the course, and each module's courseId / courseOrder match the course. + modules of the course, and each module's courseId / courseOrder match the course; a module no course lists is standalone and + must carry neither field. Usage: python scripts/validate_manifests.py """ @@ -56,6 +57,8 @@ def check_module(d: Path) -> list[str]: errs.append(f"{d.name}: estimatedMinutes must be a positive integer") if not (isinstance(m["tags"], list) and all(isinstance(t, str) and t for t in m["tags"])): errs.append(f"{d.name}: tags must be a non-empty list of strings") + if "contributors" in m and not (isinstance(m["contributors"], list) and all(isinstance(c, str) and c.strip() for c in m["contributors"])): + errs.append(f"{d.name}: contributors must be a list of \"Name, Institution\" strings") if "citation" in m and not (isinstance(m["citation"], dict) and str(m["citation"].get("text", "")).strip()): errs.append(f"{d.name}: citation must be an object with text") html = (d / "module.html").read_text(encoding="utf-8") @@ -124,6 +127,17 @@ def main() -> int: ids = {d.name for d in dirs} for path, c in courses(): errs += check_course(path, c, ids) + # a module is standalone or a member of exactly one course: it may not claim a course that does not list it + members = {m["id"] for _, c in courses() for m in c.get("modules", [])} + for d in dirs: + mp = d / "manifest.json" + if mp.exists() and d.name not in members: + try: + man = read_json(mp) + except json.JSONDecodeError: + continue + if "courseId" in man or "courseOrder" in man: + errs.append(f"{d.name}: manifest has courseId/courseOrder but no course.json lists it (remove them for a standalone lesson)") for e in errs: print("FAIL " + e) if not errs: diff --git a/tests/test_citation_cff.py b/tests/test_citation_cff.py new file mode 100644 index 0000000..1034eb9 --- /dev/null +++ b/tests/test_citation_cff.py @@ -0,0 +1,24 @@ +"""Shape check of CITATION.cff (no cffconvert here; run `cffconvert --validate` once in CI or by the owner).""" +import re + +import pytest + +from helpers import ROOT + +SPDX = {"CC-BY-4.0", "MIT"} + + +def load(): + yaml = pytest.importorskip("yaml") + return yaml.safe_load((ROOT / "CITATION.cff").read_text(encoding="utf-8")) + + +def test_citation_cff_has_the_required_keys_and_a_valid_licence(): + c = load() + assert c["cff-version"] == "1.2.0" + for k in ("message", "title", "authors"): + assert c[k], k + assert c["authors"] and all("family-names" in a or "name" in a for a in c["authors"]) + assert c["license"] in SPDX and c["license"] == "CC-BY-4.0" + assert re.fullmatch(r"https://github\.com/AI-Hydro/Modules", c["repository-code"]) + assert "doi" not in c # none issued yet diff --git a/tests/test_contributors.py b/tests/test_contributors.py new file mode 100644 index 0000000..496157f --- /dev/null +++ b/tests/test_contributors.py @@ -0,0 +1,51 @@ +"""CONTRIBUTORS.md is generated from the manifests; only people are credited.""" +import sys + +from helpers import ROOT + +sys.path.insert(0, str(ROOT / "scripts")) +import gen_contributors # noqa: E402 + + +def test_contributors_file_is_current(): + text, ai = gen_contributors.render() + assert (ROOT / "CONTRIBUTORS.md").read_text(encoding="utf-8") == text + assert ai == [], "an AI tool is named as an author in a manifest" + + +def test_ai_tools_are_not_credited_as_people(monkeypatch): + mans = {"x": {"author": "AI-Hydro Agent, AI-Hydro", "contributors": ["Ada Lovelace, Analytical Society", "Claude", "AI-Hydro Team"]}} + monkeypatch.setattr(gen_contributors, "manifests", lambda: mans) + monkeypatch.setattr(gen_contributors, "courses", lambda: []) + text, ai = gen_contributors.render() + assert [a[0] for a in ai] == ["AI-Hydro Agent", "Claude"] + assert "| Ada Lovelace |" in text and "| AI-Hydro Agent |" not in text + assert "AI-Hydro Agent (author of module `x`)" in text + + +import pytest # noqa: E402 + + +@pytest.mark.parametrize("name", ["Claude Monet", "Maria Bot", "Codex Ng", "Ana Gemini", "Gemma Copilot-Smith"]) +def test_real_people_are_not_false_positives(name): + assert gen_contributors.classify(name) == "human" + + +@pytest.mark.parametrize("name", ["AI-Hydro Agent", "ChatGPT", "dependabot[bot]", "claude", "AI assistant", "GitHub Copilot"]) +def test_ai_tool_names_are_caught(name): + assert gen_contributors.classify(name) == "ai" + + +def test_organisational_label_is_listed_not_failed(monkeypatch): + monkeypatch.setattr(gen_contributors, "manifests", lambda: {"x": {"author": "AI-Hydro Team"}}) + monkeypatch.setattr(gen_contributors, "courses", lambda: []) + text, ai = gen_contributors.render() + assert ai == [] and "## Not attributed to an individual" in text and "- AI-Hydro Team (author of module `x`)" in text + + +def test_human_confirmed_overrides_and_none_name_and_pipes_are_safe(monkeypatch): + mans = {"x": {"author": "Claude, Somewhere | Else", "human_confirmed": True}} + monkeypatch.setattr(gen_contributors, "manifests", lambda: mans) + monkeypatch.setattr(gen_contributors, "courses", lambda: [(None, {"courseId": "c", "authors": [{"name": None}]})]) + text, ai = gen_contributors.render() + assert ai == [] and "| Claude | Somewhere \\| Else |" in text diff --git a/tests/test_quiz_answers.py b/tests/test_quiz_answers.py index 12dcf96..47d3526 100644 --- a/tests/test_quiz_answers.py +++ b/tests/test_quiz_answers.py @@ -41,7 +41,7 @@ def test_each_checkpoint_keeps_its_three_content_questions_and_adds_computed_one assert len(items) >= 4, mod assert sum(1 for i in items if i["type"] == "choice") >= 3, mod numeric = [i for i in items if i["type"] == "numeric"] - assert numeric or any(i["id"] in ("q5",) for i in items), mod + assert numeric, mod # at least one numeric item (every current lesson has one) for i in numeric: assert isinstance(i["expected"], (int, float)) and math.isfinite(i["expected"]) for i in items: diff --git a/tests/test_repo.py b/tests/test_repo.py index 540fccb..2953649 100644 --- a/tests/test_repo.py +++ b/tests/test_repo.py @@ -19,17 +19,31 @@ def embedded(mod): return json.loads(m.group(1)) -def test_every_course_module_exists_and_every_directory_has_a_manifest(): - course = json.loads((ROOT / "courses/intro-to-hydrology/course.json").read_text()) - for m in course["modules"]: - assert (MODULES / m["id"] / "module.html").exists(), m["id"] +def test_every_directory_has_a_manifest_and_course_members_exist(): + """A module may be standalone (no courseId) or belong to a course. Either way: valid manifest, + unique id, and every course member must exist with a matching courseId and courseOrder.""" + ids = [] for mod in IDS: assert (MODULES / mod / "manifest.json").exists(), mod - # the module directories and the course are the same set, in the manifests' courseOrder - assert sorted(m["id"] for m in course["modules"]) == IDS - for i, m in enumerate(course["modules"], 1): - man = json.loads((MODULES / m["id"] / "manifest.json").read_text()) - assert man["courseOrder"] == i, m["id"] + ids.append(json.loads((MODULES / mod / "manifest.json").read_text())["moduleId"]) + assert len(ids) == len(set(ids)), "moduleId values must be unique" + course_ids = set() + members = set() + for cpath in sorted((ROOT / "courses").glob("*/course.json")): + course = json.loads(cpath.read_text()) + course_ids.add(course["courseId"]) + for i, m in enumerate(course["modules"], 1): + assert (MODULES / m["id"] / "module.html").exists(), m["id"] + man = json.loads((MODULES / m["id"] / "manifest.json").read_text()) + assert man["courseId"] == course["courseId"], m["id"] + assert man["courseOrder"] == i, m["id"] + assert m["id"] not in members, f"{m['id']} listed in two courses" + members.add(m["id"]) + for mod in IDS: + man = json.loads((MODULES / mod / "manifest.json").read_text()) + if mod not in members: + # standalone: no course claims it, so it must not claim a course either + assert "courseId" not in man and "courseOrder" not in man, mod @pytest.mark.parametrize("mod", IDS) diff --git a/tests/test_wave2_repo.py b/tests/test_wave2_repo.py index 1d74e01..bc6dfeb 100644 --- a/tests/test_wave2_repo.py +++ b/tests/test_wave2_repo.py @@ -19,8 +19,7 @@ import validate_manifests # noqa: E402 IDS = sorted(p.name for p in MODULES.iterdir() if p.is_dir()) -BASELINE_TOTAL_BYTES = 671_451 # sum of the eight module.html files at the Wave 1 head (b7d833d) -MAX_GROWTH_BYTES = 1_500_000 +MAX_PAGE_BYTES = 250_000 # hard cap per module.html; there is no total budget, so new lessons can be added def script(name, *args): @@ -145,13 +144,14 @@ def test_build_api_workflow_triggers_and_runs_the_script(): assert {"modules/**", "courses/**", "shared/**"} <= set(on["push"]["paths"]) text = (ROOT / ".github/workflows/build-api.yml").read_text() assert "scripts/build_api.py" in text and "fetch-depth: 0" in text - assert "api/courses.json" in text assert "datetime" not in text - # ADR-010: main is verified, never committed to by the bot; refreshes go to a reviewed branch + # ADR-010: main is verified, never committed to by the bot. Discussions are disabled, so there is no + # reaction refresh job (and nothing in the workflow writes to the repository). assert "scripts/build_api.py --check" in text - assert "git push origin \"$branch\"" in text - assert "schedule" not in on - assert "git push && exit 0" not in text + assert "schedule" not in on and "workflow_dispatch" not in on + assert set(wf["jobs"]) == {"verify"} + assert "refresh-reactions" not in text and "discussions" not in text + assert "git push" not in text and "contents: write" not in text def test_pr_workflow_runs_every_check(): @@ -159,7 +159,7 @@ def test_pr_workflow_runs_every_check(): assert "pull_request" in wf.get("on", wf.get(True)) text = (ROOT / ".github/workflows/checks.yml").read_text() for cmd in ["scripts/build_modules.py --check", "scripts/render_static_outputs.py --check", "scripts/gen_docs.py --check", - "scripts/validate_manifests.py", "scripts/check_csp.py", "scripts/build_api.py --check", "pytest tests", "node --test tests/js"]: + "scripts/gen_contributors.py --check", "scripts/validate_manifests.py", "scripts/check_csp.py", "scripts/build_api.py --check", "pytest tests", "node --test tests/js"]: assert cmd in text, cmd @@ -243,12 +243,10 @@ def test_every_executable_cell_ships_a_pre_rendered_output(mod): assert 'src="data:image/png;base64,' in img -def test_page_size_growth_stays_under_the_budget_and_is_reported(): - sizes = {m: len((MODULES / m / "module.html").read_bytes()) for m in IDS} - growth = sum(sizes.values()) - BASELINE_TOTAL_BYTES - assert growth < MAX_GROWTH_BYTES, f"{growth} bytes added in total" - for mod, sz in sizes.items(): - assert sz < 250_000, (mod, sz) +def test_every_page_stays_under_the_size_cap(): + for mod in IDS: + sz = len((MODULES / mod / "module.html").read_bytes()) + assert sz < MAX_PAGE_BYTES, (mod, sz) # ── hygiene ──────────────────────────────────────────────────────────────────────────────────