From 351f13e04a8973fe6a8e549ba04ed6e95c7d118f Mon Sep 17 00:00:00 2001 From: cflmy Date: Fri, 27 Nov 2026 21:47:11 +0800 Subject: [PATCH] ci: verify selected upstream CLI releases with the Knowledge core gate --- docs/ci.md | 12 ++++ tools/ci/verify-upstream.py | 120 ++++++++++++++++++++++++++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 tools/ci/verify-upstream.py diff --git a/docs/ci.md b/docs/ci.md index d13293b..4fa5b66 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -29,6 +29,18 @@ compatibility step also builds the existing `3.0.0-rc.4` core pin Changing the historical pin requires rerunning the tamper fixtures and recording the new Analysis fixture evidence. +For a verified upstream task, run the consumer gate from the clean Knowledge +candidate using the tag, source SHA and Linux archive digest from the task. + +```sh +python3 tools/ci/verify-upstream.py --tag "$cli_tag" \ + --source-sha "$cli_source_sha" --archive-sha256 "$cli_archive_sha256" +``` + +Pass `--archive` to reuse locally staged bytes. The gate checks the Gitea tag, +artifact digest and installed Bundle before running the existing `core` lane. +Its output records the actual consumer commit and CLI identities for review. + ## Gates executed by CI | Gate | Command | diff --git a/tools/ci/verify-upstream.py b/tools/ci/verify-upstream.py new file mode 100644 index 0000000..190fb6e --- /dev/null +++ b/tools/ci/verify-upstream.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +"""Run Knowledge's real Analysis checks against an exact published CLI.""" + +import argparse +import hashlib +import json +import os +import re +import subprocess +import sys +import tarfile +import tempfile +import urllib.error +import urllib.request +from pathlib import Path, PurePosixPath + +ROOT = Path(__file__).resolve().parents[2] +FORGE = "https://git.cflmy.cn" +REPO = "cflmy/marqdo-cli" +TARGET = "x86_64-unknown-linux-gnu" +MAX_ARCHIVE = 64 * 1024 * 1024 +MAX_EXPANDED = 256 * 1024 * 1024 + + +class VerificationError(Exception): + pass + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, request, fp, code, message, headers, newurl): + return None + + +def require(condition, message): + if not condition: + raise VerificationError(message) + + +def copy_verified(stream, output, digest): + actual = hashlib.sha256() + size = 0 + with output.open("wb") as destination: + while chunk := stream.read(1024 * 1024): + size += len(chunk) + require(size <= MAX_ARCHIVE, "CLI archive exceeds the size limit") + actual.update(chunk) + destination.write(chunk) + require(actual.hexdigest() == digest, "CLI archive SHA-256 does not match the candidate") + + +def unpack(archive, output, top): + seen = set() + total = 0 + with tarfile.open(archive, "r:gz") as tar: + for member in tar: + path = PurePosixPath(member.name) + require(path.parts and path.parts[0] == top and ".." not in path.parts + and "\\" not in member.name and path not in seen + and (member.isfile() or member.isdir()), "unexpected CLI archive entry") + seen.add(path) + total += member.size + require(len(seen) <= 2048 and total <= MAX_EXPANDED, "CLI archive expansion exceeds limits") + tar.extractall(output, filter="data") + return output / top + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--tag", required=True) + parser.add_argument("--source-sha", required=True) + parser.add_argument("--archive-sha256", required=True) + parser.add_argument("--archive", type=Path, help="use already downloaded bytes") + args = parser.parse_args() + if not (re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?", args.tag) + and re.fullmatch(r"[0-9a-f]{40}", args.source_sha) + and re.fullmatch(r"[0-9a-f]{64}", args.archive_sha256)): + parser.error("expected an exact tag, source SHA and Linux archive SHA-256") + + opener = urllib.request.build_opener(NoRedirect()) + top = f"marqdo-{args.tag[1:]}-{TARGET}" + try: + consumer = subprocess.check_output(["git", "-C", ROOT, "rev-parse", "HEAD"], text=True).strip() + require(not subprocess.check_output(["git", "-C", ROOT, "status", "--porcelain"], text=True), + "consumer checkout has uncommitted changes") + with opener.open(f"{FORGE}/api/v1/repos/{REPO}/tags/{args.tag}", timeout=30) as response: + tag = json.loads(response.read(1024 * 1024)) + require(tag["name"] == args.tag and tag["commit"]["sha"] == args.source_sha, + "authoritative CLI tag does not match the candidate") + with tempfile.TemporaryDirectory(prefix="marqdo-knowledge-upstream-") as temporary: + work = Path(temporary) + archive = work / (top + ".tar.gz") + source = (args.archive.open("rb") if args.archive else opener.open( + f"{FORGE}/{REPO}/releases/download/{args.tag}/{archive.name}", timeout=45)) + with source: + copy_verified(source, archive, args.archive_sha256) + release = unpack(archive, work, top) + metadata = json.loads((release / "RELEASE_INFO.json").read_text(encoding="utf-8")) + sha = (release / "SOURCE_SHA").read_text(encoding="utf-8").strip() + require(sha == args.source_sha == metadata["source_sha"] + and metadata["target_triple"] == TARGET, "CLI release identity or target does not match") + binary = release / "marqdo" + bundle = release / "stdlib" + require(binary.is_file() and os.access(binary, os.X_OK) and (bundle / "stdlib.json").is_file(), + "CLI archive lacks its executable or installed Bundle") + env = dict(os.environ, MARQDO_BIN=str(binary), MARQDO_STDLIB_DIR=str(bundle)) + subprocess.run([ROOT / "scripts/ci.sh", "core"], cwd=ROOT, env=env, check=True) + require(subprocess.check_output(["git", "-C", ROOT, "rev-parse", "HEAD"], text=True).strip() == consumer, + "consumer identity changed during validation") + print(json.dumps({"consumer_sha": consumer, + "cli_tag": args.tag, "cli_source_sha": sha, "archive_sha256": args.archive_sha256, + "target": TARGET, "status": "passed"}, sort_keys=True)) + except (VerificationError, OSError, ValueError, KeyError, TypeError, + tarfile.TarError, subprocess.CalledProcessError) as error: + print(f"upstream verification: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) -- 2.54.1