From 8fc0d938f0dd40aefd20c7d9fddab79820a777eb Mon Sep 17 00:00:00 2001 From: Rand McKinney Date: Fri, 13 Nov 2026 09:27:07 -0800 Subject: [PATCH 1/3] ci: require successful documentation validation and builds Validate candidate version configuration independently of the contributor trust gate, reuse the base branch validator, and fail the final docs check on skipped builds. Upload generated HTML and add configuration regressions without modifying versions.json. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/ci.yml | 63 ++++++++++++++++++++++++++++++++++++ README.md | 13 +++++++- tests/test_versioned_docs.py | 13 ++++++++ 3 files changed, 88 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 68d610f..0c0dcfa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,11 +9,51 @@ on: - reopened - synchronize - labeled + - unlabeled push: branches: - main jobs: + docs-config: + name: Documentation version configuration + permissions: + contents: read + runs-on: ubuntu-latest + steps: + - name: Checkout trusted validator + uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.base.sha || github.sha }} + path: trusted + persist-credentials: false + sparse-checkout: scripts/generate_versioned_api_docs.py + sparse-checkout-cone-mode: false + - name: Checkout candidate configuration + uses: actions/checkout@v4 + with: + path: candidate + persist-credentials: false + sparse-checkout: api-docs/versions.json + sparse-checkout-cone-mode: false + - uses: actions/setup-python@v5 + with: + python-version: '3.10' + - name: Validate candidate configuration with trusted code + working-directory: trusted + run: | + python3 -I - <<'PY' + import importlib.util + from pathlib import Path + + spec = importlib.util.spec_from_file_location( + "docs", "scripts/generate_versioned_api_docs.py" + ) + docs = importlib.util.module_from_spec(spec) + spec.loader.exec_module(docs) + docs.load_versions(Path("../candidate/api-docs/versions.json")) + PY + docs: name: Versioned API documentation permissions: @@ -43,6 +83,29 @@ jobs: env: GH_TOKEN: ${{ github.token }} run: python3 scripts/generate_versioned_api_docs.py + - name: Upload documentation preview + uses: actions/upload-artifact@v4 + with: + name: versioned-api-documentation + path: api-docs/_build/versioned/ + if-no-files-found: error + + docs-required: + name: Documentation checks + needs: [docs-config, docs] + if: always() + permissions: {} + runs-on: ubuntu-latest + steps: + - name: Require successful validation and build + env: + CONFIG_RESULT: ${{ needs.docs-config.result }} + BUILD_RESULT: ${{ needs.docs.result }} + run: | + if [ "$CONFIG_RESULT" != success ] || [ "$BUILD_RESULT" != success ]; then + echo "::error::Documentation checks did not succeed (configuration: $CONFIG_RESULT, build: $BUILD_RESULT). A maintainer must authorize gated builds with the 'safe to test' label." + exit 1 + fi tests: name: Unit tests diff --git a/README.md b/README.md index 4fcd14d..e460362 100644 --- a/README.md +++ b/README.md @@ -252,7 +252,18 @@ node --test tests/test_version_selector.js ``` The selector tests require Node.js 18 or newer. CI runs these tests and builds -the versioned documentation on pull requests. +the versioned documentation on authorized pull requests, uploading the generated +site as the `versioned-api-documentation` artifact. For contributors outside the +existing trust gate, a maintainer must add the `safe to test` label to authorize +the full build. + +The **Documentation version configuration** check runs independently of that +gate. It validates the candidate `api-docs/versions.json` with the base branch's +validator, without importing candidate Python code. The **Documentation checks** +job fails unless both configuration validation and the full docs build succeed, +including when the build is skipped. Configure branch protection or repository +rules to require **Documentation checks** so skipped builds cannot satisfy the +merge requirement. ## License diff --git a/tests/test_versioned_docs.py b/tests/test_versioned_docs.py index 00564b6..d5b8e64 100644 --- a/tests/test_versioned_docs.py +++ b/tests/test_versioned_docs.py @@ -12,6 +12,9 @@ class VersionedDocsTests(unittest.TestCase): + def test_checked_in_version_list_is_valid(self): + docs.load_versions(docs.ROOT / "api-docs/versions.json") + def test_version_list_preserves_default_and_order(self): with tempfile.TemporaryDirectory() as directory: config = Path(directory) / "versions.json" @@ -34,6 +37,16 @@ def test_invalid_version_lists_are_rejected(self): with self.assertRaises(ValueError): docs.load_versions(config) + def test_malformed_version_json_is_rejected(self): + with tempfile.TemporaryDirectory() as directory: + config = Path(directory) / "versions.json" + config.write_text( + '{"versions": ["v0.26.17","versions": ["v0.26.16"]}', + encoding="utf-8", + ) + with self.assertRaises(json.JSONDecodeError): + docs.load_versions(config) + @patch.object(docs.subprocess, "run") def test_published_release_is_verified(self, run): run.return_value = Mock( From 9f2a8c92752d49e5155fa6b24d2d69b29824b52e Mon Sep 17 00:00:00 2001 From: Rand McKinney Date: Wed, 25 Nov 2026 09:41:36 -0800 Subject: [PATCH 2/3] docs: publish stable API release lines with App promotion Validate and reconcile retained release lines, preserve exact-tag redirects, and isolate manifest promotion from Pages builds. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- .github/workflows/promote-docs.yml | 49 +++++++ .github/workflows/publish-docs.yml | 91 ++++++------ README.md | 111 +++++++++++--- api-docs/versions.json | 24 +-- docs/version-selector.js | 5 +- scripts/docs_versions.py | 105 ++++++++++++++ scripts/generate_versioned_api_docs.py | 43 +++--- scripts/promote_docs_versions.py | 84 +++++++++++ tests/test_docs_promotion.py | 193 +++++++++++++++++++++++++ tests/test_version_selector.js | 13 +- tests/test_versioned_docs.py | 45 ++++-- 12 files changed, 648 insertions(+), 117 deletions(-) create mode 100644 .github/workflows/promote-docs.yml create mode 100644 scripts/docs_versions.py create mode 100644 scripts/promote_docs_versions.py create mode 100644 tests/test_docs_promotion.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8940bc8..8c94cbb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,7 +37,7 @@ jobs: run: sudo apt-get install doxygen - name: Test documentation tooling run: | - python3 -m unittest discover -s tests -p 'test_versioned_docs.py' + python3 -m unittest discover -s tests -p 'test_*docs*.py' node --test tests/test_version_selector.js - name: Build versioned documentation env: diff --git a/.github/workflows/promote-docs.yml b/.github/workflows/promote-docs.yml new file mode 100644 index 0000000..1b6e107 --- /dev/null +++ b/.github/workflows/promote-docs.yml @@ -0,0 +1,49 @@ +name: Promote API documentation versions + +on: + release: + types: [published] + schedule: + - cron: '17 * * * *' + workflow_dispatch: + +permissions: + contents: read + +# Do not serialize promotions with Actions concurrency: pending runs can be lost. +# Each run reconciles all releases and retries conflicting manifest writes. +jobs: + promote: + if: github.event_name != 'release' || github.event.release.prerelease == false + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: main + persist-credentials: false + + - name: Require dedicated documentation App credentials + env: + APP_ID: ${{ vars.C2PA_DOCS_APP_ID }} + APP_KEY: ${{ secrets.C2PA_DOCS_APP_PRIVATE_KEY }} + run: | + if [[ -z "$APP_ID" || -z "$APP_KEY" ]]; then + echo "::error::Configure vars.C2PA_DOCS_APP_ID and secrets.C2PA_DOCS_APP_PRIVATE_KEY for the dedicated documentation GitHub App." + exit 1 + fi + + - name: Create repository-scoped manifest promotion token + id: app + uses: actions/create-github-app-token@v2 + with: + app-id: ${{ vars.C2PA_DOCS_APP_ID }} + private-key: ${{ secrets.C2PA_DOCS_APP_PRIVATE_KEY }} + owner: ${{ github.repository_owner }} + repositories: ${{ github.event.repository.name }} + permission-contents: write + + - name: Reconcile stable published releases into the manifest only + env: + DOCS_APP_TOKEN: ${{ steps.app.outputs.token }} + RELEASE_TAG: ${{ github.event_name == 'release' && github.event.release.tag_name || '' }} + run: python3 scripts/promote_docs_versions.py diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index a2cd0f2..b0300b3 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -1,74 +1,39 @@ name: Build and publish docs on: - release: - types: [published] - push: branches: ['main'] workflow_dispatch: + workflow_run: + workflows: ['Promote API documentation versions'] + types: [completed] + permissions: contents: read - pages: write - id-token: write concurrency: - group: 'github-pages' + group: github-pages cancel-in-progress: false jobs: - update-versions: - if: github.event_name == 'release' && github.event.release.prerelease == false - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - uses: actions/checkout@v4 - with: - ref: main - - - name: Update documentation versions - env: - RELEASE_TAG: ${{ github.event.release.tag_name }} - run: | - if [[ ! "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then - echo "::error::Expected a stable release tag such as v0.26.14." - exit 1 - fi - jq --arg tag "$RELEASE_TAG" \ - '.versions = [$tag] + (.versions - [$tag])' \ - api-docs/versions.json > "$RUNNER_TEMP/versions.json" - mv "$RUNNER_TEMP/versions.json" api-docs/versions.json - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git add api-docs/versions.json - if git diff --cached --quiet; then - echo "Documentation versions already include $RELEASE_TAG as the default." - else - git commit -m "docs: update API documentation versions for $RELEASE_TAG" - git push origin HEAD:main - fi - - deploy: - needs: update-versions - if: | - !cancelled() && - (needs.update-versions.result == 'success' || needs.update-versions.result == 'skipped') - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} + build: + if: github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' runs-on: ubuntu-latest + outputs: + revision: ${{ steps.revision.outputs.sha }} steps: - uses: actions/checkout@v4 with: filter: tree:0 fetch-depth: 0 ref: main + persist-credentials: false - - name: Setup Pages - uses: actions/configure-pages@v5 + - name: Record current main revision + id: revision + run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - name: Install Doxygen run: sudo apt-get install doxygen @@ -88,6 +53,36 @@ jobs: with: path: 'api-docs/_build/versioned/' + deploy: + needs: build + runs-on: ubuntu-latest + permissions: + contents: read + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Reject stale artifacts + id: current + env: + GH_TOKEN: ${{ github.token }} + BUILT_SHA: ${{ needs.build.outputs.revision }} + REPOSITORY: ${{ github.repository }} + run: | + current=$(gh api "repos/$REPOSITORY/git/ref/heads/main" --jq .object.sha) + if [[ "$current" == "$BUILT_SHA" ]]; then + echo "deploy=true" >> "$GITHUB_OUTPUT" + else + echo "Skipping stale artifact $BUILT_SHA; main is $current." + fi + + - name: Setup Pages + if: steps.current.outputs.deploy == 'true' + uses: actions/configure-pages@v5 + - name: Deploy to GitHub Pages + if: steps.current.outputs.deploy == 'true' id: deployment uses: actions/deploy-pages@v4 \ No newline at end of file diff --git a/README.md b/README.md index fcd9ddf..8058259 100644 --- a/README.md +++ b/README.md @@ -184,10 +184,12 @@ ctest --test-dir build/debug --output-on-failure ### Building API documentation The [API documentation](https://contentauth.github.io/c2pa-cpp/) is built with -Doxygen from selected published releases. Use the version selector to switch -releases. The first tag in `api-docs/versions.json` is -the default at the existing root URL; each release is also available at -`https://contentauth.github.io/c2pa-cpp/versions//`. +Doxygen from selected published stable releases. The selector displays major/minor +lines (`X.Y`); each page displays the exact `vX.Y.Z` patch that supplied its source. +`api-docs/versions.json` retains one highest stable patch per selected line, +sorted by numeric semver descending. The highest line is the default at the +existing root URL; canonical line pages are under +`https://contentauth.github.io/c2pa-cpp/versions/X.Y/`. #### Preview the versioned site @@ -209,8 +211,8 @@ python3 scripts/generate_versioned_api_docs.py Open `api-docs/_build/versioned/index.html` to preview the default release, including the version selector. -Version-specific pages are under `api-docs/_build/versioned/versions//`. -The build verifies that each configured tag has a published GitHub release and +Line-specific pages are under `api-docs/_build/versioned/versions/X.Y/`. +The build verifies that each configured tag has a published stable GitHub release and reads that tag's headers, C sources, and README without running release code. It uses the current branch's Doxygen configuration and styling. @@ -228,28 +230,89 @@ tree and does not include a version selector or require GitHub authentication. #### Publishing -Publishing a stable GitHub release automatically prepends its exact `vX.Y.Z` -tag to `api-docs/versions.json` on `main`, preserving older entries and -promoting an existing tag without duplicates. The bot commits this update -after publication; it does not modify the release tag. The same workflow then -builds and deploys the updated site, without relying on the bot's push -triggering another workflow. Prerelease publications rebuild the configured -versions without changing the version list. Rerunning a release workflow -does not create an empty commit. - -The version-update job requires `contents: write`, and branch protection or -repository rules must allow `github-actions[bot]` to push to `main`. If that -push fails, deployment is blocked rather than publishing a stale version list. -The deployment job retains read-only repository access. - -To adjust the selected releases manually, edit `api-docs/versions.json`, -putting the desired default first. Pushes to `main` and manual workflow runs -also rebuild and deploy the site without changing the version list. +`promote-docs.yml` reconciles published stable GitHub releases on release +publication, manual dispatch, and hourly recovery. It verifies release metadata, +updates retained lines only to higher patches, and adds newly released lines +above the highest known active or retired line. It never backfills unselected +historical lines or restores retired lines. Older maintenance releases cannot +regress a patch or move the default. Drafts and prereleases are excluded. + +The dependency-free Python updater writes **only `api-docs/versions.json` on +`main`** through the GitHub contents API. Each commit is guarded by the current +file SHA; conflicts trigger a fresh manifest read and full release reconciliation, +up to six attempts, without force pushes. Repeated runs make no empty commits. +Promotion runs have no Actions concurrency group: pending concurrency runs are +not a durable release queue. Full paginated reconciliation and hourly recovery +also catch missed events or exhausted retries. Failed runs remain visible and +can be rerun manually. + +After a successful promotion workflow, `publish-docs.yml` explicitly rebuilds +current `main` through `workflow_run`, even if promotion made no change; it does +not rely on a bot push. Main pushes and manual publishing dispatches remain +supported. A single workflow-wide Pages lock serializes build/deploy pairs. +Every admitted run checks out current `main`, rather than the triggering SHA, +so replacing a pending run does not discard release updates. Deployment skips +an artifact if `main` advanced during its build; the pending current-main run +rebuilds it. Builds have read-only contents access and no App credentials; +only the deployment job has Pages and OIDC write permissions. No release +workflow is triggered by manifest commits. + +##### GitHub App setup (administrator action) + +Use the shared organization documentation GitHub App with **Contents: read and +write** (plus implicit metadata read). Its installation must include +`contentauth/c2pa-cpp`. Expose the organization variable `C2PA_DOCS_APP_ID` and +organization secret `C2PA_DOCS_APP_PRIVATE_KEY` to this repository through their +repository-access policies. The workflow consumes them as +`vars.C2PA_DOCS_APP_ID` and `secrets.C2PA_DOCS_APP_PRIVATE_KEY`; no repository-local +copies are required. Configure the `main` ruleset or +branch protection to allow this App's manifest commits, including any required +pull-request bypass. Organization App provisioning alone does not establish +installation access, credential visibility, or permission to bypass protections; +administrators must verify these separately. The tooling does not change them. +Keep the installation narrowly scoped to the intended documentation repositories: +GitHub does not provide +file-level Contents permissions, so the updater's fixed contents endpoint is +the manifest-only write allowlist. + +Promotion mints a short-lived repository-scoped installation token requesting +only Contents write, revokes it at job end, and never passes it to dependency +installation, Doxygen, or deployment. Missing App configuration fails with an +explicit error; there is no ordinary-token fallback. Leave Pages configured +for GitHub Actions and authorize the `github-pages` deployment environment. +Local tests/builds do not verify App installation, ruleset bypass, or live Pages +deployment; confirm those separately after administrator setup. + +##### Manifest maintenance and pruning + +The manifest has exactly three fields: + +- `versions`: non-empty exact stable `vX.Y.Z` tags, one per active line, in + descending numeric semver order. Index zero is always the default. +- `aliases`: historical exact tag/path identifiers mapped to an active unprefixed + `X.Y`. Include the selected exact tags too. Identifiers must be single safe URL + path segments (not reserved canonical `X.Y` names), and exact-tag aliases must + point to their own line. +- `retiredLines`: unique unprefixed `X.Y` lines disjoint from active lines. + +The migration consolidates the previously listed patches without adding +historical lines. It retains all their exact-tag URLs as redirect HTML to the +current patch for that line. Redirects preserve equivalent HTML page paths, +query strings and fragments; removed pages or symbols cannot be guaranteed. +These redirects are compatibility links, not immutable historical snapshots. +Automation preserves existing aliases and adds aliases for newly selected tags. + +To prune a line, open a **human-reviewed PR** removing its tag from `versions` +and all aliases targeting that line, and adding the line to `retiredLines`. +Keep at least one active line. Do not remove the retirement marker: automation +must never resurrect it. To explicitly retain an otherwise unselected historical +line, use a human PR adding its highest published stable patch and exact-tag +alias. All builds and promotions validate the contract before proceeding. Run the documentation tooling tests with: ```sh -python3 -m unittest discover -s tests -p 'test_versioned_docs.py' +python3 -m unittest discover -s tests -p 'test_*docs*.py' node --test tests/test_version_selector.js ``` diff --git a/api-docs/versions.json b/api-docs/versions.json index 79e11cf..8d11bb3 100644 --- a/api-docs/versions.json +++ b/api-docs/versions.json @@ -1,12 +1,18 @@ { "versions": [ - "v0.27.0", - "v0.26.19", - "v0.26.18", - "v0.26.17", - "v0.26.16", - "v0.26.15", - "v0.26.14", - "v0.26.13" - ] + "v0.27.1", + "v0.26.19" + ], + "aliases": { + "v0.27.1": "0.27", + "v0.27.0": "0.27", + "v0.26.19": "0.26", + "v0.26.18": "0.26", + "v0.26.17": "0.26", + "v0.26.16": "0.26", + "v0.26.15": "0.26", + "v0.26.14": "0.26", + "v0.26.13": "0.26" + }, + "retiredLines": [] } diff --git a/docs/version-selector.js b/docs/version-selector.js index 865df83..0abd932 100644 --- a/docs/version-selector.js +++ b/docs/version-selector.js @@ -16,9 +16,10 @@ const select = document.createElement("select"); select.setAttribute("aria-label", "API documentation version"); for (const tag of versions) { + const line = tag.slice(1).split(".").slice(0, 2).join("."); const option = document.createElement("option"); - option.value = new URL("versions/" + tag + "/index.html", root).href; - option.textContent = tag; + option.value = new URL("versions/" + line + "/index.html", root).href; + option.textContent = line; option.selected = tag === script.dataset.version; select.appendChild(option); } diff --git a/scripts/docs_versions.py b/scripts/docs_versions.py new file mode 100644 index 0000000..581b798 --- /dev/null +++ b/scripts/docs_versions.py @@ -0,0 +1,105 @@ +"""Validated API documentation selection and monotonic release reconciliation.""" + +import json +import re +from pathlib import Path + + +NUMBER = r"(?:0|[1-9][0-9]*)" +TAG = re.compile(rf"v({NUMBER})\.({NUMBER})\.({NUMBER})") +LINE = re.compile(rf"({NUMBER})\.({NUMBER})") +ALIAS = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*") + + +def version(tag: str) -> tuple[int, int, int]: + if not isinstance(tag, str) or not (match := TAG.fullmatch(tag)): + raise ValueError(f"Expected an exact stable vX.Y.Z tag: {tag!r}") + return tuple(map(int, match.groups())) + + +def line(tag: str) -> str: + major, minor, _ = version(tag) + return f"{major}.{minor}" + + +def validate(config: dict) -> dict: + if not isinstance(config, dict) or set(config) != {"versions", "aliases", "retiredLines"}: + raise ValueError("Manifest requires exactly versions, aliases and retiredLines.") + versions, aliases, retired = (config[key] for key in ("versions", "aliases", "retiredLines")) + if not isinstance(versions, list) or not versions: + raise ValueError("Documentation versions must be a non-empty list.") + ordered = [version(tag) for tag in versions] + lines = [line(tag) for tag in versions] + if len(set(lines)) != len(lines) or ordered != sorted(ordered, reverse=True): + raise ValueError("Versions require unique major/minor lines in descending semver order.") + if not isinstance(retired, list) or any( + not isinstance(value, str) or not LINE.fullmatch(value) for value in retired + ): + raise ValueError("retiredLines must be an array of unprefixed X.Y lines.") + if len(set(retired)) != len(retired) or set(lines) & set(retired): + raise ValueError("Retired lines must be unique and not active.") + if not isinstance(aliases, dict): + raise ValueError("aliases must be an object.") + for alias, target in aliases.items(): + if ( + not isinstance(alias, str) or not ALIAS.fullmatch(alias) + or alias in (".", "..") or LINE.fullmatch(alias) + or not isinstance(target, str) or target not in lines + or (TAG.fullmatch(alias) and line(alias) != target) + ): + raise ValueError(f"Invalid documentation alias: {alias!r} -> {target!r}") + if any(aliases.get(tag) != line(tag) for tag in versions): + raise ValueError("Every selected exact tag must alias its canonical line.") + return config + + +def parse(text: str) -> dict: + def unique_keys(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate manifest key: {key}") + result[key] = value + return result + return validate(json.loads(text, object_pairs_hook=unique_keys)) + + +def load(path: Path) -> dict: + return parse(path.read_text(encoding="utf-8")) + + +def published_stable(release: dict) -> bool: + return ( + isinstance(release, dict) + and isinstance(release.get("tag_name"), str) + and TAG.fullmatch(release["tag_name"]) is not None + and release.get("draft") is False + and release.get("prerelease") is False + and isinstance(release.get("published_at"), str) + and bool(release["published_at"]) + ) + + +def reconcile(config: dict, releases: list[dict]) -> dict: + validate(config) + selected = {line(tag): tag for tag in config["versions"]} + retired = set(config["retiredLines"]) + floor = max(tuple(map(int, value.split("."))) for value in set(selected) | retired) + aliases = dict(config["aliases"]) + for release in releases: + if not published_stable(release): + continue + tag = release["tag_name"] + key = line(tag) + if key in retired or (key not in selected and version(tag)[:2] <= floor): + continue + previous = selected.get(key) + if previous is None or version(tag) > version(previous): + selected[key] = tag + for key, tag in selected.items(): + aliases[tag] = key + return validate({ + "versions": sorted(selected.values(), key=version, reverse=True), + "aliases": dict(sorted(aliases.items())), + "retiredLines": config["retiredLines"], + }) diff --git a/scripts/generate_versioned_api_docs.py b/scripts/generate_versioned_api_docs.py index 05d52e6..a1d5ac7 100644 --- a/scripts/generate_versioned_api_docs.py +++ b/scripts/generate_versioned_api_docs.py @@ -5,29 +5,23 @@ import io import json from pathlib import Path, PurePosixPath -import re import shutil import stat import subprocess import tempfile import zipfile +try: + from .docs_versions import line, load, published_stable +except ImportError: + from docs_versions import line, load, published_stable + ROOT = Path(__file__).resolve().parents[1] -TAG_PATTERN = re.compile(r"v[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9][A-Za-z0-9.-]*)?") def load_versions(path: Path) -> list[str]: - config = json.loads(path.read_text(encoding="utf-8")) - versions = config.get("versions") if isinstance(config, dict) else None - if not isinstance(versions, list) or not versions: - raise ValueError("Documentation versions must be a non-empty list.") - for tag in versions: - if not isinstance(tag, str) or not TAG_PATTERN.fullmatch(tag): - raise ValueError("Documentation versions must be release tags such as v0.26.14.") - if len(set(versions)) != len(versions): - raise ValueError("Documentation versions must not contain duplicate tags.") - return versions + return load(path)["versions"] def verify_release(tag: str) -> None: @@ -37,9 +31,8 @@ def verify_release(tag: str) -> None: ) release = json.loads(result.stdout) if ( - not isinstance(release, dict) + not published_stable(release) or release.get("tag_name") != tag - or release.get("draft") is not False ): raise ValueError(f"{tag} is not a published GitHub release.") @@ -113,7 +106,8 @@ def build_html(stage: Path, output: Path, tag: str, versions: list[str], prefix: def build_site() -> Path: - versions = load_versions(ROOT / "api-docs/versions.json") + config = load(ROOT / "api-docs/versions.json") + versions = config["versions"] for tag in versions: verify_release(tag) @@ -132,14 +126,29 @@ def build_site() -> Path: for asset in ("doxygen-extra.css", "version-selector.js"): shutil.copy2(ROOT / "docs" / asset, stage / "docs") destination = stage / "output" - build_html(stage, destination, tag, versions, f"versions/{tag}") - shutil.copytree(destination / "html", site / "versions" / tag) + build_html(stage, destination, tag, versions, f"versions/{line(tag)}") + shutil.copytree(destination / "html", site / "versions" / line(tag)) # Rebuild the default so selector links also work at the existing root URL. default = workspace / versions[0] destination = default / "default-output" build_html(default, destination, versions[0], versions, "") shutil.copytree(destination / "html", site, dirs_exist_ok=True) + for alias, target in config["aliases"].items(): + canonical = site / "versions" / target + for page in canonical.rglob("*.html"): + relative = page.relative_to(canonical) + redirect = site / "versions" / alias / relative + redirect.parent.mkdir(parents=True, exist_ok=True) + destination = "../" * len(relative.parts) + target + "/" + relative.as_posix() + redirect.write_text( + 'Documentation moved' + f'' + '' + f'Continue to documentation', + encoding="utf-8", + ) (site / ".nojekyll").touch() if output.exists(): shutil.rmtree(output) diff --git a/scripts/promote_docs_versions.py b/scripts/promote_docs_versions.py new file mode 100644 index 0000000..8745461 --- /dev/null +++ b/scripts/promote_docs_versions.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Reconcile published releases using manifest-only optimistic API writes.""" + +import base64 +import json +import os +import time +from urllib.error import HTTPError +from urllib.request import Request, urlopen + +try: + from .docs_versions import parse, published_stable, reconcile, version +except ImportError: + from docs_versions import parse, published_stable, reconcile, version + + +MANIFEST = "api-docs/versions.json" +REPOSITORY = "contentauth/c2pa-cpp" + + +def api(method: str, path: str, token: str, data=None): + request = Request( + f"https://api.github.com/repos/{REPOSITORY}/{path}", + data=json.dumps(data).encode() if data is not None else None, + method=method, + headers={ + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "Content-Type": "application/json", + }, + ) + with urlopen(request, timeout=60) as response: + return json.load(response) + + +def promote(token: str, release_tag: str = "", attempts: int = 6) -> bool: + if not token: + raise ValueError("A dedicated C2PA docs GitHub App installation token is required.") + event_releases = [] + if release_tag: + version(release_tag) + release = api("GET", f"releases/tags/{release_tag}", token) + if not published_stable(release) or release["tag_name"] != release_tag: + raise ValueError(f"{release_tag} is not a published stable release.") + event_releases.append(release) + for attempt in range(attempts): + current = api("GET", f"contents/{MANIFEST}?ref=main", token) + config = parse(base64.b64decode(current["content"]).decode("utf-8")) + releases = list(event_releases) + page = 1 + while True: + batch = api("GET", f"releases?per_page=100&page={page}", token) + if not isinstance(batch, list): + raise ValueError("GitHub releases response is not an array.") + releases.extend(batch) + if len(batch) < 100: + break + page += 1 + updated = reconcile(config, releases) + if updated == config: + print("Documentation versions are already current.") + return False + content = (json.dumps(updated, indent=2) + "\n").encode() + try: + # The only write endpoint is this exact manifest path on main. + api("PUT", f"contents/{MANIFEST}", token, { + "message": "docs: reconcile published API documentation versions", + "branch": "main", + "sha": current["sha"], + "content": base64.b64encode(content).decode(), + }) + print("Promoted API documentation versions on main.") + return True + except HTTPError as error: + error.close() + if error.code not in (409, 422) or attempt + 1 == attempts: + raise + time.sleep(attempt + 1) + raise RuntimeError("Manifest promotion exhausted its retry budget.") + + +if __name__ == "__main__": + promote(os.environ.get("DOCS_APP_TOKEN", ""), os.environ.get("RELEASE_TAG", "")) diff --git a/tests/test_docs_promotion.py b/tests/test_docs_promotion.py new file mode 100644 index 0000000..e44547a --- /dev/null +++ b/tests/test_docs_promotion.py @@ -0,0 +1,193 @@ +import base64 +import copy +import json +import unittest +from unittest.mock import patch +from urllib.error import HTTPError + +from scripts import docs_versions as versions +from scripts import promote_docs_versions as promotion + + +def manifest(): + return { + "versions": ["v0.27.0", "v0.26.19"], + "aliases": {"v0.27.0": "0.27", "v0.26.19": "0.26"}, + "retiredLines": [], + } + + +def release(tag, **changes): + return dict(tag_name=tag, draft=False, prerelease=False, + published_at="2026-11-19T00:00:00Z", **changes) + + +def content(config, sha="before"): + return {"sha": sha, "content": base64.b64encode(json.dumps(config).encode()).decode()} + + +class DocsManifestTests(unittest.TestCase): + def test_invalid_contracts_fail(self): + mutations = [ + {"versions": []}, + {"versions": ["v0.26.19", "v0.27.0"]}, + {"versions": ["v0.27.0", "v0.27.1"]}, + {"versions": ["v0.27.0-rc.1"]}, + {"versions": ["v00.27.0"]}, + {"versions": [None]}, + {"versions": "v0.27.0"}, + {"retiredLines": ["0.26"]}, + {"retiredLines": ["v0.25"]}, + {"retiredLines": ["0.25", "0.25"]}, + {"retiredLines": {}}, + {"aliases": []}, + {"aliases": {"../escape": "0.26"}}, + {"aliases": {"0.26": "0.26"}}, + {"aliases": dict(manifest()["aliases"], **{"0.28": "0.26"})}, + {"aliases": {"v0.26.19": "0.27"}}, + {"aliases": {"v0.25.0": "0.25"}}, + {"aliases": {}}, + {"unexpected": True}, + ] + for mutation in mutations: + with self.subTest(mutation=mutation), self.assertRaises(ValueError): + versions.validate(dict(manifest(), **mutation)) + with self.assertRaisesRegex(ValueError, "Duplicate"): + versions.parse('{"versions": [], "aliases": {"old": "0.26", "old": "0.27"}}') + + def test_patch_updates_are_monotonic_and_idempotent(self): + original = manifest() + releases = [release("v0.26.20"), release("v0.26.18"), release("v0.27.0")] + updated = versions.reconcile(original, releases) + self.assertEqual(updated["versions"], ["v0.27.0", "v0.26.20"]) + self.assertEqual(updated["aliases"]["v0.26.19"], "0.26") + self.assertEqual(updated["aliases"]["v0.26.20"], "0.26") + self.assertEqual(versions.reconcile(updated, releases), updated) + self.assertEqual(original, manifest()) + + def test_numeric_order_burst_releases_and_no_historical_backfill(self): + updated = versions.reconcile(manifest(), [ + release("v0.29.2"), release("v0.28.0"), release("v0.29.10"), + release("v0.25.99"), release("v0.26.100"), release("v1.0.0"), + ]) + self.assertEqual(updated["versions"], [ + "v1.0.0", "v0.29.10", "v0.28.0", "v0.27.0", "v0.26.100", + ]) + self.assertNotIn("v0.25.99", updated["aliases"]) + + def test_numeric_minor_order_does_not_use_lexical_sort(self): + config = { + "versions": ["v1.9.9"], "aliases": {"v1.9.9": "1.9"}, "retiredLines": [], + } + updated = versions.reconcile(config, [release("v1.10.0"), release("v1.9.10")]) + self.assertEqual(updated["versions"], ["v1.10.0", "v1.9.10"]) + + def test_retirement_cannot_be_undone_and_new_high_line_can_advance(self): + config = manifest() + config["versions"] = ["v0.26.19"] + config["aliases"] = {"v0.26.19": "0.26"} + config["retiredLines"] = ["0.27"] + updated = versions.reconcile(config, [ + release("v0.27.99"), release("v0.28.0"), release("v0.25.99"), + ]) + self.assertEqual(updated["versions"], ["v0.28.0", "v0.26.19"]) + self.assertEqual(updated["retiredLines"], ["0.27"]) + + def test_unpublished_prerelease_and_invalid_metadata_are_ignored(self): + candidates = [ + dict(release("v9.0.0"), draft=True), + dict(release("v8.0.0"), prerelease=True), + dict(release("v7.0.0"), published_at=None), + release("v6.0.0-rc.1"), release("v05.0.0"), {}, + ] + self.assertEqual(versions.reconcile(manifest(), candidates), manifest()) + + +class DocsPromotionTests(unittest.TestCase): + @patch.object(promotion, "api") + def test_idempotent_rebuild_does_not_write(self, api): + api.side_effect = [content(manifest()), []] + self.assertFalse(promotion.promote("installation-token")) + self.assertTrue(all(call.args[0] == "GET" for call in api.call_args_list)) + + @patch.object(promotion.time, "sleep") + @patch.object(promotion, "api") + def test_conflict_reloads_current_manifest_and_respects_concurrent_retirement(self, api, sleep): + pruned = copy.deepcopy(manifest()) + pruned["versions"] = ["v0.27.0"] + pruned["aliases"] = {"v0.27.0": "0.27"} + pruned["retiredLines"] = ["0.26"] + api.side_effect = [ + content(manifest()), [release("v0.26.20")], + HTTPError("", 409, "conflict", {}, None), + content(pruned, "after"), [release("v0.26.20")], + ] + self.assertFalse(promotion.promote("installation-token")) + self.assertEqual(api.call_count, 5) + sleep.assert_called_once_with(1) + + @patch.object(promotion.time, "sleep") + @patch.object(promotion, "api") + def test_conflict_merges_burst_updates_against_latest_sha(self, api, sleep): + concurrent = versions.reconcile(manifest(), [release("v0.28.0")]) + api.side_effect = [ + content(manifest()), [release("v0.29.0")], + HTTPError("", 409, "conflict", {}, None), + content(concurrent, "latest"), [release("v0.29.0")], {}, + ] + self.assertTrue(promotion.promote("token")) + body = api.call_args.args[3] + self.assertEqual(body["sha"], "latest") + self.assertEqual(json.loads(base64.b64decode(body["content"]))["versions"], + ["v0.29.0", "v0.28.0", "v0.27.0", "v0.26.19"]) + + @patch.object(promotion, "api") + def test_event_metadata_verified_and_manifest_only_write(self, api): + # A just-published release need not yet appear in the releases list. + api.side_effect = [release("v0.28.0"), content(manifest()), [], {}] + self.assertTrue(promotion.promote("installation-token", "v0.28.0")) + method, path, token, body = api.call_args.args + self.assertEqual((method, path, token), ( + "PUT", "contents/api-docs/versions.json", "installation-token", + )) + self.assertEqual(body["branch"], "main") + self.assertEqual(body["sha"], "before") + updated = json.loads(base64.b64decode(body["content"])) + self.assertEqual(updated["versions"][0], "v0.28.0") + + @patch.object(promotion, "api") + def test_missing_credentials_and_unpublished_event_fail_without_writes(self, api): + with self.assertRaisesRegex(ValueError, "installation token"): + promotion.promote("") + api.assert_not_called() + api.return_value = dict(release("v0.28.0"), prerelease=True) + with self.assertRaisesRegex(ValueError, "published stable"): + promotion.promote("token", "v0.28.0") + self.assertEqual(api.call_count, 1) + + @patch.object(promotion.time, "sleep") + @patch.object(promotion, "api") + def test_bounded_conflict_retry_and_permissions_fail_closed(self, api, sleep): + for code, count in [(409, 6), (422, 6), (403, 1)]: + with self.subTest(code=code): + api.reset_mock() + api.side_effect = [ + item + for _ in range(count) + for item in (content(manifest()), [release("v0.28.0")], + HTTPError("", code, "failure", {}, None)) + ] + with self.assertRaises(HTTPError): + promotion.promote("token") + self.assertEqual(api.call_count, count * 3) + + @patch.object(promotion, "api") + def test_release_pagination_is_exhausted(self, api): + api.side_effect = [content(manifest()), [release("v0.25.0")] * 100, + [release("v0.28.0")], {}] + self.assertTrue(promotion.promote("token")) + self.assertEqual(api.call_args_list[2].args[1], "releases?per_page=100&page=2") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_version_selector.js b/tests/test_version_selector.js index d8904af..5795737 100644 --- a/tests/test_version_selector.js +++ b/tests/test_version_selector.js @@ -9,10 +9,11 @@ const source = fs.readFileSync( ); for (const base of ["https://contentauth.github.io/c2pa-cpp/", "file:///tmp/site/"]) { - for (const prefix of ["", "versions/v0.26.14", "versions/v0.26.13"]) { + for (const prefix of ["", "versions/0.27", "versions/0.26"]) { test("selector links and navigation: " + base + prefix, function () { - const versions = ["v0.26.14", "v0.26.13"]; - const tag = prefix ? prefix.split("/").pop() : versions[0]; + const versions = ["v0.27.0", "v0.26.19"]; + const lines = ["0.27", "0.26"]; + const tag = prefix ? versions[lines.indexOf(prefix.split("/").pop())] : versions[0]; function element() { return { children: [], @@ -41,13 +42,13 @@ for (const base of ["https://contentauth.github.io/c2pa-cpp/", "file:///tmp/site const select = container.children[0].children[0]; assert.equal(select.children.length, versions.length); for (const [index, option] of select.children.entries()) { - assert.equal(option.value, base + "versions/" + versions[index] + "/index.html"); + assert.equal(option.value, base + "versions/" + lines[index] + "/index.html"); assert.equal(option.selected, versions[index] === tag); - assert.equal(option.textContent, versions[index]); + assert.equal(option.textContent, lines[index]); } select.value = select.children[1].value; select.change(); - assert.equal(navigated, base + "versions/v0.26.13/index.html"); + assert.equal(navigated, base + "versions/0.26/index.html"); }); } } diff --git a/tests/test_versioned_docs.py b/tests/test_versioned_docs.py index 00564b6..019d4b6 100644 --- a/tests/test_versioned_docs.py +++ b/tests/test_versioned_docs.py @@ -9,14 +9,24 @@ import zipfile from scripts import generate_versioned_api_docs as docs +from scripts.docs_versions import line + + +def manifest(versions=None, aliases=None, retired=None): + versions = versions if versions is not None else ["v0.27.0", "v0.26.19"] + return { + "versions": versions, + "aliases": aliases if aliases is not None else {tag: line(tag) for tag in versions}, + "retiredLines": retired if retired is not None else [], + } class VersionedDocsTests(unittest.TestCase): - def test_version_list_preserves_default_and_order(self): + def test_version_list_uses_highest_line_as_default(self): with tempfile.TemporaryDirectory() as directory: config = Path(directory) / "versions.json" - config.write_text('{"versions": ["v0.26.14", "v0.26.13"]}') - self.assertEqual(docs.load_versions(config), ["v0.26.14", "v0.26.13"]) + config.write_text(json.dumps(manifest())) + self.assertEqual(docs.load_versions(config), ["v0.27.0", "v0.26.19"]) def test_invalid_version_lists_are_rejected(self): invalid = [ @@ -37,7 +47,10 @@ def test_invalid_version_lists_are_rejected(self): @patch.object(docs.subprocess, "run") def test_published_release_is_verified(self, run): run.return_value = Mock( - stdout=json.dumps({"tag_name": "v0.26.14", "draft": False}) + stdout=json.dumps({ + "tag_name": "v0.26.14", "draft": False, + "prerelease": False, "published_at": "2026-01-01T00:00:00Z", + }) ) docs.verify_release("v0.26.14") run.assert_called_once_with( @@ -51,6 +64,10 @@ def test_unpublished_or_mismatched_release_fails(self, run): {"tag_name": "v0.26.14", "draft": True}, {"tag_name": "v0.26.13", "draft": False}, {"tag_name": "v0.26.14"}, [], + {"tag_name": "v0.26.14", "draft": False, "prerelease": True, + "published_at": "2026-01-01T00:00:00Z"}, + {"tag_name": "v0.26.14", "draft": False, "prerelease": False, + "published_at": None}, ]: with self.subTest(release=release): run.return_value = Mock(stdout=json.dumps(release)) @@ -152,13 +169,17 @@ def test_site_build_and_failure_preserve_existing_output(self, build_html, expor def build(stage, output, tag, versions, prefix): (output / "html").mkdir(parents=True) (output / "html/index.html").write_text(f"{tag}:{prefix}") + (output / "html/nested").mkdir() + (output / "html/nested/class.html").write_text("API") build_html.side_effect = build with tempfile.TemporaryDirectory() as directory: root = Path(directory) (root / "api-docs").mkdir() (root / "api-docs/versions.json").write_text( - '{"versions": ["v0.26.14", "v0.26.13"]}' + json.dumps(manifest(aliases={ + "v0.27.0": "0.27", "v0.26.19": "0.26", "v0.26.13": "0.26", + })) ) (root / "Doxyfile").touch() (root / "docs").mkdir() @@ -166,12 +187,16 @@ def build(stage, output, tag, versions, prefix): (root / "docs" / asset).touch() with patch.object(docs, "ROOT", root): site = docs.build_site() - self.assertEqual((site / "index.html").read_text(), "v0.26.14:") - for tag in ("v0.26.14", "v0.26.13"): + self.assertEqual((site / "index.html").read_text(), "v0.27.0:") + for tag in ("v0.27.0", "v0.26.19"): self.assertEqual( - (site / "versions" / tag / "index.html").read_text(), - f"{tag}:versions/{tag}", + (site / "versions" / line(tag) / "index.html").read_text(), + f"{tag}:versions/{line(tag)}", ) + redirect = (site / "versions/v0.26.13/nested/class.html").read_text() + self.assertIn("../../0.26/nested/class.html", redirect) + self.assertIn("+ location.search + location.hash", redirect) + self.assertNotIn("versions/0.25", str(list(site.rglob("*")))) self.assertTrue((site / ".nojekyll").is_file()) self.assertEqual(list((root / "api-docs/_build").iterdir()), [site]) self.assertEqual(verify.call_count, 2) @@ -180,7 +205,7 @@ def build(stage, output, tag, versions, prefix): build_html.side_effect = RuntimeError("Doxygen build failed") with self.assertRaisesRegex(RuntimeError, "Doxygen build failed"): docs.build_site() - self.assertEqual((site / "index.html").read_text(), "v0.26.14:") + self.assertEqual((site / "index.html").read_text(), "v0.27.0:") self.assertEqual(list((root / "api-docs/_build").iterdir()), [site]) From 51e6066a1a4871e2da9c42ddc44cc55884063173 Mon Sep 17 00:00:00 2001 From: Rand McKinney Date: Mon, 30 Nov 2026 10:32:02 -0800 Subject: [PATCH 3/3] docs: publish on releases with manual recovery only Remove hourly promotion and main-push publishing triggers. Keep completion-driven release deployment, manual promotion/rebuild, App isolation and stale-artifact safeguards. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/promote-docs.yml | 2 -- .github/workflows/publish-docs.yml | 3 --- README.md | 28 ++++++++++++++++++++-------- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/.github/workflows/promote-docs.yml b/.github/workflows/promote-docs.yml index 1b6e107..3cf9d0f 100644 --- a/.github/workflows/promote-docs.yml +++ b/.github/workflows/promote-docs.yml @@ -3,8 +3,6 @@ name: Promote API documentation versions on: release: types: [published] - schedule: - - cron: '17 * * * *' workflow_dispatch: permissions: diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index b0300b3..76cf899 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -1,9 +1,6 @@ name: Build and publish docs on: - push: - branches: ['main'] - workflow_dispatch: workflow_run: diff --git a/README.md b/README.md index b6e8644..20e13c3 100644 --- a/README.md +++ b/README.md @@ -231,7 +231,7 @@ tree and does not include a version selector or require GitHub authentication. #### Publishing `promote-docs.yml` reconciles published stable GitHub releases on release -publication, manual dispatch, and hourly recovery. It verifies release metadata, +publication or manual recovery dispatch. It verifies release metadata, updates retained lines only to higher patches, and adds newly released lines above the highest known active or retired line. It never backfills unselected historical lines or restores retired lines. Older maintenance releases cannot @@ -242,18 +242,30 @@ The dependency-free Python updater writes **only `api-docs/versions.json` on file SHA; conflicts trigger a fresh manifest read and full release reconciliation, up to six attempts, without force pushes. Repeated runs make no empty commits. Promotion runs have no Actions concurrency group: pending concurrency runs are -not a durable release queue. Full paginated reconciliation and hourly recovery -also catch missed events or exhausted retries. Failed runs remain visible and -can be rerun manually. +not a durable release queue. Every run reconciles all release pages, so a later +release or manual recovery can catch missed events or exhausted retries. Failed +runs remain visible; there is no scheduled recovery. After a successful promotion workflow, `publish-docs.yml` explicitly rebuilds current `main` through `workflow_run`, even if promotion made no change; it does -not rely on a bot push. Main pushes and manual publishing dispatches remain -supported. A single workflow-wide Pages lock serializes build/deploy pairs. +not rely on a bot push. Release-triggered promotion and its completion-driven +deployment are the only automatic publishing path: main pushes do not publish, +and neither publishing workflow has a schedule. CI validation on main pushes +and pull requests is unchanged. + +For **recovery**, manually run **Promote API documentation versions** to reconcile +all stable releases and then rebuild/deploy through its successful completion. +For a **rebuild only**, manually run **Build and publish docs** to build/deploy +the current manifest without changing it. After a human manifest/pruning PR or +documentation-tooling change lands, use one of these manual options to publish +it without waiting for another release. + +A single workflow-wide Pages lock serializes build/deploy pairs. Every admitted run checks out current `main`, rather than the triggering SHA, so replacing a pending run does not discard release updates. Deployment skips -an artifact if `main` advanced during its build; the pending current-main run -rebuilds it. Builds have read-only contents access and no App credentials; +an artifact if `main` advanced during its build. A pending release/manual run +can rebuild current main; otherwise manually rebuild after main settles. +Builds have read-only contents access and no App credentials; only the deployment job has Pages and OIDC write permissions. No release workflow is triggered by manifest commits.