From 1592fab495007e1ba68deb61b61b3c291dd1c436 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 29 Nov 2026 15:20:17 -0500 Subject: [PATCH 01/14] Base path: site_paths.py mounts every site path under /macro www.policyengine.org/macro will proxy to this project. Through that proxy a root path such as /models resolves on policyengine.org, where it is the website's namespace and a 404, so every link, image, stylesheet, object, font and fetch has to name /macro/models instead. - site_paths.py: BASE_PATH, mount() (href, src, , CSS url(), fetch) and a check/--write CLI over served files. - site_nav.render and every generator mount their output, so each --check gate compares mounted pages; site_contract.py and the tests compare mounted strings. - vercel.json: rewrites serve the tree under /macro; each redirect and each path-scoped header rule gets a /macro twin, since Vercel matches both on the requested path before the rewrite. - tests/conftest.py models the rewrite; tests/test_site_paths.py pins mount() and the vercel.json twins. - CI: site-provenance.yml and data/refresh.py run python3 site_paths.py. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/site-provenance.yml | 2 + assets/make_current_outlooks.py | 3 +- assets/make_hero.py | 3 +- assets/make_joins_hub.py | 3 +- data/build_page.py | 5 +- data/refresh.py | 1 + economy/build.py | 5 +- economy/topics.py | 3 +- forecasts/make_open_fans.py | 3 +- forecasts/score.py | 5 +- integration/tests/test_site_contract.py | 5 +- models/compare/build.py | 3 +- notes/generate_release_notes.py | 9 +- olg/figures/make_showcase.py | 4 +- site_contract.py | 17 ++- site_nav.py | 20 ++- site_paths.py | 173 ++++++++++++++++++++++++ tests/conftest.py | 31 ++++- tests/test_compare.py | 8 +- tests/test_refresh_pipeline.py | 5 +- tests/test_site_paths.py | 149 ++++++++++++++++++++ tools/model_hero.py | 11 +- tools/prerender_math.py | 13 +- validation/figures/make_charts.py | 3 +- vercel.json | 149 +++++++++++++++++++- 25 files changed, 588 insertions(+), 45 deletions(-) create mode 100644 site_paths.py create mode 100644 tests/test_site_paths.py diff --git a/.github/workflows/site-provenance.yml b/.github/workflows/site-provenance.yml index f567530c3..3b50c4abc 100644 --- a/.github/workflows/site-provenance.yml +++ b/.github/workflows/site-provenance.yml @@ -48,5 +48,7 @@ jobs: python3 tools/prerender_math.py --check - name: Global navigation is consistent run: python3 site_nav.py + - name: Every served path is under the base path + run: python3 site_paths.py - name: Public model inventory and evidence are complete run: python3 site_contract.py diff --git a/assets/make_current_outlooks.py b/assets/make_current_outlooks.py index 2d169237a..0b8cbd2c3 100644 --- a/assets/make_current_outlooks.py +++ b/assets/make_current_outlooks.py @@ -12,6 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) import chartkit # noqa: E402 (stdlib-only, repo root) +import site_paths # noqa: E402 (every site path goes under the base path) def points(values, xs, ymap): @@ -168,7 +169,7 @@ def render(page: Path, name: str, content: str) -> str: ) if count != 1: raise RuntimeError(f"expected one {name} block in {page}, found {count}") - return updated + return site_paths.mount(updated) if __name__ == "__main__": diff --git a/assets/make_hero.py b/assets/make_hero.py index 3ad69a9cf..cd53fc42c 100644 --- a/assets/make_hero.py +++ b/assets/make_hero.py @@ -25,6 +25,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) import chartkit # noqa: E402 (stdlib-only, repo root) +import site_paths # noqa: E402 (every site path goes under the base path) PAGE = ROOT / "index.html" SRC = ROOT / "papers" / "boe-svar" / "figures" / "current_forecast.json" @@ -228,7 +229,7 @@ def main(): args = ap.parse_args() html = PAGE.read_text() - new = render_page(html) + new = site_paths.mount(render_page(html)) if args.check: if new != html: print(f"{PAGE} is out of date; run: python3 assets/make_hero.py") diff --git a/assets/make_joins_hub.py b/assets/make_joins_hub.py index b2f66c70c..e908515a9 100644 --- a/assets/make_joins_hub.py +++ b/assets/make_joins_hub.py @@ -17,6 +17,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from site_nav import icon, MODEL_ICONS # noqa: E402 +import site_paths # noqa: E402 (every site path goes under the base path) PAGES = {"index.html": "/", "models/index.html": "/models"} OPEN, CLOSE = "", "" @@ -136,7 +137,7 @@ def main() -> int: path = ROOT / page src = path.read_text() a, b = src.index(OPEN), src.index(CLOSE) + len(CLOSE) - new = src[:a] + render(page) + src[b:] + new = site_paths.mount(src[:a] + render(page) + src[b:]) if new != src: stale.append(page) if not check: diff --git a/data/build_page.py b/data/build_page.py index 20f911ea5..7a2f4156a 100644 --- a/data/build_page.py +++ b/data/build_page.py @@ -22,10 +22,13 @@ import argparse import html import json +import sys from datetime import datetime, timedelta from pathlib import Path ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import site_paths # noqa: E402 (every site path goes under the base path) STORE = ROOT / "data" FORECASTS = ROOT / "economy" / "index.html" # the page that hosts the store @@ -712,7 +715,7 @@ def main() -> int: # Compared and written as bytes: the calendar uses the CRLF line endings # RFC 5545 requires, and text mode would silently translate them. rendered = ( - (FORECASTS, splice(page, render_fragment()).encode("utf-8")), + (FORECASTS, site_paths.mount(splice(page, render_fragment())).encode("utf-8")), (CALENDAR, render_calendar().encode("utf-8")), ) if args.check: diff --git a/data/refresh.py b/data/refresh.py index bde95bfcf..3effabe5f 100644 --- a/data/refresh.py +++ b/data/refresh.py @@ -93,6 +93,7 @@ def py(*args: str) -> tuple[str, ...]: py("assets/make_hero.py", "--check"), py("assets/make_current_outlooks.py", "--check"), py("site_nav.py"), + py("site_paths.py"), py("site_contract.py"), py("-m", "pytest", "tests", "-q"), ) diff --git a/economy/build.py b/economy/build.py index 9e4eb51d7..90ace3f76 100644 --- a/economy/build.py +++ b/economy/build.py @@ -13,6 +13,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) import chartkit # noqa: E402 (stdlib-only, repo root) +import site_paths # noqa: E402 (every site path goes under the base path) PAGE = ROOT / "economy" / "index.html" US_PAGE = ROOT / "economy" / "us" / "index.html" @@ -422,8 +423,8 @@ def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--check", action="store_true") args = parser.parse_args() - rendered_uk = render_uk() - rendered_us = render_us() + rendered_uk = site_paths.mount(render_uk()) + rendered_us = site_paths.mount(render_us()) if args.check: stale = [] for path, rendered in ( diff --git a/economy/topics.py b/economy/topics.py index c19436c90..973e8d3e5 100644 --- a/economy/topics.py +++ b/economy/topics.py @@ -126,6 +126,7 @@ def topic_url(topic: dict) -> str: sys.path.insert(0, str(ROOT)) import site_nav # noqa: E402 (canonical header/crumbs/footer renderer) import chartkit # noqa: E402 (charts; attach_table folds a data table into a chart footer) +import site_paths # noqa: E402 (every site path goes under the base path) def _module(name: str, path: Path): @@ -3485,7 +3486,7 @@ def main() -> int: parser.add_argument("--check", action="store_true") args = parser.parse_args() - artifacts = rendered() + artifacts = [(path, site_paths.mount(content)) for path, content in rendered()] if args.check: stale = [ str(path.relative_to(ROOT)) diff --git a/forecasts/make_open_fans.py b/forecasts/make_open_fans.py index 3ce34f5e2..469d0fa89 100644 --- a/forecasts/make_open_fans.py +++ b/forecasts/make_open_fans.py @@ -25,6 +25,7 @@ HERE = Path(__file__).resolve().parent sys.path.insert(0, str(ROOT)) import chartkit # noqa: E402 (stdlib-only, repo root) +import site_paths # noqa: E402 (every site path goes under the base path) ROUNDS = HERE / "rounds" PAGE = HERE / "index.html" @@ -210,7 +211,7 @@ def main() -> int: args = ap.parse_args() page_now = PAGE.read_text() - page_fresh = render_page(page_now) + page_fresh = site_paths.mount(render_page(page_now)) if args.check: if page_now != page_fresh: diff --git a/forecasts/score.py b/forecasts/score.py index 91570fa7a..6a1d8f798 100644 --- a/forecasts/score.py +++ b/forecasts/score.py @@ -33,6 +33,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) import chartkit # noqa: E402 (stdlib-only, repo root) +import site_paths # noqa: E402 (every site path goes under the base path) HERE = Path(__file__).resolve().parent ROUNDS = HERE / "rounds" OUTTURNS = HERE / "outturns.json" @@ -1487,9 +1488,9 @@ def main() -> int: fresh = build() rendered = json.dumps(fresh, indent=2) + "\n" page_now = PAGE.read_text() - page_fresh = render_page(page_now, fresh) + page_fresh = site_paths.mount(render_page(page_now, fresh)) home_now = HOME.read_text() - home_fresh = render_home(home_now, fresh) + home_fresh = site_paths.mount(render_home(home_now, fresh)) if args.check: stale = [] diff --git a/integration/tests/test_site_contract.py b/integration/tests/test_site_contract.py index 139329c4d..b76e8b5b2 100644 --- a/integration/tests/test_site_contract.py +++ b/integration/tests/test_site_contract.py @@ -4,9 +4,12 @@ import csv import json import re +import sys ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) +import site_paths # noqa: E402 (pages link under the base path) def _read(path: str) -> str: @@ -184,7 +187,7 @@ def test_paper_landings_publish_the_page_count_of_the_pdf_they_link(): for slug, pages in expected.items(): landing = _read(f"papers/{slug}/index.html") assert re.search(rf"{re.escape(slug)} · [^<]* · {pages} pages", landing) - assert f'href="/papers/{slug}"' in hub + assert f'href="{site_paths.url(f"/papers/{slug}")}"' in hub MODEL_PAGES = { diff --git a/models/compare/build.py b/models/compare/build.py index d23225b3b..d81d6d084 100644 --- a/models/compare/build.py +++ b/models/compare/build.py @@ -30,6 +30,7 @@ sys.path.insert(0, str(ROOT)) import chartkit # noqa: E402 import site_nav # noqa: E402 +import site_paths # noqa: E402 (every site path goes under the base path) PAGE = HERE / "index.html" RESULTS = HERE / "results.json" @@ -634,7 +635,7 @@ def main() -> int: for line in found: print(f"FAIL results.json: {line}", file=sys.stderr) return 1 - out = page(data) + out = site_paths.mount(page(data)) if args.check: if not PAGE.exists() or PAGE.read_text() != out: print("FAIL models/compare/index.html is stale: run python3 models/compare/build.py", file=sys.stderr) diff --git a/notes/generate_release_notes.py b/notes/generate_release_notes.py index eba271e5a..a2d97e50b 100644 --- a/notes/generate_release_notes.py +++ b/notes/generate_release_notes.py @@ -22,6 +22,7 @@ sys.path.insert(0, str(ROOT)) import site_nav # noqa: E402 (canonical header/crumbs/footer renderer) +import site_paths # noqa: E402 (every site path goes under the base path) def marker_replace(path: Path, name: str, body: str) -> None: @@ -35,7 +36,7 @@ def marker_replace(path: Path, name: str, body: str) -> None: ) if count != 1: raise RuntimeError(f"{path}: expected one {name} block, found {count}") - path.write_text(updated) + path.write_text(site_paths.mount(updated)) def snapshots(vintage: str) -> list[dict]: @@ -326,12 +327,12 @@ def latest_digest_row() -> str: ) latest = latest_digest() if not latest: - return ( + return site_paths.mount( f'

{icon}Release digests: ' 'what each stored release changed. All digests

' ) day = datetime.strptime(latest, "%Y-%m-%d").strftime("%-d %b %Y") - return ( + return site_paths.mount( f'

{icon}Latest release digest, {day}: ' f'what each stored release changed. Read the digest · ' 'All digests

' @@ -380,7 +381,7 @@ def check() -> int: failures = [] releases_index = RELEASES_INDEX.read_text() sitemap = SITEMAP.read_text() - if 'href="/notes/releases"' not in NOTES_INDEX.read_text(): + if f'href="{site_paths.url("/notes/releases")}"' not in NOTES_INDEX.read_text(): failures.append("forecasts index: missing collapsed link to /notes/releases") if "/notes/releases" not in sitemap: failures.append("sitemap: missing /notes/releases entry") diff --git a/olg/figures/make_showcase.py b/olg/figures/make_showcase.py index 6c8d91fd4..dd1f2428d 100644 --- a/olg/figures/make_showcase.py +++ b/olg/figures/make_showcase.py @@ -23,6 +23,8 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) +import site_paths # noqa: E402 (every site path goes under the base path) HERE = Path(__file__).resolve().parent PAGE = ROOT / "olg" / "index.html" @@ -93,7 +95,7 @@ def main(): args = ap.parse_args() html = PAGE.read_text() - new = render_page(html) + new = site_paths.mount(render_page(html)) if args.check: if new != html: print(f"{PAGE} is out of date; run: python3 olg/figures/make_showcase.py") diff --git a/site_contract.py b/site_contract.py index 2fa9b3cd5..860cdc562 100644 --- a/site_contract.py +++ b/site_contract.py @@ -3,6 +3,8 @@ from pathlib import Path import re +from site_paths import BASE_PATH, mount + ROOT = Path(__file__).resolve().parent # In the order the site presents them. pe-microsim leads: it is @@ -70,7 +72,7 @@ def check_economy_navigation() -> None: } for path, trends_marker in overview_routes.items(): page = _read(path) - for href in ('href="/economy"', 'href="/economy/us"'): + for href in (mount('href="/economy"'), mount('href="/economy/us"')): if href not in page: failures.append(f"{path}: missing country link {href}") if 'id="trends"' not in page: @@ -79,13 +81,13 @@ def check_economy_navigation() -> None: failures.append(f"{path}: missing generated trends block {trends_marker}") if page.count('class="economy-figure"') != 3: failures.append(f"{path}: expected three generated trend figures") - for retired in ('href="/economy/trends"', 'href="/economy/us/trends"'): + for retired in (mount('href="/economy/trends"'), mount('href="/economy/us/trends"')): if retired in page: failures.append(f"{path}: links to retired Trends page {retired}") for anchor in ('id="indicators"', 'id="markets"', 'id="releases"'): if anchor not in page: failures.append(f"{path}: missing merged-section anchor {anchor}") - if 'src="/economy/economy-nav.js"' not in page: + if mount('src="/economy/economy-nav.js"') not in page: failures.append(f"{path}: missing scroll-aware topic navigation") if path == "economy/index.html" and "ons.gov.uk/" in page: if re.search(r'href="https://www\.ons\.gov\.uk/[^"]+/data"', page): @@ -95,8 +97,8 @@ def check_economy_navigation() -> None: for path in MODEL_INVENTORY_PAGES: header = _read(path).split("", 1)[0] - home_position = header.find('href="/"') - forecasts_position = header.find('href="/forecasts"') + home_position = header.find(mount('href="/"')) + forecasts_position = header.find(mount('href="/forecasts"')) if home_position == -1 or forecasts_position == -1: failures.append(f"{path}: missing Home or Forecasts navigation") elif home_position > forecasts_position: @@ -110,7 +112,7 @@ def check_economy_navigation() -> None: # a second global tab over the same section. ('href="/economy"', "Economy"), ): - if retired in header: + if mount(retired) in header: failures.append(f"{path}: {name} remains a global navigation tab") if ">Forecasts" not in header: failures.append(f"{path}: the forecasts tab is not labelled Forecasts") @@ -249,6 +251,9 @@ def resolve(target: str) -> Path | None: # A query string selects state on the same page (/models?q=cost), # not a different file. target = target.split("?", 1)[0] + # Pages link under the base path (site_paths.py); files sit at the root. + if BASE_PATH and (target == BASE_PATH or target.startswith(BASE_PATH + "/")): + target = target[len(BASE_PATH):] candidate = ROOT / target.strip("/") if candidate.suffix == ".html": return candidate if candidate in ids else None diff --git a/site_nav.py b/site_nav.py index b0bda6041..8ed2e238b 100644 --- a/site_nav.py +++ b/site_nav.py @@ -8,6 +8,8 @@ import sys from pathlib import Path +from site_paths import BASE_PATH, mount, url + ROOT = Path(__file__).resolve().parent HEADER = re.compile( r'\s*' @@ -16,14 +18,14 @@ re.DOTALL, ) FOOTER_DIR = re.compile(r'