ra8-firmware 0.1.0
Bare-metal firmware for the Renesas RA8 family (RA8D2 / RA8P1)
Loading...
Searching...
No Matches
hook_transport_support.py
Go to the documentation of this file.
1# SPDX-License-Identifier: MIT
2# Copyright (c) 2026 Brighton Sikarskie
3"""Focused transport fixtures shared by the hook-parity selftest."""
4
5from __future__ import annotations
6
7from collections.abc import Callable
8from pathlib import Path
9from typing import Any
10
11from scripts.dev.git_environment import sanitized_git_environment
12
13
14def _write(path: Path, text: str, *, executable: bool = False) -> None:
15 """Write one private fixture file."""
16 path.parent.mkdir(parents=True, exist_ok=True)
17 path.write_text(text, encoding="utf-8")
18 if executable:
19 path.chmod(0o755)
20
21
22def transport_gate_text() -> str:
23 """Return the real-Just fixture gate used to exercise owner transport."""
24 return """#!/bin/bash -p
25set -euo pipefail
26[[ "${RA8_TRANSPORT_FIXTURE:-0}" == "1" && -f policy-mode ]] || exit 64
27mode="$(<policy-mode)"
28case "$mode" in
29 success)
30 [[ "$PATH" == *":${RA8_SELFTEST_VENV_BIN:?}:"* ]]
31 ;;
32 inspect)
33 [[ -f "path with spaces/added.txt" && ! -e delete-me && ! -e resurrect-me ]]
34 [[ -x mode.sh && -L alias && "$(readlink alias)" == link-target ]]
35 [[ -f ignored-dir/tracked.txt && ! -e untracked.txt && "${OLDPWD:-}" == "$PWD" ]]
36 ;;
37 failure) exit 42 ;;
38 hang)
39 printf 'ready\\n' >"${RA8_SELFTEST_READY:?}"
40 trap 'exit 0' HUP INT QUIT TERM
41 sleep 60
42 printf 'continued\\n' >"${RA8_SELFTEST_CONTINUED:?}"
43 ;;
44 *) exit 64 ;;
45esac
46"""
47
48
49def write_transport_justfiles(root: Path) -> None:
50 """Install a minimal real-Just module graph around the audited recipe."""
51 root_just = """set shell := ["/bin/bash", "-puc"]
52export BASH_ENV := "/dev/null"
53export ENV := "/dev/null"
54export PYTHONHOME := ""
55export PYTHONPATH := ""
56mod git_hooks "just/hooks.just"
57mod quality "quality.just"
58hooks:
59 /bin/bash -p scripts/git/install-hooks.sh
60"""
61 quality = 'set working-directory := "."\nmod local "quality_local.just"\n'
62 quality_local = """set working-directory := "."
63gate name:
64 /bin/bash -p fixture/bin/transport_gate.sh "{{ name }}"
65"""
66 _write(root / "justfile", root_just)
67 _write(root / "quality.just", quality)
68 _write(root / "quality_local.just", quality_local)
69 _write(root / "fixture/bin/transport_gate.sh", transport_gate_text(), executable=True)
70 for name in (
71 "check_mcdc_block.py",
72 "check_new_compound_has_mcdc.py",
73 "check_obsolete_standards.py",
74 ):
75 _write(
76 root / f"scripts/checks/{name}",
77 "#!/usr/bin/python3\nraise SystemExit(0)\n",
78 executable=True,
79 )
80
81
82def install_venv_wrappers(root: Path, marker: Path) -> None:
83 """Install ignored mutable owner-tool wrappers that must not run."""
84 # bash and just only. A python3 wrapper cannot prove anything here: the
85 # candidate policy is deliberately allowed to use the ignored .venv after
86 # immutable validation, so the marker would fire on designed behaviour.
87 # The owner-side property is pinned structurally instead -- see the
88 # OWNER_PYTHON tokens in check_hook_parity._check_snapshot_dispatch.
89 for name, target in (
90 ("bash", "/bin/bash -p"),
91 ("just", "just"),
92 ):
93 text = f'#!/bin/sh\nprintf "invoked\\n" >>"$RA8_SELFTEST_VENV"\nexec {target} "$@"\n'
94 _write(root / f".venv/bin/{name}", text, executable=True)
95 marker.unlink(missing_ok=True)
96
97
98def transport_environment(_base: Path, root: Path) -> dict[str, str]:
99 """Return the production-like environment for one transport fixture."""
100 environment = sanitized_git_environment()
101 environment["RA8_TRANSPORT_FIXTURE"] = "1"
102 environment["RA8_SELFTEST_VENV_BIN"] = str(root / ".venv/bin")
103 return environment
104
105
106def run_bootstrap_validator_case(
107 base: Path,
108 callbacks: tuple[Callable[..., Any], ...],
109) -> None:
110 """Prove an older HEAD permits only an exact 6/27 policy population."""
111 make_fixture, git, source_state, run_owner, fail = callbacks
112 root, temp_root = base / "bootstrap", base / "bootstrap-tmp"
113 root.mkdir()
114 temp_root.mkdir()
115 make_fixture(root, "success", "success")
116 validator = root / "scripts/dev/git_environment.py"
117 current = validator.read_text(encoding="utf-8")
118 legacy = current.replace('"--check-attributes"', '"--check-" "attributes"')
119 legacy = legacy.replace(
120 'parser.error("--commit requires --check-attributes")',
121 'parser.error("--commit requires attribute checking")',
122 )
123 if legacy == current or "--check-attributes" in legacy:
124 fail("bootstrap selftest did not hide the new validator capability from HEAD")
125 _write(validator, legacy, executable=True)
126 git(root, "add", str(validator.relative_to(root)))
127 git(root, "commit", "--quiet", "--amend", "--no-edit")
128 _write(validator, current, executable=True)
129 git(root, "add", str(validator.relative_to(root)))
130 marker = base / "bootstrap.venv"
131 install_venv_wrappers(root, marker)
132 environment = transport_environment(base, root)
133 environment["RA8_SELFTEST_VENV"] = str(marker)
134 before = source_state(root)
135 result = run_owner(root, temp_root, environment)
136 if result.returncode or source_state(root) != before or tuple(temp_root.iterdir()):
137 fail(
138 f"exact bootstrap policy population failed: {result.returncode}: "
139 f"stdout={result.stdout!r} stderr={result.stderr!r}"
140 )
141 if marker.exists():
142 fail("bootstrap validation selected a mutable source-tree owner tool")
143 ignore = root / ".gitignore"
144 ignore.write_text(ignore.read_text(encoding="utf-8") + "candidate-only/\n", encoding="utf-8")
145 git(root, "add", ".gitignore")
146 before = source_state(root)
147 result = run_owner(root, temp_root, environment)
148 if result.returncode == 0 or "pre-validator bootstrap" not in result.stderr:
149 fail("changed bootstrap policy population passed an older HEAD validator")
150 if source_state(root) != before or tuple(temp_root.iterdir()):
151 fail("bootstrap rejection mutated source state or left snapshot residue")