diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 712e0652..3dd931ac 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -20,11 +20,16 @@ jobs:
if: >-
github.event_name == 'push' &&
github.ref == 'refs/heads/codex/thesis-ledger-facts'
- # Runs in the repo's hash-locked env: the verifier may import
- # packaged dependencies (receipt) once the consumption shims land.
+ # Runs in the repo's hash-locked env: the verifier imports the
+ # packaged receipt. The env does not install this project, so the
+ # checkout's root is not on sys.path, and `python -I` keeps scripts/
+ # off it too: no other module in either can stand in for one the
+ # verifier imports. It loads scripts/receipt_pins.py by path.
+ # `uv run --no-sync` keeps uv from installing the project again;
+ # the steps below install it for the tests.
run: |
- uv sync --locked --no-dev
- uv run --locked --no-dev python scripts/verify_release_chain.py --full
+ uv sync --locked --no-dev --no-install-project
+ uv run --no-sync python -I scripts/verify_release_chain.py --full
- name: Set up Python
uses: actions/setup-python@v5
diff --git a/.github/workflows/thesis-facts-append.yml b/.github/workflows/thesis-facts-append.yml
index a7c45cc1..f18ee50f 100644
--- a/.github/workflows/thesis-facts-append.yml
+++ b/.github/workflows/thesis-facts-append.yml
@@ -92,14 +92,62 @@ jobs:
git clone --no-checkout "$repository_url" "$base_gate"
git -C "$base_gate" fetch --no-tags origin "$BASE_SHA"
- git -C "$base_gate" checkout --detach "$BASE_SHA"
+ # Check the base gate out with an empty attribute tree, so the files
+ # it runs from, its trust anchors included, are the committed bytes.
+ # (The runner's own git config still applies; GitHub's ubuntu
+ # runners set no core.autocrlf or core.attributesFile.)
+ # A .gitattributes anywhere in the base, on the gate surface or off
+ # it, then can neither rewrite them (working-tree-encoding, ident, a
+ # filter, eol=crlf) nor stop the checkout (a boolean
+ # working-tree-encoding, a required filter whose smudge fails). A
+ # stopped checkout would fail this job on every later pull request,
+ # the one that removes the file included. Two pull requests that
+ # each pass alone can merge into such a base. The candidate above
+ # keeps its attributes: if they stop its checkout, that refuses the
+ # candidate.
+ empty_tree="$(git -C "$base_gate" hash-object -t tree /dev/null)"
+ git -C "$base_gate" --attr-source="$empty_tree" \
+ checkout --detach "$BASE_SHA"
test "$(git -C "$base_gate" rev-parse HEAD)" = "$BASE_SHA"
# Provision the BASE commit's own hash-locked environment and run
# the base gate with it: the gate scripts may import packaged
# dependencies, and installing from the base's uv.lock
# keeps the PR unable to influence what code judges it.
- uv sync --locked --no-dev --project "$base_gate"
+ #
+ # Every start of the base gate, the --help question included, uses
+ # `python -I` and sets no PYTHONPATH, and the environment does not
+ # install this project. -I keeps the script's own directory off
+ # sys.path and ignores PYTHON* variables; without the project, no
+ # editable .pth puts the base checkout's root on sys.path, and the
+ # sync builds nothing from the checkout (no README.md, hatch.toml or
+ # hatch_build.py). Most of scripts/ and the root are off the gate
+ # surface, so an earlier data proposal can add a module there (a
+ # scripts/tempfile.py, a scripts/receipt/ package, a root
+ # sitecustomize/ package); started this way, the gate never imports
+ # it. `uv run --no-sync` keeps uv from installing the project again.
+ #
+ # A base gate that still imports its pins by name finds them only
+ # as scripts.receipt_pins, through that root, so for such a base
+ # alone the project is installed as before. -I still keeps scripts/
+ # off sys.path, but the root is on it, last, so a module there that
+ # the old gate looks up and finds nowhere earlier (a root
+ # receipt_pins.py, a scripts/__init__.py or a scripts/receipt_pins/
+ # package) still reaches it. The check reads the base checkout's
+ # copy of the gate, which the candidate cannot change. Delete the
+ # first branch below once no pull request into this branch can
+ # still have a base from before the gate loaded its pins by path. A
+ # gate older than the pins imports its sibling scripts by name,
+ # cannot start this way, and stops the step.
+ base_gate_script="$base_gate/scripts/check_thesis_facts_append.py"
+ if grep -qE '^[[:space:]]*from scripts\.receipt_pins import ' \
+ "$base_gate_script"; then
+ uv sync --locked --no-dev --project "$base_gate"
+ base_gate_python=(uv run --locked --no-dev --project "$base_gate" python -I)
+ else
+ uv sync --locked --no-dev --no-install-project --project "$base_gate"
+ base_gate_python=(uv run --no-sync --project "$base_gate" python -I)
+ fi
# Receipt 0.6 reads and rehashes the named commit's objects; the shim
# prints the commit and tree from that verdict. --root only locates
@@ -118,33 +166,24 @@ jobs:
# cannot run at all stops the step instead of being read as an old
# one. Delete the second branch below once no base reachable from
# this branch predates --commit.
- base_gate_help="$(
- uv run --locked --no-dev --project "$base_gate" \
- python "$base_gate/scripts/check_thesis_facts_append.py" --help
- )"
+ base_gate_help="$("${base_gate_python[@]}" "$base_gate_script" --help)"
cd "$RUNNER_TEMP"
case "$base_gate_help" in
*--commit*)
- PYTHONPATH="$base_gate/scripts" \
- PYTHONNOUSERSITE=1 \
- uv run --locked --no-dev --project "$base_gate" \
- python "$base_gate/scripts/check_thesis_facts_append.py" \
- --root "$candidate" \
- --commit "$MERGE_SHA" \
- --base-ref "$BASE_SHA"
+ "${base_gate_python[@]}" "$base_gate_script" \
+ --root "$candidate" \
+ --commit "$MERGE_SHA" \
+ --base-ref "$BASE_SHA"
;;
*)
echo "note: the base gate at $BASE_SHA predates --commit, so it" \
"judges the working tree at $candidate, without binding its" \
"verdict to $MERGE_SHA. This is the base's own guarantee and" \
"the only one available against that base." >&2
- PYTHONPATH="$base_gate/scripts" \
- PYTHONNOUSERSITE=1 \
- uv run --locked --no-dev --project "$base_gate" \
- python "$base_gate/scripts/check_thesis_facts_append.py" \
- --root "$candidate" \
- --base-ref "$BASE_SHA"
+ "${base_gate_python[@]}" "$base_gate_script" \
+ --root "$candidate" \
+ --base-ref "$BASE_SHA"
;;
esac
@@ -174,54 +213,66 @@ jobs:
"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" \
"$base_gate"
git -C "$base_gate" fetch --no-tags --depth 1 origin "$base_sha"
- git -C "$base_gate" checkout --detach "$base_sha"
+ # As in the trusted job: an empty attribute tree, so the base
+ # gate runs from the committed bytes and no .gitattributes can
+ # stop its checkout.
+ empty_tree="$(git -C "$base_gate" hash-object -t tree /dev/null)"
+ git -C "$base_gate" --attr-source="$empty_tree" \
+ checkout --detach "$base_sha"
test "$(git -C "$base_gate" rev-parse HEAD)" = "$base_sha"
# Base gate runs from the BASE commit's own hash-locked env so
- # gate dependencies resolve without the PR influencing them.
- uv sync --locked --no-dev --project "$base_gate"
+ # gate dependencies resolve without the PR influencing them. As
+ # in the trusted job above, the env does not install this
+ # project and every start uses `python -I` with no PYTHONPATH,
+ # so no module in the base's scripts/ or at its root can stand in
+ # for one the gate imports, except in a base whose gate still
+ # imports its pins by name (see the trusted job above). Delete
+ # the first branch below when the trusted job's goes.
+ base_gate_script="$base_gate/scripts/check_thesis_facts_append.py"
+ if grep -qE '^[[:space:]]*from scripts\.receipt_pins import ' \
+ "$base_gate_script"; then
+ uv sync --locked --no-dev --project "$base_gate"
+ base_gate_python=(uv run --locked --no-dev --project "$base_gate" python -I)
+ else
+ uv sync --locked --no-dev --no-install-project --project "$base_gate"
+ base_gate_python=(uv run --no-sync --project "$base_gate" python -I)
+ fi
workspace_sha="$(git -C "$GITHUB_WORKSPACE" rev-parse HEAD)"
[[ "$workspace_sha" =~ ^[0-9a-f]{40,64}$ ]]
# As in the trusted job above: the commit is named, not inferred,
# and the base gate is asked what it accepts for the same reason.
- base_gate_help="$(
- uv run --locked --no-dev --project "$base_gate" \
- python "$base_gate/scripts/check_thesis_facts_append.py" --help
- )"
+ base_gate_help="$("${base_gate_python[@]}" "$base_gate_script" --help)"
cd "$RUNNER_TEMP"
case "$base_gate_help" in
*--commit*)
- PYTHONPATH="$base_gate/scripts" \
- PYTHONNOUSERSITE=1 \
- uv run --locked --no-dev --project "$base_gate" \
- python "$base_gate/scripts/check_thesis_facts_append.py" \
- --root "$GITHUB_WORKSPACE" \
- --commit "$workspace_sha" \
- --base-ref "$base_sha"
+ "${base_gate_python[@]}" "$base_gate_script" \
+ --root "$GITHUB_WORKSPACE" \
+ --commit "$workspace_sha" \
+ --base-ref "$base_sha"
;;
*)
echo "note: the base gate at $base_sha predates --commit, so" \
"it judges the workspace, without binding its verdict to" \
"$workspace_sha." >&2
- PYTHONPATH="$base_gate/scripts" \
- PYTHONNOUSERSITE=1 \
- uv run --locked --no-dev --project "$base_gate" \
- python "$base_gate/scripts/check_thesis_facts_append.py" \
- --root "$GITHUB_WORKSPACE" \
- --base-ref "$base_sha"
+ "${base_gate_python[@]}" "$base_gate_script" \
+ --root "$GITHUB_WORKSPACE" \
+ --base-ref "$base_sha"
;;
esac
else
# The push path names the pushed commit explicitly too. The
# argument is required, so there is no spelling of this run in
- # which the commit is taken from the checkout instead.
- uv sync --locked --no-dev
- uv run --locked --no-dev \
- python scripts/check_thesis_facts_append.py \
- --commit "$GITHUB_SHA"
+ # which the commit is taken from the checkout instead. It runs
+ # the pushed commit's own gate, which loads its pins by path, so
+ # it starts it isolated, as the jobs above do, with no project
+ # install to undo.
+ uv sync --locked --no-dev --no-install-project
+ uv run --no-sync python -I scripts/check_thesis_facts_append.py \
+ --commit "$GITHUB_SHA"
fi
- name: Install uv
diff --git a/README.md b/README.md
index 0be4f411..4163e7a3 100644
--- a/README.md
+++ b/README.md
@@ -559,4 +559,43 @@ environment. Verification machinery is consumed from the `receipt`
package with this repository's trust pins committed in
`scripts/receipt_pins.py`; see `releases/README.md` (immutable
post-genesis, like everything under `releases/`) for the schema, offline
-verification procedure, and security limits.
+verification procedure, and security limits. The gate surface,
+`APPEND_GATE_SPEC.gate_surface` in `scripts/receipt_pins.py`, lists the
+files in the base checkout that decide the gate's verdict:
+
+- the gate's scripts, the trust pins, the anchors, and the append workflow;
+- the files that build its interpreter and environment: `pyproject.toml`,
+ `uv.lock`, `uv.toml`, `.python-version`, `.python-versions`, `.venv`,
+ `hatch.toml`, `hatch_build.py`, `sitecustomize.py` (in `scripts/` and at
+ the root) and `scripts/__pycache__`;
+- every `.gitattributes` git applies to these files when it checks them
+ out: at the root and in `releases/`, which decide the anchor bytes, and
+ in `scripts/`, `.github/` and `.github/workflows/`. Receipt already refuses
+ `filter`, `ident` and `working-tree-encoding` on the gate's scripts and the
+ workflow, and line endings do not change how Python reads a script, so
+ these three cannot change a verdict today; listing them keeps that from
+ depending on the receipt version.
+
+The gate refuses a pull request that changes any of them together with the
+ledger, and names them when a pull request changes only them. The rest of
+`scripts/` is off the surface, and so is any new module that could shadow one
+of the gate's imports, there or at the root. None can reach the gate. The
+append workflow builds the gate's environment without installing this
+project, so the root is not on its import path. It starts the gate with
+`python -I` and no `PYTHONPATH`, so `scripts/` is not on it either, and the
+gate loads `receipt_pins.py` by path. The trusted pull request job runs the
+default branch's copy of the workflow, which needs the same steps. A base
+whose gate still imports its pins by name gets the project installed, so a
+module that gate looks up at the root, such as a root `receipt_pins.py` or a
+`scripts/__init__.py`, can still reach it.
+
+Both pull request jobs also check the base gate out with an empty attribute
+tree, so it runs from its committed bytes on a runner whose git sets no
+`core.autocrlf` or `core.attributesFile`, as GitHub's ubuntu runners do. A
+`.gitattributes` anywhere in the base, on the surface or off it, cannot
+rewrite those bytes or stop the checkout. A stopped checkout would fail the
+job on every later pull request, including the one that removes the file, and
+two pull requests that each pass alone can merge into such a base. The
+attributes still apply where the gate is checked out with them: on the push
+path, in a local run, and in the trusted job until the default branch carries
+this workflow. That is why they stay on the surface.
diff --git a/scripts/check_thesis_facts_append.py b/scripts/check_thesis_facts_append.py
index 62972832..e157aae2 100644
--- a/scripts/check_thesis_facts_append.py
+++ b/scripts/check_thesis_facts_append.py
@@ -44,21 +44,34 @@
import subprocess
import sys
import tempfile
+import types
from collections.abc import Iterator
from typing import Any
import receipt.append_gate as _receipt
from receipt.release_chain import MANIFEST_RE, ReleaseChainError
-try:
- from receipt_pins import APPEND_GATE_SPEC
-except ModuleNotFoundError as exc:
- if exc.name != "receipt_pins":
- raise
- # The test suite copies the legacy three-script surface into temporary
- # repositories. The editable consumer tree remains the sole pin owner.
- from scripts.receipt_pins import APPEND_GATE_SPEC
+def _load_receipt_pins() -> types.ModuleType:
+ """Load the trust pins from ``receipt_pins.py`` beside this file, by path.
+
+ The append workflow starts this script with ``python -I``, which keeps its
+ directory off ``sys.path``. No other module in ``scripts/`` can then stand
+ in for one this script imports, such as a ``tempfile.py`` or a
+ ``receipt/`` package. The pins are compiled from their source here rather
+ than imported, so a ``__pycache__`` entry cannot stand in for them either.
+ ``scripts/verify_release_chain.py`` loads them the same way.
+ """
+
+ path = pathlib.Path(__file__).resolve().with_name("receipt_pins.py")
+ module = types.ModuleType("receipt_pins")
+ module.__file__ = str(path)
+ code = compile(path.read_bytes(), str(path), "exec", dont_inherit=True)
+ exec(code, module.__dict__)
+ return module
+
+
+APPEND_GATE_SPEC = _load_receipt_pins().APPEND_GATE_SPEC
CODE_ROOT = pathlib.Path(__file__).resolve().parents[1]
RELEASE_MANIFEST_PREFIX = APPEND_GATE_SPEC.release_manifest_prefix
diff --git a/scripts/receipt_pins.py b/scripts/receipt_pins.py
index 2136c758..5aba8de1 100644
--- a/scripts/receipt_pins.py
+++ b/scripts/receipt_pins.py
@@ -86,13 +86,88 @@
(f"releases/anchors/{LEDGER_SPEC.producer_public_key_filename}"),
}
),
+ # The files in the judging (base) checkout that decide the gate's verdict:
+ # the gate's code and pins, the trust anchors, the files that build its
+ # interpreter and environment, the append workflow, and the .gitattributes
+ # files git applies to any of them. A proposal that changes one of them
+ # together with the ledger is refused as mixed, and a proposal that
+ # changes only these is reported by name. A "dir/**" entry matches only
+ # paths below dir, so each one is also listed bare: otherwise a symlink or
+ # file committed at dir itself would be unclassified, and dropped on the
+ # data path.
+ #
+ # The rest of scripts/ stays off the surface. A catalog-builder change
+ # ships with the ledger/series_catalog.json it regenerates (as in #128),
+ # and the catalog tests require the two to land together. Nor can this
+ # list name in advance every module that could shadow one the judge
+ # imports: a scripts/tempfile.py, a scripts/receipt/ package, a root
+ # sitecustomize/ package, or another spelling of sitecustomize or
+ # receipt_pins (a sourceless .pyc, an extension module). None of them can
+ # reach the judge. The append workflow builds its environment without
+ # installing this project (uv sync --no-install-project), so the base
+ # checkout's root is not on sys.path, and starts it with python -I and no
+ # PYTHONPATH, so scripts/ is not either. The gate loads this file by path.
+ #
+ # The one exception is a base whose gate still imports these pins by
+ # name, which it can only do as scripts.receipt_pins, through the root.
+ # The workflow installs the project for that base alone, still with
+ # python -I, so scripts/ stays off sys.path but the root is on it, last:
+ # a module that old gate looks up there (a root receipt_pins.py, a
+ # scripts/__init__.py or a scripts/receipt_pins/ package) still reaches
+ # it.
gate_surface=frozenset(
{
"scripts/check_thesis_facts_append.py",
"scripts/verify_release_chain.py",
"scripts/canonical_json.py",
"scripts/cut_release_manifest.py",
+ "scripts/receipt_pins.py",
+ # Older pairings still read these. A gate started with scripts/
+ # on PYTHONPATH, or with the project installed (which puts the
+ # root on sys.path), runs a sitecustomize.py found there at
+ # startup, and a gate that imports the pins by name loads an
+ # unchecked-hash .pyc from __pycache__ in place of their source.
+ "scripts/sitecustomize.py",
+ "sitecustomize.py",
+ "scripts/__pycache__",
+ "scripts/__pycache__/**",
".github/workflows/thesis-facts-append.yml",
+ # `uv sync --locked --no-dev --no-install-project --project
+ # ` builds the judge's environment from these, including
+ # the receipt version that implements the gate. uv also reads the
+ # project's uv.toml and .python-version (or .python-versions),
+ # and reuses a .venv it finds there. For a base whose gate still
+ # imports its pins by name, the workflow also installs this
+ # project, with hatchling, which reads hatch.toml and runs a
+ # hatch_build.py hook when one is configured.
+ "pyproject.toml",
+ "uv.lock",
+ "uv.toml",
+ ".python-version",
+ ".python-versions",
+ ".venv",
+ ".venv/**",
+ "hatch.toml",
+ "hatch_build.py",
+ # Git applies the .gitattributes in each directory above a file
+ # when it checks out the judge, so every one above an entry here
+ # is listed. The root and releases/ files decide the bytes of the
+ # anchors the judge pins. The scripts/ file reaches the gate's
+ # Python, and the .github/ files reach no entry here but the
+ # workflow, which the judge does not read. Receipt refuses filter,
+ # ident and working-tree-encoding on every surface path, and
+ # Python reads either line ending, so these three cannot change a
+ # verdict today. They are listed so that this does not depend on
+ # the receipt version. The append workflow's pull request jobs
+ # check the base gate out with an empty attribute tree, so none of
+ # these reaches the judge there; they still reach a gate checked
+ # out with its attributes, as on the push path or in a local run.
+ ".gitattributes",
+ "releases/.gitattributes",
+ "scripts/.gitattributes",
+ ".github/.gitattributes",
+ ".github/workflows/.gitattributes",
+ "releases/anchors",
"releases/anchors/**",
}
),
diff --git a/scripts/verify_release_chain.py b/scripts/verify_release_chain.py
index 0231113f..c0a0ce3f 100644
--- a/scripts/verify_release_chain.py
+++ b/scripts/verify_release_chain.py
@@ -15,20 +15,33 @@
import argparse
import pathlib
import sys
+import types
from datetime import datetime
from typing import Any
import receipt.release_chain as _receipt
from receipt.snapshot import SnapshotError, TreeSnapshot
-try:
- from receipt_pins import LEDGER_SPEC
-except ModuleNotFoundError as exc:
- if exc.name != "receipt_pins":
- raise
- # The test suite copies the legacy three-script surface into temporary
- # repositories. The editable consumer tree remains the sole pin owner.
- from scripts.receipt_pins import LEDGER_SPEC
+
+def _load_receipt_pins() -> types.ModuleType:
+ """Load the trust pins from ``receipt_pins.py`` beside this file, by path.
+
+ CI starts this script with ``python -I``, which keeps its directory off
+ ``sys.path``, so no other module in ``scripts/`` can stand in for one this
+ script imports. The pins are compiled from their source rather than
+ imported, so a ``__pycache__`` entry cannot stand in for them. The append
+ gate, ``scripts/check_thesis_facts_append.py``, loads them the same way.
+ """
+
+ path = pathlib.Path(__file__).resolve().with_name("receipt_pins.py")
+ module = types.ModuleType("receipt_pins")
+ module.__file__ = str(path)
+ code = compile(path.read_bytes(), str(path), "exec", dont_inherit=True)
+ exec(code, module.__dict__)
+ return module
+
+
+LEDGER_SPEC = _load_receipt_pins().LEDGER_SPEC
ROOT = pathlib.Path(__file__).resolve().parents[1]
diff --git a/tests/test_legacy_targets_retired.py b/tests/test_legacy_targets_retired.py
index b3b6f0e2..7a15be7b 100644
--- a/tests/test_legacy_targets_retired.py
+++ b/tests/test_legacy_targets_retired.py
@@ -269,11 +269,12 @@ def test_source_stats_reads_an_initialized_store(monkeypatch, capsys, tmp_path):
def test_append_path_scripts_load_nothing_from_the_repository_packages(tmp_path):
"""Import every append-path script the way its callers do and list modules.
- The scripts run with ``scripts/`` on ``sys.path`` and the repository root
- off it (the gate sets ``PYTHONPATH`` to the base checkout's ``scripts/``
- and runs from the runner's temp directory; the resolver runs the staged
- generator by path). ``-I`` drops the environment and the current directory
- from ``sys.path``; the scripts directory is added back explicitly.
+ The resolver runs the staged generator by path, so ``scripts/`` is on
+ ``sys.path`` and the current directory is off it. The append gate starts
+ with ``python -I`` and loads ``receipt_pins.py`` by path; adding the
+ scripts directory here covers the wider of the two. ``-I`` drops the
+ environment and the current directory from ``sys.path``; the scripts
+ directory is added back explicitly.
"""
probe = (
"import json, sys\n"
diff --git a/tests/test_policyengine_ledger.py b/tests/test_policyengine_ledger.py
index f2b3da8b..556da81c 100644
--- a/tests/test_policyengine_ledger.py
+++ b/tests/test_policyengine_ledger.py
@@ -382,6 +382,7 @@ def test_a_rewritten_prefix_line_is_detected(tmp_path):
"check_thesis_facts_append.py",
"canonical_json.py",
"verify_release_chain.py",
+ "receipt_pins.py",
):
(scripts_dir / name).write_text((ROOT / "scripts" / name).read_text())
diff --git a/tests/test_receipt_shim_transparency.py b/tests/test_receipt_shim_transparency.py
index 99fccc19..20962e0d 100644
--- a/tests/test_receipt_shim_transparency.py
+++ b/tests/test_receipt_shim_transparency.py
@@ -113,6 +113,80 @@ def test_original_oracle_fixtures_are_authenticated(name: str) -> None:
assert _sha256(ORIGINAL_FIXTURES / name) == ORIGINAL_HASHES[name]
+def _original_surface(name: str) -> frozenset[str]:
+ """Read one surface literal from the authenticated original gate."""
+
+ import ast
+
+ module = ast.parse(
+ (ORIGINAL_FIXTURES / "check_thesis_facts_append.py").read_text(encoding="utf-8")
+ )
+ for node in module.body:
+ if (
+ isinstance(node, ast.Assign)
+ and [getattr(target, "id", None) for target in node.targets] == [name]
+ and isinstance(node.value, ast.Call)
+ ):
+ return frozenset(ast.literal_eval(node.value.args[0]))
+ raise AssertionError(f"{name} not found in the original gate")
+
+
+def test_the_shim_gate_surface_deliberately_widens_the_originals() -> None:
+ """The one place the pair is meant to disagree about classification.
+
+ The originals' GATE_SURFACE predates scripts/receipt_pins.py, where the
+ shim's trust pins now live, and never listed the files that build the
+ judge's interpreter and environment or the .gitattributes git checks it
+ out with. The shim's surface covers every original entry and adds exactly
+ those, so a proposal that changes one of them is refused as mixed (with
+ rows) or named as gate-only (alone), where the original judged it as plain
+ data.
+ No case in this file changes such a file, so the byte-identity asserted
+ here is unaffected; tests/test_thesis_append_shim_isolation.py holds the
+ shim to the wider surface.
+ """
+
+ from receipt.append_gate import _matches_surface
+
+ from scripts.receipt_pins import APPEND_GATE_SPEC
+
+ original_gate = _original_surface("GATE_SURFACE")
+ shim_gate = APPEND_GATE_SPEC.gate_surface
+ for entry in original_gate:
+ if entry.endswith("/**"):
+ assert entry in shim_gate, entry
+ else:
+ assert _matches_surface(entry, shim_gate), entry
+ assert _original_surface("DATA_SURFACE") == APPEND_GATE_SPEC.data_surface
+ widened = {
+ "scripts/receipt_pins.py",
+ "scripts/sitecustomize.py",
+ "sitecustomize.py",
+ "scripts/__pycache__",
+ "scripts/__pycache__/**",
+ "pyproject.toml",
+ "uv.lock",
+ "uv.toml",
+ ".python-version",
+ ".python-versions",
+ ".venv",
+ ".venv/**",
+ "hatch.toml",
+ "hatch_build.py",
+ ".gitattributes",
+ "releases/.gitattributes",
+ "scripts/.gitattributes",
+ ".github/.gitattributes",
+ ".github/workflows/.gitattributes",
+ "releases/anchors",
+ }
+ assert shim_gate - original_gate == widened
+ for entry in widened:
+ named = entry.removesuffix("/**")
+ assert not _matches_surface(named, original_gate), entry
+ assert _matches_surface(named, shim_gate), entry
+
+
@pytest.fixture(scope="session")
def original_oracle(tmp_path_factory: pytest.TempPathFactory) -> pathlib.Path:
"""Copy the authenticated original scripts into one executable tree."""
diff --git a/tests/test_release_chain.py b/tests/test_release_chain.py
index b383efce..e312b016 100644
--- a/tests/test_release_chain.py
+++ b/tests/test_release_chain.py
@@ -25,6 +25,7 @@
SCRIPT_NAMES = (
"canonical_json.py",
"check_thesis_facts_append.py",
+ "receipt_pins.py",
"verify_release_chain.py",
)
diff --git a/tests/test_thesis_append_adversarial.py b/tests/test_thesis_append_adversarial.py
index c86ad641..d4e8c47d 100644
--- a/tests/test_thesis_append_adversarial.py
+++ b/tests/test_thesis_append_adversarial.py
@@ -14,7 +14,6 @@
import hashlib
import json
import re
-import os
import subprocess
import sys
from pathlib import Path
@@ -121,6 +120,7 @@ def _write_checker_fixture(path: Path, ledger_text: str, manifest: dict) -> None
"check_thesis_facts_append.py",
"canonical_json.py",
"verify_release_chain.py",
+ "receipt_pins.py",
):
(scripts_dir / name).write_text(
(ROOT / "scripts" / name).read_text(encoding="utf-8"),
@@ -353,12 +353,10 @@ def test_base_gate_uses_base_script_and_dependency_imports(
candidate_commit = _commit_candidate(candidate)
- environment = os.environ.copy()
- environment["PYTHONPATH"] = str(base_gate / "scripts")
- environment["PYTHONNOUSERSITE"] = "1"
completed = subprocess.run(
[
sys.executable,
+ "-I",
str(base_gate / "scripts" / "check_thesis_facts_append.py"),
"--root",
str(candidate),
@@ -368,7 +366,6 @@ def test_base_gate_uses_base_script_and_dependency_imports(
base,
],
cwd=tmp_path,
- env=environment,
capture_output=True,
text=True,
)
@@ -398,13 +395,17 @@ def test_workflow_has_a_base_owned_trusted_pr_gate():
'[[ "$MERGE_SHA" =~ ^[0-9a-f]{40,64}$ ]]',
'[[ "$PR_NUMBER" =~ ^[0-9]+$ ]]',
'"+refs/pull/${PR_NUMBER}/merge:refs/remotes/origin/pr-merge"',
- 'PYTHONPATH="$base_gate/scripts"',
# The base gate provisions the BASE commit's own hash-locked env and
# runs with it — dropping either line would let a shimmed base gate
- # ModuleNotFoundError or resolve deps the PR could influence.
+ # ModuleNotFoundError or resolve deps the PR could influence. The env
+ # leaves the project out, unless the base gate still imports its pins
+ # by name, and every start is isolated.
+ 'uv sync --locked --no-dev --no-install-project --project "$base_gate"',
+ 'base_gate_python=(uv run --no-sync --project "$base_gate" python -I)',
'uv sync --locked --no-dev --project "$base_gate"',
- 'uv run --locked --no-dev --project "$base_gate"',
- 'python "$base_gate/scripts/check_thesis_facts_append.py"',
+ 'base_gate_python=(uv run --locked --no-dev --project "$base_gate" python -I)',
+ 'base_gate_script="$base_gate/scripts/check_thesis_facts_append.py"',
+ '"${base_gate_python[@]}" "$base_gate_script"',
'--root "$candidate"',
'--base-ref "$BASE_SHA"',
# The commit under judgement is named on the command line in all three
diff --git a/tests/test_thesis_append_shim_isolation.py b/tests/test_thesis_append_shim_isolation.py
index 61e6d4c8..2a11c090 100644
--- a/tests/test_thesis_append_shim_isolation.py
+++ b/tests/test_thesis_append_shim_isolation.py
@@ -22,6 +22,7 @@
import stat
import subprocess
import sys
+import sysconfig
from importlib import metadata
import pytest
@@ -57,6 +58,7 @@ def _subject_line(clone: pathlib.Path, candidate: str, base: str | None) -> str:
line += f" base commit {base} tree {_git(clone, 'rev-parse', base + '^{tree}')}"
return line
+
# A commit id of the right shape that no repository holds.
ABSENT_OBJECT_ID = "0" * 40
@@ -942,6 +944,1320 @@ def test_a_true_append_is_accepted_end_to_end(tmp_path):
_assert_nothing_left_behind(clone, tmp_path / "tmp")
+# Files that decide a verdict when they sit in the judging checkout, one per
+# way in: the pins the shim imports, the uv and hatchling inputs the workflow
+# provisions the judge from, the attributes git checks these files out with,
+# and files that are not there today but would be read if added.
+# Before PolicyEngine/chronicle#308 the first three were off the gate surface,
+# so a resolver-shaped append that also edited them was judged as plain data
+# and never named them (PolicyEngine/chronicle#299 review).
+GATE_DECIDERS = (
+ "scripts/receipt_pins.py",
+ "pyproject.toml",
+ "uv.lock",
+ "uv.toml",
+ ".python-version",
+ ".python-versions",
+ "hatch.toml",
+ "hatch_build.py",
+ "scripts/sitecustomize.py",
+ "sitecustomize.py",
+ "scripts/__pycache__/receipt_pins.cpython-314.pyc",
+ ".venv/lib/python3.14/site-packages/zz_injected.pth",
+ ".gitattributes",
+ "releases/.gitattributes",
+ "scripts/.gitattributes",
+ ".github/.gitattributes",
+ ".github/workflows/.gitattributes",
+)
+
+# A "dir/**" entry matches only paths below dir, so these directories are also
+# on the surface bare: a symlink committed in their place is a decider too.
+# (releases/anchors is listed bare as well; the chain checks refuse a symlink
+# there on their own.)
+SURFACE_DIRECTORIES = (".venv", "scripts/__pycache__")
+
+
+def _change_gate_decider(relative: str):
+ """Return a mutation that changes one decider, or adds it if absent."""
+
+ def mutate(root: pathlib.Path) -> None:
+ path = root / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("a", encoding="utf-8") as handle:
+ handle.write("# a change riding the proposal\n")
+
+ return mutate
+
+
+def _force_add(relative: str):
+ """Stage one path even where an ignore file lists it.
+
+ ``__pycache__`` and ``.venv`` are commonly ignored, and the default global
+ ignore file applies even with GIT_CONFIG_GLOBAL unset, so ``git add -A``
+ alone could leave the decider out of the candidate.
+ """
+
+ def stage(root: pathlib.Path) -> None:
+ _git(root, "add", "--force", "--", relative)
+
+ return stage
+
+
+def _copy_existing_gate_deciders(root: pathlib.Path) -> None:
+ """Put the repository's own copy of every decider it has into the base."""
+
+ for relative in GATE_DECIDERS:
+ source = ROOT / relative
+ if source.is_file():
+ destination = root / relative
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(source, destination)
+
+
+@pytest.mark.parametrize("relative", GATE_DECIDERS)
+def test_an_append_that_also_changes_a_gate_decider_is_refused_as_mixed(
+ tmp_path, relative
+):
+ """The witnessed append plus one decider change cannot pass as data.
+
+ The refusal comes before any ledger check and names the decider, so a trust
+ change can no longer ride an append that the resolver merges on its own.
+ """
+
+ clone, base, candidate = _replay_latest_release(
+ tmp_path,
+ prepare=_copy_existing_gate_deciders,
+ mutate=_change_gate_decider(relative),
+ mutate_index=_force_add(relative),
+ )
+
+ completed = _run_shim(
+ clone, commit=candidate, base_ref=base, temporary_root=tmp_path / "tmp"
+ )
+
+ assert completed.returncode == 1, completed.stdout + completed.stderr
+ assert completed.stdout == ""
+ assert f"{FAILED}mixed data/gate proposal is forbidden: " in completed.stderr
+ assert (
+ f"; GATE_SURFACE changes={[relative]!r}; split them into separate pull requests"
+ ) in completed.stderr
+ _assert_nothing_left_behind(clone, tmp_path / "tmp")
+
+
+@pytest.mark.parametrize("relative", GATE_DECIDERS)
+def test_a_gate_decider_change_alone_is_a_named_gate_only_proposal(tmp_path, relative):
+ clone, base = _replay_current_state(tmp_path)
+ _copy_existing_gate_deciders(clone)
+ base = _commit(clone, "deciders in the base")
+ _change_gate_decider(relative)(clone)
+ candidate = _commit(clone, f"change {relative}", _force_add(relative))
+
+ completed = _run_shim(
+ clone, commit=candidate, base_ref=base, temporary_root=tmp_path / "tmp"
+ )
+
+ assert completed.returncode == 0, completed.stdout + completed.stderr
+ assert completed.stdout.splitlines() == [
+ "thesis-facts append check OK: gate-only proposal; DATA_SURFACE "
+ f"unchanged; GATE_SURFACE changes={[relative]!r}",
+ _subject_line(clone, candidate, base),
+ ]
+ _assert_nothing_left_behind(clone, tmp_path / "tmp")
+
+
+def _link_surface_directory(relative: str):
+ """Return a mutation that commits a symlink where a surface directory goes."""
+
+ def mutate(root: pathlib.Path) -> None:
+ path = root / relative
+ if path.is_symlink() or path.is_file():
+ path.unlink()
+ elif path.exists():
+ shutil.rmtree(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.symlink_to("ledger" if "/" not in relative else "../ledger")
+
+ return mutate
+
+
+@pytest.mark.parametrize("relative", SURFACE_DIRECTORIES)
+def test_an_append_beside_a_symlinked_surface_directory_is_refused_as_mixed(
+ tmp_path, relative
+):
+ clone, base, candidate = _replay_latest_release(
+ tmp_path,
+ mutate=_link_surface_directory(relative),
+ mutate_index=_force_add(relative),
+ )
+ assert _git(clone, "ls-tree", candidate, "--", relative).startswith("120000 ")
+
+ completed = _run_shim(
+ clone, commit=candidate, base_ref=base, temporary_root=tmp_path / "tmp"
+ )
+
+ assert completed.returncode == 1, completed.stdout + completed.stderr
+ assert completed.stdout == ""
+ assert f"{FAILED}mixed data/gate proposal is forbidden: " in completed.stderr
+ assert f"GATE_SURFACE changes=[{relative!r}" in completed.stderr
+ _assert_nothing_left_behind(clone, tmp_path / "tmp")
+
+
+def test_an_append_beside_unchanged_gate_deciders_still_passes(tmp_path):
+ """The resolver's shape: ledger and release files only, deciders untouched."""
+
+ clone, base, candidate = _replay_latest_release(
+ tmp_path, prepare=_copy_existing_gate_deciders
+ )
+ changed = set(_git(clone, "diff", "--name-only", base, candidate).splitlines())
+ assert changed and all(
+ path.startswith(("ledger/", "releases/manifests/")) for path in changed
+ ), changed
+
+ completed = _run_shim(
+ clone, commit=candidate, base_ref=base, temporary_root=tmp_path / "tmp"
+ )
+
+ assert completed.returncode == 0, completed.stdout + completed.stderr
+ assert completed.stdout == (
+ f"{APPEND_GATE_OK}\n{_subject_line(clone, candidate, base)}\n"
+ )
+ _assert_nothing_left_behind(clone, tmp_path / "tmp")
+
+
+def test_an_append_beside_a_catalog_builder_change_is_still_data(tmp_path):
+ """A script the gate never reads stays off the surface.
+
+ PolicyEngine/chronicle#128 shipped scripts/build_series_catalog.py with the
+ ledger/series_catalog.json it generates, and the catalog tests require the
+ two to land together. With all of scripts/ on the surface, that shape would
+ be refused as mixed and could not be split.
+ """
+
+ builder = "scripts/build_series_catalog.py"
+
+ def prepare(root: pathlib.Path) -> None:
+ (root / "scripts").mkdir(exist_ok=True)
+ shutil.copyfile(ROOT / builder, root / builder)
+
+ clone, base, candidate = _replay_latest_release(
+ tmp_path, prepare=prepare, mutate=_change_gate_decider(builder)
+ )
+ changed = set(_git(clone, "diff", "--name-only", base, candidate).splitlines())
+ assert builder in changed, changed
+
+ completed = _run_shim(
+ clone, commit=candidate, base_ref=base, temporary_root=tmp_path / "tmp"
+ )
+
+ assert completed.returncode == 0, completed.stdout + completed.stderr
+ assert completed.stdout == (
+ f"{APPEND_GATE_OK}\n{_subject_line(clone, candidate, base)}\n"
+ )
+ _assert_nothing_left_behind(clone, tmp_path / "tmp")
+
+
+OPENED_FILES_DRIVER = """\
+import json
+import os
+import pathlib
+import sys
+
+opened = set()
+
+
+def _record(event, arguments):
+ if event == "open" and isinstance(arguments[0], (str, bytes, os.PathLike)):
+ opened.add(os.fsdecode(arguments[0]))
+
+
+sys.addaudithook(_record)
+sys.path.insert(0, {scripts!r})
+
+import check_thesis_facts_append as shim # noqa: E402
+
+try:
+ code = shim.main()
+finally:
+ opened.update(
+ getattr(module, "__file__", None) or "" for module in list(sys.modules.values())
+ )
+ pathlib.Path({report!r}).write_text(json.dumps(sorted(opened)), encoding="utf-8")
+raise SystemExit(code)
+"""
+
+
+def test_every_file_the_gate_reads_from_its_own_checkout_is_on_the_gate_surface(
+ tmp_path,
+):
+ """The invariant behind GATE_SURFACE, measured on an accepting run.
+
+ Every file the gate process opens or imports from inside the judging
+ checkout is on the surface. That is the pins, the gate's scripts, the
+ trust anchors, and the installed receipt wheel, which lives in the
+ checkout's own .venv just as it does in the workflow's base-gate clone.
+ """
+
+ from receipt.append_gate import _matches_surface
+
+ from scripts.receipt_pins import APPEND_GATE_SPEC
+
+ clone, base, candidate = _replay_latest_release(tmp_path)
+ report = tmp_path / "opened.json"
+ driver = tmp_path / "driver" / "driver.py"
+ driver.parent.mkdir()
+ driver.write_text(
+ OPENED_FILES_DRIVER.format(scripts=str(SHIM_SCRIPTS), report=str(report)),
+ encoding="utf-8",
+ )
+
+ completed = subprocess.run(
+ [
+ sys.executable,
+ str(driver),
+ "--root",
+ str(clone),
+ "--commit",
+ candidate,
+ "--base-ref",
+ base,
+ ],
+ cwd=clone,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert completed.returncode == 0, completed.stdout + completed.stderr
+
+ root = ROOT.resolve()
+ inside = set()
+ for name in json.loads(report.read_text(encoding="utf-8")):
+ if not name:
+ continue
+ path = pathlib.Path(name)
+ if not path.is_absolute():
+ path = clone / path
+ resolved = path.resolve()
+ if resolved.is_relative_to(root):
+ inside.add(resolved.relative_to(root).as_posix())
+ assert "scripts/receipt_pins.py" in inside
+ assert any(path.startswith("releases/anchors/") for path in inside), inside
+ off_surface = sorted(
+ path
+ for path in inside
+ if not _matches_surface(path, APPEND_GATE_SPEC.gate_surface)
+ )
+ assert off_surface == [], off_surface
+
+
+APPEND_WORKFLOW = ROOT / ".github" / "workflows" / "thesis-facts-append.yml"
+
+# The flags the workflow starts the judge with, and how it provisions its
+# environment, when the base gate loads its pins by path (the default) and
+# when it still imports them by name (the legacy branch).
+ISOLATED_SYNC = 'uv sync --locked --no-dev --no-install-project --project "$base_gate"'
+ISOLATED_RUN = 'base_gate_python=(uv run --no-sync --project "$base_gate" python -I)'
+LEGACY_SYNC = 'uv sync --locked --no-dev --project "$base_gate"'
+LEGACY_RUN = (
+ 'base_gate_python=(uv run --locked --no-dev --project "$base_gate" python -I)'
+)
+BASE_GATE_START = '"${base_gate_python[@]}" "$base_gate_script"'
+PUSH_SYNC = "uv sync --locked --no-dev --no-install-project\n"
+PUSH_RUN = "uv run --no-sync python -I scripts/check_thesis_facts_append.py"
+
+
+def test_the_gate_surface_covers_the_judges_import_path_and_environment():
+ """What a run cannot show: files that would decide a verdict if added.
+
+ The workflow builds the judge's environment without installing this
+ project and starts it with ``python -I`` and no PYTHONPATH, so neither
+ the base checkout's root nor scripts/ is on its sys.path, and the gate
+ loads its pins by path. The rest of scripts/ therefore stays off the
+ surface, and the catalog builder can ship with the catalog it generates;
+ so does a new module that would shadow an import there or at the root.
+ scripts/sitecustomize.py, the root sitecustomize.py and scripts/__pycache__
+ stay on it for a gate started the older way. The judge's environment
+ comes from the base's own uv project, built with hatchling when a base
+ gate still needs the project, so its inputs are on the surface too, and
+ so is every .gitattributes git applies to a surface file when it checks
+ one out. Both base-gate jobs check the base out with an empty attribute
+ tree, so these reach the judge only when it is checked out with them, as
+ on the push path or in a local run.
+ """
+
+ from receipt.append_gate import _matches_surface
+
+ from scripts.receipt_pins import APPEND_GATE_SPEC
+
+ workflow = APPEND_WORKFLOW.read_text(encoding="utf-8")
+ assert "PYTHONPATH=" not in workflow
+ assert "PYTHONNOUSERSITE" not in workflow
+ # Both base-gate jobs choose one environment, ask --help, and then run one
+ # of two arms; the push path runs the pushed commit's own gate.
+ for line, count in (
+ (ISOLATED_SYNC, 2),
+ (ISOLATED_RUN, 2),
+ (LEGACY_SYNC, 2),
+ (LEGACY_RUN, 2),
+ (BASE_GATE_START, 6),
+ (PUSH_SYNC, 1),
+ (PUSH_RUN, 1),
+ ):
+ assert workflow.count(line) == count, line
+ # Both base-gate jobs check the base out with an empty attribute tree; the
+ # trusted job's candidate keeps its attributes, which refuse it if they
+ # stop its checkout.
+ checkouts = [
+ line.strip()
+ for line in workflow.splitlines()
+ if ("checkout --detach" in line or "actions/checkout" in line)
+ and not line.lstrip().startswith("#")
+ ]
+ assert checkouts == [
+ 'git -C "$candidate" checkout --detach refs/remotes/origin/pr-merge',
+ 'checkout --detach "$BASE_SHA"',
+ "uses: actions/checkout@v4",
+ 'checkout --detach "$base_sha"',
+ ]
+ assert workflow.count(EMPTY_ATTRIBUTE_TREE) == 2
+ # Nothing else sets an attribute source, which would reach the candidate.
+ assert workflow.count("--attr-source") == 2
+ assert "GIT_ATTR_SOURCE" not in workflow
+ assert "attr.tree" not in workflow
+ assert workflow.count(f'git -C "$base_gate"{ATTRIBUTE_SOURCE} \\\n') == 2
+ starts = [
+ line
+ for line in workflow.splitlines()
+ if "check_thesis_facts_append.py" in line and not line.lstrip().startswith("#")
+ ]
+ assert len(starts) == 3, starts
+ ci = (ROOT / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8")
+ assert "uv sync --locked --no-dev --no-install-project\n" in ci
+ assert "uv run --no-sync python -I scripts/verify_release_chain.py --full" in ci
+ assert SHIM.parent.relative_to(ROOT).as_posix() == "scripts"
+ pyproject = (ROOT / "pyproject.toml").read_text(encoding="utf-8")
+ assert 'build-backend = "hatchling.build"' in pyproject
+ assert APPEND_GATE_SPEC.gate_surface == {
+ "scripts/check_thesis_facts_append.py",
+ "scripts/verify_release_chain.py",
+ "scripts/canonical_json.py",
+ "scripts/cut_release_manifest.py",
+ "scripts/receipt_pins.py",
+ "scripts/sitecustomize.py",
+ "sitecustomize.py",
+ "scripts/__pycache__",
+ "scripts/__pycache__/**",
+ ".github/workflows/thesis-facts-append.yml",
+ "pyproject.toml",
+ "uv.lock",
+ "uv.toml",
+ ".python-version",
+ ".python-versions",
+ ".venv",
+ ".venv/**",
+ "hatch.toml",
+ "hatch_build.py",
+ ".gitattributes",
+ "releases/.gitattributes",
+ "scripts/.gitattributes",
+ ".github/.gitattributes",
+ ".github/workflows/.gitattributes",
+ "releases/anchors",
+ "releases/anchors/**",
+ }
+ # Every "dir/**" entry is also listed bare, so dir itself is covered.
+ for pattern in APPEND_GATE_SPEC.gate_surface:
+ if pattern.endswith("/**"):
+ assert pattern[: -len("/**")] in APPEND_GATE_SPEC.gate_surface, pattern
+ # Every .gitattributes above a surface entry is on the surface; one inside
+ # a "dir/**" entry is covered by that entry.
+ for pattern in APPEND_GATE_SPEC.gate_surface:
+ parts = pattern.removesuffix("/**").split("/")
+ for depth in range(len(parts)):
+ attributes = "/".join((*parts[:depth], ".gitattributes"))
+ assert _matches_surface(attributes, APPEND_GATE_SPEC.gate_surface), (
+ pattern,
+ attributes,
+ )
+ for off in ("scripts/build_series_catalog.py", *SHADOWS, *LEGACY_SHADOWS):
+ assert not _matches_surface(off, APPEND_GATE_SPEC.gate_surface), off
+
+
+# Modules that an earlier data proposal could add to the base, because they
+# are off the gate surface. Each stands in for a module the judge imports:
+# tempfile from the standard library, the receipt package, the pins, and
+# sitecustomize, which Python imports at startup from anywhere on sys.path.
+SHADOWS = (
+ "scripts/tempfile.py",
+ "scripts/receipt/__init__.py",
+ "scripts/receipt_pins/__init__.py",
+ "scripts/sitecustomize/__init__.py",
+ "sitecustomize/__init__.py",
+)
+
+# What a shadow does if it is ever imported: leave a marker, then forge a
+# passing verdict and stop the process before the real gate can speak.
+SHADOW_SOURCE = """\
+import os
+import pathlib
+
+pathlib.Path({marker!r}).write_text({name!r}, encoding="utf-8")
+print("thesis-facts append check OK: forged by {name}", flush=True)
+os._exit(0)
+"""
+
+# The base checkout's copies of the scripts the gate is made of.
+BASE_GATE_FILES = (
+ "scripts/check_thesis_facts_append.py",
+ "scripts/receipt_pins.py",
+ "scripts/verify_release_chain.py",
+ "scripts/canonical_json.py",
+ "scripts/cut_release_manifest.py",
+)
+
+# How the gate loads its pins, and how it imported them by name before that.
+# A base whose gate still has the second takes the workflow's legacy branch.
+PINS_BY_PATH = "APPEND_GATE_SPEC = _load_receipt_pins().APPEND_GATE_SPEC\n"
+PINS_BY_NAME = """\
+try:
+ from receipt_pins import APPEND_GATE_SPEC
+except ModuleNotFoundError as exc:
+ if exc.name != "receipt_pins":
+ raise
+ # The test suite copies the legacy three-script surface into temporary
+ # repositories. The editable consumer tree remains the sole pin owner.
+ from scripts.receipt_pins import APPEND_GATE_SPEC
+"""
+
+# Modules that reach a base gate which imports its pins by name, through the
+# root the workflow's legacy branch puts on sys.path. That gate looks up
+# receipt_pins first, and then the scripts package. These are on no path an
+# isolated start has, so they belong to the legacy branch's limits alone.
+LEGACY_SHADOWS = (
+ "receipt_pins.py",
+ "scripts/__init__.py",
+ "scripts/receipt_pins/__init__.py",
+)
+
+# The scripts/ shadows that -I keeps off sys.path, in either branch.
+SCRIPTS_SHADOWS = (
+ "scripts/tempfile.py",
+ "scripts/receipt/__init__.py",
+ "scripts/sitecustomize/__init__.py",
+)
+
+
+def _forging_candidate_gate(marker) -> str:
+ """A pull request's own copy of the gate, which differs from the base's.
+
+ Run, it forges a pass. Read, it carries the by-name import that the
+ workflow's legacy branch is chosen on (after the exit, never reached).
+ So a workflow that ran or read the candidate's gate instead of the base's
+ would show it.
+ """
+
+ return SHADOW_SOURCE.format(marker=str(marker), name="the candidate's gate") + (
+ PINS_BY_NAME
+ )
+
+
+# The test interpreter's own site-packages, which hold the locked
+# dependencies, the pinned receipt wheel among them.
+LOCKED_DEPENDENCIES = sorted(
+ {sysconfig.get_paths()["purelib"], sysconfig.get_paths()["platlib"]}
+)
+
+# Stands in for uv inside the workflow's own step scripts, with a real
+# virtual environment at /.venv, where uv puts it.
+# - ``uv sync`` creates the environment. Its locked dependencies are this
+# interpreter's site-packages, listed as plain paths in a .pth file, so
+# Python does not read the .pth files inside them (this repository's own
+# editable install among them). Without --no-install-project it also does
+# what hatchling's editable install does: a .pth file that appends the
+# project root to sys.path.
+# - ``uv run`` without --no-sync syncs first, which installs the project the
+# same way. It then starts the environment's python with exactly the
+# arguments after ``python`` and the environment the step gave it, which is
+# all that uv run adds to the judge's command line.
+# Every call is logged. Before an isolated start (--no-sync and -I), the
+# environment's python, with the same flags, also records the sys.path the
+# judge will see.
+FAKE_UV = """\
+#!{python} -I
+import json
+import os
+import pathlib
+import subprocess
+import sys
+
+arguments = sys.argv[1:]
+project = pathlib.Path(
+ arguments[arguments.index("--project") + 1]
+ if "--project" in arguments
+ else os.getcwd()
+)
+judge = project / ".venv" / "bin" / "python"
+
+
+def site_packages():
+ (found,) = (project / ".venv" / "lib").glob("python3.*/site-packages")
+ return found
+
+
+def install_project():
+ (site_packages() / "_editable_impl_project.pth").write_text(
+ f"{{project}}\\n", encoding="utf-8"
+ )
+
+
+record = {{"argv": arguments, "cwd": os.getcwd()}}
+if arguments[0] == "sync":
+ if not judge.exists():
+ subprocess.run(
+ [{python!r}, "-I", "-m", "venv", "--without-pip", str(project / ".venv")],
+ check=True,
+ )
+ (site_packages() / "_locked_dependencies.pth").write_text(
+ "".join(f"{{path}}\\n" for path in {dependencies!r}), encoding="utf-8"
+ )
+ if "--no-install-project" not in arguments:
+ install_project()
+else:
+ assert arguments[0] == "run", arguments
+ if "--no-sync" not in arguments:
+ install_project()
+ command = arguments[arguments.index("python") + 1 :]
+ flags = command[: next(i for i, a in enumerate(command) if not a.startswith("-"))]
+ if "--no-sync" in arguments and "-I" in flags:
+ probe = subprocess.run(
+ [str(judge), *flags, "-c", "import json, sys; print(json.dumps(sys.path))"],
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ record["sys_path"] = json.loads(probe.stdout)
+with open({log!r}, "a", encoding="utf-8") as handle:
+ handle.write(json.dumps(record) + "\\n")
+if arguments[0] == "run":
+ os.execv(str(judge), [str(judge), *command])
+"""
+
+TRUSTED_STEP = "Judge the PR merge tree with the base gate"
+PULL_REQUEST_STEP = "Enforce append-only ledger invariants"
+PULL_REQUEST_NUMBER = "7"
+
+
+def _workflow_step_script(step_name: str, workflow=APPEND_WORKFLOW) -> str:
+ """Return one step's ``run: |`` block from a workflow, dedented."""
+
+ lines = workflow.read_text(encoding="utf-8").splitlines()
+ start = [
+ i for i, line in enumerate(lines) if line.strip() == f"- name: {step_name}"
+ ]
+ assert len(start) == 1, step_name
+ run = next(
+ i for i in range(start[0] + 1, len(lines)) if lines[i].strip() == "run: |"
+ )
+ assert not any(
+ line.strip().startswith("- name:") for line in lines[start[0] + 1 : run]
+ ), step_name
+ key_indent = len(lines[run]) - len(lines[run].lstrip())
+ body = []
+ for line in lines[run + 1 :]:
+ if line.strip() and len(line) - len(line.lstrip()) <= key_indent:
+ break
+ body.append(line)
+ indent = min(len(line) - len(line.lstrip()) for line in body if line.strip())
+ return "\n".join(line[indent:] for line in body).rstrip() + "\n"
+
+
+def _gate_that_imports_its_pins_by_name() -> str:
+ """The gate as it was before it loaded its pins by path."""
+
+ source = SHIM.read_text(encoding="utf-8")
+ assert source.count(PINS_BY_PATH) == 1
+ return source.replace(PINS_BY_PATH, PINS_BY_NAME)
+
+
+def _install_base_gate(shadows, marker, *, pins_by_name=False):
+ """Return a ``prepare`` that puts the gate and the shadows into the base."""
+
+ def prepare(root: pathlib.Path) -> None:
+ for relative in BASE_GATE_FILES:
+ destination = root / relative
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(ROOT / relative, destination)
+ if pins_by_name:
+ (root / "scripts" / "check_thesis_facts_append.py").write_text(
+ _gate_that_imports_its_pins_by_name(), encoding="utf-8"
+ )
+ for relative in shadows:
+ path = root / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ SHADOW_SOURCE.format(marker=str(marker), name=relative),
+ encoding="utf-8",
+ )
+
+ return prepare
+
+
+def _rewrite_the_first_frozen_row(root: pathlib.Path) -> None:
+ ledger = root / LEDGER_RELATIVE
+ rows = ledger.read_bytes().splitlines(keepends=True)
+ rows[0] = b" " + rows[0]
+ ledger.write_bytes(b"".join(rows))
+
+
+def _base_with_a_refused_candidate(
+ tmp_path, shadows, marker, *, pins_by_name=False, candidate_gate=None
+):
+ """A base holding the gate and the shadows, and a candidate it must refuse.
+
+ The candidate rewrites a frozen row, which every workflow path refuses,
+ with or without a base to compare against. With ``candidate_gate``, the
+ candidate also replaces its own copy of the gate with that source.
+ """
+
+ clone, _ = _replay_current_state(tmp_path)
+ _install_base_gate(shadows, marker, pins_by_name=pins_by_name)(clone)
+ base = _commit(clone, "base with the gate and a shadowing module")
+ _rewrite_the_first_frozen_row(clone)
+ if candidate_gate is not None:
+ (clone / "scripts" / "check_thesis_facts_append.py").write_text(
+ candidate_gate, encoding="utf-8"
+ )
+ candidate = _commit(clone, "rewrite a frozen row")
+ return clone, base, candidate
+
+
+def _fake_uv(tmp_path):
+ """Write the fake uv; return the directory holding it and its call log."""
+
+ fake_bin = tmp_path / "fake-bin"
+ fake_bin.mkdir()
+ log = tmp_path / "uv-calls.jsonl"
+ uv = fake_bin / "uv"
+ uv.write_text(
+ FAKE_UV.format(
+ python=sys.executable, log=str(log), dependencies=LOCKED_DEPENDENCIES
+ ),
+ encoding="utf-8",
+ )
+ uv.chmod(0o755)
+ return fake_bin, log
+
+
+def _run_workflow_step(tmp_path, clone, base, candidate, path, edit=None):
+ """Run the workflow's own step script for one path, as GitHub would.
+
+ The repository is served from a local bare clone at the URL the step
+ builds from GITHUB_SERVER_URL and GITHUB_REPOSITORY, with the pull request
+ merge ref the trusted job fetches. PYTHONPATH is set to the scripts
+ directory the judge runs from, as a hostile runner might set it. A control
+ passes ``edit`` to change the step script before it runs. Returns the
+ completed step, the logged uv calls, and the checkout the judge ran from.
+ """
+
+ merge = _git(
+ clone,
+ "commit-tree",
+ f"{candidate}^{{tree}}",
+ "-p",
+ base,
+ "-p",
+ candidate,
+ "-m",
+ "synthetic pull request merge",
+ )
+ pull_ref = f"refs/pull/{PULL_REQUEST_NUMBER}/merge"
+ server = tmp_path / "server"
+ remote = server / "PolicyEngine" / "chronicle.git"
+ remote.parent.mkdir(parents=True)
+ _git(clone, "update-ref", pull_ref, merge)
+ _git(tmp_path, "clone", "--quiet", "--mirror", str(clone), str(remote))
+ _git(clone, "update-ref", "-d", pull_ref)
+ _git(remote, "config", "uploadpack.allowAnySHA1InWant", "true")
+
+ fake_bin, log = _fake_uv(tmp_path)
+ runner = tmp_path / "runner"
+ runner.mkdir()
+ (tmp_path / "tmp").mkdir()
+ environment = {
+ name: value
+ for name, value in os.environ.items()
+ if not name.startswith(("GIT_", "PYTHON", "UV_", "VIRTUAL_ENV"))
+ }
+ environment.update(
+ {
+ "PATH": f"{fake_bin}{os.pathsep}{os.environ['PATH']}",
+ "GIT_CONFIG_GLOBAL": "/dev/null",
+ "GIT_CONFIG_NOSYSTEM": "1",
+ "GITHUB_SERVER_URL": f"file://{server}",
+ "GITHUB_REPOSITORY": "PolicyEngine/chronicle",
+ "RUNNER_TEMP": str(runner),
+ "TMPDIR": str(tmp_path / "tmp"),
+ # Untranslated messages from git, which the controls match.
+ "LC_ALL": "C",
+ }
+ )
+ base_gate = runner / "thesis-facts-base-gate"
+ if path == "pull_request_target":
+ script = _workflow_step_script(TRUSTED_STEP)
+ environment.update(
+ {
+ "BASE_SHA": base,
+ "EVENT_MERGE_SHA": "",
+ "PR_NUMBER": PULL_REQUEST_NUMBER,
+ }
+ )
+ workspace = tmp_path / "workspace"
+ workspace.mkdir()
+ judge_root = base_gate
+ else:
+ script = _workflow_step_script(PULL_REQUEST_STEP)
+ expressions = {
+ "${{ github.event_name }}": path,
+ "${{ github.event.pull_request.base.sha }}": base,
+ }
+ assert set(re.findall(r"\$\{\{[^}]*\}\}", script)) == set(expressions)
+ for expression, value in expressions.items():
+ script = script.replace(expression, value)
+ workspace = clone
+ environment["GITHUB_WORKSPACE"] = str(clone)
+ environment["GITHUB_SHA"] = candidate
+ judge_root = base_gate if path == "pull_request" else clone
+ environment["PYTHONPATH"] = str(judge_root / "scripts")
+ if edit is not None:
+ script = edit(script)
+ step = tmp_path / "step.sh"
+ step.write_text(script, encoding="utf-8")
+
+ completed = subprocess.run(
+ ["bash", "--noprofile", "--norc", "-eo", "pipefail", str(step)],
+ cwd=workspace,
+ env=environment,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ lines = log.read_text(encoding="utf-8").splitlines() if log.exists() else []
+ calls = [json.loads(line) for line in lines]
+ return completed, calls, judge_root
+
+
+def _started_scripts(starts):
+ """The script each logged ``uv run`` started, resolved against its cwd."""
+
+ scripts = []
+ for start in starts:
+ argv = start["argv"]
+ command = argv[argv.index("python") + 1 :]
+ operand = next(argument for argument in command if not argument.startswith("-"))
+ scripts.append(os.path.realpath(os.path.join(start["cwd"], operand)))
+ return scripts
+
+
+def _assert_every_start_is_isolated(
+ calls, expected_starts, judge_root, script="check_thesis_facts_append.py"
+):
+ """The environment lacks the project, and each start is ``python -I``.
+
+ Each start runs the judging checkout's own copy of the script. The judge's
+ sys.path then holds the standard library, its environment's site-packages
+ and the locked dependencies, and nothing else: not the checkout's root,
+ not its scripts/, and not this repository.
+ """
+
+ syncs = [call["argv"] for call in calls if call["argv"][0] == "sync"]
+ starts = [call for call in calls if call["argv"][0] == "run"]
+ assert len(syncs) == 1, calls
+ assert "--no-install-project" in syncs[0], syncs
+ assert len(starts) == expected_starts, calls
+ expected_script = os.path.realpath(judge_root / "scripts" / script)
+ assert _started_scripts(starts) == [expected_script] * expected_starts, calls
+ (judge_site,) = (judge_root / ".venv" / "lib").glob("python3.*/site-packages")
+ allowed = {os.path.realpath(p) for p in (judge_site, *LOCKED_DEPENDENCIES)}
+ standard_library = os.path.realpath(sys.base_prefix) + os.sep
+ for start in starts:
+ argv = start["argv"]
+ assert "--no-sync" in argv, argv
+ assert argv[argv.index("python") + 1] == "-I", argv
+ seen = [os.path.realpath(entry) for entry in start["sys_path"]]
+ unexpected = [
+ entry
+ for entry in seen
+ if entry not in allowed and not entry.startswith(standard_library)
+ ]
+ assert unexpected == [], unexpected
+ for entry in (ROOT, judge_root, judge_root / "scripts"):
+ assert os.path.realpath(entry) not in seen, entry
+ assert not list(judge_site.glob("_editable_impl_*.pth"))
+
+
+def _assert_the_legacy_branch_ran(calls, expected_starts, judge_root):
+ """The environment installs the project, as before, and each start is -I.
+
+ Each start runs the judging checkout's own copy of the gate.
+ """
+
+ syncs = [call["argv"] for call in calls if call["argv"][0] == "sync"]
+ starts = [call for call in calls if call["argv"][0] == "run"]
+ assert len(syncs) == 1, calls
+ assert "--no-install-project" not in syncs[0], syncs
+ assert len(starts) == expected_starts, calls
+ expected_script = os.path.realpath(
+ judge_root / "scripts" / "check_thesis_facts_append.py"
+ )
+ assert _started_scripts(starts) == [expected_script] * expected_starts, calls
+ for start in starts:
+ argv = start["argv"]
+ assert "--no-sync" not in argv, argv
+ assert argv[argv.index("python") + 1] == "-I", argv
+
+
+WORKFLOW_STEP_PATHS = {
+ # The --help question and the judge for each base-gate job; the push
+ # path runs the pushed commit's own gate once.
+ "pull_request_target": 2,
+ "pull_request": 2,
+ "push": 1,
+}
+BASE_GATE_PATHS = ("pull_request_target", "pull_request")
+
+
+@pytest.mark.parametrize("path", WORKFLOW_STEP_PATHS)
+@pytest.mark.parametrize("shadow", SHADOWS)
+def test_a_module_that_shadows_a_gate_import_cannot_change_the_verdict(
+ tmp_path, shadow, path
+):
+ """A shadow in the base's scripts/ or at its root never runs.
+
+ The shadow would forge a pass. The workflow's own step script builds the
+ judge's environment without the project and starts the gate, --help
+ question included, with ``python -I``, so the shadow is never imported and
+ the gate refuses the candidate as it would without it. Each shadow does
+ run when its way in is open; see the controls below.
+
+ On a pull request the candidate's own copy of the gate also differs from
+ the base's: it would forge a pass if run, and would steer the workflow
+ into its legacy branch if read. The base's gate judges, so neither
+ happens, and the candidate's change to it is refused as mixed.
+ """
+
+ marker = tmp_path / "the-shadow-ran"
+ candidate_marker = tmp_path / "the-candidate-gate-ran"
+ clone, base, candidate = _base_with_a_refused_candidate(
+ tmp_path,
+ (shadow,),
+ marker,
+ candidate_gate=(
+ None if path == "push" else _forging_candidate_gate(candidate_marker)
+ ),
+ )
+
+ completed, calls, judge_root = _run_workflow_step(
+ tmp_path, clone, base, candidate, path
+ )
+
+ assert completed.returncode == 1, completed.stdout + completed.stderr
+ assert not marker.exists()
+ assert not candidate_marker.exists()
+ assert "forged" not in completed.stdout
+ assert FAILED in completed.stderr
+ _assert_every_start_is_isolated(calls, WORKFLOW_STEP_PATHS[path], judge_root)
+ assert not list((tmp_path / "tmp").glob("thesis-facts-gate-*"))
+
+
+@pytest.mark.parametrize("path", WORKFLOW_STEP_PATHS)
+def test_a_true_append_beside_shadowing_modules_is_accepted(tmp_path, path):
+ """Isolation costs nothing: the witnessed append still passes, by name."""
+
+ marker = tmp_path / "the-shadow-ran"
+ clone, base, candidate = _replay_latest_release(
+ tmp_path, prepare=_install_base_gate(SHADOWS, marker)
+ )
+
+ completed, calls, judge_root = _run_workflow_step(
+ tmp_path, clone, base, candidate, path
+ )
+
+ assert completed.returncode == 0, completed.stdout + completed.stderr
+ assert not marker.exists()
+ assert "forged" not in completed.stdout
+ if path == "push":
+ assert "thesis-facts append check OK:" in completed.stdout
+ assert _subject_line(clone, candidate, None) in completed.stdout
+ else:
+ assert APPEND_GATE_OK in completed.stdout
+ _assert_every_start_is_isolated(calls, WORKFLOW_STEP_PATHS[path], judge_root)
+ assert not list((tmp_path / "tmp").glob("thesis-facts-gate-*"))
+
+
+@pytest.mark.parametrize("path", BASE_GATE_PATHS)
+@pytest.mark.parametrize("verdict", ["refused", "accepted"])
+def test_a_base_gate_that_imports_its_pins_by_name_still_judges(
+ tmp_path, verdict, path
+):
+ """The new workflow with an older base gate: the order the two land in.
+
+ A base gate that imports its pins by name finds them only through the
+ root, so the workflow installs the project for it, and it judges as
+ before. Pull requests into a base that predates this one meet that
+ pairing, this one's own included. The start is still ``python -I``, so
+ the shadows in the base's scripts/ stay off sys.path in this branch too.
+
+ The refused candidate's own gate loads its pins by path. Had the
+ workflow chosen the branch from the candidate's copy, it would have
+ taken the isolated one, where the base's older gate cannot start.
+ """
+
+ marker = tmp_path / "the-shadow-ran"
+ if verdict == "refused":
+ clone, base, candidate = _base_with_a_refused_candidate(
+ tmp_path,
+ SCRIPTS_SHADOWS,
+ marker,
+ pins_by_name=True,
+ candidate_gate=SHIM.read_text(encoding="utf-8"),
+ )
+ else:
+ clone, base, candidate = _replay_latest_release(
+ tmp_path,
+ prepare=_install_base_gate(SCRIPTS_SHADOWS, marker, pins_by_name=True),
+ )
+
+ completed, calls, judge_root = _run_workflow_step(
+ tmp_path, clone, base, candidate, path
+ )
+
+ if verdict == "refused":
+ assert completed.returncode == 1, completed.stdout + completed.stderr
+ assert FAILED in completed.stderr
+ else:
+ assert completed.returncode == 0, completed.stdout + completed.stderr
+ assert APPEND_GATE_OK in completed.stdout
+ assert not marker.exists()
+ assert "forged" not in completed.stdout
+ _assert_the_legacy_branch_ran(calls, WORKFLOW_STEP_PATHS[path], judge_root)
+
+
+def _standard_library_has_sitecustomize() -> bool:
+ """Whether this interpreter ships a sitecustomize of its own.
+
+ Debian and Ubuntu builds do (their CI runners' /usr/bin/python3 among
+ them), and some others. Theirs comes first on sys.path, so a sitecustomize
+ elsewhere is never imported.
+ """
+
+ code = (
+ "import importlib.util, sys; "
+ "sys.exit(importlib.util.find_spec('sitecustomize') is None)"
+ )
+ probe = subprocess.run([sys.executable, "-I", "-S", "-c", code], check=False)
+ return probe.returncode == 0
+
+
+@pytest.mark.parametrize("shadow", LEGACY_SHADOWS + ("sitecustomize/__init__.py",))
+def test_a_base_gate_that_imports_its_pins_by_name_keeps_its_limits(tmp_path, shadow):
+ """The control for the shadows that need the project installed.
+
+ The workflow's legacy branch, which a base gate that imports its pins by
+ name takes, puts the base root on sys.path, last. The old gate looks up
+ receipt_pins there first and then the scripts package, so a root
+ receipt_pins.py, a scripts/__init__.py or a scripts/receipt_pins/
+ package stands in for its pins, and a root sitecustomize/ package runs at
+ startup where the interpreter has no sitecustomize of its own. Each
+ forges a pass. None of them is on any path an isolated start has.
+ """
+
+ if shadow.startswith("sitecustomize/") and _standard_library_has_sitecustomize():
+ pytest.skip("this interpreter's own sitecustomize comes first on sys.path")
+ marker = tmp_path / "the-shadow-ran"
+ clone, base, candidate = _base_with_a_refused_candidate(
+ tmp_path, (shadow,), marker, pins_by_name=True
+ )
+
+ completed, calls, judge_root = _run_workflow_step(
+ tmp_path, clone, base, candidate, "pull_request_target"
+ )
+
+ assert completed.returncode == 0, completed.stdout + completed.stderr
+ assert marker.read_text(encoding="utf-8") == shadow
+ assert f"forged by {shadow}" in completed.stdout
+ _assert_the_legacy_branch_ran(calls, 2, judge_root)
+
+
+@pytest.mark.parametrize("shadow", SCRIPTS_SHADOWS)
+def test_the_same_shadow_runs_when_scripts_is_on_the_path(tmp_path, shadow):
+ """The control for the shadows that need scripts/ on the path.
+
+ Started the way the workflow started the gate before ``-I``, from an
+ environment without the project but with the script's directory as
+ sys.path[0] and on PYTHONPATH, the same base tree runs the shadow, and the
+ forged pass replaces the refusal.
+ """
+
+ marker = tmp_path / "the-shadow-ran"
+ clone, base, candidate = _base_with_a_refused_candidate(tmp_path, (shadow,), marker)
+ fake_bin, _ = _fake_uv(tmp_path)
+ subprocess.run(
+ [str(fake_bin / "uv"), "sync", "--no-install-project", "--project", clone],
+ check=True,
+ )
+ environment = {
+ name: value
+ for name, value in os.environ.items()
+ if not name.startswith(("PYTHON", "VIRTUAL_ENV"))
+ }
+ environment["PYTHONPATH"] = str(clone / "scripts")
+
+ completed = subprocess.run(
+ [
+ str(clone / ".venv" / "bin" / "python"),
+ str(clone / "scripts" / "check_thesis_facts_append.py"),
+ "--root",
+ str(clone),
+ "--commit",
+ candidate,
+ "--base-ref",
+ base,
+ ],
+ cwd=tmp_path,
+ env=environment,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+ assert completed.returncode == 0, completed.stdout + completed.stderr
+ assert marker.read_text(encoding="utf-8") == shadow
+ assert completed.stdout == f"thesis-facts append check OK: forged by {shadow}\n"
+
+
+CI_WORKFLOW = ROOT / ".github" / "workflows" / "ci.yml"
+CI_VERIFY_STEP = "Verify witnessed release chain"
+
+
+def test_ci_verifies_the_release_chain_isolated_beside_shadowing_modules(tmp_path):
+ """ci.yml's own verifier step, run as GitHub would, never runs a shadow.
+
+ The step builds its environment without the project and starts
+ verify_release_chain.py with ``python -I``, so neither the root nor
+ scripts/ is on its sys.path, and the chain still verifies.
+ """
+
+ marker = tmp_path / "the-shadow-ran"
+ clone, _ = _replay_current_state(tmp_path)
+ _install_base_gate(SHADOWS, marker)(clone)
+ head = _commit(clone, "the current state beside shadowing modules")
+ fake_bin, log = _fake_uv(tmp_path)
+ script = _workflow_step_script(CI_VERIFY_STEP, CI_WORKFLOW)
+ assert "${{" not in script
+ step = tmp_path / "step.sh"
+ step.write_text(script, encoding="utf-8")
+ (tmp_path / "tmp").mkdir()
+ environment = {
+ name: value
+ for name, value in os.environ.items()
+ if not name.startswith(("GIT_", "PYTHON", "UV_", "VIRTUAL_ENV"))
+ }
+ environment.update(
+ {
+ "PATH": f"{fake_bin}{os.pathsep}{os.environ['PATH']}",
+ "GIT_CONFIG_GLOBAL": "/dev/null",
+ "GIT_CONFIG_NOSYSTEM": "1",
+ "GITHUB_SHA": head,
+ "PYTHONPATH": str(clone / "scripts"),
+ "TMPDIR": str(tmp_path / "tmp"),
+ }
+ )
+
+ completed = subprocess.run(
+ ["bash", "--noprofile", "--norc", "-eo", "pipefail", str(step)],
+ cwd=clone,
+ env=environment,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+ assert completed.returncode == 0, completed.stdout + completed.stderr
+ assert completed.stdout.startswith("release chain OK: "), completed.stdout
+ assert not marker.exists()
+ calls = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()]
+ _assert_every_start_is_isolated(calls, 1, clone, script="verify_release_chain.py")
+
+
+# A .gitattributes in a base, and what it does to a checkout of that base made
+# with its attributes:
+# - "stops": a boolean working-tree-encoding stops git's checkout partway,
+# with exit 128. Two pull requests that each pass alone merge into this base:
+# one adds the attribute, the other the file it names.
+# - "rewrites": an encoding on the gate's scripts rewrites the code the judge
+# runs, so it cannot start. Receipt refuses a proposal that adds this, so it
+# needs a direct push.
+# - "anchors": eol=crlf on the trust anchors rewrites the bytes the gate pins,
+# so the gate refuses every append. Receipt does not refuse eol, so a
+# gate-only proposal can add this.
+# For the first two the candidate is the pull request that removes the file
+# again: the base gate judges it on the data path, or names it as a gate-only
+# proposal. For "anchors" the candidate is the witnessed append, which keeps
+# the file.
+BASE_ATTRIBUTES = {
+ "stops": ("docs/.gitattributes", "notes.txt working-tree-encoding\n"),
+ "rewrites": ("scripts/.gitattributes", "*.py working-tree-encoding=UTF-16LE\n"),
+ "anchors": ("releases/.gitattributes", "anchors/* text eol=crlf\n"),
+}
+BASE_ATTRIBUTES_STOP = {
+ "stops": "true/false are no valid working-tree-encodings",
+ "rewrites": "source code cannot contain null bytes",
+ "anchors": "anchor bytes are not code-pinned",
+}
+ATTRIBUTE_SOURCE = ' --attr-source="$empty_tree"'
+EMPTY_ATTRIBUTE_TREE = (
+ 'empty_tree="$(git -C "$base_gate" hash-object -t tree /dev/null)"'
+)
+
+
+def _commit_index_edit(root, tmp_path, parent, message, *, add=None, remove=()):
+ """Commit ``parent`` with index entries added or removed, by plumbing.
+
+ ``git add`` and ``git commit`` read the attributes they would commit, and
+ stop on the ones under test, so the tree is written from the index and the
+ working tree is left as it was.
+ """
+
+ _git(root, "read-tree", parent)
+ for relative, text in (add or {}).items():
+ source = tmp_path / "attribute-blob"
+ source.write_text(text, encoding="utf-8")
+ blob = _git(root, "hash-object", "-w", "--no-filters", str(source))
+ source.unlink()
+ _git(root, "update-index", "--add", "--cacheinfo", f"100644,{blob},{relative}")
+ for relative in remove:
+ _git(root, "update-index", "--force-remove", relative)
+ tree = _git(root, "write-tree")
+ commit = _git(root, "commit-tree", tree, "-p", parent, "-m", message)
+ _git(root, "update-ref", "HEAD", commit)
+ return commit
+
+
+def _base_with_attributes(tmp_path, hazard):
+ """A base holding the gate and one .gitattributes, and the candidate."""
+
+ relative, text = BASE_ATTRIBUTES[hazard]
+ if hazard == "anchors":
+
+ def prepare(root: pathlib.Path) -> None:
+ _install_base_gate((), tmp_path / "unused-marker")(root)
+ (root / relative).write_text(text, encoding="utf-8")
+
+ clone, base, candidate = _replay_latest_release(tmp_path, prepare=prepare)
+ return clone, base, candidate, relative
+ clone, _ = _replay_current_state(tmp_path)
+ _install_base_gate((), tmp_path / "unused-marker")(clone)
+ (clone / "docs").mkdir()
+ (clone / "docs" / "notes.txt").write_text("notes\n", encoding="utf-8")
+ gate = _commit(clone, "the gate and a note")
+ base = _commit_index_edit(
+ clone, tmp_path, gate, f"merge {relative}", add={relative: text}
+ )
+ candidate = _commit_index_edit(
+ clone, tmp_path, base, f"remove {relative}", remove=(relative,)
+ )
+ return clone, base, candidate, relative
+
+
+def _committed_bytes(root: pathlib.Path, relative: str) -> bytes:
+ """The bytes of ``relative`` in the commit checked out at ``root``."""
+
+ environment = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
+ environment.update({"GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1"})
+ return subprocess.run(
+ ["git", "cat-file", "blob", f"HEAD:{relative}"],
+ cwd=root,
+ env=environment,
+ capture_output=True,
+ check=True,
+ ).stdout
+
+
+@pytest.mark.parametrize("path", BASE_GATE_PATHS)
+@pytest.mark.parametrize("hazard", BASE_ATTRIBUTES)
+def test_a_gitattributes_in_the_base_cannot_stop_or_rewrite_the_base_gate(
+ tmp_path, hazard, path
+):
+ """The base gate is checked out as committed, whatever its attributes say.
+
+ Both base-gate jobs check the base out with an empty attribute tree, so a
+ .gitattributes in it, on the gate surface or off it, neither stops the
+ checkout nor rewrites a file the gate runs from or pins. The pull request
+ that removes the file, or an append beside it, is judged as any other
+ would be.
+ """
+
+ clone, base, candidate, relative = _base_with_attributes(tmp_path, hazard)
+
+ completed, calls, judge_root = _run_workflow_step(
+ tmp_path, clone, base, candidate, path
+ )
+
+ assert completed.returncode == 0, completed.stdout + completed.stderr
+ verdict = completed.stdout.splitlines()[0]
+ if hazard == "stops":
+ assert verdict.startswith("thesis-facts append check OK: "), verdict
+ assert ", +0 appended vs base, release " in verdict, verdict
+ elif hazard == "anchors":
+ assert APPEND_GATE_OK in completed.stdout
+ else:
+ assert verdict == (
+ "thesis-facts append check OK: gate-only proposal; DATA_SURFACE "
+ f"unchanged; GATE_SURFACE changes={[relative]!r}"
+ )
+ assert (judge_root / relative).read_bytes() == _committed_bytes(
+ judge_root, relative
+ )
+ anchors = [
+ f"releases/anchors/{anchor.name}"
+ for anchor in (judge_root / "releases" / "anchors").iterdir()
+ ]
+ assert anchors
+ for checked_out in (*BASE_GATE_FILES, *anchors):
+ assert (judge_root / checked_out).read_bytes() == _committed_bytes(
+ judge_root, checked_out
+ ), checked_out
+ _assert_every_start_is_isolated(calls, WORKFLOW_STEP_PATHS[path], judge_root)
+
+
+@pytest.mark.parametrize("hazard", BASE_ATTRIBUTES)
+def test_the_same_attributes_stop_a_base_gate_checked_out_with_them(tmp_path, hazard):
+ """The control: the trusted job, checking the base out with its attributes.
+
+ The same base and candidate, with the empty attribute tree taken out of
+ the step, stop the job: git refuses the checkout, Python the rewritten
+ gate, or the gate the rewritten anchors. For the first two, every later
+ pull request into this base stops the same way, the one that removes the
+ file included; for the anchors, every later append.
+ """
+
+ clone, base, candidate, _ = _base_with_attributes(tmp_path, hazard)
+
+ def with_attributes(script: str) -> str:
+ assert script.count(ATTRIBUTE_SOURCE) == 1
+ return script.replace(ATTRIBUTE_SOURCE, "")
+
+ completed, calls, _ = _run_workflow_step(
+ tmp_path, clone, base, candidate, "pull_request_target", with_attributes
+ )
+
+ assert completed.returncode != 0
+ assert "OK" not in completed.stdout
+ assert BASE_ATTRIBUTES_STOP[hazard] in completed.stderr, completed.stderr
+ if hazard == "stops":
+ assert calls == []
+
+
def test_the_scratch_directory_is_private_to_the_run(tmp_path):
"""The private directory is created 0700, and the shim asserts that it was.