gabriel / musehub public
release_provenance.py python
109 lines 5.1 KB
Raw
sha256:3c6d2e2751e9222a0872ba699f16baa457d9990c1998c20956badb9186ee69ee fix(deploy): image built from committed files only, with re… Opus 5.5 minor ⚠ breaking 12 days ago
1 """Independent observation of the Muse checkout a release candidate is gated against (musehub#114 Phase 6D, D2).
2
3 The gate used to *record* whatever ``--source-revision`` the operator typed. This module
4 *observes* the checkout instead, using Muse itself (no Git metadata)::
5
6 muse -C <repo> rev-parse HEAD --json -> the committed revision
7 muse -C <repo> status --json -> whether the working tree differs from it
8
9 What this does and does not establish -- keep these separate, they are different claims:
10
11 * claimed revision what the operator said. Never trusted; only compared.
12 * observed revision what Muse reports for the checkout right now.
13 * tree cleanliness nothing modified, added, deleted, renamed, staged, untracked, conflicted,
14 mid-merge or mid-checkout. Deliberately strict: an sdist is built from the
15 working tree, so any drift can change what was built.
16 * artifact identity the candidate tarball's SHA-256.
17 * build provenance that the artifact was *built from* that checkout. Nothing here attests
18 this (the build is not signed or recorded). The closest evidence is the
19 ``packaging.sdist_reproducible`` gate: a fresh sdist of the observed clean
20 checkout has member-for-member identical content to the artifact. That is
21 content equivalence, not an attestation of how the bytes were produced.
22
23 Every failure to observe is an error; there is no "unknown but proceed".
24 """
25 from __future__ import annotations
26
27 import json
28 import re
29 import subprocess
30 from collections.abc import Callable
31 from dataclasses import dataclass
32 from pathlib import Path
33 from typing import Any
34
35 REVISION_RE = re.compile(r"^sha256:[0-9a-f]{64}$")
36
37 Runner = Callable[..., "subprocess.CompletedProcess[str]"]
38
39
40 class ProvenanceError(Exception):
41 """The source revision could not be determined, or does not match what was claimed."""
42
43
44 @dataclass(frozen=True)
45 class CheckoutState:
46 revision: str
47 clean: bool
48 dirty: tuple[str, ...] = ()
49
50
51 def validate_revision(value: object) -> str:
52 if not isinstance(value, str) or not REVISION_RE.fullmatch(value):
53 raise ProvenanceError(f"not a Muse revision id (expected sha256:<64 hex>): {value!r}")
54 return value
55
56
57 def muse_json(repo: Path, args: list[str], runner: Runner = subprocess.run) -> dict[str, Any]:
58 """Run ``muse -C repo <args> --json`` and return the parsed object; any failure is a ``ProvenanceError``."""
59 argv = ["muse", "-C", str(repo), *args, "--json"]
60 try:
61 proc = runner(argv, capture_output=True, text=True, timeout=60, check=False)
62 except (OSError, subprocess.SubprocessError) as exc:
63 raise ProvenanceError(f"could not run {' '.join(argv[:5])}: {exc}") from exc
64 if proc.returncode != 0:
65 raise ProvenanceError(f"{' '.join(argv[:5])} exited {proc.returncode}: {(proc.stderr or proc.stdout or '').strip()[:300]}")
66 try:
67 data = json.loads(proc.stdout)
68 except ValueError as exc:
69 raise ProvenanceError(f"{' '.join(argv[:5])} did not return JSON: {exc}") from exc
70 if not isinstance(data, dict):
71 raise ProvenanceError(f"{' '.join(argv[:5])} returned {type(data).__name__}, not an object")
72 return data
73
74
75 def _dirty_paths(status: dict[str, Any]) -> tuple[str, ...]:
76 paths: list[str] = []
77 for key in ("added", "modified", "deleted", "untracked", "conflict_paths"):
78 value = status.get(key)
79 if not isinstance(value, list):
80 raise ProvenanceError(f"muse status --json: {key!r} missing or not a list")
81 paths += [str(p) for p in value]
82 renamed = status.get("renamed")
83 if not isinstance(renamed, dict):
84 raise ProvenanceError("muse status --json: 'renamed' missing or not an object")
85 paths += [f"{old} -> {new}" for old, new in renamed.items()]
86 for stage in ("staged", "unstaged"):
87 block = status.get(stage)
88 if not isinstance(block, dict):
89 raise ProvenanceError(f"muse status --json: {stage!r} missing or not an object")
90 for key in ("added", "modified", "deleted"):
91 paths += [str(p) for p in block.get(key, [])]
92 paths += [f"{old} -> {new}" for old, new in (block.get("renamed") or {}).items()]
93 for flag in ("merge_in_progress", "checkout_interrupted"):
94 if status.get(flag) is not False:
95 paths.append(f"<{flag}>")
96 if status.get("clean") is not True or status.get("dirty") is not False:
97 paths.append("<status reports the tree is not clean>")
98 return tuple(dict.fromkeys(paths))
99
100
101 def observe_checkout(repo: Path, *, runner: Runner = subprocess.run) -> CheckoutState:
102 """What Muse says *repo* is at, right now. Raises ``ProvenanceError`` if that cannot be established."""
103 revision = validate_revision(muse_json(repo, ["rev-parse", "HEAD"], runner).get("commit_id"))
104 status = muse_json(repo, ["status"], runner)
105 head = validate_revision(status.get("head_commit"))
106 if head != revision:
107 raise ProvenanceError(f"muse rev-parse HEAD ({revision}) and muse status ({head}) disagree")
108 dirty = _dirty_paths(status)
109 return CheckoutState(revision, not dirty, dirty)
File History 2 commits
sha256:3c6d2e2751e9222a0872ba699f16baa457d9990c1998c20956badb9186ee69ee fix(deploy): image built from committed files only, with re… Opus 5.5 minor ⚠ 12 days ago
sha256:04db68e43d9007348dbd726b2a3e52f73e83c5646a4511c07e19cb9a66e28b5f fix(release): gate provenance is observed from the checkout… Opus 5.5 minor ⚠ 12 days ago