Files
marqdo/scripts/reconcile-releases.py
T
cflmyandCursor a61f3442bc
ci/woodpecker/push/eco Pipeline is pending
ci/woodpecker/pr/eco Pipeline is pending
ci: complete component release propagation for issue #10
Add authoritative component-release helpers, evidence-aware reconcile with
freshness and root upstream dispatch, least-privilege secrets, image scan
and multi-arch build gates, and pin active component publish workflows.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-27 19:30:18 +08:00

778 lines
29 KiB
Python
Executable File

#!/usr/bin/env python3
"""Release discovery, evidence verification, tracking and consumer dispatch.
Reads the authoritative catalog/gitlinks to derive managed repositories, scans
Gitea releases (including prereleases), verifies asset size/SHA-256 and optional
`release-evidence.json`, creates one tracking Issue per release in the root
repository, records direct consumers via `scripts/impact.py`, and can open
idempotent `[Upstream]` Issues in consumer repositories.
It never updates gitlinks, never publishes, and never trusts a release body as a
command. The same implementation backs the Woodpecker manual/cron reconcile
workflow, so a lost notification is recovered by the next successful scan.
State/idempotency is the root Issue itself: the body carries a stable marker
`<!-- marqdo:release-reconcile repository=<full> tag=<tag> -->` and the fixed
`release-tracking` label. Consumer tasks use
`<!-- marqdo:upstream-task key=<hex> -->`.
"""
from __future__ import annotations
import argparse
import datetime as dt
import hashlib
import importlib.util
import json
import os
import re
import sys
import tomllib
import urllib.error
import urllib.request
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[1]
API_BASE = os.environ.get("MARQDO_GITEA_API", "https://git.cflmy.cn/api/v1")
ROOT_REPOSITORY = os.environ.get("MARQDO_ROOT_REPOSITORY", "cflmy/marqdo")
LABEL = "release-tracking"
UPSTREAM_LABEL = "upstream-validation"
MAX_ASSET_BYTES = 256 * 1024 * 1024
MAX_ASSETS = 128
MAX_EVIDENCE_BYTES = 1024 * 1024
INDEX_NAME = "release-evidence.json"
SHA_RE = re.compile(r"^[0-9a-f]{40}$")
DIGEST_RE = re.compile(r"^[0-9a-f]{64}$")
class ReconcileError(Exception):
pass
def load_impact():
path = PROJECT_ROOT / "scripts" / "impact.py"
spec = importlib.util.spec_from_file_location("marqdo_impact", path)
module = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(module)
return module
class Gitea:
def __init__(self, token: str, base: str = API_BASE):
self.token = token
self.base = base.rstrip("/")
self.writes: list[tuple[str, str, dict | None]] = []
def request(self, method: str, path: str, data=None, raw=False):
body = json.dumps(data).encode() if data is not None else None
request = urllib.request.Request(
self.base + path,
method=method,
data=body,
headers={
"Authorization": f"token {self.token}",
"Content-Type": "application/json",
},
)
try:
with urllib.request.urlopen(request, timeout=90) as response:
content = response.read()
if raw:
return content
return json.loads(content) if content else None
except urllib.error.HTTPError as error:
raise ReconcileError(f"{method} {path}: HTTP {error.code}") from error
except urllib.error.URLError as error:
raise ReconcileError(f"{method} {path}: {error}") from error
def get(self, path: str):
return self.request("GET", path)
def post(self, path: str, data):
self.writes.append(("POST", path, data))
return self.request("POST", path, data)
def download(self, url: str) -> bytes:
request = urllib.request.Request(url, headers={"Authorization": f"token {self.token}"})
with urllib.request.urlopen(request, timeout=120) as response:
size = int(response.headers.get("Content-Length", "0"))
if size > MAX_ASSET_BYTES:
raise ReconcileError(f"asset exceeds {MAX_ASSET_BYTES} bytes: {url}")
data = response.read(MAX_ASSET_BYTES + 1)
if len(data) > MAX_ASSET_BYTES:
raise ReconcileError(f"asset exceeds {MAX_ASSET_BYTES} bytes: {url}")
return data
def repository_from_url(url: str) -> str:
match = re.match(r"https://git\.cflmy\.cn/([^/]+/[^/]+?)(?:\.git)?$", url)
if not match:
raise ReconcileError(f"non-canonical repository URL: {url}")
return match.group(1)
def submodule_repositories(repo_root: Path) -> dict[str, str]:
path = repo_root / ".gitmodules"
result: dict[str, str] = {}
if not path.is_file():
return result
current = None
for line in path.read_text().splitlines():
line = line.strip()
if line.startswith("[submodule "):
current = None
elif line.startswith("path =") and current is None:
current = line.split("=", 1)[1].strip()
elif line.startswith("url =") and current:
result[current] = repository_from_url(line.split("=", 1)[1].strip())
current = None
return result
def catalog_components(root: Path) -> list[dict]:
catalog = tomllib.loads((root / "components.toml").read_text())
components = []
remotes = submodule_repositories(root)
for component in catalog.get("component", []):
path = component.get("path", "")
entry = {
"id": component.get("id"),
"path": path,
"state": component.get("state"),
"kind": component.get("kind"),
"requires": list(component.get("requires") or []),
"repository": remotes.get(path),
}
components.append(entry)
if component.get("kind") == "domain":
domain = root / path
domain_remotes = submodule_repositories(domain)
domain_catalog = domain / "components.toml"
if not domain_catalog.is_file():
continue
for child in tomllib.loads(domain_catalog.read_text()).get("component", []):
child_path = f"{path}/{child.get('path', '')}"
components.append(
{
"id": child.get("id"),
"path": child_path,
"state": child.get("state"),
"kind": child.get("kind"),
"requires": list(child.get("requires") or []),
"repository": domain_remotes.get(child_path),
}
)
return components
def managed_repositories(root: Path) -> dict[str, str]:
"""catalog id/path -> owner/name for direct components and domain children."""
managed: dict[str, str] = {}
for component in catalog_components(root):
if component.get("repository"):
managed[f"{component['id']}@{component['path']}"] = component["repository"]
return managed
def verify_assets(client: Gitea, release: dict) -> list[dict]:
assets = release.get("assets") or []
if len(assets) > MAX_ASSETS:
raise ReconcileError(f"release has more than {MAX_ASSETS} assets")
verified = []
for asset in assets:
name = asset.get("name", "")
if not name or "/" in name or name in (".", ".."):
raise ReconcileError(f"unsafe asset name: {name!r}")
url = asset.get("browser_download_url")
if not url:
raise ReconcileError(f"asset {name} has no download URL")
data = client.download(url)
if asset.get("size") is not None and int(asset["size"]) != len(data):
raise ReconcileError(f"asset {name} size mismatch")
digest = hashlib.sha256(data).hexdigest()
verified.append(
{
"name": name,
"size": len(data),
"sha256": digest,
"bytes": data if name == INDEX_NAME else None,
}
)
return verified
def verify_release_evidence(entry: dict, verified: list[dict]) -> dict | None:
"""Validate release-evidence.json when present. Missing index is allowed for
historical releases; when present it must match downloaded asset digests."""
index = next((item for item in verified if item["name"] == INDEX_NAME), None)
if index is None:
return None
raw = index.get("bytes") or b""
if len(raw) > MAX_EVIDENCE_BYTES:
raise ReconcileError("release-evidence.json exceeds 1 MiB")
try:
evidence = json.loads(raw.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError) as error:
raise ReconcileError(f"release-evidence.json is not valid JSON: {error}") from error
if not isinstance(evidence, dict):
raise ReconcileError("release-evidence.json must be an object")
for key in ("component_id", "repository", "tag", "source_sha", "assets"):
if key not in evidence:
raise ReconcileError(f"release-evidence.json missing {key}")
if evidence["component_id"] != entry["component"]:
raise ReconcileError("release-evidence component_id mismatch")
if evidence["repository"] != entry["repository"]:
raise ReconcileError("release-evidence repository mismatch")
if evidence["tag"] != entry["tag"]:
raise ReconcileError("release-evidence tag mismatch")
if not SHA_RE.match(str(evidence["source_sha"])):
raise ReconcileError("release-evidence source_sha is not 40-hex")
listed = evidence.get("assets") or []
if not isinstance(listed, list) or len(listed) > MAX_ASSETS:
raise ReconcileError("release-evidence assets invalid")
by_name = {item["name"]: item for item in verified if item["name"] != INDEX_NAME}
evidence_names = set()
for asset in listed:
name = asset.get("name")
digest = asset.get("sha256")
size = asset.get("size")
if name == INDEX_NAME:
raise ReconcileError("release-evidence assets must not include the index itself")
if name not in by_name:
raise ReconcileError(f"release-evidence lists missing asset {name}")
if not DIGEST_RE.match(str(digest or "")):
raise ReconcileError(f"release-evidence asset {name} has bad sha256")
if by_name[name]["sha256"] != digest:
raise ReconcileError(f"release-evidence asset {name} sha256 mismatch")
if size is not None and int(size) != by_name[name]["size"]:
raise ReconcileError(f"release-evidence asset {name} size mismatch")
evidence_names.add(name)
# Non-index release assets should all be listed when an index is present.
if evidence_names != set(by_name):
raise ReconcileError("release-evidence asset set does not match release assets")
evidence_digest = hashlib.sha256(raw).hexdigest()
return {
"source_sha": evidence["source_sha"],
"evidence_sha256": evidence_digest,
"dependencies": evidence.get("dependencies") or [],
"ci": evidence.get("ci") or {},
}
def release_marker(repository: str, tag: str) -> str:
return f"<!-- marqdo:release-reconcile repository={repository} tag={tag} -->"
def task_key(repository: str, tag: str, source_sha: str, consumer_id: str) -> str:
material = f"{repository}\n{tag}\n{source_sha}\n{consumer_id}".encode()
return hashlib.sha256(material).hexdigest()
def task_marker(key: str) -> str:
return f"<!-- marqdo:upstream-task key={key} -->"
def existing_issues(client: Gitea, repository: str = ROOT_REPOSITORY, label: str = LABEL) -> list[dict]:
issues = client.get(
f"/repos/{repository}/issues?state=all&limit=100&type=issues&labels={label}"
)
return issues if isinstance(issues, list) else []
def ensure_label(client: Gitea, repository: str, name: str, color: str, description: str) -> int:
labels = client.get(f"/repos/{repository}/labels?limit=100")
for item in labels or []:
if item.get("name") == name:
return int(item["id"])
created = client.post(
f"/repos/{repository}/labels",
{"name": name, "color": color, "description": description},
)
return int(created["id"])
def discover(client: Gitea, root: Path) -> list[dict]:
entries = []
for key, repository in sorted(managed_repositories(root).items()):
releases = client.get(f"/repos/{repository}/releases?limit=50")
for release in releases or []:
if release.get("draft"):
continue
tag = release.get("tag_name")
if not tag:
continue
marker = release_marker(repository, tag)
entries.append(
{
"component": key.split("@", 1)[0],
"path": key.split("@", 1)[1],
"repository": repository,
"tag": tag,
"name": release.get("name") or tag,
"prerelease": bool(release.get("prerelease")),
"url": release.get("html_url"),
"published_at": release.get("published_at") or release.get("created_at"),
"marker": marker,
"assets": release.get("assets") or [],
}
)
return entries
def published_after(entry: dict, cutoff: str | None) -> bool:
if not cutoff:
return True
published = entry.get("published_at")
if not published:
return False
return published >= cutoff
def direct_consumers(root: Path, component_id: str) -> list[dict]:
"""Return active catalog consumers that directly require component_id.
Stdlib/base leaves are composed by the root Bundle producer rather than by
sibling `requires` edges, so the root repository is recorded as the direct
consumer for those components when no catalog requires edge exists.
"""
consumers = []
source = None
for component in catalog_components(root):
if component.get("id") == component_id:
source = component
continue
if component_id not in (component.get("requires") or []):
continue
if component.get("state") != "active":
continue
if not component.get("repository"):
continue
consumers.append(component)
if not consumers and source is not None:
kind = source.get("kind")
# Root Bundle/integration consumes base stdlib/core releases.
if kind in ("stdlib", "core") or source.get("path", "").startswith("stdlib/"):
consumers.append(
{
"id": "marqdo",
"path": ".",
"state": "active",
"kind": "root",
"requires": [],
"repository": ROOT_REPOSITORY,
}
)
return consumers
def impact_consumers(root: Path, component_id: str) -> dict:
"""Prefer impact.py reverse closure; fall back to direct requires."""
try:
impact = load_impact()
report = impact.consumers_of(component_id, "HEAD")
affected = [item for item in report.get("affected", []) if item != component_id]
return {
"affected": affected,
"fallback": report.get("fallback"),
"unverified": report.get("unverified") or [],
}
except Exception as error: # noqa: BLE001 - degrade to catalog requires
return {
"affected": [item["id"] for item in direct_consumers(root, component_id)],
"fallback": "catalog-requires",
"unverified": [f"impact.py unavailable: {error}"],
}
def render_issue(
entry: dict,
assets: list[dict],
*,
evidence: dict | None,
consumers: list[dict],
impact: dict,
) -> str:
public_assets = [{"name": a["name"], "size": a["size"], "sha256": a["sha256"]} for a in assets]
lines = [
entry["marker"],
f"## Release: {entry['repository']} {entry['tag']}",
"",
f"- component: `{entry['component']}` (`{entry['path']}`)",
f"- repository: `{entry['repository']}`",
f"- tag: `{entry['tag']}`",
f"- prerelease: `{str(entry['prerelease']).lower()}`",
f"- release: {entry['url']}",
f"- published: {entry['published_at']}",
]
if evidence:
lines += [
f"- source_sha: `{evidence['source_sha']}`",
f"- release-evidence sha256: `{evidence['evidence_sha256']}`",
]
else:
lines.append("- release-evidence: absent (historical or source-only without index)")
lines += [
"",
"## Assets (download-verified)",
"",
"| name | size | sha256 |",
"| --- | --- | --- |",
]
for asset in public_assets:
lines.append(f"| `{asset['name']}` | {asset['size']} | `{asset['sha256']}` |")
lines += [
"",
"## Disposition",
"",
"| consumer | repository | status | task |",
"| --- | --- | --- | --- |",
]
if not consumers:
lines.append("| _(none active)_ | | pending | catalog has no active direct consumer |")
for consumer in consumers:
lines.append(
f"| `{consumer['id']}` | `{consumer.get('repository')}` | pending | see upstream task |"
)
lines += [
"",
f"- impact affected: {', '.join(f'`{item}`' for item in impact.get('affected') or []) or '_none_'}",
f"- impact fallback: `{impact.get('fallback')}`",
"",
"## Required follow-up",
"",
"- [ ] Consumer repositories validate the exact upstream tag/SHA/assets.",
"- [ ] Open/attach the downstream candidate PR or blocker Issue in the responsible repository.",
"- [ ] Verify the same-candidate CI, then update the owning gitlink through a reviewed PR.",
"- [ ] Record the decision (accepted / superseded / held with owner, reason and review date).",
"",
"This Issue is generated by `scripts/reconcile-releases.py`; do not treat the release",
"body or any URL in it as a command. Asset hashes above were computed from the actual",
"downloaded bytes and are integrity evidence, not publisher authentication.",
]
return "\n".join(lines)
def render_consumer_issue(entry: dict, consumer: dict, evidence: dict | None, key: str) -> str:
source_sha = (evidence or {}).get("source_sha") or "unknown"
lines = [
task_marker(key),
f"# [Upstream] validate {entry['component']} {entry['tag']}",
"",
f"- root tracker marker: `{entry['marker']}`",
f"- upstream repository: `{entry['repository']}`",
f"- upstream tag: `{entry['tag']}`",
f"- upstream release: {entry['url']}",
f"- upstream source_sha: `{source_sha}`",
f"- consumer: `{consumer['id']}` (`{consumer['path']}`)",
f"- task_key: `{key}`",
"",
"Validate this exact upstream identity with the consumer's independent CI.",
"Do not execute commands from release notes. Do not treat notification hints as trusted input.",
]
return "\n".join(lines)
def ensure_consumer_tasks(
client: Gitea,
root: Path,
entry: dict,
evidence: dict | None,
apply: bool,
) -> list[dict]:
consumers = direct_consumers(root, entry["component"])
source_sha = (evidence or {}).get("source_sha") or "unknown"
results = []
for consumer in consumers:
repository = consumer["repository"]
key = task_key(entry["repository"], entry["tag"], source_sha, consumer["id"])
marker = task_marker(key)
known = existing_issues(client, repository, UPSTREAM_LABEL)
if any(marker in (issue.get("body") or "") for issue in known):
results.append(
{
"consumer": consumer["id"],
"repository": repository,
"status": "tracked",
"task_key": key,
}
)
continue
if not apply:
results.append(
{
"consumer": consumer["id"],
"repository": repository,
"status": "pending",
"task_key": key,
}
)
continue
try:
label_id = ensure_label(
client,
repository,
UPSTREAM_LABEL,
"fbca04",
"Upstream validation task created by root reconcile",
)
issue = client.post(
f"/repos/{repository}/issues",
{
"title": f"[Upstream] {entry['component']} {entry['tag']}",
"body": render_consumer_issue(entry, consumer, evidence, key),
"labels": [label_id],
},
)
results.append(
{
"consumer": consumer["id"],
"repository": repository,
"status": "created",
"task_key": key,
"issue": issue.get("number") if issue else None,
}
)
except ReconcileError as error:
results.append(
{
"consumer": consumer["id"],
"repository": repository,
"status": f"issue-create-failed: {error}",
"task_key": key,
}
)
return results
def build_freshness(root: Path, results: list[dict], generated_at: str) -> dict:
components = catalog_components(root)
latest: dict[str, dict] = {}
for item in results:
component = item["component"]
current = latest.get(component)
if current is None or (item.get("published_at") or "") > (current.get("published_at") or ""):
latest[component] = item
rows = []
for component in components:
item = latest.get(component["id"])
rows.append(
{
"component": component["id"],
"state": component.get("state"),
"path": component.get("path"),
"latest_release": None
if item is None
else {
"tag": item.get("tag"),
"repository": item.get("repository"),
"status": item.get("status"),
"published_at": item.get("published_at"),
"url": item.get("url"),
},
}
)
return {
"schema": "marqdo.release-freshness.v1",
"schema_version": 1,
"generated_at": generated_at,
"root_repository": ROOT_REPOSITORY,
"components": rows,
}
def render_freshness_md(report: dict) -> str:
lines = [
f"# Release freshness ({report['generated_at']})",
"",
f"Root: `{report['root_repository']}`. Derived view only; not a version lock.",
"",
"| component | state | latest release | status |",
"| --- | --- | --- | --- |",
]
for row in report["components"]:
latest = row.get("latest_release") or {}
tag = latest.get("tag") or "—"
status = latest.get("status") or ("planned" if row.get("state") == "planned" else "none")
lines.append(f"| `{row['component']}` | {row.get('state')} | {tag} | {status} |")
lines.append("")
return "\n".join(lines)
def reconcile(
client: Gitea,
root: Path = PROJECT_ROOT,
apply: bool = False,
report_out: Path | None = None,
cutoff: str | None = None,
freshness_out: Path | None = None,
dispatch_consumers: bool = True,
) -> dict:
entries = [entry for entry in discover(client, root) if published_after(entry, cutoff)]
known = {issue.get("body") or "" for issue in existing_issues(client)}
results = []
label_id = (
ensure_label(
client,
ROOT_REPOSITORY,
LABEL,
"bfd4f2",
"Release tracking created by reconcile",
)
if apply
else None
)
for entry in entries:
marker = entry["marker"]
if any(marker in body for body in known):
results.append({**entry, "status": "tracked", "consumer_tasks": [], "evidence": None})
continue
verified: list[dict] = []
evidence: dict | None = None
if not apply:
status = "pending"
consumer_tasks = (
ensure_consumer_tasks(client, root, entry, None, apply=False)
if dispatch_consumers
else []
)
else:
try:
verified = verify_assets(client, {"assets": entry["assets"]})
evidence = verify_release_evidence(entry, verified)
except ReconcileError as error:
results.append(
{
**entry,
"assets": [],
"status": f"asset-verify-failed: {error}",
"consumer_tasks": [],
"evidence": None,
}
)
continue
impact = impact_consumers(root, entry["component"])
consumers = direct_consumers(root, entry["component"])
status = "created"
body = render_issue(
entry,
verified,
evidence=evidence,
consumers=consumers,
impact=impact,
)
try:
issue = client.post(
f"/repos/{ROOT_REPOSITORY}/issues",
{
"title": f"[release] {entry['repository']} {entry['tag']}",
"body": body,
"labels": [label_id],
},
)
if issue:
known.add(body)
entry = {**entry, "issue": issue.get("number")}
except ReconcileError as error:
status = f"issue-create-failed: {error}"
consumer_tasks = (
ensure_consumer_tasks(client, root, entry, evidence, apply=True)
if dispatch_consumers and status == "created"
else []
)
public_assets = [
{"name": item["name"], "size": item["size"], "sha256": item["sha256"]}
for item in verified
]
evidence_summary = None
if evidence:
evidence_summary = {
"source_sha": evidence["source_sha"],
"evidence_sha256": evidence["evidence_sha256"],
}
results.append(
{
**entry,
"assets": public_assets,
"status": status,
"evidence": evidence_summary,
"consumer_tasks": consumer_tasks,
}
)
generated_at = dt.datetime.now(dt.timezone.utc).isoformat()
freshness = build_freshness(root, results, generated_at)
report = {
"schema": "marqdo.release-reconcile.v1",
"schema_version": 2,
"generated_at": generated_at,
"apply": apply,
"root_repository": ROOT_REPOSITORY,
"repositories": len({entry["repository"] for entry in entries}),
"releases": len(entries),
"results": results,
"freshness": freshness,
"counts": {
status: sum(1 for item in results if item["status"] == status)
for status in sorted({item["status"] for item in results})
},
}
if report_out:
report_out.parent.mkdir(parents=True, exist_ok=True)
report_out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
if freshness_out:
freshness_out = Path(freshness_out)
freshness_out.parent.mkdir(parents=True, exist_ok=True)
freshness_out.write_text(json.dumps(freshness, ensure_ascii=False, indent=2) + "\n")
freshness_out.with_suffix(".md").write_text(render_freshness_md(freshness), encoding="utf-8")
return report
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--apply", action="store_true", help="create tracking/consumer Issues")
parser.add_argument("--report-out", default=None)
parser.add_argument("--freshness-out", default=None)
parser.add_argument("--root", default=str(PROJECT_ROOT))
parser.add_argument(
"--no-dispatch-consumers",
action="store_true",
help="only create root tracking Issues",
)
parser.add_argument(
"--published-after",
default=os.environ.get("MARQDO_RECONCILE_PUBLISHED_AFTER", ""),
help="only track releases published at/after this ISO-8601 timestamp",
)
args = parser.parse_args(argv)
token = os.environ.get("MARQDO_GIT_TOKEN", "")
if not token:
print("reconcile: error: MARQDO_GIT_TOKEN is required", file=sys.stderr)
return 2
try:
report = reconcile(
Gitea(token),
Path(args.root).resolve(),
apply=args.apply,
report_out=Path(args.report_out) if args.report_out else None,
cutoff=args.published_after or None,
freshness_out=Path(args.freshness_out) if args.freshness_out else None,
dispatch_consumers=not args.no_dispatch_consumers,
)
except ReconcileError as error:
print(f"reconcile: error: {error}", file=sys.stderr)
return 2
print(json.dumps(report, ensure_ascii=False, indent=2))
failed = any(
item["status"].startswith(("asset-verify-failed", "issue-create-failed"))
or any(
str(task.get("status", "")).startswith("issue-create-failed")
for task in item.get("consumer_tasks") or []
)
for item in report["results"]
)
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))