diff --git a/.github/workflows/resources.yml b/.github/workflows/resources.yml index 22f3b62..87a7247 100644 --- a/.github/workflows/resources.yml +++ b/.github/workflows/resources.yml @@ -4,54 +4,63 @@ on: push: paths: - "resources/**" + - "tests/**" - "scripts/check-resources.py" - "scripts/render-resource-guides.py" - "scripts/new-course-workspace" - - "templates/course-workspace/resources.md" - ".github/workflows/resources.yml" pull_request: paths: - "resources/**" + - "tests/**" - "scripts/check-resources.py" - "scripts/render-resource-guides.py" - "scripts/new-course-workspace" - - "templates/course-workspace/resources.md" - ".github/workflows/resources.yml" jobs: resource-check: runs-on: ubuntu-latest steps: - - name: Checkout workspace + - name: Checkout Workspace uses: actions/checkout@v4 - - name: Checkout canonical OEE curriculum + - name: Checkout OEE for unmapped course scaffolding uses: actions/checkout@v4 with: repository: 0xbuffdev/open-engineering-education path: _oee persist-credentials: false - - name: Validate catalogue and OEE course mappings - run: python3 scripts/check-resources.py --oee _oee - - name: Verify rendered resource guides + - name: Validate catalogue only (no active v1 maps) + run: python3 scripts/check-resources.py + - name: Reject stale generated reading guides run: python3 scripts/render-resource-guides.py --check - - name: Test course generator and learner file protection + - name: Strict v2 shape and pinned export regression suite + run: python3 -m unittest discover -s tests -p 'test_*.py' -v + - name: Verify unmapped scaffolding and preserve learner files shell: bash run: | set -euo pipefail bash -n scripts/new-course-workspace - dir="$(mktemp -d)" - trap 'rm -rf "$dir"' EXIT - mkdir -p "$dir/learner" "$dir/other" - OEE_REPO="$PWD/_oee" bash scripts/new-course-workspace SEF SEF1 "$dir/learner" - plan="$dir/learner/notes/SEF/SEF1/reading-plan.md" - log="$dir/learner/notes/SEF/SEF1/resources.md" - test -s "$plan" - grep -q "Module 10 — Hardware, Software & Booting" "$plan" + temp="$(mktemp -d)" + trap 'rm -rf "$temp"' EXIT + mkdir -p "$temp/learner" "$temp/other" + OEE_REPO="$PWD/_oee" bash scripts/new-course-workspace SEF SEF1 "$temp/learner" + plan="$temp/learner/notes/SEF/SEF1/reading-plan.md" + log="$temp/learner/notes/SEF/SEF1/resources.md" + test ! -e "$plan" printf '\nLearner-owned entry\n' >> "$log" - if OEE_REPO="$PWD/_oee" bash scripts/new-course-workspace SEF SEF1 "$dir/learner"; then + if OEE_REPO="$PWD/_oee" bash scripts/new-course-workspace SEF SEF1 "$temp/learner"; then echo "ERROR: existing learner directories were overwritten" >&2 exit 1 fi grep -q "Learner-owned entry" "$log" - OEE_REPO="$PWD/_oee" bash scripts/new-course-workspace SEF SEF2 "$dir/other" - test ! -e "$dir/other/notes/SEF/SEF2/reading-plan.md" + OEE_REPO="$PWD/_oee" bash scripts/new-course-workspace SEF SEF2 "$temp/other" + test ! -e "$temp/other/notes/SEF/SEF2/reading-plan.md" + # Legacy source formats are not supported, even without a resource map. + mkdir -p "$temp/legacy-oee/curriculum/SEF" "$temp/legacy-learner" + printf '**Specification:** `v0.1.0`\n' > "$temp/legacy-oee/curriculum/SEF/SEF1.md" + if OEE_REPO="$temp/legacy-oee" bash scripts/new-course-workspace SEF SEF1 "$temp/legacy-learner"; then + echo "ERROR: legacy OEE format was accepted" >&2 + exit 1 + fi + test ! -e "$temp/legacy-learner/notes/SEF/SEF1" diff --git a/README.md b/README.md index ad00ca5..da6e41d 100644 --- a/README.md +++ b/README.md @@ -145,9 +145,9 @@ A completion claim should be supported by inspectable evidence, not by a checked ## Public study resources -The [public resource library](resources/README.md) contains book and online references mapped to canonical OEE modules, as well as generated Markdown study guides. These resources support, but do not replace, the OEE curriculum. Chapter and section entries have verification labels; a module marked partial still has unresolved research gaps. +The [public resource library](resources/README.md) contains optional book and online resources and a strict v2 mapping schema. Its historical SEF1 mapping and guide have been retired because they describe a different curriculum. No reviewed v2 course mapping or guide is currently published. -For a mapped course, the generator validates the mapping against the local OEE checkout and produces a portable `reading-plan.md`. Python 3 is needed for this step. Public resource guides are separate from the private 0xNAND instructional content. Course generation never overwrites existing learner directories. +Courses currently initialize **without a reading-plan snapshot** while the new v2 map undergoes pinned-source and human editorial review. Learner-owned `resources.md` remains available, and existing learner directories are never overwritten. Public resources stay independent of private 0xNAND content. ## Evidence and reproducibility diff --git a/resources/README.md b/resources/README.md index 2944cd3..d9cf857 100644 --- a/resources/README.md +++ b/resources/README.md @@ -1,50 +1,38 @@ -# Public OEE resource library (SEF1 pilot) +# Public OEE resource library -This is the **public resource index** for [Open Engineering Education](https://github.com/0xbuffdev/open-engineering-education) independent study. +This library supports independent study of [Open Engineering Education](https://github.com/0xbuffdev/open-engineering-education). OEE owns course requirements, outcomes and assessments. This free Workspace owns optional resource recommendations and learner-authored records. -## Ownership +## Current mapping status -- **OEE** owns curriculum, outcomes, lesson order, assessments and completion requirements. -- **OEE Workspace** owns public resource metadata and optional course/module/lesson mappings. -- **Private 0xNAND Content** may import these mappings but adds its own instructional implementation. No private authored lessons are published here. +**No active reviewed course map or generated study guide is published.** The former SEF1 schema-v1 mapping describes a different curriculum. It is now a deliberately rejected [negative test fixture](../tests/fixtures/resource-map-v1-SEF1.json) and remains in Git history; its chapter assignments must not be transferred by module number. -## Browse +The public catalogue remains available: [books](catalog/books/) and [online resources](catalog/online/). The single [active mapping schema](schemas/course-map.schema.json) is **v2 only**, with an explicit OEE specification v0.2.0, exact 40-character lowercase source commit, canonical path, and optional outcome/assessment references. Module numbers, lesson locators and reading recommendations are scoped to the recorded revision. -- [SEF1 draft resource mapping](mappings/SEF/SEF1.json) -- [Book catalog](catalog/books/) and [online resources](catalog/online/) -- [Resource schema](schemas/resource.schema.json) and [mapping schema](schemas/course-map.schema.json) +The replacement SEF1 mapping requires independent editorial review under WS-I02. Until then, learner workspaces can be created **without a reading plan**; this is not an OEE completion gap. -Resource identifiers **B1, B7, B46, R89 and R90** are preserved from the private legacy catalogue. Define each resource once and reference its ID from any number of course maps. A course mapping follows the *current OEE module order*, not a textbook's chapter order. +## Editorial principles -This pilot uses JSON rather than YAML so that Python 3's standard library can validate and consume resources offline without additional dependencies. +- No legacy schema reader, converter, or automatic remapping. Historical data is not current guidance. +- Every map must reference one canonical OEE revision and carry a draft or reviewed mapping status. Valid JSON is not certification of educational meaning. +- Coverage is mapped, partial, or unmapped. Partial/unmapped require explicit gap explanations. Verified mapping claims need independent edition, section, or authoritative website checks. +- Catalogue IDs are stable and reusable, with optional resource-specific lesson, outcome and assessment references. References must exist in the exact selected OEE Toolkit export. +- Paid resources are always optional; no public OEE requirement depends on paid books, private 0xNAND content or proprietary services. -## Editorial status +## Validation -Each module has a `coverage` value: +Run catalogue checks and tests without a private service: -- `mapped`: reviewed anchor material exists, but not necessarily every lesson is independently covered. -- `partial`: known gaps or important references remain unverified. -- `unmapped`: no usable material has yet been identified. +~~~sh +python3 scripts/check-resources.py +python3 -m unittest discover -s tests -p 'test_*.py' -v +python3 scripts/render-resource-guides.py --check +~~~ -Every mapping entry has a separate `verification` value of `verified` or `review-needed`. A title or range inherited from private Content is **not verified** merely because it was previously mapped. Never invent chapter/page numbers or source URLs, and record edition differences. +For a newly reviewed v2 map and an independently generated pinned OEE Toolkit export, use: -`reference`, `practice`, and `optional` are resource recommendation roles; none imposes a paid-book requirement. The goal is adequate, freely accessible study and hands-on material for independent learners. +~~~sh +python3 scripts/check-resources.py --course SEF1 --export /path/to/pinned-SEF1-export.json +python3 scripts/render-resource-guides.py --course SEF1 --export /path/to/pinned-SEF1-export.json --stdout +~~~ -## Validate - -With a sibling OEE checkout: - -```bash -python3 scripts/check-resources.py --oee ../open-engineering-education -``` - -The validator will check catalogue identities, all resource pointers and mapping correspondence to the actual OEE module and lesson titles. The OEE source revision is recorded for provenance, not used to reject unrelated curriculum changes; structural drift fails validation. - -## Generated course guides - -- [Browse the SEF1 study guide](guides/SEF/SEF1.md). -- Regenerate public guides with `python3 scripts/render-resource-guides.py --write`. -- Check committed guides with `python3 scripts/render-resource-guides.py --check`. -- Print a course with `python3 scripts/render-resource-guides.py --course SEF1 --stdout`. - -These public guides are deterministic snapshots derived from the catalogue and mappings. Do not edit generated guides directly; change the source records and regenerate. The course generator creates a `notes/SEF/SEF1/reading-plan.md` snapshot when a map exists, while the personal `resources.md` reading log remains separate. Existing learner directories are never overwritten. Courses without mappings can still be created, but receive no reading plan yet. +The export consumer checks source identity, module/lesson locators and outcome/assessment references. The caller must independently prove that the export was derived from the named Git commit; a JSON claim alone is not cryptographic provenance. Source lookup and end-to-end binding remain WS-I01; editorial resource review is WS-I02; safe final publishing and regeneration are WS-I04. A map presented without its pinned export **fails closed as source_missing**. No new course guide has yet been accepted. diff --git a/resources/guides/SEF/SEF1.md b/resources/guides/SEF/SEF1.md deleted file mode 100644 index 0e492b8..0000000 --- a/resources/guides/SEF/SEF1.md +++ /dev/null @@ -1,224 +0,0 @@ -# SEF1 — Resource study guide - -> Draft resource guidance · [Canonical OEE course](https://github.com/0xbuffdev/open-engineering-education/blob/938b5426716c5e5809f6dbf1997c4e50f263bea9/curriculum/SEF/SEF1.md) - -This is a non-normative study aid. OEE defines the required outcomes, assessments, and labs. No book purchase is required. Check verification labels before following chapter references. - -**Curriculum revision:** 938b5426716c5e5809f6dbf1997c4e50f263bea9 - -**Map status:** Draft - -## Module 1 — Inside the Machine - -**Coverage:** Partial - -**Outstanding:** Verify B1's titles and locate freely accessible instructional readings for the introductory lessons. - -- **B1 — But How Do It Know?** — Sections “Just the Facts Ma'am” through “Eight Is Enough”. - - Role: Reference · Mapping verification: Review needed - - Study purpose: Physical two-state systems, bits and bytes. - - Access: Paid — No public source link recorded - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B1.json) - -## Module 2 — Codes, Numbers & Addresses - -**Coverage:** Partial - -**Outstanding:** Confirm B1 section placement and supply a free reference for encoding and addresses. - -- **B1 — But How Do It Know?** — Sections “Codes”, “Numbers”, “Addresses”. - - Role: Reference · Mapping verification: Review needed - - Study purpose: Meaning assigned to bit patterns, numeric representation and addressing. - - Access: Paid — No public source link recorded - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B1.json) - -- **B46 — Code: The Hidden Language of Computer Hardware and Software** — Chapters 1, 2. - - Role: Optional · Mapping verification: Review needed - - Study purpose: An alternative introduction to codes and combinations. - - Access: Paid — No public source link recorded - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B46.json) - -## Module 3 — Gates & Circuits - -**Coverage:** Mapped - -- **B7 — The Elements of Computing Systems** — Chapter 1. - - Role: Reference · Mapping verification: Verified - - Study purpose: Boolean logic, gates and hardware descriptions. - - Access: Mixed — [Official source](https://mitpress.mit.edu/9780262539807/the-elements-of-computing-systems/) · [Free companion materials](https://www.nand2tetris.org/) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B7.json) - -- **R89 — Nand to Tetris — Official Projects** — Project 1. - - Role: Practice · Mapping verification: Verified - - Study purpose: Build and test logic gates using the official project materials. - - OEE lesson: 5 — Build logic gates - - Access: Free — [Official source](https://www.nand2tetris.org/course) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/online/R89.json) - -- **R90 — NandGame** — Topics “Early logic-gate levels”. - - Role: Optional · Mapping verification: Verified - - Study purpose: Interactive introductory gate practice. - - Access: Free — [Official source](https://nandgame.com/) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/online/R90.json) - -- **B1 — But How Do It Know?** — Sections “What the…?”, “Simple Variations”. - - Role: Optional · Mapping verification: Review needed - - Study purpose: Alternative explanation of gates. - - Access: Paid — No public source link recorded - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B1.json) - -## Module 4 — Registers & Memory - -**Coverage:** Mapped - -- **B7 — The Elements of Computing Systems** — Chapter 3. - - Role: Reference · Mapping verification: Verified - - Study purpose: Sequential logic, registers and memory hierarchy. - - Access: Mixed — [Official source](https://mitpress.mit.edu/9780262539807/the-elements-of-computing-systems/) · [Free companion materials](https://www.nand2tetris.org/) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B7.json) - -- **R89 — Nand to Tetris — Official Projects** — Project 3. - - Role: Practice · Mapping verification: Verified - - Study purpose: Implement and test memory components. - - OEE lesson: 4 — Build memory - - Access: Free — [Official source](https://www.nand2tetris.org/course) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/online/R89.json) - -- **B1 — But How Do It Know?** — Sections “Remember When”, “Back to the Byte”, “The Magic Bus”, “More Gate Combinations”, “First Half of the Computer”. - - Role: Optional · Mapping verification: Review needed - - Study purpose: Alternative account of held state and memory. - - Access: Paid — No public source link recorded - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B1.json) - -## Module 5 — How Hardware Computes - -**Coverage:** Mapped - -- **B7 — The Elements of Computing Systems** — Chapter 2. - - Role: Reference · Mapping verification: Verified - - Study purpose: Binary arithmetic and ALU design. - - Access: Mixed — [Official source](https://mitpress.mit.edu/9780262539807/the-elements-of-computing-systems/) · [Free companion materials](https://www.nand2tetris.org/) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B7.json) - -- **R89 — Nand to Tetris — Official Projects** — Project 2. - - Role: Practice · Mapping verification: Verified - - Study purpose: Construct and test adders and an ALU. - - OEE lesson: 6 — Build the ALU - - Access: Free — [Official source](https://www.nand2tetris.org/course) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/online/R89.json) - -- **R90 — NandGame** — Topics “Arithmetic and ALU levels”. - - Role: Optional · Mapping verification: Verified - - Study purpose: Optional interactive arithmetic practice. - - Access: Free — [Official source](https://nandgame.com/) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/online/R90.json) - -- **B1 — But How Do It Know?** — Sections “More Gates” through “The Arithmetic and Logic Unit”. - - Role: Optional · Mapping verification: Review needed - - Study purpose: Alternative account of adders and ALU. - - Access: Paid — No public source link recorded - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B1.json) - -## Module 6 — Building the Processor - -**Coverage:** Partial - -**Outstanding:** Verify B1 subsections for clock and control logic; find accessible instruction for a stepwise execution trace. - -- **B1 — But How Do It Know?** — Sections “The Other Half of the Computer”, “More of the Processor”, “What's Next?”. - - Role: Reference · Mapping verification: Review needed - - Study purpose: Processor components, clock and execution cycle. - - Access: Paid — No public source link recorded - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B1.json) - -- **B7 — The Elements of Computing Systems** — Chapter 5. - - Role: Optional · Mapping verification: Verified - - Study purpose: Additional CPU and architecture perspective. - - Access: Mixed — [Official source](https://mitpress.mit.edu/9780262539807/the-elements-of-computing-systems/) · [Free companion materials](https://www.nand2tetris.org/) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B7.json) - -- **R89 — Nand to Tetris — Official Projects** — Project 5. - - Role: Optional · Mapping verification: Verified - - Study purpose: Stretch CPU-construction project, not the OEE lab itself. - - Access: Free — [Official source](https://www.nand2tetris.org/course) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/online/R89.json) - -## Module 7 — Instructions & Programs - -**Coverage:** Partial - -**Outstanding:** Confirm the B1 title range and find a free explanation of instruction registers and flags. - -- **B1 — But How Do It Know?** — Sections “The First Great Invention” through “Ta Daa!”. - - Role: Reference · Mapping verification: Review needed - - Study purpose: Instruction types, jumps and control flow. - - Access: Paid — No public source link recorded - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B1.json) - -- **B7 — The Elements of Computing Systems** — Chapter 4. - - Role: Optional · Mapping verification: Verified - - Study purpose: Machine-language examples. - - Access: Mixed — [Official source](https://mitpress.mit.edu/9780262539807/the-elements-of-computing-systems/) · [Free companion materials](https://www.nand2tetris.org/) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B7.json) - -- **R89 — Nand to Tetris — Official Projects** — Project 4. - - Role: Optional · Mapping verification: Verified - - Study purpose: Stretch assembly programming exercise. - - Access: Free — [Official source](https://www.nand2tetris.org/course) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/online/R89.json) - -## Module 8 — Instruction Encoding & Control - -**Coverage:** Partial - -**Outstanding:** Find readings on instruction fields, operand addressing, branch targets, status flags and decoder control signals. - -- **B7 — The Elements of Computing Systems** — Chapter 4. - - Role: Reference · Mapping verification: Verified - - Study purpose: Machine-language encodings and branch instructions. - - Access: Mixed — [Official source](https://mitpress.mit.edu/9780262539807/the-elements-of-computing-systems/) · [Free companion materials](https://www.nand2tetris.org/) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B7.json) - -- **R89 — Nand to Tetris — Official Projects** — Project 4. - - Role: Optional · Mapping verification: Verified - - Study purpose: Supplementary machine-language practice. - - Access: Free — [Official source](https://www.nand2tetris.org/course) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/online/R89.json) - -## Module 9 — I/O, Firmware & Boot - -**Coverage:** Partial - -**Outstanding:** Research free instruction on memory-mapped I/O, polling/interrupts, firmware, bootloaders, OS boundaries and device errors. - -- **B1 — But How Do It Know?** — Sections “The Outside World”. - - Role: Reference · Mapping verification: Review needed - - Study purpose: Introductory account of external devices. - - Access: Paid — No public source link recorded - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B1.json) - -## Module 10 — Hardware, Software & Booting - -**Coverage:** Partial - -**Outstanding:** Split broad B1 reading into checked sections; add free instruction on storage/boot and the final tiny-computer lab. - -- **B1 — But How Do It Know?** — Sections “The Outside World” through “Full Disclosure”. - - Role: Reference · Mapping verification: Review needed - - Study purpose: Broad legacy introduction to devices, programs, operating systems and files. - - Access: Paid — No public source link recorded - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B1.json) - -- **B7 — The Elements of Computing Systems** — Chapter 5. - - Role: Optional · Mapping verification: Verified - - Study purpose: Stretch architecture material for the integrated computer model. - - Access: Mixed — [Official source](https://mitpress.mit.edu/9780262539807/the-elements-of-computing-systems/) · [Free companion materials](https://www.nand2tetris.org/) - - [Catalogue record](https://github.com/0xbuffdev/oee-workspace/blob/main/resources/catalog/books/B7.json) - -## How to use this guide - -Read the canonical OEE module and lesson requirements first. Use these references as supporting explanations and practice, not substitutes for OEE labs or assessment evidence. - -A **Partial** module still needs editorial research. A **Review needed** reference may have unconfirmed section titles or edition-specific numbering. Do not assume that a paid book is essential or that an optional project satisfies a required OEE lab. - -When using this guide in a personal workspace, record your actual reading, editions and substitutions in the resources.md log. This guide is a versioned snapshot, not a progress log. diff --git a/resources/schemas/course-map.schema.json b/resources/schemas/course-map.schema.json index 6e28d74..3252e74 100644 --- a/resources/schemas/course-map.schema.json +++ b/resources/schemas/course-map.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "OEE Workspace course resource mapping", + "title": "OEE Workspace course resource mapping v2 (OEE v0.2.0 only)", "type": "object", "additionalProperties": false, "required": [ @@ -11,7 +11,7 @@ ], "properties": { "schemaVersion": { - "const": 1 + "const": 2 }, "status": { "enum": [ @@ -28,6 +28,7 @@ "required": [ "repository", "revision", + "specification", "course", "path" ], @@ -45,7 +46,10 @@ }, "path": { "type": "string", - "minLength": 1 + "pattern": "^curriculum/[A-Z]{2,4}/[A-Z]{2,4}[1-9][0-9]*\\.md$" + }, + "specification": { + "const": "v0.2.0" } } }, @@ -208,11 +212,89 @@ "minLength": 1 } } + }, + "outcomeIds": { + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^[A-Z]{2,4}[1-9][0-9]*-O[1-9][0-9]*$" + } + }, + "assessmentIds": { + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^[A-Z]{2,4}[1-9][0-9]*-AS[1-9][0-9]*$" + } } } } } - } + }, + "allOf": [ + { + "if": { + "properties": { + "coverage": { + "const": "mapped" + } + }, + "required": [ + "coverage" + ] + }, + "then": { + "properties": { + "resources": { + "minItems": 1 + } + } + } + }, + { + "if": { + "properties": { + "coverage": { + "const": "partial" + } + }, + "required": [ + "coverage" + ] + }, + "then": { + "required": [ + "gap" + ] + } + }, + { + "if": { + "properties": { + "coverage": { + "const": "unmapped" + } + }, + "required": [ + "coverage" + ] + }, + "then": { + "required": [ + "gap" + ], + "properties": { + "resources": { + "maxItems": 0 + } + } + } + } + ] } } } diff --git a/scripts/README.md b/scripts/README.md index 479fa5b..3b08c88 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -32,13 +32,7 @@ version, wrong SHA, unknown assessment, missing outcome coverage or changed module/lesson locator **fails explicitly**. There is no v1 reader, conversion process or fallback to the checkout's moving HEAD. -This is a narrow **derived-export consumer check**, not the complete -resource-catalog or v2 mapping validator. Workspace still has an -**old schema-v1 pilot map**, which is not eligible for this command or -proof of source compatibility. The separately reviewed WS-I03, -WS-I01 and WS-I02 work must replace that active map and validate it against -the exact source revision. Until then, this implementation is a -cross-repository test seam, not a release-ready mapped-course workflow. +This export consumer is a narrow reference-checking seam, not an editorial review. WS-I03 now provides one active v2 schema, and historical v1 SEF1 data is only a negative fixture. WS-I01 will wire exact source Git-object lookup into the validator, WS-I02 will author a new reviewed map, and WS-I04 will harden guide publishing. No active course mapping is currently approved. The source revision text in an exported file is **not cryptographic proof** by itself. For trusted provenance, derive exports from the actual selected @@ -101,7 +95,7 @@ The expected format is a base URL that precedes paths such as `curriculum/SEF///reading-plan.md` alongside an editable `resources.md` log. +There is currently **no active reviewed map or public study guide**. The retired SEF1 v1 mapping must not be used for the redesigned OEE modules. Unmapped course scaffolding creates notes, labs, exercises, and an editable resources log without a reading plan. -```bash -./scripts/new-course-workspace SEF SEF1 -python3 scripts/check-resources.py --oee ../open-engineering-education --course SEF1 +```sh +python3 scripts/check-resources.py +python3 -m unittest discover -s tests -p 'test_*.py' -v python3 scripts/render-resource-guides.py --check ``` -Course files are resolved by their exact canonical names, such as `SEF1.md`. Courses without public resource mappings are still supported but do not receive a reading plan. Existing course directories are not overwritten, so learners can retain their personal notes and decide when to refresh a guide. +For a future reviewed v2 map, validation requires the exact pinned Toolkit export: + +```sh +python3 scripts/check-resources.py --course SEF1 --export /path/to/pinned-export.json +python3 scripts/render-resource-guides.py --course SEF1 --export /path/to/pinned-export.json --stdout +``` + +Without a source export, mapped validation and guide generation fail closed; there is no fallback to the checkout's HEAD. Automatic commit resolution and review/publishing gates belong to WS-I01, WS-I02, and WS-I04. The generator continues to protect existing learner directories. diff --git a/scripts/check-resources.py b/scripts/check-resources.py index e425556..fa83142 100644 --- a/scripts/check-resources.py +++ b/scripts/check-resources.py @@ -1,16 +1,14 @@ #!/usr/bin/env python3 -"""Validate public resource records and maps against a local canonical OEE checkout. +"""Validate OEE Workspace resource-map v2 shape and pinned export identities. -Only Python 3 standard library is needed. JSON Schemas under resources/schemas -describe the interchange format; these checks additionally enforce OEE identity -and cross-file invariants that JSON Schema alone cannot express. +Standard-library only. No historical-schema adapter or moving-HEAD source fallback. """ from __future__ import annotations import argparse +import importlib.util import json import re -import subprocess import sys from pathlib import Path from urllib.parse import urlparse @@ -24,8 +22,6 @@ COVERAGE = {"mapped", "partial", "unmapped"} IDENTIFIER = re.compile(r"(?:B|R)[1-9][0-9]*\Z") CODE = re.compile(r"([A-Z]{2,4})([1-9][0-9]*)\Z") -COURSE_MODULE = re.compile(r"(?m)^### Module ([1-9][0-9]*) — ([^\n]+)$") -COURSE_LESSON = re.compile(r"(?m)^([1-9][0-9]*)\. \*\*(.*?)\*\* — \`(?:lesson|test|lab)\`$") SHA = re.compile(r"[a-f0-9]{40}\Z") @@ -100,30 +96,6 @@ def validate_catalog(check: Check): return result -def course_structure(path: Path, check: Check): - try: - body = path.read_text(encoding="utf-8") - except OSError as exc: - check.error(str(path), f"canonical OEE course not found: {exc}") - return None - heads = list(COURSE_MODULE.finditer(body)) - if not heads: - check.error(str(path), "OEE course has no numbered module headings") - return None - modules = {} - for index, match in enumerate(heads): - number = int(match.group(1)) - boundary = heads[index + 1].start() if index + 1 < len(heads) else body.find("\n## Completion requirements", match.end()) - if boundary < 0: - boundary = len(body) - section = body[match.end():boundary] - lessons = {int(m.group(1)): m.group(2) for m in COURSE_LESSON.finditer(section)} - if number in modules: - check.error(str(path), f"duplicate OEE module {number}") - modules[number] = (match.group(2).strip(), lessons) - return modules - - def valid_part(part): if not isinstance(part, dict): return False @@ -139,138 +111,185 @@ def valid_part(part): return False -def validate_maps(oee: Path, catalog: dict, check: Check, course_filter: str | None = None): +def known_fields(value, expected, loc, check): + for key in sorted(set(value) - set(expected)): + check.error(loc, f"unknown field {key!r}") + + +def validate_map_shape(mapping, catalog, check, loc): + """Validate schema-v2 shape/catalogue; source references require pinned export.""" + before = len(check.errors) + if not isinstance(mapping, dict): + check.error(loc, "mapping must be an object") + return False + if type(mapping.get("schemaVersion")) is not int or mapping["schemaVersion"] != 2: + check.error(loc, "unsupported_schema: only resource-map v2 is accepted") + return False + known_fields(mapping, {"schemaVersion", "status", "curriculum", "modules", "notes"}, loc, check) + if mapping.get("status") not in ("draft", "reviewed"): + check.error(loc, "invalid map status") + if "notes" in mapping and not isinstance(mapping["notes"], str): + check.error(loc, "notes must be a string") + canon = mapping.get("curriculum") + if not isinstance(canon, dict): + check.error(loc, "curriculum must be an object") + return False + known_fields(canon, {"repository", "revision", "specification", "course", "path"}, loc, check) + course = canon.get("course") + match = CODE.fullmatch(course) if isinstance(course, str) else None + if not match: + check.error(loc, "invalid canonical course code") + return False + program = match.group(1) + wanted = f"curriculum/{program}/{course}.md" + if canon.get("repository") != "0xbuffdev/open-engineering-education": + check.error(loc, "invalid canonical OEE repository") + if canon.get("path") != wanted: + check.error(loc, f"invalid canonical OEE path; expected {wanted}") + if canon.get("specification") != "v0.2.0": + check.error(loc, "unsupported_format: only OEE v0.2.0 is supported") + revision = canon.get("revision") + if not isinstance(revision, str) or not SHA.fullmatch(revision): + check.error(loc, "curriculum.revision must be a full lowercase Git SHA") + modules = mapping.get("modules") + if not isinstance(modules, list) or not modules: + check.error(loc, "modules must be a nonempty array") + return False + for index, module in enumerate(modules, start=1): + ml = f"{loc}: module {index}" + if not isinstance(module, dict): + check.error(ml, "module must be an object") + continue + known_fields(module, {"number", "title", "coverage", "gap", "resources"}, ml, check) + if type(module.get("number")) is not int or module["number"] != index: + check.error(ml, "module numbers must be ordered and contiguous from 1") + if not text(module.get("title")): + check.error(ml, "missing module title") + coverage = module.get("coverage") + if coverage not in COVERAGE: + check.error(ml, "invalid coverage") + if coverage in ("partial", "unmapped") and not text(module.get("gap")): + check.error(ml, f"{coverage} module requires an explicit gap") + if "gap" in module and not text(module["gap"]): + check.error(ml, "gap must contain explanatory text") + entries = module.get("resources") + if not isinstance(entries, list): + check.error(ml, "resources must be an array") + continue + if coverage == "mapped" and not entries: + check.error(ml, "mapped module requires resource anchors") + if coverage == "unmapped" and entries: + check.error(ml, "unmapped module cannot claim resources") + seen = set() + free_verified = False + for ordinal, item in enumerate(entries, start=1): + el = f"{ml}: entry {ordinal}" + if not isinstance(item, dict): + check.error(el, "resource entry must be an object") + continue + known_fields(item, {"resource", "role", "part", "purpose", "verification", + "lesson", "outcomeIds", "assessmentIds"}, el, check) + rid = item.get("resource") + record = catalog.get(rid) if isinstance(rid, str) else None + if record is None: + check.error(el, f"unknown catalogue resource {rid!r}") + if item.get("role") not in RESOURCE_ROLES or not text(item.get("purpose")): + check.error(el, "invalid role or missing purpose") + state = item.get("verification") + if state not in REVIEW_STATES: + check.error(el, "invalid mapping verification") + if state == "verified" and record and record.get("verification", {}).get("status") != "verified": + check.error(el, "catalogue cannot support verified mapping claim") + part = item.get("part") + if not valid_part(part): + check.error(el, "invalid chapter/project/section locator") + lesson = item.get("lesson") + if lesson is not None: + if not isinstance(lesson, dict): + check.error(el, "lesson must be an object") + else: + known_fields(lesson, {"number", "title"}, el + ": lesson", check) + if type(lesson.get("number")) is not int or lesson["number"] < 1 or not text(lesson.get("title")): + check.error(el, "invalid revision-scoped lesson locator") + for field, suffix in (("outcomeIds", "O"), ("assessmentIds", "AS")): + if field in item: + ids = item[field] + pattern = re.compile(rf"{re.escape(course)}-{suffix}[1-9][0-9]*\Z") + if not isinstance(ids, list) or not ids or any( + not isinstance(value, str) or not pattern.fullmatch(value) for value in ids): + check.error(el, f"{field} must contain canonical {course} IDs") + elif len(ids) != len(set(ids)): + check.error(el, f"duplicate {field}") + key = (str(rid), json.dumps(part, sort_keys=True), json.dumps(lesson, sort_keys=True)) + if key in seen: + check.error(el, "duplicate resource/part/lesson reference") + seen.add(key) + if record and state == "verified" and record.get("access", {}).get("mode") in ("free", "mixed"): + free_verified = True + if coverage == "mapped" and not free_verified: + check.error(ml, "mapped coverage requires verified free/companion anchor") + if coverage == "partial" and text(module.get("gap")): + check.warn(ml, module["gap"]) + return len(check.errors) == before + + +def load_consumer(): + name = "oee_workspace_export_consumer" + spec = importlib.util.spec_from_file_location(name, ROOT / "scripts" / "verify-oee-export.py") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +def validate_maps(catalog, check, course_filter=None, export_path=None): paths = sorted(MAPPINGS.rglob("*.json")) if course_filter: - paths = [p for p in paths if p.stem == course_filter] + paths = [path for path in paths if path.stem == course_filter] if not paths: - check.error("mappings", "no mappings found") + if course_filter: + check.error("mappings", f"unmapped course {course_filter}; no active v2 map") + return + if export_path is not None and len(paths) != 1: + check.error("mappings", "--export requires exactly one selected map (--course CODE)") + return + consumer = load_consumer() if export_path is not None else None for path in paths: loc = str(path.relative_to(ROOT)) mapping = load_json(path, check) - if not isinstance(mapping, dict): - check.error(loc, "mapping must be an object") - continue - if mapping.get("schemaVersion") != 1 or mapping.get("status") not in ("draft", "reviewed"): - check.error(loc, "expected schemaVersion 1 and status draft/reviewed") - canon = mapping.get("curriculum") - if not isinstance(canon, dict): - check.error(loc, "curriculum must be an object") - continue - course = canon.get("course") - match = CODE.fullmatch(course) if isinstance(course, str) else None - if not match: - check.error(loc, "invalid canonical course code") + if not validate_map_shape(mapping, catalog, check, loc): continue - program = match.group(1) - wanted = f"curriculum/{program}/{course}.md" + canon = mapping["curriculum"] + course = canon["course"] + program = CODE.fullmatch(course).group(1) if path.parent.name != program or path.stem != course: - check.error(loc, f"mapping path must be mappings/{program}/{course}.json") - if canon.get("repository") != "0xbuffdev/open-engineering-education" or canon.get("path") != wanted: - check.error(loc, f"curriculum repository/path must be canonical {wanted}") + check.error(loc, f"map path must be mappings/{program}/{course}.json") continue - revision = canon.get("revision") - if not isinstance(revision, str) or not SHA.fullmatch(revision): - check.error(loc, "curriculum.revision must be a 40-character Git SHA") - course_modules = course_structure(oee / wanted, check) - if course_modules is None: + if consumer is None: + check.error(loc, "source_missing: exact pinned OEE export required; automatic Git resolution pending WS-I01") continue - module_items = mapping.get("modules") - if not isinstance(module_items, list): - check.error(loc, "modules must be an array") - continue - seen = set() - for module in module_items: - if not isinstance(module, dict): - check.error(loc, "module must be an object") - continue - number = module.get("number") - if type(number) is not int or number < 1 or number in seen: - check.error(loc, f"invalid/duplicate module number {number!r}") - continue - seen.add(number) - ml = f"{loc}: module {number}" - if number not in course_modules: - check.error(ml, "module not found in OEE") - continue - canonical_title, canonical_lessons = course_modules[number] - if module.get("title") != canonical_title: - check.error(ml, f"title differs from OEE ({canonical_title})") - coverage = module.get("coverage") - if coverage not in COVERAGE: - check.error(ml, "invalid coverage") - if coverage == "partial" and not text(module.get("gap")): - check.error(ml, "partial module needs an explicit gap explanation") - entries = module.get("resources") - if not isinstance(entries, list): - check.error(ml, "resources must be an array") - continue - if coverage == "mapped" and not entries: - check.error(ml, "mapped module has no resources") - if coverage == "unmapped" and entries: - check.error(ml, "unmapped module should not carry resources") - used = set() - free_verified = False - for entry in entries: - if not isinstance(entry, dict): - check.error(ml, "resource entry must be an object") - continue - rid = entry.get("resource") - item = catalog.get(rid) if isinstance(rid, str) else None - if not item: - check.error(ml, f"unknown resource {rid!r}") - continue - role = entry.get("role") - if role not in RESOURCE_ROLES or not text(entry.get("purpose")): - check.error(ml, f"{rid}: invalid role or missing purpose") - status = entry.get("verification") - if status not in REVIEW_STATES: - check.error(ml, f"{rid}: invalid verification state") - if status == "verified" and item.get("verification", {}).get("status") != "verified": - check.error(ml, f"{rid}: cannot verify a map entry using unverified catalogue metadata") - part = entry.get("part") - if not valid_part(part): - check.error(ml, f"{rid}: invalid chapter/project/section locator") - lesson = entry.get("lesson") - if lesson is not None: - if not isinstance(lesson, dict) or type(lesson.get("number")) is not int or canonical_lessons.get(lesson["number"]) != lesson.get("title"): - check.error(ml, f"{rid}: lesson reference does not match canonical OEE") - key = (rid, json.dumps(part, sort_keys=True), json.dumps(lesson, sort_keys=True)) - if key in used: - check.error(ml, f"{rid}: duplicate resource/locator/lesson entry") - used.add(key) - if status == "verified" and item.get("access", {}).get("mode") in ("free", "mixed"): - free_verified = True - if coverage == "mapped" and not free_verified: - check.error(ml, "mapped status needs at least one verified free/companion-material resource") - if coverage == "partial": - check.warn(ml, module.get("gap", "open coverage gap")) - if set(course_modules) != seen: - check.error(loc, f"module coverage differs from OEE: missing {sorted(set(course_modules)-seen)}, extra {sorted(seen-set(course_modules))}") - try: - head = subprocess.run(["git", "-C", str(oee), "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() - for path in paths: - data = json.loads(path.read_text(encoding="utf-8")) - expected = data.get("curriculum", {}).get("revision") - if expected and expected != head: - check.warn(str(path.relative_to(ROOT)), f"source revision {expected[:12]} differs from local OEE HEAD {head[:12]}; structural checks still ran") - except (OSError, subprocess.CalledProcessError, ValueError): - pass + try: + verified = consumer.check_export(consumer.load_json(export_path), canon["revision"]) + consumer.check_map(mapping, verified) + except consumer.ContractError as exc: + check.error(loc, f"{exc.category}: {exc.code}: {exc}") def main(): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--oee", type=Path, default=Path("../open-engineering-education"), help="path to a local canonical OEE checkout") - parser.add_argument("--course", help="validate only the named course map") + parser.add_argument("--course", help="check one active v2 course map") + parser.add_argument("--export", type=Path, help="independently generated pinned OEE export-format-v1 JSON") args = parser.parse_args() check = Check() catalog = validate_catalog(check) - validate_maps(args.oee.resolve(), catalog, check, args.course) + validate_maps(catalog, check, args.course, args.export) for warning in check.warnings: print(f"WARNING: {warning}", file=sys.stderr) for error in check.errors: print(f"ERROR: {error}", file=sys.stderr) - print(f"Resource check: {len(catalog)} catalogued IDs, {len(check.warnings)} warnings, {len(check.errors)} errors") + print(f"Resource check: {len(catalog)} catalogue IDs, {len(check.warnings)} warnings, {len(check.errors)} errors") + if not list(MAPPINGS.rglob("*.json")): + print("No active v2 resource maps; catalog validation only.") return 1 if check.errors else 0 diff --git a/scripts/new-course-workspace b/scripts/new-course-workspace old mode 100755 new mode 100644 index b058d6d..58b6532 --- a/scripts/new-course-workspace +++ b/scripts/new-course-workspace @@ -72,6 +72,12 @@ if [[ ! -f "$course_file" ]]; then exit 64 fi +# Scaffold only explicitly supported OEE v0.2.0 courses, even when unmapped. +if ! grep -Fqx '**Specification:** `v0.2.0`' "$course_file"; then + echo "unsupported_format: OEE course $course must declare Specification v0.2.0." >&2 + exit 64 +fi + course_name="$course.md" oee_url="${OEE_CURRICULUM_URL:-https://github.com/0xbuffdev/open-engineering-education/blob/main}" @@ -127,7 +133,7 @@ if [[ -f "$mapping_file" ]]; then echo "Python 3 is required for public resource mapping." >&2 exit 1 fi - python3 "$workspace_repo_root/scripts/check-resources.py" --oee "$oee_repo" --course "$course" + python3 "$workspace_repo_root/scripts/check-resources.py" --course "$course" python3 "$workspace_repo_root/scripts/render-resource-guides.py" --course "$course" --stdout >/dev/null fi diff --git a/scripts/render-resource-guides.py b/scripts/render-resource-guides.py index d1f073c..a6a5d4a 100644 --- a/scripts/render-resource-guides.py +++ b/scripts/render-resource-guides.py @@ -9,6 +9,7 @@ import argparse import json import re +import subprocess import sys from pathlib import Path @@ -109,15 +110,25 @@ def render(mapping, catalog): return "\n".join(lines) -def outputs(course_filter): +def outputs(course_filter, export_path): catalog = load_catalog() found = False for path in sorted(MAPPINGS.rglob("*.json")): mapping = json.loads(path.read_text(encoding="utf-8")) + if mapping.get("schemaVersion") != 2 or mapping.get("curriculum", {}).get("specification") != "v0.2.0": + raise ValueError("unsupported_schema: only OEE v0.2.0 resource-map v2 is supported") code = mapping["curriculum"]["course"] if course_filter and code != course_filter: continue found = True + if export_path is None: + raise ValueError("source_missing: mapped guides require a reviewed, pinned --export") + checked = subprocess.run( + [sys.executable, str(ROOT / "scripts" / "check-resources.py"), + "--course", code, "--export", str(export_path)], + capture_output=True, text=True, check=False) + if checked.returncode: + raise ValueError("resource map failed pinned-source validation: " + checked.stderr.strip()) program = re.match(r"^[A-Z]+", code).group() yield GUIDES / program / (code + ".md"), render(mapping, catalog) if course_filter and not found: @@ -131,6 +142,8 @@ def main(): modes.add_argument("--check", action="store_true", help="verify all guides match their mappings") modes.add_argument("--stdout", action="store_true", help="print one course guide") parser.add_argument("--course", help="course code (required with --stdout)") + parser.add_argument("--export", type=Path, + help="independently generated pinned OEE Toolkit export for one selected map") args = parser.parse_args() if args.stdout and not args.course: parser.error("--stdout requires --course") @@ -139,7 +152,7 @@ def main(): if args.check and args.course: parser.error("--check validates all guides; omit --course") try: - results = list(outputs(args.course)) + results = list(outputs(args.course, args.export)) if args.stdout: if len(results) != 1: raise ValueError("Expected exactly one mapped course") diff --git a/resources/mappings/SEF/SEF1.json b/tests/fixtures/resource-map-v1-SEF1.json similarity index 100% rename from resources/mappings/SEF/SEF1.json rename to tests/fixtures/resource-map-v1-SEF1.json diff --git a/tests/test_resource_map_v2.py b/tests/test_resource_map_v2.py new file mode 100644 index 0000000..043d606 --- /dev/null +++ b/tests/test_resource_map_v2.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""WS-I03: schema-v2 shape and fail-closed source tests.""" +import copy +import importlib.util +import json +import subprocess +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("resource_check", ROOT / "scripts/check-resources.py") +validator = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = validator +spec.loader.exec_module(validator) +PIN = "a" * 40 +CATALOG = {"R1": {"access": {"mode": "free"}, + "verification": {"status": "review-needed", "basis": "Editorial review pending"}}} + + +def valid_map(): + return {"schemaVersion": 2, "status": "draft", + "curriculum": {"repository": "0xbuffdev/open-engineering-education", + "revision": PIN, "specification": "v0.2.0", + "course": "SEF1", "path": "curriculum/SEF/SEF1.md"}, + "modules": [{"number": 1, "title": "Observe", "coverage": "partial", + "gap": "Needs reviewed free source", + "resources": [{"resource": "R1", "role": "optional", + "part": {"type": "topics", "titles": ["Observe"]}, + "purpose": "Background", "verification": "review-needed", + "outcomeIds": ["SEF1-O1"], "assessmentIds": ["SEF1-AS1"], + "lesson": {"number": 1, "title": "Observe a case"}}]}]} + + +class ContractTests(unittest.TestCase): + def check(self, mapping): + findings = validator.Check() + ok = validator.validate_map_shape(mapping, CATALOG, findings, "fixture") + return ok, findings + + def test_valid_v2_shape(self): + ok, findings = self.check(valid_map()) + self.assertTrue(ok, findings.errors) + + def test_legacy_sef1_fixture_is_unsupported_and_not_active(self): + path = ROOT / "tests/fixtures/resource-map-v1-SEF1.json" + legacy = json.loads(path.read_text(encoding="utf-8")) + self.assertEqual(legacy["modules"][0]["title"], "Inside the Machine") + self.assertEqual(legacy["curriculum"]["revision"], + "938b5426716c5e5809f6dbf1997c4e50f263bea9") + ok, findings = self.check(legacy) + self.assertFalse(ok) + self.assertIn("unsupported_schema", findings.errors[0]) + self.assertFalse((ROOT / "resources/mappings/SEF/SEF1.json").exists()) + + def test_reject_unsupported_source_identity(self): + for field, value in (("specification", "v0.1.0"), ("revision", "main"), + ("repository", "example/private"), + ("path", "curriculum/APP/APP1.md")): + mapping = valid_map() + mapping["curriculum"][field] = value + with self.subTest(field=field): + self.assertFalse(self.check(mapping)[0]) + + def test_reject_bad_reference_shapes_and_extra_properties(self): + mutations = [ + lambda m: m.update(legacy=True), + lambda m: m["modules"][0].update(extra=True), + lambda m: m["modules"][0]["resources"][0].update(outcomeIds=[]), + lambda m: m["modules"][0]["resources"][0].update(outcomeIds=["APP1-O1"]), + lambda m: m["modules"][0]["resources"][0].update(assessmentIds=["SEF1-AS1", "SEF1-AS1"]), + lambda m: m["modules"][0]["resources"][0].update(verification="invented"), + ] + for fn in mutations: + mapping = valid_map() + fn(mapping) + self.assertFalse(self.check(mapping)[0]) + + def test_partial_and_unmapped_require_gaps(self): + for coverage, resources in (("partial", []), ("unmapped", []), + ("unmapped", valid_map()["modules"][0]["resources"]), + ("mapped", [])): + mapping = valid_map() + module = mapping["modules"][0] + module.update(coverage=coverage, resources=resources) + module.pop("gap", None) + self.assertFalse(self.check(mapping)[0]) + mapping = valid_map() + mapping["modules"][0].update(coverage="unmapped", gap="Not mapped", resources=[]) + self.assertTrue(self.check(mapping)[0]) + + def test_duplicate_module_and_resource_rejected(self): + mapping = valid_map() + mapping["modules"].append(copy.deepcopy(mapping["modules"][0])) + self.assertFalse(self.check(mapping)[0]) + mapping = valid_map() + mapping["modules"][0]["resources"].append(copy.deepcopy(mapping["modules"][0]["resources"][0])) + self.assertFalse(self.check(mapping)[0]) + + def test_only_v2_schema_is_active(self): + schema = json.loads((ROOT / "resources/schemas/course-map.schema.json").read_text()) + self.assertEqual(schema["properties"]["schemaVersion"]["const"], 2) + self.assertIn("specification", schema["properties"]["curriculum"]["required"]) + self.assertEqual(schema["properties"]["curriculum"]["properties"]["specification"]["const"], "v0.2.0") + + def test_no_map_is_catalog_only_and_sef1_is_unmapped(self): + command = [sys.executable, str(ROOT / "scripts/check-resources.py")] + clean = subprocess.run(command, capture_output=True, text=True) + self.assertEqual(clean.returncode, 0, clean.stderr) + self.assertIn("catalog validation only", clean.stdout) + unmapped = subprocess.run([*command, "--course", "SEF1"], capture_output=True, text=True) + self.assertNotEqual(unmapped.returncode, 0) + self.assertIn("unmapped course", unmapped.stderr) + + +if __name__ == "__main__": + unittest.main()