diff --git a/.gitignore b/.gitignore index 8e19d8f..700193f 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,6 @@ build/ .studio-engine/ .studio-source/ node_modules/ +/.hypertext/formatter-tools/runtime.json +/.hypertext/formatter-tools/bin/ +/.hypertext/formatter-tools/__pycache__/ diff --git a/.hypertext/formatter-tools/native-addons-rules.json b/.hypertext/formatter-tools/native-addons-rules.json new file mode 100644 index 0000000..42e43f6 --- /dev/null +++ b/.hypertext/formatter-tools/native-addons-rules.json @@ -0,0 +1,45 @@ +{ + "setup": [ + [ + "python3", + "{repo}/.hypertext/formatter-tools/native-addons.py", + "setup-swift" + ], + [ + "python3", + "{repo}/.hypertext/formatter-tools/native-addons.py", + "setup-terraform" + ] + ], + "rules": [ + { + "name": "SwiftFormat 0.64.0", + "patterns": ["**/*.swift", "*.swift"], + "argv": [ + "python3", + "{repo}/.hypertext/formatter-tools/native-addons.py", + "swift", + "--path", + "{path}" + ] + }, + { + "name": "Terraform 1.15.5", + "patterns": [ + "**/*.tf", + "*.tf", + "**/*.tfvars", + "*.tfvars", + "**/*.hcl", + "*.hcl" + ], + "argv": [ + "python3", + "{repo}/.hypertext/formatter-tools/native-addons.py", + "terraform", + "--path", + "{path}" + ] + } + ] +} diff --git a/.hypertext/formatter-tools/native-addons.py b/.hypertext/formatter-tools/native-addons.py new file mode 100644 index 0000000..624fa0c --- /dev/null +++ b/.hypertext/formatter-tools/native-addons.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Pinned stdin native formatters; downloads occur only in explicit setup commands.""" + +import argparse +import hashlib +import io +import os +from pathlib import Path +import platform +import subprocess +import sys +import tempfile +import urllib.request +import zipfile + +ROOT = Path(__file__).resolve().parents[2] +CACHE = ( + Path(os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))) + / "hypertext-formatters" +) +SWIFT_VERSION = "0.64.0" +SWIFT_ARCHIVE = "95ea62625d0b898a7af870293311ae6f09e4a3147ecd900593687e4b9ab2fd98" +SWIFT_BINARY = "c2b098cc3ae30ff9fdd1acf7342f9b6efac4c403cf0b4e2d473690c92ac41210" +TF_VERSION = "1.15.5" +TF_HASHES = { + "darwin_arm64": "01137660510005b918bba82154866fbeac4393163d8277c2abe861dfb5842c3c", + "darwin_amd64": "3687d07c034b3e7deed5b072cd8ae2b34835bcb139baec3fc4f5fd534dabf5ed", + "linux_arm64": "06e7b48de826146c6d9331ba35b13da12332d8392be30d1dd6b789ba4713fff0", + "linux_amd64": "702b2136af6728c8ff037f843dd2dbce2b7ad88786b7381d1d72aefa250f601c", +} +# Archive digests from HashiCorp's versioned SHA256SUMS and PyPI release metadata. +CLANG_VERSION = "23.1.3" +CLANG_WHEELS = { + "darwin_arm64": ( + "https://files.pythonhosted.org/packages/47/a5/2007b7a7a53dfe417e66d0a6b38b2f87f16391bfe6fe522d436d1e50be1c/clang_format-23.1.3-py2.py3-none-macosx_11_0_arm64.whl", + "79f53ac55434af6dda88eb90eeb65d903ff920c910f78041de41e3ca666dfba5", + ), + "darwin_amd64": ( + "https://files.pythonhosted.org/packages/05/0f/a1813ede1e149e700ee810baf22dd9c863ca0bd719d73f86e8c10b67a6bb/clang_format-23.1.3-py2.py3-none-macosx_10_9_x86_64.whl", + "0b8e86cc5a870ca42989bd1ccfe5220fbab96e386922d0a8f0ca350db30593df", + ), + "linux_arm64": ( + "https://files.pythonhosted.org/packages/1d/00/a0f99e24dc4892fb120e82fa9cf6e8fcb92714181ffd1165ab7eaf5ba1fd/clang_format-23.1.3-py2.py3-none-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", + "072113527b49a9c0ab9058006d9fe20e583823e6482608a34e1883dd2c49ae7d", + ), + "linux_amd64": ( + "https://files.pythonhosted.org/packages/11/d1/658d3da4dcbca98620956868c7cf6f4ba19fccecbdfc30cc055e19c9d4a7/clang_format-23.1.3-py2.py3-none-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", + "58bf1804216501669832a39f2415e14284337438a062ff564729792adec664ac", + ), +} + + +def checked(data, digest): + if hashlib.sha256(data).hexdigest() != digest: + raise RuntimeError( + "Native formatter checksum differs from its reviewed pin; rerun setup after inspection" + ) + return data + + +def atomic_write(path, data, executable=False): + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, name = tempfile.mkstemp(prefix=".formatter-", dir=path.parent) + temporary = Path(name) + try: + with os.fdopen(descriptor, "wb") as output: + output.write(data) + if executable: + temporary.chmod(0o755) + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) + + +def download(url): + with urllib.request.urlopen(url, timeout=120) as response: + data = response.read(128 * 1024 * 1024 + 1) + if len(data) > 128 * 1024 * 1024: + raise RuntimeError("Native formatter download exceeds 128 MiB") + return data + + +def platform_key(): + arch = { + "arm64": "arm64", + "aarch64": "arm64", + "x86_64": "amd64", + "AMD64": "amd64", + }.get(platform.machine()) + key = platform.system().lower() + "_" + str(arch) + if key not in TF_HASHES: + raise RuntimeError( + "Pinned formatter setup supports macOS/Linux on arm64 or x86_64" + ) + return key + + +def zip_tool(tool, setup=False): + key = platform_key() + if tool == "terraform": + filename = f"terraform_{TF_VERSION}_{key}.zip" + url = f"https://releases.hashicorp.com/terraform/{TF_VERSION}/{filename}" + digest, member = TF_HASHES[key], "terraform" + directory = CACHE / "terraform" / TF_VERSION / key + else: + url, digest = CLANG_WHEELS[key] + filename = url.rsplit("/", 1)[1] + member = "clang_format/data/bin/clang-format" + directory = CACHE / "clang-format" / CLANG_VERSION / key + archive, binary = directory / filename, directory / Path(member).name + if not archive.is_file(): + if not setup: + raise RuntimeError( + f"Native formatter is not prepared; run native-addons.py setup-{tool}" + ) + atomic_write(archive, checked(download(url), digest)) + with zipfile.ZipFile(io.BytesIO(checked(archive.read_bytes(), digest))) as bundle: + executable = bundle.read(member) + if not binary.is_file(): + if not setup: + raise RuntimeError( + f"Native formatter executable is missing; run native-addons.py setup-{tool}" + ) + atomic_write(binary, executable, executable=True) + checked(binary.read_bytes(), hashlib.sha256(executable).hexdigest()) + return binary + + +def swift_tool(setup=False): + if platform.system() != "Darwin": + raise RuntimeError("Pinned SwiftFormat setup requires macOS") + path = CACHE / "swiftformat" / SWIFT_VERSION / "swiftformat" + if not path.is_file(): + if not setup: + raise RuntimeError( + "SwiftFormat is not prepared; run native-addons.py setup-swift" + ) + url = f"https://github.com/nicklockwood/SwiftFormat/releases/download/{SWIFT_VERSION}/swiftformat.zip" + with zipfile.ZipFile( + io.BytesIO(checked(download(url), SWIFT_ARCHIVE)) + ) as bundle: + atomic_write( + path, checked(bundle.read("swiftformat"), SWIFT_BINARY), executable=True + ) + checked(path.read_bytes(), SWIFT_BINARY) + return path + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "tool", + choices=[ + "swift", + "terraform", + "metal", + "setup-swift", + "setup-terraform", + "setup-metal", + ], + ) + parser.add_argument("--path", default="input.swift") + args = parser.parse_args() + setup = args.tool.startswith("setup-") + tool = args.tool.removeprefix("setup-") + binary = swift_tool(setup) if tool == "swift" else zip_tool(tool, setup) + if setup: + print(f"Pinned {tool} formatter ready.") + return 0 + if tool == "swift": + command = [ + str(binary), + "stdin", + "--stdin-path", + args.path, + "--quiet", + "--cache", + "ignore", + ] + if (ROOT / ".swiftformat").is_file(): + command += ["--config", str(ROOT / ".swiftformat")] + elif tool == "terraform": + command = [str(binary), "fmt", "-no-color", "-"] + else: + # Metal's shader syntax is C++ based. The virtual .cpp extension selects + # that parser while retaining the source directory for native style lookup. + command = [ + str(binary), + "--assume-filename", + str(Path(args.path).with_suffix(".cpp")), + "--style=file", + "--fallback-style=LLVM", + ] + environment = { + k: v for k, v in os.environ.items() if not k.startswith("TF_CLI_ARGS") + } + environment.update(CHECKPOINT_DISABLE="1", TF_IN_AUTOMATION="1") + return subprocess.call(command, cwd=ROOT, env=environment) + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except (OSError, RuntimeError, ValueError, KeyError, zipfile.BadZipFile) as error: + print("Native formatter blocked: " + str(error), file=sys.stderr) + raise SystemExit(1) diff --git a/.hypertext/formatter-tools/npm-lock.json b/.hypertext/formatter-tools/npm-lock.json new file mode 100644 index 0000000..3ed57c3 --- /dev/null +++ b/.hypertext/formatter-tools/npm-lock.json @@ -0,0 +1,473 @@ +{ + "name": "studio-formatter-runtime", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "studio-formatter-runtime", + "dependencies": { + "prettier": "3.9.6", + "prettier-plugin-sh": "0.20.2", + "prettier-plugin-toml": "4.1.0" + } + }, + "node_modules/@reteps/dockerfmt": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/@reteps/dockerfmt/-/dockerfmt-0.5.4.tgz", + "integrity": "sha512-HEGgXVVOb+JtGUSSzXl/XPKFIZjMDTUoHarCjaQdkY+cb5M9K/O3b5xm+x0IPIk3SfHurbc0bSgcFsQlzjitxA==", + "license": "MIT", + "bin": { + "dockerfmt": "dist/launcher.js" + }, + "engines": { + "node": "^v12.20.0 || ^14.13.0 || >=16.0.0" + }, + "optionalDependencies": { + "@reteps/dockerfmt-darwin-arm64": "0.5.4", + "@reteps/dockerfmt-darwin-x64": "0.5.4", + "@reteps/dockerfmt-linux-arm64": "0.5.4", + "@reteps/dockerfmt-linux-x64": "0.5.4" + } + }, + "node_modules/@reteps/dockerfmt-darwin-arm64": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/@reteps/dockerfmt-darwin-arm64/-/dockerfmt-darwin-arm64-0.5.4.tgz", + "integrity": "sha512-urMqV+dQyvVI8/WrXwClX9e1PEyS35wFdwJjpZYmL09AkV4Io5U1oam8UBKK7jZk0+YsdF88ay6e86Kn6DIyQg==", + "cpu": ["arm64"], + "license": "MIT", + "optional": true, + "os": ["darwin"] + }, + "node_modules/@reteps/dockerfmt-darwin-x64": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/@reteps/dockerfmt-darwin-x64/-/dockerfmt-darwin-x64-0.5.4.tgz", + "integrity": "sha512-fJORy6DFxbgDiMqxpLTPZlb5KUY0Vq0iR4NGnyKnuYZ9LdZUS508DK2kt/AJ87/jIKNV1qRG0JXG1Tc6xdvWjw==", + "cpu": ["x64"], + "license": "MIT", + "optional": true, + "os": ["darwin"] + }, + "node_modules/@reteps/dockerfmt-linux-arm64": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/@reteps/dockerfmt-linux-arm64/-/dockerfmt-linux-arm64-0.5.4.tgz", + "integrity": "sha512-6pVakO06eXtDuvxy1Dnjs/gQyUoGGycle8PRSt5IFRwLi/AVaOQwfkfmW0WP8VH9wNUeti6BfJ3ksTn2G+XMxg==", + "cpu": ["arm64"], + "license": "MIT", + "optional": true, + "os": ["linux"] + }, + "node_modules/@reteps/dockerfmt-linux-x64": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/@reteps/dockerfmt-linux-x64/-/dockerfmt-linux-x64-0.5.4.tgz", + "integrity": "sha512-OD6SIlUV1D4TgJoTui3FMBAZsGbTSPYsiT0BKhD6jMUcJb3GpFTa7dY9rL8rP9FUqfL7OTHVUGUOL4Rh64Olog==", + "cpu": ["x64"], + "license": "MIT", + "optional": true, + "os": ["linux"] + }, + "node_modules/@tombit/binding-android-arm-eabi": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-android-arm-eabi/-/binding-android-arm-eabi-0.1.7.tgz", + "integrity": "sha512-iyPsflbdpyrQuFGjsq/2F0EY3mwgtYMSjHOo8E28lRw7Bk0q60YHSsrgDY31MCfEOEgzDqfjX8Olr6iYTFwMjw==", + "cpu": ["arm"], + "license": "MIT", + "optional": true, + "os": ["android"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-android-arm64": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-android-arm64/-/binding-android-arm64-0.1.7.tgz", + "integrity": "sha512-PDe05sj7SnGBhrOFda7Zbc4HPoV9pc9YfiioH2prhKWCsdkOPdRrsINNzKaQ9zB/UidMu35EsgDfpzR7GAPTvA==", + "cpu": ["arm64"], + "license": "MIT", + "optional": true, + "os": ["android"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-darwin-arm64": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-darwin-arm64/-/binding-darwin-arm64-0.1.7.tgz", + "integrity": "sha512-miTaFHWcB3ZrP+LR/V7P6itH4rt5GqubfOhg99U84KVmRhNAUSqq9OcSaUU4nJAS+KKea9Ee2qSCXxfNWfNLCw==", + "cpu": ["arm64"], + "license": "MIT", + "optional": true, + "os": ["darwin"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-darwin-x64": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-darwin-x64/-/binding-darwin-x64-0.1.7.tgz", + "integrity": "sha512-8AdCarDY+voPiQO+Nes3AMnG/b5cnt4PJpgFG78fss9YlQwvttxiDXydDeEtb3VQ6hK8tJk1bt0j1mrbu323HA==", + "cpu": ["x64"], + "license": "MIT", + "optional": true, + "os": ["darwin"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-freebsd-x64": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-freebsd-x64/-/binding-freebsd-x64-0.1.7.tgz", + "integrity": "sha512-3+FbhwB5/SZPe2hYH9LhS3X977kMIn9ulnCu3T8ToSDe3g9YwZzUobYxIXazQvNwerQEhri7kcRqqVizr3UJ1A==", + "cpu": ["x64"], + "license": "MIT", + "optional": true, + "os": ["freebsd"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-linux-arm-gnueabihf": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.1.7.tgz", + "integrity": "sha512-pBweM11IOeWxEEeFQ2ldNC8RLFOnr4T+Zs43zHIPGAB0eBi6QBn2LpD6O7aSB5jBOgR3rYAJ5VNZ3XdDYzDzkw==", + "cpu": ["arm"], + "license": "MIT", + "optional": true, + "os": ["linux"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-linux-arm-musleabihf": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.1.7.tgz", + "integrity": "sha512-vJSsAeTHGuTzZCT+ibOXtBfkSHFbBs+0Ckz+zpQLzJzrYooWXb4vxbq5YcU7ANnJ8BHFHq3bfpQd9ld9wvo2Xw==", + "cpu": ["arm"], + "license": "MIT", + "optional": true, + "os": ["linux"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-linux-arm64-gnu": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.1.7.tgz", + "integrity": "sha512-v/xQuHzUi2Y4fgAWjKekMOEYtDNnE7bNYuZhX/TUmL1rL7MES5+e19cSiPPqwZTx7XlA3PIeOtwV/gBpbr+/iw==", + "cpu": ["arm64"], + "libc": ["glibc"], + "license": "MIT", + "optional": true, + "os": ["linux"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-linux-arm64-musl": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.1.7.tgz", + "integrity": "sha512-HgRIXOh99HKd/IkRqPvNMy5LSZ0mXVRj7yM6l62lHbxS1rDMW0fyJtxikrJX6FMMAZrbCcYKpOjNFqWdln8Zzg==", + "cpu": ["arm64"], + "libc": ["musl"], + "license": "MIT", + "optional": true, + "os": ["linux"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-linux-loong64-gnu": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-linux-loong64-gnu/-/binding-linux-loong64-gnu-0.1.7.tgz", + "integrity": "sha512-vGmWQG+A2VgiX1YmcPkzDrCmdphjk1pc8Y724SeSz1nggJRsD6qy42kpxFR4Mwmpv3fneKfsP9AA5DvgNMBMCA==", + "cpu": ["loong64"], + "libc": ["glibc"], + "license": "MIT", + "optional": true, + "os": ["linux"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-linux-loong64-musl": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-linux-loong64-musl/-/binding-linux-loong64-musl-0.1.7.tgz", + "integrity": "sha512-BjepP36zGh0PX2ok3v/Q1HHZLHSJkCTdnLwQxpWp0Ts3Jm2lUL7oBpwTFqBMVW7qEmoezH3RcYa+hIlCEht/mw==", + "cpu": ["loong64"], + "libc": ["musl"], + "license": "MIT", + "optional": true, + "os": ["linux"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-linux-ppc64-gnu": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.1.7.tgz", + "integrity": "sha512-aTYG3ND7CcLUZ4QCWyWnW6b8g2L481n3dRx564BB2tsdMYR+UTTMT9Ht8GCk8NRni5jR4qOj8/6opZU5iUWepw==", + "cpu": ["ppc64"], + "libc": ["glibc"], + "license": "MIT", + "optional": true, + "os": ["linux"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-linux-ppc64-musl": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-linux-ppc64-musl/-/binding-linux-ppc64-musl-0.1.7.tgz", + "integrity": "sha512-cLJegaEISxKO1+l6o+tePYL9e4zZ+7e/HC6akVKIUA5KlINLgBRoi1f1wdSAWVeN3p73zGC1HZnCwflmu5ueOA==", + "cpu": ["ppc64"], + "libc": ["musl"], + "license": "MIT", + "optional": true, + "os": ["linux"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-linux-riscv64-gnu": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.1.7.tgz", + "integrity": "sha512-pmrjVWhX7f2ze8rGPvceRSYP2R57R2Y1hUkks0qDnAweFvNlJM6tn575ArDUF/Wq3jcbjmfuFQOnfeB3qIEoRg==", + "cpu": ["riscv64"], + "libc": ["glibc"], + "license": "MIT", + "optional": true, + "os": ["linux"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-linux-riscv64-musl": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.1.7.tgz", + "integrity": "sha512-cSOZ3ybyJa3SY9mM0ZM9p2xwrw/emdcSPSg+sRkqpT9Pk/LvAL1Tckj3+fm2WtphctAnjDNhuvL7hOdUTDqlMA==", + "cpu": ["riscv64"], + "libc": ["musl"], + "license": "MIT", + "optional": true, + "os": ["linux"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-linux-s390x-gnu": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.1.7.tgz", + "integrity": "sha512-KZir6MHNSXi06kUQ4D6VJdTmVekH2qgVP5lCCI3+19u0fNaXwG4ncB0AG+JYm76o8/bneS5QHjUtzAoh+paaPA==", + "cpu": ["s390x"], + "libc": ["glibc"], + "license": "MIT", + "optional": true, + "os": ["linux"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-linux-x64-gnu": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.1.7.tgz", + "integrity": "sha512-lvEGWsuTK7tBf/ck5tb07qxC2eEv4MP5ZRS5VnOsJg+cUwdthEkrYkb8oeCyu2j4nwHW3U9QoHXChv7Gs8/51w==", + "cpu": ["x64"], + "libc": ["glibc"], + "license": "MIT", + "optional": true, + "os": ["linux"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-linux-x64-musl": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-linux-x64-musl/-/binding-linux-x64-musl-0.1.7.tgz", + "integrity": "sha512-BT84fASpACpaID1xj2Td0nPpuzGt3jDr1uU+fxi0uczVrNcrWLDSBjllD2ttf3lPiJ/Q/ceQGESTOy9a5+nZgQ==", + "cpu": ["x64"], + "libc": ["musl"], + "license": "MIT", + "optional": true, + "os": ["linux"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-openharmony-arm64": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-openharmony-arm64/-/binding-openharmony-arm64-0.1.7.tgz", + "integrity": "sha512-bouy+zR5Z+oKAuVpPFoxiv0EZynvVaJLJkmz35InQ2Cle/0RHnnk5C/SF8DAksfXf7Cz1M+mjtoB3DQ0+Qvphw==", + "cpu": ["arm64"], + "license": "MIT", + "optional": true, + "os": ["openharmony"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-openharmony-x64": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-openharmony-x64/-/binding-openharmony-x64-0.1.7.tgz", + "integrity": "sha512-I/CIJsBu1DKS5Lvq+pp4o7BMuVANeTFO61BV1BY4W9Unkc9H020WVkpDKAkMhdDOI3qhI2GcafunkdIUIa/8Vw==", + "cpu": ["x64"], + "license": "MIT", + "optional": true, + "os": ["openharmony"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-win32-arm64-msvc": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.1.7.tgz", + "integrity": "sha512-W7wJ+grPsqk0QAzqlgQgwVFY7mapKU5XKVLMU/ZVSZn72bAb0dyhc9mceuPIzZHFS/emmWpsPD6+bIiraJObYA==", + "cpu": ["arm64"], + "license": "MIT", + "optional": true, + "os": ["win32"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-win32-ia32-msvc": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.1.7.tgz", + "integrity": "sha512-hpM4AxTVmwf9K4Wo2/sLpqJEHPDAecaF7a5K5sg66A2/XCwX+s86vBXLeXuDdMm8+U1svM6nOsqqFjWz3VnhFw==", + "cpu": ["ia32"], + "license": "MIT", + "optional": true, + "os": ["win32"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@tombit/binding-win32-x64-msvc": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@tombit/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.1.7.tgz", + "integrity": "sha512-qWtuJEDiZCn01ha9WBaVp0hx6xjveWs4eQzITXQbXtSNrm0c4UtdQApMmgOS9TzwRhoxyZyKgLKBLnJTBHBy4w==", + "cpu": ["x64"], + "license": "MIT", + "optional": true, + "os": ["win32"], + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/napi-postinstall": { + "version": "0.3.7", + "resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.7.tgz", + "integrity": "sha512-jyU4cU4kVAmy/3qjP+DcoQTNXfINHc+dFw54gGqWC8nu0mpV0kOnk7kff+J+Q18SbX0k3Np8Rm7yFjd3phatNQ==", + "license": "MIT", + "bin": { + "napi-patch": "lib/patch.js", + "napi-postinstall": "lib/cli.js" + }, + "engines": { + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/napi-postinstall" + } + }, + "node_modules/prettier": { + "version": "3.9.6", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.6.tgz", + "integrity": "sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g==", + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/prettier-plugin-sh": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/prettier-plugin-sh/-/prettier-plugin-sh-0.20.2.tgz", + "integrity": "sha512-4QVyY7Vav0f5i6AVa80SFwUJXaWsAv9t0yUZIivwI0ucxTei6Jwhso/khWqaKDj4QGdwjP2py1nxQrDUeZ0jyQ==", + "license": "MIT", + "dependencies": { + "@reteps/dockerfmt": "^0.5.4", + "sh-syntax": "^0.7.0" + }, + "engines": { + "node": ">=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/unts" + }, + "peerDependencies": { + "prettier": "^3.6.0" + } + }, + "node_modules/prettier-plugin-toml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/prettier-plugin-toml/-/prettier-plugin-toml-4.1.0.tgz", + "integrity": "sha512-6+qgmRqD79kSsincO3odPzMpteTCpeP+WxxYmI7vDrhfpiQMFeciozuqUcnWc4XfJ97OZiuWeUfVcDktvACIDg==", + "license": "MIT", + "dependencies": { + "tombit": "^0.1.3" + }, + "engines": { + "node": ">=20.0.0" + }, + "funding": { + "url": "https://opencollective.com/unts" + }, + "peerDependencies": { + "prettier": "^3.0.3" + } + }, + "node_modules/sh-syntax": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/sh-syntax/-/sh-syntax-0.7.0.tgz", + "integrity": "sha512-sgMyAxpHiGgAaNg+gD3ad41vha24CzIjjghD4mdiON1lUafZPLJNYknyjcXmU4geilPstd69zCKkpccY0YvajA==", + "license": "MIT", + "engines": { + "node": ">=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/sh-syntax" + } + }, + "node_modules/tombit": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/tombit/-/tombit-0.1.7.tgz", + "integrity": "sha512-0jMD7Zji2JV6yIia7krTZVxle/jmKGWvqaIrcjSuRIhR3qIGEkSYfjcdz9dAf9EJC37pyW/A4nz+sjErLgfZHg==", + "license": "MIT", + "dependencies": { + "napi-postinstall": "^0.3.7" + }, + "engines": { + "node": ">=20.0.0" + }, + "optionalDependencies": { + "@tombit/binding-android-arm-eabi": "0.1.7", + "@tombit/binding-android-arm64": "0.1.7", + "@tombit/binding-darwin-arm64": "0.1.7", + "@tombit/binding-darwin-x64": "0.1.7", + "@tombit/binding-freebsd-x64": "0.1.7", + "@tombit/binding-linux-arm-gnueabihf": "0.1.7", + "@tombit/binding-linux-arm-musleabihf": "0.1.7", + "@tombit/binding-linux-arm64-gnu": "0.1.7", + "@tombit/binding-linux-arm64-musl": "0.1.7", + "@tombit/binding-linux-loong64-gnu": "0.1.7", + "@tombit/binding-linux-loong64-musl": "0.1.7", + "@tombit/binding-linux-ppc64-gnu": "0.1.7", + "@tombit/binding-linux-ppc64-musl": "0.1.7", + "@tombit/binding-linux-riscv64-gnu": "0.1.7", + "@tombit/binding-linux-riscv64-musl": "0.1.7", + "@tombit/binding-linux-s390x-gnu": "0.1.7", + "@tombit/binding-linux-x64-gnu": "0.1.7", + "@tombit/binding-linux-x64-musl": "0.1.7", + "@tombit/binding-openharmony-arm64": "0.1.7", + "@tombit/binding-openharmony-x64": "0.1.7", + "@tombit/binding-win32-arm64-msvc": "0.1.7", + "@tombit/binding-win32-ia32-msvc": "0.1.7", + "@tombit/binding-win32-x64-msvc": "0.1.7" + } + } + } +} diff --git a/.hypertext/formatter-tools/prettier.mjs b/.hypertext/formatter-tools/prettier.mjs new file mode 100644 index 0000000..e82ea26 --- /dev/null +++ b/.hypertext/formatter-tools/prettier.mjs @@ -0,0 +1,431 @@ +#!/usr/bin/env node +import { readFile, readdir } from "node:fs/promises"; +import { createRequire, registerHooks } from "node:module"; +import path from "node:path"; +import { pathToFileURL, fileURLToPath } from "node:url"; +import { isDeepStrictEqual } from "node:util"; + +const tools = path.dirname(fileURLToPath(import.meta.url)); +const repo = path.resolve(tools, "../.."); +const bytes = await readFile(path.join(tools, "tools.json")); +const spec = JSON.parse(bytes); +const runtime = JSON.parse(await readFile(path.join(tools, "runtime.json"))); +if (!isDeepStrictEqual(runtime.spec, spec)) + throw Error("Formatter pins changed; rerun hook setup"); +const npm = createRequire(path.join(runtime.npm, "../package.json")); +const importedPrettier = await import(pathToFileURL(npm.resolve("prettier"))); +const prettier = importedPrettier.default ?? importedPrettier; +if (prettier.version !== runtime.prettier) + throw Error("Prepared Prettier version does not match repository pin"); +if (spec.prettier.manifest) { + const data = JSON.parse( + await readFile(path.join(repo, spec.prettier.manifest)), + ); + let version = data.devDependencies?.prettier ?? data.dependencies?.prettier; + if (version?.startsWith("catalog:")) + version = ( + await readFile(path.join(repo, "pnpm-workspace.yaml"), "utf8") + ).match(/^\s+prettier:\s*['"]?(\d+\.\d+\.\d+)/m)?.[1]; + if (version !== runtime.prettier) + throw Error("Repository Prettier pin changed; rerun hook setup"); +} +const filename = path.resolve(repo, process.argv[2]); +const parser = process.argv[3]; +const source = await new Promise((resolve, reject) => { + let text = ""; + process.stdin.setEncoding("utf8"); + process.stdin.on("data", (chunk) => (text += chunk)); + process.stdin.on("end", () => resolve(text)); + process.stdin.on("error", reject); +}); + +const configFile = await prettier.resolveConfigFile(filename); +const contexts = []; +for ( + let folder = configFile ? path.dirname(configFile) : path.dirname(filename); + ; +) { + const manifest = await readFile(path.join(folder, "package.json"), "utf8") + .then(JSON.parse) + .catch(() => null); + if (manifest) + contexts.push({ + folder, + manifest, + dependencies: { ...manifest.dependencies, ...manifest.devDependencies }, + }); + if (folder === repo || !folder.startsWith(repo + path.sep)) break; + folder = path.dirname(folder); +} +const dependencies = Object.assign( + {}, + ...contexts.toReversed().map((context) => context.dependencies), +); +const workspaceModules = new Map(); +const exactVersion = (value) => + typeof value === "string" && /^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(value); +const scalar = (value) => value.trim().replace(/^(['"])(.*)\1$/, "$2"); + +function declaringContext(base) { + const context = contexts.find( + (value) => value.manifest.name === base || value.dependencies[base], + ); + if (!context) + throw Error("Project config dependency is not declared: " + base); + return context; +} + +async function expectedVersion(base) { + const context = declaringContext(base); + if (context.manifest.name === base) { + if (!exactVersion(context.manifest.version)) + throw Error("Workspace config package needs an exact version: " + base); + workspaceModules.set(base, context.folder); + return context.manifest.version; + } + const declared = context.dependencies[base]; + if (exactVersion(declared)) return declared; + // pnpm's root importer is authoritative for ranges and catalog references. Require the + // matching specifier as well, so a stale lock cannot bless a changed package manifest. + const lock = await readFile(path.join(repo, "pnpm-lock.yaml"), "utf8").catch( + () => "", + ); + const importerName = + path.relative(repo, context.folder).split(path.sep).join("/") || "."; + const sections = (lock.split(/^importers:\s*$/m)[1] ?? "").split( + /^(?= {2}\S)/m, + ); + const importer = sections.find( + (section) => + scalar(section.split("\n")[0].trim().replace(/:$/, "")) === importerName, + ); + if (importer) { + const lines = importer.split("\n"); + for (let index = 0; index < lines.length; index++) { + const key = lines[index].match(/^ {6}(.+):\s*$/); + if (!key || scalar(key[1]) !== base) continue; + const fields = {}; + for ( + let next = index + 1; + next < lines.length && /^ {8}/.test(lines[next]); + next++ + ) { + const field = lines[next].match(/^ {8}(specifier|version):\s*(.+)$/); + if (field) fields[field[1]] = scalar(field[2]); + } + if ( + fields.specifier === declared && + declared.startsWith("workspace:") && + fields.version?.startsWith("link:") + ) { + const folder = path.resolve(context.folder, fields.version.slice(5)); + if (folder !== repo && !folder.startsWith(repo + path.sep)) + throw Error("Workspace config link escapes repository"); + const metadata = JSON.parse( + await readFile(path.join(folder, "package.json"), "utf8"), + ); + const requested = declared.slice("workspace:".length); + if ( + metadata.name !== base || + !exactVersion(metadata.version) || + (exactVersion(requested) && requested !== metadata.version) + ) { + throw Error( + "Workspace config package does not match its declaration: " + base, + ); + } + workspaceModules.set(base, folder); + return metadata.version; + } + const version = fields.version?.match( + /^(\d+\.\d+\.\d+(?:-[\w.-]+)?)(?:\(|$)/, + )?.[1]; + if (fields.specifier === declared && version) return version; + } + } + if (declared === "catalog:") { + const workspace = await readFile( + path.join(repo, "pnpm-workspace.yaml"), + "utf8", + ); + const catalog = + workspace.split(/^catalog:\s*$/m)[1]?.split(/^\S/m)[0] ?? ""; + for (const line of catalog.split("\n")) { + const field = line.match(/^ {2}(.+):\s*(.+)$/); + if (field && scalar(field[1]) === base && exactVersion(scalar(field[2]))) + return scalar(field[2]); + } + } + throw Error("Cannot establish exact locked project dependency: " + base); +} + +function packageParts(name) { + const parts = name.split("/"); + return name.startsWith("@") + ? [parts.slice(0, 2).join("/"), parts.slice(2)] + : [parts[0], parts.slice(1)]; +} + +async function validateModule(filename, base, expected) { + let folder = path.dirname(filename); + while (true) { + const metadata = await readFile(path.join(folder, "package.json"), "utf8") + .then(JSON.parse) + .catch(() => null); + if (metadata?.name === base) { + if (metadata.version !== expected) + throw Error( + `Project dependency ${base} resolved ${metadata.version}; expected ${expected}`, + ); + return filename; + } + const parent = path.dirname(folder); + if (parent === folder) + throw Error("Cannot identify resolved project dependency: " + base); + folder = parent; + } +} + +async function projectModule(name) { + const [base, rest] = packageParts(name); + const expected = await expectedVersion(base); + const context = declaringContext(base); + let direct; + try { + direct = createRequire(path.join(context.folder, "package.json")).resolve( + name, + ); + } catch { + // An absent direct installation can still resolve from a verified workspace or cache. + } + if (workspaceModules.has(base)) { + const folder = workspaceModules.get(base); + const metadata = JSON.parse( + await readFile(path.join(folder, "package.json"), "utf8"), + ); + const exported = rest.length + ? metadata.exports?.["./" + rest.join("/")] + : (metadata.exports?.["."] ?? metadata.main); + const relative = + typeof exported === "string" + ? exported + : (exported?.import ?? exported?.default); + if (!relative || typeof relative !== "string") + throw Error("Workspace config export is missing: " + name); + const resolved = path.resolve(folder, relative); + if (!resolved.startsWith(folder + path.sep)) + throw Error("Workspace config export escapes package"); + return validateModule(resolved, base, expected); + } + if (direct) return validateModule(direct, base, expected); + const prefix = base.replace("/", "+") + "@"; + const stores = [ + ...new Set([ + path.join(context.folder, "node_modules/.pnpm"), + path.join(repo, "node_modules/.pnpm"), + ]), + ]; + const matches = []; + for (const store of stores) + for (const entry of (await readdir(store).catch(() => [])).filter((value) => + value.startsWith(prefix), + )) { + const folder = path.join(store, entry, "node_modules", base); + const metadata = await readFile(path.join(folder, "package.json"), "utf8") + .then(JSON.parse) + .catch(() => null); + if (metadata?.name !== base || metadata.version !== expected) continue; + const peer = entry.match( + /(?:^|_)prettier@(\d+\.\d+\.\d+(?:-[\w.-]+)?)(?:_|$)/, + )?.[1]; + const declaredPrettier = context.dependencies.prettier; + const preferredPeer = exactVersion(declaredPrettier) + ? declaredPrettier + : runtime.prettier; + if (peer && peer !== preferredPeer) continue; + let resolved; + if (!rest.length) { + try { + resolved = createRequire(path.join(folder, "package.json")).resolve( + base, + ); + } catch { + // This cached package has no root export; keep searching matching snapshots. + } + } else { + const exported = metadata.exports?.["./" + rest.join("/")]; + const relative = + typeof exported === "string" + ? exported + : (exported?.import ?? exported?.default); + if (typeof relative === "string" && relative.startsWith("./")) + resolved = path.resolve(folder, relative); + } + if (resolved) + matches.push(await validateModule(resolved, base, expected)); + } + if (matches.length > 1) + throw Error("Ambiguous locked project dependency peer snapshots: " + name); + if (matches.length === 1) return matches[0]; + throw Error( + "Install the locked project config dependency: " + name + "@" + expected, + ); +} + +async function pluginModule(name) { + const [base] = packageParts(name); + if (dependencies[base]) { + const expected = await expectedVersion(base); + try { + return await projectModule(name); + } catch (error) { + // A mismatched or ambiguous project installation is an error, not a cache fallback. + if ( + !error.message.startsWith( + "Install the locked project config dependency:", + ) + ) + throw error; + if (spec.npm[base] !== expected) + throw Error("Project plugin pin changed; rerun hook setup: " + base, { + cause: error, + }); + return validateModule(npm.resolve(name), base, expected); + } + } + if (!spec.npm[base]) + throw Error("Formatter plugin has no exact tool pin: " + base); + return validateModule(npm.resolve(name), base, spec.npm[base]); +} + +let config; +if (configFile && /\.(?:mjs|cjs|js)$/.test(configFile)) { + const text = await readFile(configFile, "utf8"); + const imports = [ + ...text.matchAll( + /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s*)['"]([^'"]+)['"]/g, + ), + ] + .map((match) => match[1]) + .filter( + (name) => + !name.startsWith(".") && + !name.startsWith("/") && + !name.startsWith("node:"), + ); + const resolved = new Map( + await Promise.all( + [...new Set(imports)].map(async (name) => [ + name, + pathToFileURL(await projectModule(name)).href, + ]), + ), + ); + const configURL = pathToFileURL(configFile).href; + // Resolve this config's own validated imports while executing the original file unchanged. + // Relative imports, import.meta.url, and composed configuration remain native Node behavior. + const hooks = registerHooks({ + resolve(name, context, next) { + if (context.parentURL === configURL && resolved.has(name)) + return { url: resolved.get(name), shortCircuit: true }; + return next(name, context); + }, + }); + try { + config = (await import(configURL)).default; + } finally { + hooks.deregister(); + } +} else { + config = await prettier.resolveConfig(filename); +} +config = { ...config }; +config.plugins = await Promise.all( + (config.plugins ?? []).map((plugin) => + typeof plugin === "string" ? pluginModule(plugin) : plugin, + ), +); +const addon = { + xml: "@prettier/plugin-xml", + toml: "prettier-plugin-toml", + sql: "prettier-plugin-sql", + sh: "prettier-plugin-sh", + ini: "prettier-plugin-ini", + properties: "prettier-plugin-properties", + astro: "prettier-plugin-astro", +}[parser]; +if (addon && spec.npm[addon]) config.plugins.push(await pluginModule(addon)); +if (parser === "sql") config.language = spec.sql_dialect ?? "postgresql"; +// Java properties comments do not continue across physical lines. Values can; +// never trim a continuation merely because it begins with a comment marker. +function propertiesEntries(text) { + const entries = new Map(); + const decode = (value) => + value.replace(/\\(u[0-9a-fA-F]{4}|[\s\S])/g, (_, escape) => { + if (escape.startsWith("u")) + return String.fromCharCode(parseInt(escape.slice(1), 16)); + return { t: "\t", n: "\n", r: "\r", f: "\f" }[escape] ?? escape; + }); + let logical = ""; + let continued = false; + for (let line of text.split(/\r\n|\r|\n/)) { + if (!continued && /^[ \t\f]*(?:[#!]|$)/.test(line)) continue; + if (continued) line = line.replace(/^[ \t\f]+/, ""); + logical += line; + continued = (line.match(/\\+$/)?.[0].length ?? 0) % 2 === 1; + if (continued) { + logical = logical.slice(0, -1); + continue; + } + const content = logical.replace(/^[ \t\f]+/, ""); + let end = 0; + for (; end < content.length; end++) { + if (content[end] === "\\") end++; + else if (/[=:\t\f ]/.test(content[end])) break; + } + let start = end; + while (/[ \t\f]/.test(content[start] ?? "") && start < content.length) + start++; + if (content[start] === "=" || content[start] === ":") start++; + while (/[ \t\f]/.test(content[start] ?? "") && start < content.length) + start++; + entries.set(decode(content.slice(0, end)), decode(content.slice(start))); + logical = ""; + } + if (continued) { + // A dangling continuation at EOF still contributes the logical entry. + return propertiesEntries(text + "\n"); + } + return [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); +} + +function cleanPropertiesCommentWhitespace(text) { + let continued = false; + return text + .split(/(?<=\n)/) + .map((physical) => { + const body = physical.replace(/\r?\n$/, ""); + const comment = !continued && /^[ \t\f]*[#!]/.test(body); + continued = !comment && (body.match(/\\+$/)?.[0].length ?? 0) % 2 === 1; + return comment ? physical.replace(/[ \t]+(\r?\n|$)/, "$1") : physical; + }) + .join(""); +} + +let formatted = await prettier.format(source, { + ...config, + filepath: filename, + ...(parser + ? { parser: parser === "properties" ? "dot-properties" : parser } + : {}), +}); +if (parser === "properties") { + formatted = cleanPropertiesCommentWhitespace(formatted); + if ( + !isDeepStrictEqual(propertiesEntries(source), propertiesEntries(formatted)) + ) + throw Error( + "Properties formatter changed a key or value; staged bytes were not changed", + ); +} +process.stdout.write(formatted); diff --git a/.hypertext/formatter-tools/run.py b/.hypertext/formatter-tools/run.py new file mode 100644 index 0000000..b79c5f2 --- /dev/null +++ b/.hypertext/formatter-tools/run.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +"""Use the prepared pinned Python formatter with filename/config context.""" + +import hashlib +import json +from pathlib import Path +import subprocess +import sys + +TOOLS = Path(__file__).resolve().parent +runtime = json.loads((TOOLS / "runtime.json").read_text()) +spec = json.loads((TOOLS / "tools.json").read_text()) +if runtime["spec"] != spec: + raise SystemExit("Formatter pins changed; rerun hook setup") +if ( + subprocess.check_output([runtime["ruff"], "--version"]).strip() + != ("ruff " + spec["ruff"]).encode() +): + raise SystemExit("Pinned Ruff is unavailable; rerun hook setup") +raise SystemExit( + subprocess.call([runtime["ruff"], "format", "--stdin-filename", sys.argv[1], "-"]) +) diff --git a/.hypertext/formatter-tools/setup.py b/.hypertext/formatter-tools/setup.py new file mode 100644 index 0000000..3267443 --- /dev/null +++ b/.hypertext/formatter-tools/setup.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Prepare only pinned formatter dependencies; never run on commit.""" + +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys + +TOOLS = Path(__file__).resolve().parent +ROOT = TOOLS.parents[1] +SPEC = json.loads((TOOLS / "tools.json").read_text()) +CACHE = ( + Path(os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))) + / "hypertext-studio/formatters" +) + + +def prettier_version(): + source = SPEC["prettier"] + if "version" in source: + return source["version"] + manifest = ROOT / source["manifest"] + data = json.loads(manifest.read_text()) + value = next( + ( + data.get(k, {}).get("prettier") + for k in ("devDependencies", "dependencies") + if data.get(k, {}).get("prettier") + ), + None, + ) + if value and value.startswith("catalog:"): + workspace = (ROOT / "pnpm-workspace.yaml").read_text() + match = re.search( + r"^\s+prettier:\s*[\'\"]?(\d+\.\d+\.\d+)[\'\"]?\s*$", workspace, re.M + ) + value = match[1] if match else None + if not value or not re.fullmatch(r"\d+\.\d+\.\d+", value): + raise ValueError( + "Existing Prettier must have an exact repository pin before setup" + ) + return value + + +def npm_command(): + npm = shutil.which("npm") + if not npm: + raise ValueError("Install Node/npm to prepare pinned Markdown formatting") + path = Path(npm).resolve() + script = ( + path + if path.suffix == ".js" + else path.parent / "node_modules/npm/bin/npm-cli.js" + ) + return ["node", str(script)] if script.is_file() else [npm] + + +def npm_inventory_matches(folder, lock, recipe): + """Check the installed locked package inventory, including every direct plugin.""" + packages = lock.get("packages", {}) + for name, version in recipe["dependencies"].items(): + if not re.fullmatch(r"\d+\.\d+\.\d+(?:-[\w.-]+)?", version): + raise ValueError("Formatter dependencies require exact pins: " + name) + metadata = folder / "node_modules" / name / "package.json" + try: + if json.loads(metadata.read_text()).get("version") != version: + return False + except (OSError, ValueError): + return False + for name, expected in packages.items(): + if not name: + continue + relative = Path(name) + if ( + relative.is_absolute() + or ".." in relative.parts + or relative.parts[0] != "node_modules" + ): + raise ValueError("Formatter lock contains an unsafe package path") + metadata = folder / relative / "package.json" + if expected.get("optional") and not metadata.exists(): + # npm omits platform-incompatible optional packages. Direct dependencies were + # checked above and never receive this exemption. + continue + try: + if json.loads(metadata.read_text()).get("version") != expected.get( + "version" + ): + return False + except (OSError, ValueError): + return False + return True + + +def prepare_npm(folder, recipe, lock_bytes): + """Reuse only a complete install bound to the exact reviewed integrity lock.""" + data = json.loads(lock_bytes) + if ( + data.get("packages", {}).get("", {}).get("dependencies") + != recipe["dependencies"] + ): + raise ValueError("Formatter lock differs from current repository pins") + for name, package in data["packages"].items(): + if name and (not package.get("version") or not package.get("integrity")): + raise ValueError( + "Formatter lock lacks package version or integrity: " + name + ) + wanted = { + "schema_version": 1, + "lock_sha256": hashlib.sha256(lock_bytes).hexdigest(), + "recipe_sha256": hashlib.sha256( + json.dumps(recipe, sort_keys=True).encode() + ).hexdigest(), + } + marker = folder / ".installed.json" + try: + complete = json.loads(marker.read_text()) == wanted + except (OSError, ValueError): + complete = False + if complete and npm_inventory_matches(folder, data, recipe): + return + marker.unlink(missing_ok=True) + subprocess.run( + [ + *npm_command(), + "ci", + "--prefix", + str(folder), + "--ignore-scripts", + "--no-audit", + "--no-fund", + "--registry=https://registry.npmjs.org", + ], + check=True, + ) + if not npm_inventory_matches(folder, data, recipe): + raise ValueError( + "Formatter dependency installation is incomplete; rerun hook setup" + ) + # A failed or interrupted npm ci never publishes a successful installation marker. + temporary = marker.with_suffix(".tmp." + str(os.getpid())) + try: + temporary.write_text(json.dumps(wanted, indent=2) + "\n") + os.replace(temporary, marker) + finally: + temporary.unlink(missing_ok=True) + + +def main(): + version = prettier_version() + recipe = { + "name": "studio-formatter-runtime", + "private": True, + "dependencies": {"prettier": version, **SPEC["npm"]}, + } + key = hashlib.sha256(json.dumps(recipe, sort_keys=True).encode()).hexdigest()[:20] + folder = CACHE / "npm" / key + folder.mkdir(parents=True, exist_ok=True) + manifest = folder / "package.json" + manifest.write_text(json.dumps(recipe, indent=2) + "\n") + lock = TOOLS / "npm-lock.json" + if not lock.exists(): + subprocess.run( + [ + *npm_command(), + "install", + "--prefix", + str(folder), + "--package-lock-only", + "--ignore-scripts", + "--no-audit", + "--no-fund", + "--registry=https://registry.npmjs.org", + ], + check=True, + ) + lock.write_bytes((folder / "package-lock.json").read_bytes()) + data = json.loads(lock.read_text()) + if data["packages"][""]["dependencies"] != recipe["dependencies"]: + raise ValueError( + "Formatter lock differs from current repository pins; regenerate npm-lock.json with the reviewed dependency change" + ) + (folder / "package-lock.json").write_bytes(lock.read_bytes()) + prepare_npm(folder, recipe, lock.read_bytes()) + ruffdir = CACHE / "ruff" / SPEC["ruff"] + python = ruffdir / ("Scripts/python.exe" if os.name == "nt" else "bin/python") + ruff = ruffdir / ("Scripts/ruff.exe" if os.name == "nt" else "bin/ruff") + if not python.is_file(): + subprocess.run([sys.executable, "-m", "venv", str(ruffdir)], check=True) + if ( + not ruff.is_file() + or subprocess.check_output([str(ruff), "--version"]).strip() + != ("ruff " + SPEC["ruff"]).encode() + ): + subprocess.run( + [ + str(python), + "-m", + "pip", + "install", + "--disable-pip-version-check", + "ruff==" + SPEC["ruff"], + ], + check=True, + ) + for command in SPEC.get("native_setup", []): + subprocess.run( + [ + v.replace("{repo}", str(ROOT)).replace("{root}", str(ROOT)) + for v in command + ], + cwd=ROOT, + check=True, + ) + runtime = { + "npm": str(folder / "node_modules"), + "prettier": version, + "ruff": str(ruff), + "spec": SPEC, + } + (TOOLS / "runtime.json").write_text(json.dumps(runtime, indent=2) + "\n") + print("Pinned commit formatters prepared.") + + +if __name__ == "__main__": + main() diff --git a/.hypertext/formatter-tools/test_native_addons.py b/.hypertext/formatter-tools/test_native_addons.py new file mode 100644 index 0000000..cb7d9d7 --- /dev/null +++ b/.hypertext/formatter-tools/test_native_addons.py @@ -0,0 +1,62 @@ +"""Real stdin and missing-tool acceptance for native formatter routes.""" + +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +HELPER = Path(__file__).with_name("native-addons.py") +RULES = Path(__file__).with_name("native-addons-rules.json") + + +class NativeAddonTests(unittest.TestCase): + def test_real_stdin_is_clean_idempotent_and_does_not_write_source(self): + samples = { + "swift": ("sample.swift", b"let value=1\n"), + "terraform": ("sample.tf", b'variable "region" {default="sample"}\n'), + "metal": ("sample.metal", b"kernel void sample(){int value=1;}\n"), + } + rules = json.loads(RULES.read_text())["rules"] + for rule in rules: + tool = rule["argv"][-3] + with self.subTest(tool=tool), tempfile.TemporaryDirectory() as directory: + name, source = samples[tool] + target = Path(directory) / name + before = b"private unstaged draft\n" + target.write_bytes(before) + command = [sys.executable, str(HELPER), tool, "--path", str(target)] + first = subprocess.run( + command, input=source, capture_output=True, cwd=ROOT + ) + self.assertEqual(first.returncode, 0, first.stderr.decode()) + self.assertNotEqual(first.stdout, source) + self.assertTrue(first.stdout.endswith(b"\n")) + second = subprocess.run( + command, input=first.stdout, capture_output=True, cwd=ROOT + ) + self.assertEqual(second.returncode, 0, second.stderr.decode()) + self.assertEqual(first.stdout, second.stdout) + self.assertEqual(target.read_bytes(), before) + + def test_commit_does_not_install_missing_tools(self): + for rule in json.loads(RULES.read_text())["rules"]: + tool = rule["argv"][-3] + with self.subTest(tool=tool), tempfile.TemporaryDirectory() as directory: + result = subprocess.run( + [sys.executable, str(HELPER), tool, "--path", "sample.swift"], + env=dict(os.environ, XDG_CACHE_HOME=directory), + input=b"let value=1\n", + capture_output=True, + ) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(result.stdout, b"") + self.assertIn(b"setup", result.stderr.lower()) + self.assertEqual(list(Path(directory).iterdir()), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/.hypertext/formatter-tools/text.py b/.hypertext/formatter-tools/text.py new file mode 100644 index 0000000..c80fec7 --- /dev/null +++ b/.hypertext/formatter-tools/text.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Canonical whitespace for line-oriented HTTP metadata; preserve order and values.""" + +import sys + +source = sys.stdin.buffer.read().decode("utf-8") +if "\x00" in source: + raise ValueError("Expected UTF-8 HTTP metadata") +# These grammars do not assign meaning to trailing horizontal whitespace. +lines = [line.rstrip(" \t\r") for line in source.split("\n")] +while lines and not lines[-1]: + lines.pop() +sys.stdout.buffer.write(("\n".join(lines) + "\n").encode()) diff --git a/.hypertext/formatter-tools/tools.json b/.hypertext/formatter-tools/tools.json new file mode 100644 index 0000000..65c8532 --- /dev/null +++ b/.hypertext/formatter-tools/tools.json @@ -0,0 +1,24 @@ +{ + "schema_version": 1, + "prettier": { + "version": "3.9.6" + }, + "npm": { + "prettier-plugin-sh": "0.20.2", + "prettier-plugin-toml": "4.1.0" + }, + "ruff": "0.15.9", + "native_setup": [ + [ + "python3", + "{repo}/.hypertext/formatter-tools/native-addons.py", + "setup-swift" + ], + [ + "python3", + "{repo}/.hypertext/formatter-tools/native-addons.py", + "setup-terraform" + ] + ], + "sql_dialect": "postgresql" +} diff --git a/.hypertext/formatters.json b/.hypertext/formatters.json new file mode 100644 index 0000000..7e05337 --- /dev/null +++ b/.hypertext/formatters.json @@ -0,0 +1,136 @@ +{ + "schema_version": 1, + "formatters": [ + { + "include": ["**/*.swift", "*.swift"], + "argv": [ + "python3", + "{repo}/.hypertext/formatter-tools/native-addons.py", + "swift", + "--path", + "{path}" + ] + }, + { + "include": [ + "**/*.tf", + "*.tf", + "**/*.tfvars", + "*.tfvars", + "**/*.hcl", + "*.hcl" + ], + "argv": [ + "python3", + "{repo}/.hypertext/formatter-tools/native-addons.py", + "terraform", + "--path", + "{path}" + ] + }, + { + "include": ["*.yml", "*.yaml"], + "argv": [ + "node", + ".hypertext/formatter-tools/prettier.mjs", + "{path}", + "yaml" + ] + }, + { + "include": ["*.json"], + "argv": [ + "node", + ".hypertext/formatter-tools/prettier.mjs", + "{path}", + "json" + ] + }, + { + "include": ["*.py", "*.pyi"], + "argv": ["python3", ".hypertext/formatter-tools/run.py", "{path}"] + }, + { + "include": ["*.md", "*.markdown", "*.mdc"], + "argv": [ + "node", + ".hypertext/formatter-tools/prettier.mjs", + "{path}", + "markdown" + ] + }, + { + "include": ["assets/run.sh.in", "*.sh", "*.bash", "*.zsh"], + "argv": [ + "node", + ".hypertext/formatter-tools/prettier.mjs", + "{path}", + "sh" + ] + }, + { + "include": ["*.toml"], + "argv": [ + "node", + ".hypertext/formatter-tools/prettier.mjs", + "{path}", + "toml" + ] + }, + { + "include": ["*.js", "*.jsx", "*.mjs", "*.cjs"], + "argv": [ + "node", + ".hypertext/formatter-tools/prettier.mjs", + "{path}", + "babel" + ] + } + ], + "exclude": [ + { + "include": [ + ".hypertext/formatting/*", + ".hypertext/formatter-tools/setup.py", + ".hypertext/formatter-tools/run.py", + ".hypertext/formatter-tools/prettier.mjs", + ".hypertext/formatter-tools/text.py" + ], + "kind": "vendored", + "reason": "Locked shared formatter engine; maintained and formatted in product-standards." + }, + { + "include": ["LICENSE"], + "kind": "non-formattable", + "reason": "Exact license text is legal material, not prose to reflow." + }, + { + "include": [".gitignore"], + "kind": "non-formattable", + "reason": "Git patterns and exact runtime version tokens have tool-specific semantics." + }, + { + "include": ["tests/fixtures/legacy-runtime/v0.1.7.tar.gz"], + "kind": "binary", + "reason": "Images, JAR/archive payloads, and serialized Xcode UI state are binary artifacts." + }, + { + "include": [ + "tests/fixtures/legacy-runtime/v0.1.7.commit", + "infra/**/.terraform.lock.hcl" + ], + "kind": "generated", + "reason": "Immutable release fixture identity and Terraform-generated provider lock selections must retain tool-owned bytes." + }, + { + "include": ["Package.resolved"], + "kind": "generated", + "reason": "Tool-owned dependency lock, credential/value file, or exact line protocol; preserve its semantic bytes." + }, + { + "include": ["tests/fixtures/legacy-runtime/README.md"], + "kind": "generated", + "reason": "Immutable package patch or compatibility fixture consumed byte-for-byte." + } + ] +} diff --git a/.hypertext/formatting/LOCK.json b/.hypertext/formatting/LOCK.json new file mode 100644 index 0000000..421ecf5 --- /dev/null +++ b/.hypertext/formatting/LOCK.json @@ -0,0 +1,8 @@ +{ + "__init__.py": "3858bfb4a4fa531ea1269e6e42cce86f0b7bfaf351600a755afc159def4c85d3", + "gate.py": "172510d10dc9a4f6d8623eb25d92991dd032c72ef81f62634c2a0715cbef93e6", + "runner.py": "bdd2d79fa3e00cdf8375da0fe3092e3dba67ec2f8462a9611182ea346f64a167", + "setup_files.py": "fbe7525bdac4f3f8dabb5c3cc298386db9700a881d86d37e9a033ae59d115b53", + "formatting.py": "3f2fbabd12f2ee87679e4f4d6e8200dfec93cc3399c0d28cde9981ec058d8a81", + "git_policy.py": "87337a7465e95df1d4da345a5ab9bf8c3f7dccadc38f88a41aec24e0ec21780d" +} diff --git a/.hypertext/formatting/commit.py b/.hypertext/formatting/commit.py new file mode 100644 index 0000000..c4ec235 --- /dev/null +++ b/.hypertext/formatting/commit.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""Run the locked shared staged-blob formatter, independently of commit scopes.""" + +import os +import sys + +if not sys.flags.isolated or not sys.flags.no_site: + os.execv( + sys.executable, [sys.executable, "-I", "-S", "-B", __file__, *sys.argv[1:]] + ) + +import hashlib +import json +from pathlib import Path +import types + +root = Path(__file__).resolve().parent +repo = root.parents[1] +try: + expected = ("__init__", "gate", "runner", "setup_files", "formatting", "git_policy") + lock = json.loads((root / "LOCK.json").read_text()) + if set(lock) != {name + ".py" for name in expected}: + raise ValueError("Invalid formatter engine lock") + sources = {} + for name in expected: + path = root / "core" / (name + ".py") + if path.is_symlink() or not path.is_file() or path.stat().st_size > 1024 * 1024: + raise ValueError("Unsafe formatter engine lock input") + sources[name] = path.read_bytes() + if hashlib.sha256(sources[name]).hexdigest() != lock[name + ".py"]: + raise ValueError("Formatter engine lock mismatch: " + name) + package = types.ModuleType("core") + package.__path__ = [] + sys.modules["core"] = package + for name in expected: + module = package if name == "__init__" else types.ModuleType("core." + name) + module.__file__ = str(root / "core" / (name + ".py")) + module.__package__ = "core" + if name != "__init__": + sys.modules[module.__name__] = module + setattr(package, name, module) + exec(compile(sources[name], module.__file__, "exec"), module.__dict__) + changed = package.formatting.format_staged(repo) + if changed: + print("Automatically formatted " + str(len(changed)) + " staged file(s).") +except Exception as error: + print("Commit formatting blocked: " + str(error), file=sys.stderr) + raise SystemExit(1) diff --git a/.hypertext/formatting/core/__init__.py b/.hypertext/formatting/core/__init__.py new file mode 100644 index 0000000..c2b380d --- /dev/null +++ b/.hypertext/formatting/core/__init__.py @@ -0,0 +1 @@ +"""Agent-independent Hypertext Studio checks and verification runner.""" diff --git a/.hypertext/formatting/core/formatting.py b/.hypertext/formatting/core/formatting.py new file mode 100644 index 0000000..712422d --- /dev/null +++ b/.hypertext/formatting/core/formatting.py @@ -0,0 +1,575 @@ +"""Format staged blobs without stashing or staging working-tree edits.""" + +import fnmatch +import io +import json +import os +from pathlib import Path +import shutil +import stat +import subprocess +import tempfile +import time + +from . import runner, setup_files + +POLICY = ".hypertext/formatters.json" +MAX_FILE = 16 * 1024 * 1024 +MAX_FILES = 1000 +CONFIG_NAMES = { + ".editorconfig", + "pyproject.toml", + "ruff.toml", + ".ruff.toml", + "rustfmt.toml", + ".rustfmt.toml", + ".swiftformat", + ".swift-format", + ".clang-format", + ".prettierignore", + "package.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", +} + + +def configuration_file(name): + base = Path(name).name + return ( + base in CONFIG_NAMES + or Path(name).parent.name == "prettier" + and Path(name).suffix in {".js", ".mjs", ".cjs"} + or base.startswith((".prettierrc", "prettier.config.")) + or str(name).replace("\\", "/").startswith(".hypertext/formatter-tools/") + and base + in { + "tools.json", + "native-rules.json", + "native-addons-rules.json", + "document-rules.json", + "dsl-rules.json", + "kotlin.editorconfig", + "npm-lock.json", + } + ) + + +def read_file(path): + if path.is_symlink(): + raise ValueError("Formatting refuses symlinked files: " + str(path)) + if not path.exists(): + return None + info = path.stat() + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_size > MAX_FILE: + raise ValueError( + "Formatting requires a regular, unshared file under 16 MiB: " + str(path) + ) + return path.read_bytes() + + +def validate_policy(value): + if ( + not isinstance(value, dict) + or set(value) != {"schema_version", "formatters", "exclude"} + or type(value["schema_version"]) is not int + or value["schema_version"] != 1 + ): + raise ValueError( + "Formatter policy needs schema_version 1, formatters and exclude" + ) + if ( + not isinstance(value["formatters"], list) + or not value["formatters"] + or not isinstance(value["exclude"], list) + ): + raise ValueError("Configure actual formatters and explicit exclusions") + for rule in value["formatters"] + value["exclude"]: + if not isinstance(rule, dict): + raise ValueError("Invalid formatter rule") + patterns = rule.get("include") + if ( + not isinstance(patterns, list) + or not patterns + or any( + not isinstance(p, str) + or not p + or "\0" in p + or p.startswith("/") + or ".." in p.split("/") + for p in patterns + ) + ): + raise ValueError( + "Formatter include patterns must be nonempty repository-relative globs" + ) + if "argv" in rule: + argv = rule["argv"] + if ( + set(rule) - {"include", "argv", "timeout_seconds"} + or not isinstance(argv, list) + or not argv + or any(not isinstance(a, str) or not a or "\0" in a for a in argv) + ): + raise ValueError( + "A formatter requires an argv array, not a shell command" + ) + timeout = rule.get("timeout_seconds", 30) + if type(timeout) is not int or not 1 <= timeout <= 120: + raise ValueError("Formatter timeout must be between 1 and 120 seconds") + elif ( + set(rule) != {"include", "kind", "reason"} + or rule["kind"] + not in {"binary", "generated", "vendored", "non-formattable"} + or not isinstance(rule["reason"], str) + or not rule["reason"].strip() + ): + raise ValueError( + "Every formatter exclusion needs a kind and a concrete reason" + ) + if any("argv" not in r for r in value["formatters"]) or any( + "argv" in r for r in value["exclude"] + ): + raise ValueError( + "Keep formatter commands and justified exclusions in their respective lists" + ) + return value + + +def format_staged(repo): + repo = Path(repo).resolve() + git_executable = setup_files.trusted_git(repo) + environment = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + if os.environ.get("GIT_INDEX_FILE"): + environment["GIT_INDEX_FILE"] = os.environ["GIT_INDEX_FILE"] + environment.update( + GIT_TERMINAL_PROMPT="0", GCM_INTERACTIVE="never", SSH_ASKPASS_REQUIRE="never" + ) + deadline = time.monotonic() + 120 + + def execute(argv, data=None, env=None, allowed=(0,), timeout=30): + remaining = min(timeout, deadline - time.monotonic()) + if remaining <= 0: + raise ValueError("Staged formatting exceeded its 120-second deadline") + output = io.BytesIO() + with tempfile.TemporaryFile() as source, tempfile.TemporaryFile() as errors: + if data is not None: + source.write(data) + source.seek(0) + try: + code = runner.execute( + argv, + repo, + output, + remaining, + stdin=source, + environment=environment if env is None else env, + stderr=errors, + ) + except (OSError, subprocess.SubprocessError) as error: + raise ValueError( + "Formatting tool unavailable, failed or timed out: " + + Path(argv[0]).name + ) from None + if code not in allowed: + raise ValueError( + "Formatting command failed: " + + Path(argv[0]).name + + " (exit " + + str(code) + + ")" + ) + return code, output.getvalue() + + def git(*args, data=None, env=None, allowed=(0,)): + return execute( + [ + git_executable, + "--no-replace-objects", + "-c", + "core.fsmonitor=false", + "-C", + str(repo), + *args, + ], + data, + env, + allowed, + 15, + ) + + index = Path(os.fsdecode(git("rev-parse", "--git-path", "index")[1]).strip()) + if not index.is_absolute(): + index = repo / index + index = index.absolute() + original_index = read_file(index) + if original_index is None: + raise ValueError("The selected Git index is missing") + lock = index.with_name(index.name + ".lock") + # Respect the lock Git uses for the real index or --only's temporary index. + fd = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + owned_lock = os.fstat(fd) + temporary = None + + def owns_lock(): + try: + current = lock.lstat() + return (current.st_dev, current.st_ino) == ( + owned_lock.st_dev, + owned_lock.st_ino, + ) + except FileNotFoundError: + return False + + published = False + retain_recovery = False + writes = [] + pending_index = None + pending_written = False + try: + temporary = Path(tempfile.mkdtemp(prefix="studio-format-", dir=index.parent)) + if read_file(index) != original_index: + raise ValueError("Git index changed before formatting; retry the commit") + candidate = temporary / "index" + candidate.write_bytes(original_index) + candidate_env = dict(environment, GIT_INDEX_FILE=str(candidate)) + paths = git( + "diff", + "--cached", + "--name-only", + "--no-renames", + "--no-ext-diff", + "--diff-filter=ACMT", + "-z", + env=candidate_env, + )[1].split(b"\0")[:-1] + if not paths: + return [] + if len(paths) > MAX_FILES: + raise ValueError("Staged formatting exceeds 1000 files; split the commit") + paths = [os.fsdecode(p) for p in paths] + normal_env = {k: v for k, v in environment.items() if k != "GIT_INDEX_FILE"} + normal_index = Path( + os.fsdecode( + git("rev-parse", "--git-path", "index", env=normal_env)[1] + ).strip() + ) + if not normal_index.is_absolute(): + normal_index = repo / normal_index + if ( + normal_index.absolute() != index + and index.parent == normal_index.absolute().parent + and index.name.startswith("next-index-") + ): + # --only gives the hook a temporary index, while Git separately holds + # the real index's pending lock. Keep its selected entries in sync. + pending = normal_index.with_name(normal_index.name + ".lock") + pending_bytes = read_file(pending) + if pending_bytes is None: + raise ValueError( + "Alternate index requires Git partial-commit pending index" + ) + pending_info = pending.stat() + pending_candidate = temporary / "pending-index" + pending_candidate.write_bytes(pending_bytes) + pending_env = dict(environment, GIT_INDEX_FILE=str(pending_candidate)) + pending_index = (pending, pending_bytes, pending_info, pending_candidate) + + entries = {} + for row in git("ls-files", "--stage", "-z", env=candidate_env)[1].split(b"\0")[ + :-1 + ]: + meta, name = row.split(b"\t", 1) + mode, oid, stage = meta.decode("ascii").split() + if stage != "0": + raise ValueError("Resolve merge conflicts before formatting a commit") + entries[os.fsdecode(name)] = (mode, oid) + + def blob(name): + if name not in entries: + raise ValueError( + "Stage the repository formatter policy before committing: " + POLICY + ) + return git("cat-file", "blob", entries[name][1], env=candidate_env)[1] + + from .git_policy import unique + + policy_path = setup_files.confined(repo / POLICY, repo) + policy_bytes = blob(POLICY) + if read_file(policy_path) != policy_bytes: + raise ValueError("Working and staged formatter policies differ: " + POLICY) + policy = validate_policy(json.loads(policy_bytes, object_pairs_hook=unique)) + # Interpreter entrypoints are part of the selected formatter configuration. + # Never execute unstaged edits to an authored repository adapter. + adapter_inputs = set() + for rule in policy["formatters"]: + for argument in rule["argv"]: + expanded = argument.replace("{repo}", str(repo)) + adapter_path = Path(expanded) + if not adapter_path.is_absolute(): + adapter_path = repo / adapter_path + if adapter_path.is_relative_to(repo) and adapter_path.suffix in { + ".py", + ".mjs", + ".js", + ".sh", + }: + relative = adapter_path.relative_to(repo).as_posix() + if relative in entries or adapter_path.is_file(): + adapter_inputs.add(relative) + for name in adapter_inputs: + if name not in entries or read_file( + setup_files.confined(repo / name, repo) + ) != blob(name): + raise ValueError( + "Stage or restore formatter configuration before committing: " + + name + ) + # Native formatter configuration remains authoritative, but unstaged + # configuration must not silently determine the committed style. + for name in entries: + base = Path(name).name + if configuration_file(name): + if read_file(setup_files.confined(repo / name, repo)) != blob(name): + raise ValueError( + "Stage or restore formatter configuration before committing: " + + name + ) + + directories = {repo} + for name in paths: + directories.update((repo / name).parent.parents) + directories.add((repo / name).parent) + for directory in directories: + if not directory.exists(): + continue + for config in directory.iterdir(): + base = config.name + relative = ( + config.relative_to(repo).as_posix() + if config.is_relative_to(repo) + else base + ) + if configuration_file(relative): + if not config.is_file() and not config.is_symlink(): + continue + if not config.is_relative_to(repo): + raise ValueError( + "External formatter configuration must be made repository-local: " + + str(config) + ) + name = config.relative_to(repo).as_posix() + if name not in entries or read_file(config) != blob(name): + raise ValueError( + "Stage or restore formatter configuration before committing: " + + name + ) + + changes = [] + for number, name in enumerate(paths): + mode, oid = entries[name] + excluded = [ + r + for r in policy["exclude"] + if any(fnmatch.fnmatchcase(name, p) for p in r["include"]) + ] + if excluded: + if any(r["kind"] == "binary" for r in excluded) and mode in { + "100644", + "100755", + }: + content = blob(name) + try: + content.decode("utf-8") + text = b"\0" not in content + except UnicodeDecodeError: + text = False + if text: + raise ValueError( + "Text cannot use a binary formatter exclusion: " + name + ) + continue + if mode not in {"100644", "100755"}: + raise ValueError( + "Explicitly classify nonregular staged entries before formatting: " + + name + ) + rules = [ + r + for r in policy["formatters"] + if any(fnmatch.fnmatchcase(name, p) for p in r["include"]) + ] + if len(rules) != 1: + raise ValueError( + "Expected exactly one formatter for staged file: " + name + ) + target = setup_files.confined(repo / name, repo) + working = read_file(target) + original = blob(name) + if len(original) > MAX_FILE or b"\0" in original: + raise ValueError( + "Explicitly classify binary/oversized staged files: " + name + ) + argv = [ + a.replace("{path}", name).replace("{repo}", str(repo)) + for a in rules[0]["argv"] + ] + timeout = rules[0].get("timeout_seconds", 30) + try: + formatted = execute(argv, original, timeout=timeout)[1] + except ValueError as error: + raise ValueError(str(error) + ": " + name) from None + if b"\0" in formatted: + raise ValueError("Formatter returned binary output: " + name) + if original.strip() and not formatted.strip(): + raise ValueError( + "Formatter returned empty content for a nonempty file: " + name + ) + if execute(argv, formatted, timeout=timeout)[1] != formatted: + raise ValueError("Formatter is not idempotent: " + name) + if original == formatted: + continue + merged = None + if working is not None: + if working == original: + merged = formatted + else: + base_bytes, new_bytes = original, formatted + if b"\r\n" in working and b"\n" not in working.replace( + b"\r\n", b"" + ): + base_bytes = original.replace(b"\r\n", b"\n").replace( + b"\n", b"\r\n" + ) + new_bytes = formatted.replace(b"\r\n", b"\n").replace( + b"\n", b"\r\n" + ) + files = [ + temporary / (str(number) + suffix) + for suffix in (".working", ".base", ".formatted") + ] + for path, data in zip(files, (working, base_bytes, new_bytes)): + path.write_bytes(data) + code, merged = git( + "merge-file", + "--stdout", + *map(str, files), + allowed=tuple(range(128)), + ) + if code: + raise ValueError( + "Formatting conflicts with unstaged edits; index and files preserved: " + + name + ) + new_oid = ( + git("hash-object", "-w", "--stdin", data=formatted)[1] + .decode("ascii") + .strip() + ) + git( + "update-index", + "--cacheinfo", + mode + "," + new_oid + "," + name, + env=candidate_env, + ) + if pending_index is not None: + git( + "update-index", + "--cacheinfo", + mode + "," + new_oid + "," + name, + env=pending_env, + ) + changes.append((target, working, merged, name)) + + if pending_index is not None: + pending, pending_bytes, pending_info, pending_candidate = pending_index + current = pending.lstat() + if (current.st_dev, current.st_ino) != ( + pending_info.st_dev, + pending_info.st_ino, + ) or read_file(pending) != pending_bytes: + raise ValueError("Git partial-commit index changed during formatting") + if read_file(index) != original_index or any( + read_file(p) != old for p, old, new, name in changes + ): + raise ValueError( + "Index or working files changed during formatting; retry without discarding edits" + ) + for target, old, new, name in changes: + if old is not None and old != new: + # Retain original bytes until the index transaction is published. + (temporary / ("backup-" + str(len(writes)))).write_bytes(old) + writes.append((target, old, new)) + target.write_bytes(new) + if read_file(index) != original_index: + raise ValueError( + "Git index changed during formatting; preserving the concurrent index" + ) + if not owns_lock(): + raise ValueError( + "Git index lock changed during formatting; retry the commit" + ) + with os.fdopen(fd, "wb") as output: + fd = None + output.write(candidate.read_bytes()) + output.flush() + os.fsync(output.fileno()) + if not owns_lock(): + raise ValueError( + "Git index lock changed during formatting; retry the commit" + ) + if pending_index is not None: + pending_fd = os.open(pending, os.O_RDWR | getattr(os, "O_NOFOLLOW", 0)) + with os.fdopen(pending_fd, "r+b") as output: + current = os.fstat(output.fileno()) + if (current.st_dev, current.st_ino) != ( + pending_info.st_dev, + pending_info.st_ino, + ) or output.read() != pending_bytes: + raise ValueError( + "Git partial-commit index changed before publication" + ) + pending_written = True + output.seek(0) + output.write(pending_candidate.read_bytes()) + output.truncate() + output.flush() + os.fsync(output.fileno()) + os.replace(lock, index) + published = True + return [name for target, old, new, name in changes] + except BaseException: + if pending_written: + try: + current = pending.lstat() + if (current.st_dev, current.st_ino) != ( + pending_info.st_dev, + pending_info.st_ino, + ): + raise ValueError("Pending index replaced") + pending.write_bytes(pending_bytes) + except (OSError, ValueError): + (temporary / "pending-index-original").write_bytes(pending_bytes) + retain_recovery = True + for target, old, new in reversed(writes): + try: + if read_file(target) == new: + target.write_bytes(old) + else: + retain_recovery = True + except OSError: + retain_recovery = True + except ValueError: + retain_recovery = True + if retain_recovery: + print( + "Formatter recovery bytes retained at " + str(temporary), + file=__import__("sys").stderr, + ) + raise + finally: + if fd is not None: + os.close(fd) + if not published and owns_lock(): + lock.unlink() + if temporary is not None and not retain_recovery: + shutil.rmtree(temporary) diff --git a/.hypertext/formatting/core/gate.py b/.hypertext/formatting/core/gate.py new file mode 100644 index 0000000..f5763a9 --- /dev/null +++ b/.hypertext/formatting/core/gate.py @@ -0,0 +1,363 @@ +#!/usr/bin/env python3 +"""Read-only release evidence gate. Never executes commands from a target repo.""" + +from datetime import date, datetime, timezone, timedelta +import hashlib +import json +from pathlib import Path +import re +import subprocess + +ROOT = Path(__file__).resolve().parents[1] + + +def digest(path): + result = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def git_bytes(repo, *args): + from . import setup_files + code,output=setup_files.git_read(repo,*args) + if code: raise subprocess.CalledProcessError(code,['trusted git',*args],output=output) + return output + + +def git(repo, *args): + return git_bytes(repo,*args).decode('utf-8').strip() + + +def read(path): + if path.stat().st_size > 8 * 1024 * 1024: + raise ValueError("JSON exceeds the 8 MiB input limit") + def unique(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate JSON key: {key}") + result[key] = value + return result + value = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique, + parse_constant=lambda value: (_ for _ in ()).throw(ValueError("Non-finite JSON number"))) + if not isinstance(value, dict): + raise ValueError(f"Expected an object: {path.name}") + return value + + +def context(repo, profile): + if Path(git(repo, "rev-parse", "--show-toplevel")).resolve() != repo.resolve(): + raise ValueError("--repo must name the checkout root") + flags = git(repo, "ls-files", "-v", "-z").split("\0") + if any(row and (row[0].islower() or row[0] == "S") for row in flags): + raise ValueError("Hidden index flags (assume-unchanged/skip-worktree) prevent exact verification") + if git(repo, "-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false", "status", "--porcelain", "--untracked-files=all", "--ignore-submodules=none"): + raise ValueError("Release checkout has uncommitted or untracked changes") + if not profile.resolve().is_relative_to(repo.resolve()): + raise ValueError("Release profile must be inside the tested checkout") + relative = profile.resolve().relative_to(repo.resolve()).as_posix() + git(repo, "ls-files", "--error-unmatch", "--", relative) + committed = git_bytes(repo,"show",f"HEAD:{relative}") + if hashlib.sha256(committed).hexdigest() != digest(profile): + raise ValueError("Release profile must match the tested commit") + return { + "commit": git(repo, "rev-parse", "HEAD"), + "engine_sha256": hashlib.sha256("".join( + f"{name}:{digest(ROOT / 'core' / name)}\n" + for name in ("__init__.py", "gate.py", "runner.py", "bootstrap.py", "setup_files.py", "setup.py", "repository.py", "doctor.py", "install.py", "cli.py") + ).encode()).hexdigest(), + "standards_sha256": digest(ROOT / "docs/product-standards.md"), + "android_sources_sha256": digest(ROOT / "policy/android-sources/manifest.json"), + "policy_sha256": digest(ROOT / "policy/key-standards.json"), + "profile_sha256": digest(profile), + } + + +def required(profile, policy): + if set(policy) != {"version", "capabilities", "rules"} or type(policy["version"]) is not int or policy["version"] != 1: + raise ValueError("Invalid policy version or fields") + names, rules = policy["capabilities"], policy["rules"] + if not isinstance(names, list) or not names or any(not isinstance(n, str) for n in names) or len(set(names)) != len(names): + raise ValueError("Invalid policy capabilities") + if not isinstance(rules, list) or not rules: + raise ValueError("Policy needs rules") + seen = set() + for rule in rules: + if not isinstance(rule, dict) or set(rule) != {"id", "when", "evidence_kinds", "source", "exception_allowed"}: + raise ValueError("Invalid policy rule fields") + identifier = rule["id"] + if not isinstance(identifier, str) or not identifier or identifier in seen: + raise ValueError("Invalid or duplicate policy ID") + seen.add(identifier) + if not isinstance(rule["when"], list) or any(n not in names for n in rule["when"]): + raise ValueError("Unknown policy condition") + if not isinstance(rule["evidence_kinds"], list) or not rule["evidence_kinds"] or any(k not in {"automated", "observed", "device", "provider"} for k in rule["evidence_kinds"]): + raise ValueError("Invalid policy evidence kinds") + if type(rule["exception_allowed"]) is not bool or not isinstance(rule["source"], str) or not rule["source"]: + raise ValueError("Invalid policy applicability") + if set(profile) - {"schema_version", "product", "capabilities", "verification"}: + raise ValueError("Unknown profile fields") + if type(profile.get("schema_version")) is not int or profile["schema_version"] != 1 or not isinstance(profile.get("product"), str) or not profile["product"].strip(): + raise ValueError("Profile needs schema_version 1 and a nonempty product name") + capabilities = profile.get("capabilities") + if not isinstance(capabilities, dict) or set(capabilities) != set(policy["capabilities"]): + raise ValueError("Profile must explicitly declare every supported capability; no unknown keys") + if any(type(value) is not bool for value in capabilities.values()): + raise ValueError("Capabilities must be booleans") + if capabilities["android"] and not capabilities["interface"]: + raise ValueError("An Android app must declare its interface capability") + return [rule for rule in policy["rules"] if not rule["when"] or any(capabilities[key] for key in rule["when"])] + + +def artifact(record, directory): + location = record.get("artifact") + if not isinstance(location, str) or not location: + raise ValueError("Missing evidence artifact") + relative = Path(location) + if relative.is_absolute() or ".." in relative.parts: + raise ValueError("Evidence paths must be relative and cannot traverse parents") + unresolved = directory / relative + if any(directory.joinpath(*relative.parts[:index]).is_symlink() for index in range(1, len(relative.parts) + 1)): + raise ValueError("Evidence cannot use symlinks") + path = unresolved.resolve() + if not path.is_relative_to(directory.resolve()) or not path.is_file(): + raise ValueError("Artifact must be a file inside the evidence directory") + if path.stat().st_size > 256 * 1024 * 1024: + raise ValueError("Evidence artifact exceeds 256 MiB") + if path.stat().st_size == 0 or record.get("sha256") != digest(path): + raise ValueError("Evidence artifact is empty, changed, or has no matching SHA-256") + return path + + +def acceptance(path, repo, supplemental, shipping, target, signature=None, allowed_signers=None): + if path is None or shipping is None or not target: + raise ValueError("Release requires external --acceptance, --artifact and --target") + if path.resolve().is_relative_to(repo.resolve()) or path.resolve().is_relative_to(supplemental.parent.resolve()): + raise ValueError("Acceptance must come from outside the candidate and evidence directories") + value = read(path) + if set(value) != {"schema_version", "subject", "target", "artifact_sha256", "evidence_sha256", "files", "observed_at", "expires_at", "approved_exceptions"} or type(value["schema_version"]) is not int or value["schema_version"] != 1: + raise ValueError("Invalid acceptance contract") + now = datetime.now(timezone.utc) + observed, expires = (datetime.fromisoformat(value[key]) for key in ("observed_at", "expires_at")) + if observed.tzinfo is None or expires.tzinfo is None or not observed <= now < expires or expires - observed > timedelta(days=7): + raise ValueError("Acceptance is stale, future-dated, or exceeds seven days") + if value["target"] != target or value["artifact_sha256"] != digest(shipping) or value["evidence_sha256"] != digest(supplemental): + raise ValueError("Acceptance does not match target, shipping artifact, or evidence") + if not isinstance(value["approved_exceptions"], dict) or not isinstance(value["files"], dict): + raise ValueError("Invalid acceptance files or exception approvals") + if value["approved_exceptions"]: + if signature is None or allowed_signers is None or allowed_signers.resolve().is_relative_to(repo.resolve()) or allowed_signers.resolve().is_relative_to(supplemental.parent.resolve()): + raise ValueError("Exceptions require an owner-signed acceptance and externally pinned allowed signers") + from . import setup_files + verified = subprocess.run([setup_files.trusted_tool(repo,"ssh-keygen"), "-Y", "verify", "-f", str(allowed_signers), "-I", "hypertext-owner", + "-n", "hypertext-release", "-s", str(signature)], input=path.read_bytes(), capture_output=True) + if verified.returncode != 0: + raise ValueError("Owner exception signature verification failed") + actual = {p.relative_to(supplemental.parent).as_posix() for p in supplemental.parent.rglob("*") if p.is_file() or p.is_symlink()} + if actual != set(value["files"]) | {supplemental.name}: + raise ValueError("Acceptance must bind the complete evidence directory") + if sum((supplemental.parent / name).stat().st_size for name in value["files"]) > 512 * 1024 * 1024: + raise ValueError("Evidence bundle exceeds 512 MiB") + for name, sha in value["files"].items(): + artifact({"artifact": name, "sha256": sha}, supplemental.parent) + for record in read(supplemental).get("checks", []): + if value["files"].get(record.get("artifact")) != record.get("sha256"): + raise ValueError("Acceptance must bind every supplemental artifact") + return value + + +def android_matrix(path): + source = (ROOT / "docs/product-standards.md").read_text(encoding="utf-8") + start, end = "### Google Android adaptive design requirements\n", "### Research and inclusive product decisions\n" + if start not in source or end not in source: + raise ValueError("Android source boundaries require explicit reconciliation") + baseline = source.split(start, 1)[1].split(end, 1)[0] + expected = set(re.findall(r"https://developer\.android\.com/[^)\s]+#[^)\s]+", baseline)) + document = read(path) + manifest_path = ROOT / "policy/android-sources/manifest.json" + if document.get("sources_sha256") != digest(manifest_path): + raise ValueError("Android evidence must bind the frozen source manifest") + manifest = read(manifest_path) + expected_pages = set(re.findall(r"https://developer\.android\.com/[^)\s]+", baseline)) + expected_pages = {url.split("#")[0] for url in expected_pages} + if {source["url"] for source in manifest["sources"]} != expected_pages: + raise ValueError("Frozen sources do not cover the complete source baseline") + wanted_clauses = {} + for source in manifest["sources"]: + snapshot_path = ROOT / "policy/android-sources" / source["file"] + if digest(snapshot_path) != source["sha256"]: + raise ValueError("Android source snapshot changed") + for clause in read(snapshot_path)["clauses"]: + wanted_clauses[(source["url"], clause["label"])] = clause["sha256"] + coverage = document.get("clauses") + if not isinstance(coverage, list): + raise ValueError("Android needs full source clause coverage, including specialized checklists") + covered = set() + for row in coverage: + if not isinstance(row, dict): raise ValueError("Invalid source clause") + key = (row.get("source"), row.get("clause")) + if key in covered or wanted_clauses.get(key) != row.get("sha256"): + raise ValueError("Duplicate, changed or unknown Android source clause") + covered.add(key) + if row.get("status") == "not_applicable": + if not isinstance(row.get("reason"), str) or not row["reason"].strip() or not isinstance(row.get("applicability_condition"), str) or not row["applicability_condition"].strip(): + raise ValueError("Source clause exclusion needs the actual applicability condition and product reason") + elif row.get("status") != "pass" or not isinstance(row.get("observation"), str) or not row["observation"].strip(): + raise ValueError("Source clause lacks observed result") + if covered != set(wanted_clauses): + raise ValueError("Incomplete Android subclause or specialized-source coverage") + matrix = document.get("checks") + if not expected or not isinstance(matrix, list): + raise ValueError("Android evidence needs the indexed guideline/test matrix") + seen = set() + for row in matrix: + if not isinstance(row, dict) or not isinstance(row.get("source"), str): + raise ValueError("Invalid Android matrix row") + identifier = row["source"] + if identifier in seen: + raise ValueError("Duplicate Android source row") + seen.add(identifier) + if row.get("status") == "not_applicable": + if "/tier-3#Config_" in identifier or "/tier-3#T-Config_" in identifier: + raise ValueError("Mandatory configuration transitions cannot be exempted") + if not isinstance(row.get("reason"), str) or not row["reason"].strip(): + raise ValueError("Android non-applicability needs a capability-based reason") + if row.get("applicability_condition") is None or "not implemented" in row["reason"].lower(): + raise ValueError("Android exclusions need the actual source applicability condition") + elif row.get("status") != "pass" or not isinstance(row.get("observation"), str) or not row["observation"].strip(): + raise ValueError("Android row has no passing observed result") + if seen != expected: + raise ValueError("Android matrix does not cover every indexed guideline and test") + + +def record_digest(record): + return hashlib.sha256(json.dumps(record, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest() + + +def check(repo, profile_path, evidence_path, policy, approved_exceptions=None): + profile = read(profile_path) + rules = required(profile, policy) + expected = context(repo, profile_path) + evidence = read(evidence_path) + if type(evidence.get("schema_version")) is not int or evidence.get("schema_version") != 1 or evidence.get("subject") != expected: + raise ValueError("Evidence does not match this commit, profile, standards, and gate policy") + rows = evidence.get("checks") + if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows): + raise ValueError("checks must be a list of objects") + mapping = {} + for row in rows: + identifier = row.get("id") + if not isinstance(identifier, str) or identifier in mapping: + raise ValueError("Missing or duplicate check ID") + mapping[identifier] = row + if set(mapping) != {rule["id"] for rule in rules}: + missing = sorted({rule["id"] for rule in rules} - set(mapping)) + extra = sorted(set(mapping) - {rule["id"] for rule in rules}) + raise ValueError(f"Evidence must cover exactly the applicable key checks; missing/extra checks cannot pass; missing={missing}; extra={extra}") + errors = [] + for rule in rules: + record = mapping[rule["id"]] + try: + if not isinstance(record.get("summary"), str) or not record["summary"].strip(): + raise ValueError("Missing observed outcome summary") + if record.get("status") == "exception": + if not rule["exception_allowed"] or record.get("kind") != "owner-decision": + raise ValueError("This check cannot be waived") + approved = (approved_exceptions or {}).get(rule["id"]) + canonical = record_digest(record) + if approved != canonical: + raise ValueError("Exception needs an exact owner-approved record digest from the external trust boundary") + for field in ("reason", "impact", "compensation", "decided_on", "review_on"): + if not isinstance(record.get(field), str) or not record[field].strip(): + raise ValueError(f"Missing exception field: {field}") + if date.fromisoformat(record["decided_on"]) > date.today() or date.fromisoformat(record["review_on"]) <= date.today(): + raise ValueError("Exception is future-dated or expired") + elif record.get("status") != "pass" or record.get("kind") not in rule["evidence_kinds"]: + raise ValueError("Missing pass or inappropriate evidence kind") + path = artifact(record, evidence_path.parent) + if rule["id"] == "android.adaptive": + android_matrix(path) + except (ValueError, OSError) as error: + errors.append(f"{rule['id']}: {error}") + return errors + + +def diagnostics(failures, policy=None, evidence=None): + """Explain failures without changing their acceptance or exception semantics.""" + rules = {row["id"]: row for row in (policy or {}).get("rules", [])} + results = [] + for failure in failures: + identifier, _, detail = str(failure).partition(": ") + rule = rules.get(identifier) + message = detail if rule else str(failure) + action = "Correct the reported input or configuration, then rerun the same gate." + lower = message.lower() + if "command failed" in lower: + action = "Read the command report and linked log; fix the failing behavior and rerun verification into a new output directory." + elif any(term in lower for term in ("uncommitted", "untracked", "checkout", "index flags")): + action = "Inspect git status and index flags; preserve unrelated work and verify the intended clean commit." + elif any(term in lower for term in ("exception", "waived", "authorization", "trusted")): + action = "Supply the required external trust input or obtain the owner's scoped decision; the agent cannot approve or weaken this check." + elif any(term in lower for term in ("stale", "does not match", "changed", "modified", "hash", "digest")): + action = "Recollect evidence for the actual commit, policy, profile and artifact; do not edit hashes to make old evidence pass." + elif "missing/extra" in lower or "cover exactly" in lower: + action = "List applicable requirements with hypertext.py doctor --requirements; collect the missing outcomes and remove only genuinely inapplicable records." + elif "timeout" in lower: + action = "Inspect the bounded command log and resolve the hang or missing prerequisite before retrying." + elif "no such file" in lower or "not found" in lower: + action = "Supply the named file or executable at the expected path; do not substitute an asserted pass." + elif rule: + action = "Collect a passing observed outcome using an allowed evidence kind, including its artifact; rerun release validation." + results.append({"requirement": identifier if rule else "gate.input", "source": rule["source"] if rule else "Gate execution and evidence integrity", + "allowed_evidence_kinds": rule["evidence_kinds"] if rule else [], "problem": message, "evidence": str(evidence) if evidence else None, "next_action": action}) + return results + + +def report(failures, policy=None, evidence=None, json_output=False, scope="evidence-records"): + rows = diagnostics(failures, policy, evidence) + if json_output: + print(json.dumps({"status": "blocked" if rows else "passed", "scope": scope, "diagnostics": rows, "limitation": "Read-only record validation; no checks executed and no release readiness or production outcome established." if scope == 'evidence-records' else "Record integrity and executed checks do not independently prove non-automated app outcomes."}, indent=2)) + else: + for row in rows: + print(f"{row['requirement']}: {row['problem']}\n Source: {row['source']}\n Next: {row['next_action']}") + if row["evidence"]: + print(f" Evidence: {row['evidence']}") + return 1 if rows else 0 + + +def main(argv=None): + from .cli import Parser + parser = Parser(description=__doc__) + parser.add_argument("command", choices=("requirements", "subject", "check")) + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--profile", type=Path, help="Defaults to REPO/.hypertext/product.json") + parser.add_argument("--evidence", type=Path) + parser.add_argument("--json", action="store_true", help="Structured check diagnostics") + args = parser.parse_args(argv) + repo = args.repo.resolve() + profile = args.profile.resolve() if args.profile else repo / ".hypertext/product.json" + try: + policy = read(ROOT / "policy/key-standards.json") + rules = required(read(profile), policy) + if args.command == "requirements": + print(json.dumps(rules, indent=2)) + elif args.command == "subject": + print(json.dumps(context(repo, profile), indent=2)) + else: + if args.evidence is None: + raise ValueError("check requires --evidence") + failures = check(repo, profile, args.evidence.resolve(), policy) + if failures: + raise SystemExit(report(failures, policy, args.evidence, args.json)) + if args.json: + report([], policy, args.evidence, True) + else: + print(f"Evidence records accepted for {len(rules)} key checks. This does not independently prove app behavior or full conformance.") + except (OSError, ValueError, subprocess.CalledProcessError) as error: + raise SystemExit(report([str(error)], locals().get("policy"), args.evidence, args.json)) + + +if __name__ == "__main__": + main() diff --git a/.hypertext/formatting/core/git_policy.py b/.hypertext/formatting/core/git_policy.py new file mode 100644 index 0000000..036ff1f --- /dev/null +++ b/.hypertext/formatting/core/git_policy.py @@ -0,0 +1,942 @@ +"""Studio commit contracts, local hooks and changelogs. No host or agent dependency.""" + +import hashlib +import contextvars +import functools +import io +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import time + +POLICY_PATH = ".hypertext/commits.json" +FORBIDDEN_SCOPES = { + "internal", + "misc", + "other", + "general", + "all", + "core", + "ui", + "frontend", + "backend", + "components", + "utils", + "tests", + "docs", + "ci", + "build", + "refactor", + "deps", +} +HEADER = re.compile( + r"(feat|fix|chore)\(([a-z][a-z0-9]*(?:-[a-z0-9]+)*)\)(!)?: (\S(?:.*\S)?)" +) +IDENTITY = re.compile(r"[^<>\r\n]+ <[^<>\s@]+@[^<>\s@]+>") +TECHNICAL = re.compile( + r"\b(?:refactor(?:ing|ed)?|middleware|JWT|OAuth|SQL|React|SwiftUI|ViewModel|DTO|ORM|webpack|tsconfig|node_modules|useEffect)\b|`[^`]+`|\b\w+\.(?:tsx?|jsx?|py|swift|kt|rs)\b", + re.I, +) +VAGUE = re.compile( + r"^(?:update|fix|change|improve|add|remove)(?: (?:stuff|things|code|files|misc|something|updates?))?[.!]?$", + re.I, +) +MARKER = "# Hypertext Studio managed Git hook v1" +DEADLINE = contextvars.ContextVar("git_policy_deadline", default=None) +MAX_COMMITS = 10000 + + +def bounded_history(function): + @functools.wraps(function) + def run(*args, **kwargs): + token = DEADLINE.set(time.monotonic() + 60) + try: + return function(*args, **kwargs) + finally: + DEADLINE.reset(token) + + return run + + +def unique(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("Duplicate commit-policy key: " + key) + result[key] = value + return result + + +def read_text(path): + path = Path(path) + if ( + path.is_symlink() + or not path.is_file() + or path.stat().st_nlink != 1 + or path.stat().st_size > 1024 * 1024 + ): + raise ValueError("Expected a regular file under 1 MiB: " + str(path)) + with path.open(encoding="utf-8", newline="") as stream: + return stream.read() + + +def validate_policy(value): + if ( + not isinstance(value, dict) + or set(value) != {"schema_version", "scopes"} + or type(value["schema_version"]) is not int + or value["schema_version"] != 1 + ): + raise ValueError("Commit policy requires schema_version 1 and scopes") + scopes = value["scopes"] + if not isinstance(scopes, dict) or not scopes: + raise ValueError("Define actual product domains in the commit scope registry") + for name, scope in scopes.items(): + if ( + not re.fullmatch(r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*", name) + or name in FORBIDDEN_SCOPES + ): + raise ValueError( + "Scope must name a feature/domain, never a catch-all or implementation layer: " + + name + ) + if ( + not isinstance(scope, dict) + or set(scope) != {"description", "includes", "excludes", "technical"} + or type(scope["technical"]) is not bool + ): + raise ValueError( + "Each scope needs description, includes, excludes and an explicit technical boolean: " + + name + ) + if ( + not isinstance(scope["description"], str) + or not scope["description"].strip() + ): + raise ValueError( + "Scope needs an understandable domain description: " + name + ) + for key in ("includes", "excludes"): + if ( + not isinstance(scope[key], list) + or not scope[key] + or any( + not isinstance(item, str) or not item.strip() for item in scope[key] + ) + ): + raise ValueError( + "Define scope boundaries with nonempty includes and excludes: " + + name + ) + return value + + +def read_policy(path): + return validate_policy(json.loads(read_text(path), object_pairs_hook=unique)) + + +def trailers(message): + """Only terminal trailer paragraphs count; quoted claims in prose do not.""" + block = message.strip().split("\n\n")[-1] + lines = block.splitlines() + if not lines or not all( + re.match(r"^[A-Za-z][A-Za-z -]*: .+", line) or line.startswith((" ", "\t")) + for line in lines + ): + return [] + return [ + (key.lower(), value.strip()) + for line in lines + if not line.startswith((" ", "\t")) + for key, value in [line.split(": ", 1)] + ] + + +def coauthors(message): + values = [value for key, value in trailers(message) if key == "co-authored-by"] + if any(not IDENTITY.fullmatch(value) for value in values): + raise ValueError( + "Co-authored-by must contain the actual contributor name and email" + ) + return values + + +def validate_message(message, policy, expected_agents=()): + validate_policy(policy) + if ( + not isinstance(message, str) + or not message + or "\r" in message + or any(ord(c) < 32 and c not in "\n\t" for c in message) + ): + raise ValueError("Commit message must be plain text with LF line endings") + lines = message.rstrip().split("\n") + match = HEADER.fullmatch(lines[0]) + if not match: + raise ValueError( + "Use feat(scope): outcome, fix(scope): outcome, or chore(scope): specific maintenance" + ) + kind, scope, bang, description = match.groups() + if scope not in policy["scopes"]: + raise ValueError( + "Unregistered scope " + + scope + + "; choose an existing domain. New feature categories require owner review" + ) + if VAGUE.fullmatch(description) or description.lower() in { + "wip", + "work in progress", + "changes", + "updates", + }: + raise ValueError( + "Describe the actual high-level change; generic maintenance messages are insufficient" + ) + if len(lines) > 1 and lines[1] != "": + raise ValueError("Separate the title and body/trailers with a blank line") + authors = coauthors(message) + for agent in expected_agents: + if not IDENTITY.fullmatch(agent): + raise ValueError("Expected agent attribution must be Name ") + if agent not in authors: + raise ValueError("Missing terminal Co-authored-by: " + agent) + + # Machine footers are metadata, not product prose. A technical word in body + # prose still fails even when followed by otherwise valid attribution. + def metadata(line): + if re.fullmatch(r"Co-authored-by: " + IDENTITY.pattern, line, re.I): + return True + return bool( + re.fullmatch( + r"(?:Refs|Closes|Fixes): (?:#[0-9]+|[A-Z][A-Z0-9]+-[0-9]+|https://[^\s]+)(?:, (?:#[0-9]+|[A-Z][A-Z0-9]+-[0-9]+|https://[^\s]+))*", + line, + ) + ) + + narrative = "\n".join(line for line in lines if not metadata(line)) + if ( + kind in {"feat", "fix"} + and not policy["scopes"][scope]["technical"] + and TECHNICAL.search(narrative) + ): + raise ValueError( + "Use product-facing language for " + + scope + + "; explain what people can do or what now works" + ) + body = "\n".join(lines[2:]).strip() + footer_block = message.strip().split("\n\n")[-1] if trailers(message) else "" + substantive = ( + body[: -len(footer_block)].strip() + if footer_block and body.endswith(footer_block) + else body + ) + if kind == "chore" and not substantive: + raise ValueError( + "chore needs a body explaining the maintenance and why it matters; attribution alone is insufficient" + ) + breaking = re.search(r"^BREAKING(?: CHANGE|-CHANGE): (\S[^\n]*)", message, re.M) + if bang and not breaking: + raise ValueError( + "Breaking changes require a BREAKING CHANGE: explanation and migration impact" + ) + return { + "type": kind, + "scope": scope, + "description": description, + "breaking": breaking.group(1) if breaking else None, + "coauthors": authors, + } + + +def git(repo, *args, identity=False): + from . import setup_files, runner + + environment = dict(os.environ) + for key in list(environment): + if key.startswith("GIT_") and not identity: + environment.pop(key) + environment.update( + GIT_TERMINAL_PROMPT="0", GCM_INTERACTIVE="never", SSH_ASKPASS_REQUIRE="never" + ) + timeout = ( + min(15, max(0, DEADLINE.get() - time.monotonic())) if DEADLINE.get() else 15 + ) + if timeout <= 0: + raise ValueError( + "Git history inspection exceeded 60 seconds; narrow the transaction" + ) + output = io.BytesIO() + argv = [ + setup_files.trusted_git(Path(repo)), + "--no-replace-objects", + "-c", + "core.fsmonitor=false", + "-c", + "protocol.ext.allow=never", + "-C", + str(repo), + *args, + ] + try: + code = runner.execute( + argv, + Path(repo), + output, + timeout, + stdin=subprocess.DEVNULL, + environment=environment, + ) + except (OSError, subprocess.SubprocessError) as error: + raise ValueError( + "Git inspection stopped: " + + args[0] + + "; command time/output limit or execution failure" + ) from None + # Never echo remote URLs, credential-bearing errors or message contents. + if code: + raise ValueError( + "Git inspection failed: " + + args[0] + + "; check repository, access and fetched history" + ) + try: + return output.getvalue().decode("utf-8").strip() + except UnicodeError: + raise ValueError("Git inspection returned invalid UTF-8: " + args[0]) from None + + +def check_hook_context(repo): + expected = git(repo, "rev-parse", "--absolute-git-dir") + actual = git(repo, "rev-parse", "--absolute-git-dir", identity=True) + if Path(actual).resolve() != Path(expected).resolve(): + raise ValueError( + "Hook repository context differs from the checkout; use the intended worktree" + ) + + +def complete_history(repo): + if git(repo, "rev-parse", "--is-shallow-repository") != "false": + raise ValueError( + "Shallow history cannot establish commit coverage; fetch complete history" + ) + graft = Path(git(repo, "rev-parse", "--git-path", "info/grafts")) + if not graft.is_absolute(): + graft = Path(repo) / graft + if graft.exists() or graft.is_symlink(): + raise ValueError( + "Grafted history cannot establish commit coverage; remove the graph override" + ) + + +def tree_policy(repo, tree): + return validate_policy( + json.loads( + git(repo, "show", tree + ":" + POLICY_PATH), object_pairs_hook=unique + ) + ) + + +def authorized_policy(repo, candidate, baseline): + if candidate == baseline: + return + digest = hashlib.sha256( + read_text(Path(repo) / POLICY_PATH).encode("utf-8") + ).hexdigest() + if os.environ.get("HYPERTEXT_APPROVED_COMMIT_POLICY_SHA256") != digest: + raise ValueError( + "Scope registry differs from committed/published policy; owner review and exact policy authorization required" + ) + + +def hook_policy(repo): + check_hook_context(repo) + policy = read_policy(Path(repo) / POLICY_PATH) + # Git supplies a temporary index for partial commits. Inspect that exact index. + staged = validate_policy( + json.loads( + git(repo, "show", ":" + POLICY_PATH, identity=True), + object_pairs_hook=unique, + ) + ) + if staged != policy: + raise ValueError( + "Working and staged scope registries differ; stage the reviewed registry with its change" + ) + if git(repo, "rev-parse", "--revs-only", "HEAD"): + authorized_policy(repo, policy, tree_policy(repo, "HEAD")) + return policy + + +def check_registry(repo, policy): + from . import setup_files + + path = setup_files.confined(Path(repo) / POLICY_PATH, Path(repo)) + if read_policy(path) != policy: + raise ValueError( + "Candidate scope registry differs from the trusted baseline; review scope changes separately before using them" + ) + + +@bounded_history +def verify_range(repo, base, head, policy, synthetic_head=False): + complete_history(repo) + check_registry(repo, policy) + + def resolve(value): + result = git( + repo, "rev-parse", "--verify", "--end-of-options", value + "^{commit}" + ) + if not re.fullmatch(r"[a-f0-9]{40}|[a-f0-9]{64}", result): + raise ValueError("Expected an exact commit identity") + return result + + base, head = resolve(base), resolve(head) + git(repo, "merge-base", "--is-ancestor", base, head) + commits = git( + repo, + "rev-list", + "--reverse", + "--max-count=" + str(MAX_COMMITS + 1), + base + ".." + head, + ).splitlines() + if not commits: + raise ValueError( + "No new commits in the selected range; choose the actual previous release/base" + ) + if len(commits) > MAX_COMMITS: + raise ValueError("Commit range exceeds 10000 commits") + return validate_commits(repo, commits, policy, head if synthetic_head else None) + + +def validate_commits(repo, commits, policy, synthetic_head=None): + rows = [] + for commit in commits: + parents = git(repo, "rev-list", "--parents", "-n", "1", commit).split()[1:] + if len(parents) > 1: + if commit == synthetic_head: + continue # host-created merge-queue candidate only + raise ValueError( + "Merge commits cannot enter the Studio changelog; rebase the change before main: " + + commit[:12] + ) + message = git(repo, "show", "-s", "--format=%B", commit) + try: + row = validate_message(message, policy) + except ValueError as error: + raise ValueError(commit[:12] + ": " + str(error)) from error + row["commit"] = commit + rows.append(row) + if not rows: + raise ValueError("No product commits validated in the selected range") + return rows + + +def validate_host_policy(value): + expected = { + "default_branch": "main", + "allow_rebase_merge": True, + "allow_merge_commit": False, + "allow_squash_merge": False, + } + if not isinstance(value, dict): + raise ValueError( + "Repository merge settings must be an authenticated API object" + ) + for key, wanted in expected.items(): + if type(value.get(key)) is not type(wanted) or value[key] != wanted: + raise ValueError( + "Repository must use main and rebase-only PR merging; configure " + + key + + "=" + + str(wanted) + ) + + +@bounded_history +def verify_main_range(repo, base, head, policy, main_ref="refs/heads/main"): + if main_ref not in {"refs/heads/main", "refs/remotes/origin/main"}: + raise ValueError("Changelog authority must be main, never a topic branch") + complete_history(repo) + head = git(repo, "rev-parse", "--verify", "--end-of-options", head + "^{commit}") + try: + git(repo, "merge-base", "--is-ancestor", head, main_ref) + except ValueError: + raise ValueError( + "Product changelogs require commits landed on main; fetch main and integrate the change first" + ) from None + return verify_range(repo, base, head, policy) + + +def validate_squash(message, rows, policy): + agents = sorted({agent for row in rows for agent in row["coauthors"]}) + return validate_message(message, policy, agents) + + +def changelog(rows, policy): + lines = ["# Changelog", ""] + breaking = [row for row in rows if row["breaking"]] + if breaking: + lines += ["## Breaking changes", ""] + lines += ["- " + row["breaking"] for row in breaking] + lines += [""] + for title, kinds in (("Changes", {"feat", "fix"}), ("Maintenance", {"chore"})): + selected = [row for row in rows if row["type"] in kinds] + if not selected: + continue + lines += ["## " + title, ""] + for scope in sorted({row["scope"] for row in selected}): + lines += ["### " + policy["scopes"][scope]["description"], ""] + lines += [ + "- " + row["description"] for row in selected if row["scope"] == scope + ] + lines += [""] + return "\n".join(lines) + + +def hook_contents(root, relative=False): + launcher = Path(root) / "scripts/hypertext.py" + # Installed product launchers remain relative to the checkout; plugin-owned + # installations can also use their verified package until gate adoption. + import shlex + + location = "scripts/hypertext.py" if relative else str(launcher) + prefix = "exec python3 " + shlex.quote(location) + ' verify --repo "$PWD" ' + return { + "pre-commit": "#!/bin/sh\n" + MARKER + "\n" + prefix + "--git-precommit\n", + "commit-msg": "#!/bin/sh\n" + MARKER + "\n" + prefix + '--git-message "$1"\n', + "pre-push": "#!/bin/sh\n" + + MARKER + + "\n" + + prefix + + '--git-prepush --git-remote "$1" --git-remote-url "$2"\n', + } + + +def install_hooks(repo, root, apply=False): + from . import setup_files + + repo = Path(repo).resolve() + if Path(git(repo, "rev-parse", "--show-toplevel")).resolve() != repo: + raise ValueError("Git hook installation requires the checkout root") + configured = ( + git(repo, "config", "--get-regexp", r"^core\.hooksPath$") + if git_configured(repo) + else "" + ) + if configured and configured.split(None, 1)[-1] != ".githooks": + raise ValueError( + "Existing core.hooksPath needs explicit reconciliation; no hooks were replaced" + ) + default = Path(git(repo, "rev-parse", "--git-common-dir")) + if not default.is_absolute(): + default = repo / default + old_hooks = default / "hooks" + if old_hooks.is_dir(): + for existing in old_hooks.iterdir(): + if not existing.name.endswith(".sample"): + raise ValueError( + "Existing Git hook needs explicit reconciliation: " + str(existing) + ) + target = setup_files.confined(repo / ".githooks", repo) + hooks = hook_contents(root, relative=Path(root).resolve() == repo) + for name, content in hooks.items(): + path = setup_files.confined(target / name, repo) + if path.exists() and read_text(path) != content: + raise ValueError( + "Existing hook differs; preserve and reconcile " + str(path) + ) + if apply: + target.mkdir(exist_ok=True) + for name, content in hooks.items(): + path = target / name + if not path.exists(): + with path.open("x", encoding="utf-8", newline="\n") as stream: + stream.write(content) + path.chmod(path.stat().st_mode | 0o111) + git(repo, "config", "--local", "core.hooksPath", ".githooks") + return { + "applied": apply, + "hooks": sorted(hooks), + "hooks_path": ".githooks", + "host_protection": "unverified", + } + + +def git_configured(repo): + # --get exits 1 for an absent value; don't conflate it with inspection errors. + return bool( + git(repo, "config", "--list", "--name-only") + .splitlines() + .count("core.hookspath") + ) + + +def repository_contract(repo, active=False): + from . import setup_files + + repo = Path(repo).resolve() + policy = read_policy(setup_files.confined(repo / POLICY_PATH, repo)) + for name, content in hook_contents(repo, relative=True).items(): + path = setup_files.confined(repo / ".githooks" / name, repo) + if read_text(path) != content: + raise ValueError( + "Missing/modified Studio hook: " + name + "; reconcile and reinstall" + ) + if active and os.name != "nt" and not os.access(path, os.X_OK): + raise ValueError("Studio hook is not executable: " + name) + if active: + if ( + not git_configured(repo) + or git(repo, "config", "--get", "core.hooksPath") != ".githooks" + ): + raise ValueError( + "Local Git hooks are not active; install --git-hooks --apply when authorized" + ) + return policy + + +def require_studio_identity(repo): + check_hook_context(repo) + identity = git(repo, "var", "GIT_COMMITTER_IDENT", identity=True) + match = re.search(r"<([^<>]+)>", identity) + if not match: + raise ValueError("Git could not resolve the effective committer email") + email = match.group(1) + if not re.fullmatch(r"[^@\s]+@hypertext\.studio", email, re.I | re.ASCII): + if os.environ.get("HYPERTEXT_ALLOW_NON_STUDIO_EMAIL") == "1": + return "Explicit non-Studio committer exception: " + email + raise ValueError( + "Committer " + + email + + " is outside @hypertext.studio. Set git config --local user.email YOUR@hypertext.studio and clear conflicting identity overrides. An authorized exception requires HYPERTEXT_ALLOW_NON_STUDIO_EMAIL=1 for this operation. Co-authored-by emails are unrestricted." + ) + return None + + +@bounded_history +def verify_push(repo, remote, updates, policy, remote_url=None): + """Validate the exact ref-update transaction supplied by native Git pre-push.""" + check_registry(repo, policy) + complete_history(repo) + if len(updates) > 1024 * 1024: + raise ValueError("Push transaction exceeds 1 MiB") + lines = updates.splitlines() + if len(lines) > 1024: + raise ValueError("Push transaction exceeds 1024 refs") + inspected = set() + published = None + queried = False + + def commit(oid): + return git(repo, "rev-parse", "--verify", "--end-of-options", oid + "^{commit}") + + for line in lines: + parts = line.split() + if len(parts) != 4 or any( + not re.fullmatch(r"[a-f0-9]{40}|[a-f0-9]{64}", oid) + for oid in (parts[1], parts[3]) + ): + raise ValueError("Malformed native pre-push ref transaction") + local_ref, local_oid, remote_ref, remote_oid = parts + if not remote_ref.startswith("refs/"): + raise ValueError("Expected a full remote ref name") + git(repo, "check-ref-format", remote_ref) + if set(local_oid) == {"0"}: + if remote_ref == "refs/heads/main": + raise ValueError("Deleting main is prohibited") + continue + head = commit(local_oid) + if tree_policy(repo, head) != policy: + raise ValueError( + "Pushed ref scope registry differs from selected policy; inspect the actual outgoing branch" + ) + base = None + if set(remote_oid) != {"0"}: + try: + previous = commit(remote_oid) + except ValueError as error: + raise ValueError( + "Remote history is unavailable locally; fetch the remote before pushing" + ) from error + base = git(repo, "merge-base", previous, head) + authorized_policy(repo, policy, tree_policy(repo, previous)) + if remote_ref == "refs/heads/main" and base != previous: + raise ValueError("Rewriting main history is prohibited") + else: + # Local tracking refs are editable. Query the actual push destination + # once, never a fetch URL or a guessed local branch. + if not queried: + url = remote_url or git(repo, "remote", "get-url", "--push", remote) + advertised = git( + repo, "ls-remote", "--", url, "refs/heads/main" + ).splitlines() + if advertised: + if len(advertised) != 1 or not re.fullmatch( + r"(?:[a-f0-9]{40}|[a-f0-9]{64})\trefs/heads/main", advertised[0] + ): + raise ValueError("Remote main advertisement is malformed") + try: + published = commit(advertised[0].split()[0]) + except ValueError as error: + raise ValueError( + "Published main history is missing locally; fetch the push destination" + ) from error + queried = True + previous = published + if previous is not None: + authorized_policy(repo, policy, tree_policy(repo, previous)) + if previous is not None: + base = git(repo, "merge-base", previous, head) + selection = base + ".." + head if base else head + commits = git( + repo, + "rev-list", + "--reverse", + "--max-count=" + str(MAX_COMMITS + 1), + selection, + ).splitlines() + if len(set(commits) | inspected) > MAX_COMMITS: + raise ValueError("Push transaction exceeds 10000 unique commits") + new = [oid for oid in commits if oid not in inspected] + if new: + validate_commits(repo, new, policy) + inspected.update(commits) + return len(inspected) + + +def main(argv, command): + from .cli import Parser + + parser = Parser( + prog="hypertext " + command, + description=__doc__, + repeatable=("--agent-coauthor",), + ) + parser.add_argument("--repo", type=Path, required=True) + modes = parser.add_mutually_exclusive_group(required=True) + modes.add_argument( + "--git-host-policy", + type=Path, + help="Validate authenticated repository API merge settings", + ) + modes.add_argument("--git-message", type=Path) + modes.add_argument("--git-range", help="BASE..HEAD, with explicit endpoints") + modes.add_argument( + "--git-identity", + action="store_true", + help="Enforce local committer identity (legacy hook entry)", + ) + modes.add_argument( + "--git-precommit", + action="store_true", + help="Shared pre-commit staged formatting, identity and registry gate", + ) + modes.add_argument( + "--git-prepush", + action="store_true", + help="Validate the native ref transaction on stdin", + ) + parser.add_argument( + "--git-main-ref", + choices=("refs/heads/main", "refs/remotes/origin/main"), + help="Main ref used as changelog authority", + ) + parser.add_argument("--git-remote", help="Remote name supplied by native pre-push") + parser.add_argument( + "--git-remote-url", help="Actual destination supplied by native pre-push" + ) + parser.add_argument("--trusted-git-policy", type=Path) + parser.add_argument( + "--approved-git-policy-sha256", + help="Owner-controlled authorization for one exact scope-registry change", + ) + parser.add_argument("--git-squash-message", type=Path) + parser.add_argument( + "--git-synthetic-head", + action="store_true", + help="Only for a protected host merge-queue synthetic HEAD", + ) + parser.add_argument("--agent-coauthor", action="append", default=[]) + parser.add_argument( + "--changelog", + action="store_true", + help="Write generated Markdown to stdout from a validated range", + ) + args = parser.parse_args(argv) + try: + if args.git_host_policy: + if command != "verify" or any( + ( + args.changelog, + args.git_main_ref, + args.trusted_git_policy, + args.git_squash_message, + args.git_synthetic_head, + args.agent_coauthor, + args.approved_git_policy_sha256, + args.git_remote, + args.git_remote_url, + ) + ): + raise ValueError( + "Repository settings validation requires verify --git-host-policy only" + ) + validate_host_policy( + json.loads(read_text(args.git_host_policy), object_pairs_hook=unique) + ) + print( + "Repository settings require rebase-only PR merging on main; required-check protection must be activated separately." + ) + return 0 + if args.git_main_ref and not args.changelog: + raise ValueError("--git-main-ref is only valid for a main changelog") + if args.changelog and (args.git_squash_message or args.git_synthetic_head): + raise ValueError( + "Main changelogs cannot use a squash proposal or synthetic merge head" + ) + if args.git_identity or args.git_precommit: + if command != "verify" or any( + ( + args.changelog, + args.trusted_git_policy, + args.git_squash_message, + args.agent_coauthor, + args.git_synthetic_head, + args.approved_git_policy_sha256, + args.git_remote, + args.git_remote_url, + ) + ): + raise ValueError( + "Pre-commit identity checks cannot combine with history or release options" + ) + exception = require_studio_identity(args.repo) + if exception: + print(exception, file=sys.stderr) + if args.git_precommit: + hook_policy(args.repo) + from .formatting import format_staged + + changed = format_staged(args.repo) + hook_policy(args.repo) + if changed: + print( + "Automatically formatted " + + str(len(changed)) + + " staged file(s)." + ) + return 0 + if args.git_prepush: + if ( + command != "verify" + or not args.git_remote + or any( + ( + args.changelog, + args.trusted_git_policy, + args.git_squash_message, + args.agent_coauthor, + args.git_synthetic_head, + args.approved_git_policy_sha256, + ) + ) + ): + raise ValueError( + "Pre-push requires verify --git-prepush --git-remote NAME without release/range options" + ) + policy = read_policy(args.repo / POLICY_PATH) + check_hook_context(args.repo) + verify_push( + args.repo, + args.git_remote, + sys.stdin.read(1024 * 1024 + 1), + policy, + args.git_remote_url, + ) + return 0 + if args.git_remote or args.git_remote_url: + raise ValueError("Remote options are only valid for --git-prepush") + if args.changelog and (command != "release" or not args.git_range): + raise ValueError( + "Generate changelogs with release --changelog --git-range BASE..HEAD" + ) + if command == "release" and not args.changelog: + raise ValueError( + "Use release --changelog for Git-only release notes; normal release gates remain separate" + ) + if (args.git_squash_message or args.git_synthetic_head) and not args.git_range: + raise ValueError("Squash/merge-queue validation requires a commit range") + if args.trusted_git_policy and args.trusted_git_policy.resolve().is_relative_to( + args.repo.resolve() + ): + raise ValueError("Trusted scope policy must be outside candidate control") + policy = read_policy(args.trusted_git_policy or args.repo / POLICY_PATH) + if args.approved_git_policy_sha256: + if not args.trusted_git_policy: + raise ValueError( + "Scope authorization requires a protected baseline policy" + ) + candidate = args.repo / POLICY_PATH + if ( + hashlib.sha256(candidate.read_bytes()).hexdigest() + != args.approved_git_policy_sha256 + ): + raise ValueError( + "Scope authorization does not match the exact candidate policy" + ) + policy = read_policy(candidate) + check_registry(args.repo, policy) + if args.git_message: + if not args.trusted_git_policy: + policy = hook_policy(args.repo) + expected = args.agent_coauthor or ( + [os.environ["HYPERTEXT_AGENT_COAUTHOR"]] + if os.environ.get("HYPERTEXT_AGENT_COAUTHOR") + else [] + ) + validate_message( + read_text(args.git_message).replace("\r\n", "\n"), policy, expected + ) + else: + endpoints = args.git_range.split("..") + if len(endpoints) != 2 or not all(endpoints): + raise ValueError( + "Supply an explicit BASE..HEAD range, not a three-dot or implicit range" + ) + if args.changelog: + rows = verify_main_range( + args.repo, + *endpoints, + policy, + main_ref=args.git_main_ref or "refs/heads/main", + ) + else: + rows = verify_range( + args.repo, + *endpoints, + policy, + synthetic_head=args.git_synthetic_head, + ) + for row in rows: + if any(agent not in row["coauthors"] for agent in args.agent_coauthor): + raise ValueError( + "Commit " + + row["commit"][:12] + + " is missing expected agent attribution" + ) + if args.git_squash_message: + validate_squash(read_text(args.git_squash_message), rows, policy) + if args.changelog: + print(changelog(rows, policy)) + return 0 + print( + "Commit structure and registered scopes passed; semantic review and contribution truth remain required." + ) + return 0 + except (OSError, ValueError, subprocess.SubprocessError) as error: + print("Git policy blocked: " + str(error), file=sys.stderr) + return 1 diff --git a/.hypertext/formatting/core/runner.py b/.hypertext/formatting/core/runner.py new file mode 100644 index 0000000..e4df29f --- /dev/null +++ b/.hypertext/formatting/core/runner.py @@ -0,0 +1,673 @@ +"""Execute repository checks and enforce release evidence without an agent.""" + +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import time +import threading +import queue +import sys +from . import gate + + +def configuration(profile, rules): + checks = profile.get("verification") + allowed = {rule["id"] for rule in rules if "automated" in rule["evidence_kinds"]} + if not isinstance(checks, list) or not checks: + raise ValueError("Profile needs a nonempty verification command list") + seen = set() + for entry in checks: + if not isinstance(entry, dict) or set(entry) != { + "id", + "argv", + "timeout_seconds", + }: + raise ValueError("Each command needs exactly id, argv, timeout_seconds") + identifier, argv = entry["id"], entry["argv"] + if ( + not isinstance(identifier, str) + or identifier not in allowed + or identifier in seen + ): + raise ValueError( + "Unknown, inapplicable, non-automated, or duplicate command ID" + ) + if ( + not isinstance(argv, list) + or not argv + or any(not isinstance(arg, str) or not arg or "\x00" in arg for arg in argv) + ): + raise ValueError("argv must be a nonempty list of nonempty strings") + timeout = entry["timeout_seconds"] + if type(timeout) is not int or not 1 <= timeout <= 3600: + raise ValueError( + "Command timeout must be an integer from 1 to 3600 seconds" + ) + seen.add(identifier) + if "execution.verification" not in seen: + raise ValueError( + "execution.verification must execute; no asserted-pass substitute" + ) + return checks + + +def watch_windows_parent(pid): + """Stop an isolated CLI if its waiting Windows wrapper is terminated.""" + import ctypes as c + from ctypes import wintypes as w + + if pid != os.getppid(): + raise ValueError("Windows wrapper parent changed before setup") + kernel = c.WinDLL("kernel32", use_last_error=True) + kernel.OpenProcess.argtypes = [w.DWORD, w.BOOL, w.DWORD] + kernel.OpenProcess.restype = w.HANDLE + kernel.GetCurrentProcess.restype = w.HANDLE + kernel.GetProcessTimes.argtypes = [w.HANDLE, *([c.c_void_p] * 4)] + kernel.WaitForSingleObject.argtypes = [w.HANDLE, w.DWORD] + kernel.CloseHandle.argtypes = [w.HANDLE] + parent = kernel.OpenProcess( + 0x101000, False, pid + ) # SYNCHRONIZE | QUERY_LIMITED_INFORMATION + if not parent: + raise c.WinError(c.get_last_error()) + try: + times = [] + for handle in (parent, kernel.GetCurrentProcess()): + values = (c.c_uint64 * 4)() + if not kernel.GetProcessTimes( + handle, *[c.byref(values, i * 8) for i in range(4)] + ): + raise c.WinError(c.get_last_error()) + times.append(values[0]) + if times[0] > times[1] or kernel.WaitForSingleObject(parent, 0) != 258: + raise ValueError("Windows wrapper exited before setup; refusing PID reuse") + except BaseException: + kernel.CloseHandle(parent) + raise + + def watch(): + kernel.WaitForSingleObject(parent, 0xFFFFFFFF) + # OS closure of our job handles kills command descendants even on hard exit. + os._exit(130) + + threading.Thread(target=watch, daemon=True).start() + + +def windows_job(): + """An unnamed, non-breakaway job; closing its last handle kills descendants.""" + import ctypes as c + from ctypes import wintypes as w + + kernel = c.WinDLL("kernel32", use_last_error=True) + kernel.CreateJobObjectW.argtypes = [c.c_void_p, w.LPCWSTR] + kernel.CreateJobObjectW.restype = w.HANDLE + kernel.SetInformationJobObject.argtypes = [w.HANDLE, c.c_int, c.c_void_p, w.DWORD] + kernel.CloseHandle.argtypes = [w.HANDLE] + + class Basic(c.Structure): + _fields_ = [ + ("times", c.c_int64 * 2), + ("flags", w.DWORD), + ("minimum", c.c_size_t), + ("maximum", c.c_size_t), + ("active", w.DWORD), + ("affinity", c.c_size_t), + ("priority", w.DWORD), + ("scheduling", w.DWORD), + ] + + class Extended(c.Structure): + _fields_ = [ + ("basic", Basic), + ("io", c.c_uint64 * 6), + ("limits", c.c_size_t * 4), + ] + + job = kernel.CreateJobObjectW(None, None) + if not job: + raise c.WinError(c.get_last_error()) + info = Extended() + info.basic.flags = 0x2000 # KILL_ON_JOB_CLOSE, no breakaway + if not kernel.SetInformationJobObject(job, 9, c.byref(info), c.sizeof(info)): + kernel.CloseHandle(job) + raise c.WinError(c.get_last_error()) + return job, kernel + + +# The trusted isolated launcher joins the job BEFORE spawning any project code. +# Unlike assigning Popen's child afterward, this leaves no descendant-escape race. +WINDOWS_LAUNCHER = """ +import ctypes as c, json, subprocess, sys +from ctypes import wintypes as w +k=c.WinDLL('kernel32',use_last_error=True) +k.GetCurrentProcess.restype=w.HANDLE +k.AssignProcessToJobObject.argtypes=[w.HANDLE,w.HANDLE] +k.CloseHandle.argtypes=[w.HANDLE] +h=int(sys.argv[1]) +if not k.AssignProcessToJobObject(h,k.GetCurrentProcess()): + raise c.WinError(c.get_last_error()) +k.CloseHandle(h) +sys.exit(subprocess.call(json.loads(sys.argv[2]), shell=False, close_fds=True)) +""" + + +def windows_executable(name, repo, environment): + """Resolve explicit local commands against the project; never search CWD implicitly.""" + values = {key.upper(): value for key, value in environment.items()} + path = Path(name) + if path.is_absolute() or path.parent != Path(".") or "/" in name or "\\" in name: + candidates = [path if path.is_absolute() else Path(repo) / path] + else: + suffixes = [""] if path.suffix else [".exe", ".com"] + candidates = [ + Path(directory) / (name + suffix) + for directory in values.get("PATH", "").split(os.pathsep) + if directory and Path(directory).is_absolute() + for suffix in suffixes + ] + for candidate in candidates: + if candidate.suffix.lower() in {".exe", ".com"} and candidate.is_file(): + return str(candidate.absolute()) + raise FileNotFoundError( + "Windows native executable unavailable; scripts require an explicit trusted interpreter" + ) + + +def stop_windows_job(job, kernel): + """Terminate explicitly, then prove the entire job drained before returning success.""" + import ctypes as c + from ctypes import wintypes as w + + kernel.TerminateJobObject.argtypes = [w.HANDLE, w.UINT] + kernel.QueryInformationJobObject.argtypes = [ + w.HANDLE, + c.c_int, + c.c_void_p, + w.DWORD, + c.c_void_p, + ] + + class Accounting(c.Structure): + _fields_ = [ + ("times", c.c_int64 * 4), + ("faults", w.DWORD), + ("total", w.DWORD), + ("active", w.DWORD), + ("terminated", w.DWORD), + ] + + try: + if not kernel.TerminateJobObject(job, 130): + raise c.WinError(c.get_last_error()) + deadline = time.monotonic() + 2 + while True: + info = Accounting() + if not kernel.QueryInformationJobObject( + job, 1, c.byref(info), c.sizeof(info), None + ): + raise c.WinError(c.get_last_error()) + if info.active == 0: + return + if time.monotonic() >= deadline: + raise OSError( + "Windows command descendants did not stop within cleanup budget" + ) + time.sleep(0.01) + finally: + if not kernel.CloseHandle(job): + raise c.WinError(c.get_last_error()) + + +def execute( + argv, + repo, + stream, + timeout, + stdin=None, + stop_event=None, + on_start=None, + environment=None, + stderr=subprocess.STDOUT, +): + if stop_event is not None and stop_event.is_set(): + raise InterruptedError("Command stopped before execution") + deadline = time.monotonic() + timeout + child_environment = dict( + os.environ if environment is None else environment, PYTHONDONTWRITEBYTECODE="1" + ) + job, kernel, options = None, None, {} + command = argv + if os.name == "nt": + if Path(argv[0]).suffix.lower() in {".cmd", ".bat", ".ps1"}: + raise ValueError( + "Windows commands require a native executable; use an explicit trusted interpreter for scripts" + ) + executable = windows_executable(argv[0], repo, child_environment) + job, kernel = windows_job() + command = [ + sys.executable, + "-I", + "-S", + "-B", + "-c", + WINDOWS_LAUNCHER, + str(job), + json.dumps([executable, *argv[1:]]), + ] + startup = subprocess.STARTUPINFO() + startup.lpAttributeList = {"handle_list": [job]} + options["startupinfo"] = startup + try: + if job is not None: + os.set_handle_inheritable(job, True) + process = subprocess.Popen( + command, + cwd=repo, + stdin=stdin, + stdout=subprocess.PIPE, + stderr=stderr, + shell=False, + start_new_session=os.name == "posix", + **options, + env=child_environment, + ) + except BaseException: + if job is not None: + kernel.CloseHandle(job) + raise + finally: + if job is not None and kernel is not None: + # Popen has copied the handle; project descendants must never inherit it. + try: + os.set_handle_inheritable(job, False) + except OSError: + pass + reader, old_handler = None, None + stopped = threading.Event() + try: + chunks = queue.Queue(maxsize=2) + stopped = threading.Event() + + def collect(): + try: + while not stopped.is_set(): + chunk = process.stdout.read1(65536) + while not stopped.is_set(): + try: + chunks.put(chunk, timeout=0.05) + break + except queue.Full: + continue + if not chunk: + break + finally: + process.stdout.close() + + reader = threading.Thread(target=collect, daemon=True) + reader.start() + if threading.current_thread() is threading.main_thread(): + old_handler = signal.getsignal(signal.SIGTERM) + + def cancelled(signum, frame): + raise InterruptedError("Verification cancelled") + + signal.signal(signal.SIGTERM, cancelled) + if on_start is not None: + on_start(process) + size = 0 + while True: + if stop_event is not None and stop_event.is_set(): + raise InterruptedError("Command stopped") + remaining = deadline - time.monotonic() + if remaining <= 0: + raise subprocess.TimeoutExpired(argv, timeout) + try: + chunk = chunks.get(timeout=min(0.05, remaining)) + except queue.Empty: + continue + if not chunk: + return process.wait(timeout=max(0.01, deadline - time.monotonic())) + size += len(chunk) + if size > 16 * 1024 * 1024: + raise OSError("Verification log exceeds 16 MiB") + stream.write(chunk) + finally: + stopped.set() + tree_stopped = False + try: + if os.name == "posix": + os.killpg(process.pid, signal.SIGKILL) + tree_stopped = True + elif job is not None: + try: + stop_windows_job(job, kernel) + tree_stopped = True + finally: + job = None + elif process.poll() is None: + process.kill() + except ProcessLookupError: + tree_stopped = True + finally: + # A launcher cancelled before joining the job is still our direct child. + if process.poll() is None: + process.kill() + process.wait(timeout=2) + if reader is not None and reader.ident is not None: + reader.join(timeout=2) + if process.stdout is not None and (reader is None or not reader.is_alive()): + process.stdout.close() + if old_handler is not None: + signal.signal(signal.SIGTERM, old_handler) + if reader is not None and reader.is_alive(): + raise OSError("Command output reader did not stop") + process.hypertext_tree_stopped = tree_stopped + + +def run( + repo, + profile_path, + output, + supplemental=None, + trusted_profile=None, + acceptance_path=None, + shipping=None, + target=None, + approved_profile_sha256=None, + signature=None, + allowed_signers=None, +): + repo, output = repo.resolve(), output.absolute() + if output.resolve().is_relative_to(repo): + raise ValueError("Collect fresh evidence outside the target checkout") + accepted = None + if supplemental is not None: + if trusted_profile is None: + raise ValueError("Release requires a trusted profile") + accepted = gate.acceptance( + acceptance_path, + repo, + supplemental, + shipping, + target, + signature, + allowed_signers, + ) + policy = gate.read(gate.ROOT / "policy/key-standards.json") + profile = gate.read(profile_path) + rules = gate.required(profile, policy) + commands = configuration(profile, rules) + if trusted_profile is not None and trusted_profile.resolve().is_relative_to(repo): + raise ValueError( + "Trusted profile must come from outside the candidate checkout" + ) + if trusted_profile is not None and approved_profile_sha256 != gate.digest( + profile_path + ): + trusted = gate.read(trusted_profile) + gate.required(trusted, policy) + if any( + value and not profile["capabilities"][key] + for key, value in trusted["capabilities"].items() + ): + raise ValueError( + "Product capability downgrade requires owner authorization" + ) + current = {entry["id"]: entry for entry in commands} + for previous in configuration(trusted, gate.required(trusted, policy)): + if current.get(previous["id"]) != previous: + raise ValueError( + "Removing or replacing a trusted check requires owner authorization" + ) + from . import repository + + workspace_failures = [] + repository.workspace_checks( + repo, + repo, + lambda identifier, ok, problem: ( + workspace_failures.append(identifier + ": " + problem) if not ok else None + ), + ) + if workspace_failures: + raise ValueError( + "Studio workspace conformance blocks verification: " + + "; ".join(workspace_failures) + ) + subject = gate.context(repo, profile_path) + if accepted is not None and accepted["subject"] != subject: + raise ValueError("Acceptance has a stale subject") + from . import setup_files + + store = setup_files.Output(output) + rows, failures = [], [] + try: + for index, entry in enumerate(commands): + log = output / f"command-{index}.log" + started, code, error = time.monotonic(), None, None + with store.log(log.name) as stream: + try: + code = execute( + entry["argv"], repo, stream, entry["timeout_seconds"] + ) + except (OSError, subprocess.TimeoutExpired) as exception: + error = type(exception).__name__ + report = { + "subject": subject, + "argv": entry["argv"], + "exit_code": code, + "error": error, + "duration_ms": round((time.monotonic() - started) * 1000), + "log": log.name, + "log_sha256": gate.digest(log), + } + path = output / f"command-{index}.json" + store.save(report, path.name) + passed = code == 0 and error is None + rows.append( + { + "id": entry["id"], + "status": "pass" if passed else "fail", + "kind": "automated", + "summary": f"Executed command; exit_code={code}; error={error}", + "artifact": path.name, + "sha256": gate.digest(path), + } + ) + if not passed: + failures.append( + f"{entry['id']}: command failed (exit={code}, error={error}); see {path}" + ) + break + try: + if gate.context(repo, profile_path) != subject: + failures.append("Checkout or baseline changed during verification") + except (ValueError, subprocess.CalledProcessError): + failures.append("Verification modified the checkout or profile") + evidence = {"schema_version": 1, "subject": subject, "checks": rows} + evidence_path = output / "evidence.json" + store.save(evidence, evidence_path.name) + for index in range(len(rows)): + try: + gate.artifact(rows[index], output) + except ValueError: + failures.append("Command report was modified after collection") + report = gate.read(output / f"command-{index}.json") + if report["log_sha256"] != gate.digest(output / report["log"]): + failures.append("Command evidence was modified after collection") + store.verify() + except (OSError, ValueError) as error: + try: + store.quarantine("evidence.json") + except (OSError, ValueError): + pass + return ["Verification output integrity failed: " + str(error)] + finally: + store.close() + if failures: + return failures + if supplemental is not None: + if ( + gate.acceptance( + acceptance_path, + repo, + supplemental, + shipping, + target, + signature, + allowed_signers, + ) + != accepted + ): + raise ValueError("Acceptance changed during verification") + additional = gate.read(supplemental) + if ( + additional.get("schema_version") != 1 + or additional.get("subject") != subject + ): + raise ValueError("Supplemental evidence has a different or stale subject") + supplied = additional.get("checks") + if not isinstance(supplied, list): + raise ValueError("Supplemental checks must be a list") + repacked_approvals = {} + actual_ids, seen = {entry["id"] for entry in commands}, set() + for index, record in enumerate(supplied): + if ( + not isinstance(record, dict) + or not isinstance(record.get("id"), str) + or record["id"] in seen + ): + raise ValueError("Invalid or duplicate supplemental ID") + seen.add(record["id"]) + if record["id"] in actual_ids: + raise ValueError( + "Supplemental records cannot replace freshly executed checks" + ) + original = gate.artifact(record, supplemental.parent) + copied = dict(record, artifact="supplemental/" + record["artifact"]) + if record.get("status") == "exception" and accepted[ + "approved_exceptions" + ].get(record["id"]) == gate.record_digest(record): + repacked_approvals[record["id"]] = gate.record_digest(copied) + evidence["checks"].append(copied) + for name, sha in accepted["files"].items(): + original = gate.artifact( + {"artifact": name, "sha256": sha}, supplemental.parent + ) + destination = output / "supplemental" / name + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(original, destination) + if gate.digest(destination) != sha: + raise ValueError("Supplemental dependency changed during collection") + evidence_path.write_text( + json.dumps(evidence, indent=2) + "\n", encoding="utf-8" + ) + return gate.check(repo, profile_path, evidence_path, policy, repacked_approvals) + return [] + + +def main(argv=None, command=None): + from .cli import Parser + + parser = Parser( + prog="hypertext " + command if command else None, description=__doc__ + ) + if command is None: + parser.add_argument("command", choices=("verify", "release")) + else: + parser.set_defaults(command=command) + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--evidence", type=Path) + parser.add_argument( + "--trusted-profile", + type=Path, + help="Profile from the protected baseline; expansions allowed, weakening blocked", + ) + parser.add_argument( + "--approved-profile-sha256", + help="Owner-controlled external authorization for one exact profile change", + ) + parser.add_argument( + "--acceptance-signature", + type=Path, + help="SSH signature required for exceptions", + ) + parser.add_argument( + "--allowed-signers", type=Path, help="External owner public-key allowlist" + ) + parser.add_argument( + "--acceptance", + type=Path, + help="External protected-job or owner acceptance manifest", + ) + parser.add_argument("--artifact", type=Path, help="Exact shipping artifact") + parser.add_argument( + "--target", help="Exact environment and provider-configuration identity" + ) + parser.add_argument( + "--json", action="store_true", help="Structured gate diagnostics" + ) + args = parser.parse_args(argv) + try: + if args.command == "release" and args.evidence is None: + raise ValueError( + "release requires --evidence; device/provider/design checks cannot be skipped" + ) + if args.command == "verify" and any( + value is not None + for value in ( + args.evidence, + args.acceptance, + args.artifact, + args.target, + args.acceptance_signature, + args.allowed_signers, + ) + ): + raise ValueError( + "Use release for supplemental evidence and release acceptance inputs" + ) + failures = run( + args.repo, + args.repo / ".hypertext/product.json", + args.output, + args.evidence.resolve() if args.evidence else None, + args.trusted_profile.resolve() if args.trusted_profile else None, + args.acceptance.resolve() if args.acceptance else None, + args.artifact.resolve() if args.artifact else None, + args.target, + args.approved_profile_sha256, + args.acceptance_signature, + args.allowed_signers, + ) + if failures: + raise SystemExit( + gate.report( + failures, + gate.read(gate.ROOT / "policy/key-standards.json"), + args.output, + args.json, + scope=args.command, + ) + ) + except (OSError, ValueError, subprocess.CalledProcessError) as error: + raise SystemExit( + gate.report( + [str(error)], + evidence=args.output, + json_output=args.json, + scope=args.command, + ) + ) + if args.json: + gate.report([], evidence=args.output, json_output=True, scope=args.command) + else: + print( + "Executed checks passed." + if args.command == "verify" + else "Executed checks and release evidence validation passed; non-automated outcomes still require inspection." + ) diff --git a/.hypertext/formatting/core/setup_files.py b/.hypertext/formatting/core/setup_files.py new file mode 100644 index 0000000..53e535c --- /dev/null +++ b/.hypertext/formatting/core/setup_files.py @@ -0,0 +1,946 @@ +"""Bounded local inspection and tamper-evident setup output. Not an OS sandbox.""" + +import hashlib +import io +import json +import os +import ntpath +from pathlib import Path +import stat +import subprocess +import time +import uuid +from . import runner + +GENERATED = { + ".git", + "node_modules", + ".venv", + "venv", + "__pycache__", + "target", + "build", + "dist", + ".next", + ".gradle", + ".cache", + ".turbo", + ".build", +} +MAX_FILE = 64 * 1024 * 1024 +MAX_TOTAL = 256 * 1024 * 1024 + + +def relative_path(name): + if not isinstance(name, str) or not name or "\0" in name: + raise ValueError("Expected a nonempty relative file path") + if os.name == "nt": + parts = name.replace("\\", "/").split("/") + if ntpath.splitdrive(name)[0] or any( + ":" in p + or p.endswith((" ", ".")) + or p.split(".")[0].upper() + in { + "CON", + "PRN", + "AUX", + "NUL", + *(f"COM{i}" for i in range(10)), + *(f"LPT{i}" for i in range(10)), + } + for p in parts + ): + raise ValueError("Ambiguous Windows file path") + path = Path(name) + if path.is_absolute() or ".." in path.parts or path == Path("."): + raise ValueError("File path must stay inside the selected repo") + return path + + +BUNDLE_FILES = ( + "core/__init__.py", + "core/gate.py", + "core/runner.py", + "core/bootstrap.py", + "core/setup_files.py", + "core/setup.py", + "core/repository.py", + "docs/repository-standards.md", + "docs/repository-profiles.md", + "core/doctor.py", + "core/install.py", + "core/cli.py", + "core/git_policy.py", + "core/formatting.py", + "core/git_setup.py", + "core/formatter_distribution.py", + "adapters/formatting/commit.py", + "adapters/formatting/install.py", + "adapters/formatting/tools/setup.py", + "adapters/formatting/tools/run.py", + "adapters/formatting/tools/prettier.mjs", + "adapters/formatting/tools/text.py", + "adapters/formatters/package.json", + "adapters/formatters/package-lock.json", + "adapters/formatters/run.py", + "docs/git-standards.md", + "docs/product-standards.md", + "docs/repo-gates.md", + "policy/key-standards.json", + "scripts/hypertext.py", + "adapters/repository/hypertext.py", + "adapters/repository/AGENTS.md", + "adapters/repository/github-actions.yml", + "adapters/generic/AGENTS.md", + "adapters/claude/CLAUDE.md", + "adapters/cursor/hypertext.mdc", + "adapters/copilot/hypertext.instructions.md", + "action.yml", + "LICENSE", + "NOTICE.md", + "policy/android-sources/manifest.json", +) + + +def bundle_files(root): + from . import gate + + manifest = gate.read(Path(root) / "policy/android-sources/manifest.json") + names = [row["file"] for row in manifest["sources"]] + if len(names) != len(set(names)): + raise ValueError("Duplicate Android source filename") + for name in names: + path = relative_path(name) + if len(path.parts) != 1 or path.suffix != ".json" or name == "manifest.json": + raise ValueError("Invalid Android source filename") + return (*BUNDLE_FILES, *("policy/android-sources/" + name for name in names)) + + +def confined(path, root): + path, root = Path(path).absolute(), Path(root).absolute() + if not path.is_relative_to(root): + raise ValueError("Path escapes the selected directory") + for part in (path, *path.parents): + if part == root: + break + if part.is_symlink() or ( + os.name == "nt" + and part.exists() + and part.lstat().st_file_attributes & 0x400 + ): + raise ValueError(f"Symlinked path: {path.relative_to(root)}") + return path + + +def regular(path, root, limit=MAX_FILE): + path = confined(path, root) + info = path.stat(follow_symlinks=False) + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + raise ValueError(f"Not a bounded regular file: {path.relative_to(root)}") + return info + + +def windows_security(path): + """Fingerprint owner, group and DACL without exporting identities or permissions.""" + import ctypes as c + from ctypes import wintypes as w + + api = c.WinDLL("advapi32", use_last_error=True) + api.GetFileSecurityW.argtypes = [ + w.LPCWSTR, + w.DWORD, + c.c_void_p, + w.DWORD, + c.POINTER(w.DWORD), + ] + needed = w.DWORD() + api.GetFileSecurityW(str(path), 7, None, 0, c.byref(needed)) + if not 0 < needed.value <= 1024 * 1024: + raise ValueError("Cannot inspect bounded Windows security descriptor") + buffer = c.create_string_buffer(needed.value) + if not api.GetFileSecurityW(str(path), 7, buffer, needed, c.byref(needed)): + raise c.WinError(c.get_last_error()) + return hashlib.sha256(buffer.raw[: needed.value]).hexdigest() + + +def windows_streams(path, limit=MAX_FILE): + """Bound named $DATA streams; the unnamed stream is hashed separately.""" + import ctypes as c + from ctypes import wintypes as w + + api = c.WinDLL("kernel32", use_last_error=True) + + class Stream(c.Structure): + _fields_ = [("size", c.c_int64), ("name", w.WCHAR * 296)] + + api.FindFirstStreamW.argtypes = [w.LPCWSTR, c.c_int, c.c_void_p, w.DWORD] + api.FindFirstStreamW.restype = w.HANDLE + api.FindNextStreamW.argtypes = [w.HANDLE, c.c_void_p] + api.FindClose.argtypes = [w.HANDLE] + entry = Stream() + handle = api.FindFirstStreamW(str(path), 0, c.byref(entry), 0) + if handle == c.c_void_p(-1).value: + error = c.get_last_error() + if error == 38: + return () + raise c.WinError(error) + rows = [] + total = 0 + try: + while True: + if entry.name != "::$DATA": + if len(rows) >= 64 or entry.size < 0 or total + entry.size > limit: + raise ValueError("Windows named streams exceed inspection limit") + content = hashlib.sha256() + count = 0 + with open(str(path) + entry.name, "rb") as source: + for chunk in iter(lambda: source.read(65536), b""): + count += len(chunk) + if total + count > limit: + raise ValueError( + "Windows stream grew beyond inspection limit" + ) + content.update(chunk) + total += count + rows.append((entry.name, count, content.hexdigest())) + if not api.FindNextStreamW(handle, c.byref(entry)): + if c.get_last_error() != 38: + raise c.WinError(c.get_last_error()) + break + finally: + api.FindClose(handle) + return tuple(sorted(rows)) + + +def windows_metadata(path, info=None): + info = path.lstat() if info is None else info + if ( + info.st_file_attributes & 0x400 + or stat.S_ISREG(info.st_mode) + and info.st_nlink != 1 + ): + raise ValueError("Reparse points and hardlinked protected files are unsafe") + return ( + info.st_dev, + info.st_ino, + info.st_file_attributes, + windows_security(path), + windows_streams( + path, MAX_FILE - info.st_size if stat.S_ISREG(info.st_mode) else MAX_FILE + ), + ) + + +def trusted_tool(repo, name): + """Read-only inspection must not run checkout-owned or CWD-discovered tools.""" + import shutil + + directories = [] + for entry in os.environ.get("PATH", "").split(os.pathsep): + path = Path(entry) + if not entry or not path.is_absolute(): + continue + path = path.resolve() + if path.is_relative_to(repo.resolve()): + continue + directories.append(str(path)) + if os.name == "nt": + for directory in directories: + candidate = Path(directory) / (name + ".exe") + if candidate.is_file() and not candidate.resolve().is_relative_to( + repo.resolve() + ): + return str(candidate.resolve()) + raise FileNotFoundError( + "Trusted executable unavailable outside the selected checkout" + ) + candidate = shutil.which(name, path=os.pathsep.join(directories)) + if not candidate or Path(candidate).resolve().is_relative_to(repo.resolve()): + raise FileNotFoundError( + "Trusted executable unavailable outside the selected checkout" + ) + return str(Path(candidate).resolve()) + + +def trusted_git(repo): + return trusted_tool(repo, "git") + + +def fingerprint(path, root): + info = regular(path, root) + digest = hashlib.sha256() + with path.open("rb") as source: + size = 0 + for chunk in iter(lambda: source.read(65536), b""): + size += len(chunk) + if size > MAX_FILE: + raise ValueError("File grew beyond inspection limit") + digest.update(chunk) + return ( + (stat.S_IMODE(info.st_mode), digest.hexdigest(), windows_metadata(path, info)) + if os.name == "nt" + else (stat.S_IMODE(info.st_mode), digest.hexdigest()) + ) + + +def git_read(repo, *args): + """Bound Git reads and disable checkout-configured executable filters, including submodules.""" + deadline = time.monotonic() + 5 + try: + executable = trusted_git(repo) + environment = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + base = [ + executable, + "--no-optional-locks", + "-c", + "core.fsmonitor=false", + "-c", + "core.untrackedCache=false", + ] + + def invoke(directory, options): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError("Git inspection budget exhausted") + stream = io.BytesIO() + code = runner.execute( + [*base, "-C", str(directory), *options], + directory, + stream, + remaining, + environment=environment, + ) + return code, stream.getvalue() + + overrides = [] + if "status" in args: + pending = [Path(repo)] + seen = set() + filters = set() + while pending: + directory = pending.pop() + if directory in seen: + continue + seen.add(directory) + if len(seen) > 64: + raise ValueError("Git submodule inspection exceeds 64 checkouts") + code, keys = invoke( + directory, + [ + "config", + "--null", + "--name-only", + "--get-regexp", + r"^filter\..*\.(clean|process|smudge|required)$", + ], + ) + if code not in (0, 1): + return 1, b"" + filters.update( + key.rsplit(b".", 1)[0].decode("utf-8") + for key in keys.split(b"\0") + if key + ) + if len(filters) > 256 or any(len(key) > 256 for key in filters): + raise ValueError("Git filter inspection exceeds limit") + code, index = invoke(directory, ["ls-files", "--stage", "-z"]) + if code: + return 1, b"" + for row in index.split(b"\0"): + if row.startswith(b"160000 ") and b"\t" in row: + child = confined( + directory + / relative_path(os.fsdecode(row.split(b"\t", 1)[1])), + Path(repo), + ) + if child.is_dir(): + pending.append(child) + for key in sorted(filters): + for suffix, value in ( + ("clean", ""), + ("process", ""), + ("smudge", ""), + ("required", "false"), + ): + overrides.extend(["-c", key + "." + suffix + "=" + value]) + return invoke(repo, [*overrides, *args]) + except (OSError, ValueError, TimeoutError, subprocess.TimeoutExpired): + return 1, b"" + + +def git_state(repo): + code, output = git_read(repo, "rev-parse", "--show-toplevel") + if code: + present = (repo / ".git").exists() or (repo / ".git").is_symlink() + return { + "state": "unknown" if present else "not_a_git_repo", + "tracked": [], + "head": None, + "index": None, + } + code, output = git_read(repo, "ls-files", "--stage", "-z") + if code: + raise ValueError("Cannot inspect the Git index") + tracked = [ + os.fsdecode(entry.split(b"\t", 1)[1]) + for entry in output.split(b"\0") + if b"\t" in entry + ] + _, head = git_read(repo, "rev-parse", "--verify", "HEAD") + code, dirty = git_read( + repo, "status", "--porcelain", "--untracked-files=normal", "--", "." + ) + _, common = git_read(repo, "rev-parse", "--git-common-dir") + config_path = repo / Path(os.fsdecode(common).strip()) / "config" + if config_path.is_file() and config_path.stat().st_size > 1024 * 1024: + raise ValueError("Git configuration exceeds inspection limit") + config = ( + hashlib.sha256(config_path.read_bytes()).hexdigest() + if config_path.is_file() + else None + ) + index_code, index_name = git_read(repo, "rev-parse", "--git-path", "index") + if index_code: + raise ValueError("Cannot locate the protected Git index") + index_path = repo / Path(os.fsdecode(index_name).strip()) + index_identity = None + if index_path.exists(): + info = regular(index_path, index_path.parent) + index_identity = ( + info.st_dev, + info.st_ino, + fingerprint(index_path, index_path.parent), + ) + output += json.dumps(index_identity, sort_keys=True).encode() + if os.name == "nt" and (repo / ".git").exists(): + config = hashlib.sha256( + json.dumps( + (config, windows_metadata(repo / ".git")), sort_keys=True + ).encode() + ).hexdigest() + return { + "state": "unknown" if code else "dirty" if dirty else "clean", + "tracked": tracked, + "config": config, + "head": hashlib.sha256(head).hexdigest(), + "index": hashlib.sha256(output).hexdigest(), + } + + +def inventory(repo): + """Protect existing source, including Git-tracked files in generated directories.""" + git = git_state(repo) + if git["state"] == "unknown": + raise ValueError( + "Cannot prove Git ownership while repository inspection is unavailable" + ) + tracked = set(git["tracked"]) + tracked_names = ( + {windows_name(name) for name in tracked} if os.name == "nt" else tracked + ) + result, size, visited = {}, 0, 0 + if os.name == "nt": + result["\0root"] = windows_metadata(repo) + size = sum(row[1] for row in result["\0root"][-1]) + for directory, folders, files in os.walk( + repo, followlinks=False, onerror=lambda error: (_ for _ in ()).throw(error) + ): + parent = Path(directory) + visited += 1 + if visited > 10000: + raise ValueError("Source inspection exceeds 10000 entries") + if parent != repo and ".git" in [*folders, *files]: + nested = git_state(parent) + result["\0git:" + parent.relative_to(repo).as_posix()] = ( + nested["head"], + nested["index"], + nested.get("config"), + ) + folders[:] = sorted( + name + for name in folders + if name != ".git" + and ( + name not in GENERATED + or any( + p.startswith( + ( + windows_name((parent / name).relative_to(repo).as_posix()) + if os.name == "nt" + else (parent / name).relative_to(repo).as_posix() + ) + + "/" + ) + for p in tracked_names + ) + ) + ) + for name in [*folders, *files]: + path = parent / name + relative = path.relative_to(repo).as_posix() + if ( + any(part in GENERATED for part in path.relative_to(repo).parts) + and (windows_name(relative) if os.name == "nt" else relative) + not in tracked_names + ): + continue + info = path.lstat() + if os.name == "nt" and info.st_file_attributes & 0x400: + raise ValueError("Reparse point in source inventory: " + relative) + if stat.S_ISDIR(info.st_mode): + if os.name == "nt" or adoption_path(relative): + result[relative] = ( + ("directory", windows_metadata(path, info)) + if os.name == "nt" + else ("directory", stat.S_IMODE(info.st_mode)) + ) + if os.name == "nt": + size += sum(row[1] for row in result[relative][1][-1]) + if size > MAX_TOTAL: + raise ValueError( + "Source streams exceed total inspection limit" + ) + continue + visited += 1 + if visited > 10000: + raise ValueError( + "Source inspection exceeds 10000 files; select a narrower repo or isolate generated files" + ) + if stat.S_ISLNK(info.st_mode): + result[relative] = ("symlink", os.readlink(path)) + elif stat.S_ISREG(info.st_mode): + size += info.st_size + if size > MAX_TOTAL: + raise ValueError("Source inspection exceeds 256 MiB") + result[relative] = fingerprint(path, repo) + if os.name == "nt": + size += sum(row[1] for row in result[relative][2][-1]) + if size > MAX_TOTAL: + raise ValueError("Source streams exceed total inspection limit") + else: + result[relative] = ("special", stat.S_IFMT(info.st_mode)) + for name in tracked: + if not (repo / name).exists() and not (repo / name).is_symlink(): + result[name] = ("missing",) + result["\0git"] = (git["head"], git["index"], git.get("config")) + if os.name == "nt": + normalized = {} + for name, value in result.items(): + key = windows_name(name) + if key in normalized: + raise ValueError("Ambiguous case-sensitive Windows source paths") + normalized[key] = value + return normalized + return result + + +def adoption_path(name): + name = name.replace("\\", "/").casefold() + return ( + name == ".hypertext" + or name.startswith(".hypertext/") + or name in {"scripts/hypertext.py", ".github/workflows/hypertext-standards.yml"} + ) + + +def windows_name(name): + # Unicode casefold merges distinct NTFS names (for example ß and ss). + # Normalize ordinary Windows aliases; unusual case aliases may fail closed. + return name.replace("\\", "/").translate( + str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") + ) + + +def changes(before, after, writes): + if os.name == "nt": + before = {windows_name(k): v for k, v in before.items()} + after = {windows_name(k): v for k, v in after.items()} + writes = {windows_name(n) for n in writes} + changed = {name for name in before if after.get(name) != before[name]} + changed |= {name for name in set(after) - set(before) if adoption_path(name)} + return sorted( + name.replace("\0git", "[Git metadata]").replace("\0root", "[Repo directory]") + for name in changed + if name not in writes or adoption_path(name) + ) + + +class WindowsOutput: + """Pin local directory ancestry without delete sharing; owner-only NTFS ACLs.""" + + def __init__(self, path): + import ctypes as c + from ctypes import wintypes as w + + self.c, self.handles, self.acls, self.identities = c, [], {}, {} + self.k = c.WinDLL("kernel32", use_last_error=True) + self.a = c.WinDLL("advapi32", use_last_error=True) + self.k.CreateFileW.argtypes = [ + w.LPCWSTR, + w.DWORD, + w.DWORD, + c.c_void_p, + w.DWORD, + w.DWORD, + w.HANDLE, + ] + self.k.CreateFileW.restype = w.HANDLE + self.k.CloseHandle.argtypes = [w.HANDLE] + self.k.GetCurrentProcess.restype = w.HANDLE + self.k.LocalFree.argtypes = [c.c_void_p] + self.k.CreateDirectoryW.argtypes = [w.LPCWSTR, c.c_void_p] + self.a.OpenProcessToken.argtypes = [w.HANDLE, w.DWORD, c.POINTER(w.HANDLE)] + self.a.GetTokenInformation.argtypes = [ + w.HANDLE, + c.c_int, + c.c_void_p, + w.DWORD, + c.POINTER(w.DWORD), + ] + self.a.ConvertSidToStringSidW.argtypes = [c.c_void_p, c.POINTER(w.LPWSTR)] + self.a.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [ + w.LPCWSTR, + w.DWORD, + c.POINTER(c.c_void_p), + c.c_void_p, + ] + self.a.GetFileSecurityW.argtypes = [ + w.LPCWSTR, + w.DWORD, + c.c_void_p, + w.DWORD, + c.POINTER(w.DWORD), + ] + + class Security(c.Structure): + _fields_ = [ + ("length", w.DWORD), + ("descriptor", c.c_void_p), + ("inherit", w.BOOL), + ] + + self.descriptor = c.c_void_p() + token = w.HANDLE() + needed = w.DWORD() + sid = w.LPWSTR() + self.check( + self.a.OpenProcessToken(self.k.GetCurrentProcess(), 8, c.byref(token)) + ) + try: + self.a.GetTokenInformation(token, 1, None, 0, c.byref(needed)) + buffer = c.create_string_buffer(needed.value) + self.check( + self.a.GetTokenInformation(token, 1, buffer, needed, c.byref(needed)) + ) + self.check( + self.a.ConvertSidToStringSidW( + c.cast(buffer, c.POINTER(c.c_void_p))[0], c.byref(sid) + ) + ) + try: + sddl = "D:P(A;OICI;FA;;;" + sid.value + ")(A;OICI;FA;;;SY)" + self.check( + self.a.ConvertStringSecurityDescriptorToSecurityDescriptorW( + sddl, 1, c.byref(self.descriptor), None + ) + ) + finally: + self.k.LocalFree(sid) + finally: + self.k.CloseHandle(token) + self.security = Security(c.sizeof(Security), self.descriptor, False) + try: + path = path.absolute() + if path.drive.startswith("\\\\") or not path.drive: + raise ValueError( + "Windows output requires a local drive with ACL support" + ) + # Pin root first, then every ancestor before creating the next component. + for directory in [*reversed(path.parents), path]: + if directory == path or not directory.exists(): + self.check( + self.k.CreateDirectoryW(str(directory), c.byref(self.security)) + ) + # Attribute-only handles do not enforce Windows sharing restrictions. + # Ancestors retain a pinned child, so cannot become empty junctions. + # Permit ordinary temp-file writes there; lock writes on the output itself. + share = 1 if directory == path else 3 + handle = self.k.CreateFileW( + str(directory), 0x80000000, share, None, 3, 0x02200000, None + ) + if handle == c.c_void_p(-1).value: + raise c.WinError(c.get_last_error()) + self.handles.append(handle) + if directory.lstat().st_file_attributes & 0x400: + raise ValueError("Reparse points are unsafe output ancestors") + self.path = path + self.directory_acl = self.acl(path) + # Filesystems without persistent ACLs cannot provide private evidence. + flags = w.DWORD() + self.k.GetVolumeInformationW.argtypes = [ + w.LPCWSTR, + w.LPWSTR, + w.DWORD, + c.c_void_p, + c.c_void_p, + c.POINTER(w.DWORD), + w.LPWSTR, + w.DWORD, + ] + self.check( + self.k.GetVolumeInformationW( + path.anchor, None, 0, None, None, c.byref(flags), None, 0 + ) + ) + if not flags.value & 8: + raise ValueError("Windows output volume must support persistent ACLs") + except BaseException: + self.close() + raise + + def check(self, result): + if not result: + raise self.c.WinError(self.c.get_last_error()) + + def acl(self, path): + return windows_security(path) + + def verify(self): + if self.acl(self.path) != self.directory_acl: + raise ValueError("Setup output directory permissions were modified") + if windows_streams(self.path): + raise ValueError("Unexpected output directory streams") + for name, acl in self.acls.items(): + info = (self.path / name).lstat() + if ( + (info.st_dev, info.st_ino, info.st_file_attributes) + != self.identities[name] + or info.st_nlink != 1 + or windows_streams(self.path / name) + ): + raise ValueError("Setup output identity or streams were modified") + if self.acl(self.path / name) != acl: + raise ValueError("Setup output file permissions were modified") + + def open(self, name): + import msvcrt + + c = self.c + handle = self.k.CreateFileW( + str(self.path / name), + 0xC0000000, + 1, + c.byref(self.security), + 1, + 0x00200080, + None, + ) + if handle == c.c_void_p(-1).value: + raise c.WinError(c.get_last_error()) + try: + descriptor = msvcrt.open_osfhandle(handle, os.O_RDWR | os.O_BINARY) + except BaseException: + self.k.CloseHandle(handle) + raise + try: + self.acls[name] = self.acl(self.path / name) + info = (self.path / name).lstat() + self.identities[name] = (info.st_dev, info.st_ino, info.st_file_attributes) + return os.fdopen(descriptor, "w+b") + except BaseException: + os.close(descriptor) + raise + + def replace(self, name, target, replace=True): + # MoveFileEx opens the parent for writing, conflicting with our pin. + # Native same-directory rename uses the source handle without reopening its parent. + from ctypes import wintypes as w + + c = self.c + + class Rename(c.Structure): + _fields_ = [ + ("replace", w.DWORD), + ("root", w.HANDLE), + ("length", w.DWORD), + ("name", w.WCHAR * (len(target) + 1)), + ] + + info = Rename(int(replace), None, len(target.encode("utf-16-le")), target) + native = c.WinDLL("ntdll") + + class Status(c.Structure): + _fields_ = [("status", c.c_void_p), ("information", c.c_size_t)] + + native.NtSetInformationFile.argtypes = [ + w.HANDLE, + c.c_void_p, + c.c_void_p, + w.DWORD, + c.c_int, + ] + native.NtSetInformationFile.restype = c.c_long + native.RtlNtStatusToDosError.argtypes = [c.c_long] + native.RtlNtStatusToDosError.restype = w.DWORD + handle = self.k.CreateFileW( + str(self.path / name), 0x80010000, 1, None, 3, 0x00200000, None + ) + if handle == c.c_void_p(-1).value: + raise c.WinError(c.get_last_error()) + try: + status = Status() + result = native.NtSetInformationFile( + handle, c.byref(status), c.byref(info), c.sizeof(info), 10 + ) + if result < 0: + raise c.WinError(native.RtlNtStatusToDosError(result)) + finally: + self.k.CloseHandle(handle) + self.acls[target] = self.acls.pop(name) + self.identities[target] = self.identities.pop(name) + + def close(self): + for handle in reversed(self.handles): + self.k.CloseHandle(handle) + self.handles.clear() + if self.descriptor: + self.k.LocalFree(self.descriptor) + self.descriptor = None + + +class Output: + """Exclusive logs and anchored atomic reports; commands cannot redirect our writes.""" + + def __init__(self, path): + self.windows = None + if os.name not in {"posix", "nt"}: + raise ValueError("Host has no safe output backend") + self.path = path + if os.name == "nt": + self.windows = WindowsOutput(path) + else: + path.mkdir(parents=True, exist_ok=False) + self.identity = (path.stat().st_dev, path.stat().st_ino) + self.fd = ( + os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) + if os.name == "posix" + else None + ) + self.ledger = {} + + def close(self): + if self.windows is not None: + self.windows.close() + if self.fd is not None: + os.close(self.fd) + self.fd = None + + def identity_check(self): + if ( + self.path.is_symlink() + or not self.path.is_dir() + or (self.path.stat().st_dev, self.path.stat().st_ino) != self.identity + ): + raise ValueError( + "Setup output directory was replaced; no further writes are safe" + ) + + def verify(self): + self.identity_check() + if self.windows is not None: + self.windows.verify() + actual = {p.name for p in self.path.iterdir()} + if actual != set(self.ledger): + raise ValueError("Unexpected or missing files in setup output") + for name, digest in self.ledger.items(): + mode, actual_digest = fingerprint(self.path / name, self.path)[:2] + if actual_digest != digest or os.name == "posix" and mode != 0o600: + raise ValueError(f"Setup output was modified: {name}") + + def open(self, name): + relative_path(name) + if Path(name).name != name or name in {".", ".."}: + raise ValueError("Output name must be a single file name") + if self.windows is not None: + return self.windows.open(name) + flags = os.O_RDWR | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open( + name if self.fd is not None else self.path / name, + flags, + 0o600, + **({"dir_fd": self.fd} if self.fd is not None else {}), + ) + return os.fdopen(descriptor, "w+b") + + def log(self, name): + self.verify() + return Log(self, name) + + def quarantine(self, name="results.json"): + """Preserve suspect published bytes under an invalid name without overwriting them.""" + self.identity_check() + if name not in self.ledger or not (self.path / name).exists(): + return + regular(self.path / name, self.path) + target = "invalid-" + uuid.uuid4().hex + ".json" + if self.windows is not None: + self.windows.replace(name, target, replace=False) + else: + os.link( + name, + target, + src_dir_fd=self.fd, + dst_dir_fd=self.fd, + follow_symlinks=False, + ) + os.unlink(name, dir_fd=self.fd) + if name in self.ledger: + self.ledger[target] = self.ledger.pop(name) + + def save(self, data, target="results.json"): + relative_path(target) + if Path(target).name != target: + raise ValueError("Report name must be a single file name") + self.verify() + name = ".report-" + uuid.uuid4().hex + encoded = (json.dumps(data, indent=2) + "\n").encode("utf-8") + with self.open(name) as stream: + stream.write(encoded) + # Use the original directory descriptor even if its pathname was swapped. + kwargs = ( + {"src_dir_fd": self.fd, "dst_dir_fd": self.fd} + if self.fd is not None + else {} + ) + if self.windows is not None: + self.windows.replace(name, target) + else: + os.replace(name, target, **kwargs) + self.ledger[target] = hashlib.sha256(encoded).hexdigest() + self.verify() + + +class Log: + def __init__(self, output, name): + self.output, self.name = output, name + self.stream = output.open(name) + info = os.fstat(self.stream.fileno()) + self.identity = (info.st_dev, info.st_ino) + self.digest = hashlib.sha256() + + def write(self, content): + self.stream.write(content) + self.digest.update(content) + + def __enter__(self): + return self + + def __exit__(self, *error): + self.stream.close() + self.output.identity_check() + path = self.output.path / self.name + info = regular(path, self.output.path, 16 * 1024 * 1024) + if (info.st_dev, info.st_ino) != self.identity: + raise ValueError("Setup command log was replaced") + self.output.ledger[self.name] = self.digest.hexdigest() + self.output.verify() diff --git a/.hypertext/formatting/install.py b/.hypertext/formatting/install.py new file mode 100644 index 0000000..fd8538e --- /dev/null +++ b/.hypertext/formatting/install.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python3 +"""Install pinned tools and compose repository hooks without replacing checks.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import shlex +import shutil +import subprocess +import sys + +repo = Path(__file__).resolve().parents[2] +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("--skip-tools", action="store_true") +args = parser.parse_args() + + +def git(*argv, optional=False): + result = subprocess.run( + ["git", "-C", str(repo), *argv], + capture_output=True, + text=True, + check=not optional, + ) + return result.stdout.strip() + + +def absolute(value): + path = Path(value) + return path if path.is_absolute() else repo / path + + +def prepared_path_header(): + """Retain only validated executable directories for noninteractive Git hooks.""" + executables = [sys.executable] + for name in ( + "node", + "python3", + "java", + "rustup", + "dotnet", + "ruby", + "pnpm", + "cargo", + "swift", + ): + found = shutil.which(name) + if found: + executables.append(found) + directories = [] + for executable in executables: + path = Path(executable).absolute() + if not path.is_file() or not os.access(path, os.X_OK): + raise ValueError("Prepared tool executable is unavailable: " + path.name) + # Keep the discovered directory: a symlink target can have a different + # basename (pnpm -> pnpm.cjs), so its resolved parent may not expose pnpm. + directory = str(path.parent) + if directory not in directories: + directories.append(directory) + prefix = os.pathsep.join(directories) + value = shlex.quote(prefix) + if os.name == "nt": + # Git for Windows runs these hooks in its POSIX shell. + value = "$(cygpath -p -u " + value + ")" + return "#!/bin/sh\nPATH=" + value + ':"${PATH:-/usr/bin:/bin}"\nexport PATH\n' + + +try: + gitdir = absolute(git("rev-parse", "--git-dir")).resolve() + common = absolute(git("rev-parse", "--git-common-dir")).resolve() + target = gitdir / "hypertext-formatting-hooks" + current = git("config", "--get", "core.hooksPath", optional=True) + effective = ( + absolute(current) + if current + else absolute(git("rev-parse", "--git-path", "hooks")) + ) + metadata = gitdir / "hypertext-formatting-hooks.json" + if metadata.is_symlink() or target.is_symlink(): + raise ValueError("Managed hook metadata and directory must not be symlinked") + receipt = json.loads(metadata.read_text()) if metadata.is_file() else {} + if not isinstance(receipt, dict): + raise ValueError("Invalid composed-hook ownership receipt") + if receipt.get("schema_version") == 1: + if set(receipt) != {"schema_version", "sources", "wrappers"}: + raise ValueError("Invalid composed-hook ownership receipt") + previous = receipt["sources"] + previous_wrappers = receipt["wrappers"] + else: + # Existing installations recorded only their native source paths. + previous, previous_wrappers = receipt, {} + for values in (previous, previous_wrappers): + if not isinstance(values, dict) or any( + not isinstance(name, str) + or name in {"", ".", ".."} + or Path(name).name != name + or not isinstance(value, str) + for name, value in values.items() + ): + raise ValueError("Invalid composed-hook ownership receipt") + if any( + len(value) != 64 or any(c not in "0123456789abcdef" for c in value) + for value in previous_wrappers.values() + ): + raise ValueError("Invalid composed-hook digest") + sources = {} + for directory in (repo / ".githooks", effective): + if directory.resolve() == target.resolve(): + sources.update( + { + name: absolute(path) + for name, path in previous.items() + if absolute(path).is_file() + } + ) + continue + if not directory.is_dir(): + continue + for path in directory.iterdir(): + if path.name.endswith(".sample") or not path.is_file(): + continue + candidate = path.resolve() + # Absolute primary-checkout hooks must resolve inside this worktree. + if gitdir != common: + try: + relative = candidate.relative_to(common.parent) + if (repo / relative).is_file(): + candidate = repo / relative + except ValueError: + pass + sources[path.name] = candidate + precommit = sources.get("pre-commit") + owns_formatting = bool( + precommit and ".hypertext/formatting/commit.py" in precommit.read_text() + ) + if precommit and not owns_formatting: + body = precommit.read_text() + if any( + token in body + for token in ("lint-staged", "ktlintFormat", "git add ", "--fix") + ): + raise ValueError( + "Reconcile the mutating legacy pre-commit hook before installation: " + + str(precommit) + ) + header = prepared_path_header() + desired = {} + for name, source in sources.items(): + if name != "pre-commit": + desired[name] = header + "exec " + shlex.quote(str(source)) + ' "$@"\n' + body = header + if not owns_formatting: + body += ( + shlex.quote(sys.executable) + + " " + + shlex.quote(str(repo / ".hypertext/formatting/commit.py")) + + " || exit $?\n" + ) + if precommit: + body += "exec " + shlex.quote(str(precommit)) + ' "$@"\n' + desired["pre-commit"] = body + + def recognized_legacy(name, content): + if content.startswith(header): + content = "#!/bin/sh\n" + content[len(header) :] + original = previous.get(name) + forwarding = ( + "#!/bin/sh\nexec " + shlex.quote(original) + ' "$@"\n' if original else None + ) + if content == forwarding: + return True + if name != "pre-commit": + return False + lines = content.splitlines() + if not lines or lines[0] != "#!/bin/sh": + return False + expected_length = 3 if original else 2 + if len(lines) != expected_length: + return False + try: + command = shlex.split(lines[1]) + except ValueError: + return False + if ( + len(command) != 5 + or not Path(command[0]).name.lower().startswith("python") + or command[1] != str(repo / ".hypertext/formatting/commit.py") + or command[2:] != ["||", "exit", "$?"] + ): + return False + return not original or lines[2] == "exec " + shlex.quote(original) + ' "$@"' + + # Preflight every managed/affected hook before setup, deletions or rewrites. + # Legacy source-only receipts migrate only when the wrapper has a known body. + for name in set(previous) | set(previous_wrappers) | set(desired): + path = target / name + if path.is_symlink(): + raise ValueError( + "Locally modified composed hook needs reconciliation: " + name + ) + if not path.exists(): + continue + if not path.is_file(): + raise ValueError( + "Locally modified composed hook needs reconciliation: " + name + ) + actual = path.read_bytes() + owned_digest = previous_wrappers.get(name) + if owned_digest: + recognized = hashlib.sha256(actual).hexdigest() == owned_digest + else: + content = actual.decode("utf-8") + recognized = recognized_legacy(name, content) or ( + not previous and content == desired.get(name) + ) + if not recognized: + raise ValueError( + "Locally modified composed hook needs reconciliation: " + name + ) + + if not args.skip_tools: + setup = repo / ".hypertext/formatter-tools/setup.py" + if setup.is_file(): + subprocess.run([sys.executable, str(setup)], cwd=repo, check=True) + target.mkdir(exist_ok=True) + for name in (set(previous) | set(previous_wrappers)) - set(desired): + (target / name).unlink(missing_ok=True) + for name, content in desired.items(): + path = target / name + path.write_text(content) + path.chmod(0o755) + metadata.write_text( + json.dumps( + { + "schema_version": 1, + "sources": {name: str(path) for name, path in sources.items()}, + "wrappers": { + name: hashlib.sha256(content.encode()).hexdigest() + for name, content in desired.items() + }, + }, + indent=2, + ) + + "\n" + ) + if gitdir != common: + git("config", "--local", "extensions.worktreeConfig", "true") + git("config", "--worktree", "core.hooksPath", str(target)) + else: + git("config", "--local", "core.hooksPath", str(target)) + print("Shared commit formatting installed; existing hook checks retained.") +except (OSError, ValueError, subprocess.SubprocessError) as error: + print("Hook installation blocked: " + str(error), file=sys.stderr) + raise SystemExit(1) diff --git a/.hypertext/formatting/managed.json b/.hypertext/formatting/managed.json new file mode 100644 index 0000000..70696f2 --- /dev/null +++ b/.hypertext/formatting/managed.json @@ -0,0 +1,18 @@ +{ + "schema_version": 1, + "files": { + ".hypertext/formatting/core/__init__.py": "3858bfb4a4fa531ea1269e6e42cce86f0b7bfaf351600a755afc159def4c85d3", + ".hypertext/formatting/core/gate.py": "172510d10dc9a4f6d8623eb25d92991dd032c72ef81f62634c2a0715cbef93e6", + ".hypertext/formatting/core/runner.py": "bdd2d79fa3e00cdf8375da0fe3092e3dba67ec2f8462a9611182ea346f64a167", + ".hypertext/formatting/core/setup_files.py": "fbe7525bdac4f3f8dabb5c3cc298386db9700a881d86d37e9a033ae59d115b53", + ".hypertext/formatting/core/formatting.py": "3f2fbabd12f2ee87679e4f4d6e8200dfec93cc3399c0d28cde9981ec058d8a81", + ".hypertext/formatting/core/git_policy.py": "87337a7465e95df1d4da345a5ab9bf8c3f7dccadc38f88a41aec24e0ec21780d", + ".hypertext/formatting/LOCK.json": "00a0305b8c184e6d093105b9e1805e5a5b2cf73a8f85e5f2187fb1b82a89e467", + ".hypertext/formatting/commit.py": "5745312af7089246e44ac8a2fd537db9c9b69203753eebfc83d8d2ab2604f8b4", + ".hypertext/formatting/install.py": "a67c1660c371f22a5befa5cf61c4b34f1cd37c477d6a9225ea3a34a272095df2", + ".hypertext/formatter-tools/setup.py": "f472125c6773982fe1dcae32293d49435a814cd0a950464eaf92127f23d03bbc", + ".hypertext/formatter-tools/run.py": "d6fbab2bab923d03d8fa904d9e35d54436e0ee36ba471708931cd6d409fe421e", + ".hypertext/formatter-tools/prettier.mjs": "56ea416b45c56a09331009a3e1eecd261100d0262d3a8ae9ca134b502ddbe278", + ".hypertext/formatter-tools/text.py": "0c0e7f27d6ec0b9e02ec330a7faa60f535f60fafb8a4eb5bf023af68acc6a149" + } +} diff --git a/README.md b/README.md index 3f6dd8a..532eaa2 100644 --- a/README.md +++ b/README.md @@ -82,3 +82,15 @@ reviewed commit at `TheHypertextStudio/release-engineering/actions/turbo-cache@< It mints an audience-bound Google ID token for each repository's dedicated cache identity, keeps untrusted refs local-only, and preserves client artifact signatures. This small composite action is independent of candidate/promotion workflows and never deploys a website. + +## Local commit formatting + +Prepare the pinned formatting tools and local Git hooks from this repository's root: + +```sh +python3 .hypertext/formatting/install.py +``` + +Repeat this command after updating formatter pins or creating a checkout. Commits +format staged source and configuration while retaining unstaged edits. Setup +prepares dependencies; committing never downloads tools or starts build services.