From b6340a3df183c47511f9ce8edeec0ce69012ba4a Mon Sep 17 00:00:00 2001 From: Florent Pollet Date: Tue, 3 Nov 2026 10:32:27 -0500 Subject: [PATCH 1/2] Add curated algorithm catalogue and public release observations --- .github/workflows/catalogue.yml | 44 ++++++ .github/workflows/ci.yml | 5 +- .github/workflows/publish.yml | 4 +- README.md | 3 + TESTING.md | 15 ++ catalogue/algorithms.yaml | 28 ++++ catalogue/updates.json | 13 ++ docs/catalogue.py | 258 ++++++++++++++++++++++++++++++++ docs/implemented-algorithms.md | 67 +++++++++ mkdocs.yml | 2 + pyproject.toml | 2 +- template/RELEASING.md.jinja | 12 ++ tests/test_catalogue.py | 174 +++++++++++++++++++++ uv.lock | 2 + 14 files changed, 624 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/catalogue.yml create mode 100644 catalogue/algorithms.yaml create mode 100644 catalogue/updates.json create mode 100644 docs/catalogue.py create mode 100644 docs/implemented-algorithms.md create mode 100644 tests/test_catalogue.py diff --git a/.github/workflows/catalogue.yml b/.github/workflows/catalogue.yml new file mode 100644 index 0000000..a6a4582 --- /dev/null +++ b/.github/workflows/catalogue.yml @@ -0,0 +1,44 @@ +name: Catalogue updates + +on: + schedule: + - cron: '23 9 * * 1' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: catalogue-updates + cancel-in-progress: false + +jobs: + observe: + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@v4 + with: + ref: main + - uses: astral-sh/setup-uv@v6 + - run: uv sync --locked --group docs + - run: uv run pytest -q tests/test_catalogue.py + - run: uv run python docs/catalogue.py --check-remote + - run: uv run --group docs mkdocs build --strict + - uses: actions/upload-artifact@v4 + with: + name: catalogue-observations + path: catalogue/updates.json + - uses: peter-evans/create-pull-request@v8 + with: + branch: codex/catalogue-release-observations + add-paths: catalogue/updates.json + commit-message: Refresh catalogue release observations + title: Review algorithm catalogue release observations + body: | + Public release metadata changed. Review catalogue/updates.json, then update + catalogue/algorithms.yaml separately after checking the relevant revision and evidence. + This PR does not promote implementation or validation status and does not change install pins. + Private repositories were not queried. Registry tests and strict docs ran in the update workflow. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 918d818..5a3c54d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,8 +12,9 @@ jobs: - uses: actions/checkout@v4 - uses: astral-sh/setup-uv@v6 - run: uv sync --group dev - - run: uv run ruff check src tests scripts docs/hooks.py - - run: uv run ruff format --check src tests scripts docs/hooks.py + - run: uv run ruff check src tests scripts docs/hooks.py docs/catalogue.py + - run: uv run ruff format --check src tests scripts docs/hooks.py docs/catalogue.py + - run: uv run python docs/catalogue.py - uses: actions/setup-node@v4 with: node-version: "24" diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 2411b75..0d569cf 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -39,8 +39,8 @@ jobs: git merge-base --is-ancestor HEAD origin/main - run: python scripts/check_release.py - run: uv sync --locked --group dev --group docs - - run: uv run ruff check src tests scripts docs/hooks.py - - run: uv run ruff format --check src tests scripts docs/hooks.py + - run: uv run ruff check src tests scripts docs/hooks.py docs/catalogue.py + - run: uv run ruff format --check src tests scripts docs/hooks.py docs/catalogue.py - uses: actions/setup-node@v4 with: node-version: "24" diff --git a/README.md b/README.md index 313793b..5b2dd94 100644 --- a/README.md +++ b/README.md @@ -419,6 +419,9 @@ and [shared-package assessment](https://github.com/McDermottHealthAI/MEDS_algori ### Unreleased +- Add a curated algorithm catalogue with reviewed PyPI install pins and separate implementation/validation states. +- Check public release metadata weekly and propose observation updates without automatically changing evidence. + - Generate an algorithm release guide, Trusted Publishing workflow, and installed-distribution checks. - Configure PyPI metadata separately from Python names and bundle portable run/profile YAMLs once at build time. diff --git a/TESTING.md b/TESTING.md index 4c8d81e..1b58c1a 100644 --- a/TESTING.md +++ b/TESTING.md @@ -118,6 +118,21 @@ builder uses plain JavaScript without runtime dependencies, network calls or per ## Release checks outside pytest +### test_catalogue.py + +| Test | What it checks | Why it exists | +|---|---|---| +| `test_private_unpublished_entry_renders_without_network` | Renders the pinned GenHPF entry with access/status labels, without fetching metadata or inventing an install command. | Keep public docs builds independent of private access and distinguish declared names from published distributions. | +| `test_published_entry_generates_escaped_pinned_install_command` | Generates a version-pinned PyPI link/command and escapes names/notes as HTML. | Make installation reproducible and keep registry content inert. | +| `test_registry_rejects_ambiguous_or_unsafe_entries` | Rejects moving revisions, unknown profiles/states, duplicate profiles, unapproved listings, invalid URLs and review dates. | Require an auditable registration record. | +| `test_registry_rejects_invalid_install_or_evidence_fields` | Rejects malformed package names/versions, traversing report paths and unknown evidence statuses. | Prevent unsafe commands and ambiguous evidence links. | +| `test_registry_rejects_duplicates_and_unknown_fields` | Rejects duplicate IDs and unrecognized schema fields. | Catch copy/paste errors and misspelled metadata. | +| `test_release_observer_skips_private_source_and_never_changes_evidence` | Detects public PyPI candidates, ignores yanked/empty releases, skips private GitHub access, and produces stable observations without mutating entries. | Keep release discovery separate from scientific review and avoid timestamp-only PRs. | +| `test_missing_public_repository_and_yanked_reviewed_release_are_observed` | Records unavailable repositories and yanked reviewed releases. | Surface broken availability without silently choosing a replacement. | +| `test_public_github_release_and_absent_pypi_are_observed` | Observes a public GitHub release independently of PyPI availability. | A GitHub tag/release is not proof of an installable PyPI distribution. | +| `test_network_errors_are_not_missing_release_evidence` | Propagates server/rate-limit errors and verifies requests omit credentials. | Avoid false disappearance reports and private-source access. | +| `test_observation_snapshot_contains_only_metadata` | Checks the committed observation snapshot corresponds to registered entries. | Keep the example snapshot valid and separate from implementation reports. | + ### Generated algorithm release tests | Test | What it checks | Why it exists | diff --git a/catalogue/algorithms.yaml b/catalogue/algorithms.yaml new file mode 100644 index 0000000..51406b7 --- /dev/null +++ b/catalogue/algorithms.yaml @@ -0,0 +1,28 @@ +schema_version: 1 +algorithms: + - id: genhpf-upstream + name: GenHPF (upstream package) + description: MEDS adapter using the original GenHPF implementation. + repository: https://github.com/florian6973/meds-model-genhpf-upstream + access: private + public_listing: true + paper: https://arxiv.org/abs/2207.09858 + profiles: [supervised] + implementation_status: in_review + implementation_pr: 1 + revision: f749d61fbbec92b1cd05d57fdeaa428c365cc266 + reviewed_on: '2026-11-03' + package: + name: genhpf-meds + pypi_version: null + evidence: + report: IMPLEMENTATION_REPORT.md + synthetic: reported_pass + meds_dev: reported_pass + clinical_demo: pending + full_dataset: pending + notes: >- + Implementation is on open PR #1; main still contains stubs. Validation statuses summarize + the pinned implementation report, not a new independent execution. No PyPI distribution + was available at review; current dependencies include Git references. Repository and + evidence links require access. This is the first catalogue entry used to exercise registration. diff --git a/catalogue/updates.json b/catalogue/updates.json new file mode 100644 index 0000000..072195c --- /dev/null +++ b/catalogue/updates.json @@ -0,0 +1,13 @@ +{ + "observations": { + "genhpf-upstream": { + "latest_github_release": null, + "latest_pypi_release": null, + "pypi": "not_found", + "repository": "private_manual_review", + "reviewed_pypi_release": null, + "reviewed_release_available": null + } + }, + "schema_version": 1 +} diff --git a/docs/catalogue.py b/docs/catalogue.py new file mode 100644 index 0000000..ca45842 --- /dev/null +++ b/docs/catalogue.py @@ -0,0 +1,258 @@ +"""Validate/render the curated catalogue offline; optionally observe public release metadata.""" + +import argparse +import json +import re +from datetime import date +from html import escape +from pathlib import Path +from urllib.error import HTTPError +from urllib.parse import quote, urlsplit +from urllib.request import Request, urlopen + +import yaml +from meds_algorithm import ALGORITHM_PROFILES +from packaging.version import InvalidVersion, Version + +ROOT = Path(__file__).resolve().parents[1] +VALIDATION_LABELS = { + "reported_pass": "Pass reported", + "pending": "Pending", + "not_run": "Not run", + "failed": "Failed", + "not_reported": "Not reported", +} +STATUS_LABELS = { + "implemented": "Implemented", + "in_review": "Implementation under review", + "in_progress": "Implementation in progress", +} + + +def exact_fields(value, fields, context): + if not isinstance(value, dict) or set(value) != set(fields.split()): + raise ValueError(f"{context}: expected fields {fields}") + + +def text(value, context): + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{context}: expected nonempty text") + return value + + +def https_url(value): + parts = urlsplit(text(value, "URL")) + if parts.scheme != "https" or not parts.hostname or parts.username or parts.password: + raise ValueError("URLs must use HTTPS without credentials") + return value + + +def release_version(value): + # Also restrict characters before a version is used in a generated shell command. + if not isinstance(value, str) or not re.fullmatch(r"[0-9A-Za-z.!+_-]+", value): + raise ValueError("Invalid package version") + try: + return Version(value) + except InvalidVersion as error: + raise ValueError("Invalid package version") from error + + +def load_catalogue(path): + data = yaml.safe_load(Path(path).read_text(encoding="utf-8")) + exact_fields(data, "schema_version algorithms", "catalogue") + if type(data["schema_version"]) is not int or data["schema_version"] != 1: + raise ValueError("Unsupported catalogue schema") + if not isinstance(data["algorithms"], list): + raise ValueError("algorithms must be a list") + identifiers = set() + repositories = set() + for entry in data["algorithms"]: + exact_fields( + entry, + "id name description repository access public_listing paper profiles " + "implementation_status implementation_pr revision reviewed_on package evidence notes", + "entry", + ) + identifier = text(entry["id"], "id") + if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", identifier) or identifier in identifiers: + raise ValueError("Catalogue ids must be unique lowercase slugs") + identifiers.add(identifier) + for field in ("name", "description", "notes"): + text(entry[field], field) + repository = text(entry["repository"], "repository") + if not re.fullmatch(r"https://github\.com/[A-Za-z0-9_-]+/[A-Za-z0-9_.-]+", repository): + raise ValueError("Expected canonical GitHub repository URL") + if repository.lower() in repositories: + raise ValueError("Duplicate repository") + repositories.add(repository.lower()) + if entry["access"] not in ("public", "private") or entry["public_listing"] is not True: + raise ValueError( + "Every listing needs explicit public metadata approval and an access designation" + ) + if entry["paper"] is not None: + https_url(entry["paper"]) + profiles = entry["profiles"] + if ( + not isinstance(profiles, list) + or not profiles + or not all(isinstance(p, str) for p in profiles) + or len(set(profiles)) != len(profiles) + or not set(profiles) <= set(ALGORITHM_PROFILES) + ): + raise ValueError("Unknown, empty or duplicate profiles") + if entry["implementation_status"] not in STATUS_LABELS: + raise ValueError("Unknown implementation status") + pr = entry["implementation_pr"] + if pr is not None and (type(pr) is not int or pr <= 0): + raise ValueError("implementation_pr must be null or a positive integer") + if entry["implementation_status"] == "in_review" and pr is None: + raise ValueError("An implementation under review needs its PR number") + if not isinstance(entry["revision"], str) or not re.fullmatch(r"[0-9a-f]{40}", entry["revision"]): + raise ValueError("Review must pin a full immutable commit SHA") + reviewed = date.fromisoformat(text(entry["reviewed_on"], "reviewed_on")) + if reviewed > date.today(): + raise ValueError("Review date cannot be in the future") + exact_fields(entry["package"], "name pypi_version", "package") + package = entry["package"] + if not isinstance(package["name"], str) or not re.fullmatch( + r"[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?", package["name"] + ): + raise ValueError("Invalid distribution name") + if package["pypi_version"] is not None: + release_version(package["pypi_version"]) + exact_fields(entry["evidence"], "report synthetic meds_dev clinical_demo full_dataset", "evidence") + report = text(entry["evidence"]["report"], "report") + if not re.fullmatch(r"[A-Za-z0-9_./-]+\.md", report) or any( + p in ("", ".", "..") for p in report.split("/") + ): + raise ValueError("Report must be a repository-relative Markdown file") + for field, value in entry["evidence"].items(): + if field != "report" and value not in VALIDATION_LABELS: + raise ValueError(f"Unknown validation status for {field}") + return data["algorithms"] + + +def render_catalogue(entries): + sections = [] + for entry in entries: + repository = entry["repository"] + revision = entry["revision"] + source = f"{repository}/tree/{revision}" + report = f"{repository}/blob/{revision}/{entry['evidence']['report']}" + access = "Private — access required" if entry["access"] == "private" else "Public" + parts = [ + f'

{escape(entry["name"])}

', + f"

{escape(entry['description'])}

", + f"

{STATUS_LABELS[entry['implementation_status']]} · {access}

", + f'

Repository · ' + f'Reviewed revision {revision[:7]} · ' + f'Implementation report

', + ] + if entry["paper"]: + parts.append(f'

Paper

') + if entry["implementation_pr"]: + parts.append( + f'

Implementation PR

' + ) + parts.append( + f"

Declared profiles: {', '.join(entry['profiles'])}. " + f"Metadata reviewed: {entry['reviewed_on']}.

" + ) + package = entry["package"] + name, version = package["name"], package["pypi_version"] + if version is None: + parts.append( + f"

Declared package name: {name}. No reviewed PyPI release; " + "no PyPI installation command is advertised.

" + ) + else: + parts.append( + f'

' + f"{name} {version} on PyPI

" + ) + parts.append(f'
python -m pip install "{name}=={version}"
') + parts.append( + "" + "" + ) + for field, label in ( + ("synthetic", "Synthetic/local"), + ("meds_dev", "MEDS-DEV integration"), + ("clinical_demo", "Clinical demo"), + ("full_dataset", "Full dataset"), + ): + parts.append(f"") + parts.append(f"
Validation at the reviewed revisionEvidence
{label}{VALIDATION_LABELS[entry['evidence'][field]]}

{escape(entry['notes'])}

") + sections.append("\n".join(parts)) + return "\n\n".join(sections) or "No algorithms have been registered yet." + + +def on_page_markdown(markdown, page, **kwargs): + if page.file.src_uri == "implemented-algorithms.md": + entries = load_catalogue(ROOT / "catalogue/algorithms.yaml") + return markdown.replace("", render_catalogue(entries)) + return markdown + + +def fetch_json(url): + # Public metadata only. Do not send GitHub credentials or clone/import any algorithm. + request = Request(url, headers={"User-Agent": "MEDS-algorithm-catalogue", "Accept": "application/json"}) + try: + with urlopen(request, timeout=30) as response: + return json.load(response) + except HTTPError as error: + if error.code == 404: + return None + raise # Rate limits/network failures are errors, never evidence of an unavailable package. + + +def observe_releases(entries, fetch=fetch_json): + observations = {} + for entry in entries: + observation = {"repository": "private_manual_review", "latest_github_release": None} + if entry["access"] == "public": + api = "https://api.github.com/repos/" + entry["repository"].removeprefix("https://github.com/") + repository = fetch(api) + observation["repository"] = "available" if repository else "unavailable_or_private" + if repository: + release = fetch(api + "/releases/latest") + observation["latest_github_release"] = release.get("tag_name") if release else None + name = entry["package"]["name"] + metadata = fetch(f"https://pypi.org/pypi/{name}/json") + available = [] + if metadata: + for version, files in metadata.get("releases", {}).items(): + try: + parsed = release_version(version) + except ValueError: + continue + if any(not file.get("yanked", False) for file in files): + available.append((parsed, version)) + pinned = entry["package"]["pypi_version"] + observation.update( + pypi="available" if metadata else "not_found", + latest_pypi_release=max(available)[1] if available else None, + reviewed_pypi_release=pinned, + reviewed_release_available=any(version == pinned for _, version in available) if pinned else None, + ) + observations[entry["id"]] = observation + return {"schema_version": 1, "observations": observations} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--registry", type=Path, default=ROOT / "catalogue/algorithms.yaml") + parser.add_argument("--check-remote", action="store_true") + parser.add_argument("--output", type=Path, default=ROOT / "catalogue/updates.json") + args = parser.parse_args() + entries = load_catalogue(args.registry) + if args.check_remote: + result = observe_releases(entries) + args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print(f"Release observations written to {args.output}; curated evidence was not changed.") + else: + print(f"Validated {len(entries)} catalogue entries offline.") + + +if __name__ == "__main__": + main() diff --git a/docs/implemented-algorithms.md b/docs/implemented-algorithms.md new file mode 100644 index 0000000..89b5ba3 --- /dev/null +++ b/docs/implemented-algorithms.md @@ -0,0 +1,67 @@ +# Implemented algorithms + +This catalogue records implementations and their review status, including work under review. Listing is +not a claim of clinical validation. Profiles are declared capabilities; validation is summarized separately +from the linked implementation report at an immutable revision. “Pass reported” means the report records +a passing run, not that the catalogue build reran it. + +Published entries include their PyPI name and an exact-version installation command. An unpublished +package name is only the name declared in its repository; it is not reserved on PyPI. Private entries +are explicitly approved public metadata listings; their source and evidence links still require access. + + + +## Register or update an algorithm + +Open a PR editing `catalogue/algorithms.yaml` in the template repository. Copy an entry and supply: + +- A stable ID, display name, short description, repository access level and optional paper URL. +- The declared profiles and implementation status; include the PR number for work under review. +- The full commit SHA examined, date of metadata review and report path at that commit. +- The distribution name from `pyproject.toml`. Leave `pypi_version: null` until a release is actually + on PyPI and its ownership, source revision and validation evidence have been checked. Set an exact + reviewed version to generate its install command; do not set it merely because the name exists on PyPI. +- Separate evidence statuses for synthetic/local tests, MEDS-DEV, clinical demo and full-dataset runs: + `reported_pass`, `pending`, `not_run`, `failed`, or `not_reported`. Link the evidence rather than copying + private results, dataset descriptions or logs into the registry. +- `public_listing: true` only after the owner authorizes these metadata for public documentation. + +The schema accepts `implemented`, `in_review`, and `in_progress` implementation states. Profile names come +from the installed core contract. Keep one entry per repository even when it supports several profiles. +When updating a reviewed version, recheck its commit and evidence; a newer package is not automatically +validated. The registry is the single source for this page, including the install commands. + +```bash +uv sync --group docs +uv run python docs/catalogue.py +uv run --group docs mkdocs build --strict +``` + +## Keeping the catalogue current + +Normal docs builds and PR checks validate the committed registry offline. They do not fetch private +repositories, install algorithms, or require GitHub credentials. + +The **Catalogue updates** workflow runs weekly and can be dispatched manually. It checks public GitHub +repository availability/latest stable release and PyPI release availability, including prereleases and +yanked files. It skips private repository queries entirely. PyPI checks still use the approved public +package name. A network/rate-limit failure fails the job rather than marking the package missing. + +```bash +uv run python docs/catalogue.py --check-remote +gh workflow run catalogue.yml --repo McDermottHealthAI/MEDS_algorithm_template +``` + +The workflow writes `catalogue/updates.json` and opens or updates one PR only when observations change. +It does not change reviewed versions, implementation status or evidence. There is no timestamp churn. +Maintainers inspect that PR and separately update the curated entry after reviewing the new release. +The observation report is advisory; it neither establishes package ownership nor changes install commands. + +To enable update PRs after merging this workflow into `main`, allow GitHub Actions to create pull requests +under **Settings → Actions → General → Workflow permissions** (the organization may control this setting). +The workflow requests contents/PR write access only for its update job. The default `GITHUB_TOKEN` does +not trigger other PR workflows; this job runs registry tests and a strict docs build itself before opening +its report PR. A maintainer can run checks locally before changing curated entries. See the +[action's permission and token documentation](https://github.com/peter-evans/create-pull-request#workflow-permissions). +The workflow also uploads its report as an artifact, so observations remain available if PR creation is +disabled. Private entries need manual source/evidence review by someone with access. diff --git a/mkdocs.yml b/mkdocs.yml index 664581e..ddb22cc 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -7,6 +7,7 @@ repo_name: McDermottHealthAI/MEDS_algorithm_template edit_uri: edit/main/docs/ hooks: - docs/hooks.py + - docs/catalogue.py extra_css: - assets/prompt-builder.css @@ -70,6 +71,7 @@ nav: - Overview: index.md - Concepts: concepts.md - Choosing a profile: profiles.md + - Implemented algorithms: implemented-algorithms.md - Workflow: workflow.md - Building an algorithm: - Implementation prompt builder: prompt-builder.md diff --git a/pyproject.toml b/pyproject.toml index 88a9301..191725a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,7 +25,7 @@ packages = ["src/meds_algorithm_template"] [dependency-groups] dev = ["meds-algorithm[conformance,orchestration]==0.4.0a5", "polars>=1", "pyarrow>=15", "pytest>=8", "pyyaml>=6", "ruff"] # MkDocs 2.0 removes the plugin and theme systems Material depends on, so stay on 1.x. -docs = ["mkdocs>=1.6,<2", "mkdocs-material>=9.5,<10"] +docs = ["mkdocs>=1.6,<2", "mkdocs-material>=9.5,<10", "packaging>=24"] [tool.pytest.ini_options] testpaths = ["tests"] diff --git a/template/RELEASING.md.jinja b/template/RELEASING.md.jinja index 4928db8..ec54f4e 100644 --- a/template/RELEASING.md.jinja +++ b/template/RELEASING.md.jinja @@ -85,6 +85,18 @@ files using Trusted Publishing. Rehearsal and production runs each build and che from the same tag. After success, install `{{ package_name }}==$version` in a fresh environment and repeat the smoke check. Never move a published tag or reuse a published version; increment it for fixes. +## Registering your algorithm + +After publication, register the package in the template documentation's +[algorithm catalogue](https://mcdermotthealthai.github.io/MEDS_algorithm_template/implemented-algorithms/). +Open a PR against `catalogue/algorithms.yaml` with the PyPI name `{{ package_name }}`, exact published +version, immutable implementation commit, declared profiles and links to validation evidence. The site +generates the installation command from that reviewed pin. An implementation under review can be listed +earlier with `pypi_version: null`; do not advertise an install command for an unpublished name. +For a private repository, authorize only metadata intended for public listing and mark access private. +Update the entry when a new release has been reviewed; automated release discovery does not establish +scientific validation. Keep dataset contents and private run details out of the public catalogue. + ## What installation includes `configs/runs/` and `algorithms/` are the single editable source for portable run defaults and MEDS-DEV diff --git a/tests/test_catalogue.py b/tests/test_catalogue.py new file mode 100644 index 0000000..8f324c6 --- /dev/null +++ b/tests/test_catalogue.py @@ -0,0 +1,174 @@ +"""Catalogue evidence is curated; network observations cannot silently promote it.""" + +import copy +import importlib.util +import json +from pathlib import Path +from types import SimpleNamespace +from urllib.error import HTTPError + +import pytest +import yaml + +ROOT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location("catalogue", ROOT / "docs/catalogue.py") +catalogue = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(catalogue) + + +def sample_entry(): + return copy.deepcopy(catalogue.load_catalogue(ROOT / "catalogue/algorithms.yaml")[0]) + + +def write_registry(tmp_path, entries): + path = tmp_path / "algorithms.yaml" + path.write_text(yaml.safe_dump({"schema_version": 1, "algorithms": entries}), encoding="utf-8") + return path + + +def test_private_unpublished_entry_renders_without_network(monkeypatch): + monkeypatch.setattr(catalogue, "fetch_json", lambda url: pytest.fail("Docs must build offline")) + page = SimpleNamespace(file=SimpleNamespace(src_uri="implemented-algorithms.md")) + result = catalogue.on_page_markdown("", page) + assert "genhpf-meds" in result + assert "Private — access required" in result + assert "Implementation under review" in result + assert "Pass reported" in result and "Pending" in result + assert "python -m pip install" not in result + assert "f749d61fbbec92b1cd05d57fdeaa428c365cc266/IMPLEMENTATION_REPORT.md" in result + + +def test_published_entry_generates_escaped_pinned_install_command(tmp_path): + entry = sample_entry() + entry["package"]["pypi_version"] = "0.2.0a1" + entry["name"] = '' + entry["notes"] = '' + entries = catalogue.load_catalogue(write_registry(tmp_path, [entry])) + result = catalogue.render_catalogue(entries) + assert 'python -m pip install "genhpf-meds==0.2.0a1"' in result + assert "https://pypi.org/project/genhpf-meds/0.2.0a1/" in result + assert "' - entry["notes"] = '' - entries = catalogue.load_catalogue(write_registry(tmp_path, [entry])) - result = catalogue.render_catalogue(entries) - assert 'python -m pip install "genhpf-meds==0.2.0a1"' in result - assert "https://pypi.org/project/genhpf-meds/0.2.0a1/" in result - assert "