From 3ac2a957bbbc18ac92ba21b317e561c905ff4a5e Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:22:33 +0800 Subject: [PATCH] Exercise pinned external skill reproduction from both Git routes Agent-assisted-by: Codex / unknown [effort=unknown] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- .../test_external_skill_reproduction.py | 81 +++++ tools/reproduce_external_skill.py | 282 ++++++++++++++++++ 2 files changed, 363 insertions(+) create mode 100644 tests/knowledge/test_external_skill_reproduction.py create mode 100644 tools/reproduce_external_skill.py diff --git a/tests/knowledge/test_external_skill_reproduction.py b/tests/knowledge/test_external_skill_reproduction.py new file mode 100644 index 000000000..46c511444 --- /dev/null +++ b/tests/knowledge/test_external_skill_reproduction.py @@ -0,0 +1,81 @@ +import json +import os +import subprocess +import sys +from pathlib import Path + +TOOL = Path(__file__).resolve().parents[2] / "tools" / "reproduce_external_skill.py" +CLOSURE = "52fdf73e8e2cda67bc7ea121f411e699f9a1aef9dde61f5f8f2a15e073ab5d03" +PATHS = {"LICENSE", "SKILL.md", "references/guide.md"} + + +def run_tool(*args, offline=False): + env = os.environ.copy() + if offline: + env["PATH"] = "" + return subprocess.run( + [sys.executable, str(TOOL), *map(str, args)], + capture_output=True, + text=True, + env=env, + timeout=100, + ) + + +def test_pinned_link_and_submodule_then_independent_offline_verification(tmp_path): + evidence = tmp_path / "evidence" + demo = run_tool("demo", evidence) + assert demo.returncode == 0, demo.stderr + report = json.loads(demo.stdout) + assert report == json.loads((evidence / "report.json").read_text(encoding="utf-8")) + manifest_path = evidence / "manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + assert set(manifest) == PATHS + assert report["manifest_sha256"] == CLOSURE + assert report["moved_tag_commit"] != report["registered_commit"] + assert report["repository"].startswith("http://127.0.0.1:") + assert report["fresh"]["submodule"]["gitlink"] == report["registered_commit"] + assert report["fresh"]["link"]["commands"][-1]["argv"][-1] == report["registered_commit"] + for route in ("link", "submodule"): + fresh = report["fresh"][route] + assert fresh["resolved_url"] == report["repository"] + assert fresh["checkout_commit"] == report["registered_commit"] + assert fresh["manifest"] == manifest + assert all(step["exit_code"] == 0 for step in fresh["commands"]) + cold = report["source_unavailable_cold"][route] + assert cold["exit_code"] != 0 + assert cold["argv"][1] == ("clone" if route == "link" else "submodule") + assert cold["source_status"] == 503 + assert cold["files"] == {} + + snapshot = evidence / "snapshot" + assert {p.relative_to(snapshot).as_posix() for p in snapshot.rglob("*") if p.is_file()} == PATHS + offline_args = ("verify", snapshot, manifest_path, CLOSURE) + replay = run_tool(*offline_args, offline=True) + assert replay.returncode == 0, replay.stderr + expected = { + "matches": True, + "closure_sha256": CLOSURE, + "missing": [], + "changed": [], + "unexpected": [], + } + assert json.loads(replay.stdout) == expected + assert report["offline"] == {"snapshot": expected, "populated_submodule": expected} + + (snapshot / "references" / "guide.md").write_bytes(b"changed attachment") + (snapshot / "LICENSE").unlink() + (snapshot / "extra.md").write_bytes(b"unregistered") + replay = run_tool(*offline_args, offline=True) + assert replay.returncode == 1 + diff = json.loads(replay.stdout) + assert not diff["matches"] and diff["closure_sha256"] != CLOSURE + assert diff["changed"] == ["references/guide.md"] + assert diff["missing"] == ["LICENSE"] + assert diff["unexpected"] == ["extra.md"] + + manifest.pop("LICENSE") + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + altered_manifest = run_tool(*offline_args, offline=True) + assert altered_manifest.returncode == 1 + assert "Manifest does not match the recorded closure SHA-256" in altered_manifest.stderr diff --git a/tools/reproduce_external_skill.py b/tools/reproduce_external_skill.py new file mode 100644 index 000000000..16c8f1d69 --- /dev/null +++ b/tools/reproduce_external_skill.py @@ -0,0 +1,282 @@ +"""Compare two ways to reproduce a synthetic, pinned Git skill on loopback. + + python tools/reproduce_external_skill.py demo + python tools/reproduce_external_skill.py verify + +The second command needs only the retained files, manifest and independently recorded digest. +""" + +import argparse +import hashlib +import json +import os +import shutil +import subprocess +import tempfile +import threading +from contextlib import contextmanager +from functools import partial +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +FILES = { + "LICENSE": b"Controlled fixture. Copying is permitted for this local experiment.\n", + "SKILL.md": b"# Controlled fixture\nSee references/guide.md.\n", + "references/guide.md": b"Local procedure v1.\n", +} +MODULE = "vendor/fixture" + + +def closure(manifest): + canonical = json.dumps(manifest, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + +def manifest_for(directory, *, checkout=False): + def fail_on_unreadable(error): + raise error + + manifest = {} + for root, dirs, files in os.walk(directory, onerror=fail_on_unreadable): + here = Path(root) + if checkout and here == directory: + dirs[:] = [name for name in dirs if name != ".git"] + files = [name for name in files if name != ".git"] + for name in [*dirs, *files]: + if (here / name).is_symlink(): + raise ValueError(f"Expected regular fixture content: {name}") + for name in files: + path = here / name + manifest[path.relative_to(directory).as_posix()] = hashlib.sha256( + path.read_bytes() + ).hexdigest() + return dict(sorted(manifest.items())) + + +def verify(directory, manifest, digest, *, checkout=False): + if closure(manifest) != digest: + raise ValueError("Manifest does not match the recorded closure SHA-256") + actual = manifest_for(directory, checkout=checkout) + return { + "matches": actual == manifest, + "closure_sha256": closure(actual), + "missing": sorted(manifest.keys() - actual.keys()), + "unexpected": sorted(actual.keys() - manifest.keys()), + "changed": sorted(k for k in manifest.keys() & actual.keys() if manifest[k] != actual[k]), + } + + +def git(where, *args, check=True): + env = {k: v for k, v in os.environ.items() if not k.upper().startswith("GIT_")} + env.update( + GIT_CONFIG_NOSYSTEM="1", + GIT_CONFIG_GLOBAL=os.devnull, + GIT_ATTR_NOSYSTEM="1", + GIT_TERMINAL_PROMPT="0", + GIT_ALLOW_PROTOCOL="file:http", + NO_PROXY="127.0.0.1", + no_proxy="127.0.0.1", + GIT_AUTHOR_DATE="2001-01-01T00:00:00Z", + GIT_COMMITTER_DATE="2001-01-01T00:00:00Z", + ) + return subprocess.run( + [ + "git", + "-c", + "user.name=Local fixture", + "-c", + "user.email=fixture@example.invalid", + "-c", + "core.autocrlf=false", + "-c", + f"core.attributesFile={os.devnull}", + "-C", + str(where), + *args, + ], + env=env, + capture_output=True, + text=True, + check=check, + timeout=45, + ) + + +def checked_equal(observed, expected, description): + if observed != expected: + raise ValueError(f"{description}: expected {expected!r}, observed {observed!r}") + + +def fetch_step(work, directory, args, *, check=True): + result = git(directory, *args, check=check) + return { + "cwd": directory.relative_to(work).as_posix(), + "argv": ["git", *args], + "exit_code": result.returncode, + } + + +@contextmanager +def serve_repo(directory): + unavailable = threading.Event() + refusals = [] + + class Handler(SimpleHTTPRequestHandler): + def do_GET(self): + if unavailable.is_set(): + refusals.append(self.path) + self.send_error(503) + else: + super().do_GET() + + def log_message(self, *args): + pass + + with ThreadingHTTPServer( + ("127.0.0.1", 0), partial(Handler, directory=str(directory)) + ) as server: + worker = threading.Thread(target=server.serve_forever, daemon=True) + worker.start() + try: + yield f"http://127.0.0.1:{server.server_port}/fixture.git", unavailable, refusals + finally: + server.shutdown() + worker.join() + + +def prepare_source(work): + source = work / "source" + git(work, "init", "-q", "-b", "main", str(source)) + for name, data in FILES.items(): + path = source / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + git(source, "add", ".") + git(source, "commit", "-qm", "controlled v1") + pin = git(source, "rev-parse", "HEAD").stdout.strip() + git(source, "tag", "scene", pin) + (source / "references/guide.md").write_bytes(b"Local procedure v2.\n") + git(source, "commit", "-qam", "controlled v2") + git(source, "tag", "-f", "scene", "HEAD") + web = work / "http" + web.mkdir() + git(work, "clone", "-q", "--no-local", "--bare", str(source), str(web / "fixture.git")) + git(web / "fixture.git", "update-server-info") + return web, pin, git(source, "rev-parse", "HEAD").stdout.strip() + + +def fetched(checkout, url, pin, manifest): + origin = git(checkout, "remote", "get-url", "origin").stdout.strip() + observed = git(checkout, "rev-parse", "HEAD").stdout.strip() + actual = manifest_for(checkout, checkout=True) + checked_equal((origin, observed, actual), (url, pin, manifest), "Fresh checkout") + return {"resolved_url": origin, "checkout_commit": observed, "manifest": actual} + + +def demonstrate(output): + if output.exists(): + raise FileExistsError(f"Choose a new evidence directory: {output}") + manifest = {p: hashlib.sha256(b).hexdigest() for p, b in FILES.items()} + digest = closure(manifest) + with tempfile.TemporaryDirectory(prefix="skill-reproduction-") as temp: + work = Path(temp) + web, pin, moved = prepare_source(work) + proof = work / "evidence" + snapshot = proof / "snapshot" + parent, direct, cold_parent = (work / p for p in ("parent", "direct", "cold-parent")) + with serve_repo(web) as (url, unavailable, refusals): + git(work, "init", "-q", "-b", "main", str(parent)) + git(parent, "config", "-f", ".gitmodules", "submodule.fixture.path", MODULE) + git(parent, "config", "-f", ".gitmodules", "submodule.fixture.url", url) + git(parent, "add", ".gitmodules") + git(parent, "update-index", "--add", "--cacheinfo", f"160000,{pin},{MODULE}") + git(parent, "commit", "-qm", "pin controlled v1") + git(work, "clone", "-q", "--no-local", str(parent), str(cold_parent)) + gitlink = git(cold_parent, "ls-tree", "HEAD", MODULE).stdout.split() + checked_equal(gitlink, ["160000", "commit", pin, MODULE], "Cold parent gitlink") + + clone = fetch_step(work, work, ["clone", "-q", url, direct.name]) + observed_tag = git(direct, "rev-parse", "scene^{commit}").stdout.strip() + checked_equal(observed_tag, moved, "Moved tag") + if observed_tag == pin: + raise ValueError("Fixture tag still points at the registered version") + checkout = fetch_step(work, direct, ["checkout", "-q", "--detach", pin]) + link = fetched(direct, url, pin, manifest) + link["commands"] = [clone, checkout] + update_args = ["submodule", "update", "--init", "--", MODULE] + update = fetch_step(work, parent, update_args) + module = fetched(parent / MODULE, url, pin, manifest) + module["commands"] = [update] + for name in manifest: + destination = snapshot / name + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(direct / name, destination) + unavailable.set() + cold = {} + for route, cwd, args, target in ( + ("link", work, ["clone", "-q", url, "cold-link"], work / "cold-link"), + ( + "submodule", + cold_parent, + update_args, + cold_parent / MODULE, + ), + ): + before = len(refusals) + step = fetch_step(work, cwd, args, check=False) + delivered = manifest_for(target, checkout=True) if target.exists() else {} + if not step["exit_code"] or len(refusals) == before or delivered: + raise ValueError(f"Expected fresh {route} to fail at the unavailable source") + cold[route] = { + **step, + "source_status": 503, + "files": delivered, + } + + offline = { + "snapshot": verify(snapshot, manifest, digest), + "populated_submodule": verify(parent / MODULE, manifest, digest, checkout=True), + } + for result in offline.values(): + checked_equal(result["matches"], True, "Offline bytes") + report = { + "repository": url, + "registered_commit": pin, + "moved_tag_commit": observed_tag, + "manifest_sha256": digest, + "manifest_encoding": "UTF-8 JSON, sorted path keys, compact separators, no trailing LF", + "fresh": {"link": link, "submodule": {**module, "gitlink": gitlink[2]}}, + "offline": offline, + "source_unavailable_cold": cold, + } + for filename, payload in [("manifest.json", manifest), ("report.json", report)]: + (proof / filename).write_bytes((json.dumps(payload, indent=2) + "\n").encode("utf-8")) + shutil.copytree(proof, output) + return report + + +def main(): + cli = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + commands = cli.add_subparsers(dest="command", required=True) + commands.add_parser("demo").add_argument("output", type=Path) + verifier = commands.add_parser("verify") + verifier.add_argument("snapshot", type=Path) + verifier.add_argument("manifest", type=Path) + verifier.add_argument("digest") + args = cli.parse_args() + try: + if args.command == "demo": + result = demonstrate(args.output) + else: + manifest = json.loads(args.manifest.read_text(encoding="utf-8")) + result = verify(args.snapshot, manifest, args.digest) + except (ValueError, OSError) as error: + cli.exit(1, f"{error}\n") + print(json.dumps(result, indent=2)) + return 0 if result.get("matches", True) else 1 + + +if __name__ == "__main__": + raise SystemExit(main())