diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 8096c64..fe12910 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -9,13 +9,21 @@ # (`pwsh-ci-image.yml`). It runs on Linux, so what only a Windows machine can # answer - the registry, the Store alias, a real Mark of the Web - is covered by # the environment hooks `tools/preflight.ps1` documents, not by this job. +# `python314` is the other end of the Python span tools/prerequisites.txt admits +# (Gitea #245): `verify` runs the suite on 3.13, this job on 3.14 - what is +# admitted is exactly what is checked here. +# +# Every package comes from a lock under tools/, installed with --require-hashes: +# the stack's own (through the preflight), the MCP server's, and the test tools' +# in requirements-dev.lock. Nothing is installed by name, so no run takes whatever +# was published that morning (Gitea #243, #245). # # Runner: `linux-docker` is one of this Gitea instance's three routing labels # (alongside `container-builder` and `k3s-deploy`). The job image is named # explicitly rather than inherited from the runner's label mapping, which is # not documented anywhere: `debian:trixie-slim` is the base the instance's -# container-build workflows already use, and Trixie's python3 is 3.13, past -# the 3.11 floor `doctor` enforces. +# container-build workflows already use, and Trixie's python3 is 3.13, the +# lower end of the span tools/prerequisites.txt admits. # # Pinning that image makes `nodejs` this workflow's own responsibility. # `actions/checkout` is a JavaScript action, and act_runner runs it with `node` @@ -111,15 +119,14 @@ jobs: cp .wikitool-tools.json /tmp/tools-first.json tools/preflight.sh > /tmp/preflight-second.txt cmp .wikitool-tools.json /tmp/tools-first.json - # pytest-cov is CI-only: tools/requirements.txt describes what an - # *instance* needs at runtime and ships with `dist export`, and an - # instance does not measure this suite. Installed beside pytest for - # the same reason pytest itself is. - tools/.venv/bin/python -m pip install --quiet pytest pytest-cov # The MCP server's dependency is optional for an instance but not for # CI: its tests skip without it, and a skipped golden test is exactly # how the server's output and the CLI's would drift apart unnoticed. - tools/.venv/bin/python -m pip install --quiet -r tools/requirements-mcp.txt + tools/.venv/bin/python -m pip install --quiet --require-hashes -r tools/requirements-mcp.lock + # The test tools - pytest, pytest-cov, radicale - are dev-only: + # tools/requirements.txt describes what an *instance* needs at runtime + # and ships with `dist export`, and an instance does not run this suite. + tools/.venv/bin/python -m pip install --quiet --require-hashes -r tools/requirements-dev.lock - name: Tests # Not run with WIKI_TRACE=0: two telemetry tests assert that a trace is @@ -180,10 +187,10 @@ jobs: - name: Start Radicale # Its own step because the script hands the server's address to the suite through - # $GITHUB_ENV, which only reaches the steps after the one that wrote it. + # $GITHUB_ENV, which only reaches the steps after the one that wrote it. Radicale + # itself came in with requirements-dev.lock above. run: | set -eu - tools/.venv/bin/python -m pip install --quiet radicale .gitea/scripts/start-radicale.sh tools/.venv/bin/python /tmp/radicale - name: Live tracker suite (CalDAV) @@ -420,7 +427,7 @@ jobs: rm .wikitool-tools.json tools/preflight.sh cmp .wikitool-tools.json /tmp/tools-pwsh.json - tools/.venv/bin/python -m pip install --quiet pytest + tools/.venv/bin/python -m pip install --quiet --require-hashes -r tools/requirements-dev.lock - name: The launcher, started from PowerShell # `tools/wikitool` from pwsh resolves to wikitool.ps1, not the sh launcher - the one @@ -436,3 +443,44 @@ jobs: set -eu cd tools .venv/bin/python -m pytest -q chemenu/tests/test_preflight_pwsh.py chemenu/tests/test_preflight.py chemenu/tests/test_doctor.py chemenu/tests/test_bugreport_launcher.py + + python314: + # The suite on the upper end of the Python span (Gitea #245). The official Python image + # on the same Debian base as `verify`, so the one difference between the two jobs is the + # interpreter: its python3 is 3.14, which the preflight finds and builds tools/.venv on. + # Only the suite - the distribution replay, the version gate and the live steps answer + # questions that do not depend on the Python minor, and the one runner works through + # the jobs of a push one after another. + runs-on: linux-docker + container: + image: python:3.14-slim-trixie + env: + WIKITOOL_SESSION_ID: ci-py314-${{ github.run_id }} + WIKI_TRACE_DIR: /tmp/wikitool-trace + + steps: + - name: System dependencies + # `nodejs` for act_runner's checkout action, as in `verify`; no python3 package - + # the image's own 3.14 is the point of this job. + run: | + set -eu + apt-get update -qq + apt-get install -y --no-install-recommends git nodejs ripgrep ca-certificates + rm -rf /var/lib/apt/lists/* + + - uses: actions/checkout@v7 + + - name: Tool environment + run: | + set -eu + git config --global --add safe.directory "$GITHUB_WORKSPACE" + tools/preflight.sh + tools/.venv/bin/python -c 'import sys; assert sys.version_info[:2] == (3, 14), sys.version' + tools/.venv/bin/python -m pip install --quiet --require-hashes -r tools/requirements-mcp.lock + tools/.venv/bin/python -m pip install --quiet --require-hashes -r tools/requirements-dev.lock + + - name: Tests + run: | + set -eu + cd tools + .venv/bin/python -m pytest -q diff --git a/.gitea/workflows/converters.yml b/.gitea/workflows/converters.yml index 15f21eb..88e3179 100644 --- a/.gitea/workflows/converters.yml +++ b/.gitea/workflows/converters.yml @@ -40,6 +40,7 @@ on: - 'tools/chemenu/tests/test_raw_derive*.py' - 'tools/chemenu/tests/binary_formats.py' - 'tools/requirements.txt' + - 'tools/requirements.lock' - '.gitea/workflows/converters.yml' workflow_dispatch: @@ -76,7 +77,7 @@ jobs: set -eu git config --global --add safe.directory "$GITHUB_WORKSPACE" tools/preflight.sh - tools/.venv/bin/python -m pip install --quiet pytest + tools/.venv/bin/python -m pip install --quiet --require-hashes -r tools/requirements-dev.lock - name: Real documents # `-c pytest.ini` applies the suite's own configuration to a harness that lives outside diff --git a/.gitea/workflows/nightly.yml b/.gitea/workflows/nightly.yml index 0fe0a3b..f750e05 100644 --- a/.gitea/workflows/nightly.yml +++ b/.gitea/workflows/nightly.yml @@ -25,6 +25,15 @@ # container, so it is installed before the checkout or the job dies with exit # 127. Do not re-derive this; see the header of ci.yml. # +# Two more kinds of drift happen with no commit at all, in the packages the locks under +# tools/ pin (Gitea #245), and the last three steps watch them without touching the tree: +# a vulnerability published for a pinned version (`pip-audit` against every lock - red +# means a security lift is due), and the next regular lift breaking the suite (a fresh +# resolution with the same 7-day cooldown, in a venv of its own, and the suite against +# it - red means the lift will need more than a new lock). They run even when an +# earlier step failed, so a red lint never hides them. The procedure for either answer +# is instructions/dev/dependency-locks.md. +# # Failure is meant to be visible without opening the Actions page. That is # Gitea's own run notification, not something this workflow builds: a job that # files its own issue needs an Actions token with issue-write and a dedup rule, @@ -100,3 +109,46 @@ jobs: set -eu tools/wikitool sources coverage tools/wikitool migrate status + + - name: Audit tools, in a venv of their own + # pip-audit and uv come from the test tools' lock - never into tools/.venv, which + # stays exactly what the preflight installed. + if: ${{ !cancelled() }} + run: | + set -eu + python3 -m venv /tmp/audit + /tmp/audit/bin/python -m pip install --quiet --require-hashes -r tools/requirements-dev.lock + + - name: No known vulnerability in any lock + # --disable-pip audits the pinned versions as written, installing none of them. + if: ${{ !cancelled() }} + run: | + set -eu + /tmp/audit/bin/pip-audit --disable-pip --require-hashes --progress-spinner off \ + -r tools/requirements.lock -r tools/requirements-mcp.lock \ + -r tools/requirements-browser.lock -r tools/requirements-dev.lock + + - name: The suite passes against a fresh resolution + # What the next regular lift would produce today: every source file resolved again + # with the cooldown, written outside the tree, installed into a venv of its own. + if: ${{ !cancelled() }} + run: | + set -eu + PATH="/tmp/audit/bin:$PATH" python3 tools/lock_requirements.py --out /tmp/fresh-locks + python3 -m venv /tmp/fresh + for lock in requirements requirements-mcp requirements-dev; do + /tmp/fresh/bin/python -m pip install --quiet --require-hashes -r "/tmp/fresh-locks/${lock}.lock" + done + cd tools + /tmp/fresh/bin/python -m pytest -q -p no:cacheprovider + + - name: The tree is unchanged + if: ${{ !cancelled() }} + run: | + set -eu + changed=$(git status --porcelain) + if [ -n "$changed" ]; then + echo "The nightly changed the tree:" + printf '%s\n' "$changed" + exit 1 + fi diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 0984183..c3a0141 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -94,7 +94,7 @@ jobs: set -eu git config --global --add safe.directory "$GITHUB_WORKSPACE" tools/preflight.sh - tools/.venv/bin/python -m pip install --quiet pytest + tools/.venv/bin/python -m pip install --quiet --require-hashes -r tools/requirements-dev.lock - name: Real documents if: steps.version.outputs.skip != 'true' diff --git a/.gitea/workflows/tracker-live.yml b/.gitea/workflows/tracker-live.yml index 1c4a1f5..9fc80a0 100644 --- a/.gitea/workflows/tracker-live.yml +++ b/.gitea/workflows/tracker-live.yml @@ -1,7 +1,7 @@ # The live tracker suite, nightly (Gitea #156): the documented `task` and `review` workflow # against a real Super Productivity and a real CalDAV server, not against fakes. # -# `ci.yml` already runs the CalDAV half on every push (Radicale is a pip install). This +# `ci.yml` already runs the CalDAV half on every push (Radicale comes from tools/requirements-dev.lock). This # workflow adds the half that needs the desktop app, inside the prebuilt # `chemenu-sp-live` image (`sp-live-image.yml`), and runs both, so one green night covers both # providers. @@ -52,7 +52,7 @@ jobs: set -eu git config --global --add safe.directory "$GITHUB_WORKSPACE" tools/preflight.sh - tools/.venv/bin/python -m pip install --quiet pytest radicale + tools/.venv/bin/python -m pip install --quiet --require-hashes -r tools/requirements-dev.lock - name: Start Radicale run: .gitea/scripts/start-radicale.sh tools/.venv/bin/python /tmp/radicale diff --git a/CHANGES.md b/CHANGES.md index 4be981c..d6aa563 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -14,11 +14,18 @@ place only: `instructions/dev/version-parts.md` § The candidate model. --- -## 10.2.0-beta.2 - 2026-11-18 - Abhängigkeiten: Testsuite läuft unter pytest 9.2, Befehlshilfe und Referenz folgen typer 0.29 - Untergrenze typer>=0.29.1 (#243) +## 11.0.0-beta.1 - 2026-11-18 - Abhängigkeiten festgeschrieben: Lock-Dateien mit Hashes und 7 Tagen Abkühlzeit, pip-audit im Nightly; Python 3.13-3.14 als zugelassene Spanne (#245) **Author:** Torben Nehmer +**Breaking Change:** Python 3.11 und 3.12 sind nicht mehr zugelassen (ebenso 3.15): der Preflight weist sie mit exit 42 ab. Eine Instanz darauf installiert Python 3.13 oder 3.14 und führt den Preflight erneut aus; er legt tools/.venv darauf neu an. + +**Migration:** none required - kb/ bleibt unberührt + +**High impact** +- Abhängigkeiten festgeschrieben: Lock-Dateien mit Hashes und 7 Tagen Abkühlzeit, pip-audit im Nightly; Python 3.13-3.14 als zugelassene Spanne (#245) + **Medium impact** - Reine Lesevorgänge schreiben keinen Log-Eintrag mehr, und ein offener Log-Eintrag allein lässt den Katalog beim Abgleich unangetastet - Ingest: Präzisierungen des Operators als Begleitdatei im Bundle der Quelle - neuer Befehl raw clarify (#241) @@ -28,6 +35,10 @@ place only: `instructions/dev/version-parts.md` § The candidate model. - Publish-, Sync-Hilfe und Log-Vorlage nennen den reinen Log-Zusatz beim Abgleich +### Abhängigkeiten festgeschrieben + +Neben jeder `tools/requirements*.txt` (nur Untergrenzen) liegt eine `.lock` mit exakter Version und SHA-256 je Paket, transitive eingeschlossen, erzeugt mit 7 Tagen Abkühlzeit; Preflight und CI installieren nur daraus, mit `--require-hashes`. Ändert ein neuer Stand das Lock, bringt der nächste Preflight `tools/.venv` genau auf dessen Versionen, auch abwärts - bisher fror eine Instanz auf ihrem Installationstag ein. Python ist eine Spanne, 3.13 bis 3.14, in `tools/prerequisites.txt`; der Preflight nimmt auch `python3.14`/`py -3.14` und legt ein venv außerhalb der Spanne neu an. CI prüft beide Enden, der Nightly `pip-audit` und eine frische Auflösung. Eine Instanz auf 3.11/3.12 installiert Python 3.13 oder 3.14 und führt den Preflight erneut aus; der MCP-Server kommt jetzt aus `tools/requirements-mcp.lock`. + --- ## 10.1.0 - 2026-10-16 - Große PDFs und lange Quellen beim Ingest, vollständiger Export, Konverter-Tests gegen echte Dokumente diff --git a/INSTALL.md b/INSTALL.md index 3108de5..d409182 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -24,11 +24,18 @@ preflight names the install command for your system. The list is generated from `tools/prerequisites.txt`, the same file the preflight reads: -- **Python** ≥ 3.11 +- **Python** 3.13 – 3.14 - **Git** - **ripgrep (rg)** +Python has an upper bound as well as a lower one: the stack is checked on 3.13 and 3.14 and +runs on nothing else. On Windows and macOS the install command the preflight names installs a +3.14. On Linux it is your distribution's own Python, which is in that span on Debian 13, Ubuntu +25.04 and newer and Arch - but not on Debian 12 (3.11) or Ubuntu 24.04 (3.12). There, a Python +3.13 or 3.14 installed some other way works too: tell the agent its path, and it passes it on with +`--set python=`. + Optional: the **1Password CLI (`op`)**, if you want secrets and private values in the settings to come from 1Password ([use-1password-for-settings.md](docs/how-to/use-1password-for-settings.md)). The preflight records it when it finds it and never asks for it. @@ -162,8 +169,9 @@ are done; then it checks again. It may not work around the stop or install anyth - **A tool is missing** - Python, git, ripgrep, on Windows also PowerShell 7. The output names the install command for your system. If it is installed, just somewhere else, tell the agent the path; it passes it on with `--set =`. -- **A version is too old** - Python below 3.11, for example. Install a newer version or name its - path. +- **A version is too old, or too new** - Python below 3.13 or above 3.14, for example. Install + one in the span or name the path of one you have; a `python3.14` or `python3.13` beside a newer + default is found by itself. - **A path you named does not work** - the path must point at the program itself, not at its folder. - **The Python environment (`tools/.venv`) or its libraries could not be set up.** The output diff --git a/VERSION b/VERSION index 03f498c..e8db92a 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -10.2.0-beta.2 +11.0.0-beta.1 diff --git a/docs/dev/development.md b/docs/dev/development.md index 110177e..9a862f1 100644 --- a/docs/dev/development.md +++ b/docs/dev/development.md @@ -196,8 +196,8 @@ refills the Gitea wiki by hand (see below). `.gitea/workflows/converters.yml` runs the converters against the real documents of the private repository (the clone above, run with the checkout's `tools/.venv`). It starts by itself on a push to `main` that touches the converter surface - `tools/chemenu/filters/`, `raw/derive.py`, -`raw/accept.py`, `tests/test_raw_derive*.py`, `tests/binary_formats.py`, `tools/requirements.txt` -and the workflow itself - and by hand (`workflow_dispatch`), which is how to run it after a change +`raw/accept.py`, `tests/test_raw_derive*.py`, `tests/binary_formats.py`, `tools/requirements.txt`, +`tools/requirements.lock` and the workflow itself - and by hand (`workflow_dispatch`), which is how to run it after a change in the private repository alone: a push there starts nothing here. It always tests `main` of the private repository, so a converter change that alters an expected output is two commits, the private one first. Before a release without suffix, `release.yml` runs the same steps as a job its @@ -284,9 +284,9 @@ preceding a release measures a tree that is one commit short of the published on The pair says more than either number does. Between them the measured code grew by a quarter and the suite by a third, and the quota moved by a tenth of a point - which is the observation a threshold was waiting for, rather than the total itself. Reproduce either with -`cd tools && .venv/bin/python -m pytest -q --cov` (needs `pytest-cov`, which is CI-only and -deliberately absent from `tools/requirements.txt` - an instance runs the wiki, it does not -measure this suite). +`cd tools && .venv/bin/python -m pytest -q --cov` (needs `pytest-cov`, which sits in the dev-only +`tools/requirements-dev.lock` and deliberately not in `tools/requirements.txt` - an instance runs +the wiki, it does not measure this suite). The total stays the least interesting number here. What the report is for is *which* modules sit low, and three kinds have to be told apart before any of it turns into work: diff --git a/docs/how-to/set-up-the-mcp-server.md b/docs/how-to/set-up-the-mcp-server.md index 5052dea..ab1d708 100644 --- a/docs/how-to/set-up-the-mcp-server.md +++ b/docs/how-to/set-up-the-mcp-server.md @@ -58,8 +58,9 @@ Set up the MCP read server for this instance ``` It installs the server's optional dependency, which is deliberately not in -`tools/requirements.txt`: an instance that only uses the CLI should not have to install pydantic, -starlette, uvicorn and cryptography. It also checks that tracing cannot write into the served tree. +`tools/requirements.txt`: an instance that only uses the CLI should not have to install +starlette, uvicorn and the rest of a web server. It installs `tools/requirements-mcp.lock`, with +exact versions and hashes that agree with the rest of `tools/.venv`. It also checks that tracing cannot write into the served tree. The server refuses to start if it could: ```text diff --git a/instructions/dev/dependency-locks.md b/instructions/dev/dependency-locks.md new file mode 100644 index 0000000..6fa2456 --- /dev/null +++ b/instructions/dev/dependency-locks.md @@ -0,0 +1,140 @@ +--- +type: types/instruction.md +name: dependency-locks +description: How the Python packages of the stack are pinned and moved - the four lock files under tools/, regenerating them with the 7-day cooldown, lifting one package at once for a security fix without ever lowering it again, checking that no locked package was too young, and what a red nightly audit or fresh-resolution run asks for. +--- +# Pin the stack's packages, and move them on purpose + +Every Python package the stack or its CI installs comes from a lock under `tools/`: exact +versions with SHA-256 hashes, transitive packages included, installed with +`pip install --require-hashes`. Before Gitea #245 the requirement files carried lower bounds +only, CI installed whatever was newest that morning, and an instance kept the packages of the day +it was set up - CI went red after four quiet weeks when pytest 9.2 and typer 0.29.1 came out +(#243), and a compromised release would have reached the next install unchecked. Pins answer both +sides of faster attacks: nothing new flows in unchecked, and a known hole is closed by a +deliberate lift, at once. + + +## Contents + +- [The files](#the-files) +- [When to run](#when-to-run) +- [Steps](#steps) +- [Decision points](#decision-points) +- [Scope](#scope) + + +## The files + +| Source (lower bounds) | Lock | Installed by | Ships | +|---|---|---|---| +| `tools/requirements.txt` | `tools/requirements.lock` | the preflight, every run whose stamp differs | yes | +| `tools/requirements-mcp.txt` | `tools/requirements-mcp.lock` | the user, by hand (command in the source's head); CI | yes | +| `tools/requirements-browser.txt` | `tools/requirements-browser.lock` | the preflight, `--with browser` and after | yes | +| `tools/requirements-dev.txt` | `tools/requirements-dev.lock` | CI and a developer: pytest, pytest-cov, radicale, pip-audit, uv | no (`TOOLS_DEV_ONLY`) | + +`tools/lock_requirements.py` (dev-only) is the one way a lock is written. It resolves the four in +that order, each constrained by every lock above it (`-c`), because all of them land in one venv: +a package in two locks has one version, and a later `pip install -r` never moves a package an +earlier lock placed. `test_dependency_locks.py` holds every property below on each push. + +The locks resolve for the Python minimum in `tools/prerequisites.txt` with `--universal`, so one +file serves Linux, macOS and Windows across the admitted span. A source file is never installed +itself - not by the preflight, not by CI (the same test reads every workflow for it). + +## When to run + +- **A regular lift** - a new package version is wanted, a source file's floor moved, or a lock is + simply due. It is a small stack package of its own: the locks, a patch bump, `publish`. +- **A security lift** - the nightly's `pip-audit` step is red, or an advisory names a locked + version. Same day, one package, no cooldown. +- **The nightly's fresh-resolution step is red** - today's regular lift would break the suite. + Not a lift yet: the defect it shows is fixed first, in a package of its own, and the lift + follows with it. + +## Steps + +1. **Have `uv` on `PATH`.** `requirements-dev.lock` carries it; in a checkout with the test tools + installed, `tools/.venv/bin/uv` is it. + +2. **Regular lift - regenerate every lock:** + + ```bash + PATH="$PWD/tools/.venv/bin:$PATH" python3 tools/lock_requirements.py + ``` + + It sets `--exclude-newer` to now minus 7 days: a file uploaded later is not considered. A + compromised release is usually found and pulled within hours to days; the cooldown lets that + happen before a lock can take one. Exceptions from an earlier security lift are carried over + while still younger than the cutoff and dropped once it passes them (step 3). + +3. **Security lift - one package, at once.** `pip-audit` names the package and the first fixed + version X: + + - Raise the floor in its source file to `>=X`. It stays there for good - it is simply + true that vulnerable versions are no longer taken, and it is what keeps every later lift + from lowering the package again. + - Regenerate with an exception for that package alone, up to X's upload time plus a minute + (PyPI's JSON API shows it as `upload_time_iso_8601` per file): + + ```bash + PATH="$PWD/tools/.venv/bin:$PATH" python3 tools/lock_requirements.py \ + --exception = + ``` + + uv writes the exception into each lock's head beside the cutoff. **The invariant: no later + lift lowers the package below X.** While X is younger than the cooldown, the script carries + the exception into the next regular lift; once the cutoff has passed X, the exception is no + longer needed and drops out, and the floor stays. Without both, a lift would fail loudly - + "No solution ... filtered by `exclude-newer`" - rather than lower the package silently: that + is the floor doing its job, not a reason to remove it. + +4. **Check the result.** + + ```bash + cd tools && .venv/bin/python -m pytest -q chemenu/tests/test_dependency_locks.py + ``` + + It holds: an exact version and at least one SHA-256 per package; every source requirement + pinned at or above its floor; one version per package across the four locks; each lock + constrained by the ones before it; and **no package younger than 7 days** - the lock's + `--exclude-newer` lies at least 7 days before the lock's last commit (before now, while the + file differs from `HEAD`). A security lift's package is the one exception, visible as + `--exclude-newer-package` in the head. Read the diff as well: a package that moved a major + version, or one new in a lock, is worth a line in the changelog entry. + +5. **Install and run the suite against the new locks** - the preflight installs + `requirements.lock` by itself once its hash changed; the other two by hand: + + ```bash + tools/preflight.sh + tools/.venv/bin/python -m pip install --require-hashes -r tools/requirements-mcp.lock + tools/.venv/bin/python -m pip install --require-hashes -r tools/requirements-dev.lock + cd tools && .venv/bin/python -m pytest -q + ``` + +6. **Bump and publish.** A lock under `tools/` reaches every instance - its next preflight moves + the venv to it - so it is a patch bump ([version-parts.md](version-parts.md)) with a changelog + entry naming the lift, then [publish-and-ci.md](publish-and-ci.md). A lift that touches + `requirements.lock` also starts the `Converters` workflow. + +## Decision points + +- **The nightly's `pip-audit` step is red, but no fixed version exists yet?** Nothing to lift. + Name the advisory and whether the stack reaches the vulnerable code in the topic issue, and + check again when a fix is released. +- **A regular lift fails with "No solution found ... filtered by `exclude-newer`"?** A floor in a + source file names a version younger than the cutoff - usually a security lift whose exception + was lost. Restore the exception from the lock's head in `git log -p`; never lower the floor. +- **A package wants a Python outside the span?** The resolution for the minimum fails or picks an + old version. The span is a design decision in `tools/prerequisites.txt`, not something a lift + moves; take it to `stack-dev`. +- **A new dependency?** Add it to the source file that matches who needs it, with a floor, then + regenerate. A package only the origin repository's tests need goes into + `requirements-dev.txt`, never into a lock that ships. + +## Scope + +The origin repository only - `dist export` ships the three runtime locks, not this file, the +script or the dev lock. The span of Python versions itself is `tools/prerequisites.txt` and +[instructions/preflight.md](../preflight.md); reasons for the design are Gitea #245. diff --git a/instructions/dev/publish-and-ci.md b/instructions/dev/publish-and-ci.md index f71f702..26d89ce 100644 --- a/instructions/dev/publish-and-ci.md +++ b/instructions/dev/publish-and-ci.md @@ -40,10 +40,12 @@ formality after it - which is why waiting for it belongs to the phase that wrote 3. **Wait for CI on the published commit, this way.** One runner serves the repository and it currently runs **no jobs in parallel**, so the jobs of a push run **one after another**: CI's `verify` job (about - **8 minutes**) and `pwsh` job (about **3 minutes**) first, then the second run a push to + **8 minutes**), `pwsh` job (about **3 minutes**) and `python314` job (the suite on the upper + end of the Python span, about **6 minutes**) first, then the second run a push to `main` starts - `release.yml`, preceded by the `Converters` check - which waits `queued` until CI is done and then takes about **1 minute**. From the push to the last green run that - is about **12 minutes** (measured 10.5 to 13 minutes, October 2026); a second run still + is about **18 minutes** (measured 10.5 to 13 minutes in October 2026, before the `python314` + job, whose share is an estimate until measured); a second run still `queued` while CI works is the runner's order, not a hang. The times below rest on that setup (`ENVIRONMENT.md` § CI records it); once the runner takes parallel jobs, measure them again and rewrite them here. @@ -52,8 +54,8 @@ formality after it - which is why waiting for it belongs to the phase that wrote `ENVIRONMENT.md` lists (the Gitea MCP's `actions_run_read`, `list_runs`), right after `publish`, to get their ids. **Never anonymously via `curl`:** Gitea answers the Actions API with `401 token is required` even for this public repo. - - Check again after about 11 minutes, then every 2 minutes. - - **Give up after 25 minutes** - twice the usual time, so a slow day is not mistaken for a + - Check again after about 16 minutes, then every 2 minutes. + - **Give up after 35 minutes** - about twice the usual time, so a slow day is not mistaken for a hang - and hand the open runs to the user by id and link, rather than waiting on. - **Count from when the runner is free, not from the push.** Runs of an earlier push that are still open when you publish run first, and the runner does not keep push order: it may take @@ -69,11 +71,11 @@ formality after it - which is why waiting for it belongs to the phase that wrote **Converter changes have a second run.** When the published commit touches the converter surface - `tools/chemenu/filters/`, `tools/chemenu/commands/raw/derive.py` or `accept.py`, `tools/chemenu/tests/test_raw_derive*.py`, `tools/chemenu/tests/binary_formats.py`, - `tools/requirements.txt` or `.gitea/workflows/converters.yml` - the `Converters` workflow + `tools/requirements.txt`, `tools/requirements.lock` or `.gitea/workflows/converters.yml` - the `Converters` workflow (`converters.yml`) starts by itself with CI and derives the real documents of the private test corpus. Deriving the corpus takes about **10 minutes** on top of CI, on the same - runner and after it, so the last run finishes about **22 minutes** after the push; give up - after **35 minutes** instead of 25, and count a red run like a red CI run (step 4). Start it by hand + runner and after it, so the last run finishes about **28 minutes** after the push; give up + after **45 minutes** instead of 35, and count a red run like a red CI run (step 4). Start it by hand (`actions_run_write`, `dispatch_workflow` on `main`) when only the private repository changed or when the commit reaches the converters only indirectly. A release without suffix runs the same steps as the first job of `release.yml`, which the release waits for. diff --git a/instructions/dev/stack-mode.md b/instructions/dev/stack-mode.md index cc0f101..4f812c4 100644 --- a/instructions/dev/stack-mode.md +++ b/instructions/dev/stack-mode.md @@ -92,6 +92,11 @@ slash command for the operator, and stops. *good*, not merely working: the converters against reference tools over the private corpus, seven measures, markings judged against the original, a baseline moved only on purpose. Read it before designing a converter change, after building one, and when the corpus gains a file. +- [dependency-locks.md](dependency-locks.md) - the four lock files under `tools/`: how a lock + is regenerated with the 7-day cooldown, how one package is lifted at once for a security fix + without ever being lowered again, how the result is checked, and what a red nightly audit or + fresh-resolution run asks for. Read it before changing a `tools/requirements*.txt`, and when + the nightly's dependency steps are red. - [doc-pull-through.md](doc-pull-through.md) - which document makes a claim about a touched surface (a `wikitool` command, a stage's rules, an `AGENTS.md` rule/gate/invariant, a README-shaped human doc, a `docs/` page's reasoning) and therefore needs updating alongside diff --git a/instructions/dev/tracker-testing.md b/instructions/dev/tracker-testing.md index a3244b6..6d95e48 100644 --- a/instructions/dev/tracker-testing.md +++ b/instructions/dev/tracker-testing.md @@ -123,7 +123,7 @@ that fails against theirs. The steps differ per tracker only in the profile and | Workflow | When | What | |---|---|---| -| `ci.yml`, step "Live tracker suite (CalDAV)" | Every push and PR | Radicale as a process on loopback (`pip install radicale`), `CHEMENU_LIVE_REQUIRE=caldav`. The one half that needs no app and no display. | +| `ci.yml`, step "Live tracker suite (CalDAV)" | Every push and PR | Radicale as a process on loopback (from `tools/requirements-dev.lock`), `CHEMENU_LIVE_REQUIRE=caldav`. The one half that needs no app and no display. | | `tracker-live.yml` | Nightly 05:00 UTC, and by hand | Both kinds, `CHEMENU_LIVE_REQUIRE=sp,caldav`, inside the `chemenu-sp-live` image. It logs the installed Super Productivity version and warns when it differs from the update channel. | | `sp-live-image.yml` | Daily 04:10 UTC, and by hand | Builds `gitea.nehmer.net/torben/chemenu-sp-live` when the registry lacks the channel's current version, and once a month regardless. | @@ -178,9 +178,9 @@ shows a new answer shape, and when the manifest's version is more than a few rel 1. Get a Super Productivity to record from: the current `chemenu-sp-live` image with the checkout mounted (`docker run --rm -v "$PWD:/work" -w /work/tools ...`, then a venv from - `requirements.txt` inside it), or any machine with the `.deb` installed and + `requirements.lock` inside it), or any machine with the `.deb` installed and `CHEMENU_LIVE_SP_BINARY` set. -2. From `tools/`, in an environment that has `requirements.txt`: +2. From `tools/`, in an environment that has `requirements.lock` installed: ```bash .venv/bin/python -m chemenu.tests.record_sp_fixtures chemenu/tests/fixtures/sp/api diff --git a/instructions/mcp-read-server.md b/instructions/mcp-read-server.md index ff7c7a0..22d0ea1 100644 --- a/instructions/mcp-read-server.md +++ b/instructions/mcp-read-server.md @@ -41,11 +41,12 @@ everything an operator needs that is *true of the software* rather than of one i ## Steps 1. **Install the server's dependency.** It is deliberately not in `requirements.txt`: an - instance that only uses the CLI should not be made to install pydantic, starlette, uvicorn - and cryptography to do it. + instance that only uses the CLI should not be made to install starlette, uvicorn and the + rest of a web server to do it. Install the lock beside it, never the `.txt`: exact versions + and hashes, consistent with what the preflight put into `tools/.venv`. ```bash - tools/.venv/bin/python -m pip install -r tools/requirements-mcp.txt + tools/.venv/bin/python -m pip install --require-hashes -r tools/requirements-mcp.lock ``` 2. **Decide which checkout it serves.** The root resolves by precedence - an explicit `--root`, diff --git a/instructions/preflight.md b/instructions/preflight.md index 15cd0e9..4144a06 100644 --- a/instructions/preflight.md +++ b/instructions/preflight.md @@ -14,20 +14,25 @@ known to exist: `tools/preflight.sh` for POSIX shells, `tools/preflight.ps1` for Windows. The two answer the same questions from the same list and write the same `.wikitool-tools.json`. It does three things, all inside the install folder: -- checks the tools listed in `tools/prerequisites.txt` - Python 3.11 or newer, git, ripgrep - (`rg`) - and, on Windows, that the install folder is short enough for Windows' path limit and +- checks the tools listed in `tools/prerequisites.txt` - Python 3.13 to 3.14 (both checked in + CI; an older or newer one is refused with exit 42, and a `python3.14`/`python3.13`, or `py -3.14` + on Windows, is taken where the plain `python` lies outside), git, ripgrep (`rg`) - and, on Windows, that the install folder is short enough for Windows' path limit and (PowerShell only) that the execution policy and the files' Mark of the Web let `tools/wikitool.ps1` start; - records the absolute path of each tool in `.wikitool-tools.json`, which `wikitool` then starts them from instead of trusting whatever `PATH` a session inherited - and of an optional tool, such as the 1Password CLI `op`, when it finds one: an optional tool missing is reported as `ABSENT` and is never a reason to stop, nor to install anything; -- creates `tools/.venv` from the recorded Python and installs `tools/requirements.txt` into it. +- creates `tools/.venv` from the recorded Python and installs `tools/requirements.lock` into it: + exact versions with their SHA-256 hashes (`pip install --require-hashes`), so every instance + of one stack version runs the same packages. When an update brings a changed lock, the next + run moves the venv to it, a version up or down; a venv built on a Python outside the span is + built again on the one found. One more thing it does only when the user asks for it: `--with browser` installs the optional -browser component - `tools/requirements-browser.txt` and the Chromium it drives - into +browser component - `tools/requirements-browser.lock` and the Chromium it drives - into `tools/.venv`. Only `raw login` and a page a site handler fetches through a browser need it. Once -installed, every later run keeps it up to date; nothing else ever installs it. +installed, every later run keeps it at its lock; nothing else ever installs it. ## Contents diff --git a/tools/CONTRACT.md b/tools/CONTRACT.md index 337764c..91ae642 100644 --- a/tools/CONTRACT.md +++ b/tools/CONTRACT.md @@ -4240,7 +4240,8 @@ Check that this instance is correctly configured. - **The MCP server** (`chemenu/mcp/`) is that second adapter: `search`, `types`, `describe_type`, `lint` and `status` over `chemenu.api`, on `stdio` or `streamable-http`. Its dependency is optional and lives in - `requirements-mcp.txt`, so a CLI-only instance does not install it. Five of + `requirements-mcp.txt` (installed from its lock, `requirements-mcp.lock`), so a CLI-only + instance does not install it. Five of its tools are structurally read-only - nothing under `commands/` is importable from the server, so `new`/`touch`/`xref`/`cite`/ `publish`/`migrate` are unreachable rather than filtered - and every @@ -4294,12 +4295,13 @@ type-specs and conventions rather than an instance's. There: ```bash cd tools -.venv/bin/pip install pytest pytest-cov # one time; pytest-cov is optional +.venv/bin/python -m pip install --require-hashes -r requirements-dev.lock # one time .venv/bin/python -m pytest -q # add --cov for a coverage report ``` -Neither is in `requirements.txt`, and `pytest-cov` is CI-only by intent: `requirements.txt` is -what an instance needs at runtime, and an instance does not measure this suite. +The test tools sit in `requirements-dev.txt` and its lock, not in `requirements.txt`: that one +is what an instance needs at runtime, and an instance does not run this suite. Both, and the +`lock_requirements.py` that writes every lock, are dev-only as well. ## Maintenance schedule diff --git a/tools/README.md b/tools/README.md index c5ac7a1..d93e8ba 100644 --- a/tools/README.md +++ b/tools/README.md @@ -27,11 +27,23 @@ pwsh -NoProfile -ExecutionPolicy Bypass -File tools/preflight.ps1 # PowerShell The preflight is the one way a checkout gets its environment: it checks the tools listed in `prerequisites.txt`, records their absolute paths in -`../.wikitool-tools.json`, creates `.venv` and installs `requirements.txt` into -it with `-m pip`. It is POSIX sh because it has to run before Python is known +`../.wikitool-tools.json`, creates `.venv` and installs `requirements.lock` into +it with `-m pip --require-hashes`. It is POSIX sh because it has to run before Python is known to exist; exit 42 means the user has to act, and its output says how. The procedure an agent follows around it is `instructions/preflight.md`. +Python is admitted in a span, both ends in `prerequisites.txt` (3.13 to 3.14): what CI checks +is exactly what the preflight and `doctor` accept. A `.venv` built on a Python outside it is +built again on the one the preflight found. + +Every `requirements*.txt` holds lower bounds only and is never installed itself. Beside each +sits a `.lock` with exact versions and SHA-256 hashes for everything it resolves to, written +from it with a 7-day cooldown on new releases; the preflight stamps the lock's hash into +`.venv/.chemenu-requirements.sha256` and installs it again whenever it changes, so an +instance follows the lock of the stack it runs, up or down. The three locks resolve against +each other, so a package that sits in two has one version. They are written in the origin +repository, never by hand. + Each release also attaches `preflight.sh` and `preflight.ps1` as assets, for the first install before any tree exists. `release.yml` writes the download address of that same release into two placeholder lines of the copy (`RELEASE_ARCHIVE_URL`/`RELEASE_CHECKSUM_URL` in the shell script, @@ -74,7 +86,7 @@ but are imported only when a PDF or an Outlook `.msg` is derived, so a missing o that format alone; `doctor` reports each. Playwright is the one package that is not in `requirements.txt`: it sits in -`requirements-browser.txt`, which the preflight installs - together with the Chromium it +`requirements-browser.txt` (installed from its lock), which the preflight installs - together with the Chromium it drives, into `.venv/ms-playwright` - only when the user runs it with `--with browser`, and keeps up to date from then on (`.venv/.chemenu-browser.sha256` remembers the choice). Only `raw login` and a page a site handler declares `render` need it; `browser.py` imports it @@ -288,7 +300,13 @@ ignoring generated copies. The suite exists in the origin repository only: `dist export` leaves out `chemenu/tests/`, `pytest.ini` and `.coveragerc`, because the suite tests that repository's own type-specs and -conventions, not an instance's. +conventions, not an instance's. The same goes for the test tools - `requirements-dev.txt` and +its lock (pytest, pytest-cov, radicale, pip-audit, uv) - and `lock_requirements.py`, which +writes every lock; `instructions/dev/dependency-locks.md` has the procedure. + +```bash +.venv/bin/python -m pip install --require-hashes -r requirements-dev.lock # one time +``` ```bash cd tools && .venv/bin/python -m pytest -q @@ -300,13 +318,12 @@ cd tools && .venv/bin/python -m pytest -q Coverage is optional locally and measured on every CI run: ```bash -.venv/bin/pip install pytest-cov # one time, CI-only dependency .venv/bin/python -m pytest -q --cov ``` -`pytest-cov` is deliberately not in `requirements.txt`: that file is what an *instance* -needs at runtime and ships with `dist export`, and an instance does not measure this -suite. Configuration is `.coveragerc` (coverage.py does not read `pytest.ini`), which +`pytest-cov` is deliberately not in `requirements.txt` but in `requirements-dev.txt`: the +first is what an *instance* needs at runtime and ships with `dist export`, and an instance +does not measure this suite. Configuration is `.coveragerc` (coverage.py does not read `pytest.ini`), which measures `chemenu/` without `chemenu/tests/` and sets no threshold - the origin repository's developer guide, `docs/dev/development.md` § "How much of the stack the suite reaches", has the measured number and how to read it. diff --git a/tools/chemenu/commands/dist_cmd.py b/tools/chemenu/commands/dist_cmd.py index adfbdf5..55cf1e2 100644 --- a/tools/chemenu/commands/dist_cmd.py +++ b/tools/chemenu/commands/dist_cmd.py @@ -130,7 +130,15 @@ TOOLS_EXCLUDE_DIRS = {".venv", "__pycache__", ".pytest_cache", ".wikitool_sessio # own decisions - so in an exported tree a quarter of it fails, and `pytest` is # not in requirements.txt to run it with anyway. Matched by exact path, not by # name: a directory called `tests` elsewhere under tools/ would be machinery. -TOOLS_DEV_ONLY = frozenset({"chemenu/tests", "pytest.ini", ".coveragerc"}) +# +# The dependency locks go the same way in part (Gitea #245): an instance ships the +# three runtime locks it installs from, but not the test tools' source and lock +# (`requirements-dev.*`) nor the script that writes every lock - resolving needs +# `uv` and the source files' history, which belong to the origin repository. +TOOLS_DEV_ONLY = frozenset({ + "chemenu/tests", "pytest.ini", ".coveragerc", + "requirements-dev.txt", "requirements-dev.lock", "lock_requirements.py", +}) # The rest of coverage's output lands beside the code rather than in a directory # of its own - `.coverage`, `coverage.xml`, and `.coverage..` under a diff --git a/tools/chemenu/commands/doctor.py b/tools/chemenu/commands/doctor.py index 43fa834..a6254fd 100644 --- a/tools/chemenu/commands/doctor.py +++ b/tools/chemenu/commands/doctor.py @@ -57,11 +57,15 @@ EXPORT_HOW_TO = "docs/how-to/export-to-a-synced-folder.md" def check_python() -> Check: + """The Python `wikitool` runs on - tools/.venv's - against the span + tools/prerequisites.txt admits, the same line the preflight reads.""" version = sys.version_info - if version < (3, 11): + python = prerequisites.load_manifest().tool("python") + if not python.admits(version.major, version.minor): return Check( - "python", "FAIL", f"Python {version.major}.{version.minor} found, need >= 3.11", - f"Install Python 3.11+, then: {PREFLIGHT_FIX}", + "python", "FAIL", + f"tools/.venv runs on Python {version.major}.{version.minor}, the stack needs {python.span()}", + f"Install Python {python.span()}, then: {PREFLIGHT_FIX} - it rebuilds tools/.venv on it", ) return Check("python", "OK", f"Python {version.major}.{version.minor}.{version.micro}") diff --git a/tools/chemenu/install_doc.py b/tools/chemenu/install_doc.py index a901b9f..d1cda92 100644 --- a/tools/chemenu/install_doc.py +++ b/tools/chemenu/install_doc.py @@ -12,7 +12,7 @@ neither can drift silently: preflight and `doctor` read it. `INSTALL.md` carries it as a generated region per platform value (`` for `all`, `` otherwise), rendered from the - label and minimum version only. The manifest's `why` field stays out: it + label and version bounds only. The manifest's `why` field stays out: it explains a tool to whoever reads the preflight's own output, while the region only says what to install. A region is never placed by the tool - where it goes is the human document's own decision - so a missing one is @@ -63,12 +63,19 @@ def region_name(platform: str) -> str: return REGION_PREFIX if platform == "all" else f"{REGION_PREFIX}-{platform}" +def _bounds(tool: prerequisites.Tool) -> str: + if tool.minimum and tool.maximum: + return f" {tool.minimum} – {tool.maximum}" + if tool.minimum: + return f" ≥ {tool.minimum}" + if tool.maximum: + return f" ≤ {tool.maximum}" + return "" + + def render_lines(tools: tuple[prerequisites.Tool, ...]) -> list[str]: - """One list item per tool - label and minimum version, nothing in a language.""" - return [ - f"- **{tool.label}**" + (f" ≥ {tool.minimum}" if tool.minimum else "") - for tool in tools - ] + """One list item per tool - label and version bounds, nothing in a language.""" + return [f"- **{tool.label}**{_bounds(tool)}" for tool in tools] def expected_regions(manifest: prerequisites.Manifest) -> dict[str, str]: diff --git a/tools/chemenu/prerequisites.py b/tools/chemenu/prerequisites.py index 1f72b65..d99e28d 100644 --- a/tools/chemenu/prerequisites.py +++ b/tools/chemenu/prerequisites.py @@ -45,6 +45,29 @@ class Tool: platforms: str label: str why: str + maximum: Optional[str] = None + + def admits(self, major: int, minor: int) -> bool: + """Whether major.minor lies within this tool's bounds, both inclusive.""" + have = (major, minor) + return ((self.minimum is None or have >= version_tuple(self.minimum)) + and (self.maximum is None or have <= version_tuple(self.maximum))) + + def span(self) -> str: + """The admitted versions in words: `3.13 to 3.14`, `7 or newer`, or ``.""" + if self.minimum and self.maximum: + return f"{self.minimum} to {self.maximum}" + if self.minimum: + return f"{self.minimum} or newer" + if self.maximum: + return f"{self.maximum} or older" + return "" + + +def version_tuple(text: str) -> tuple[int, int]: + """`3.13` -> (3, 13), `7` -> (7, 0) - the major.minor the manifest names.""" + major, _, minor = text.partition(".") + return int(major), int(minor or 0) @dataclass(frozen=True) @@ -64,6 +87,12 @@ class Manifest: def tools_for(self, platform: str) -> tuple[Tool, ...]: return tuple(t for t in self.tools if t.platforms in ("all", platform)) + def tool(self, name: str) -> Tool: + for candidate in self.tools: + if candidate.name == name: + return candidate + raise KeyError(name) + def manifest_path() -> Path: return config._PACKAGE_ROOT / "tools" / "prerequisites.txt" @@ -82,7 +111,8 @@ def load_manifest(path: Optional[Path] = None) -> Manifest: limits[fields[1]] = int(fields[2]) elif fields[0] == "tool": minimum = None if fields[2] == "-" else fields[2] - tools.append(Tool(fields[1], minimum, fields[3], fields[4], fields[5])) + maximum = None if fields[3] == "-" else fields[3] + tools.append(Tool(fields[1], minimum, fields[4], fields[5], fields[6], maximum)) elif fields[0] == "optional": optional.append(OptionalTool(fields[1], fields[2], fields[3])) return Manifest(limits, tuple(tools), tuple(optional)) diff --git a/tools/chemenu/tests/test_dependency_locks.py b/tools/chemenu/tests/test_dependency_locks.py new file mode 100644 index 0000000..32f47bb --- /dev/null +++ b/tools/chemenu/tests/test_dependency_locks.py @@ -0,0 +1,163 @@ +"""The dependency locks under tools/ (Gitea #245): what each one has to hold, and how +they hold together. + +The locks are written by tools/lock_requirements.py and installed with +`pip install --require-hashes`; instructions/dev/dependency-locks.md is the procedure. +These tests read the committed files only - nothing here resolves or downloads. +""" +from __future__ import annotations + +import importlib.util +import re +import subprocess +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import pytest +from packaging.requirements import Requirement +from packaging.utils import canonicalize_name +from packaging.version import Version + +from chemenu import config + +TOOLS = config._PACKAGE_ROOT / "tools" +WORKFLOWS = config._PACKAGE_ROOT / ".gitea" / "workflows" + + +def _load_script(): + spec = importlib.util.spec_from_file_location("lock_requirements", TOOLS / "lock_requirements.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +SCRIPT = _load_script() +CHAIN = [(TOOLS / source, TOOLS / lock) for source, lock in SCRIPT.CHAIN] + +PIN_RE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9._-]*)==([^\s;\\]+)") + + +def entries(lock: Path) -> dict[str, tuple[str, list[str]]]: + """name -> (version, hashes) for every package the lock pins.""" + found: dict[str, tuple[str, list[str]]] = {} + current = None + for line in lock.read_text(encoding="utf-8").splitlines(): + if line.startswith("#") or not line.strip(): + continue + pin = PIN_RE.match(line) + if pin: + current = canonicalize_name(pin.group(1)) + assert current not in found, f"{lock.name} pins {current} twice" + found[current] = (pin.group(2), []) + elif not line.startswith(" "): + pytest.fail(f"{lock.name}: a line that pins nothing exactly: {line!r}") + if current: + found[current][1].extend(re.findall(r"--hash=sha256:([0-9a-f]{64})", line)) + return found + + +@pytest.mark.parametrize("source, lock", CHAIN, ids=[lock.name for _, lock in CHAIN]) +def test_every_package_is_pinned_exactly_with_a_sha256(source, lock): + pinned = entries(lock) + assert pinned, f"{lock.name} pins nothing" + for name, (version, hashes) in pinned.items(): + assert hashes, f"{lock.name}: {name}=={version} carries no sha256" + + +@pytest.mark.parametrize("source, lock", CHAIN, ids=[lock.name for _, lock in CHAIN]) +def test_every_requirement_of_the_source_is_in_its_lock_at_or_above_its_floor(source, lock): + """The floor in the source file is what keeps a later lift from lowering a package - + the invariant of a security lift (#245, point 3): `>=X` stays, so the lock never falls + below X again.""" + pinned = entries(lock) + for line in source.read_text(encoding="utf-8").splitlines(): + line = line.split("#", 1)[0].strip() + if not line: + continue + requirement = Requirement(line) + name = canonicalize_name(requirement.name) + assert name in pinned, f"{source.name} asks for {name}, {lock.name} does not pin it" + assert requirement.specifier.contains(Version(pinned[name][0]), prereleases=True), ( + f"{lock.name} pins {name}=={pinned[name][0]}, outside {source.name}'s {requirement.specifier}") + + +def test_a_package_in_two_locks_has_the_same_version_in_both(): + """All of them land in one venv; a later `pip install -r` of one lock must not move a + package another placed (#245, point 8).""" + seen: dict[str, tuple[str, str]] = {} + for _, lock in CHAIN: + for name, (version, _) in entries(lock).items(): + if name in seen: + assert seen[name][0] == version, ( + f"{name}: {seen[name][1]} pins {seen[name][0]}, {lock.name} pins {version}") + else: + seen[name] = (version, lock.name) + + +@pytest.mark.parametrize("source, lock", CHAIN, ids=[lock.name for _, lock in CHAIN]) +def test_each_lock_is_constrained_by_every_lock_before_it(source, lock): + command = SCRIPT.header(lock) + position = [lock for _, lock in CHAIN].index(lock) + for _, earlier in CHAIN[:position]: + assert f"-c tools/{earlier.name}" in command, f"{lock.name} was not resolved against {earlier.name}" + assert "--universal" in command and "--generate-hashes" in command + + +def _written_at(lock: Path) -> datetime: + """When the lock was written, as far as git can say: its last commit, or now while + it differs from HEAD (it has just been regenerated).""" + root = config._PACKAGE_ROOT + try: + dirty = subprocess.run(["git", "status", "--porcelain", "--", str(lock)], cwd=root, + capture_output=True, text=True, timeout=10) + stamp = subprocess.run(["git", "log", "-1", "--format=%cI", "--", str(lock)], cwd=root, + capture_output=True, text=True, timeout=10) + except (OSError, subprocess.SubprocessError): + return datetime.now(timezone.utc) + if dirty.returncode != 0 or dirty.stdout.strip() or not stamp.stdout.strip(): + return datetime.now(timezone.utc) + return datetime.fromisoformat(stamp.stdout.strip()).astimezone(timezone.utc) + + +@pytest.mark.parametrize("source, lock", CHAIN, ids=[lock.name for _, lock in CHAIN]) +def test_no_package_was_younger_than_the_cooldown_when_the_lock_was_written(source, lock): + """`--exclude-newer` in the lock's head is the cutoff uv honoured; it has to lie at least + COOLDOWN_DAYS before the lock was written. A security lift is the one way past it, and + it shows as `--exclude-newer-package` beside the cutoff (#245, points 2 and 3).""" + cutoff = SCRIPT.cutoff_of(lock) + assert cutoff is not None, f"{lock.name} was written without --exclude-newer" + assert cutoff <= _written_at(lock) - timedelta(days=SCRIPT.COOLDOWN_DAYS), ( + f"{lock.name}: cutoff {cutoff:%Y-%m-%d %H:%M} is less than {SCRIPT.COOLDOWN_DAYS} days " + "before the lock was written - regenerate it with tools/lock_requirements.py") + + +def test_the_locks_resolve_for_the_python_minimum_of_the_manifest(): + for _, lock in CHAIN: + assert f"--python-version {SCRIPT.python_minimum()}" in SCRIPT.header(lock) + + +def test_an_exception_is_carried_while_young_and_dropped_once_the_cutoff_passes_it(tmp_path, monkeypatch): + lock = tmp_path / "requirements.lock" + lock.write_text( + "# This file was autogenerated by uv via the following command:\n" + "# uv pip compile tools/requirements.txt --exclude-newer 2026-11-01T00:00:00Z " + "--exclude-newer-package young=2026-11-16T10:00:00Z " + "--exclude-newer-package old=2026-10-20T10:00:00Z -o tools/requirements.lock\n" + "pyyaml==6.0.3 \\\n --hash=sha256:" + "0" * 64 + "\n", + encoding="utf-8") + monkeypatch.setattr(SCRIPT, "CHAIN", (("requirements.txt", "requirements.lock"),)) + monkeypatch.setattr(SCRIPT, "TOOLS", tmp_path) + cutoff = datetime(2026, 11, 11, tzinfo=timezone.utc) + assert SCRIPT.carried_exceptions(cutoff) == {"young": datetime(2026, 11, 16, 10, tzinfo=timezone.utc)} + + +def test_no_workflow_installs_a_package_or_requirements_file_without_a_lock(): + """#245: every `pip install` in CI goes through a lock with --require-hashes.""" + offenders = [] + for workflow in sorted(WORKFLOWS.glob("*.yml")): + for number, line in enumerate(workflow.read_text(encoding="utf-8").splitlines(), 1): + if "pip install" not in line or line.lstrip().startswith("#"): + continue + if "--require-hashes" not in line or not re.search(r"-r \S+\.lock\b", line): + offenders.append(f"{workflow.name}:{number}: {line.strip()}") + assert offenders == [] diff --git a/tools/chemenu/tests/test_dist_cmd.py b/tools/chemenu/tests/test_dist_cmd.py index 25618e5..5e9aa50 100644 --- a/tools/chemenu/tests/test_dist_cmd.py +++ b/tools/chemenu/tests/test_dist_cmd.py @@ -349,6 +349,26 @@ def test_plan_excludes_the_test_suite_and_its_configuration_by_exact_path(repo): assert "tools/chemenu/tests.py" in plan +def test_plan_ships_the_runtime_locks_but_not_the_dev_ones_nor_the_script_that_writes_them(repo): + """#245: an instance installs from requirements.lock (and the MCP and browser locks, + when it wants those parts) - so they ship. The test tools' source and lock and + lock_requirements.py serve only the origin repository and stay behind.""" + tools_dir = repo / "tools" + names = ("requirements", "requirements-mcp", "requirements-browser", "requirements-dev") + for name in names: + (tools_dir / f"{name}.txt").write_text("x>=1\n", encoding="utf-8") + (tools_dir / f"{name}.lock").write_text("x==1 --hash=sha256:00\n", encoding="utf-8") + (tools_dir / "lock_requirements.py").write_text("", encoding="utf-8") + + plan = dist_cmd.build_plan() + + for name in names[:3]: + assert f"tools/{name}.txt" in plan and f"tools/{name}.lock" in plan + assert "tools/requirements-dev.txt" not in plan + assert "tools/requirements-dev.lock" not in plan + assert "tools/lock_requirements.py" not in plan + + def test_plan_ships_the_environment_template_but_not_the_filled_file(repo): """Same split as the personalization pair, for the same reason: a distribution can say what the file is for, never what one checkout's diff --git a/tools/chemenu/tests/test_doctor.py b/tools/chemenu/tests/test_doctor.py index 321bce7..0bb5f1e 100644 --- a/tools/chemenu/tests/test_doctor.py +++ b/tools/chemenu/tests/test_doctor.py @@ -813,3 +813,40 @@ def test_an_installed_browser_component_is_ok(instance, monkeypatch): monkeypatch.setattr(browser, "missing", lambda: None) assert _status(doctor.run_doctor(), "browser") == "OK" + + +# --- the Python span (Gitea #245) ------------------------------------------------------- + + +def _python_check(monkeypatch, major: int, minor: int) -> doctor.Check: + from types import SimpleNamespace + + fake = SimpleNamespace(version_info=SimpleNamespace(major=major, minor=minor, micro=4)) + monkeypatch.setattr(doctor, "sys", fake) + return doctor.check_python() + + +@pytest.mark.parametrize("minor, status", [(12, "FAIL"), (13, "OK"), (14, "OK"), (15, "FAIL")]) +def test_python_is_judged_against_the_span_of_the_manifest(monkeypatch, minor, status): + check = _python_check(monkeypatch, 3, minor) + assert check.status == status + if status == "FAIL": + assert f"Python 3.{minor}" in check.detail and "3.13 to 3.14" in check.detail + assert "Install Python 3.13 to 3.14" in check.fix and "preflight" in check.fix + + +def test_python_follows_the_manifest_rather_than_a_literal(monkeypatch, tmp_path): + manifest = tmp_path / "prerequisites.txt" + manifest.write_text("tool|python|3.10|3.11|all|Python|why|-|-|-|-|-\n", encoding="utf-8") + monkeypatch.setattr(prerequisites, "manifest_path", lambda: manifest) + assert _python_check(monkeypatch, 3, 11).status == "OK" + assert _python_check(monkeypatch, 3, 13).status == "FAIL" + + +def test_doctor_carries_no_python_version_literal(): + """The span lives in tools/prerequisites.txt alone; doctor once had 3.11 typed in.""" + import re + + source = Path(doctor.__file__).read_text(encoding="utf-8") + body = source.split("def check_python", 1)[1].split("\ndef ", 1)[0] + assert not re.search(r"\b3\.\d+\b|\(3,\s*\d+\)", body) diff --git a/tools/chemenu/tests/test_install_doc.py b/tools/chemenu/tests/test_install_doc.py index c421d18..d983249 100644 --- a/tools/chemenu/tests/test_install_doc.py +++ b/tools/chemenu/tests/test_install_doc.py @@ -9,7 +9,7 @@ runner = CliRunner() MANIFEST = prerequisites.Manifest( limits={}, tools=( - prerequisites.Tool("python", "3.11", "all", "Python", "why"), + prerequisites.Tool("python", "3.13", "all", "Python", "why", "3.14"), prerequisites.Tool("git", None, "all", "Git", "why"), prerequisites.Tool("pwsh", "7", "windows", "PowerShell 7 (pwsh)", "why"), ), @@ -20,7 +20,7 @@ CURRENT = """# Installation You need: -- **Python** ≥ 3.11 +- **Python** 3.13 – 3.14 - **Git** @@ -76,14 +76,25 @@ def test_this_repos_setup_instruction_marks_its_questions(): } -def test_render_lines_are_label_and_minimum_only(): +def test_render_lines_are_label_and_version_bounds_only(): assert install_doc.render_lines(MANIFEST.tools) == [ - "- **Python** ≥ 3.11", + "- **Python** 3.13 – 3.14", "- **Git**", "- **PowerShell 7 (pwsh)** ≥ 7", ] +def test_a_maximum_alone_renders_as_an_upper_bound(): + tool = prerequisites.Tool("x", None, "all", "X", "why", "2") + assert install_doc.render_lines((tool,)) == ["- **X** ≤ 2"] + + +def test_the_real_install_doc_names_the_python_span(): + """#245: INSTALL.md carries the admitted span, not a floor alone.""" + text = (config._PACKAGE_ROOT / install_doc.INSTALL_DOC).read_text(encoding="utf-8") + assert "- **Python** 3.13 – 3.14" in text + + def test_a_current_install_doc_passes(tmp_path, monkeypatch): _tree(tmp_path, monkeypatch) assert install_doc.check_prerequisite_regions() == [] @@ -122,7 +133,7 @@ def test_a_missing_install_doc_is_reported(tmp_path, monkeypatch): def test_refresh_touches_nothing_outside_the_regions(tmp_path): - stale = CURRENT.replace("≥ 3.11", "≥ 3.9") + stale = CURRENT.replace("3.13 – 3.14", "≥ 3.9") refreshed, missing = install_doc.refresh(stale, MANIFEST) assert missing == [] assert refreshed == CURRENT @@ -154,7 +165,7 @@ def test_a_question_no_longer_asked_fails(tmp_path, monkeypatch): def test_docs_prerequisites_is_a_dry_run_by_default(tmp_path, monkeypatch): - stale = CURRENT.replace("≥ 3.11", "≥ 3.9") + stale = CURRENT.replace("3.13 – 3.14", "≥ 3.9") root = _tree(tmp_path, monkeypatch, install=stale) result = runner.invoke(app, ["docs", "prerequisites"]) assert result.exit_code == 0, result.output @@ -163,7 +174,7 @@ def test_docs_prerequisites_is_a_dry_run_by_default(tmp_path, monkeypatch): def test_docs_prerequisites_apply_rewrites_the_regions(tmp_path, monkeypatch): - root = _tree(tmp_path, monkeypatch, install=CURRENT.replace("≥ 3.11", "≥ 3.9")) + root = _tree(tmp_path, monkeypatch, install=CURRENT.replace("3.13 – 3.14", "≥ 3.9")) result = runner.invoke(app, ["docs", "prerequisites", "--apply"]) assert result.exit_code == 0, result.output assert (root / "INSTALL.md").read_text(encoding="utf-8") == CURRENT diff --git a/tools/chemenu/tests/test_preflight.py b/tools/chemenu/tests/test_preflight.py index 4d8ba30..54268bc 100644 --- a/tools/chemenu/tests/test_preflight.py +++ b/tools/chemenu/tests/test_preflight.py @@ -61,13 +61,14 @@ case "$1" in case "$2" in *hashlib*) exec "{real}" "$@" ;; esac - printf '%s\\n%s\\n' "${{FAKE_PY_VERSION:-3.13}}" "$0" + printf '%s\\n%s\\n' "{version}" "$0" exit 0 ;; -m) case "$2" in venv) shift 2 - [ "$1" = --clear ] && shift + # --clear empties the folder first, stamps included, as the real one does. + if [ "$1" = --clear ]; then shift; rm -rf "$1"; fi if [ -n "${{FAKE_VENV_FAIL:-}}" ]; then echo "Error: ensurepip is not available" >&2 exit 1 @@ -115,7 +116,7 @@ class Machine: for name in ("preflight.sh", "preflight.ps1", "prerequisites.txt", "wikitool", "wikitool.ps1", "run_wikitool.py", "trace-hook", "trace-hook.ps1"): shutil.copy2(TOOLS / name, self.tools / name) - (self.tools / "requirements.txt").write_text("PyYAML\n", encoding="utf-8") + (self.tools / "requirements.lock").write_text("pyyaml==6.0.3 --hash=sha256:00\n", encoding="utf-8") self.sysbin = base / "sysbin" self.sysbin.mkdir(exist_ok=True) for name in UTILITIES: @@ -131,8 +132,26 @@ class Machine: def stub(self, name: str, text: str, where: Path | None = None) -> Path: return _executable((where or self.stubs) / name, text) - def python(self, name: str = "python3", where: Path | None = None) -> Path: - return self.stub(name, FAKE_PYTHON.format(real=sys.executable), where) + def python(self, name: str = "python3", where: Path | None = None, version: str | None = None) -> Path: + """The fake Python; `version` fixes the one it reports, else FAKE_PY_VERSION decides + (3.13 when unset).""" + return self.stub(name, FAKE_PYTHON.format(real=sys.executable, + version=version or "${FAKE_PY_VERSION:-3.13}"), where) + + def py_launcher(self, default: str, versions: tuple[str, ...]) -> dict[str, Path]: + """Windows' `py`: `-3.X` starts the fake Python of that version, which lies off + PATH as the real ones do; anything else is a fake Python of `default`. Returns the + version -> interpreter map, whose paths are what the probe reports.""" + installed = {version: self.python(f"python{version}", self.base / "py-installs" / version, version) + for version in versions} + cases = "".join(f' -{version}) shift; exec "{path}" "$@" ;;\n' for version, path in installed.items()) + fallback = self.python("python-default", self.base / "py-installs" / "default", default) + self.stub("py", f'#!/bin/sh\ncase "$1" in\n{cases} -3) shift ;;\nesac\nexec "{fallback}" "$@"\n') + return installed + + def existing_venv(self, version: str) -> Path: + """A tools/.venv left by an earlier run, whose Python reports `version`.""" + return self.python("python", self.tools / ".venv" / "bin", version) def standard(self, rg: bool = True, pwsh: bool = False) -> "Machine": self.python() @@ -270,6 +289,163 @@ def test_python_too_old_stops(machine, shell): assert_guidance(result.stdout, "Python 3.9 is too old") +# --- the Python span (Gitea #245) ---------------------------------------------------- + +PY_SPAN = prerequisites.load_manifest().tool("python") + + +def test_the_manifest_admits_python_3_13_to_3_14(): + assert (PY_SPAN.minimum, PY_SPAN.maximum) == ("3.13", "3.14") + + +@pytest.mark.parametrize("shell", SHELLS) +@pytest.mark.parametrize("version, status", [("3.12", "TOO_OLD"), ("3.13", "OK"), + ("3.14", "OK"), ("3.15", "TOO_NEW")]) +def test_both_ends_of_the_span_are_inclusive_and_only_they(machine, shell, version, status): + machine.standard() + machine.extra_env["FAKE_PY_VERSION"] = version + result = machine.run(shell=shell) + assert any(line.split()[:2] == [status, "python"] for line in result.stdout.splitlines()), result.stdout + if status == "OK": + assert result.returncode == 0, result.stdout + return + assert result.returncode == 42 + word = "old" if status == "TOO_OLD" else "new" + assert_guidance(result.stdout, f"Python {version} is too {word} - this stack needs Python 3.13 to 3.14", + "--set python=") + assert not (machine.tools / ".venv").exists() + + +@pytest.mark.parametrize("shell", SHELLS) +@pytest.mark.parametrize("default", ["3.12", "3.15"]) +def test_a_versioned_python_of_the_span_is_taken_when_the_plain_one_lies_outside(machine, shell, default): + machine.standard() + machine.python("python3", version=default) + versioned = machine.python("python3.14", version="3.14", where=machine.base / "elsewhere") + machine.path_dirs.append(versioned.parent) + result = machine.run(shell=shell) + assert result.returncode == 0, result.stdout + assert machine.recorded()["tools"]["python"] == str(versioned) + + +@pytest.mark.parametrize("shell", SHELLS) +def test_on_windows_the_launcher_is_asked_for_a_version_of_the_span(machine, shell): + machine.standard(pwsh=True) + machine.extra_env.update(CHEMENU_PREFLIGHT_PLATFORM="windows", CHEMENU_PREFLIGHT_LONGPATHS="1", + FAKE_PY_VERSION="3.15") + installed = machine.py_launcher("3.15", ("3.13", "3.14")) + result = machine.run(shell=shell) + assert result.returncode == 0, result.stdout + assert machine.recorded()["tools"]["python"] == str(installed["3.14"]) + + +@pytest.mark.parametrize("shell", SHELLS) +def test_on_linux_an_out_of_span_python_names_the_distribution_and_set_but_no_other_tool(machine, shell): + """Variant A of #245, point 10: the apt line stays, and the message says that the + distribution may have no Python of the span - pointing at --set, not at uv or a PPA.""" + machine.standard() + machine.stub("apt-get", "#!/bin/sh\nexit 0\n") + machine.extra_env.update(CHEMENU_PREFLIGHT_PLATFORM="linux", FAKE_PY_VERSION="3.12") + result = machine.run(shell=shell) + assert result.returncode == 42 + assert_guidance(result.stdout, "sudo apt install python3 python3-venv", + "package source of this Linux distribution may offer no Python 3.13 to 3.14", + f"{'tools/preflight.sh'} --set python=") + fix = result.stdout.split("Fix:", 1)[1] + for other in ("uv ", "pyenv", "deadsnakes", "conda", "ppa:"): + assert other not in fix + + +@pytest.mark.parametrize("shell", SHELLS) +@pytest.mark.parametrize("platform", ["macos", "windows"]) +def test_off_linux_the_message_carries_no_distribution_note(machine, shell, platform): + machine.standard(pwsh=True) + machine.extra_env.update(CHEMENU_PREFLIGHT_PLATFORM=platform, CHEMENU_PREFLIGHT_LONGPATHS="1", + FAKE_PY_VERSION="3.15") + result = machine.run(shell=shell) + assert result.returncode == 42 + assert_guidance(result.stdout, "Python 3.15 is too new") + assert "Linux distribution" not in result.stdout + + +def test_the_python_install_fields_name_a_version_of_the_span(): + """winget, choco and brew can install one given version, so the manifest names that one + rather than the newest; apt and pacman stay the distribution's own python (#245, point 10).""" + fields = next(line.split("|") for line in (TOOLS / "prerequisites.txt").read_text(encoding="utf-8").splitlines() + if line.startswith("tool|python|")) + choco, winget, brew, apt, pacman = fields[7:12] + assert choco == "choco install python314" + assert winget == "winget install --id Python.Python.3.14 -e" + assert brew == "brew install python@3.14" + assert (apt, pacman) == ("sudo apt install python3 python3-venv", "sudo pacman -S python") + + +# --- tools/.venv and the lock (Gitea #245) ------------------------------------------- + + +@pytest.mark.parametrize("shell", SHELLS) +def test_the_venv_installs_the_lock_with_hashes_required(machine, shell): + machine.standard() + assert machine.run(shell=shell).returncode == 0 + (line,) = [line for line in machine.pip_log.read_text(encoding="utf-8").splitlines() if "install" in line] + assert "--require-hashes" in line.split() + assert line.endswith(str(machine.tools / "requirements.lock")) + stamp = (machine.tools / ".venv" / ".chemenu-requirements.sha256").read_text(encoding="utf-8").strip() + assert stamp == hashlib.sha256((machine.tools / "requirements.lock").read_bytes()).hexdigest() + + +@pytest.mark.parametrize("shell", SHELLS) +def test_a_changed_lock_is_installed_on_the_next_run_and_only_then(machine, shell): + """An instance whose tools/ was replaced by a newer stack moves its venv to the new lock - + pip installs `==` pins whichever way they point - with no step of its own.""" + machine.standard() + assert machine.run(shell=shell).returncode == 0 + assert machine.run(shell=shell).returncode == 0 + (machine.tools / "requirements.lock").write_text("pyyaml==6.0.2 --hash=sha256:11\n", encoding="utf-8") + assert machine.run(shell=shell).returncode == 0 + installs = [line for line in machine.pip_log.read_text(encoding="utf-8").splitlines() if "install" in line] + assert len(installs) == 2 and all("--require-hashes" in line for line in installs) + + +@pytest.mark.parametrize("shell", SHELLS) +def test_a_stamp_of_the_old_requirements_txt_reinstalls_from_the_lock(machine, shell): + """Before #245 the stamp hashed requirements.txt; an instance carrying one installs the + lock on its first run under the new stack.""" + machine.standard() + machine.existing_venv("3.13") + (machine.tools / ".venv" / ".chemenu-requirements.sha256").write_text( + hashlib.sha256(b"PyYAML\n").hexdigest() + "\n", encoding="utf-8") + assert machine.run(shell=shell).returncode == 0 + assert "requirements.lock" in machine.pip_log.read_text(encoding="utf-8") + + +@pytest.mark.parametrize("shell", SHELLS) +def test_a_venv_outside_the_span_is_built_again_on_the_python_found(machine, shell): + machine.standard() + old = machine.existing_venv("3.12") + (old.parent.parent / ".chemenu-requirements.sha256").write_text( + hashlib.sha256((machine.tools / "requirements.lock").read_bytes()).hexdigest() + "\n", encoding="utf-8") + result = machine.run(shell=shell) + assert result.returncode == 0, result.stdout + assert any(line.split()[:3] == ["REBUILD", "venv", "3.12"] for line in result.stdout.splitlines()) + probe = subprocess.run([str(old), "-c", "import sys"], capture_output=True, text=True, + env={"PATH": os.pathsep.join(str(d) for d in machine.path_dirs)}) + assert probe.stdout.splitlines()[0] == "3.13" + # --clear took the old stamp with it, so the lock went in again. + assert "requirements.lock" in machine.pip_log.read_text(encoding="utf-8") + + +@pytest.mark.parametrize("shell", SHELLS) +def test_a_venv_inside_the_span_stays_when_the_python_found_is_another_version(machine, shell): + machine.standard() + kept = machine.existing_venv("3.14") + before = kept.read_bytes() + result = machine.run(shell=shell) + assert result.returncode == 0, result.stdout + assert "REBUILD" not in result.stdout + assert kept.read_bytes() == before + + @pytest.mark.parametrize("shell", SHELLS) def test_invalid_set_path_writes_nothing(machine, shell): machine.standard() @@ -346,7 +522,7 @@ def _browser_lines(machine) -> list[str]: @pytest.mark.parametrize("shell", SHELLS) def test_without_with_browser_nothing_of_the_component_is_installed(machine, shell): machine.standard() - (machine.tools / "requirements-browser.txt").write_text("playwright\n", encoding="utf-8") + (machine.tools / "requirements-browser.lock").write_text("playwright\n", encoding="utf-8") result = machine.run(shell=shell) assert result.returncode == 0, result.stdout + result.stderr assert _browser_lines(machine) == [] @@ -356,19 +532,19 @@ def test_without_with_browser_nothing_of_the_component_is_installed(machine, she @pytest.mark.parametrize("shell", SHELLS) def test_with_browser_installs_the_component_into_the_venv_and_keeps_it(machine, shell): machine.standard() - (machine.tools / "requirements-browser.txt").write_text("playwright\n", encoding="utf-8") + (machine.tools / "requirements-browser.lock").write_text("playwright\n", encoding="utf-8") result = machine.run("--with", "browser", shell=shell) assert result.returncode == 0, result.stdout + result.stderr venv = machine.tools / ".venv" lines = _browser_lines(machine) - assert any("-r" in line and line.endswith("requirements-browser.txt") for line in lines) + assert any("-r" in line and line.endswith("requirements-browser.lock") for line in lines) assert f"playwright install chromium into {venv / 'ms-playwright'}" in lines assert any(line.split()[:2] == ["OK", "browser"] for line in result.stdout.splitlines()) assert (venv / ".chemenu-browser.sha256").is_file() # A later plain run keeps it, and reinstalls only when its requirements change. assert machine.run(shell=shell).returncode == 0 assert len(_browser_lines(machine)) == 2 - (machine.tools / "requirements-browser.txt").write_text("playwright>=2\n", encoding="utf-8") + (machine.tools / "requirements-browser.lock").write_text("playwright>=2\n", encoding="utf-8") result = machine.run(shell=shell) assert result.returncode == 0 and len(_browser_lines(machine)) == 4 assert "OK browser" in result.stdout @@ -378,7 +554,7 @@ def test_with_browser_installs_the_component_into_the_venv_and_keeps_it(machine, @pytest.mark.parametrize("failing", ["FAKE_BROWSER_PIP_FAIL", "FAKE_PLAYWRIGHT_FAIL"]) def test_a_component_that_fails_stops_but_leaves_wikitool_working(machine, shell, failing): machine.standard() - (machine.tools / "requirements-browser.txt").write_text("playwright\n", encoding="utf-8") + (machine.tools / "requirements-browser.lock").write_text("playwright\n", encoding="utf-8") machine.extra_env[failing] = "1" result = machine.run("--with=browser", shell=shell) assert result.returncode == 42 @@ -514,7 +690,7 @@ def build_release(base: Path, *, limit: int | None = None, tops: tuple[str, ...] (stage / top / "tools").mkdir(parents=True) for file in STACK_FILES: shutil.copy2(TOOLS / file, stage / top / "tools" / file) - (stage / top / "tools" / "requirements.txt").write_text("PyYAML\n", encoding="utf-8") + (stage / top / "tools" / "requirements.lock").write_text("pyyaml==6.0.3 --hash=sha256:00\n", encoding="utf-8") if limit is not None: manifest = stage / top / "tools" / "prerequisites.txt" manifest.write_text( @@ -725,7 +901,7 @@ def test_set_and_the_exit_code_pass_through_to_the_tree_copy(asset, shell): # moment; with :partial each failed attempt has already moved one file of the entry up, # which is what a move that falls back to copying and deleting leaves behind. -ARCHIVED_TOOLS = sorted((*STACK_FILES, "requirements.txt")) +ARCHIVED_TOOLS = sorted((*STACK_FILES, "requirements.lock")) MOVE_ATTEMPTS = 8 diff --git a/tools/chemenu/tests/test_preflight_pwsh.py b/tools/chemenu/tests/test_preflight_pwsh.py index 39b567a..1571058 100644 --- a/tools/chemenu/tests/test_preflight_pwsh.py +++ b/tools/chemenu/tests/test_preflight_pwsh.py @@ -142,6 +142,86 @@ def test_python_too_old_stops(machine): assert_guidance(result.stdout, "Python 3.9 is too old") +# --- the Python span and the lock (Gitea #245) --------------------------------------- + + +@pytest.mark.parametrize("version, status", [("3.12", "TOO_OLD"), ("3.13", "OK"), + ("3.14", "OK"), ("3.15", "TOO_NEW")]) +def test_both_ends_of_the_span_are_inclusive_and_only_they(machine, version, status): + machine.extra_env["FAKE_PY_VERSION"] = version + result = _preflight(machine) + assert any(line.split()[:2] == [status, "python"] for line in result.stdout.splitlines()), result.stdout + if status == "OK": + assert result.returncode == 0, result.stdout + return + assert result.returncode == 42 + word = "old" if status == "TOO_OLD" else "new" + assert_guidance(result.stdout, f"Python {version} is too {word} - this stack needs Python 3.13 to 3.14", + "--set python=") + + +@pytest.mark.parametrize("default", ["3.12", "3.15"]) +def test_a_versioned_python_of_the_span_is_taken_when_the_plain_one_lies_outside(machine, default): + machine.python("python3", version=default) + versioned = machine.python("python3.13", version="3.13", where=machine.base / "elsewhere") + machine.path_dirs.append(versioned.parent) + result = _preflight(machine) + assert result.returncode == 0, result.stdout + assert machine.recorded()["tools"]["python"] == str(versioned) + + +def test_on_windows_the_launcher_is_asked_for_a_version_of_the_span(tmp_path): + machine = Machine(tmp_path.resolve()).standard(pwsh=True) + machine.extra_env.update(WINDOWS, FAKE_PY_VERSION="3.15") + installed = machine.py_launcher("3.15", ("3.13", "3.14")) + result = _preflight(machine) + assert result.returncode == 0, result.stdout + assert machine.recorded()["tools"]["python"] == str(installed["3.14"]) + + +def test_on_linux_an_out_of_span_python_names_the_distribution_and_set_but_no_other_tool(machine): + machine.stub("apt-get", "#!/bin/sh\nexit 0\n") + machine.extra_env.update(CHEMENU_PREFLIGHT_PLATFORM="linux", FAKE_PY_VERSION="3.15") + result = _preflight(machine) + assert result.returncode == 42 + assert_guidance(result.stdout, "sudo apt install python3 python3-venv", + "package source of this Linux distribution may offer no Python 3.13 to 3.14", + "--set python=") + fix = result.stdout.split("Fix:", 1)[1] + for other in ("uv ", "pyenv", "deadsnakes", "conda", "ppa:"): + assert other not in fix + + +def test_the_venv_installs_the_lock_with_hashes_required_and_follows_a_changed_one(machine): + assert _preflight(machine).returncode == 0 + assert _preflight(machine).returncode == 0 + (machine.tools / "requirements.lock").write_text("pyyaml==6.0.2 --hash=sha256:11\n", encoding="utf-8") + assert _preflight(machine).returncode == 0 + installs = [line for line in machine.pip_log.read_text(encoding="utf-8").splitlines() if "install" in line] + assert len(installs) == 2 + assert all("--require-hashes" in line.split() and line.endswith("requirements.lock") for line in installs) + + +def test_a_venv_outside_the_span_is_built_again_on_the_python_found(machine): + old = machine.existing_venv("3.12") + result = _preflight(machine) + assert result.returncode == 0, result.stdout + assert any(line.split()[:3] == ["REBUILD", "venv", "3.12"] for line in result.stdout.splitlines()) + probe = subprocess.run([str(old), "-c", "import sys"], capture_output=True, text=True, + env={"PATH": os.pathsep.join(str(d) for d in machine.path_dirs)}) + assert probe.stdout.splitlines()[0] == "3.13" + assert "requirements.lock" in machine.pip_log.read_text(encoding="utf-8") + + +def test_a_venv_inside_the_span_stays_when_the_python_found_is_another_version(machine): + kept = machine.existing_venv("3.14") + before = kept.read_bytes() + result = _preflight(machine) + assert result.returncode == 0, result.stdout + assert "REBUILD" not in result.stdout + assert kept.read_bytes() == before + + def test_invalid_set_path_writes_nothing(machine): result = _preflight(machine, "--set", f"rg={machine.base / 'nowhere' / 'rg'}") assert result.returncode == 42 @@ -191,7 +271,7 @@ def _browser_lines(machine: Machine) -> list[str]: def test_with_browser_installs_the_component_and_a_plain_run_keeps_it(machine): - (machine.tools / "requirements-browser.txt").write_text("playwright\n", encoding="utf-8") + (machine.tools / "requirements-browser.lock").write_text("playwright\n", encoding="utf-8") assert _preflight(machine).returncode == 0 assert _browser_lines(machine) == [] result = _preflight(machine, "--with", "browser") @@ -205,7 +285,7 @@ def test_with_browser_installs_the_component_and_a_plain_run_keeps_it(machine): @pytest.mark.parametrize("failing", ["FAKE_BROWSER_PIP_FAIL", "FAKE_PLAYWRIGHT_FAIL"]) def test_a_component_that_fails_stops_but_leaves_wikitool_working(machine, failing): - (machine.tools / "requirements-browser.txt").write_text("playwright\n", encoding="utf-8") + (machine.tools / "requirements-browser.lock").write_text("playwright\n", encoding="utf-8") machine.extra_env[failing] = "1" result = _preflight(machine, "--with=browser") assert result.returncode == 42 diff --git a/tools/lock_requirements.py b/tools/lock_requirements.py new file mode 100644 index 0000000..1ba9ad4 --- /dev/null +++ b/tools/lock_requirements.py @@ -0,0 +1,158 @@ +"""Write the four lock files of tools/ from their source files - dev-only. + + python3 tools/lock_requirements.py regenerate tools/*.lock + python3 tools/lock_requirements.py --out write them into instead + python3 tools/lock_requirements.py --exception = + a security lift (see below) + +Each `tools/requirements*.txt` names what the stack needs with lower bounds; its +`.lock` beside it names exact versions and SHA-256 hashes for everything that +resolves from it, transitive packages included. The preflight and CI install only +from the locks, with `pip install --require-hashes`. This script is the one way +a lock is written; the procedure around it - when to run it, the security lift, +how the result is checked - is instructions/dev/dependency-locks.md. + +What every run does: + +- resolves with `uv pip compile --universal --generate-hashes` (one file for + Linux, macOS and Windows), for the Python minimum in tools/prerequisites.txt; +- leaves out every file uploaded in the last COOLDOWN_DAYS days + (`--exclude-newer`): a compromised release is usually found and pulled within + hours to days, and a lock never takes one before that has had time to happen; +- resolves the locks in a chain, each constrained by the ones before it, so a + package that sits in two locks has the same version in both - all four end up + in one venv, and a later lock must not move a package an earlier one placed; +- carries every `--exclude-newer-package` exception from the current locks' + headers over while its timestamp is still inside the cooldown, and drops it + once the global cutoff has passed it. `--exception` adds a new one. + +Needs `uv` on PATH (requirements-dev.lock carries it). An instance never runs +this: it ships no source of truth to resolve against, only the locks. +""" +from __future__ import annotations + +import argparse +import re +import shutil +import subprocess +import sys +from datetime import datetime, timedelta, timezone +from pathlib import Path + +TOOLS = Path(__file__).resolve().parent +ROOT = TOOLS.parent +COOLDOWN_DAYS = 7 + +# Source file -> lock file, in the order they are resolved: each one is +# constrained by every lock above it. +CHAIN = ( + ("requirements.txt", "requirements.lock"), + ("requirements-mcp.txt", "requirements-mcp.lock"), + ("requirements-browser.txt", "requirements-browser.lock"), + ("requirements-dev.txt", "requirements-dev.lock"), +) + +EXCEPTION_RE = re.compile(r"--exclude-newer-package[ =]([A-Za-z0-9._-]+)=(\S+)") +CUTOFF_RE = re.compile(r"--exclude-newer[ =](\S+)") + + +def timestamp(moment: datetime) -> str: + return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def parse_timestamp(text: str) -> datetime: + return datetime.fromisoformat(text.replace("Z", "+00:00")).astimezone(timezone.utc) + + +def header(lock: Path) -> str: + """The command uv wrote into the lock's head, or '' for a missing file.""" + if not lock.is_file(): + return "" + lines = [] + for line in lock.read_text(encoding="utf-8").splitlines(): + if not line.startswith("#"): + break + lines.append(line) + return "\n".join(lines) + + +def cutoff_of(lock: Path) -> datetime | None: + found = CUTOFF_RE.search(header(lock)) + return parse_timestamp(found.group(1)) if found else None + + +def exceptions_of(lock: Path) -> dict[str, datetime]: + return {name: parse_timestamp(stamp) for name, stamp in EXCEPTION_RE.findall(header(lock))} + + +def python_minimum() -> str: + for line in (TOOLS / "prerequisites.txt").read_text(encoding="utf-8").splitlines(): + fields = line.split("|") + if fields[:2] == ["tool", "python"]: + return fields[2] + raise SystemExit("lock_requirements: tools/prerequisites.txt has no python line") + + +def carried_exceptions(cutoff: datetime) -> dict[str, datetime]: + """Exceptions in the current locks still younger than the cutoff - the ones + without which the next resolution would fail rather than lower the package.""" + carried: dict[str, datetime] = {} + for _, lock in CHAIN: + for name, stamp in exceptions_of(TOOLS / lock).items(): + if stamp > cutoff: + carried[name] = max(stamp, carried.get(name, stamp)) + return carried + + +def relative(path: Path) -> str: + try: + return path.relative_to(ROOT).as_posix() + except ValueError: + return str(path) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n", 1)[0]) + parser.add_argument("--out", type=Path, help="write the locks here instead of tools/") + parser.add_argument("--exception", action="append", default=[], metavar="NAME=TIMESTAMP", + help="exempt one package from the cooldown up to TIMESTAMP (a security lift)") + args = parser.parse_args(argv) + + uv = shutil.which("uv") + if not uv: + print("lock_requirements: uv is not on PATH - install tools/requirements-dev.lock, " + "or put uv on PATH another way", file=sys.stderr) + return 1 + + cutoff = datetime.now(timezone.utc).replace(microsecond=0) - timedelta(days=COOLDOWN_DAYS) + exceptions = carried_exceptions(cutoff) + for entry in args.exception: + name, sep, stamp = entry.partition("=") + if not sep or not name: + parser.error(f"--exception wants NAME=TIMESTAMP, got {entry!r}") + exceptions[name.lower()] = parse_timestamp(stamp) + + out = (args.out or TOOLS).resolve() + out.mkdir(parents=True, exist_ok=True) + done: list[Path] = [] + for source, lock in CHAIN: + target = out / lock + command = [uv, "pip", "compile", relative(TOOLS / source)] + for previous in done: + command += ["-c", relative(previous)] + command += ["--universal", "--generate-hashes", "--python-version", python_minimum(), + "--exclude-newer", timestamp(cutoff)] + for name in sorted(exceptions): + command += ["--exclude-newer-package", f"{name}={timestamp(exceptions[name])}"] + command += ["--no-config", "--quiet", "-o", relative(target)] + result = subprocess.run(command, cwd=ROOT) + if result.returncode != 0: + print(f"lock_requirements: resolving {source} failed - see uv's message above", file=sys.stderr) + return result.returncode + done.append(target) + print(f"wrote {relative(target)}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/preflight.ps1 b/tools/preflight.ps1 index 86d3bcc..a3111e3 100644 --- a/tools/preflight.ps1 +++ b/tools/preflight.ps1 @@ -6,10 +6,15 @@ # pwsh -NoProfile -ExecutionPolicy Bypass -File tools/preflight.ps1 --set rg=C:\Tools\rg.exe # pwsh -NoProfile -ExecutionPolicy Bypass -File tools/preflight.ps1 --with browser # -# --with browser installs tools/requirements-browser.txt into tools/.venv and the +# tools/.venv gets exactly the versions tools/requirements.lock names, checked against +# the hashes in it (pip --require-hashes); whenever the lock changes, the next run moves +# the venv to it, up or down. A venv built on a Python outside the span the manifest +# admits is built again on the Python found here. +# +# --with browser installs tools/requirements-browser.lock into tools/.venv and the # Chromium that Playwright drives into tools/.venv/ms-playwright - only on request, # because it is a large download that only `raw login` and pages a site handler -# declares `render` need. Once installed, every later run keeps it up to date. +# declares `render` need. Once installed, every later run keeps it at its lock. # # As the release asset `preflight.ps1` - a copy with no tools/prerequisites.txt next # to it - the script is the first install step instead: it downloads the stack @@ -61,9 +66,9 @@ $Root = Split-Path -Parent $Dir $Manifest = Join-Path $Dir 'prerequisites.txt' $ToolsFile = Join-Path $Root '.wikitool-tools.json' $Venv = Join-Path $Dir '.venv' -$Requirements = Join-Path $Dir 'requirements.txt' +$Requirements = Join-Path $Dir 'requirements.lock' $Stamp = Join-Path $Venv '.chemenu-requirements.sha256' -$BrowserRequirements = Join-Path $Dir 'requirements-browser.txt' +$BrowserRequirements = Join-Path $Dir 'requirements-browser.lock' $BrowserStamp = Join-Path $Venv '.chemenu-browser.sha256' $Browsers = Join-Path $Venv 'ms-playwright' $Self = 'pwsh -NoProfile -ExecutionPolicy Bypass -File tools/preflight.ps1' @@ -564,7 +569,7 @@ foreach ($line in $ManifestLines) { Write-ErrorLine "preflight: bad tool name '$($parts[1])' in $Manifest" exit 1 } - if ($parts[3] -eq 'all' -or $parts[3] -eq $Platform) { + if ($parts[4] -eq 'all' -or $parts[4] -eq $Platform) { $Tools += $parts[1] } } @@ -585,11 +590,11 @@ foreach ($line in $ManifestLines) { function Get-InstallHint { param([string]$Tool) - $choco = Get-ManifestField 'tool' $Tool 7 - $winget = Get-ManifestField 'tool' $Tool 8 - $brew = Get-ManifestField 'tool' $Tool 9 - $apt = Get-ManifestField 'tool' $Tool 10 - $pacman = Get-ManifestField 'tool' $Tool 11 + $choco = Get-ManifestField 'tool' $Tool 8 + $winget = Get-ManifestField 'tool' $Tool 9 + $brew = Get-ManifestField 'tool' $Tool 10 + $apt = Get-ManifestField 'tool' $Tool 11 + $pacman = Get-ManifestField 'tool' $Tool 12 $hint = '' switch ($Platform) { 'windows' { @@ -752,10 +757,27 @@ foreach ($name in $Sets.Keys) { $script:Py = '' $script:PyVersion = '' -$script:PyOld = $null +$script:PyOut = $null $PyMin = Get-ManifestField 'tool' 'python' 3 +$PyMax = Get-ManifestField 'tool' 'python' 4 -# Sets Py/PyVersion on success, PyOld when the version is too old. +# Whether major.minor lies in the span the manifest admits, both ends inclusive. +function Test-PythonAdmitted { + param([string]$Version) + if (-not (Test-VersionGe $Version $PyMin)) { + return $false + } + return ($PyMax -eq '-' -or (Test-VersionGe $PyMax $Version)) +} + +# The span in words, for every message that names it. +if ($PyMax -eq '-') { + $PySpan = "$PyMin or newer" +} else { + $PySpan = "$PyMin to $PyMax" +} + +# Sets Py/PyVersion on success, PyOut when the version lies outside the span. function Test-PythonCandidate { param([string]$Path, [string[]]$Extra = @()) $out = Invoke-Native -Path $Path -Arguments ($Extra + @('-c', $PyProbe)) @@ -771,12 +793,14 @@ function Test-PythonCandidate { if (-not $version -or -not $executable) { return $false } - if (Test-VersionGe $version $PyMin) { + if (Test-PythonAdmitted $version) { $script:Py = $executable $script:PyVersion = $version return $true } - $script:PyOld = @{ Version = $version; Path = $Path } + if (-not $script:PyOut) { + $script:PyOut = @{ Version = $version; Path = $Path } + } return $false } @@ -789,12 +813,33 @@ function Get-PythonExtra { return @() } +# The versioned interpreters of the span, newest first - python3.14 python3.13 - so a +# machine whose plain python lies outside the span, with one inside it beside, is not +# turned away. On Windows the launcher's py -3.14 py -3.13 come before each. +function Get-VersionedCandidate { + if ($PyMax -eq '-') { + return @() + } + $major = $PyMin.Split('.')[0] + if ($PyMax.Split('.')[0] -ne $major) { + return @() + } + $candidates = @() + for ($minor = [int]$PyMax.Split('.')[1]; $minor -ge [int]$PyMin.Split('.')[1]; $minor--) { + if ($Platform -eq 'windows') { + $candidates += , @('py', @("-$major.$minor")) + } + $candidates += , @("python$major.$minor", @()) + } + return $candidates +} + $given = Get-SetValue 'python' if ($given) { if (-not (Test-Usable $given) -or -not (Test-PythonCandidate $given (Get-PythonExtra $given))) { Add-Problem "The path given for Python does not work: $given" ` - "every wikitool command runs on Python $PyMin or newer, and this path did not start one" ` - "Check the path - it has to be the python executable itself, version $PyMin or newer.`nThen run: $Self --set python=" + "every wikitool command runs on Python $PySpan, and this path did not start one" ` + "Check the path - it has to be the python executable itself, version $PySpan.`nThen run: $Self --set python=" $script:BadSet = $true } } else { @@ -808,6 +853,7 @@ if ($given) { } else { $order = @(@('python3', @()), @('python', @())) } + $order += Get-VersionedCandidate foreach ($candidate in $order) { foreach ($path in (Find-OnPath $candidate[0])) { if (Test-PythonCandidate $path $candidate[1]) { @@ -835,16 +881,30 @@ if ($script:Py) { Add-Report 'OK' 'python' $script:PyVersion $script:Py $Found['python'] = $script:Py } elseif (-not $script:BadSet) { - $label = Get-ManifestField 'tool' 'python' 5 - $why = Get-ManifestField 'tool' 'python' 6 - if ($script:PyOld) { - Add-Report 'TOO_OLD' 'python' $script:PyOld.Version $script:PyOld.Path - Add-Problem "$label $($script:PyOld.Version) is too old - this stack needs $PyMin or newer." $why ` - "$(Get-InstallHint 'python')`nOr, if a newer one is already installed, give its full path:`n$Self --set python=" + $label = Get-ManifestField 'tool' 'python' 6 + $why = Get-ManifestField 'tool' 'python' 7 + # On Linux the fix is the distribution's own package, which may hold no Python of + # the span at all (Debian 12 has 3.11, Ubuntu 24.04 3.12); then the only way is a + # Python installed some other way, named with --set. No other tool is suggested. + $distro = '' + if ($Platform -eq 'linux') { + $distro = "`nThe package source of this Linux distribution may offer no Python $PySpan -`nthen that command installs one outside the span, and a Python $PySpan`ninstalled another way has to be named with --set (below)." + } + if ($script:PyOut) { + if (Test-VersionGe $script:PyOut.Version $PyMin) { + $status = 'TOO_NEW' + $adjective = 'new' + } else { + $status = 'TOO_OLD' + $adjective = 'old' + } + Add-Report $status 'python' $script:PyOut.Version $script:PyOut.Path + Add-Problem "$label $($script:PyOut.Version) is too $adjective - this stack needs Python $PySpan." $why ` + "$(Get-InstallHint 'python')$distro`nOr, if a Python $PySpan is already installed, give its full path:`n$Self --set python=" } else { Add-Report 'MISSING' 'python' '-' '-' - Add-Problem "$label $PyMin or newer was not found." $why ` - "$(Get-InstallHint 'python')`nOr, if it is installed somewhere this check did not look, give its full path:`n$Self --set python=" + Add-Problem "$label $PySpan was not found." $why ` + "$(Get-InstallHint 'python')$distro`nOr, if it is installed somewhere this check did not look, give its full path:`n$Self --set python=" } } @@ -852,8 +912,8 @@ foreach ($tool in $Tools) { if ($tool -eq 'python') { continue } - $label = Get-ManifestField 'tool' $tool 5 - $why = Get-ManifestField 'tool' $tool 6 + $label = Get-ManifestField 'tool' $tool 6 + $why = Get-ManifestField 'tool' $tool 7 $minimum = Get-ManifestField 'tool' $tool 3 $given = Get-SetValue $tool $path = '' @@ -1066,8 +1126,24 @@ function Get-LastLine { return ((($Text -split "`n") | Select-Object -Last 5 | ForEach-Object { " $_" }) -join "`n") } +# A venv keeps the Python it was created with, whatever the search above found. One +# outside the span - an instance set up under an older stack - is built again on $Py; +# `--clear` takes the stamps with it, so the install below runs. A venv inside the span +# stays, even when $Py is another version of it. $venvPython = Get-VenvPython +$rebuild = $false if (-not $venvPython -or $null -eq (Invoke-Native -Path $venvPython -Arguments @('-m', 'pip', '--version'))) { + $rebuild = $true +} else { + $probe = Invoke-Native -Path $venvPython -Arguments @('-c', $PyProbe) + $venvVersion = if ($probe) { ($probe -split "`n")[0].Trim() } else { '' } + if (-not $venvVersion -or -not (Test-PythonAdmitted $venvVersion)) { + $rebuild = $true + $shown = if ($venvVersion) { $venvVersion } else { '-' } + Write-Line ('REBUILD venv {0,-8} Python {0} is outside {1} - building tools/.venv again on {2}' -f $shown, $PySpan, $script:PyVersion) + } +} +if ($rebuild) { $created = Invoke-NativeVerbose -Path $script:Py -Arguments @('-m', 'venv', '--clear', $Venv) $venvPython = Get-VenvPython if ($created.Code -ne 0 -or -not $venvPython) { @@ -1088,7 +1164,7 @@ if (Test-Path -LiteralPath $Stamp -PathType Leaf) { $have = (Get-Content -Raw -LiteralPath $Stamp).Trim() } if ($want -ne $have) { - $installed = Invoke-NativeVerbose -Path $venvPython -Arguments @('-m', 'pip', 'install', '--disable-pip-version-check', '--quiet', '-r', $Requirements) + $installed = Invoke-NativeVerbose -Path $venvPython -Arguments @('-m', 'pip', 'install', '--disable-pip-version-check', '--quiet', '--require-hashes', '-r', $Requirements) if ($installed.Code -ne 0) { Add-Problem 'The libraries wikitool needs could not be installed into tools/.venv.' ` 'they are downloaded once from the internet; without them no wikitool command starts' ` @@ -1123,7 +1199,7 @@ if ($With -eq 'browser' -or (Test-Path -LiteralPath $BrowserStamp -PathType Leaf $have = (Get-Content -Raw -LiteralPath $BrowserStamp).Trim() } if ($want -ne $have -or -not (Test-Browser)) { - $installed = Invoke-NativeVerbose -Path $venvPython -Arguments @('-m', 'pip', 'install', '--disable-pip-version-check', '--quiet', '-r', $BrowserRequirements) + $installed = Invoke-NativeVerbose -Path $venvPython -Arguments @('-m', 'pip', 'install', '--disable-pip-version-check', '--quiet', '--require-hashes', '-r', $BrowserRequirements) if ($installed.Code -ne 0) { Add-Problem 'The optional browser component could not be installed into tools/.venv.' ` 'only raw login and pages a site handler fetches through a browser need it; everything else works without it' ` diff --git a/tools/preflight.sh b/tools/preflight.sh index 512b625..f0733d6 100755 --- a/tools/preflight.sh +++ b/tools/preflight.sh @@ -6,10 +6,15 @@ # tools/preflight.sh --set rg=/opt/rg/rg use a path the user named # tools/preflight.sh --with browser also install the optional browser component # -# --with browser installs tools/requirements-browser.txt into tools/.venv and the +# tools/.venv gets exactly the versions tools/requirements.lock names, checked against +# the hashes in it (pip --require-hashes); whenever the lock changes, the next run moves +# the venv to it, up or down. A venv built on a Python outside the span the manifest +# admits is built again on the Python found here. +# +# --with browser installs tools/requirements-browser.lock into tools/.venv and the # Chromium that Playwright drives into tools/.venv/ms-playwright - only on request, # because it is a large download that only `raw login` and pages a site handler -# declares `render` need. Once installed, every later run keeps it up to date. +# declares `render` need. Once installed, every later run keeps it at its lock. # # As the release asset `preflight.sh` - a copy with no tools/prerequisites.txt next # to it - the script is the first install step instead: it downloads the stack @@ -52,9 +57,9 @@ ROOT=$(dirname -- "$DIR") MANIFEST="$DIR/prerequisites.txt" TOOLS_FILE="$ROOT/.wikitool-tools.json" VENV="$DIR/.venv" -REQUIREMENTS="$DIR/requirements.txt" +REQUIREMENTS="$DIR/requirements.lock" STAMP="$VENV/.chemenu-requirements.sha256" -BROWSER_REQUIREMENTS="$DIR/requirements-browser.txt" +BROWSER_REQUIREMENTS="$DIR/requirements-browser.lock" BROWSER_STAMP="$VENV/.chemenu-browser.sha256" BROWSERS="$VENV/ms-playwright" SELF="tools/preflight.sh" @@ -475,7 +480,7 @@ manifest_field() { # } TOOLS="" -while IFS='|' read -r kind name minimum platforms rest; do +while IFS='|' read -r kind name minimum maximum platforms rest; do case "$kind" in ''|'#'*) continue ;; esac [ "$kind" = tool ] || continue case "$name" in *[!a-z0-9]*|'') echo "preflight: bad tool name '$name' in $MANIFEST" >&2; exit 1 ;; esac @@ -494,11 +499,11 @@ done < "$MANIFEST" # The install command for this machine's package manager, or every known one. install_hint() { # - choco=$(manifest_field tool "$1" 7) - winget=$(manifest_field tool "$1" 8) - brew=$(manifest_field tool "$1" 9) - apt=$(manifest_field tool "$1" 10) - pacman=$(manifest_field tool "$1" 11) + choco=$(manifest_field tool "$1" 8) + winget=$(manifest_field tool "$1" 9) + brew=$(manifest_field tool "$1" 10) + apt=$(manifest_field tool "$1" 11) + pacman=$(manifest_field tool "$1" 12) hint="" case "$PLATFORM" in windows) @@ -606,19 +611,33 @@ done # --- python ------------------------------------------------------------------------- -PY="" PY_VERSION="" PY_OLD="" +PY="" PY_VERSION="" PY_OUT="" PY_MIN=$(manifest_field tool python 3) +PY_MAX=$(manifest_field tool python 4) -try_python() { # [extra] -> sets PY/PY_VERSION on success, PY_OLD when too old +# Whether major.minor lies in the span the manifest admits, both ends inclusive. +py_admitted() { # + version_ge "$1" "$PY_MIN" || return 1 + [ "$PY_MAX" = - ] || version_ge "$PY_MAX" "$1" +} + +# The span in words, for every message that names it. +if [ "$PY_MAX" = - ]; then + PY_SPAN="$PY_MIN or newer" +else + PY_SPAN="$PY_MIN to $PY_MAX" +fi + +try_python() { # [extra] -> sets PY/PY_VERSION on success, PY_OUT when outside the span out=$(probe_python "$@") || return 1 version=$(printf '%s\n' "$out" | sed -n 1p) executable=$(printf '%s\n' "$out" | sed -n 2p) [ -n "$version" ] && [ -n "$executable" ] || return 1 - if version_ge "$version" "$PY_MIN"; then + if py_admitted "$version"; then PY=$executable PY_VERSION=$version return 0 fi - PY_OLD="$version $1" + [ -n "$PY_OUT" ] || PY_OUT="$version $1" return 1 } @@ -626,13 +645,30 @@ python_extra() { # py and py.exe are the launcher: they need -3 case "${1##*/}" in py|py.exe) printf '%s\n' -3 ;; esac } +# The versioned interpreters of the span, newest first - python3.14 python3.13 - so a +# machine whose plain python3 lies outside the span, with one inside it beside, is not +# turned away. On Windows the launcher's py -3.14 py -3.13 come before each. +versioned_candidates() { + [ "$PY_MAX" != - ] || return 0 + major=${PY_MIN%%.*} + [ "${PY_MAX%%.*}" = "$major" ] || return 0 + minor=${PY_MAX#*.} + while [ "$minor" -ge "${PY_MIN#*.}" ]; do + if [ "$PLATFORM" = windows ]; then + printf 'py:-%s.%s ' "$major" "$minor" + fi + printf 'python%s.%s: ' "$major" "$minor" + minor=$((minor - 1)) + done +} + given=$(set_value python) if [ -n "$given" ]; then extra=$(python_extra "$given") if ! usable "$given" || ! try_python "$given" $extra; then problem "The path given for Python does not work: $given" \ - "every wikitool command runs on Python $PY_MIN or newer, and this path did not start one" \ - "Check the path - it has to be the python executable itself, version $PY_MIN or newer. + "every wikitool command runs on Python $PY_SPAN, and this path did not start one" \ + "Check the path - it has to be the python executable itself, version $PY_SPAN. Then run: $SELF --set python=" BAD_SET=1 fi @@ -643,9 +679,9 @@ else fi if [ -z "$PY" ]; then if [ "$PLATFORM" = windows ]; then - order="python: py:-3 python3:" + order="python: py:-3 python3: $(versioned_candidates)" else - order="python3: python:" + order="python3: python: $(versioned_candidates)" fi for candidate in $order; do name=${candidate%%:*} @@ -679,18 +715,34 @@ if [ -n "$PY" ]; then report OK python "$PY_VERSION" "$PY" eval "FOUND_python=\$PY" elif [ "$BAD_SET" -eq 0 ]; then - label=$(manifest_field tool python 5) - why=$(manifest_field tool python 6) - if [ -n "$PY_OLD" ]; then - report TOO_OLD python "${PY_OLD%% *}" "${PY_OLD#* }" - problem "$label ${PY_OLD%% *} is too old - this stack needs $PY_MIN or newer." "$why" \ - "$(install_hint python) -Or, if a newer one is already installed, give its full path: + label=$(manifest_field tool python 6) + why=$(manifest_field tool python 7) + # On Linux the fix is the distribution's own package, which may hold no Python of + # the span at all (Debian 12 has 3.11, Ubuntu 24.04 3.12); then the only way is a + # Python installed some other way, named with --set. No other tool is suggested. + distro="" + if [ "$PLATFORM" = linux ]; then + distro=" +The package source of this Linux distribution may offer no Python $PY_SPAN - +then that command installs one outside the span, and a Python $PY_SPAN +installed another way has to be named with --set (below)." + fi + if [ -n "$PY_OUT" ]; then + out_version=${PY_OUT%% *} + if version_ge "$out_version" "$PY_MIN"; then + status=TOO_NEW adjective=new + else + status=TOO_OLD adjective=old + fi + report "$status" python "$out_version" "${PY_OUT#* }" + problem "$label $out_version is too $adjective - this stack needs Python $PY_SPAN." "$why" \ + "$(install_hint python)$distro +Or, if a Python $PY_SPAN is already installed, give its full path: $SELF --set python=" else report MISSING python - - - problem "$label $PY_MIN or newer was not found." "$why" \ - "$(install_hint python) + problem "$label $PY_SPAN was not found." "$why" \ + "$(install_hint python)$distro Or, if it is installed somewhere this check did not look, give its full path: $SELF --set python=" fi @@ -698,8 +750,8 @@ fi for tool in $TOOLS; do [ "$tool" = python ] && continue - label=$(manifest_field tool "$tool" 5) - why=$(manifest_field tool "$tool" 6) + label=$(manifest_field tool "$tool" 6) + why=$(manifest_field tool "$tool" 7) minimum=$(manifest_field tool "$tool" 3) given=$(set_value "$tool") path="" @@ -837,8 +889,23 @@ last_lines() { printf '%s\n' "$1" | tail -n 5 | sed 's/^/ /' } +# A venv keeps the Python it was created with, whatever the search above found. One +# outside the span - an instance set up under an older stack - is built again on $PY; +# `--clear` takes the stamps with it, so the install below runs. A venv inside the span +# stays, even when $PY is another version of it. VPY=$(venv_python) || VPY="" +rebuild="" if [ -z "$VPY" ] || ! "$VPY" -m pip --version >/dev/null 2>&1; then + rebuild=1 +else + venv_version=$(probe_python "$VPY" | sed -n 1p) + if [ -z "$venv_version" ] || ! py_admitted "$venv_version"; then + rebuild=1 + printf 'REBUILD venv %-8s Python %s is outside %s - building tools/.venv again on %s\n' \ + "${venv_version:--}" "${venv_version:-of unknown version}" "$PY_SPAN" "$PY_VERSION" + fi +fi +if [ -n "$rebuild" ]; then if ! output=$("$PY" -m venv --clear "$VENV" 2>&1) || ! VPY=$(venv_python); then fix="Python said: $(last_lines "$output")" @@ -857,7 +924,7 @@ want=$("$VPY" -c 'import hashlib, sys; print(hashlib.sha256(open(sys.argv[1], "r "$REQUIREMENTS" 2>/dev/null | tr -d '\r') have=$(cat "$STAMP" 2>/dev/null) || have="" if [ -z "$want" ] || [ "$want" != "$have" ]; then - if ! output=$("$VPY" -m pip install --disable-pip-version-check --quiet -r "$REQUIREMENTS" 2>&1); then + if ! output=$("$VPY" -m pip install --disable-pip-version-check --quiet --require-hashes -r "$REQUIREMENTS" 2>&1); then problem "The libraries wikitool needs could not be installed into tools/.venv." \ "they are downloaded once from the internet; without them no wikitool command starts" \ "Check that this computer can reach the internet (a proxy or a security program can block it; if so, ask whoever looks after this computer). @@ -891,7 +958,7 @@ if [ "$WITH" = browser ] || [ -f "$BROWSER_STAMP" ]; then "$BROWSER_REQUIREMENTS" 2>/dev/null | tr -d '\r') have=$(cat "$BROWSER_STAMP" 2>/dev/null) || have="" if [ -z "$want" ] || [ "$want" != "$have" ] || ! has_browser; then - if ! output=$("$VPY" -m pip install --disable-pip-version-check --quiet -r "$BROWSER_REQUIREMENTS" 2>&1); then + if ! output=$("$VPY" -m pip install --disable-pip-version-check --quiet --require-hashes -r "$BROWSER_REQUIREMENTS" 2>&1); then problem "The optional browser component could not be installed into tools/.venv." \ "only raw login and pages a site handler fetches through a browser need it; everything else works without it" \ "Check that this computer can reach the internet (a proxy or a security program can block it; if so, ask whoever looks after this computer), then run: $SELF --with browser diff --git a/tools/prerequisites.txt b/tools/prerequisites.txt index 52224ea..83a1c11 100644 --- a/tools/prerequisites.txt +++ b/tools/prerequisites.txt @@ -5,11 +5,15 @@ # Line format, fields separated by `|` so a POSIX shell reads it with `IFS='|' read`: # # limit|| -# tool||||