From 3766287fcaec0034f9ac5819ab119273ce3f384b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 2 Dec 2026 14:22:05 +0100 Subject: [PATCH] Release gate: check_harness_bundle.py reads the Harness BUNDLE.json out of an installer and fails unless it is the pinned one For a staged folder, an install folder, BUNDLE.json, a .tar.gz / .zip (the macOS Strata.app archive), an AppImage (unsquashfs) or a setup.exe / .dmg (7-Zip). Fails unless commit, version and builtAt are right, the patch ids are exactly the pinned three, package / file / afterSha256 equal the pin's, the platform is the installer's, and the patched files inside hash to afterSha256 (BUNDLE.json is a record, the file is the fact). A target it cannot read fails. Run on the real 0.2.24 files it fails the Windows install (commit null, two patches missing, two files unpatched) and passes the macOS app archive. tools/test_check_harness_bundle.py covers the folder, tar, zip, AppImage (when squashfs-tools is there) and the failure cases. --- tools/packaging/check_harness_bundle.py | 274 ++++++++++++++++++++++++ tools/test_check_harness_bundle.py | 215 +++++++++++++++++++ 2 files changed, 489 insertions(+) create mode 100644 tools/packaging/check_harness_bundle.py create mode 100644 tools/test_check_harness_bundle.py diff --git a/tools/packaging/check_harness_bundle.py b/tools/packaging/check_harness_bundle.py new file mode 100644 index 0000000000..6e4c023f22 --- /dev/null +++ b/tools/packaging/check_harness_bundle.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python3 +"""Release gate: does an installer ship the pinned DeepSeek Harness, with every Strata patch? (0.2.25) + +0.2.23 and 0.2.24 shipped three different Harness bundles: the Windows installer carried a 2026-10-16 staging with commit null and one of the three +patches, Linux a 2026-11-17 staging, macOS a fresh one. The Windows users' fixes #5964 (fs search) and #6014 (MCP session) never reached the Windows +installer. This reads the Harness BUNDLE.json out of what is actually shipped and fails unless it matches app/desktop/harness-pin.json: + + * commit == the pinned commit, version == the pinned version, builtAt present + * the patch ids are exactly the pinned ones (a missing patch fails; so does an unknown one, since a different patch set is a different Harness) + * each patch's package, file and afterSha256 equal the pin's, and the bytes of that file inside the installer hash to afterSha256 + (BUNDLE.json is a record; the file is the fact) + * the platform in BUNDLE.json is the platform of the installer (win32 for *.exe, linux for *.AppImage, darwin for *.dmg / Strata.app) + + python -I check_harness_bundle.py [--pin app/desktop/harness-pin.json] [--platform win32|linux|darwin] [--no-files] [...] + +A target is one of: a staged Harness folder (the folder that holds BUNDLE.json, or an app / install folder that holds harness/BUNDLE.json), a BUNDLE.json, +a .tar.gz / .tgz / .tar / .zip (the Strata.app archive of the macOS build, a zipped install), a .AppImage (needs `unsquashfs` from squashfs-tools; Linux), +a Windows setup .exe or a .dmg (need 7-Zip: `7z` or `7za` on PATH). A target that cannot be read FAILS: the gate never passes on something it did not see. +Exit 0 when every target passes, 1 otherwise. Standard library only. +""" +import argparse +import hashlib +import json +import os +import shutil +import struct +import subprocess +import sys +import tarfile +import zipfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +DEFAULT_PIN = HERE.parent.parent / "app" / "desktop" / "harness-pin.json" +# Where the Harness folder sits inside each kind of target (tried in order). +PREFIXES = ("", "harness/", "resources/harness/", "Contents/Resources/harness/", "Strata.app/Contents/Resources/harness/", "usr/lib/Strata/harness/") + + +class Unreadable(Exception): + pass + + +def appimage_squashfs_offset(path): + """The squashfs starts where the ELF runtime ends: the end of its section header table (type 2 runtime; the same number `--appimage-offset` prints).""" + with open(path, "rb") as f: + head = f.read(64) + if len(head) < 64 or head[:4] != b"\x7fELF" or head[4] != 2 or head[5] != 1: + raise Unreadable("not an ELF64 little-endian AppImage") + shoff, = struct.unpack_from(" bytes of /; raises Unreadable. kind and root say what was found.""" + + def __init__(self, target): + self.target = Path(target) + self.kind = None + self.root = None + self._open() + + # -- folder / json --------------------------------------------------------------------------------------------- + def _open(self): + t = self.target + low = t.name.lower() + if not t.exists(): + raise Unreadable("no such file or folder") + if t.is_dir(): + self.kind = "folder" + for p in PREFIXES: + if (t / p / "BUNDLE.json").is_file(): + self.root = p + self._read = lambda rel, p=p: (t / p / rel).read_bytes() + return + raise Unreadable("no harness/BUNDLE.json in the folder") + if low == "bundle.json": + self.kind = "json" + self.root = "" + self._read = lambda rel: (t.parent / rel).read_bytes() + return + if low.endswith((".tar.gz", ".tgz", ".tar")): + self._open_tar() + elif low.endswith(".zip"): + self._open_zip() + elif low.endswith(".appimage"): + self._open_appimage() + elif low.endswith((".exe", ".dmg")): + self._open_7z() + else: + raise Unreadable("unknown kind of target") + + def _find_root(self, names): + for name in names: + norm = name.lstrip("./") + if norm == "BUNDLE.json" or norm.endswith("harness/BUNDLE.json"): + return norm[: -len("BUNDLE.json")] + raise Unreadable("no harness/BUNDLE.json inside") + + def _open_tar(self): + self.kind = "tar" + with tarfile.open(self.target) as tf: + names = [m.name for m in tf.getmembers() if m.isfile()] + # the macOS app archive: prefer the app's own Resources/harness over any other harness folder + pref = [n for n in names if n.endswith("Contents/Resources/harness/BUNDLE.json")] + self.root = self._find_root(pref or names) + original = {n.lstrip("./"): n for n in names} + + def read(rel): + with tarfile.open(self.target) as tf: + member = original.get(self.root + rel) + if member is None: + raise Unreadable(f"{rel} not in the archive") + return tf.extractfile(member).read() + self._read = read + + def _open_zip(self): + self.kind = "zip" + with zipfile.ZipFile(self.target) as zf: + names = zf.namelist() + self.root = self._find_root(names) + + def read(rel): + with zipfile.ZipFile(self.target) as zf: + try: + return zf.read(self.root + rel) + except KeyError: + raise Unreadable(f"{rel} not in the archive") from None + self._read = read + + def _open_appimage(self): + self.kind = "appimage" + tool = shutil.which("unsquashfs") + if not tool: + raise Unreadable("unsquashfs (squashfs-tools) is needed to read an AppImage and was not found") + offset = appimage_squashfs_offset(self.target) + + def read(rel): + r = subprocess.run([tool, "-o", str(offset), "-cat", str(self.target), self.root + rel], capture_output=True) + if r.returncode != 0 or not r.stdout: + raise Unreadable(f"{rel} not in the AppImage ({r.stderr.decode(errors='replace').strip()[:120]})") + return r.stdout + for p in PREFIXES[1:]: + self.root = p + try: + read("BUNDLE.json") + break + except Unreadable: + continue + else: + raise Unreadable("no harness/BUNDLE.json inside the AppImage") + self._read = read + + def _open_7z(self): + self.kind = "7z" + tool = seven_zip() + + def read(rel): + r = subprocess.run([tool, "e", "-so", "-y", str(self.target), self.root + rel], capture_output=True) + if r.returncode != 0 or not r.stdout: + raise Unreadable(f"{rel} not in the installer") + return r.stdout + for p in PREFIXES[1:]: + self.root = p + try: + read("BUNDLE.json") + break + except Unreadable: + continue + else: + raise Unreadable("no harness/BUNDLE.json inside the installer") + self._read = read + + def read(self, rel): + try: + return self._read(rel) + except OSError as e: + raise Unreadable(f"{rel}: {e.strerror or e}") from None + + +def expected_platform(target): + low = Path(target).name.lower() + if low.endswith((".exe", ".msi")): + return "win32" + if low.endswith(".appimage"): + return "linux" + if low.endswith(".dmg") or "strata.app" in low or "macos" in low or "darwin" in low: + return "darwin" + return None + + +def check_bundle(bundle, pin, platform=None): + """Problems of a parsed BUNDLE.json against the pin (a list of strings, empty = good).""" + bad = [] + if bundle.get("component") != pin["component"]: + bad.append(f"component {bundle.get('component')!r}") + if bundle.get("version") != pin["version"]: + bad.append(f"version {bundle.get('version')!r}, pinned {pin['version']}") + if bundle.get("commit") != pin["commit"]: + bad.append(f"commit {bundle.get('commit')!r}, pinned {pin['commit']}") + if not bundle.get("builtAt"): + bad.append("no builtAt") + if platform and bundle.get("platform") != platform: + bad.append(f"platform {bundle.get('platform')!r}, expected {platform}") + have = {p.get("id"): p for p in bundle.get("patches") or [] if isinstance(p, dict)} + for want in pin["patches"]: + got = have.get(want["id"]) + if got is None: + bad.append(f"patch {want['id']} is missing") + continue + for key in ("package", "file", "afterSha256"): + if got.get(key) != want[key]: + bad.append(f"patch {want['id']}: {key} is {got.get(key)!r}, pinned {want[key]!r}") + for extra in sorted(set(have) - {p["id"] for p in pin["patches"]}): + bad.append(f"patch {extra} is not in the pin") + return bad + + +def check_target(target, pin, platform=None, files=True): + """(problems, one-line description). Any failure to read is a problem.""" + try: + src = Source(target) + bundle = json.loads(src.read("BUNDLE.json").decode("utf-8")) + except Unreadable as e: + return [f"cannot read: {e}"], "unreadable" + except (ValueError, tarfile.TarError, zipfile.BadZipFile) as e: + return [f"cannot read: {e}"], "unreadable" + hint = "darwin" if "Contents/Resources" in (src.root or "") else "linux" if "usr/lib/Strata" in (src.root or "") else None # where the folder sits tells the OS + bad = check_bundle(bundle, pin, platform or expected_platform(target) or hint) + if files: + for want in pin["patches"]: + try: + digest = hashlib.sha256(src.read(want["file"])).hexdigest() + except Unreadable as e: + bad.append(f"patched file {want['file']}: {e}") + continue + if digest != want["afterSha256"]: + bad.append(f"patched file {want['file']} hashes to {digest[:12]}, pinned {want['afterSha256'][:12]}") + what = f"{src.kind} {bundle.get('platform')} v{bundle.get('version')} commit {str(bundle.get('commit'))[:10]} built {bundle.get('builtAt')} patches {len(bundle.get('patches') or [])}" + return bad, what + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + ap.add_argument("targets", nargs="+") + ap.add_argument("--pin", default=str(DEFAULT_PIN)) + ap.add_argument("--platform", choices=("win32", "linux", "darwin")) + ap.add_argument("--no-files", action="store_true", help="trust BUNDLE.json: do not hash the patched files themselves") + args = ap.parse_args(argv) + pin = json.loads(Path(args.pin).read_text(encoding="utf-8")) + failed = 0 + for target in args.targets: + bad, what = check_target(target, pin, args.platform, not args.no_files) + print(f"{'FAIL' if bad else 'ok '} {target}: {what}") + for b in bad: + print(f" - {b}") + failed += bool(bad) + print(f"HARNESS GATE {'FAILED' if failed else 'OK'} ({len(args.targets) - failed} of {len(args.targets)} pass; pin {pin['commit'][:10]})") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/test_check_harness_bundle.py b/tools/test_check_harness_bundle.py new file mode 100644 index 0000000000..05be380f6d --- /dev/null +++ b/tools/test_check_harness_bundle.py @@ -0,0 +1,215 @@ +"""tools/packaging/check_harness_bundle.py: the release gate that every installer ships the pinned Harness with all three Strata patches.""" +import hashlib +import io +import json +import os +import shutil +import struct +import subprocess +import sys +import tarfile +import tempfile +import unittest +import zipfile +from pathlib import Path + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "packaging")) +import check_harness_bundle as gate # noqa: E402 + +REPO = Path(__file__).resolve().parent.parent +COMMIT = "571902028a75c64c1d767f4ae5fd099485f0ddf0" +FILES = { # patched file -> bytes of the patched version (a stand-in; the test pin is built from these) + "node_modules/@earendil-works/pi-ai/dist/api/simple-options.js": b"// patched pi-ai\n", + "node_modules/@deepseek-ai/dsh-tool-fs-search/lib/index.js": b"// patched search\n", + "node_modules/@deepseek-ai/dsh-mcp-client/lib/index.js": b"// patched mcp\n", +} +IDS = ["strata-pi-ai-context-safety-v2", "strata-fs-search-partial-v1", "strata-mcp-session-reconnect-v1"] +PKGS = ["@earendil-works/pi-ai", "@deepseek-ai/dsh-tool-fs-search", "@deepseek-ai/dsh-mcp-client"] + + +def sha(b): + return hashlib.sha256(b).hexdigest() + + +def pin(): + return {"component": "deepseek-harness", "version": "0.2.1-alpha.3", "commit": COMMIT, + "patches": [{"id": i, "package": p, "file": f, "afterSha256": sha(FILES[f])} for i, p, f in zip(IDS, PKGS, FILES)]} + + +def bundle(platform="win32", **changes): + b = {"component": "deepseek-harness", "version": "0.2.1-alpha.3", "commit": COMMIT, "platform": platform, "builtAt": "2026-12-02T01:31:59.504Z", + "patches": [{"id": p["id"], "package": p["package"], "file": p["file"], "afterSha256": p["afterSha256"]} for p in pin()["patches"]]} + b.update(changes) + return b + + +def write_tree(root, b, files=FILES): + root.mkdir(parents=True, exist_ok=True) + (root / "BUNDLE.json").write_text(json.dumps(b), encoding="utf-8") + for rel, data in files.items(): + (root / rel).parent.mkdir(parents=True, exist_ok=True) + (root / rel).write_bytes(data) + + +class GateTests(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="strata-harness-gate-")) + self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True) + self.pin = pin() + self.pin_file = self.tmp / "pin.json" + self.pin_file.write_text(json.dumps(self.pin), encoding="utf-8") + + def run_gate(self, *targets, extra=()): + out = io.StringIO() + real = sys.stdout + sys.stdout = out + try: + code = gate.main(["--pin", str(self.pin_file), *extra, *targets]) + finally: + sys.stdout = real + return code, out.getvalue() + + def test_a_staged_folder_with_everything_passes(self): + write_tree(self.tmp / "h", bundle()) + code, text = self.run_gate(str(self.tmp / "h")) + self.assertEqual(code, 0, text) + self.assertIn("HARNESS GATE OK", text) + + def test_an_install_folder_with_harness_inside_passes(self): + write_tree(self.tmp / "app" / "harness", bundle()) + self.assertEqual(self.run_gate(str(self.tmp / "app"))[0], 0) + + def test_the_0224_windows_bundle_fails_three_ways(self): + # commit null, one patch only (what the 0.2.24 setup.exe carried), the two other files unpatched + b = bundle(commit=None, builtAt="2026-10-16T17:45:39.441Z", patches=bundle()["patches"][:1]) + old = dict(FILES) + old["node_modules/@deepseek-ai/dsh-tool-fs-search/lib/index.js"] = b"// original search\n" + old["node_modules/@deepseek-ai/dsh-mcp-client/lib/index.js"] = b"// original mcp\n" + write_tree(self.tmp / "h", b, old) + code, text = self.run_gate(str(self.tmp / "h")) + self.assertEqual(code, 1) + self.assertIn("commit None", text) + self.assertIn("strata-fs-search-partial-v1 is missing", text) + self.assertIn("strata-mcp-session-reconnect-v1 is missing", text) + self.assertIn("dsh-mcp-client/lib/index.js hashes to", text) + + def test_a_bundle_json_that_claims_the_patch_but_a_file_that_is_not_patched_fails(self): + files = dict(FILES) + files["node_modules/@deepseek-ai/dsh-mcp-client/lib/index.js"] = b"// original mcp\n" + write_tree(self.tmp / "h", bundle(), files) + code, text = self.run_gate(str(self.tmp / "h")) + self.assertEqual(code, 1) + self.assertIn("patched file node_modules/@deepseek-ai/dsh-mcp-client/lib/index.js hashes to", text) + self.assertEqual(self.run_gate(str(self.tmp / "h"), extra=["--no-files"])[0], 0) # the record alone is what --no-files trusts + + def test_other_commit_version_unknown_patch_missing_builtat_and_wrong_platform_each_fail(self): + cases = { + "commit": bundle(commit="a" * 40), + "version": bundle(version="0.2.2"), + "builtAt": bundle(builtAt=None), + "unknown patch": bundle(patches=bundle()["patches"] + [{"id": "strata-extra-v1", "package": "x", "file": "x", "afterSha256": "0" * 64}]), + "patch hash": bundle(patches=[dict(bundle()["patches"][0], afterSha256="0" * 64)] + bundle()["patches"][1:]), + "empty patches": bundle(patches=[]), + "no patches key": {k: v for k, v in bundle().items() if k != "patches"}, + } + for name, b in cases.items(): + with self.subTest(name): + write_tree(self.tmp / name.replace(" ", "_"), b) + self.assertEqual(self.run_gate(str(self.tmp / name.replace(" ", "_")))[0], 1) + write_tree(self.tmp / "plat", bundle(platform="linux")) + self.assertEqual(self.run_gate(str(self.tmp / "plat"), extra=["--platform", "win32"])[0], 1) + self.assertEqual(self.run_gate(str(self.tmp / "plat"), extra=["--platform", "linux"])[0], 0) + + def test_the_platform_follows_the_installer_name(self): + self.assertEqual(gate.expected_platform("Strata-0.2.25-windows-x64-setup.exe"), "win32") + self.assertEqual(gate.expected_platform("Strata-0.2.25-linux-x86_64.AppImage"), "linux") + self.assertEqual(gate.expected_platform("Strata-0.2.25-macos-arm64.dmg"), "darwin") + self.assertEqual(gate.expected_platform("Strata.app.tar.gz"), "darwin") + self.assertIsNone(gate.expected_platform("folder")) + + def test_the_macos_app_archive_is_read_and_checked_as_darwin(self): + stage = self.tmp / "mac" + write_tree(stage / "Strata.app" / "Contents" / "Resources" / "harness", bundle("darwin")) + archive = self.tmp / "Strata.app.tar.gz" + with tarfile.open(archive, "w:gz") as tf: + tf.add(stage / "Strata.app", arcname="Strata.app") + code, text = self.run_gate(str(archive)) + self.assertEqual(code, 0, text) + self.assertIn("darwin", text) + write_tree(stage / "bad" / "Strata.app" / "Contents" / "Resources" / "harness", bundle("win32")) + bad = self.tmp / "Strata-bad.app.tar.gz" + with tarfile.open(bad, "w:gz") as tf: + tf.add(stage / "bad" / "Strata.app", arcname="Strata.app") + self.assertEqual(self.run_gate(str(bad))[0], 1) + + def test_a_zip_install_is_read(self): + stage = self.tmp / "z" + write_tree(stage / "harness", bundle()) + archive = self.tmp / "install.zip" + with zipfile.ZipFile(archive, "w") as zf: + for p in (stage).rglob("*"): + if p.is_file(): + zf.write(p, p.relative_to(stage).as_posix()) + self.assertEqual(self.run_gate(str(archive))[0], 0) + + def test_something_that_cannot_be_read_fails_and_is_never_skipped(self): + for name in ("missing.exe", "nothing"): + code, text = self.run_gate(str(self.tmp / name)) + self.assertEqual(code, 1) + self.assertIn("cannot read", text) + (self.tmp / "empty").mkdir() + self.assertEqual(self.run_gate(str(self.tmp / "empty"))[0], 1) + (self.tmp / "broken.json").write_text("{", encoding="utf-8") + (self.tmp / "BUNDLE.json").write_text("{", encoding="utf-8") + self.assertEqual(self.run_gate(str(self.tmp / "BUNDLE.json"))[0], 1) + + def test_one_failing_target_fails_the_run(self): + write_tree(self.tmp / "good", bundle()) + write_tree(self.tmp / "bad", bundle(commit=None)) + code, text = self.run_gate(str(self.tmp / "good"), str(self.tmp / "bad")) + self.assertEqual(code, 1) + self.assertIn("1 of 2 pass", text) + + def test_the_squashfs_offset_is_the_end_of_the_elf_section_headers(self): + head = bytearray(64) + head[:4] = b"\x7fELF" + head[4], head[5] = 2, 1 + struct.pack_into("